void PieView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
{

        QRect contentsRect = rect.translated(
                                horizontalScrollBar()->value(),
                                verticalScrollBar()->value()).normalized();

        int rows = model()->rowCount(rootIndex());
        int columns = model()->columnCount(rootIndex());
        QModelIndexList indexes;

        for (int row = 0; row < rows; ++row) {
                for (int column = 0; column < columns; ++column) {
                        QModelIndex index = model()->index(row, column, rootIndex());
                        QRegion region = itemRegion(index);
                        if (!region.intersect(contentsRect).isEmpty())
                                indexes.append(index);
                }
        }

        if (indexes.size() > 0) {
                int firstRow = indexes[0].row();
                int lastRow = indexes[0].row();
                int firstColumn = indexes[0].column();
                int lastColumn = indexes[0].column();

                for (int i = 1; i < indexes.size(); ++i) {
                        firstRow = qMin(firstRow, indexes[i].row());
                        lastRow = qMax(lastRow, indexes[i].row());
                        firstColumn = qMin(firstColumn, indexes[i].column());
                        lastColumn = qMax(lastColumn, indexes[i].column());
                }

                QItemSelection selection(
                        model()->index(firstRow, firstColumn, rootIndex()),
                        model()->index(lastRow, lastColumn, rootIndex())
                            );
                selectionModel()->select(selection, command);
        } else {
                QModelIndex noIndex;
                QItemSelection selection(noIndex, noIndex);
                selectionModel()->select(selection, command);
        }

        update();
}
void ThumbnailView::Delegate::paintCellText( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    // Optimization based on result from KCacheGrind
    if ( !Settings::SettingsData::instance()->displayLabels() && !Settings::SettingsData::instance()->displayCategories() )
        return;

    DB::FileName fileName = model()->imageAt( index.row() );
    if ( fileName.isNull() )
        return;

    QString title = index.data( Qt::DisplayRole ).value<QString>();
    QRect rect = cellGeometryInfo()->cellTextGeometry();
    painter->setPen( Utilities::contrastColor( Settings::SettingsData::instance()->backgroundColor() ) );

    //Qt::TextWordWrap just in case, if the text's width is wider than the cell's width
    painter->drawText( rect.translated( option.rect.topLeft() ), Qt::AlignCenter | Qt::TextWordWrap, title );
}
Example #3
0
void Q_EXPORT_SCROLLRECT qt_scrollRectInImage(QImage &img, const QRect &rect, const QPoint &offset)
{
    // make sure we don't detach
    uchar *mem = const_cast<uchar*>(const_cast<const QImage &>(img).bits());

    int lineskip = img.bytesPerLine();
    int depth = img.depth() >> 3;

    const QRect imageRect(0, 0, img.width(), img.height());
    const QRect r = rect & imageRect & imageRect.translated(-offset);
    const QPoint p = rect.topLeft() + offset;

    if (r.isEmpty())
        return;

    const uchar *src;
    uchar *dest;

    if (r.top() < p.y()) {
        src = mem + r.bottom() * lineskip + r.left() * depth;
        dest = mem + (p.y() + r.height() - 1) * lineskip + p.x() * depth;
        lineskip = -lineskip;
    } else {
        src = mem + r.top() * lineskip + r.left() * depth;
        dest = mem + p.y() * lineskip + p.x() * depth;
    }

    const int w = r.width();
    int h = r.height();
    const int bytes = w * depth;

    // overlapping segments?
    if (offset.y() == 0 && qAbs(offset.x()) < w) {
        do {
            ::memmove(dest, src, bytes);
            dest += lineskip;
            src += lineskip;
        } while (--h);
    } else {
        do {
            ::memcpy(dest, src, bytes);
            dest += lineskip;
            src += lineskip;
        } while (--h);
    }
}
void Inner::paintInlineItems(Painter &p, const QRect &r) {
	if (_restrictedLabel) {
		return;
	}
	if (_rows.isEmpty() && !_switchPmButton) {
		p.setFont(st::normalFont);
		p.setPen(st::noContactsColor);
		p.drawText(QRect(0, 0, width(), (height() / 3) * 2 + st::normalFont->height), lang(lng_inline_bot_no_results), style::al_center);
		return;
	}
	auto gifPaused = _controller->isGifPausedAtLeastFor(Window::GifPauseReason::InlineResults);
	InlineBots::Layout::PaintContext context(getms(), false, gifPaused, false);

	auto top = st::stickerPanPadding;
	if (_switchPmButton) {
		top += _switchPmButton->height() + st::inlineResultsSkip;
	}

	auto fromx = rtl() ? (width() - r.x() - r.width()) : r.x();
	auto tox = rtl() ? (width() - r.x()) : (r.x() + r.width());
	for (auto row = 0, rows = _rows.size(); row != rows; ++row) {
		auto &inlineRow = _rows[row];
		if (top >= r.top() + r.height()) break;
		if (top + inlineRow.height > r.top()) {
			auto left = st::inlineResultsLeft - st::buttonRadius;
			if (row == rows - 1) context.lastRow = true;
			for (int col = 0, cols = inlineRow.items.size(); col < cols; ++col) {
				if (left >= tox) break;

				auto item = inlineRow.items.at(col);
				auto w = item->width();
				if (left + w > fromx) {
					p.translate(left, top);
					item->paint(p, r.translated(-left, -top), &context);
					p.translate(-left, -top);
				}
				left += w;
				if (item->hasRightSkip()) {
					left += st::inlineResultsSkip;
				}
			}
		}
		top += inlineRow.height;
	}
}
QSize QVGEGLWindowSurfacePrivate::windowSurfaceSize(QWidget *widget) const
{
    Q_UNUSED(widget);

    QRect rect = winSurface->geometry();
    QSize newSize = rect.size();

#if defined(Q_WS_QWS)
    // Account for the widget mask, if any.
    if (widget && !widget->mask().isEmpty()) {
        const QRegion region = widget->mask()
                               & rect.translated(-widget->geometry().topLeft());
        newSize = region.boundingRect().size();
    }
#endif

    return newSize;
}
Example #6
0
void QWSLocalMemSurface::setGeometry(const QRect &rect)
{
    QSize size = rect.size();

    QWidget *win = window();
    if (win && !win->mask().isEmpty()) {
        const QRegion region = win->mask()
                               & rect.translated(-win->geometry().topLeft());
        size = region.boundingRect().size();
    }

    uchar *deleteLater = 0;

    if (img.size() != size) {
        if (size.isEmpty()) {
            if (memsize) {
                // In case of a Hide event we need to delete the memory after sending the
                // event to the server in order to let the server animate the event.
                deleteLater = mem;
                memsize = 0;
            }
            mem = 0;
            img = QImage();
        } else {
            const QImage::Format format = preferredImageFormat(win);
            const int bpl = nextMulOf4(bytesPerPixel(format) * size.width());
            const int imagesize = bpl * size.height();
            if (memsize < imagesize) {
                delete[] mem;
                memsize = imagesize;
                mem = new uchar[memsize];
            }
            img = QImage(mem, size.width(), size.height(), bpl, format);
            setImageMetrics(img, win);
        }
    }

    QWSWindowSurface::setGeometry(rect);

    delete[] deleteLater;
}
Example #7
0
void NLabel::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter;
    QRect rect = contentsRect();

    if (painter.isActive())
        painter.setFont(font());

    if (m_enabled && m_shadowOffset != QPoint(0, 0)) {
        painter.begin(this);
        painter.setPen(QPen(m_shadowColor));
        painter.drawText(rect.translated(m_shadowOffset), alignment(), m_elidedText);
        painter.end();
    }

    painter.begin(this);
    painter.drawText(rect, alignment(), m_elidedText);
    painter.end();
}
void EventTimelineDatePainter::paintDate(const QDate &date)
{
    QDateTime dt = QDateTime(date, QTime(), Qt::UTC);

    if (m_visibleTimeStart >= dt.addDays(1))
        return;

    QString dateStr = dateToString(date);
    QRect dateRect = dateStringToRect(date, dateStr);

    if (isRectUnused(dateRect))
    {
        paintDateString(dateStr, dateRect);
        if (shouldPaintUndrawnDate())
            paintDateString(m_undrawnDateString, m_undrawnDateRect);
        setUndrawnDateString(QString(), QRect());
    }
    else
        setUndrawnDateString(dateStr, dateRect.translated(m_lastDrawnDateRect.right() - dateRect.left(), 0));

    m_useLongDateFormat = false;
}
Example #9
0
//________________________________________________
QPixmap TransitionWidget::grab( QWidget* widget, QRect rect )
{

    // change rect
    if( !rect.isValid() ) rect = widget->rect();
    if( !rect.isValid() ) return QPixmap();

    // initialize pixmap
    QPixmap out( rect.size() );
    out.fill( Qt::transparent );
    _paintEnabled = false;

    if( testFlag( GrabFromWindow ) )
    {

        rect = rect.translated( widget->mapTo( widget->window(), widget->rect().topLeft() ) );
        widget = widget->window();
#if QT_VERSION < 0x050000
        out = QPixmap::grabWidget( widget, rect );
#else
        out = widget->grab( rect );
#endif

    } else {

        if( !testFlag( Transparent ) ) {
            grabBackground( out, widget, rect );
        }
        grabWidget( out, widget, rect );

    }

    _paintEnabled = true;

    return out;

}
Example #10
0
void KisCloneLayer::updateProjection(const QRect& r)
{
    if (!m_d->copyFrom) return;
    if (!r.isValid()) return ;

    // XXX: update only the overlap of r and the rects in the dirty region

    // if there are effect masks, apply them to the either original or
    // to the original's projection.
    if (hasEffectMasks()) {
        if (m_d->projection == 0) {
            m_d->projection = new KisPaintDevice(m_d->copyFrom->colorSpace());
        }

        qint32 deltaX = m_d->copyFrom->x() - m_d->x;
        qint32 deltaY = m_d->copyFrom->y() - m_d->y;
        QRect rc = r.translated(deltaX, deltaY);

        KisPainter gc(m_d->projection);
        gc.setCompositeOp(colorSpace()->compositeOp(COMPOSITE_COPY));

        // TODO don't copy
        KisPaintDeviceSP src = 0;
        switch (m_d->type) {
        case COPY_PROJECTION:
            gc.bitBlt(rc.topLeft(), m_d->copyFrom->projection(), rc);
            src = m_d->copyFrom->projection();
            break;
        case COPY_ORIGINAL:
        default:
            gc.bitBlt(rc.topLeft(), m_d->copyFrom->original(), rc);
            src = m_d->copyFrom->original();
        }
        applyEffectMasks(m_d->copyFrom->original(), m_d->projection, r);
    }
}
Example #11
0
void PsiTipLabel::paintEvent(QPaintEvent *)
{
    QStylePainter p(this);
    QStyleOptionFrame opt;
    opt.init(this);
    if(enableColoring_) {
        p.drawPrimitive(QStyle::PE_Frame, opt);
    } else {
        p.drawPrimitive(QStyle::PE_PanelTipLabel, opt);
    }
    p.end();

    // stolen from QLabel::paintEvent
    QPainter painter(this);
    drawFrame(&painter);
    QRect cr = contentsRect();
    cr.adjust(margin, margin, -margin, -margin);

    PsiRichText::ensureTextLayouted(doc, width() - 2*margin);
    QAbstractTextDocumentLayout *layout = doc->documentLayout();
    // QRect lr = rect();
    QRect lr = cr;

    QAbstractTextDocumentLayout::PaintContext context;

    // Adjust the palette
    context.palette = palette();
    if (foregroundRole() != QPalette::Text && isEnabled())
        context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole()));

    painter.save();
    painter.translate(lr.x() + 1, lr.y() + 1);
    painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1));
    layout->draw(&painter, context);
    painter.restore();
}
Example #12
0
void QStyleItem::paint(QPainter *painter)
{
    if (width() < 1 || height() <1)
        return;

    initStyleOption();

    switch (m_itemType) {
    case Button:
        qApp->style()->drawControl(QStyle::CE_PushButton, m_styleoption, painter);
        break;
    case ItemRow :{
        QPixmap pixmap;
        // Only draw through style once
        const QString pmKey = QLatin1Literal("itemrow") % QString::number(m_styleoption->state,16) % activeControl();
        if (!QPixmapCache::find(pmKey, pixmap) || pixmap.width() < width() || height() != pixmap.height()) {
            int newSize = width();
            pixmap = QPixmap(newSize, height());
            pixmap.fill(Qt::transparent);
            QPainter pixpainter(&pixmap);
            qApp->style()->drawPrimitive(QStyle::PE_PanelItemViewRow, m_styleoption, &pixpainter);
            if (!qApp->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected) && selected())
                pixpainter.fillRect(m_styleoption->rect, m_styleoption->palette.highlight());
            QPixmapCache::insert(pmKey, pixmap);
        }
        painter->drawPixmap(0, 0, pixmap);
    }
        break;
    case Item:
        qApp->style()->drawControl(QStyle::CE_ItemViewItem, m_styleoption, painter);
        break;
    case Header:
        qApp->style()->drawControl(QStyle::CE_Header, m_styleoption, painter);
        break;
    case ToolButton:

#ifdef Q_OS_MAC
        if (style() == "mac" && hint().indexOf("segmented") != -1) {
            const QPaintDevice *target = painter->device();
             HIThemeSegmentDrawInfo sgi;
            sgi.version = 0;
            sgi.state = isEnabled() ? kThemeStateActive : kThemeStateDisabled;
            if (sunken()) sgi.state |= kThemeStatePressed;
            sgi.size = kHIThemeSegmentSizeNormal;
            sgi.kind = kHIThemeSegmentKindTextured;
            sgi.value = on() && !sunken() ? kThemeButtonOn : kThemeButtonOff;

            sgi.adornment |= kHIThemeSegmentAdornmentLeadingSeparator;
            if (sunken()) {
                sgi.adornment |= kHIThemeSegmentAdornmentTrailingSeparator;
            }
            SInt32 button_height;
            GetThemeMetric(kThemeMetricButtonRoundedHeight, &button_height);
            sgi.position = info() == "leftmost" ? kHIThemeSegmentPositionFirst:
                                                  info() == "rightmost" ? kHIThemeSegmentPositionLast :
                                                               info() == "h_middle" ? kHIThemeSegmentPositionMiddle :
                                                                                   kHIThemeSegmentPositionOnly;
            QRect centered = m_styleoption->rect;
            centered.setHeight(button_height);
            centered.moveCenter(m_styleoption->rect.center());
            HIRect hirect = qt_hirectForQRect(centered.translated(0, -1), QRect(0, 0, 0, 0));
            HIThemeDrawSegment(&hirect, &sgi, qt_mac_cg_context(target), kHIThemeOrientationNormal);
        } else
#endif
        qApp->style()->drawComplexControl(QStyle::CC_ToolButton, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter);
        break;
    case Tab:
        qApp->style()->drawControl(QStyle::CE_TabBarTab, m_styleoption, painter);
        break;
    case Frame:
        qApp->style()->drawControl(QStyle::CE_ShapedFrame, m_styleoption, painter);
        break;
    case FocusFrame:
        if (style() == "mac" && hint().indexOf("rounded") != -1)
            break; // embedded in the line itself
        else
            qApp->style()->drawControl(QStyle::CE_FocusFrame, m_styleoption, painter);
        break;
    case TabFrame:
        qApp->style()->drawPrimitive(QStyle::PE_FrameTabWidget, m_styleoption, painter);
        break;
    case MenuBar:
        qApp->style()->drawControl(QStyle::CE_MenuBarEmptyArea, m_styleoption, painter);
        break;
    case MenuBarItem:
        qApp->style()->drawControl(QStyle::CE_MenuBarItem, m_styleoption, painter);
        break;
    case MenuItem:
    case ComboBoxItem: // fall through
        qApp->style()->drawControl(QStyle::CE_MenuItem, m_styleoption, painter);
        break;
    case CheckBox:
        qApp->style()->drawControl(QStyle::CE_CheckBox, m_styleoption, painter);
        break;
    case RadioButton:
        qApp->style()->drawControl(QStyle::CE_RadioButton, m_styleoption, painter);
        break;
    case Edit: {
#ifdef Q_OS_MAC
        if (style() == "mac" && hint().indexOf("rounded") != -1) {
            const QPaintDevice *target = painter->device();
            HIThemeFrameDrawInfo fdi;
            fdi.version = 0;
            fdi.state = kThemeStateActive;
            SInt32 frame_size;
            GetThemeMetric(kThemeMetricEditTextFrameOutset, &frame_size);
            fdi.kind = kHIThemeFrameTextFieldRound;
            if ((m_styleoption->state & QStyle::State_ReadOnly) || !(m_styleoption->state & QStyle::State_Enabled))
                fdi.state = kThemeStateInactive;
            fdi.isFocused = hasFocus();
            HIRect hirect = qt_hirectForQRect(m_styleoption->rect,
                                              QRect(frame_size, frame_size,
                                                    frame_size * 2, frame_size * 2));
            HIThemeDrawFrame(&hirect, &fdi, qt_mac_cg_context(target), kHIThemeOrientationNormal);
        } else
#endif
        qApp->style()->drawPrimitive(QStyle::PE_PanelLineEdit, m_styleoption, painter);
    }
        break;
    case MacHelpButton:
#ifdef Q_OS_MAC
    {
        const QPaintDevice *target = painter->device();
        HIThemeButtonDrawInfo fdi;
        fdi.kind = kThemeRoundButtonHelp;
        fdi.version = 0;
        fdi.adornment = 0;
        fdi.state = sunken() ? kThemeStatePressed : kThemeStateActive;
        HIRect hirect = qt_hirectForQRect(m_styleoption->rect,QRect(0, 0, 0, 0));
        HIThemeDrawButton(&hirect, &fdi, qt_mac_cg_context(target), kHIThemeOrientationNormal, NULL);
    }
#endif
        break;
    case Widget:
        qApp->style()->drawPrimitive(QStyle::PE_Widget, m_styleoption, painter);
        break;
    case ScrollAreaCorner:
        qApp->style()->drawPrimitive(QStyle::PE_PanelScrollAreaCorner, m_styleoption, painter);
        break;
    case Splitter:
        if (m_styleoption->rect.width() == 1)
            painter->fillRect(0, 0, width(), height(), m_styleoption->palette.dark().color());
        else
            qApp->style()->drawControl(QStyle::CE_Splitter, m_styleoption, painter);
        break;
    case ComboBox:
    {
        qApp->style()->drawComplexControl(QStyle::CC_ComboBox,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        // This is needed on mac as it will use the painter color and ignore the palette
        QPen pen = painter->pen();
        painter->setPen(m_styleoption->palette.text().color());
        qApp->style()->drawControl(QStyle::CE_ComboBoxLabel, m_styleoption, painter);
        painter->setPen(pen);
    }    break;
    case SpinBox:
        qApp->style()->drawComplexControl(QStyle::CC_SpinBox,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        break;
    case Slider:
        qApp->style()->drawComplexControl(QStyle::CC_Slider,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        break;
    case Dial:
        qApp->style()->drawComplexControl(QStyle::CC_Dial,
                                          qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
                                          painter);
        break;
    case ProgressBar:
        qApp->style()->drawControl(QStyle::CE_ProgressBar, m_styleoption, painter);
        break;
    case ToolBar:
        qApp->style()->drawControl(QStyle::CE_ToolBar, m_styleoption, painter);
        break;
    case StatusBar:
        if (style() == "mac") {
            m_styleoption->rect.adjust(0, 1, 0, 0);
            qApp->style()->drawControl(QStyle::CE_ToolBar, m_styleoption, painter);
            m_styleoption->rect.adjust(0, -1, 0, 0);
            painter->setPen(m_styleoption->palette.dark().color().darker(120));
            painter->drawLine(m_styleoption->rect.topLeft(), m_styleoption->rect.topRight());
        } else {
            qApp->style()->drawPrimitive(QStyle::PE_PanelToolBar, m_styleoption, painter);
        }
        break;
    case GroupBox:
        qApp->style()->drawComplexControl(QStyle::CC_GroupBox, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter);
        break;
    case ScrollBar:
        qApp->style()->drawComplexControl(QStyle::CC_ScrollBar, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter);
        break;
    case Menu: {
        QStyleHintReturnMask val;
        qApp->style()->styleHint(QStyle::SH_Menu_Mask, m_styleoption, 0, &val);
        painter->save();
        painter->setClipRegion(val.region);
        painter->fillRect(m_styleoption->rect, m_styleoption->palette.window());
        painter->restore();
        qApp->style()->drawPrimitive(QStyle::PE_PanelMenu, m_styleoption, painter);

        QStyleOptionFrame frame;
        frame.lineWidth = qApp->style()->pixelMetric(QStyle::PM_MenuPanelWidth);
        frame.midLineWidth = 0;
        frame.rect = m_styleoption->rect;
        qApp->style()->drawPrimitive(QStyle::PE_FrameMenu, &frame, painter);
    }
        break;
    default:
        break;
    }
}
Example #13
0
void QVFbScreen::setDirty(const QRect& rect)
{
    const QRect r = rect.translated(-offset());
    d_ptr->hdr->dirty = true;
    d_ptr->hdr->update = d_ptr->hdr->update.united(r);
}
void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset)
{
    Q_D(QRasterWindowSurface);

    // Not ready for painting yet, bail out. This can happen in
    // QWidget::create_sys()
    if (!d->image || rgn.rectCount() == 0)
        return;

#ifdef Q_WS_WIN
    QRect br = rgn.boundingRect();

    if (!qt_widget_private(window())->isOpaque
        && window()->testAttribute(Qt::WA_TranslucentBackground)
        && (qt_widget_private(window())->data.window_flags & Qt::FramelessWindowHint))
    {
        QRect r = window()->frameGeometry();
        QPoint frameOffset = qt_widget_private(window())->frameStrut().topLeft();
        QRect dirtyRect = br.translated(offset + frameOffset);

        SIZE size = {r.width(), r.height()};
        POINT ptDst = {r.x(), r.y()};
        POINT ptSrc = {0, 0};
        BLENDFUNCTION blend = {AC_SRC_OVER, 0, (BYTE)(255.0 * window()->windowOpacity()), Q_AC_SRC_ALPHA};
        RECT dirty = {dirtyRect.x(), dirtyRect.y(),
            dirtyRect.x() + dirtyRect.width(), dirtyRect.y() + dirtyRect.height()};
        Q_UPDATELAYEREDWINDOWINFO info = {sizeof(info), NULL, &ptDst, &size, d->image->hdc, &ptSrc, 0, &blend, Q_ULW_ALPHA, &dirty};
        ptrUpdateLayeredWindowIndirect(window()->internalWinId(), &info);
    } else

    {
        QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft();

        HDC widget_dc = widget->getDC();

        QRect wbr = br.translated(-wOffset);
        BitBlt(widget_dc, wbr.x(), wbr.y(), wbr.width(), wbr.height(),
               d->image->hdc, br.x() + offset.x(), br.y() + offset.y(), SRCCOPY);
        widget->releaseDC(widget_dc);
    }

#ifndef QT_NO_DEBUG
    static bool flush = !qgetenv("QT_FLUSH_WINDOWSURFACE").isEmpty();
    if (flush) {
        SelectObject(qt_win_display_dc(), GetStockObject(BLACK_BRUSH));
        Rectangle(qt_win_display_dc(), 0, 0, d->image->width() + 2, d->image->height() + 2);
        BitBlt(qt_win_display_dc(), 1, 1, d->image->width(), d->image->height(),
               d->image->hdc, 0, 0, SRCCOPY);
    }
#endif

#endif

#ifdef Q_WS_X11
    extern void *qt_getClipRects(const QRegion &r, int &num); // in qpaintengine_x11.cpp
    extern QWidgetData* qt_widget_data(QWidget *);
    QPoint wOffset = qt_qwidget_data(widget)->wrect.topLeft();

    if (widget->window() != window()) {
        XFreeGC(X11->display, d_ptr->gc);
        d_ptr->gc = XCreateGC(X11->display, widget->handle(), 0, 0);
    }

    QRegion wrgn(rgn);
    if (!wOffset.isNull())
        wrgn.translate(-wOffset);

    if (wrgn.rectCount() != 1) {
        int num;
        XRectangle *rects = (XRectangle *)qt_getClipRects(wrgn, num);
        XSetClipRectangles(X11->display, d_ptr->gc, 0, 0, rects, num, YXBanded);
    }

    QPoint widgetOffset = offset + wOffset;
    QRect clipRect = widget->rect().translated(widgetOffset).intersected(d_ptr->image->image.rect());

    QRect br = rgn.boundingRect().translated(offset).intersected(clipRect);
    QPoint wpos = br.topLeft() - widgetOffset;

#ifndef QT_NO_MITSHM
    if (d_ptr->image->xshmpm) {
        XCopyArea(X11->display, d_ptr->image->xshmpm, widget->handle(), d_ptr->gc,
                  br.x(), br.y(), br.width(), br.height(), wpos.x(), wpos.y());
        d_ptr->needsSync = true;
    } else if (d_ptr->image->xshmimg) {
        XShmPutImage(X11->display, widget->handle(), d_ptr->gc, d_ptr->image->xshmimg,
                     br.x(), br.y(), wpos.x(), wpos.y(), br.width(), br.height(), False);
        d_ptr->needsSync = true;
    } else
#endif
    {
        int depth = widget->x11Info().depth();
        const QImage &src = d->image->image;
        if (src.format() != QImage::Format_RGB32 || depth < 24 || X11->bppForDepth.value(depth) != 32) {
            Q_ASSERT(src.depth() >= 16);
            const QImage sub_src(src.scanLine(br.y()) + br.x() * (uint(src.depth()) / 8),
                                 br.width(), br.height(), src.bytesPerLine(), src.format());
            QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType);
            data->xinfo = widget->x11Info();
            data->fromImage(sub_src, Qt::NoOpaqueDetection);
            QPixmap pm = QPixmap(data);
            XCopyArea(X11->display, pm.handle(), widget->handle(), d_ptr->gc, 0 , 0 , br.width(), br.height(), wpos.x(), wpos.y());
        } else {
            // qpaintengine_x11.cpp
            extern void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const QImage &image, Drawable hd, GC gc, Display *dpy, Visual *visual, int depth);
            qt_x11_drawImage(br, wpos, src, widget->handle(), d_ptr->gc, X11->display, (Visual *)widget->x11Info().visual(), depth);
        }
    }

    if (wrgn.rectCount() != 1)
        XSetClipMask(X11->display, d_ptr->gc, XNone);
#endif // FALCON

#ifdef Q_WS_MAC

    Q_UNUSED(offset);

    // This is mainly done for native components like native "open file" dialog.
    if (widget->testAttribute(Qt::WA_DontShowOnScreen)) {
        return;
    }

#ifdef QT_MAC_USE_COCOA

    this->needsFlush = true;
    this->regionToFlush += rgn;

    // The actual flushing will be processed in [view drawRect:rect]
    qt_mac_setNeedsDisplay(widget);

#else
    // Get a context for the widget.
    CGContextRef context;
    CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
    QDBeginCGContext(port, &context);
    CGContextRetain(context);
    CGContextSaveGState(context);

    // Flip context.
    CGContextTranslateCTM(context, 0, widget->height());
    CGContextScaleCTM(context, 1, -1);

    // Clip to region.
    const QVector<QRect> &rects = rgn.rects();
    for (int i = 0; i < rects.size(); ++i) {
        const QRect &rect = rects.at(i);
        CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()));
    }
    CGContextClip(context);

    QRect r = rgn.boundingRect().intersected(d->image->image.rect());
    const CGRect area = CGRectMake(r.x(), r.y(), r.width(), r.height());
    CGImageRef image = CGBitmapContextCreateImage(d->image->cg);
    CGImageRef subImage = CGImageCreateWithImageInRect(image, area);

    qt_mac_drawCGImage(context, &area, subImage);

    CGImageRelease(subImage);
    CGImageRelease(image);

    QDEndCGContext(port, &context);

    // Restore context.
    CGContextRestoreGState(context);
    CGContextRelease(context);
#endif // QT_MAC_USE_COCOA

#endif // Q_WS_MAC

}
QT_BEGIN_NAMESPACE

QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h)
{
    QWidget *widget = QWidget::find(window);
    if (!widget)
        return QPixmap();

    QRect grabRect = widget->frameGeometry();
    if (!widget->isWindow())
        grabRect.translate(widget->parentWidget()->mapToGlobal(QPoint()));
    if (w < 0)
        w = widget->width() - x;
    if (h < 0)
        h = widget->height() - y;
    grabRect &= QRect(x, y, w, h).translated(widget->mapToGlobal(QPoint()));

    QScreen *screen = qt_screen;
    QDesktopWidget *desktop = QApplication::desktop();
    if (!desktop)
        return QPixmap();
    if (desktop->numScreens() > 1) {
        const int screenNo = desktop->screenNumber(widget);
        if (screenNo != -1)
            screen = qt_screen->subScreens().at(screenNo);
        grabRect = grabRect.translated(-screen->region().boundingRect().topLeft());
    }

    if (screen->pixelFormat() == QImage::Format_Invalid) {
        qWarning("QPixmap::grabWindow(): Unable to copy pixels from framebuffer");
        return QPixmap();
    }

    if (screen->isTransformed()) {
        const QSize screenSize(screen->width(), screen->height());
        grabRect = screen->mapToDevice(grabRect, screenSize);
    }

    QWSDisplay::grab(false);
    QPixmap pixmap;
    QImage img(screen->base(),
               screen->deviceWidth(), screen->deviceHeight(),
               screen->linestep(), screen->pixelFormat());
    img = img.copy(grabRect);
    QWSDisplay::ungrab();

    if (screen->isTransformed()) {
        QMatrix matrix;
        switch (screen->transformOrientation()) {
        case 1: matrix.rotate(90); break;
        case 2: matrix.rotate(180); break;
        case 3: matrix.rotate(270); break;
        default: break;
        }
        img = img.transformed(matrix);
    }

    if (screen->pixelType() == QScreen::BGRPixel)
        img = img.rgbSwapped();

    return QPixmap::fromImage(img);
}
void HistoryGame::draw(Painter &p, const QRect &r, TextSelection selection, crl::time ms) const {
	if (width() < st::msgPadding.left() + st::msgPadding.right() + 1) return;
	auto paintw = width(), painth = height();

	auto outbg = _parent->hasOutLayout();
	bool selected = (selection == FullSelection);

	auto &barfg = selected ? (outbg ? st::msgOutReplyBarSelColor : st::msgInReplyBarSelColor) : (outbg ? st::msgOutReplyBarColor : st::msgInReplyBarColor);
	auto &semibold = selected ? (outbg ? st::msgOutServiceFgSelected : st::msgInServiceFgSelected) : (outbg ? st::msgOutServiceFg : st::msgInServiceFg);
	auto &regular = selected ? (outbg ? st::msgOutDateFgSelected : st::msgInDateFgSelected) : (outbg ? st::msgOutDateFg : st::msgInDateFg);

	QMargins bubble(_attach ? _attach->bubbleMargins() : QMargins());
	auto padding = inBubblePadding();
	auto tshift = padding.top();
	auto bshift = padding.bottom();
	paintw -= padding.left() + padding.right();
	if (isBubbleBottom() && _attach && _attach->customInfoLayout() && _attach->width() + _parent->skipBlockWidth() > paintw + bubble.left() + bubble.right()) {
		bshift += bottomInfoPadding();
	}

	QRect bar(rtlrect(st::msgPadding.left(), tshift, st::webPageBar, height() - tshift - bshift, width()));
	p.fillRect(bar, barfg);

	auto lineHeight = unitedLineHeight();
	if (_titleLines) {
		p.setPen(semibold);
		auto endskip = 0;
		if (_title.hasSkipBlock()) {
			endskip = _parent->skipBlockWidth();
		}
		_title.drawLeftElided(p, padding.left(), tshift, paintw, width(), _titleLines, style::al_left, 0, -1, endskip, false, selection);
		tshift += _titleLines * lineHeight;
	}
	if (_descriptionLines) {
		p.setPen(outbg ? st::webPageDescriptionOutFg : st::webPageDescriptionInFg);
		auto endskip = 0;
		if (_description.hasSkipBlock()) {
			endskip = _parent->skipBlockWidth();
		}
		_description.drawLeftElided(p, padding.left(), tshift, paintw, width(), _descriptionLines, style::al_left, 0, -1, endskip, false, toDescriptionSelection(selection));
		tshift += _descriptionLines * lineHeight;
	}
	if (_attach) {
		auto attachAtTop = !_titleLines && !_descriptionLines;
		if (!attachAtTop) tshift += st::mediaInBubbleSkip;

		auto attachLeft = padding.left() - bubble.left();
		auto attachTop = tshift - bubble.top();
		if (rtl()) attachLeft = width() - attachLeft - _attach->width();

		auto attachSelection = selected ? FullSelection : TextSelection { 0, 0 };

		p.translate(attachLeft, attachTop);
		_attach->draw(p, r.translated(-attachLeft, -attachTop), attachSelection, ms);
		auto pixwidth = _attach->width();
		auto pixheight = _attach->height();

		auto gameW = _gameTagWidth + 2 * st::msgDateImgPadding.x();
		auto gameH = st::msgDateFont->height + 2 * st::msgDateImgPadding.y();
		auto gameX = pixwidth - st::msgDateImgDelta - gameW;
		auto gameY = pixheight - st::msgDateImgDelta - gameH;

		App::roundRect(p, rtlrect(gameX, gameY, gameW, gameH, pixwidth), selected ? st::msgDateImgBgSelected : st::msgDateImgBg, selected ? DateSelectedCorners : DateCorners);

		p.setFont(st::msgDateFont);
		p.setPen(st::msgDateImgFg);
		p.drawTextLeft(gameX + st::msgDateImgPadding.x(), gameY + st::msgDateImgPadding.y(), pixwidth, lang(lng_game_tag).toUpper());

		p.translate(-attachLeft, -attachTop);
	}
}
Example #17
0
void VideoOutputOpenGL::PrepareFrame(VideoFrame *buffer, FrameScanType t,
                                     OSD *osd)
{
    if (!gl_context)
        return;

    OpenGLLocker ctx_lock(gl_context);

    if (!buffer)
    {
        buffer = vbuffers.GetScratchFrame();
        if (m_deinterlacing && !IsBobDeint())
            t = kScan_Interlaced;
    }

    gl_context_lock.lock();
    framesPlayed = buffer->frameNumber + 1;
    gl_context_lock.unlock();

    gl_context->BindFramebuffer(0);
    if (db_letterbox_colour == kLetterBoxColour_Gray25)
        gl_context->SetBackground(127, 127, 127, 255);
    else
        gl_context->SetBackground(0, 0, 0, 255);
    gl_context->ClearFramebuffer();

    // stereoscopic views
    QRect main   = gl_context->GetViewPort();
    QRect first  = main;
    QRect second = main;
    bool twopass = (m_stereo == kStereoscopicModeSideBySide) ||
                   (m_stereo == kStereoscopicModeTopAndBottom);

    if (kStereoscopicModeSideBySide == m_stereo)
    {
        first  = QRect(main.left() / 2,  main.top(),
                       main.width() / 2, main.height());
        second = first.translated(main.width() / 2, 0);
    }
    else if (kStereoscopicModeTopAndBottom == m_stereo)
    {
        first  = QRect(main.left(),  main.top() / 2,
                       main.width(), main.height() / 2);
        second = first.translated(0, main.height() / 2);
    }

    // main UI when embedded
    MythMainWindow *mwnd = GetMythMainWindow();
    if (mwnd && mwnd->GetPaintWindow() && window.IsEmbedding())
    {
        if (twopass)
            gl_context->SetViewPort(first, true);
        mwnd->GetPaintWindow()->clearMask();
        // Must force a UI redraw when embedded.  If not, when the EPG or
        // finder screen is popped up over the video and the user then clicks
        // away from Myth, the UI is left blank.
        mwnd->GetMainStack()->GetTopScreen()->SetRedraw();
        mwnd->draw(gl_painter);
        if (twopass)
        {
            gl_context->SetViewPort(second, true);
            mwnd->GetPaintWindow()->clearMask();
            mwnd->GetMainStack()->GetTopScreen()->SetRedraw();
            mwnd->draw(gl_painter);
            gl_context->SetViewPort(main, true);
        }
    }

    // video
    if (gl_videochain && !buffer->dummy)
    {
        gl_videochain->SetVideoRect(vsz_enabled ? vsz_desired_display_rect :
                                                  window.GetDisplayVideoRect(),
                                    window.GetVideoRect());
        gl_videochain->PrepareFrame(buffer->top_field_first, t,
                                    m_deinterlacing, framesPlayed, m_stereo);
    }

    // PiPs/PBPs
    if (gl_pipchains.size())
    {
        QMap<MythPlayer*,OpenGLVideo*>::iterator it = gl_pipchains.begin();
        for (; it != gl_pipchains.end(); ++it)
        {
            if (gl_pip_ready[it.key()])
            {
                bool active = gl_pipchain_active == *it;
                if (twopass)
                    gl_context->SetViewPort(first, true);
                (*it)->PrepareFrame(buffer->top_field_first, t,
                                    m_deinterlacing, framesPlayed,
                                    kStereoscopicModeNone, active);
                if (twopass)
                {
                    gl_context->SetViewPort(second, true);
                    (*it)->PrepareFrame(buffer->top_field_first, t,
                                    m_deinterlacing, framesPlayed,
                                    kStereoscopicModeNone, active);
                    gl_context->SetViewPort(main);
                }
            }
        }
    }

    // visualisation
    if (m_visual && gl_painter && !window.IsEmbedding())
    {
        if (twopass)
            gl_context->SetViewPort(first, true);
        m_visual->Draw(GetTotalOSDBounds(), gl_painter, nullptr);
        if (twopass)
        {
            gl_context->SetViewPort(second, true);
            m_visual->Draw(GetTotalOSDBounds(), gl_painter, nullptr);
            gl_context->SetViewPort(main);
        }
    }

    // OSD
    if (osd && gl_painter && !window.IsEmbedding())
    {
        if (twopass)
            gl_context->SetViewPort(first, true);
        osd->DrawDirect(gl_painter, GetTotalOSDBounds().size(), true);
        if (twopass)
        {
            gl_context->SetViewPort(second, true);
            osd->DrawDirect(gl_painter, GetTotalOSDBounds().size(), true);
            gl_context->SetViewPort(main);
        }
    }

    gl_context->Flush(false);

    if (vbuffers.GetScratchFrame() == buffer)
        vbuffers.SetLastShownFrameToScratch();
}
Example #18
0
void SearchDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
   QStyleOptionViewItemV4 newOption(option);
   newOption.state = option.state & (~QStyle::State_HasFocus);

   switch (index.column())
   {
   case 0:
      {
         this->initStyleOption(&newOption, index);

         QTextDocument doc;
         doc.setHtml(this->toHtmlText(newOption.text));

         // Painting item without text.
         newOption.text = QString();
         QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &newOption, painter, newOption.widget);

         QAbstractTextDocumentLayout::PaintContext ctx;
         ctx.palette = newOption.palette;

         const QRect textRect = QApplication::style()->subElementRect(QStyle::SE_ItemViewItemText, &newOption);
         painter->save();
         painter->translate(textRect.topLeft());
         painter->setClipRect(textRect.translated(-textRect.topLeft()));
         doc.documentLayout()->draw(painter, ctx);
         painter->restore();
      }
      break;

   case 2: // Match rate.
      {
         QStyledItemDelegate::paint(painter, newOption, index);

         if (index.data().isNull())
            return;

         int value = index.data().toInt();

         QStyleOptionProgressBarV2 progressBarOption;
         progressBarOption.QStyleOption::operator=(option);
         progressBarOption.minimum = 0;
         progressBarOption.maximum = 100;
         progressBarOption.textAlignment = Qt::AlignHCenter;
         progressBarOption.progress = value;
         progressBarOption.textVisible = false;

         QRect rect(progressBarOption.rect);
         const int height = rect.height();
         rect.setTop(rect.top() + height / 4);
         rect.setBottom(rect.bottom() - height / 4);
         progressBarOption.rect = rect;

         QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter, &this->model);
      }
      break;

   default:
      QStyledItemDelegate::paint(painter, newOption, index);
   }
}
Example #19
0
/*!
    \reimp
*/
void QTransformedScreen::blit(const QImage &image, const QPoint &topLeft,
                              const QRegion &region)
{
    const Transformation trans = d_ptr->transformation;
    if (trans == None) {
        QProxyScreen::blit(image, topLeft, region);
        return;
    }

    const QVector<QRect> rects = region.rects();
    const QRect bound = QRect(0, 0, QScreen::w, QScreen::h)
                        & QRect(topLeft, image.size());

    BlitFunc func = 0;
#ifdef QT_QWS_DEPTH_GENERIC
    if (d_ptr->doGenericColors && depth() == 16) {
        if (image.depth() == 16)
            SET_BLIT_FUNC(qrgb_generic16, quint16, trans, func);
        else
            SET_BLIT_FUNC(qrgb_generic16, quint32, trans, func);
    } else
#endif
    switch (depth()) {
#ifdef QT_QWS_DEPTH_32
    case 32:
#ifdef QT_QWS_DEPTH_16
        if (image.depth() == 16)
            SET_BLIT_FUNC(quint32, quint16, trans, func);
        else
#endif
            SET_BLIT_FUNC(quint32, quint32, trans, func);
        break;
#endif
#if defined(QT_QWS_DEPTH_24) || defined(QT_QWS_DEPTH18)
    case 24:
    case 18:
        SET_BLIT_FUNC(quint24, quint24, trans, func);
        break;
#endif
#if defined(QT_QWS_DEPTH_16) || defined(QT_QWS_DEPTH_15) || defined(QT_QWS_DEPTH_12)
    case 16:
#if defined QT_QWS_ROTATE_BGR
        if (pixelType() == BGRPixel && image.depth() == 16) {
            SET_BLIT_FUNC(qbgr565, quint16, trans, func);
            break;
        } //fall-through here!!!
#endif
    case 15:
#if defined QT_QWS_ROTATE_BGR
        if (pixelType() == BGRPixel && image.format() == QImage::Format_RGB555) {
            SET_BLIT_FUNC(qbgr555, qrgb555, trans, func);
            break;
        } //fall-through here!!!
#endif
    case 12:
        if (image.depth() == 16)
            SET_BLIT_FUNC(quint16, quint16, trans, func);
        else
            SET_BLIT_FUNC(quint16, quint32, trans, func);
        break;
#endif
#ifdef QT_QWS_DEPTH_8
    case 8:
        if (image.format() == QImage::Format_RGB444)
            SET_BLIT_FUNC(quint8, qrgb444, trans, func);
        else if (image.depth() == 16)
            SET_BLIT_FUNC(quint8, quint16, trans, func);
        else
            SET_BLIT_FUNC(quint8, quint32, trans, func);
        break;
#endif
    default:
        return;
    }
    if (!func)
        return;

    QWSDisplay::grab();
    for (int i = 0; i < rects.size(); ++i) {
        const QRect r = rects.at(i) & bound;

        QPoint dst;
        switch (trans) {
        case Rot90:
            dst = mapToDevice(r.topRight(), QSize(w, h));
            break;
        case Rot180:
            dst = mapToDevice(r.bottomRight(), QSize(w, h));
            break;
        case Rot270:
            dst = mapToDevice(r.bottomLeft(), QSize(w, h));
            break;
        default:
            break;
        }
        func(this, image, r.translated(-topLeft), dst);
    }
    QWSDisplay::ungrab();

}
Example #20
0
void AMDetailedItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const  {

	QStyleOptionViewItemV4 opt(option);
	initStyleOption(&opt, index);


	QStyle* sty = QApplication::style();

	// Draw the background: (this will handle selection for us. You can also probe selection directly with opt.state & QStyle::State_Selected)
	sty->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter);


	int textStartingPoint = horizontalMargin();
	// Do we have a pixmap available?
	QRect pmap = opt.rect;
	pmap.setLeft( pmap.left() + horizontalMargin() );
	pmap.setTop( pmap.top() + verticalMargin() );
	pmap.setBottom( pmap.bottom() - verticalMargin() );

	if(opt.features & QStyleOptionViewItemV2::HasDecoration) {
		QPixmap p = opt.icon.pixmap(pmap.height());
		sty->drawItemPixmap(painter, pmap, Qt::AlignLeft | Qt::AlignVCenter, p);
		textStartingPoint += horizontalMargin() + p.width() + horizontalSpacing();
	}

	QRect textRect = opt.rect;
	textRect.setLeft( textRect.left() + textStartingPoint);


	if (index.data(AM::ModifiedRole).toBool()) {
		fontItalic_.setPointSize(size1_);
		painter->setFont(fontItalic_);
	}
	else {
		font_.setPointSize(size1_);
		painter->setFont(font_);
	}
	painter->setPen(color1_);

	painter->drawText(textRect, index.data(Qt::DisplayRole).toString());

	QVariant description = index.data(AM::DescriptionRole);
	if(!description.isNull()){
		font_.setPointSize(size2_);
		painter->setFont(font_);
		painter->setPen(color2_);
		QFontMetrics fontMetrics(font_);

		painter->drawText(textRect.translated(QPoint(0,20)), fontMetrics.elidedText(description.toString(), Qt::ElideRight, textRect.width() ));

	}

	/// call base class to draw close button:
	drawCloseButton(painter, opt, index);


	/* What info is available:
enum OptionType
enum Position
enum StyleOptionType
enum StyleOptionVersion
enum ViewItemFeature
flags ViewItemFeatures
enum ViewItemPosition
QStyleOptionViewItemV4 ()
QStyleOptionViewItemV4 ( const QStyleOptionViewItemV4 & )
QStyleOptionViewItemV4 ( const QStyleOptionViewItem & )
backgroundBrush : QBrush
checkState : Qt::CheckState
decorationAlignment : Qt::Alignment
decorationPosition : Position
decorationSize : QSize
direction : Qt::LayoutDirection
displayAlignment : Qt::Alignment
features : ViewItemFeatures
font : QFont
fontMetrics : QFontMetrics
icon : QIcon
index : QModelIndex
initFrom ( const QWidget * )
locale : QLocale
palette : QPalette
rect : QRect
showDecorationSelected : bool
state : QStyle::State
text : QString
textElideMode : Qt::TextElideMode
type : int
version : int
viewItemPosition : ViewItemPosition
widget : const QWidget *
operator= ( const QStyleOptionViewItem & ) : QStyleOption
*/
}
Example #21
0
void FilmstripFrames::paintEvent(QPaintEvent *evt) {
  QPainter p(this);

  // p.setRenderHint(QPainter::Antialiasing, true);

  QRect clipRect = evt->rect();

  p.fillRect(clipRect, Qt::black);
  // thumbnail rect, including offsets
  QRect iconImgRect = QRect(QPoint(fs_leftMargin + fs_iconMarginLR,
                                   fs_frameSpacing / 2 + fs_iconMarginTop),
                            m_iconSize);
  // frame size with margins
  QSize frameSize = m_iconSize + QSize(fs_iconMarginLR * 2,
                                       fs_iconMarginTop + fs_iconMarginBottom);
  //  .. and with offset
  QRect frameRect =
      QRect(QPoint(fs_leftMargin, fs_frameSpacing / 2), frameSize);

  int oneFrameHeight = frameSize.height() + fs_frameSpacing;

  // visible frame index range
  int i0 = y2index(clipRect.top());
  int i1 = y2index(clipRect.bottom());

  // fids, frameCount <- frames del livello
  std::vector<TFrameId> fids;
  TXshSimpleLevel *sl = getLevel();
  if (sl)
    sl->getFids(fids);
  else {
    for (int i = i0; i <= i1; i++) {
      // draw white rectangles if obtaining the level is failed
      QRect iconRect = frameRect.translated(QPoint(0, oneFrameHeight * i));
      p.setBrush(QColor(192, 192, 192));
      p.setPen(Qt::NoPen);
      p.drawRect(iconRect);
    }
    return;
  }

  //--- compute navigator rect ---

  QRect naviRect;
  ComboViewerPanel *inknPaintViewerPanel =
      TApp::instance()->getInknPaintViewerPanel();
  if (sl->getType() == TZP_XSHLEVEL && inknPaintViewerPanel) {
    // show navigator only if the inknpaint viewer is visible
    if (inknPaintViewerPanel->isVisible()) {
      SceneViewer *viewer = inknPaintViewerPanel->getSceneViewer();
      // imgSize: image's pixel size
      QSize imgSize(sl->getProperties()->getImageRes().lx,
                    sl->getProperties()->getImageRes().ly);
      // Viewer affine
      TAffine viewerAff =
          inknPaintViewerPanel->getSceneViewer()->getViewMatrix();
      // pixel size which will be displayed with 100% scale in Viewer Stage
      TFrameId currentId = TApp::instance()->getCurrentFrame()->getFid();
      double imgPixelWidth =
          (double)(imgSize.width()) / sl->getDpi(currentId).x * Stage::inch;
      double imgPixelHeight =
          (double)(imgSize.height()) / sl->getDpi(currentId).y * Stage::inch;

      // get the image's corner positions in viewer matrix (with current zoom
      // scale)
      TPointD imgTopRight =
          viewerAff * TPointD(imgPixelWidth / 2.0f, imgPixelHeight / 2.0f);
      TPointD imgBottomLeft =
          viewerAff * TPointD(-imgPixelWidth / 2.0f, -imgPixelHeight / 2.0f);

      // pixel size in viewer matrix ( with current zoom scale )
      QSizeF imgSizeInViewer(imgTopRight.x - imgBottomLeft.x,
                             imgTopRight.y - imgBottomLeft.y);

      // ratio of the Viewer frame's position and size
      QRectF naviRatio(
          (-(float)viewer->width() * 0.5f - (float)imgBottomLeft.x) /
              imgSizeInViewer.width(),
          1.0f -
              ((float)viewer->height() * 0.5f - (float)imgBottomLeft.y) /
                  imgSizeInViewer.height(),
          (float)viewer->width() / imgSizeInViewer.width(),
          (float)viewer->height() / imgSizeInViewer.height());

      naviRect = QRect(iconImgRect.left() +
                           (int)(naviRatio.left() * (float)iconImgRect.width()),
                       iconImgRect.top() +
                           (int)(naviRatio.top() * (float)iconImgRect.height()),
                       (int)((float)iconImgRect.width() * naviRatio.width()),
                       (int)((float)iconImgRect.height() * naviRatio.height()));
      // for drag move
      m_naviRectPos = naviRect.center();

      naviRect = naviRect.intersected(frameRect);

      m_icon2ViewerRatio.setX(imgSizeInViewer.width() /
                              (float)iconImgRect.width());
      m_icon2ViewerRatio.setY(imgSizeInViewer.height() /
                              (float)iconImgRect.height());
    }
  }

  //--- compute navigator rect end ---

  int frameCount = (int)fids.size();

  std::set<TFrameId> editableFrameRange;

  if (sl) editableFrameRange = sl->getEditableRange();

  bool isReadOnly    = false;
  if (sl) isReadOnly = sl->isReadOnly();

  int i;
  int iconWidth   = m_iconSize.width();
  int x0          = m_frameLabelWidth;
  int x1          = x0 + iconWidth;
  int frameHeight = m_iconSize.height();

  // linee orizzontali che separano i frames
  p.setPen(getLightLineColor());
  for (i = i0; i <= i1; i++) {
    int y = index2y(i) + frameHeight;
    p.drawLine(0, y, x1, y);
  }

  TFilmstripSelection::InbetweenRange range = m_selection->getInbetweenRange();

  // draw for each frames
  for (i = i0; i <= i1; i++) {
    QRect tmp_iconImgRect =
        iconImgRect.translated(QPoint(0, oneFrameHeight * i));
    QRect tmp_frameRect = frameRect.translated(QPoint(0, oneFrameHeight * i));

    bool isCurrentFrame =
        (i == sl->fid2index(TApp::instance()->getCurrentFrame()->getFid()));
    bool isSelected =
        (0 <= i && i < frameCount && m_selection->isSelected(fids[i]));

    if (0 <= i && i < frameCount) {
      TFrameId fid = fids[i];

      // normal or inbetween (for vector levels)
      int flags = (sl->getType() == PLI_XSHLEVEL && range.first < fid &&
                   fid < range.second)
                      ? F_INBETWEEN_RANGE
                      : F_NORMAL;

      // draw icons
      drawFrameIcon(p, tmp_iconImgRect, i, fid, flags);

      p.setPen(Qt::NoPen);
      p.setBrush(Qt::NoBrush);
      p.drawRect(tmp_iconImgRect);

      // Frame number
      if (m_selection->isSelected(fids[i])) {
        if (TApp::instance()->getCurrentFrame()->isEditingLevel() &&
            isCurrentFrame)
          p.setPen(Qt::red);
        else
          p.setPen(Qt::white);
      } else
        p.setPen(QColor(192, 192, 192));

      p.setBrush(Qt::NoBrush);
      // for single frame
      QString text;
      if (fid.getNumber() == TFrameId::EMPTY_FRAME ||
          fid.getNumber() == TFrameId::NO_FRAME) {
        text = QString("Single Frame");
      }
      // for sequencial frame (with letter)
      else if (Preferences::instance()->isShowFrameNumberWithLettersEnabled()) {
        text = fidToFrameNumberWithLetter(fid.getNumber());
      }
      // for sequencial frame
      else {
        text = QString::number(fid.getNumber()).rightJustified(4, '0');
      }
      p.drawText(tmp_frameRect.adjusted(0, 0, -3, 2), text,
                 QTextOption(Qt::AlignRight | Qt::AlignBottom));
      p.setPen(Qt::NoPen);

      // Read-only frames (lock)
      if (0 <= i && i < frameCount) {
        if ((editableFrameRange.empty() && isReadOnly) ||
            (isReadOnly && (!editableFrameRange.empty() &&
                            editableFrameRange.count(fids[i]) == 0))) {
          static QPixmap lockPixmap(":Resources/forbidden.png");
          p.drawPixmap(tmp_frameRect.bottomLeft() + QPoint(3, -13), lockPixmap);
        }
      }
    }

    // navigator rect
    if (naviRect.isValid() && isCurrentFrame) {
      p.setPen(QPen(Qt::red, 1));
      p.drawRect(naviRect.translated(0, oneFrameHeight * i));
      p.setPen(Qt::NoPen);
    }

    // red frame for the current frame
    if (TApp::instance()->getCurrentFrame()->isEditingLevel() &&
        (isCurrentFrame || isSelected)) {
      QPen pen;
      pen.setColor(Qt::red);
      pen.setWidth(2);
      pen.setJoinStyle(Qt::RoundJoin);
      p.setPen(pen);

      p.drawRect(tmp_frameRect.adjusted(-1, -1, 2, 2));
      p.setPen(Qt::NoPen);
    }
  }

  // se sono in modalita' level edit faccio vedere la freccia che indica il
  // frame corrente
  if (TApp::instance()->getCurrentFrame()->isEditingLevel())
    m_frameHeadGadget->draw(p, QColor(Qt::white), QColor(Qt::black));
}
Example #22
0
void GrabberBase::grab() {
    DEBUG_MID_LEVEL << Q_FUNC_INFO << this->metaObject()->className();
    QList< ScreenInfo > screens2Grab;
    screens2Grab.reserve(5);
    screensWithWidgets(&screens2Grab, *_context->grabWidgets);
    if (isReallocationNeeded(screens2Grab)) {
        if (!reallocate(screens2Grab)) {
            qCritical() << Q_FUNC_INFO << " couldn't reallocate grabbing buffer";
            emit frameGrabAttempted(GrabResultError);
            return;
        }
    }
    _lastGrabResult = grabScreens();
    if (_lastGrabResult == GrabResultOk) {
        _context->grabResult->clear();

        for (int i = 0; i < _context->grabWidgets->size(); ++i) {
            QRect widgetRect = _context->grabWidgets->at(i)->frameGeometry();
            getValidRect(widgetRect);

            const GrabbedScreen *grabbedScreen = screenOfRect(widgetRect);
            if (grabbedScreen == NULL) {
                DEBUG_HIGH_LEVEL << Q_FUNC_INFO << " widget is out of screen " << Debug::toString(widgetRect);
                _context->grabResult->append(0);
                continue;
            }
            DEBUG_HIGH_LEVEL << Q_FUNC_INFO << Debug::toString(widgetRect);
            QRect monitorRect = grabbedScreen->screenInfo.rect;

            QRect clippedRect = monitorRect.intersected(widgetRect);

            // Checking for the 'grabme' widget position inside the monitor that is used to capture color
            if( !clippedRect.isValid() ){

                DEBUG_MID_LEVEL << "Widget 'grabme' is out of screen:" << Debug::toString(clippedRect);

                _context->grabResult->append(qRgb(0,0,0));
                continue;
            }

            // Convert coordinates from "Main" desktop coord-system to capture-monitor coord-system
            QRect preparedRect = clippedRect.translated(-monitorRect.x(), -monitorRect.y());

            // Align width by 4 for accelerated calculations
            preparedRect.setWidth(preparedRect.width() - (preparedRect.width() % 4));

            if( !preparedRect.isValid() ){
                qWarning() << Q_FUNC_INFO << " preparedRect is not valid:" << Debug::toString(preparedRect);
                // width and height can't be negative

                _context->grabResult->append(qRgb(0,0,0));
                continue;
            }

            using namespace Grab;
            const int bytesPerPixel = 4;
            QRgb avgColor;
            if (_context->grabWidgets->at(i)->isAreaEnabled()) {
                Calculations::calculateAvgColor(&avgColor, grabbedScreen->imgData, grabbedScreen->imgFormat, grabbedScreen->screenInfo.rect.width() * bytesPerPixel, preparedRect );
                _context->grabResult->append(avgColor);
            } else {
                _context->grabResult->append(qRgb(0,0,0));
            }
        }

    }
    emit frameGrabAttempted(_lastGrabResult);
}
Example #23
0
 void update( const QRect & rect ) { m_parent->update( rect.translated( m_rect.topLeft() ) ); }
Example #24
0
void ArthurStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *option,
                                     QPainter *painter, const QWidget *widget) const
{
    switch (control) {
    case CC_Slider:
        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(option)) {
            QRect groove = subControlRect(CC_Slider, option, SC_SliderGroove, widget);
            QRect handle = subControlRect(CC_Slider, option, SC_SliderHandle, widget);

            painter->save();

            bool hover = (slider->state & State_Enabled) && (slider->state & State_MouseOver);
            if (hover) {
                QRect moderated = widget->rect().adjusted(0, 4, 0, -4);
                drawHoverRect(painter, moderated);
            }

            if ((option->subControls & SC_SliderGroove) && groove.isValid()) {
                QPixmap grv = cached(":res/images/slider_bar.png");
                painter->drawPixmap(QRect(groove.x() + 5, groove.y(),
                                          groove.width() - 10, grv.height()),
                                    grv);
            }
            if ((option->subControls & SC_SliderHandle) && handle.isValid()) {
                QPixmap hndl = cached(":res/images/slider_thumb_on.png");
                painter->drawPixmap(handle.topLeft(), hndl);
            }

            painter->restore();
        }
        break;
    case CC_GroupBox:
        if (const QStyleOptionGroupBox *groupBox
                = qstyleoption_cast<const QStyleOptionGroupBox *>(option)) {
            QStyleOptionGroupBox groupBoxCopy(*groupBox);
            groupBoxCopy.subControls &= ~SC_GroupBoxLabel;
            QWindowsStyle::drawComplexControl(control, &groupBoxCopy, painter, widget);

            if (groupBox->subControls & SC_GroupBoxLabel) {
                const QRect &r = groupBox->rect;
                QPixmap titleLeft = cached(":res/images/title_cap_left.png");
                QPixmap titleRight = cached(":res/images/title_cap_right.png");
                QPixmap titleStretch = cached(":res/images/title_stretch.png");
                int txt_width = groupBox->fontMetrics.width(groupBox->text) + 20;
                painter->drawPixmap(r.center().x() - txt_width/2, 0, titleLeft);
                QRect tileRect = subControlRect(control, groupBox, SC_GroupBoxLabel, widget);
                painter->drawTiledPixmap(tileRect, titleStretch);
                painter->drawPixmap(tileRect.x() + tileRect.width(), 0, titleRight);
                int opacity = 31;
                painter->setPen(QColor(0, 0, 0, opacity));
                painter->drawText(tileRect.translated(0, 1),
                                  Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text);
                painter->drawText(tileRect.translated(2, 1),
                                  Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text);
                painter->setPen(QColor(0, 0, 0, opacity * 2));
                painter->drawText(tileRect.translated(1, 1),
                                  Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text);
                painter->setPen(Qt::white);
                painter->drawText(tileRect, Qt::AlignVCenter | Qt::AlignHCenter, groupBox->text);
            }
        }
        break;
    default:
        QWindowsStyle::drawComplexControl(control, option, painter, widget);
        break;
    }
    return;
}
void PlaylistItemDelegate::paintAlbumHeader(
        QPainter* painter, const QStyleOptionViewItem& option, QRect line, Track* track) const {

    QString headerTitle;
    Album *album = track->getAlbum();
    if (album) headerTitle = album->getTitle();
    Artist *artist = track->getArtist();
    if (artist) headerTitle += " - " + artist->getName();

    painter->save();

    // cover background
    /*
    QImage p = album->getPhoto();
    if (!p.isNull()) {
        painter->drawTiledPixmap(line, QPixmap::fromImage(p));
        QLinearGradient linearGrad(0, 0, 0, line.height());
        linearGrad.setColorAt(0, QColor(0,0,0, 96));
        linearGrad.setColorAt(1, QColor(0,0,0, 64));
        painter->fillRect(line, QBrush(linearGrad));
    } else {
        QLinearGradient linearGrad(0, 0, 0, line.height());
        linearGrad.setColorAt(0, option.palette.color(QPalette::Mid));
        linearGrad.setColorAt(1, option.palette.midlight().color());
        painter->fillRect(line, QBrush(linearGrad));
    }*/

    QLinearGradient linearGrad(0, 0, 0, line.height());
#ifdef APP_MAC
    linearGrad.setColorAt(0, QColor(0x99, 0x99, 0x99, 0xFF));
    linearGrad.setColorAt(1, QColor(0xCC, 0xCC, 0xCC, 0xFF));
#else
    linearGrad.setColorAt(0, option.palette.color(QPalette::Mid));
    linearGrad.setColorAt(1, option.palette.color(QPalette::Midlight));
#endif
    painter->fillRect(line, QBrush(linearGrad));

    // borders
    // painter->setPen(option.palette.color(QPalette::Light));
    // painter->drawLine(0, 0, line.width(), 0);
    painter->setPen(option.palette.color(QPalette::Mid));
    painter->drawLine(0, line.height()-1, line.width(), line.height()-1);

    // font
    QFont boldFont = painter->font();
    boldFont.setBold(true);
    painter->setFont(boldFont);

    // text size
    QSize trackStringSize(QFontMetrics(painter->font()).size(Qt::TextSingleLine, headerTitle));
    QPoint textLoc(PADDING*6, 0);
    QRect trackTextBox(textLoc.x(), textLoc.y(), trackStringSize.width(), line.height());

    // text shadow
    painter->setPen(QColor(0, 0, 0, 64));
    painter->drawText(trackTextBox.translated(0, -1), Qt::AlignLeft | Qt::AlignVCenter, headerTitle);

    // text
    painter->setPen(option.palette.color(QPalette::Light));
    painter->drawText(trackTextBox, Qt::AlignLeft | Qt::AlignVCenter, headerTitle);
    
    // album length
    if (album) {
        // TODO this is the album duration, but not necessarily what we have in the playlist
        int totalLength = Track::getTotalLength(album->getTracks());
        QString albumLength;
        if (totalLength > 3600)
            albumLength =  QTime().addSecs(totalLength).toString("h:mm:ss");
        else
            albumLength = QTime().addSecs(totalLength).toString("m:ss");
        QFont normalFont = painter->font();
        normalFont.setBold(false);
        // normalFont.setPointSize(boldFont.pointSize()*.9);
        painter->setFont(normalFont);
        painter->drawText(line.translated(-PADDING, 0), Qt::AlignRight | Qt::AlignVCenter, albumLength);
    }

    // TODO album year

    painter->restore();
}
QPixmap QS60StylePrivate::frame(SkinFrameElements frame, const QSize &size,
                                SkinElementFlags flags)
{
    const QS60StyleEnums::SkinParts center =        m_frameElementsData[frame].center;
    const QS60StyleEnums::SkinParts topLeft =       QS60StyleEnums::SkinParts(center - 8);
    const QS60StyleEnums::SkinParts topRight =      QS60StyleEnums::SkinParts(center - 7);
    const QS60StyleEnums::SkinParts bottomLeft =    QS60StyleEnums::SkinParts(center - 6);
    const QS60StyleEnums::SkinParts bottomRight =   QS60StyleEnums::SkinParts(center - 5);
    const QS60StyleEnums::SkinParts top =           QS60StyleEnums::SkinParts(center - 4);
    const QS60StyleEnums::SkinParts bottom =        QS60StyleEnums::SkinParts(center - 3);
    const QS60StyleEnums::SkinParts left =          QS60StyleEnums::SkinParts(center - 2);
    const QS60StyleEnums::SkinParts right =         QS60StyleEnums::SkinParts(center - 1);

    // The size of topLeft defines all other sizes
    const QSize cornerSize(partSize(topLeft));
    // if frame is so small that corners would cover it completely, draw only center piece
    const bool drawOnlyCenter =
        2 * cornerSize.width() + 1 >= size.width() || 2 * cornerSize.height() + 1 >= size.height();

    const int cornerWidth = cornerSize.width();
    const int cornerHeight = cornerSize.height();
    const int rectWidth = size.width();
    const int rectHeight = size.height();
    const QRect rect(QPoint(), size);

    const QRect topLeftRect = QRect(rect.topLeft(), cornerSize);
    const QRect topRect = rect.adjusted(cornerWidth, 0, -cornerWidth, -(rectHeight - cornerHeight));
    const QRect topRightRect = topLeftRect.translated(rectWidth - cornerWidth, 0);
    const QRect rightRect = rect.adjusted(rectWidth - cornerWidth, cornerHeight, 0, -cornerHeight);
    const QRect bottomRightRect = topRightRect.translated(0, rectHeight - cornerHeight);
    const QRect bottomRect = topRect.translated(0, rectHeight - cornerHeight);
    const QRect bottomLeftRect = topLeftRect.translated(0, rectHeight - cornerHeight);
    const QRect leftRect = rightRect.translated(cornerWidth - rectWidth, 0);
    const QRect centerRect = drawOnlyCenter ? rect : rect.adjusted(cornerWidth, cornerWidth, -cornerWidth, -cornerWidth);

    QPixmap result(size);
    result.fill(Qt::transparent);
    QPainter painter(&result);

#if 0
    painter.save();
    painter.setOpacity(.3);
    painter.fillRect(topLeftRect, Qt::red);
    painter.fillRect(topRect, Qt::green);
    painter.fillRect(topRightRect, Qt::blue);
    painter.fillRect(rightRect, Qt::green);
    painter.fillRect(bottomRightRect, Qt::red);
    painter.fillRect(bottomRect, Qt::blue);
    painter.fillRect(bottomLeftRect, Qt::green);
    painter.fillRect(leftRect, Qt::blue);
    painter.fillRect(centerRect, Qt::red);
    painter.restore();
#else
    drawPart(topLeft, &painter, topLeftRect, flags);
    drawPart(top, &painter, topRect, flags);
    drawPart(topRight, &painter, topRightRect, flags);
    drawPart(right, &painter, rightRect, flags);
    drawPart(bottomRight, &painter, bottomRightRect, flags);
    drawPart(bottom, &painter, bottomRect, flags);
    drawPart(bottomLeft, &painter, bottomLeftRect, flags);
    drawPart(left, &painter, leftRect, flags);
    drawPart(center, &painter, centerRect, flags);
#endif

    return result;
}
Example #27
0
void
GetNewStuffDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    QStyleOptionViewItemV4 opt = option;
    initStyleOption( &opt, index );

    QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget );

    painter->setRenderHint( QPainter::Antialiasing );

    QFont titleFont = opt.font;
    titleFont.setBold( true );
    titleFont.setPointSize( titleFont.pointSize() + 2 );
    QFontMetrics titleMetrics( titleFont );

    QFont authorFont = opt.font;
    authorFont.setItalic( true );
    authorFont.setPointSize( authorFont.pointSize() - 1 );
    QFontMetrics authorMetrics( authorFont );

    QFont descFont = authorFont;
    descFont.setItalic( false );
    QFontMetrics descMetrics( descFont );

    QFont installFont = opt.font;
    installFont.setPointSize( installFont.pointSize() - 1 );
    QFontMetrics installMetrics( descFont );

    const int height = opt.rect.height();
    const int center = height / 2 + opt.rect.top();

    // Pixmap
    QPixmap p = index.data( Qt::DecorationRole ).value< QPixmap >();
    const int pixmapWidth = height - 2*PADDING;
    QRect pixmapRect( PADDING, PADDING + opt.rect.top(), pixmapWidth, pixmapWidth );
    if ( p.isNull() ) // default image... TODO
        p = m_defaultCover;
    else
        p = p.scaled( pixmapRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation );

    painter->drawPixmap( pixmapRect, p );

    // Go from right edge now, stars, install button, and downloaded info

    // install / status button
    AtticaManager::ResolverState state = static_cast< AtticaManager::ResolverState >( index.data( GetNewStuffModel::StateRole ).toInt() );
    QString actionText;
    switch( state )
    {
        case AtticaManager::Uninstalled:
            actionText = tr( "Install" );
            break;
        case AtticaManager::Installing:
            actionText = tr( "Installing" );
            break;
        case AtticaManager::Upgrading:
            actionText = tr( "Upgrading" );
            break;
        case AtticaManager::Failed:
            actionText = tr( "Failed" );
            break;
        case AtticaManager::Installed:
            actionText = tr( "Uninstall" );
            break;
        case AtticaManager::NeedsUpgrade:
            actionText = tr( "Upgrade" );
            break;
    }

    const int btnWidth = m_widestTextWidth + 7;
    const int leftEdge = opt.rect.width() - PADDING - btnWidth - 3;
    const QRect btnRect( leftEdge, center - ( installMetrics.height() + 4 ) / 2, btnWidth, installMetrics.height() + 4 );
    m_cachedButtonRects[ QPair<int, int>(index.row(), index.column()) ] = btnRect;

    QPen saved = painter->pen();
    painter->setPen( opt.palette.color( QPalette::Active, QPalette::AlternateBase ) );

    QPainterPath btnPath;
    const int radius = 3;
    //btnPath.addRoundedRect( btnRect, 3, 3 );
    // draw top half gradient
    const int btnCenter = btnRect.bottom() - ( btnRect.height() / 2 );
    btnPath.moveTo( btnRect.left(), btnCenter );
    btnPath.lineTo( btnRect.left(), btnRect.top() + radius );
    btnPath.quadTo( QPoint( btnRect.topLeft() ), QPoint( btnRect.left() + radius, btnRect.top() ) );
    btnPath.lineTo( btnRect.right() - radius, btnRect.top() );
    btnPath.quadTo( QPoint( btnRect.topRight() ), QPoint( btnRect.right(), btnRect.top() + radius ) );
    btnPath.lineTo( btnRect.right(),btnCenter );
    btnPath.lineTo( btnRect.left(), btnCenter );

    QLinearGradient g;
    g.setColorAt( 0, QColor(54, 127, 211) );
    g.setColorAt( 0.5, QColor(43, 104, 182) );
    //painter->setPen( bg.darker() );
    painter->fillPath( btnPath, g );
    //painter->drawPath( btnPath );

    btnPath = QPainterPath();
    btnPath.moveTo( btnRect.left(), btnCenter );
    btnPath.lineTo( btnRect.left(), btnRect.bottom() - radius );
    btnPath.quadTo( QPoint( btnRect.bottomLeft() ), QPoint( btnRect.left() + radius, btnRect.bottom() ) );
    btnPath.lineTo( btnRect.right() - radius, btnRect.bottom() );
    btnPath.quadTo( QPoint( btnRect.bottomRight() ), QPoint( btnRect.right(), btnRect.bottom() - radius ) );
    btnPath.lineTo( btnRect.right(), btnCenter );
    btnPath.lineTo( btnRect.left(), btnCenter );

    g.setColorAt( 0, QColor(34, 85, 159) );
    g.setColorAt( 0.5, QColor(35, 79, 147) );
    painter->fillPath( btnPath, g );

    painter->setFont( installFont );
    painter->drawText( btnRect, Qt::AlignCenter, actionText );

    painter->setPen( saved );

    // rating stars
    int rating = index.data( GetNewStuffModel::RatingRole ).toInt();
    const int ratingWidth = 5 * ( m_ratingStarPositive.width() + PADDING_BETWEEN_STARS );
    int runningEdge = ( btnRect.right() - btnRect.width() / 2 ) - ratingWidth / 2;
    for ( int i = 1; i < 6; i++ )
    {
        QRect r( runningEdge, btnRect.top() - m_ratingStarPositive.height() - PADDING, m_ratingStarPositive.width(), m_ratingStarPositive.height() );
        if ( i == 1 )
            m_cachedStarRects[ QPair<int, int>(index.row(), index.column()) ] = r;

        const bool userHasRated = index.data( GetNewStuffModel::UserHasRatedRole ).toBool();
        if ( !userHasRated && // Show on-hover animation if the user hasn't rated it yet, and is hovering over it
             m_hoveringOver > -1 &&
             m_hoveringItem == index )
        {
            if ( i <= m_hoveringOver ) // positive star
                painter->drawPixmap( r, m_onHoverStar );
            else
                painter->drawPixmap( r, m_ratingStarNegative );
        }
        else
        {
            if ( i <= rating ) // positive or rated star
            {
                if ( userHasRated )
                    painter->drawPixmap( r, m_onHoverStar );
                else
                    painter->drawPixmap( r, m_ratingStarPositive );
            }
            else
                painter->drawPixmap( r, m_ratingStarNegative );
        }
        runningEdge += m_ratingStarPositive.width() + PADDING_BETWEEN_STARS;
    }

    // downloaded num times, underneath button
    QString count = tr( "%1 downloads" ).arg( index.data( GetNewStuffModel::DownloadCounterRole ).toInt() );
    const QRect countRect( btnRect.left(), btnRect.bottom() + PADDING, btnRect.width(), opt.rect.bottom() - PADDING - btnRect.bottom() );
    QFont countFont = descFont;
    countFont.setPointSize( countFont.pointSize() - 2 );
    countFont.setBold( true );
    painter->setFont( countFont );
    painter->drawText( countRect, Qt::AlignCenter | Qt::TextWordWrap, count );

    // author and version
    QString author = index.data( GetNewStuffModel::AuthorRole ).toString();
    const int authorWidth = authorMetrics.width( author );
    const int topTextLine = opt.rect.top() + PADDING;
    const QRect authorRect( btnRect.x() - 3*PADDING - authorWidth, topTextLine, authorWidth + 6, authorMetrics.height() );
    painter->setFont( authorFont );
    painter->drawText( authorRect, Qt::AlignCenter, author );

    const QRect versionRect = authorRect.translated( 0, authorRect.height() );
    QString version = index.data( GetNewStuffModel::VersionRole ).toString();
    painter->drawText( versionRect, Qt::AlignCenter, version );

    // title
    QString title = index.data( Qt::DisplayRole ).toString();
    const int rightTitleEdge = authorRect.left() - PADDING;
    const int leftTitleEdge = pixmapRect.right() + PADDING;
    const QRect textRect( leftTitleEdge, topTextLine, rightTitleEdge - leftTitleEdge, versionRect.bottom() - opt.rect.top() - PADDING );
    painter->setFont( titleFont );
    painter->drawText( textRect, Qt::AlignVCenter | Qt::AlignLeft, title );

    // description
    QString desc = index.data( GetNewStuffModel::DescriptionRole ).toString();
    const int descWidth = btnRect.left() - leftTitleEdge - PADDING;
    const QRect descRect( leftTitleEdge, versionRect.bottom(), descWidth, opt.rect.bottom() - versionRect.bottom() + PADDING );
    painter->setFont( descFont );
    painter->drawText( descRect, Qt::AlignLeft | Qt::TextWordWrap, desc );
}
void HistoryInvoice::draw(Painter &p, const QRect &r, TextSelection selection, crl::time ms) const {
	if (width() < st::msgPadding.left() + st::msgPadding.right() + 1) return;
	auto paintw = width(), painth = height();

	auto outbg = _parent->hasOutLayout();
	bool selected = (selection == FullSelection);

	auto &barfg = selected ? (outbg ? st::msgOutReplyBarSelColor : st::msgInReplyBarSelColor) : (outbg ? st::msgOutReplyBarColor : st::msgInReplyBarColor);
	auto &semibold = selected ? (outbg ? st::msgOutServiceFgSelected : st::msgInServiceFgSelected) : (outbg ? st::msgOutServiceFg : st::msgInServiceFg);
	auto &regular = selected ? (outbg ? st::msgOutDateFgSelected : st::msgInDateFgSelected) : (outbg ? st::msgOutDateFg : st::msgInDateFg);

	QMargins bubble(_attach ? _attach->bubbleMargins() : QMargins());
	auto padding = inBubblePadding();
	auto tshift = padding.top();
	auto bshift = padding.bottom();
	paintw -= padding.left() + padding.right();
	if (isBubbleBottom() && _attach && _attach->customInfoLayout() && _attach->width() + _parent->skipBlockWidth() > paintw + bubble.left() + bubble.right()) {
		bshift += bottomInfoPadding();
	}

	auto lineHeight = unitedLineHeight();
	if (_titleHeight) {
		p.setPen(semibold);
		p.setTextPalette(selected ? (outbg ? st::outTextPaletteSelected : st::inTextPaletteSelected) : (outbg ? st::outSemiboldPalette : st::inSemiboldPalette));

		auto endskip = 0;
		if (_title.hasSkipBlock()) {
			endskip = _parent->skipBlockWidth();
		}
		_title.drawLeftElided(p, padding.left(), tshift, paintw, width(), _titleHeight / lineHeight, style::al_left, 0, -1, endskip, false, selection);
		tshift += _titleHeight;

		p.setTextPalette(selected ? (outbg ? st::outTextPaletteSelected : st::inTextPaletteSelected) : (outbg ? st::outTextPalette : st::inTextPalette));
	}
	if (_descriptionHeight) {
		p.setPen(outbg ? st::webPageDescriptionOutFg : st::webPageDescriptionInFg);
		_description.drawLeft(p, padding.left(), tshift, paintw, width(), style::al_left, 0, -1, toDescriptionSelection(selection));
		tshift += _descriptionHeight;
	}
	if (_attach) {
		auto attachAtTop = !_titleHeight && !_descriptionHeight;
		if (!attachAtTop) tshift += st::mediaInBubbleSkip;

		auto attachLeft = padding.left() - bubble.left();
		auto attachTop = tshift - bubble.top();
		if (rtl()) attachLeft = width() - attachLeft - _attach->width();

		auto attachSelection = selected ? FullSelection : TextSelection { 0, 0 };

		p.translate(attachLeft, attachTop);
		_attach->draw(p, r.translated(-attachLeft, -attachTop), attachSelection, ms);
		auto pixwidth = _attach->width();
		auto pixheight = _attach->height();

		auto available = _status.maxWidth();
		auto statusW = available + 2 * st::msgDateImgPadding.x();
		auto statusH = st::msgDateFont->height + 2 * st::msgDateImgPadding.y();
		auto statusX = st::msgDateImgDelta;
		auto statusY = st::msgDateImgDelta;

		App::roundRect(p, rtlrect(statusX, statusY, statusW, statusH, pixwidth), selected ? st::msgDateImgBgSelected : st::msgDateImgBg, selected ? DateSelectedCorners : DateCorners);

		p.setFont(st::msgDateFont);
		p.setPen(st::msgDateImgFg);
		_status.drawLeftElided(p, statusX + st::msgDateImgPadding.x(), statusY + st::msgDateImgPadding.y(), available, pixwidth);

		p.translate(-attachLeft, -attachTop);
	} else {
		p.setPen(outbg ? st::webPageDescriptionOutFg : st::webPageDescriptionInFg);
		_status.drawLeft(p, padding.left(), tshift + st::mediaInBubbleSkip, paintw, width());
	}
}
Example #29
0
void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *option,
                                 QPainter *painter, const QWidget *widget) const {
    if (!panelWidget(widget))
        return d->style->drawControl(element, option, painter, widget);

    switch (element) {
    case CE_MenuBarItem:
        painter->save();
        if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
            QColor highlightOutline = StyleHelper::borderColor().lighter(120);
            bool act = mbi->state & State_Selected && mbi->state & State_Sunken;
            bool dis = !(mbi->state & State_Enabled);
            StyleHelper::menuGradient(painter, option->rect, option->rect);
            QStyleOptionMenuItem item = *mbi;
            item.rect = mbi->rect;
            QPalette pal = mbi->palette;
            pal.setBrush(QPalette::ButtonText, dis ? Qt::gray : Qt::black);
            item.palette = pal;
            QCommonStyle::drawControl(element, &item, painter, widget);
            QRect r = option->rect;

            if (act) {
                // Fill|
                QColor baseColor = StyleHelper::baseColor();
                QLinearGradient grad(option->rect.topLeft(), option->rect.bottomLeft());
                grad.setColorAt(0, baseColor.lighter(120));
                grad.setColorAt(1, baseColor.lighter(130));
                painter->fillRect(option->rect.adjusted(1, 1, -1, 0), grad);

                // Outline
                painter->setPen(QPen(highlightOutline, 0));
                painter->drawLine(QPoint(r.left(), r.top() + 1), QPoint(r.left(), r.bottom()));
                painter->drawLine(QPoint(r.right(), r.top() + 1), QPoint(r.right(), r.bottom()));
                painter->drawLine(QPoint(r.left() + 1, r.top()), QPoint(r.right() - 1, r.top()));
                highlightOutline.setAlpha(60);
                painter->setPen(QPen(highlightOutline, 0));
                painter->drawPoint(r.topLeft());
                painter->drawPoint(r.topRight());

                QPalette pal = mbi->palette;
                uint alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
                if (!styleHint(SH_UnderlineShortcut, mbi, widget))
                    alignment |= Qt::TextHideMnemonic;
                pal.setBrush(QPalette::Text, dis ? Qt::gray : QColor(0, 0, 0, 60));
                drawItemText(painter, item.rect.translated(0, 1), alignment, pal, mbi->state & State_Enabled, mbi->text, QPalette::Text);
                pal.setBrush(QPalette::Text, dis ? Qt::gray : Qt::white);
                drawItemText(painter, item.rect, alignment, pal, mbi->state & State_Enabled, mbi->text, QPalette::Text);
            }
        }
        painter->restore();
        break;

    case CE_ComboBoxLabel:
        if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(option)) {
            if (panelWidget(widget)) {
                QRect editRect = subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget);
                QPalette customPal = cb->palette;

                if (!cb->currentIcon.isNull()) {
                    QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal
                                       : QIcon::Disabled;
                    QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, mode);
                    QRect iconRect(editRect);
                    iconRect.setWidth(cb->iconSize.width() + 4);
                    iconRect = alignedRect(cb->direction,
                                           Qt::AlignLeft | Qt::AlignVCenter,
                                           iconRect.size(), editRect);
                    if (cb->editable)
                        painter->fillRect(iconRect, customPal.brush(QPalette::Base));
                    drawItemPixmap(painter, iconRect, Qt::AlignCenter, pixmap);

                    if (cb->direction == Qt::RightToLeft)
                        editRect.translate(-4 - cb->iconSize.width(), 0);
                    else
                        editRect.translate(cb->iconSize.width() + 4, 0);

                    // Reserve some space for the down-arrow
                    editRect.adjust(0, 0, -13, 0);
                }

                customPal.setBrush(QPalette::All, QPalette::ButtonText, QColor(0, 0, 0, 70));

                QString text = option->fontMetrics.elidedText(cb->currentText, Qt::ElideRight, editRect.width());
                drawItemText(painter, editRect.translated(0, 1),
                             visualAlignment(option->direction, Qt::AlignLeft | Qt::AlignVCenter),
                             customPal, cb->state & State_Enabled, text, QPalette::ButtonText);
                customPal.setBrush(QPalette::All, QPalette::ButtonText, StyleHelper::panelTextColor());
                drawItemText(painter, editRect,
                             visualAlignment(option->direction, Qt::AlignLeft | Qt::AlignVCenter),
                             customPal, cb->state & State_Enabled, text, QPalette::ButtonText);
            } else {
                d->style->drawControl(element, option, painter, widget);
            }
        }
        break;

    case CE_SizeGrip: {
        painter->save();
        QColor dark = Qt::white;
        dark.setAlphaF(0.1);
        int x, y, w, h;
        option->rect.getRect(&x, &y, &w, &h);
        int sw = qMin(h, w);
        if (h > w)
            painter->translate(0, h - w);
        else
            painter->translate(w - h, 0);
        int sx = x;
        int sy = y;
        int s = 4;
        painter->setPen(dark);
        if (option->direction == Qt::RightToLeft) {
            sx = x + sw;
            for (int i = 0; i < 4; ++i) {
                painter->drawLine(x, sy, sx, sw);
                sx -= s;
                sy += s;
            }
        } else {
            for (int i = 0; i < 4; ++i) {
                painter->drawLine(sx, sw, sw, sy);
                sx += s;
                sy += s;
            }
        }
        painter->restore();
    }
    break;

    case CE_MenuBarEmptyArea: {
        StyleHelper::menuGradient(painter, option->rect, option->rect);
        painter->save();
        painter->setPen(StyleHelper::borderColor());
        painter->drawLine(option->rect.bottomLeft(), option->rect.bottomRight());
        painter->restore();
    }
    break;

    case CE_ToolBar: {
        QString key;
        key.sprintf("mh_toolbar %d %d %d", option->rect.width(), option->rect.height(), StyleHelper::baseColor().rgb());;

        QPixmap pixmap;
        QPainter *p = painter;
        QRect rect = option->rect;
        if (StyleHelper::usePixmapCache() && !QPixmapCache::find(key, pixmap)) {
            pixmap = QPixmap(option->rect.size());
            p = new QPainter(&pixmap);
            rect = QRect(0, 0, option->rect.width(), option->rect.height());
        }

        bool horizontal = option->state & State_Horizontal;
        // Map offset for global window gradient
        QPoint offset = widget->window()->mapToGlobal(option->rect.topLeft()) -
                        widget->mapToGlobal(option->rect.topLeft());
        QRect gradientSpan;
        if (widget) {
            gradientSpan = QRect(offset, widget->window()->size());
        }
        if (horizontal)
            StyleHelper::horizontalGradient(p, gradientSpan, rect);
        else
            StyleHelper::verticalGradient(p, gradientSpan, rect);

        painter->setPen(StyleHelper::borderColor());

        if (horizontal) {
            // Note: This is a hack to determine if the
            // toolbar should draw the top or bottom outline
            // (needed for the find toolbar for instance)
            QColor lighter(255, 255, 255, 40);
            if (widget && widget->property("topBorder").toBool()) {
                p->drawLine(rect.topLeft(), rect.topRight());
                p->setPen(lighter);
                p->drawLine(rect.topLeft() + QPoint(0, 1), rect.topRight() + QPoint(0, 1));
            } else {
                p->drawLine(rect.bottomLeft(), rect.bottomRight());
                p->setPen(lighter);
                p->drawLine(rect.topLeft(), rect.topRight());
            }
        } else {
            p->drawLine(rect.topLeft(), rect.bottomLeft());
            p->drawLine(rect.topRight(), rect.bottomRight());
        }

        if (StyleHelper::usePixmapCache() && !QPixmapCache::find(key, pixmap)) {
            painter->drawPixmap(rect.topLeft(), pixmap);
            p->end();
            delete p;
            QPixmapCache::insert(key, pixmap);
        }
    }
    break;

    default:
        d->style->drawControl(element, option, painter, widget);
        break;
    }
}
Example #30
0
void StyledButton::paintEvent(QPaintEvent *ev)
{
	QPainter p(this);

	// Initialize button style options
	QStyleOptionButton opt;
	initStyleOption(&opt);

	// Determine colour set to paint with
	QColor topCol(*(m_colorSet.topColor));
	QColor bottomCol(*(m_colorSet.bottomColor));
	QColor highlightCol(*(m_colorSet.highlightColor));
	QColor shadowCol(*(m_colorSet.shadowColor));
	StyleHelper::ColorSet set(&topCol, &bottomCol, &highlightCol, &shadowCol);
	if(m_hovered) {
		topCol = topCol.darker(BUTTON_HOVER_DARKEN_AMOUNT);
		bottomCol = bottomCol.darker(BUTTON_HOVER_DARKEN_AMOUNT);
		highlightCol = highlightCol.darker(BUTTON_HOVER_DARKEN_AMOUNT);
		shadowCol = shadowCol.darker(BUTTON_HOVER_DARKEN_AMOUNT);
	}
	opt.palette.setColor(QPalette::ButtonText, m_textColor);

	// Draw background
	StyleHelper::drawBackground(
		&p, QRect(0, 0, width(), height()), set,
		opt.state & QStyle::State_Sunken, 0.0f, m_joinLeft, m_joinRight);

	//-------------------------------------------------------------------------
	// This section duplicated in `DarkStyle` (CE_PushButtonLabel)
	// The only difference is that we hard-code the pressed button offset

	// Get contents rectangle
	QMargins margins = contentsMargins();
	QStyleOptionButton subopt = opt;
	subopt.rect = opt.rect.adjusted(
		margins.left(), margins.top(),
		-margins.right(), -margins.bottom());

	QRect textRect = subopt.rect;
	uint tf = Qt::AlignVCenter | Qt::TextShowMnemonic;
	if(!style()->styleHint(QStyle::SH_UnderlineShortcut, &subopt, this))
		tf |= Qt::TextHideMnemonic;

	// Draw the icon if one exists. We need to modify the text rectangle as
	// well as we want both the icon and the text centered on the button
	QRect iconRect;
	if(!subopt.icon.isNull()) {
		// Determine icon state
		QIcon::Mode mode = (subopt.state & QStyle::State_Enabled) ?
			QIcon::Normal : QIcon::Disabled;
		if(mode == QIcon::Normal && subopt.state & QStyle::State_HasFocus)
			mode = QIcon::Active;
		QIcon::State state = QIcon::Off;
		if(subopt.state & QStyle::State_On)
			state = QIcon::On;

		// Determine metrics
		QPixmap pixmap = subopt.icon.pixmap(subopt.iconSize, mode, state);
		int labelWidth = pixmap.width();
		int labelHeight = pixmap.height();
		int iconSpacing = 4; // See `sizeHint()`
		int textWidth = subopt.fontMetrics.boundingRect(
			subopt.rect, tf, subopt.text).width();
		if(!subopt.text.isEmpty())
			labelWidth += textWidth + iconSpacing;

		// Determine icon rectangle
		iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
			textRect.y() + (textRect.height() - labelHeight) / 2,
			pixmap.width(), pixmap.height());
		iconRect = QStyle::visualRect(subopt.direction, textRect, iconRect);

		// Change where the text will be displayed
		tf |= Qt::AlignLeft; // Left align, we adjust the text rect instead
		if(subopt.direction == Qt::RightToLeft)
			textRect.setRight(iconRect.left() - iconSpacing);
		else
			textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);

		// Translate the contents slightly when the button is pressed
		if(subopt.state & QStyle::State_Sunken)
			iconRect.translate(1, 1);

		// Draw pixmap
		p.drawPixmap(iconRect, pixmap);
	} else
		tf |= Qt::AlignHCenter;

	// HACK: Move the text up 1px so that it is vertically centered
	textRect.translate(0, -1);

	// Translate the contents slightly when the button is pressed
	if(subopt.state & QStyle::State_Sunken)
		textRect.translate(1, 1);

	// Draw text shadow only if the button is enabled
	if(subopt.state & QStyle::State_Enabled) {
		QPalette pal(subopt.palette);
		pal.setColor(QPalette::ButtonText, m_textShadowColor);
		style()->drawItemText(
			&p, textRect.translated(2, 1).adjusted(-1, -1, 1, 1), tf, pal,
			true, subopt.text, QPalette::ButtonText);
	}

	// Draw text. HACK: We offset the text by one pixel to the right as the
	// font metrics include the character spacing to the right of the last
	// character making the text appear slightly to the left. We also increase
	// the rectangle by 1px in every direction in order for the text to not get
	// clipped with some fonts.
	style()->drawItemText(
		&p, textRect.translated(1, 0).adjusted(-1, -1, 1, 1), tf,
		subopt.palette, (subopt.state & QStyle::State_Enabled), subopt.text,
		QPalette::ButtonText);

	//-------------------------------------------------------------------------
	// This section is based off QCommonStyle (CE_PushButton)
	// We change the way the focus rectangle is calculated as the original
	// algorithm has some bugs

	// Draw focus rectangle
	if(hasFocus()) {
		int pad =
			style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &opt, this) + 1;

		QStyleOptionFocusRect fropt;
		fropt.initFrom(this);
		fropt.QStyleOption::operator=(opt);

		// Determine bounding rectangle
		if(!subopt.icon.isNull()) {
			QRegion region(subopt.fontMetrics.boundingRect(
				textRect, tf, subopt.text));
			region += iconRect;
			fropt.rect = region.boundingRect();
			fropt.rect = fropt.rect.adjusted(-pad, -pad, pad, pad);
		} else if(!subopt.text.isEmpty()) {
			fropt.rect = subopt.fontMetrics.boundingRect(
				textRect, tf, subopt.text);
			fropt.rect = fropt.rect.adjusted(-pad, -pad, pad, pad);
		} else {
			fropt.rect = subopt.rect;

			// Translate the contents slightly when the button is pressed
			if(subopt.state & QStyle::State_Sunken)
				fropt.rect.translate(1, 1);
		}

		style()->drawPrimitive(QStyle::PE_FrameFocusRect, &fropt, &p, this);
		//p.drawRect(fropt.rect);
	}

	//-------------------------------------------------------------------------
}