Example #1
0
    void flushImage(const QPoint &pos, const QImage &image, const QRect &destinationRect)
    {
        checkPauseApplication();
        QMutexLocker locker(&m_surfaceMutex);
        if (!m_surface)
            return;
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

        int bpp = 2;
        AndroidBitmapInfo info;
        int ret;

        if ((ret = AndroidBitmap_getInfo(env.jniEnv, m_surface, &info)) < 0) {
            qWarning() << "AndroidBitmap_getInfo() failed ! error=" << ret;
            m_javaVM->DetachCurrentThread();
            return;
        }

        if (info.format != ANDROID_BITMAP_FORMAT_RGB_565) {
            qWarning() << "Bitmap format is not RGB_565!";
            m_javaVM->DetachCurrentThread();
            return;
        }

        void *pixels;
        unsigned char *screenBits;
        if ((ret = AndroidBitmap_lockPixels(env.jniEnv, m_surface, &pixels)) < 0) {
            qWarning() << "AndroidBitmap_lockPixels() failed! error=" << ret;
            m_javaVM->DetachCurrentThread();
            return;
        }

        screenBits = static_cast<unsigned char *>(pixels);
        int sbpl = info.stride;
        int swidth = info.width;
        int sheight = info.height;

        unsigned sposx = pos.x() + destinationRect.x();
        unsigned sposy = pos.y() + destinationRect.y();

        screenBits += sposy * sbpl;

        unsigned ibpl = image.bytesPerLine();
        unsigned iposx = destinationRect.x();
        unsigned iposy = destinationRect.y();

        const unsigned char *imageBits = static_cast<const unsigned char *>(image.bits());
        imageBits += iposy * ibpl;

        unsigned width = swidth - sposx < unsigned(destinationRect.width())
                         ? (swidth-sposx)
                         : destinationRect.width();
        unsigned height = sheight - sposy < unsigned(destinationRect.height())
                          ? (sheight - sposy)
                          : destinationRect.height();

        for (unsigned y = 0; y < height; y++) {
            memcpy(screenBits + y*sbpl + sposx*bpp,
                   imageBits + y*ibpl + iposx*bpp,
                   width*bpp);
        }
        AndroidBitmap_unlockPixels(env.jniEnv, m_surface);

        env.jniEnv->CallStaticVoidMethod(m_applicationClass,
                                         m_redrawSurfaceMethodID,
                                         jint(destinationRect.left()),
                                         jint(destinationRect.top()),
                                         jint(destinationRect.right() + 1),
                                         jint(destinationRect.bottom() + 1));
#warning FIXME dirty hack, figure out why it needs to add 1 to right and bottom !!!!
    }
QRect EventEditorDelegate::paint( QPainter* painter,
                                  const QStyleOptionViewItem& option,
                                  const QString& taskName,
                                  const QString& timespan,
                                  double logDuration,
                                  EventState state ) const
{
    painter->save();
    const QPalette& palette = option.palette;
    QFont mainFont = painter->font();
    QFont detailFont ( mainFont );
    detailFont.setPointSizeF( mainFont.pointSizeF() * 0.8 );
    QPixmap decoration;
    QColor foreground;
    QColor background;

    switch( state ) {
    case EventState_Locked:
        decoration = Data::editorLockedPixmap();
        foreground = palette.color( QPalette::Disabled, QPalette::WindowText );
        background = palette.color( QPalette::Disabled, QPalette::Window );
        break;
    case EventState_Dirty:
        decoration = Data::editorDirtyPixmap();
        foreground = palette.color( QPalette::Active, QPalette::WindowText );
        background = palette.color( QPalette::Active, QPalette::Window );
        break;
    case EventState_Default:
    default:
        foreground = palette.color( QPalette::Active, QPalette::WindowText );
        background = palette.color( QPalette::Active, QPalette::Window );
        break;
    };

    if ( option.state & QStyle::State_Selected ) {
        QBrush brush( palette.color( QPalette::Active, QPalette::Highlight ) );
        painter->setBrush( brush );
        painter->setPen( Qt::NoPen );
        painter->drawRect( option.rect );
        if ( state != EventState_Locked ) {
            foreground = palette.color(
                QPalette::Active, QPalette::HighlightedText );
        }
    }

    painter->setPen( foreground );

    // draw line 1 and decoration:
    painter->setFont( mainFont );
    QRect taskRect;
    taskRect.setTopLeft( option.rect.topLeft() );
    taskRect.setWidth( option.rect.width() - decoration.width() );
    taskRect.setHeight( option.rect.height() );
    QPoint decorationPoint ( option.rect.width() - decoration.width(),
                             option.rect.top() + ( option.rect.height() - decoration.height() ) / 2 );

    QRect boundingRect;
    QString elidedTask = Charm::elidedTaskName( taskName, mainFont, taskRect.width() );
    painter->drawText( taskRect, Qt::AlignLeft | Qt::AlignTop, elidedTask,
                       &boundingRect );
    taskRect.setSize( boundingRect.size() );
    taskRect.setHeight( qMax( taskRect.height(), decoration.height() ) );
    // now taskRect tells us where to start line 2
    painter->drawPixmap( decorationPoint, decoration );

    // draw line 2 (timespan and comment, partly):
    painter->setFont( detailFont );
    QRect detailsRect;
    detailsRect.setTopLeft( QPoint( taskRect.topLeft().x(),
                                    taskRect.topLeft().y() + taskRect.height() ) );
    detailsRect.setWidth( option.rect.width() );
    detailsRect.setHeight( option.rect.height() - taskRect.height() );
    painter->drawText( detailsRect, Qt::AlignLeft | Qt::AlignTop,
                       timespan, &boundingRect );
    detailsRect.setSize( boundingRect.size() );

    // draw the duration line:
    const int Margin = 2;
    QRect durationRect( option.rect.left() + 1, detailsRect.bottom(),
                static_cast<int>( logDuration * ( option.rect.width() - 2 ) ), Margin  );
    painter->setBrush( palette.dark() );
    painter->setPen( Qt::NoPen );
    painter->drawRect( durationRect );

    painter->restore();
    // return bounding rectangle
    return QRect( 0, 0,
                  qMax( taskRect.width(), detailsRect.width() ),
                  durationRect.bottom() + 1 - option.rect.top() );

}
Example #3
0
//! [region start]
QRegion MyDecoration::region(const QWidget *widget, const QRect &insideRect,
                             int decorationRegion)
{
    //! [region start]
    //! [calculate the positions of buttons based on the window flags used]
    QHash<DecorationRegion, int> buttons;
    Qt::WindowFlags flags = widget->windowFlags();
    int dx = -buttonMargin - buttonWidth;

    foreach (Qt::WindowType button, buttonHints) {
        if (flags & button) {
            int x = (buttons.size() + 1) * dx;
            buttons[buttonHintMap[button]] = x;
        }
    }
    //! [calculate the positions of buttons based on the window flags used]

    //! [calculate the extent of the title]
    int titleRightMargin = buttons.size() * dx;

    QRect outsideRect(insideRect.left() - border,
                      insideRect.top() - titleHeight - border,
                      insideRect.width() + 2 * border,
                      insideRect.height() + titleHeight + 2 * border);
    //! [calculate the extent of the title]

    //! [check for all regions]
    QRegion region;

    if (decorationRegion == All) {
        region += QRegion(outsideRect) - QRegion(insideRect);
        return region;
    }
    //! [check for all regions]

    //! [compose a region based on the decorations specified]
    if (decorationRegion & Title) {
        QRect rect = outsideRect.adjusted(border, border, -border, 0);
        rect.setHeight(titleHeight);

        // Adjust the width to accommodate buttons.
        rect.setWidth(qMax(0, rect.width() + titleRightMargin));
        region += rect;
    }
    if (decorationRegion & Top) {
        QRect rect = outsideRect.adjusted(border, 0, -border, 0);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & Left) {
        QRect rect = outsideRect.adjusted(0, border, 0, -border);
        rect.setWidth(border);
        region += rect;
    }
    if (decorationRegion & Right) {
        QRect rect = outsideRect.adjusted(0, border, 0, -border);
        rect.setLeft(rect.right() + 1 - border);
        region += rect;
    }
    if (decorationRegion & Bottom) {
        QRect rect = outsideRect.adjusted(border, 0, -border, 0);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    if (decorationRegion & TopLeft) {
        QRect rect = outsideRect;
        rect.setWidth(border);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & TopRight) {
        QRect rect = outsideRect;
        rect.setLeft(rect.right() + 1 - border);
        rect.setHeight(border);
        region += rect;
    }
    if (decorationRegion & BottomLeft) {
        QRect rect = outsideRect;
        rect.setWidth(border);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    if (decorationRegion & BottomRight) {
        QRect rect = outsideRect;
        rect.setLeft(rect.right() + 1 - border);
        rect.setTop(rect.bottom() + 1 - border);
        region += rect;
    }
    //! [compose a region based on the decorations specified]

    //! [add a region for each button only if it is present]
    foreach (QDecoration::DecorationRegion testRegion, stateRegions) {
        if (decorationRegion & testRegion and buttons.contains(testRegion)) {
            // Inside the title rectangle
            QRect rect = outsideRect.adjusted(border, border, -border, 0);
            rect.setHeight(titleHeight);

            dx = buttons[testRegion];
            rect.setLeft(rect.right() + 1 + dx);
            rect.setWidth(buttonWidth + buttonMargin);
            region += rect;
        }
    }
    //! [add a region for each button only if it is present]

    //! [region end]
    return region;
}
void KdeConnectDevicesDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    painter->setFont(option.font);

    QRect iconRect;
    if (((QListView*) option.widget)->viewMode() == QListView::IconMode) {
        iconRect.setLeft(option.rect.left() + 38 * getDPIScaling());
        iconRect.setTop(option.rect.top() + 6 * getDPIScaling());
        iconRect.setHeight(32 * getDPIScaling());
        iconRect.setWidth(32 * getDPIScaling());

        QRect textRect;
        textRect.setLeft(option.rect.left() + 6 * getDPIScaling());
        textRect.setTop(iconRect.bottom() + 6 * getDPIScaling());
        textRect.setBottom(option.rect.bottom());
        textRect.setRight(option.rect.right());

        if (option.state & QStyle::State_Selected) {
            painter->setPen(Qt::transparent);
            painter->setBrush(option.palette.color(QPalette::Highlight));
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::HighlightedText));
            painter->drawText(textRect, index.data().toString());
        } else if (option.state & QStyle::State_MouseOver) {
            QColor col = option.palette.color(QPalette::Highlight);
            col.setAlpha(127);
            painter->setBrush(col);
            painter->setPen(Qt::transparent);
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
        } else {
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
        }
    } else {
        iconRect.setLeft(option.rect.left() + 12 * getDPIScaling());
        iconRect.setTop(option.rect.top() + 6 * getDPIScaling());
        iconRect.setBottom(iconRect.top() + 32 * getDPIScaling());
        iconRect.setRight(iconRect.left() + 32 * getDPIScaling());

        QRect textRect;
        textRect.setLeft(iconRect.right() + 6 * getDPIScaling());
        textRect.setTop(option.rect.top() + 6 * getDPIScaling());
        textRect.setBottom(option.rect.top() + option.fontMetrics.height() + 6 * getDPIScaling());
        textRect.setRight(option.rect.right());

        QRect descRect;
        descRect.setLeft(iconRect.right() + 6 * getDPIScaling());
        descRect.setTop(option.rect.top() + option.fontMetrics.height() + 8 * getDPIScaling());
        descRect.setBottom(option.rect.top() + option.fontMetrics.height() * 2 + 6 * getDPIScaling());
        descRect.setRight(option.rect.right());

        if (option.state & QStyle::State_Selected) {
            painter->setPen(Qt::transparent);
            painter->setBrush(option.palette.color(QPalette::Highlight));
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::HighlightedText));
            painter->drawText(textRect, index.data().toString());
            painter->drawText(descRect, index.data(Qt::UserRole).toString());
        } else if (option.state & QStyle::State_MouseOver) {
            QColor col = option.palette.color(QPalette::Highlight);
            col.setAlpha(127);
            painter->setBrush(col);
            painter->setPen(Qt::transparent);
            painter->drawRect(option.rect);
            painter->setBrush(Qt::transparent);
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
            painter->setPen(option.palette.color(QPalette::Disabled, QPalette::WindowText));
            painter->drawText(descRect, index.data(Qt::UserRole).toString());
        } else {
            painter->setPen(option.palette.color(QPalette::WindowText));
            painter->drawText(textRect, index.data().toString());
            painter->setPen(option.palette.color(QPalette::Disabled, QPalette::WindowText));
            painter->drawText(descRect, index.data(Qt::UserRole).toString());
        }
    }
    painter->drawPixmap(iconRect, index.data(Qt::DecorationRole).value<QIcon>().pixmap(iconRect.size()));

    QDBusInterface device("org.kde.kdeconnect", "/modules/kdeconnect/devices/" + index.data(Qt::UserRole + 1).toString(), "org.kde.kdeconnect.device");
    bool reachable = device.property("isReachable").toBool();
    bool trusted = device.property("isTrusted").toBool();

    if (reachable && trusted) {
        painter->setBrush(QColor(0, 100, 0));
        painter->setPen(Qt::transparent);
        painter->drawRect(option.rect.left(), option.rect.top(), 6 * getDPIScaling(), option.rect.height());
    }
}
void SubtotalDialog::accept()
{
    Sheet *const sheet = d->selection->lastSheet();
    QRect range = d->selection->lastRange();

    int numOfCols = range.width();
    QVector<int> columns(numOfCols);

    bool empty = true;
    int left = range.left();
    for (int i = 0; i < d->mainWidget.m_columnList->count(); ++i) {
        QListWidgetItem* item = d->mainWidget.m_columnList->item(i);
        if (item->checkState() == Qt::Checked) {
            columns[i] = left + i;
            empty = false;
        } else
            columns[i] = -1;
    }

    if (empty) {
        KMessageBox::sorry(this, i18n("You need to select at least one column for adding subtotals."));
        return;
    }

    if (d->detailsWidget.m_replaceSubtotals->isChecked())
        removeSubtotalLines();

    range = d->selection->lastRange();

    int mainCol = left + d->mainWidget.m_columnBox->currentIndex();
    int bottom = range.bottom();
    int top    = range.top();
    int newBottom = bottom;
    left       = range.left();
    QString oldText = Cell(sheet, mainCol, top).displayText();
    QString newText;
    QString result(' ' + i18n("Result"));
    int lastChangedRow = top;

    bool ignoreEmptyCells = d->detailsWidget.m_IgnoreBox->isChecked();
    bool addRow;
    if (!d->detailsWidget.m_summaryOnly->isChecked()) {
        int y = top + 1;
        kDebug() << "Starting in row" << y;
        while (y <= bottom) {
            addRow = true;
            newText = Cell(sheet, mainCol, y).displayText();

            if (ignoreEmptyCells && (newText.length() == 0)) {
                ++y;
                kDebug() << "Still the same ->" << y;
                continue;
            }

            if (newText != oldText) {
                int saveY = y;
                for (int x = 0; x < numOfCols; ++x) {
                    kDebug() << "Column:" << x << "," << columns[x];
                    if (columns[x] != -1) {
                        if (!addSubtotal(mainCol, columns[x], y - 1, lastChangedRow, addRow, oldText + result))
                            reject();

                        if (addRow) {
                            ++saveY;
                            ++bottom;
                        }

                        addRow = false;
                    }
                }
                y = saveY;
                lastChangedRow = y;
            }
            oldText = newText;
            ++y;
        }

        addRow = true;
        for (int x = 0; x < numOfCols; ++x) {
            if (columns[x] != -1) {
                if (!addSubtotal(mainCol, columns[x], y - 1, lastChangedRow, addRow, oldText + result))
                    reject();
                addRow = false;
            }
        }
        newBottom = y;
    }

    if (d->detailsWidget.m_summaryBelow->isChecked()) {
        addRow = true;
        int bottom = newBottom;
        for (int x = 0; x < numOfCols; ++x) {
            if (columns[x] != -1) {
                addSubtotal(mainCol, columns[x], bottom, top, addRow, i18n("Grand Total"));
                addRow = false;
            }
        }
    }

    KDialog::accept();
}
Example #6
0
void K3b::FillStatusDisplayWidget::paintEvent( QPaintEvent* )
{
    QPainter p( this );

    const QPalette::ColorGroup colorGroup = isEnabled() ? QPalette::Normal : QPalette::Disabled;

    const Msf docSize = d->doc->length();
    const Msf cdSize = d->cdSize;
    const Msf maxValue = (cdSize > docSize ? cdSize : docSize) + ( 10*60*75 );
    const Msf tolerance = 60*75;

    QBrush fillBrush;
    if( docSize <= cdSize - tolerance ) {
        fillBrush = KColorScheme( colorGroup, KColorScheme::Selection ).background( KColorScheme::PositiveBackground );
    }
    else if( docSize > cdSize + tolerance ) {
        fillBrush = KColorScheme( colorGroup, KColorScheme::Selection ).background( KColorScheme::NegativeBackground );
    }
    else {
        fillBrush = KColorScheme( colorGroup, KColorScheme::Selection ).background( KColorScheme::NeutralBackground );
    }

    const QPen normalPen = KColorScheme( colorGroup, KColorScheme::Window ).foreground( KColorScheme::NormalText ).color();
    const QPen fillPen = KColorScheme( colorGroup, KColorScheme::Selection ).foreground( KColorScheme::NormalText ).color();

    QStyleOptionProgressBarV2 sopb;
    sopb.direction = layoutDirection();
    sopb.fontMetrics = fontMetrics();
    sopb.palette = palette();
    sopb.palette.setBrush( QPalette::Highlight, fillBrush );
    sopb.rect = rect();
    sopb.state = isEnabled() ? QStyle::State_Enabled : QStyle::State_None;
    sopb.minimum = 0;
    sopb.maximum = maxValue.totalFrames();
    sopb.progress = docSize.totalFrames();
    style()->drawControl( QStyle::CE_ProgressBar, &sopb, &p );

    const QRect barRect = style()->subElementRect( QStyle::SE_ProgressBarContents, &sopb );

    // so split width() in maxValue pieces
    double one = (double)barRect.width() / (double)maxValue.totalFrames();

    QRect crect( barRect );
    crect.setWidth( (int)(one*(double)docSize.totalFrames()) );

    // ====================================================================================
    // Now the colored bar is painted
    // Continue with the texts
    // ====================================================================================

    // first we determine the text to display
    // ====================================================================================
    QString docSizeText;
    if( d->showTime )
        docSizeText = i18n("%1 min", d->doc->length().toString(false));
    else
        docSizeText = KIO::convertSize( d->doc->size() );

    QString overSizeText;
    if( d->cdSize.mode1Bytes() >= d->doc->size() )
        overSizeText = i18n("Available: %1 of %2",
                            d->showTime
                            ? i18n("%1 min", (cdSize - d->doc->length()).toString(false) )
                            : KIO::convertSize( (cdSize - d->doc->length()).mode1Bytes() ),
                            d->showTime
                            ? i18n("%1 min", cdSize.toString(false))
                            : KIO::convertSize( cdSize.mode1Bytes() ) );
    else
        overSizeText = i18n("Capacity exceeded by %1",
                            d->showTime
                            ? i18n("%1 min", (d->doc->length() - cdSize ).toString(false))
                            : KIO::convertSize( (long long)d->doc->size() - cdSize.mode1Bytes() ) );
    // ====================================================================================

    // calculate the medium size marker
    // ====================================================================================
    int mediumSizeMarkerPos = barRect.left() + (int)(one*cdSize.lba());
    QPoint mediumSizeMarkerFrom( mediumSizeMarkerPos, barRect.bottom() );
    QPoint mediumSizeMarkerTo( mediumSizeMarkerPos, barRect.top() + barRect.height()/2 );
    // ====================================================================================

    // we want to draw the docSizeText centered in the filled area
    // if there is not enough space we just align it left
    // ====================================================================================
    int docSizeTextPos = 0;
    int docSizeTextLength = fontMetrics().width(docSizeText);
    if( docSizeTextLength + 5 > crect.width() ) {
        docSizeTextPos = crect.left() + 5; // a little margin
    }
    else {
        docSizeTextPos = ( crect.width() - docSizeTextLength ) / 2;

        // make sure the text does not cross the medium size marker
        if( docSizeTextPos <= mediumSizeMarkerPos && mediumSizeMarkerPos <= docSizeTextPos + docSizeTextLength )
            docSizeTextPos = qMax( crect.left() + 5, mediumSizeMarkerPos - docSizeTextLength - 5 );
    }
    // ====================================================================================

    // calculate the over size text
    // ====================================================================================
    QFont overSizeFont(font());
    overSizeFont.setPointSize( qMax( 8, overSizeFont.pointSize()-4 ) );
    overSizeFont.setBold(false);

    QRect overSizeTextRect( barRect );
    int overSizeTextLength = QFontMetrics(overSizeFont).width(overSizeText);
    if( overSizeTextLength + 5 > overSizeTextRect.width() - (int)(one*cdSize.totalFrames()) ) {
        // we don't have enough space on the right, so we paint to the left of the line
        overSizeTextRect.setLeft( (int)(one*cdSize.totalFrames()) - overSizeTextLength - 5 );
    }
    else {
        overSizeTextRect.setLeft( mediumSizeMarkerPos + 5 );
    }

    // make sure the two text do not overlap (this does not cover all cases though)
    if( overSizeTextRect.left() < docSizeTextPos + docSizeTextLength )
        docSizeTextPos = qMax( crect.left() + 5, qMin( overSizeTextRect.left() - docSizeTextLength - 5, mediumSizeMarkerPos - docSizeTextLength - 5 ) );

    QRect docTextRect( barRect );
    docTextRect.setLeft( docSizeTextPos );

    // Draw the fill part
    p.setPen( fillPen );
    p.setClipRect( QStyle::visualRect( layoutDirection(), barRect, crect ) );
    p.drawLine( QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerFrom ),
                QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerTo ) );
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, docTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), docSizeText );
    p.setFont(overSizeFont);
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, overSizeTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), overSizeText );

    // Draw the remain part
    p.setPen( normalPen );
    p.setClipRect( QStyle::visualRect( layoutDirection(), barRect,
                                       QRect( crect.right(), barRect.top(), barRect.width()-crect.width(), barRect.height() ) ) );
    p.drawLine( QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerFrom ),
                QStyle::visualPos( layoutDirection(), barRect, mediumSizeMarkerTo ) );
    p.setFont( font() );
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, docTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), docSizeText );
    p.setFont(overSizeFont);
    p.drawText( QStyle::visualRect( layoutDirection(), barRect, overSizeTextRect ),
                QStyle::visualAlignment( layoutDirection(), Qt::AlignLeft | Qt::AlignVCenter ), overSizeText );
    // ====================================================================================
}
Example #7
0
void KisOpenGLCanvas2::drawImage()
{
    if (!d->displayShader) {
        return;
    }

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    KisCoordinatesConverter *converter = coordinatesConverter();

    d->displayShader->bind();

    QMatrix4x4 projectionMatrix;
    projectionMatrix.setToIdentity();
    projectionMatrix.ortho(0, width(), height(), 0, NEAR_VAL, FAR_VAL);

    // Set view/projection matrices
    QMatrix4x4 modelMatrix(coordinatesConverter()->imageToWidgetTransform());
    modelMatrix.optimize();
    modelMatrix = projectionMatrix * modelMatrix;
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::ModelViewProjection), modelMatrix);

    QMatrix4x4 textureMatrix;
    textureMatrix.setToIdentity();
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::TextureMatrix), textureMatrix);

    QRectF widgetRect(0,0, width(), height());
    QRectF widgetRectInImagePixels = converter->documentToImage(converter->widgetToDocument(widgetRect));

    qreal scaleX, scaleY;
    converter->imageScale(&scaleX, &scaleY);
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::ViewportScale), (GLfloat) scaleX);
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::TexelSize), (GLfloat) d->openGLImageTextures->texelSize());

    QRect ir = d->openGLImageTextures->storedImageBounds();
    QRect wr = widgetRectInImagePixels.toAlignedRect();

    if (!d->wrapAroundMode) {
        // if we don't want to paint wrapping images, just limit the
        // processing area, and the code will handle all the rest
        wr &= ir;
    }

    int firstColumn = d->xToColWithWrapCompensation(wr.left(), ir);
    int lastColumn = d->xToColWithWrapCompensation(wr.right(), ir);
    int firstRow = d->yToRowWithWrapCompensation(wr.top(), ir);
    int lastRow = d->yToRowWithWrapCompensation(wr.bottom(), ir);

    int minColumn = d->openGLImageTextures->xToCol(ir.left());
    int maxColumn = d->openGLImageTextures->xToCol(ir.right());
    int minRow = d->openGLImageTextures->yToRow(ir.top());
    int maxRow = d->openGLImageTextures->yToRow(ir.bottom());

    int imageColumns = maxColumn - minColumn + 1;
    int imageRows = maxRow - minRow + 1;

    for (int col = firstColumn; col <= lastColumn; col++) {
        for (int row = firstRow; row <= lastRow; row++) {

            int effectiveCol = col;
            int effectiveRow = row;
            QPointF tileWrappingTranslation;

            if (effectiveCol > maxColumn || effectiveCol < minColumn) {
                int translationStep = floor(qreal(col) / imageColumns);
                int originCol = translationStep * imageColumns;
                effectiveCol = col - originCol;
                tileWrappingTranslation.rx() = translationStep * ir.width();
            }

            if (effectiveRow > maxRow || effectiveRow < minRow) {
                int translationStep = floor(qreal(row) / imageRows);
                int originRow = translationStep * imageRows;
                effectiveRow = row - originRow;
                tileWrappingTranslation.ry() = translationStep * ir.height();
            }

            KisTextureTile *tile =
                    d->openGLImageTextures->getTextureTileCR(effectiveCol, effectiveRow);

            if (!tile) {
                warnUI << "OpenGL: Trying to paint texture tile but it has not been created yet.";
                continue;
            }

            /*
             * We create a float rect here to workaround Qt's
             * "history reasons" in calculation of right()
             * and bottom() coordinates of integer rects.
             */
            QRectF textureRect(tile->tileRectInTexturePixels());
            QRectF modelRect(tile->tileRectInImagePixels().translated(tileWrappingTranslation.x(), tileWrappingTranslation.y()));

            //Setup the geometry for rendering
            if (KisOpenGL::hasOpenGL3()) {
                rectToVertices(d->vertices, modelRect);

                d->quadBuffers[0].bind();
                d->quadBuffers[0].write(0, d->vertices, 3 * 6 * sizeof(float));

                rectToTexCoords(d->texCoords, textureRect);
                d->quadBuffers[1].bind();
                d->quadBuffers[1].write(0, d->texCoords, 2 * 6 * sizeof(float));
            }
            else {
                rectToVertices(d->vertices, modelRect);
                d->displayShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
                d->displayShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, d->vertices);

                rectToTexCoords(d->texCoords, textureRect);
                d->displayShader->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
                d->displayShader->setAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE, d->texCoords);
            }

            if (d->displayFilter) {
                glActiveTexture(GL_TEXTURE0 + 1);
                glBindTexture(GL_TEXTURE_3D, d->displayFilter->lutTexture());
                d->displayShader->setUniformValue(d->displayShader->location(Uniform::Texture1), 1);
            }

            int currentLodPlane = tile->currentLodPlane();
            if (d->displayShader->location(Uniform::FixedLodLevel) >= 0) {
                d->displayShader->setUniformValue(d->displayShader->location(Uniform::FixedLodLevel),
                                                  (GLfloat) currentLodPlane);
            }

            glActiveTexture(GL_TEXTURE0);
            tile->bindToActiveTexture();

            if (currentLodPlane > 0) {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
            } else if (SCALE_MORE_OR_EQUAL_TO(scaleX, scaleY, 2.0)) {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            } else {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

                switch(d->filterMode) {
                case KisOpenGL::NearestFilterMode:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
                    break;
                case KisOpenGL::BilinearFilterMode:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                    break;
                case KisOpenGL::TrilinearFilterMode:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
                    break;
                case KisOpenGL::HighQualityFiltering:
                    if (SCALE_LESS_THAN(scaleX, scaleY, 0.5)) {
                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
                    } else {
                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                    }
                    break;
                }
            }

            glDrawArrays(GL_TRIANGLES, 0, 6);
        }
    }

    glBindTexture(GL_TEXTURE_2D, 0);
    d->displayShader->release();
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
Example #8
0
void KProgress::drawContents(QPainter *p)
{
	QRect cr = contentsRect(), er = cr;
	fr = cr;
	QBrush fb(bar_color), eb(backgroundColor());

	if (bar_pixmap)
		fb.setPixmap(*bar_pixmap);

	if (backgroundPixmap())
		eb.setPixmap(*backgroundPixmap());

	switch (bar_style) {
		case Solid:
			if (orient == Horizontal) {
				fr.setWidth(recalcValue(cr.width()));
				er.setLeft(fr.right() + 1);
			} else {
				fr.setTop(cr.bottom() - recalcValue(cr.height()));
				er.setBottom(fr.top() - 1);
			}
				
			p->setBrushOrigin(cr.topLeft());
			p->fillRect(fr, fb);
			p->fillRect(er, eb);
			
			break;
			
		case Blocked:
			const int margin = 2;
			int max, num, dx, dy;
			if (orient == Horizontal) {
				fr.setHeight(cr.height() - 2 * margin);
				fr.setWidth((int)(0.67 * fr.height()));
				fr.moveTopLeft(QPoint(cr.left() + margin, cr.top() + margin));
				dx = fr.width() + margin;
				dy = 0;
				max = (cr.width() - margin) / (fr.width() + margin) + 1;
				num = recalcValue(max);
			} else {
				fr.setWidth(cr.width() - 2 * margin);
				fr.setHeight((int)(0.67 * fr.width()));
				fr.moveBottomLeft(QPoint(cr.left() + margin, cr.bottom() - margin));
				dx = 0;
				dy = - (fr.height() + margin);
				max = (cr.height() - margin) / (fr.height() + margin) + 1;
				num = recalcValue(max);
			}
			p->setClipRect(cr.x() + margin, cr.y() + margin, 
						   cr.width() - margin, cr.height() - margin);
			for (int i = 0; i < num; i++) {
				p->setBrushOrigin(fr.topLeft());
				p->fillRect(fr, fb);
				fr.moveBy(dx, dy);
			}
			
			if (num != max) {
				if (orient == Horizontal) 
					er.setLeft(fr.right() + 1);
				else
					er.setBottom(fr.bottom() + 1);
				if (!er.isNull()) {
					p->setBrushOrigin(cr.topLeft());
					p->fillRect(er, eb);
				}
			}
			
			break;
	}	
				
	if (text_enabled && bar_style != Blocked)
		drawText(p);
		
}			
Example #9
0
void KisInfinityManager::imagePositionChanged()
{
    QRect imageRect = view()->canvasBase()->coordinatesConverter()->imageRectInWidgetPixels().toAlignedRect();
    QRect widgetRect = view()->canvasBase()->canvasWidget()->rect();

    KisConfig cfg;
    qreal vastScrolling = cfg.vastScrolling();

    int xReserve = vastScrolling * widgetRect.width();
    int yReserve = vastScrolling * widgetRect.height();

    int xThreshold = imageRect.width() - 0.4 * xReserve;
    int yThreshold = imageRect.height() - 0.4 * yReserve;

    const int stripeWidth = 48;

    int xCut = widgetRect.width() - stripeWidth;
    int yCut = widgetRect.height() - stripeWidth;

    m_decorationPath = QPainterPath();
    m_decorationPath.setFillRule(Qt::WindingFill);

    m_handleTransform.clear();

    m_sideRects.clear();
    m_sideRects.resize(NSides);

    bool visible = false;

    if (imageRect.x() <= -xThreshold) {
        QRect areaRect(widgetRect.adjusted(xCut, 0, 0, 0));
        QPointF pt = areaRect.center() + QPointF(-0.1 * stripeWidth, 0);
        addDecoration(areaRect, pt, 0, Right);
        visible = true;
    }

    if (imageRect.y() <= -yThreshold) {
        QRect areaRect(widgetRect.adjusted(0, yCut, 0, 0));
        QPointF pt = areaRect.center() + QPointF(0, -0.1 * stripeWidth);
        addDecoration(areaRect, pt, 90, Bottom);
        visible = true;
    }

    if (imageRect.right() > widgetRect.width() + xThreshold) {
        QRect areaRect(widgetRect.adjusted(0, 0, -xCut, 0));
        QPointF pt = areaRect.center() + QPointF(0.1 * stripeWidth, 0);
        addDecoration(areaRect, pt, 180, Left);
        visible = true;
    }

    if (imageRect.bottom() > widgetRect.height() + yThreshold) {
        QRect areaRect(widgetRect.adjusted(0, 0, 0, -yCut));
        QPointF pt = areaRect.center() + QPointF(0, 0.1 * stripeWidth);
        addDecoration(areaRect, pt, 270, Top);
        visible = true;
    }

    if (visible && !m_filteringEnabled) {
        view()->canvasBase()->inputManager()->attachPriorityEventFilter(this);
        m_filteringEnabled = true;
    }

    if (!visible && m_filteringEnabled) {
        view()->canvasBase()->inputManager()->detachPriorityEventFilter(this);
        m_filteringEnabled = false;
    }
}
Example #10
0
/*!\reimp
 */
void QWindowsStyle::drawScrollBarControls( QPainter* p, const QScrollBar* sb, int sliderStart, uint controls, uint activeControl )
{
#ifndef QT_NO_SCROLLBAR
#define ADD_LINE_ACTIVE ( activeControl == AddLine )
#define SUB_LINE_ACTIVE ( activeControl == SubLine )
    QColorGroup g  = sb->colorGroup();

    int sliderMin, sliderMax, sliderLength, buttonDim;
    scrollBarMetrics( sb, sliderMin, sliderMax, sliderLength, buttonDim );

    if (sliderStart > sliderMax) { // sanity check
	sliderStart = sliderMax;
    }

    int b = 0;
    int dimB = buttonDim;
    QRect addB;
    QRect subB;
    QRect addPageR;
    QRect subPageR;
    QRect sliderR;
    int addX, addY, subX, subY;
    int length = HORIZONTAL ? sb->width()  : sb->height();
    int extent = HORIZONTAL ? sb->height() : sb->width();

    if ( HORIZONTAL ) {
	subY = addY = ( extent - dimB ) / 2;
	subX = b;
	addX = length - dimB - b;
    } else {
	subX = addX = ( extent - dimB ) / 2;
	subY = b;
	addY = length - dimB - b;
    }

    subB.setRect( subX,subY,dimB,dimB );
    addB.setRect( addX,addY,dimB,dimB );

    int sliderEnd = sliderStart + sliderLength;
    int sliderW = extent - b*2;
    if ( HORIZONTAL ) {
	subPageR.setRect( subB.right() + 1, b,
			  sliderStart - subB.right() - 1 , sliderW );
	addPageR.setRect( sliderEnd, b, addX - sliderEnd, sliderW );
	sliderR .setRect( sliderStart, b, sliderLength, sliderW );
    } else {
	subPageR.setRect( b, subB.bottom() + 1, sliderW,
			  sliderStart - subB.bottom() - 1 );
	addPageR.setRect( b, sliderEnd, sliderW, addY - sliderEnd );
	sliderR .setRect( b, sliderStart, sliderW, sliderLength );
    }

    bool maxedOut = (sb->maxValue() == sb->minValue());
    if ( controls & AddLine ) {
	qDrawWinPanel( p, addB.x(), addB.y(),
		       addB.width(), addB.height(), g,
		       ADD_LINE_ACTIVE, &g.brush( QColorGroup::Button ) );
	drawArrow( p, VERTICAL ? DownArrow : RightArrow,
		   ADD_LINE_ACTIVE, addB.x()+2, addB.y()+2,
		   addB.width()-4, addB.height()-4, g, !maxedOut );
    }
    if ( controls & SubLine ) {
	qDrawWinPanel( p, subB.x(), subB.y(),
		       subB.width(), subB.height(), g,
		       SUB_LINE_ACTIVE, &g.brush( QColorGroup::Button )  );
	drawArrow( p, VERTICAL ? UpArrow : LeftArrow,
		   SUB_LINE_ACTIVE, subB.x()+2, subB.y()+2,
		   subB.width()-4, subB.height()-4, g, !maxedOut );
    }
    QBrush br =
	g.brush( QColorGroup::Light ).pixmap() ?
		 g.brush( QColorGroup::Light )     :
		 QBrush(g.light(), Dense4Pattern);
    p->setBrush( br );
    p->setPen( NoPen );
    p->setBackgroundMode( OpaqueMode );
    if ( maxedOut ) {
	p->drawRect( sliderR );
    } else {
	if ( (controls & SubPage && SubPage == activeControl) ||
	     (controls  & AddPage && AddPage == activeControl) ) {
	    QBrush b = p->brush();
	    QColor c = p->backgroundColor();
// 	    p->fillRect( AddPage == activeControl? addPageR : subPageR, g.fillDark() );
	    p->setBackgroundColor( g.dark() );
	    p->setBrush( QBrush(g.shadow(), Dense4Pattern) );
	    p->drawRect( AddPage == activeControl? addPageR : subPageR );
	    p->setBackgroundColor( c );
	    p->setBrush( b );
	}
	if ( controls & SubPage && SubPage != activeControl)
	    p->drawRect( subPageR );
	if ( controls & AddPage && AddPage != activeControl)
	    p->drawRect( addPageR );
	if ( controls & Slider ) {
	    if ( !maxedOut ) {
		QPoint bo = p->brushOrigin();
		if ( !sb->testWState(WState_GlobalBrushOrigin) )
		    p->setBrushOrigin(sliderR.topLeft());
		qDrawWinPanel( p, sliderR.x(), sliderR.y(),
				 sliderR.width(), sliderR.height(), g,
				 FALSE, &g.brush( QColorGroup::Button ) );
		p->setBrushOrigin(bo);
	    }
	}
    }
    // ### perhaps this should not be able to accept focus if maxedOut?
    if ( sb->hasFocus() && (controls & Slider) )
	drawFocusRect(p, QRect(sliderR.x()+2, sliderR.y()+2,
			       sliderR.width()-5, sliderR.height()-5), g,
		      &sb->backgroundColor());
#endif
}
void NcWidgetData::resizeWidget( const QPoint& globalMousePos )
{
  QRect origRect;

  if ( d->mUseRubberBandOnResize )
    origRect = mRubberBand->frameGeometry();
  else
    origRect = mWidget->frameGeometry();


  int left = origRect.left();
  int top = origRect.top();
  int right = origRect.right();
  int bottom = origRect.bottom();
  origRect.getCoords( &left, &top, &right, &bottom );

  int minWidth = mWidget->minimumWidth();
  int minHeight = mWidget->minimumHeight();

  if ( mPressedMousePos.onTopLeftEdge )
  {
    left = globalMousePos.x();
    top = globalMousePos.y();
  }
  else if ( mPressedMousePos.onBottomLeftEdge )
  {
    left = globalMousePos.x();
    bottom = globalMousePos.y();
  }
  else if ( mPressedMousePos.onTopRightEdge )
  {
    right = globalMousePos.x();
    top = globalMousePos.y();
  }
  else if ( mPressedMousePos.onBottomRightEdge )
  {
    right = globalMousePos.x();
    bottom = globalMousePos.y();
  }
  else if ( mPressedMousePos.onLeftEdge )
  {
    left = globalMousePos.x();
  }
  else if ( mPressedMousePos.onRightEdge )
  {
    right = globalMousePos.x();
  }
  else if ( mPressedMousePos.onTopEdge )
  {
    top = globalMousePos.y();
  }
  else if ( mPressedMousePos.onBottomEdge )
  {
    bottom = globalMousePos.y();
  }

  QRect newRect( QPoint(left, top), QPoint(right, bottom) );

  if ( newRect.isValid() )
  {
    if ( minWidth > newRect.width() )
    {
      //determine what has caused the width change.
      if( left != origRect.left() )
        newRect.setLeft( origRect.left() );
      else
        newRect.setRight( origRect.right() );
    }
    if ( minHeight > newRect.height() )
    {
      //determine what has caused the height change.
      if ( top != origRect.top() )
        newRect.setTop( origRect.top() );
      else
        newRect.setBottom( origRect.bottom() );
    }

    if ( d->mUseRubberBandOnResize )
    {
      mRubberBand->setGeometry( newRect );
    }
    else
    {
      mWidget->setGeometry( newRect );
    }
  }
  else
  {
    //qDebug() << "Calculated Rect is not valid" << newRect;
  }

}
void IsometricRenderer::drawTileLayer(QPainter *painter,
                                      const TileLayer *layer,
                                      const QRectF &exposed) const
{
    const int tileWidth = map()->tileWidth();
    const int tileHeight = map()->tileHeight();

    if (tileWidth <= 0 || tileHeight <= 1)
        return;

    QRect rect = exposed.toAlignedRect();
    if (rect.isNull())
        rect = boundingRect(layer->bounds());

    QMargins drawMargins = layer->drawMargins();
    drawMargins.setTop(drawMargins.top() - tileHeight);
    drawMargins.setRight(drawMargins.right() - tileWidth);

    rect.adjust(-drawMargins.right(),
                -drawMargins.bottom(),
                drawMargins.left(),
                drawMargins.top());

    // Determine the tile and pixel coordinates to start at
    QPointF tilePos = pixelToTileCoords(rect.x(), rect.y());
    QPoint rowItr = QPoint((int) std::floor(tilePos.x()),
                           (int) std::floor(tilePos.y()));
    QPointF startPos = tileToPixelCoords(rowItr);
    startPos.rx() -= tileWidth / 2;
    startPos.ry() += tileHeight;

    // Compensate for the layer position
    rowItr -= QPoint(layer->x(), layer->y());

    /* Determine in which half of the tile the top-left corner of the area we
     * need to draw is. If we're in the upper half, we need to start one row
     * up due to those tiles being visible as well. How we go up one row
     * depends on whether we're in the left or right half of the tile.
     */
    const bool inUpperHalf = startPos.y() - rect.y() > tileHeight / 2;
    const bool inLeftHalf = rect.x() - startPos.x() < tileWidth / 2;

    if (inUpperHalf) {
        if (inLeftHalf) {
            --rowItr.rx();
            startPos.rx() -= tileWidth / 2;
        } else {
            --rowItr.ry();
            startPos.rx() += tileWidth / 2;
        }
        startPos.ry() -= tileHeight / 2;
    }

    // Determine whether the current row is shifted half a tile to the right
    bool shifted = inUpperHalf ^ inLeftHalf;

    QTransform baseTransform = painter->transform();

    for (int y = startPos.y(); y - tileHeight < rect.bottom();
         y += tileHeight / 2)
    {
        QPoint columnItr = rowItr;

        for (int x = startPos.x(); x < rect.right(); x += tileWidth) {
            if (layer->contains(columnItr)) {
                const Cell &cell = layer->cellAt(columnItr);
                if (!cell.isEmpty()) {
                    const QPixmap &img = cell.tile->image();
                    const QPoint offset = cell.tile->tileset()->tileOffset();

                    qreal m11 = 1;      // Horizontal scaling factor
                    qreal m12 = 0;      // Vertical shearing factor
                    qreal m21 = 0;      // Horizontal shearing factor
                    qreal m22 = 1;      // Vertical scaling factor
                    qreal dx = offset.x() + x;
                    qreal dy = offset.y() + y - img.height();

                    if (cell.flippedAntiDiagonally) {
                        // Use shearing to swap the X/Y axis
                        m11 = 0;
                        m12 = 1;
                        m21 = 1;
                        m22 = 0;

                        // Compensate for the swap of image dimensions
                        dy += img.height() - img.width();
                    }
                    if (cell.flippedHorizontally) {
                        m11 = -m11;
                        m21 = -m21;
                        dx += cell.flippedAntiDiagonally ? img.height()
                                                         : img.width();
                    }
                    if (cell.flippedVertically) {
                        m12 = -m12;
                        m22 = -m22;
                        dy += cell.flippedAntiDiagonally ? img.width()
                                                         : img.height();
                    }

                    const QTransform transform(m11, m12, m21, m22, dx, dy);
                    painter->setTransform(transform * baseTransform);

                    painter->drawPixmap(0, 0, img);
                }
            }

            // Advance to the next column
            ++columnItr.rx();
            --columnItr.ry();
        }

        // Advance to the next row
        if (!shifted) {
            ++rowItr.rx();
            startPos.rx() += tileWidth / 2;
            shifted = true;
        } else {
            ++rowItr.ry();
            startPos.rx() -= tileWidth / 2;
            shifted = false;
        }
    }

    painter->setTransform(baseTransform);
}
Example #13
0
static bool read_jpeg_image(QImage *outImage,
                            QSize scaledSize, QRect scaledClipRect,
                            QRect clipRect, int inQuality, j_decompress_ptr info, struct my_error_mgr* err  )
{
    if (!setjmp(err->setjmp_buffer)) {
        // -1 means default quality.
        int quality = inQuality;
        if (quality < 0)
            quality = 75;

        // If possible, merge the scaledClipRect into either scaledSize
        // or clipRect to avoid doing a separate scaled clipping pass.
        // Best results are achieved by clipping before scaling, not after.
        if (!scaledClipRect.isEmpty()) {
            if (scaledSize.isEmpty() && clipRect.isEmpty()) {
                // No clipping or scaling before final clip.
                clipRect = scaledClipRect;
                scaledClipRect = QRect();
            } else if (scaledSize.isEmpty()) {
                // Clipping, but no scaling: combine the clip regions.
                scaledClipRect.translate(clipRect.topLeft());
                clipRect = scaledClipRect.intersected(clipRect);
                scaledClipRect = QRect();
            } else if (clipRect.isEmpty()) {
                // No clipping, but scaling: if we can map back to an
                // integer pixel boundary, then clip before scaling.
                if ((info->image_width % scaledSize.width()) == 0 &&
                        (info->image_height % scaledSize.height()) == 0) {
                    int x = scaledClipRect.x() * info->image_width /
                            scaledSize.width();
                    int y = scaledClipRect.y() * info->image_height /
                            scaledSize.height();
                    int width = (scaledClipRect.right() + 1) *
                                info->image_width / scaledSize.width() - x;
                    int height = (scaledClipRect.bottom() + 1) *
                                 info->image_height / scaledSize.height() - y;
                    clipRect = QRect(x, y, width, height);
                    scaledSize = scaledClipRect.size();
                    scaledClipRect = QRect();
                }
            } else {
                // Clipping and scaling: too difficult to figure out,
                // and not a likely use case, so do it the long way.
            }
        }

        // Determine the scale factor to pass to libjpeg for quick downscaling.
        if (!scaledSize.isEmpty()) {
            if (clipRect.isEmpty()) {
                info->scale_denom =
                    qMin(info->image_width / scaledSize.width(),
                         info->image_height / scaledSize.height());
            } else {
                info->scale_denom =
                    qMin(clipRect.width() / scaledSize.width(),
                         clipRect.height() / scaledSize.height());
            }
            if (info->scale_denom < 2) {
                info->scale_denom = 1;
            } else if (info->scale_denom < 4) {
                info->scale_denom = 2;
            } else if (info->scale_denom < 8) {
                info->scale_denom = 4;
            } else {
                info->scale_denom = 8;
            }
            info->scale_num = 1;
            if (!clipRect.isEmpty()) {
                // Correct the scale factor so that we clip accurately.
                // It is recommended that the clip rectangle be aligned
                // on an 8-pixel boundary for best performance.
                while (info->scale_denom > 1 &&
                       ((clipRect.x() % info->scale_denom) != 0 ||
                        (clipRect.y() % info->scale_denom) != 0 ||
                        (clipRect.width() % info->scale_denom) != 0 ||
                        (clipRect.height() % info->scale_denom) != 0)) {
                    info->scale_denom /= 2;
                }
            }
        }

        // If high quality not required, use fast decompression
        if( quality < HIGH_QUALITY_THRESHOLD ) {
            info->dct_method = JDCT_IFAST;
            info->do_fancy_upsampling = FALSE;
        }

        (void) jpeg_calc_output_dimensions(info);

        // Determine the clip region to extract.
        QRect imageRect(0, 0, info->output_width, info->output_height);
        QRect clip;
        if (clipRect.isEmpty()) {
            clip = imageRect;
        } else if (info->scale_denom == info->scale_num) {
            clip = clipRect.intersected(imageRect);
        } else {
            // The scale factor was corrected above to ensure that
            // we don't miss pixels when we scale the clip rectangle.
            clip = QRect(clipRect.x() / int(info->scale_denom),
                         clipRect.y() / int(info->scale_denom),
                         clipRect.width() / int(info->scale_denom),
                         clipRect.height() / int(info->scale_denom));
            clip = clip.intersected(imageRect);
        }

        // Allocate memory for the clipped QImage.
        if (!ensureValidImage(outImage, info, clip.size()))
            longjmp(err->setjmp_buffer, 1);

        // Avoid memcpy() overhead if grayscale with no clipping.
        bool quickGray = (info->output_components == 1 &&
                          clip == imageRect);
        if (!quickGray) {
            // Ask the jpeg library to allocate a temporary row.
            // The library will automatically delete it for us later.
            // The libjpeg docs say we should do this before calling
            // jpeg_start_decompress().  We can't use "new" here
            // because we are inside the setjmp() block and an error
            // in the jpeg input stream would cause a memory leak.
            JSAMPARRAY rows = (info->mem->alloc_sarray)
                              ((j_common_ptr)info, JPOOL_IMAGE,
                               info->output_width * info->output_components, 1);

            (void) jpeg_start_decompress(info);

            while (info->output_scanline < info->output_height) {
                int y = int(info->output_scanline) - clip.y();
                if (y >= clip.height())
                    break;      // We've read the entire clip region, so abort.

                (void) jpeg_read_scanlines(info, rows, 1);

                if (y < 0)
                    continue;   // Haven't reached the starting line yet.

                if (info->output_components == 3) {
                    uchar *in = rows[0] + clip.x() * 3;
                    QRgb *out = (QRgb*)outImage->scanLine(y);
                    rgb888ToRgb32ConverterPtr(out, in, clip.width());
                } else if (info->out_color_space == JCS_CMYK) {
                    // Convert CMYK->RGB.
                    uchar *in = rows[0] + clip.x() * 4;
                    QRgb *out = (QRgb*)outImage->scanLine(y);
                    for (int i = 0; i < clip.width(); ++i) {
                        int k = in[3];
                        *out++ = qRgb(k * in[0] / 255, k * in[1] / 255,
                                      k * in[2] / 255);
                        in += 4;
                    }
                } else if (info->output_components == 1) {
                    // Grayscale.
                    memcpy(outImage->scanLine(y),
                           rows[0] + clip.x(), clip.width());
                }
            }
        } else {
            // Load unclipped grayscale data directly into the QImage.
            (void) jpeg_start_decompress(info);
            while (info->output_scanline < info->output_height) {
                uchar *row = outImage->scanLine(info->output_scanline);
                (void) jpeg_read_scanlines(info, &row, 1);
            }
        }

        if (info->output_scanline == info->output_height)
            (void) jpeg_finish_decompress(info);

        if (info->density_unit == 1) {
            outImage->setDotsPerMeterX(int(100. * info->X_density / 2.54));
            outImage->setDotsPerMeterY(int(100. * info->Y_density / 2.54));
        } else if (info->density_unit == 2) {
            outImage->setDotsPerMeterX(int(100. * info->X_density));
            outImage->setDotsPerMeterY(int(100. * info->Y_density));
        }

        if (scaledSize.isValid() && scaledSize != clip.size()) {
            *outImage = outImage->scaled(scaledSize, Qt::IgnoreAspectRatio, quality >= HIGH_QUALITY_THRESHOLD ? Qt::SmoothTransformation : Qt::FastTransformation);
        }

        if (!scaledClipRect.isEmpty())
            *outImage = outImage->copy(scaledClipRect);
        return !outImage->isNull();
    }
    else
        return false;
}
Example #14
0
void AxisImp::paintEvent(QPaintEvent* e)
{
    // Draw to an off-screen pixmap
    QRect rcWidget = rect();
    QPixmap pix(rcWidget.size());
    pix.fill(this, 0, 0);

    QPainter p(&pix);

    // Size the scale
    int iScaleWidth = 0;
    int iScaleHeight = 0;

    switch (mScaleDraw.alignment())
    {
    case QwtScaleDraw::LeftScale:
        iScaleWidth = mScaleDraw.extent(p.pen(), p.font());
        iScaleHeight = mScaleDraw.minLength(p.pen(), p.font());
        mScaleDraw.move(rcWidget.right(), rcWidget.y());
        mScaleDraw.setLength(rcWidget.height());
        break;

    case QwtScaleDraw::RightScale:
        iScaleWidth = mScaleDraw.extent(p.pen(), p.font());
        iScaleHeight = mScaleDraw.minLength(p.pen(), p.font());
        mScaleDraw.move(rcWidget.x(), rcWidget.y());
        mScaleDraw.setLength(rcWidget.height());
        break;

    case QwtScaleDraw::TopScale:
        iScaleWidth = mScaleDraw.minLength(p.pen(), p.font());
        iScaleHeight = mScaleDraw.extent(p.pen(), p.font());
        mScaleDraw.move(rcWidget.x(), rcWidget.bottom());
        mScaleDraw.setLength(rcWidget.width());
        break;

    case QwtScaleDraw::BottomScale:
        iScaleWidth = mScaleDraw.minLength(p.pen(), p.font());
        iScaleHeight = mScaleDraw.extent(p.pen(), p.font());
        mScaleDraw.move(rcWidget.x(), rcWidget.y());
        mScaleDraw.setLength(rcWidget.width());
        break;

    default:
        break;
    }

    // Draw the scale
    mScaleDraw.draw(&p, palette());

    // Draw the title
    if (mTitle.isEmpty() == false)
    {
        p.setFont(mTitleFont.toQFont());
        p.setPen(mTitleColor);
        int iTitleHeight = p.fontMetrics().height();

        QRect rcText = rcWidget;
        switch (mScaleDraw.alignment())
        {
        case QwtScaleDraw::LeftScale:
            p.rotate(-90.0);
            p.drawText(-rcWidget.bottom(), rcWidget.left(), rcWidget.height(),
                       rcWidget.width() - iScaleWidth - TITLE_MARGIN, Qt::AlignCenter, mTitle);
            break;

        case QwtScaleDraw::RightScale:
            p.rotate(90.0);
            p.drawText(rcWidget.top(), rcWidget.right(), rcWidget.height(),
                       rcWidget.width() - iScaleWidth - TITLE_MARGIN, Qt::AlignCenter, mTitle);
            break;

        case QwtScaleDraw::TopScale:
            rcText.setBottom(rcWidget.bottom() - iScaleHeight - TITLE_MARGIN);
            p.drawText(rcText, Qt::AlignCenter, mTitle);
            break;

        case QwtScaleDraw::BottomScale:
            rcText.setTop(rcWidget.top() + iScaleHeight + TITLE_MARGIN);
            p.drawText(rcText, Qt::AlignCenter, mTitle);
            break;

        default:
            break;
        }
    }

    p.end();

    // Draw to the widget
    p.begin(this);
    p.drawPixmap(rcWidget.topLeft(), pix);
    p.end();
}
Example #15
0
void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                 const QModelIndex &index) const
{
  QStyledItemDelegate::paint(painter,option,index);

  painter->save();

  QFont aliasFont = option.font;
  QFont subFont   = option.font;
  QFont errorFont = subFont;
  QFont progressFont = subFont;

  progressFont.setPointSize( subFont.pointSize()-1);
  //font.setPixelSize(font.weight()+);
  aliasFont.setBold(true);
  aliasFont.setPointSize( subFont.pointSize()+2 );

  QFontMetrics subFm( subFont );
  QFontMetrics aliasFm( aliasFont );
  QFontMetrics progressFm( progressFont );

  int aliasMargin = aliasFm.height()/2;
  int margin = subFm.height()/4;

  QIcon statusIcon      = qvariant_cast<QIcon>(index.data(FolderStatusIconRole));
  QString aliasText     = qvariant_cast<QString>(index.data(FolderAliasRole));
  QString pathText      = qvariant_cast<QString>(index.data(FolderPathRole));
  QString remotePath    = qvariant_cast<QString>(index.data(FolderSecondPathRole));
  QStringList errorTexts= qvariant_cast<QStringList>(index.data(FolderErrorMsg));

  int overallPercent    = qvariant_cast<int>(index.data(SyncProgressOverallPercent));
  QString overallString = qvariant_cast<QString>(index.data(SyncProgressOverallString));
  QString itemString    = qvariant_cast<QString>(index.data(SyncProgressItemString));
  int warningCount      = qvariant_cast<int>(index.data(WarningCount));
  bool syncOngoing      = qvariant_cast<bool>(index.data(SyncRunning));
  // QString statusText = qvariant_cast<QString>(index.data(FolderStatus));
  bool syncEnabled = index.data(FolderSyncEnabled).toBool();
  // QString syncStatus = syncEnabled? tr( "Enabled" ) : tr( "Disabled" );

  QRect iconRect = option.rect;
  QRect aliasRect = option.rect;

  iconRect.setLeft( aliasMargin );
  iconRect.setTop( iconRect.top() + aliasMargin ); // (iconRect.height()-iconsize.height())/2);

  // alias box
  aliasRect.setTop(aliasRect.top() + aliasMargin );
  aliasRect.setBottom(aliasRect.top() + aliasFm.height());
  aliasRect.setRight(aliasRect.right() - aliasMargin );

  // remote directory box
  QRect remotePathRect = aliasRect;
  remotePathRect.setTop(aliasRect.bottom() + margin );
  remotePathRect.setBottom(remotePathRect.top() + subFm.height());

  // local directory box
  QRect localPathRect = remotePathRect;
  localPathRect.setTop( remotePathRect.bottom() + margin );
  localPathRect.setBottom( localPathRect.top() + subFm.height());

  iconRect.setBottom(localPathRect.bottom());
  iconRect.setWidth(iconRect.height());

  int nextToIcon = iconRect.right()+aliasMargin;
  aliasRect.setLeft(nextToIcon);
  localPathRect.setLeft(nextToIcon);
  remotePathRect.setLeft(nextToIcon);

  int iconSize = iconRect.width();

  QPixmap pm = statusIcon.pixmap(iconSize, iconSize, syncEnabled ? QIcon::Normal : QIcon::Disabled );
  painter->drawPixmap(QPoint(iconRect.left(), iconRect.top()), pm);

  // only show the warning icon if the sync is running. Otherwise its
  // encoded in the status icon.
  if( warningCount > 0 && syncOngoing) {
      QRect warnRect;
      warnRect.setLeft(iconRect.left());
      warnRect.setTop(iconRect.bottom()-17);
      warnRect.setWidth(16);
      warnRect.setHeight(16);

      QIcon warnIcon(":/mirall/resources/warning-16");
      QPixmap pm = warnIcon.pixmap(16,16, syncEnabled ? QIcon::Normal : QIcon::Disabled );
      painter->drawPixmap(QPoint(warnRect.left(), warnRect.top()),pm );
  }

  if ((option.state & QStyle::State_Selected)
          && (option.state & QStyle::State_Active)
          // Hack: Windows Vista's light blue is not contrasting enough for white
          && !qApp->style()->inherits("QWindowsVistaStyle")) {
      painter->setPen(option.palette.color(QPalette::HighlightedText));
  } else {
      painter->setPen(option.palette.color(QPalette::Text));
  }
  QString elidedAlias = aliasFm.elidedText(aliasText, Qt::ElideRight, aliasRect.width());
  painter->setFont(aliasFont);
  painter->drawText(aliasRect, elidedAlias);

  painter->setFont(subFont);
  QString elidedRemotePathText;

  if (remotePath.isEmpty() || remotePath == QLatin1String("/")) {
      elidedRemotePathText = subFm.elidedText(tr("Syncing all files in your account with"),
                                              Qt::ElideRight, remotePathRect.width());
  } else {
      elidedRemotePathText = subFm.elidedText(tr("Remote path: %1").arg(remotePath),
                                              Qt::ElideMiddle, remotePathRect.width());
  }
  painter->drawText(remotePathRect, elidedRemotePathText);

  QString elidedPathText = subFm.elidedText(pathText, Qt::ElideMiddle, localPathRect.width());
  painter->drawText(localPathRect, elidedPathText);

  // paint an error overlay if there is an error string

  int h = iconRect.bottom();
  if( !errorTexts.isEmpty() ) {
      h += aliasMargin;
      QRect errorRect = localPathRect;
      errorRect.setLeft( iconRect.left());
      errorRect.setTop( h );
      errorRect.setHeight(errorTexts.count() * subFm.height()+aliasMargin);
      errorRect.setRight( option.rect.right()-aliasMargin );

      painter->setBrush( QColor(0xbb, 0x4d, 0x4d) );
      painter->setPen( QColor(0xaa, 0xaa, 0xaa));
      painter->drawRoundedRect( errorRect, 4, 4 );

      painter->setPen( Qt::white );
      painter->setFont(errorFont);
      QRect errorTextRect = errorRect;
      errorTextRect.setLeft( errorTextRect.left()+aliasMargin );
      errorTextRect.setTop( errorTextRect.top()+aliasMargin/2 );

      int x = errorTextRect.left();
      int y = errorTextRect.top()+aliasMargin/2 + subFm.height()/2;

      foreach( QString eText, errorTexts ) {
          painter->drawText(x, y, subFm.elidedText( eText, Qt::ElideLeft, errorTextRect.width()-2*aliasMargin));
          y += subFm.height();
      }
Example #16
0
void Widget::resizeEvent(QResizeEvent *event)
{
	if(m_layout->count()) {
		QRect desktop = qApp->desktop()->availableGeometry();

		bool animate = (x() < 0) && m_animation;
		if(!animate) {
			switch(m_position) {
				case TopLeft:
					move(desktop.left(), desktop.top());
				break;

				case TopRight:
					move(desktop.right() - width(), desktop.top());
				break;

				case BottomLeft:
					move(desktop.left(), desktop.bottom() - height());
				break;

				case BottomRight:
					move(desktop.right() - width(), desktop.bottom() - height());
				break;
			}
		} else {
			QPoint target;
			QPropertyAnimation *animation = new QPropertyAnimation(this, "pos");

			switch(m_position) {
				case TopLeft:
					move(desktop.left(), desktop.top() - height());
					target = QPoint(desktop.left(), desktop.top());
				break;

				case TopRight:
					move(desktop.right() - width(), desktop.top() - height());
					target = QPoint(desktop.right() - width(), desktop.top());
				break;

				case BottomLeft:
				{
					move(desktop.left(), desktop.bottom());
					target = QPoint(desktop.left(), desktop.bottom() - height());
				}
				break;

				case BottomRight:
				{
					move(desktop.right() - width(), desktop.bottom());
					target = QPoint(desktop.right() - width(), desktop.bottom() - height());
				}
				break;
			}

			animation->setStartValue(pos());
			animation->setEndValue(target);
			animation->setDuration(150);
			animation->start(QPropertyAnimation::DeleteWhenStopped);
		}
	}
}
Example #17
0
// e.g.: Sheet4.A1:Sheet4.E28
//used in Sheet::saveOdf
QString Calligra::Sheets::Odf::convertRangeToRef(const QString & sheetName, const QRect & _area)
{
    return sheetName + '.' + Cell::name(_area.left(), _area.top()) + ':' + sheetName + '.' + Cell::name(_area.right(), _area.bottom());
}
Example #18
0
void starter::popupMenu()
{
   if (popupBlocked)
      return;
   {
//       if (!isDialog_)
//          return;
      startMenu->setMinimumSize ( 0, 0 );
      startMenu->setMaximumSize ( 32767, 32767 );
      setActiveWindow();
      startMenu->setPanelPosition((StartMenu::PanelPosition)configDialog->popupPanelPos->currentItem());
      if (configDialog->customPopupSize->isChecked())
      {
         startMenu->resize(configDialog->popupW->value(),configDialog->popupH->value());
         startMenu->setFixedSize(startMenu->size());
//          startMenu->setFixedSize(_MAX_(configDialog->popupW->value(), startMenu->minimumWidth()), _MAX_(configDialog->popupH->value(), startMenu->minimumHeight()));
      }
      else
      {
         QRect desktop = QDesktopWidget().availableGeometry( startMenu );
         startMenu->resize(desktop.width()/5, 2*desktop.height()/3);
         startMenu->setFixedSize(startMenu->size());
//          startMenu->setFixedSize(_MAX_(startMenu->minimumWidth(), desktop.width()/5) ,_MAX_(startMenu->minimumHeight(), 2*desktop.height()/3)); // 1/5 screen width, 2/3 screen height
      }
      
      QPoint pt = mapToGlobal(pos());
      QRect desktop = QDesktopWidget().availableGeometry( startMenu );
      int x = pt.x();
      int y = pt.y();
      
      switch(position())
      {
      case pTop:
         y += height() + 1;
         if (x + startMenu->width() > desktop.right())
            x =  desktop.right() - startMenu->width();
         if (x < 0) x = 0;
         break;
      case pLeft:
         x += width() + 1;
         if (y + startMenu->height() > desktop.bottom())
            y =  desktop.bottom() - startMenu->height();
         if (y < 0) y = 0;
         break;
      case pBottom:
         y -= startMenu->height() - 1;
         if (x + startMenu->width() > desktop.right())
            x =  desktop.right() - startMenu->width();
         if (x < 0) x = 0;
         break;
      case pRight:
         x -= startMenu->width() - 1;
         if (y + startMenu->height() > desktop.bottom())
            y =  desktop.bottom() - startMenu->height();
         if (y < 0) y = 0;
      }
      pt = QPoint(x, y);
      
      startMenu->reparent(this, Qt::WType_Popup, pt, true);
   }
}
Example #19
0
void QFrame::setFrameRect(const QRect &r)
{
    Q_D(QFrame);
    QRect cr = r.isValid() ? r : rect();
    cr.adjust(d->leftFrameWidth, d->topFrameWidth, -d->rightFrameWidth, -d->bottomFrameWidth);
    setContentsMargins(cr.left(), cr.top(), rect().right() - cr.right(), rect().bottom() - cr.bottom());
}
void YaTabBarBase::drawTab(QPainter* painter, int index, const QRect& tabRect)
{
	QStyleOptionTabV2 tab = getStyleOption(index);
	if (!(tab.state & QStyle::State_Enabled)) {
		tab.palette.setCurrentColorGroup(QPalette::Disabled);
	}

	// Don't bother drawing a tab if the entire tab is outside of the visible tab bar.
	if (tabRect.right() < 0 ||
	    tabRect.left() > width() ||
	    tabRect.bottom() < 0 ||
	    tabRect.top() > height() ||
	    tabRect.width() < 3)
	{
		return;
	}

	bool isCurrent = index == currentIndex();
	bool isHovered = tabHovered(index);
	bool isHighlighted = tabData(index).toBool();

	QColor backgroundColor = this->tabBackgroundColor();
	if (isCurrent) {
#ifndef WIDGET_PLUGIN
		backgroundColor = Ya::VisualUtil::editAreaColor();
#else
		backgroundColor = Qt::white;
#endif
	}
	else if (isHovered) {
#ifndef WIDGET_PLUGIN
		backgroundColor = Ya::VisualUtil::tabHighlightColor();
#else
		backgroundColor = Qt::gray;
#endif
	}
	else if (isHighlighted) {
		backgroundColor = highlightColor();
	}

	if (backgroundColor.isValid()) {
		painter->fillRect(tabRect, backgroundColor);
	}

	painter->save();
#ifndef WIDGET_PLUGIN
	painter->setPen(Ya::VisualUtil::rosterTabBorderColor());
#endif

	bool drawLeftLine  = tabRect.left() != rect().left();
	bool drawRightLine = true; // tabRect.right() != rect().right() || rect().width() < maximumWidth();

	switch (shape()) {
	case YaTabBarBase::RoundedSouth:
	case YaTabBarBase::TriangularSouth:
		if (isMultiLine())
			drawRightLine = tabRect.right() + 1 < maximumWidth();

		if (!isCurrent || isMultiLine())
			painter->drawLine(tabRect.topLeft(), tabRect.topRight());

		if (isCurrent) {
			if (drawLeftLine && !isMultiLine())
				painter->drawLine(tabRect.topLeft(), tabRect.bottomLeft());
			if (drawRightLine)
				painter->drawLine(tabRect.topRight(), tabRect.bottomRight());
		}
		else {
			if (isHovered || isMultiLine()) {
				if (currentIndex() != (index - 1) && !isMultiLine())
					if (drawLeftLine)
						painter->drawLine(tabRect.topLeft(), tabRect.bottomLeft());
				if (currentIndex() != (index + 1) || isMultiLine())
					if (drawRightLine)
						painter->drawLine(tabRect.topRight(), tabRect.bottomRight());
			}
		}
		break;
	default:
		Q_ASSERT(false);
		break;
	}

	painter->restore();

	tabIcon(index).paint(painter, tabIconRect(index));

	QRect textRect = tabTextRect(index);
	QString text = tabText(index);

	if (drawTabNumbers_ && index < 10) {
		int numberToDraw = index + 1;
		if (numberToDraw > 9) {
			numberToDraw = 0;
		}

		painter->save();
		painter->setPen(Qt::gray);
		QString numberToDrawText = QString::number(numberToDraw) + " ";
		painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, numberToDrawText);
		textRect.adjust(fontMetrics().width(numberToDrawText), 0, 0, 0);
		painter->restore();
	}

	painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, text);
#ifndef WIDGET_PLUGIN
	if (textWidth(text) > textRect.width() && backgroundColor.isValid()) {
		Ya::VisualUtil::drawTextFadeOut(painter, textRect.adjusted(1, 0, 1, 0), backgroundColor, 15);
	}
#endif

	if (isMultiLine()) {
		QPixmap shadow(tabShadow(isCurrent));
		QRect r(tabRect);
		r.setHeight(shadow.height());
		painter->drawTiledPixmap(r, shadow);
	}
}
// resize this to contain its sub elements
void ActivityContainerCanvas::resize_to_contain(QList<QGraphicsItem*> & all,
        BooL & need_sub_upper)
{
    QList<QGraphicsItem*>::Iterator cit;
    BrowserNode * browser_node = get_bn();
    QRect r = rect();
    int resize_left = 0;
    int resize_right = 0;
    int resize_top = 0;
    int resize_bottom = 0;

    for (cit = all.begin(); cit != all.end(); ++cit) {
        if ((*cit)->isVisible() && !(*cit)->isSelected()) {
            DiagramItem * di = QCanvasItemToDiagramItem(*cit);

            if ((di != 0) &&
                (di->get_bn() != 0) &&
                (((BrowserNode *) di->get_bn())->parent() == browser_node)) {
                // must look at the type because some canvas items have browser_node
                // attr equals to the diagram and the parent of the diagram is the activity
                switch (di->typeUmlCode()) {
                case UmlActivityObject:
                case UmlActivityAction:
                case UmlActivityPartition:
                case UmlExpansionRegion:
                case UmlInterruptibleActivityRegion:
                case InitialAN:
                case FlowFinalAN:
                case ActivityFinalAN:
                case DecisionAN:
                case MergeAN:
                case ForkAN:
                case JoinAN: {
                    QRect di_r = di->rect();
                    int dx = 0;
                    int dy = 0;

                    if (di_r.left() < r.left()) {
                        dx = r.left() - di_r.left();

                        if (dx > resize_left)
                            resize_left = dx;
                    }

                    if (di_r.right() > r.right()) {
                        dx = di_r.right() - r.right();

                        if (dx > resize_right)
                            resize_right = dx;
                    }

                    if (di_r.top() < r.top()) {
                        dy = r.top() - di_r.top();

                        if (dy > resize_top)
                            resize_top = dy;
                    }

                    if (di_r.bottom() > r.bottom()) {
                        dy = di_r.bottom() - r.bottom();

                        if (dy > resize_bottom)
                            resize_bottom = dy;
                    }
                }

                need_sub_upper |= ((*cit)->zValue() <= zValue());
                break;

                default:
                    break;
                }
            }
        }
    }

    int dx = 0;
    int dy = 0;
    int dw = 0;
    int dh = 0;

    if (resize_top != 0) {
        dy = -resize_top;
        dh = resize_top;
    }

    if (resize_bottom != 0)
        dh += resize_bottom;

    if (resize_left != 0) {
        dx = -resize_left;
        dw = resize_left;
    }

    if (resize_right != 0)
        dw += resize_right;

    if ((dx != 0) || (dy != 0)) {
        moveBy(dx, dy);
        moveSelfRelsBy(dx, dy);
    }

    if ((dw != 0) || (dh != 0))
        DiagramCanvas::resize(width() + dw, height() + dh);
}
QRegion QWSDefaultDecoration::region(const QWidget *widget, const QRect &rect, QWSDecoration::Region type)
{
//    int titleWidth = getTitleWidth(widget);
    int titleHeight = getTitleHeight(widget);

    QRegion region;

    int bw = BORDER_WIDTH;

    switch (type) {
	case All: {
		if ( widget->isMaximized() ) {
		    QRect r(rect.left(), rect.top() - titleHeight,
			    rect.width(), rect.height() + titleHeight);
		    region = r;
		} else {
		    QRect r(rect.left() - bw,
			    rect.top() - titleHeight - bw,
			    rect.width() + 2 * bw,
			    rect.height() + titleHeight + 2 * bw);
		    region = r;
		}
		region -= rect;
	    }
	    break;

	case Title: {
		    QRect r(rect.left() + titleHeight, rect.top() - titleHeight,
			    rect.width() - 4*titleHeight, titleHeight);
		    if (r.width() > 0)
			region = r;
	    }
	    break;

	case Top: {
		    QRect r(rect.left() + CORNER_GRAB,
			    rect.top() - titleHeight - bw,
			    rect.width() - 2 * CORNER_GRAB,
			    bw);
		    region = r;
	    }
	    break;

	case Left: {
		QRect r(rect.left() - bw,
			rect.top() - titleHeight + CORNER_GRAB,
			bw,
			rect.height() + titleHeight - 2 * CORNER_GRAB);
		region = r;
	    }
	    break;

	case Right: {
		QRect r(rect.right() + 1,
			rect.top() - titleHeight + CORNER_GRAB,
			bw,
			rect.height() + titleHeight - 2 * CORNER_GRAB);
		region = r;
	    }
	    break;

	case Bottom: {
		QRect r(rect.left() + CORNER_GRAB,
			rect.bottom() + 1,
			rect.width() - 2 * CORNER_GRAB,
			bw);
		region = r;
	    }
	    break;

	case TopLeft: {
		QRect r1(rect.left() - bw,
			rect.top() - bw - titleHeight,
			CORNER_GRAB + bw,
			bw);

		QRect r2(rect.left() - bw,
			rect.top() - bw - titleHeight,
			bw,
			CORNER_GRAB + bw);

		region = QRegion(r1) + r2;
	    }
	    break;

	case TopRight: {
		QRect r1(rect.right() - CORNER_GRAB,
			rect.top() - bw - titleHeight,
			CORNER_GRAB + bw,
			bw);

		QRect r2(rect.right() + 1,
			rect.top() - bw - titleHeight,
			bw,
			CORNER_GRAB + bw);

		region = QRegion(r1) + r2;
	    }
	    break;

	case BottomLeft: {
		QRect r1(rect.left() - bw,
			rect.bottom() + 1,
			CORNER_GRAB + bw,
			bw);

		QRect r2(rect.left() - bw,
			rect.bottom() - CORNER_GRAB,
			bw,
			CORNER_GRAB + bw);
		region = QRegion(r1) + r2;
	    }
	    break;

	case BottomRight: {
		QRect r1(rect.right() - CORNER_GRAB,
			rect.bottom() + 1,
			CORNER_GRAB + bw,
			bw);

		QRect r2(rect.right() + 1,
			rect.bottom() - CORNER_GRAB,
			bw,
			CORNER_GRAB + bw);
		region = QRegion(r1) + r2;
	    }
	    break;

	case Menu: {
		    QRect r(rect.left(), rect.top() - titleHeight,
			    titleHeight, titleHeight);
		    region = r;
	    }
	    break;

	case Close: {
		QRect r(rect.right() - titleHeight, rect.top() - titleHeight,
			titleHeight, titleHeight);
		if (r.left() > rect.left() + titleHeight)
		    region = r;
	    }
	    break;

	case Maximize: {
		QRect r(rect.right() - 2*titleHeight, rect.top() - titleHeight,
			titleHeight, titleHeight);
		if (r.left() > rect.left() + titleHeight)
		    region = r;
	    }
	    break;

	case Minimize: {
		QRect r(rect.right() - 3*titleHeight, rect.top() - titleHeight,
			titleHeight, titleHeight);
		if (r.left() > rect.left() + titleHeight)
		    region = r;
	    }
	    break;

	default:
	    break;
    }

    return region;
}
Example #23
0
void qDrawBorderPixmap(QPainter *painter, const QRect &targetRect, const QMargins &targetMargins,
                       const QPixmap &pixmap, const QRect &sourceRect,const QMargins &sourceMargins,
                       const QTileRules &rules, QDrawBorderPixmap::DrawingHints hints)
{
    QPainter::PixmapFragment d;
    d.opacity = 1.0;
    d.rotation = 0.0;

    QPixmapFragmentsArray opaqueData;
    QPixmapFragmentsArray translucentData;

    // source center
    const int sourceCenterTop = sourceRect.top() + sourceMargins.top();
    const int sourceCenterLeft = sourceRect.left() + sourceMargins.left();
    const int sourceCenterBottom = sourceRect.bottom() - sourceMargins.bottom() + 1;
    const int sourceCenterRight = sourceRect.right() - sourceMargins.right() + 1;
    const int sourceCenterWidth = sourceCenterRight - sourceCenterLeft;
    const int sourceCenterHeight = sourceCenterBottom - sourceCenterTop;
    // target center
    const int targetCenterTop = targetRect.top() + targetMargins.top();
    const int targetCenterLeft = targetRect.left() + targetMargins.left();
    const int targetCenterBottom = targetRect.bottom() - targetMargins.bottom() + 1;
    const int targetCenterRight = targetRect.right() - targetMargins.right() + 1;
    const int targetCenterWidth = targetCenterRight - targetCenterLeft;
    const int targetCenterHeight = targetCenterBottom - targetCenterTop;

    QVarLengthArray<qreal, 16> xTarget; // x-coordinates of target rectangles
    QVarLengthArray<qreal, 16> yTarget; // y-coordinates of target rectangles

    int columns = 3;
    int rows = 3;
    if (rules.horizontal != Qt::StretchTile && sourceCenterWidth != 0)
        columns = qMax(3, 2 + qCeil(targetCenterWidth / qreal(sourceCenterWidth)));
    if (rules.vertical != Qt::StretchTile && sourceCenterHeight != 0)
        rows = qMax(3, 2 + qCeil(targetCenterHeight / qreal(sourceCenterHeight)));

    xTarget.resize(columns + 1);
    yTarget.resize(rows + 1);

    bool oldAA = painter->testRenderHint(QPainter::Antialiasing);
    if (painter->paintEngine()->type() != QPaintEngine::OpenGL
        && painter->paintEngine()->type() != QPaintEngine::OpenGL2
        && oldAA && painter->combinedTransform().type() != QTransform::TxNone) {
        painter->setRenderHint(QPainter::Antialiasing, false);
    }

    xTarget[0] = targetRect.left();
    xTarget[1] = targetCenterLeft;
    xTarget[columns - 1] = targetCenterRight;
    xTarget[columns] = targetRect.left() + targetRect.width();

    yTarget[0] = targetRect.top();
    yTarget[1] = targetCenterTop;
    yTarget[rows - 1] = targetCenterBottom;
    yTarget[rows] = targetRect.top() + targetRect.height();

    qreal dx = targetCenterWidth;
    qreal dy = targetCenterHeight;

    switch (rules.horizontal) {
    case Qt::StretchTile:
        dx = targetCenterWidth;
        break;
    case Qt::RepeatTile:
        dx = sourceCenterWidth;
        break;
    case Qt::RoundTile:
        dx = targetCenterWidth / qreal(columns - 2);
        break;
    }

    for (int i = 2; i < columns - 1; ++i)
        xTarget[i] = xTarget[i - 1] + dx;

    switch (rules.vertical) {
    case Qt::StretchTile:
        dy = targetCenterHeight;
        break;
    case Qt::RepeatTile:
        dy = sourceCenterHeight;
        break;
    case Qt::RoundTile:
        dy = targetCenterHeight / qreal(rows - 2);
        break;
    }

    for (int i = 2; i < rows - 1; ++i)
        yTarget[i] = yTarget[i - 1] + dy;

    // corners
    if (targetMargins.top() > 0 && targetMargins.left() > 0 && sourceMargins.top() > 0 && sourceMargins.left() > 0) { // top left
        d.x = (0.5 * (xTarget[1] + xTarget[0]));
        d.y = (0.5 * (yTarget[1] + yTarget[0]));
        d.sourceLeft = sourceRect.left();
        d.sourceTop = sourceRect.top();
        d.width = sourceMargins.left();
        d.height = sourceMargins.top();
        d.scaleX = qreal(xTarget[1] - xTarget[0]) / d.width;
        d.scaleY = qreal(yTarget[1] - yTarget[0]) / d.height;
        if (hints & QDrawBorderPixmap::OpaqueTopLeft)
            opaqueData.append(d);
        else
            translucentData.append(d);
    }
    if (targetMargins.top() > 0 && targetMargins.right() > 0 && sourceMargins.top() > 0 && sourceMargins.right() > 0) { // top right
        d.x = (0.5 * (xTarget[columns] + xTarget[columns - 1]));
        d.y = (0.5 * (yTarget[1] + yTarget[0]));
        d.sourceLeft = sourceCenterRight;
        d.sourceTop = sourceRect.top();
        d.width = sourceMargins.right();
        d.height = sourceMargins.top();
        d.scaleX = qreal(xTarget[columns] - xTarget[columns - 1]) / d.width;
        d.scaleY = qreal(yTarget[1] - yTarget[0]) / d.height;
        if (hints & QDrawBorderPixmap::OpaqueTopRight)
            opaqueData.append(d);
        else
            translucentData.append(d);
    }
    if (targetMargins.bottom() > 0 && targetMargins.left() > 0 && sourceMargins.bottom() > 0 && sourceMargins.left() > 0) { // bottom left
        d.x = (0.5 * (xTarget[1] + xTarget[0]));
        d.y =(0.5 * (yTarget[rows] + yTarget[rows - 1]));
        d.sourceLeft = sourceRect.left();
        d.sourceTop = sourceCenterBottom;
        d.width = sourceMargins.left();
        d.height = sourceMargins.bottom();
        d.scaleX = qreal(xTarget[1] - xTarget[0]) / d.width;
        d.scaleY = qreal(yTarget[rows] - yTarget[rows - 1]) / d.height;
        if (hints & QDrawBorderPixmap::OpaqueBottomLeft)
            opaqueData.append(d);
        else
            translucentData.append(d);
    }
    if (targetMargins.bottom() > 0 && targetMargins.right() > 0 && sourceMargins.bottom() > 0 && sourceMargins.right() > 0) { // bottom right
        d.x = (0.5 * (xTarget[columns] + xTarget[columns - 1]));
        d.y = (0.5 * (yTarget[rows] + yTarget[rows - 1]));
        d.sourceLeft = sourceCenterRight;
        d.sourceTop = sourceCenterBottom;
        d.width = sourceMargins.right();
        d.height = sourceMargins.bottom();
        d.scaleX = qreal(xTarget[columns] - xTarget[columns - 1]) / d.width;
        d.scaleY = qreal(yTarget[rows] - yTarget[rows - 1]) / d.height;
        if (hints & QDrawBorderPixmap::OpaqueBottomRight)
            opaqueData.append(d);
        else
            translucentData.append(d);
    }

    // horizontal edges
    if (targetCenterWidth > 0 && sourceCenterWidth > 0) {
        if (targetMargins.top() > 0 && sourceMargins.top() > 0) { // top
            QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueTop ? opaqueData : translucentData;
            d.sourceLeft = sourceCenterLeft;
            d.sourceTop = sourceRect.top();
            d.width = sourceCenterWidth;
            d.height = sourceMargins.top();
            d.y = (0.5 * (yTarget[1] + yTarget[0]));
            d.scaleX = dx / d.width;
            d.scaleY = qreal(yTarget[1] - yTarget[0]) / d.height;
            for (int i = 1; i < columns - 1; ++i) {
                d.x = (0.5 * (xTarget[i + 1] + xTarget[i]));
                data.append(d);
            }
            if (rules.horizontal == Qt::RepeatTile)
                data[data.size() - 1].width = ((xTarget[columns - 1] - xTarget[columns - 2]) / d.scaleX);
        }
        if (targetMargins.bottom() > 0 && sourceMargins.bottom() > 0) { // bottom
            QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueBottom ? opaqueData : translucentData;
            d.sourceLeft = sourceCenterLeft;
            d.sourceTop = sourceCenterBottom;
            d.width = sourceCenterWidth;
            d.height = sourceMargins.bottom();
            d.y = (0.5 * (yTarget[rows] + yTarget[rows - 1]));
            d.scaleX = dx / d.width;
            d.scaleY = qreal(yTarget[rows] - yTarget[rows - 1]) / d.height;
            for (int i = 1; i < columns - 1; ++i) {
                d.x = (0.5 * (xTarget[i + 1] + xTarget[i]));
                data.append(d);
            }
            if (rules.horizontal == Qt::RepeatTile)
                data[data.size() - 1].width = ((xTarget[columns - 1] - xTarget[columns - 2]) / d.scaleX);
        }
    }

    // vertical edges
    if (targetCenterHeight > 0 && sourceCenterHeight > 0) {
        if (targetMargins.left() > 0 && sourceMargins.left() > 0) { // left
            QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueLeft ? opaqueData : translucentData;
            d.sourceLeft = sourceRect.left();
            d.sourceTop = sourceCenterTop;
            d.width = sourceMargins.left();
            d.height = sourceCenterHeight;
            d.x = (0.5 * (xTarget[1] + xTarget[0]));
            d.scaleX = qreal(xTarget[1] - xTarget[0]) / d.width;
            d.scaleY = dy / d.height;
            for (int i = 1; i < rows - 1; ++i) {
                d.y = (0.5 * (yTarget[i + 1] + yTarget[i]));
                data.append(d);
            }
            if (rules.vertical == Qt::RepeatTile)
                data[data.size() - 1].height = ((yTarget[rows - 1] - yTarget[rows - 2]) / d.scaleY);
        }
        if (targetMargins.right() > 0 && sourceMargins.right() > 0) { // right
            QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueRight ? opaqueData : translucentData;
            d.sourceLeft = sourceCenterRight;
            d.sourceTop = sourceCenterTop;
            d.width = sourceMargins.right();
            d.height = sourceCenterHeight;
            d.x = (0.5 * (xTarget[columns] + xTarget[columns - 1]));
            d.scaleX = qreal(xTarget[columns] - xTarget[columns - 1]) / d.width;
            d.scaleY = dy / d.height;
            for (int i = 1; i < rows - 1; ++i) {
                d.y = (0.5 * (yTarget[i + 1] + yTarget[i]));
                data.append(d);
            }
            if (rules.vertical == Qt::RepeatTile)
                data[data.size() - 1].height = ((yTarget[rows - 1] - yTarget[rows - 2]) / d.scaleY);
        }
    }

    // center
    if (targetCenterWidth > 0 && targetCenterHeight > 0 && sourceCenterWidth > 0 && sourceCenterHeight > 0) {
        QPixmapFragmentsArray &data = hints & QDrawBorderPixmap::OpaqueCenter ? opaqueData : translucentData;
        d.sourceLeft = sourceCenterLeft;
        d.sourceTop = sourceCenterTop;
        d.width = sourceCenterWidth;
        d.height = sourceCenterHeight;
        d.scaleX = dx / d.width;
        d.scaleY = dy / d.height;

        qreal repeatWidth = (xTarget[columns - 1] - xTarget[columns - 2]) / d.scaleX;
        qreal repeatHeight = (yTarget[rows - 1] - yTarget[rows - 2]) / d.scaleY;

        for (int j = 1; j < rows - 1; ++j) {
            d.y = (0.5 * (yTarget[j + 1] + yTarget[j]));
            for (int i = 1; i < columns - 1; ++i) {
                d.x = (0.5 * (xTarget[i + 1] + xTarget[i]));
                data.append(d);
            }
            if (rules.horizontal == Qt::RepeatTile)
                data[data.size() - 1].width = repeatWidth;
        }
        if (rules.vertical == Qt::RepeatTile) {
            for (int i = 1; i < columns - 1; ++i)
                data[data.size() - i].height = repeatHeight;
        }
    }

    if (opaqueData.size())
        painter->drawPixmapFragments(opaqueData.data(), opaqueData.size(), pixmap, QPainter::OpaqueHint);
    if (translucentData.size())
        painter->drawPixmapFragments(translucentData.data(), translucentData.size(), pixmap);

    if (oldAA)
        painter->setRenderHint(QPainter::Antialiasing, true);
}
void PlaylistItemDelegate::paintBody(QPainter *painter,
                                     const QStyleOptionViewItem &option,
                                     const QModelIndex &index) const {
    const bool isSelected = option.state & QStyle::State_Selected;
    if (isSelected)
        QApplication::style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter);

    painter->save();
    painter->translate(option.rect.topLeft());

    QRect line(0, 0, option.rect.width(), option.rect.height());
    if (downloadInfo) line.setWidth(line.width() / 2);

    const bool isActive = index.data(ActiveTrackRole).toBool();

    // get the video metadata
    const Video *video = index.data(VideoRole).value<VideoPointer>().data();

    // draw the "current track" highlight underneath the text
    if (isActive && !isSelected) paintActiveOverlay(painter, option, line);

    // thumb
    const QPixmap &thumb = video->getThumbnail();
    if (!thumb.isNull()) {
        painter->drawPixmap(0, 0, thumb);
        if (video->getDuration() > 0) drawTime(painter, video->getFormattedDuration(), line);
    }

    const bool thumbsOnly = line.width() <= thumbWidth + 60;
    const bool isHovered = index.data(HoveredItemRole).toBool();

    // play icon overlayed on the thumb
    bool needPlayIcon = isActive;
    if (thumbsOnly) needPlayIcon = needPlayIcon && !isHovered;
    if (needPlayIcon) painter->drawPixmap(0, 0, playIcon);

    if (!thumbsOnly) {
        // text color
        if (isSelected)
            painter->setPen(QPen(option.palette.highlightedText(), 0));
        else
            painter->setPen(QPen(option.palette.text(), 0));

        // title
        QStringRef title(&video->getTitle());
        QString elidedTitle = video->getTitle();
        static const int titleFlags = Qt::AlignTop | Qt::TextWordWrap;
        QRect textBox = line.adjusted(padding + thumbWidth, padding, -padding, 0);
        textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
        while (textBox.height() > 55 && elidedTitle.length() > 10) {
#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
            title = title.left(title.length() - 1);
#elif QT_VERSION < QT_VERSION_CHECK(5, 8, 0)
            title.truncate(title.length() - 1);
#else
            title.chop(1);
#endif
            elidedTitle = title.trimmed() + QStringLiteral("…");
            textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
        }
        painter->drawText(textBox, titleFlags, elidedTitle);

        painter->setFont(smallerFont);
        painter->setOpacity(.5);
        QFontMetrics fontMetrics = painter->fontMetrics();
        static const int flags = Qt::AlignLeft | Qt::AlignTop;

        // published date
        const QString &published = video->getFormattedPublished();
        QSize textSize(fontMetrics.size(Qt::TextSingleLine, published));
        QPoint textPoint(padding + thumbWidth, padding * 2 + textBox.height());
        textBox = QRect(textPoint, textSize);
        painter->drawText(textBox, flags, published);

        bool elided = false;

        // author
        if (!listView || listView->isClickableAuthors()) {
            bool authorHovered = isHovered && index.data(AuthorHoveredRole).toBool();

            painter->save();
            painter->setFont(smallerBoldFont);
            if (!isSelected) {
                if (authorHovered)
                    painter->setPen(QPen(option.palette.brush(QPalette::Highlight), 0));
            }
            const QString &author = video->getChannelTitle();
            textPoint.setX(textBox.right() + padding);
            textSize = QSize(painter->fontMetrics().size(Qt::TextSingleLine, author));
            textBox = QRect(textPoint, textSize);
            authorRects.insert(index.row(), textBox);
            if (textBox.right() > line.width() - padding) {
                textBox.setRight(line.width());
                elided = drawElidedText(painter, textBox, flags, author);
            } else {
                painter->drawText(textBox, flags, author);
            }
            painter->restore();
        }

        // view count
        if (video->getViewCount() > 0) {
            const QString &viewCount = video->getFormattedViewCount();
            textPoint.setX(textBox.right() + padding);
            textSize = QSize(fontMetrics.size(Qt::TextSingleLine, viewCount));
            if (elided || textPoint.x() + textSize.width() > line.width() - padding) {
                textPoint.setX(thumbWidth + padding);
                textPoint.setY(textPoint.y() + textSize.height() + padding);
            }
            textBox = QRect(textPoint, textSize);
            if (textBox.bottom() <= line.height()) {
                painter->drawText(textBox, flags, viewCount);
            }
        }

        if (downloadInfo) {
            const QString &def = VideoDefinition::forCode(video->getDefinitionCode()).getName();
            textPoint.setX(textBox.right() + padding);
            textSize = QSize(fontMetrics.size(Qt::TextSingleLine, def));
            textBox = QRect(textPoint, textSize);
            painter->drawText(textBox, flags, def);
        }

    } else {
        // thumbs only
        if (isHovered) {
            painter->setFont(smallerFont);
            painter->setPen(Qt::white);
            QStringRef title(&video->getTitle());
            QString elidedTitle = video->getTitle();
            static const int titleFlags = Qt::AlignTop | Qt::TextWordWrap;
            QRect textBox(padding, padding, thumbWidth - padding * 2, thumbHeight - padding * 2);
            textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
            while (textBox.height() > 55 && elidedTitle.length() > 10) {
#if QT_VERSION < QT_VERSION_CHECK(5, 6, 0)
                title = title.left(title.length() - 1);
#elif QT_VERSION < QT_VERSION_CHECK(5, 8, 0)
                title.truncate(title.length() - 1);
#else
                title.chop(1);
#endif
                elidedTitle = title.trimmed() + QStringLiteral("…");
                textBox = painter->boundingRect(textBox, titleFlags, elidedTitle);
            }
            painter->fillRect(QRect(0, 0, thumbWidth, textBox.height() + padding * 2),
                              QColor(0, 0, 0, 128));
            painter->drawText(textBox, titleFlags, elidedTitle);
        }
    }

    painter->restore();

    if (downloadInfo) paintDownloadInfo(painter, option, index);
}
Example #25
0
void KisTextureTile::update(const KisTextureTileUpdateInfo &updateInfo)
{
    glBindTexture(GL_TEXTURE_2D, m_textureId);

    setTextureParameters();

    const GLvoid *fd = updateInfo.data();
#ifdef USE_PIXEL_BUFFERS
    KisConfig cfg;
    if (!m_glBuffer) {
        QByteArray ba;
        ba.fromRawData((const char*)updateInfo.data(), updateInfo.patchPixelsLength());
        createTextureBuffer(ba);
    }
#endif

    if (updateInfo.isEntireTileUpdated()) {

#ifdef USE_PIXEL_BUFFERS

        if (cfg.useOpenGLTextureBuffer()) {

            m_glBuffer->bind();
            m_glBuffer->allocate(updateInfo.patchPixelsLength());

            void *vid = m_glBuffer->map(QGLBuffer::WriteOnly);
            memcpy(vid, fd, updateInfo.patchPixelsLength());
            m_glBuffer->unmap();

            // we set fill data to 0 so the next glTexImage2D call uses our buffer
            fd = 0;
        }
#endif

        glTexImage2D(GL_TEXTURE_2D, 0,
                     m_texturesInfo->internalFormat,
                     m_texturesInfo->width,
                     m_texturesInfo->height, 0,
                     m_texturesInfo->format,
                     m_texturesInfo->type,
                     fd);

#ifdef USE_PIXEL_BUFFERS
        if (cfg.useOpenGLTextureBuffer()) {
            m_glBuffer->release();
        }
#endif

    }
    else {
        QPoint patchOffset = updateInfo.patchOffset();
        QSize patchSize = updateInfo.patchSize();

#ifdef USE_PIXEL_BUFFERS
        if (cfg.useOpenGLTextureBuffer()) {
            m_glBuffer->bind();
            quint32 size = patchSize.width() * patchSize.height() * updateInfo.pixelSize();
            m_glBuffer->allocate(size);

            void *vid = m_glBuffer->map(QGLBuffer::WriteOnly);
            memcpy(vid, fd, size);
            m_glBuffer->unmap();

            // we set fill data to 0 so the next glTexImage2D call uses our buffer
            fd = 0;
        }
#endif

        glTexSubImage2D(GL_TEXTURE_2D, 0,
                        patchOffset.x(), patchOffset.y(),
                        patchSize.width(), patchSize.height(),
                        m_texturesInfo->format,
                        m_texturesInfo->type,
                        fd);

#ifdef USE_PIXEL_BUFFERS
        if (cfg.useOpenGLTextureBuffer()) {
            m_glBuffer->release();
        }
#endif

    }

    /**
     * On the boundaries of KisImage, there is a border-effect as well.
     * So we just repeat the bounding pixels of the image to make
     * bilinear interpolator happy.
     */

    /**
     * WARN: The width of the stripes will be equal to the broder
     *       width of the tiles.
     */

    const int pixelSize = updateInfo.pixelSize();
    const QRect imageRect = updateInfo.imageRect();
    const QPoint patchOffset = updateInfo.patchOffset();
    const QSize patchSize = updateInfo.patchSize();
    const QRect patchRect = QRect(m_textureRectInImagePixels.topLeft() +
                                  patchOffset,
                                  patchSize);
    const QSize tileSize = updateInfo.tileRect().size();


    if(imageRect.top() == patchRect.top()) {
        int start = 0;
        int end = patchOffset.y() - 1;
        for (int i = start; i <= end; i++) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                            patchOffset.x(), i,
                            patchSize.width(), 1,
                            m_texturesInfo->format,
                            m_texturesInfo->type,
                            updateInfo.data());
        }
    }

    if (imageRect.bottom() == patchRect.bottom()) {
        int shift = patchSize.width() * (patchSize.height() - 1) *
                    pixelSize;

        int start = patchOffset.y() + patchSize.height();
        int end = tileSize.height() - 1;
        for (int i = start; i < end; i++) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                            patchOffset.x(), i,
                            patchSize.width(), 1,
                            m_texturesInfo->format,
                            m_texturesInfo->type,
                            updateInfo.data() + shift);
        }
    }

    if (imageRect.left() == patchRect.left()) {

        QByteArray columnBuffer(patchSize.height() * pixelSize, 0);

        quint8 *srcPtr = updateInfo.data();
        quint8 *dstPtr = (quint8*) columnBuffer.data();
        for(int i = 0; i < patchSize.height(); i++) {
            memcpy(dstPtr, srcPtr, pixelSize);

            srcPtr += patchSize.width() * pixelSize;
            dstPtr += pixelSize;
        }

        int start = 0;
        int end = patchOffset.x() - 1;
        for (int i = start; i <= end; i++) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                            i, patchOffset.y(),
                            1, patchSize.height(),
                            m_texturesInfo->format,
                            m_texturesInfo->type,
                            columnBuffer.constData());
        }
    }

    if (imageRect.right() == patchRect.right()) {

        QByteArray columnBuffer(patchSize.height() * pixelSize, 0);

        quint8 *srcPtr = updateInfo.data() + (patchSize.width() - 1) * pixelSize;
        quint8 *dstPtr = (quint8*) columnBuffer.data();
        for(int i = 0; i < patchSize.height(); i++) {
            memcpy(dstPtr, srcPtr, pixelSize);

            srcPtr += patchSize.width() * pixelSize;
            dstPtr += pixelSize;
        }

        int start = patchOffset.x() + patchSize.width();
        int end = tileSize.width() - 1;
        for (int i = start; i <= end; i++) {
            glTexSubImage2D(GL_TEXTURE_2D, 0,
                            i, patchOffset.y(),
                            1, patchSize.height(),
                            m_texturesInfo->format,
                            m_texturesInfo->type,
                            columnBuffer.constData());
        }
    }

    setNeedsMipmapRegeneration();
}
Example #26
0
void pTreeComboBox::calculPopupGeometry()
{
    if ( !mView ) {
        return;
    }
    
    QStyle * const style = this->style();

    // set current item and select it
    view()->selectionModel()->setCurrentIndex( mCurrentIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
    QFrame* container = mFrame;
    QStyleOptionComboBox opt;
    initStyleOption( &opt );
    QRect listRect( style->subControlRect( QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxListBoxPopup, this ) );
    QRect screen = popupGeometry( QApplication::desktop()->screenNumber( this ) );
    QPoint below = mapToGlobal( listRect.bottomLeft() );
    int belowHeight = screen.bottom() -below.y();
    QPoint above = mapToGlobal( listRect.topLeft() );
    int aboveHeight = above.y() -screen.y();
    bool boundToScreen = !window()->testAttribute( Qt::WA_DontShowOnScreen );
    
    listRect.moveTopLeft( mapToGlobal( rect().bottomLeft() ) );
    listRect.setSize( QSize( 
        qMax( qMax( view()->viewport()->width(), mFrame->width() ), width() )
        ,
        qMax( view()->viewport()->height(), mFrame->height() )
    ) );

    const bool usePopup = style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this );
    {
        int listHeight = 0;
        int count = 0;
        QStack<QModelIndex> toCheck;
        toCheck.push( view()->rootIndex() );
#ifndef QT_NO_TREEVIEW
        QTreeView* treeView = qobject_cast<QTreeView*>( view() );
        if ( treeView && treeView->header() && !treeView->header()->isHidden() )
            listHeight += treeView->header()->height();
#endif
        while ( !toCheck.isEmpty() ) {
            QModelIndex parent = toCheck.pop();
            for ( int i = 0; i < model()->rowCount( parent ); ++i ) {
                QModelIndex idx = model()->index( i, mModelColumn, parent );
                if ( !idx.isValid() )
                    continue;
                listHeight += view()->visualRect( idx ).height();
#ifndef QT_NO_TREEVIEW
                if ( model()->hasChildren( idx ) && treeView && treeView->isExpanded( idx ) )
                    toCheck.push( idx );
#endif
                ++count;
                if ( !usePopup && count > mMaxVisibleItems ) {
                    toCheck.clear();
                    break;
                }
            }
        }
        listRect.setHeight( listHeight );
    }

    {
        // add the spacing for the grid on the top and the bottom;
        int heightMargin = 0;

        // add the frame of the container
        int marginTop, marginBottom;
        container->getContentsMargins( 0, &marginTop, 0, &marginBottom );
        heightMargin += marginTop +marginBottom;

        //add the frame of the view
        view()->getContentsMargins( 0, &marginTop, 0, &marginBottom );
        marginTop += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top*/;
        marginBottom += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom*/;
        heightMargin += marginTop +marginBottom;

        listRect.setHeight( listRect.height() +heightMargin );
    }

    // Add space for margin at top and bottom if the style wants it.
    if ( usePopup )
        listRect.setHeight( listRect.height() +style->pixelMetric( QStyle::PM_MenuVMargin, &opt, this ) *2 );

    // Make sure the popup is wide enough to display its contents.
    if ( usePopup ) {
        const int diff = sizeHint().width() /*d->computeWidthHint()*/ -width();
        if ( diff > 0 )
            listRect.setWidth( listRect.width() +diff );
    }

    //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
    container->layout()->activate();
    //takes account of the minimum/maximum size of the container
    listRect.setSize( listRect.size().expandedTo(container->minimumSize())
                      .boundedTo(container->maximumSize()));

    // make sure the widget fits on screen
    if (boundToScreen) {
        if (listRect.width() > screen.width() )
            listRect.setWidth(screen.width());
        if (/*mapToGlobal(*/listRect/*.bottomRight())*/.x() > screen.right()) {
            below.setX(screen.x() + screen.width() - listRect.width());
            above.setX(screen.x() + screen.width() - listRect.width());
        }
        if (/*mapToGlobal(*/listRect/*.topLeft())*/.x() < screen.x() ) {
            below.setX(screen.x());
            above.setX(screen.x());
        }
    }

    if ( usePopup ) {
        // Position horizontally.
        listRect.moveLeft( above.x() );

        // Position vertically so the curently selected item lines up
        // with the combo box.
        /*const QRect currentItemRect = view()->visualRect( view()->currentIndex() );
        const int offset = listRect.top() -currentItemRect.top();
        listRect.moveTop( above.y() +offset -listRect.top() );*/

        // Clamp the listRect height and vertical position so we don't expand outside the
        // available screen geometry.This may override the vertical position, but it is more
        // important to show as much as possible of the popup.
        const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
        listRect.setHeight(height);
        if (boundToScreen) {
            if (listRect.top() < screen.top())
                listRect.moveTop(screen.top());
            if (listRect.bottom() > screen.bottom())
                listRect.moveBottom(screen.bottom());
        }
    } else if (!boundToScreen || listRect.height() <= belowHeight) {
        listRect.moveTopLeft(below);
    } else if (listRect.height() <= aboveHeight) {
        listRect.moveBottomLeft(above);
    } else if (belowHeight >= aboveHeight) {
        listRect.setHeight(belowHeight);
        listRect.moveTopLeft(below);
    } else {
        listRect.setHeight(aboveHeight);
        listRect.moveBottomLeft(above);
    }

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#ifndef QT_NO_IM
    if ( QInputContext *qic = inputContext() )
        qic->reset();
#endif
#endif
    QScrollBar* sb = view()->horizontalScrollBar();
    Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy();
    bool needHorizontalScrollBar = ( policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn ) && sb->minimum() < sb->maximum();
    if ( needHorizontalScrollBar ) {
        listRect.adjust( 0, 0, 0, sb->height() );
    }
    
    container->setGeometry( listRect );

#ifndef Q_WS_MAC
    const bool updatesEnabled = container->updatesEnabled();
#endif

#if defined( Q_WS_WIN ) && !defined( QT_NO_EFFECTS )
// FIXME Fix me ASAP
    /*bool scrollDown = ( listRect.topLeft() == below );
    if ( QApplication::isEffectEnabled( Qt::UI_AnimateCombo ) 
        && !style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) && !window()->testAttribute( Qt::WA_DontShowOnScreen ) )
        qScrollEffect( container, scrollDown ? QEffects::DownScroll : QEffects::UpScroll, 150 );*/
#endif

// Don't disable updates on Mac OS X. Windows are displayed immediately on this platform,
// which means that the window will be visible before the call to container->show() returns.
// If updates are disabled at this point we'll miss our chance at painting the popup 
// menu before it's shown, causing flicker since the window then displays the standard gray 
// background.
#ifndef Q_WS_MAC
    container->setUpdatesEnabled( false );
#endif

    container->raise();
    container->show();
    //container->updateScrollers();
    view()->setFocus();

    view()->scrollTo( view()->currentIndex(), style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) ? QAbstractItemView::PositionAtCenter : QAbstractItemView::EnsureVisible );

#ifndef Q_WS_MAC
    container->setUpdatesEnabled( updatesEnabled );
#endif

    container->update();
#ifdef QT_KEYPAD_NAVIGATION
    if ( QApplication::keypadNavigationEnabled() )
        view()->setEditFocus( true );
#endif
}
Example #27
0
/*!
  \brief Draw the marker
  \param p Painter
  \param x X position
  \param y Y position
  \param r Bounding rectangle
*/
void QwtMarker::draw(QPainter *p, int x, int y, const QRect &r)
{
    // draw lines
    if (d_style != NoLine)
    {
        p->setPen(d_pen);
        if ((d_style == HLine) || (d_style == Cross))
            p->drawLine(r.left(), y, r.right(), y);
        if ((d_style == VLine)||(d_style == Cross))
            p->drawLine(x, r.top(), x, r.bottom());
    }

    // draw symbol
    QSize sSym;
    if (d_sym.style() != QwtSymbol::None)
    {
        sSym = d_sym.size();
        d_sym.draw(p, x - (sSym.width() - 1) / 2 ,y - (sSym.width() - 1) / 2);
    }
    else
    {
        sSym.setWidth(0);
        sSym.setHeight(0);
    }
    

    // draw label
    if (!d_label.isEmpty())
    {
        p->setPen(d_tPen);
        p->setFont(d_font);

        const int th = p->fontMetrics().height();
        const int tw = p->fontMetrics().width(d_label);
        int lw = qwtMax(int(d_pen.width()), 1);
        int lw1;

        if ((d_style == VLine) || (d_style == HLine))
        {
            lw1 = (lw + 1) / 2 + LabelDist;
            lw = lw / 2 + LabelDist;
        }
        else 
        {
            lw1 = qwtMax((lw + 1) / 2, (sSym.width() + 1) / 2) + LabelDist;
            lw = qwtMax(lw / 2, (sSym.width() + 1) / 2) + LabelDist;
        }

        
        QRect tr;
        if (d_style == VLine)
        {
            if (d_align & (int) Qt::AlignTop)
               tr.setY(r.top() + LabelDist);
            else if (d_align & (int) Qt::AlignBottom)
               tr.setY(r.bottom() - LabelDist - th);
            else
               tr.setY(r.top() + (r.bottom() - r.top()) / 2);
        }
        else 
        {
            if (d_align & (int) Qt::AlignTop)
               tr.setY(y - lw - th);
            else if (d_align & (int) Qt::AlignBottom)
               tr.setY(y + lw1);
            else
               tr.setY(y - th/2);
        }


        if (d_style == HLine)
        {
            if (d_align & (int) Qt::AlignLeft)
               tr.setX(r.left() + LabelDist);
            else if (d_align & (int) Qt::AlignRight)
               tr.setX(r.right() - tw - LabelDist);
            else
               tr.setX(r.left() + (r.right() - r.left()) / 2);
        }
        else
        {
            if (d_align & (int) Qt::AlignLeft)
               tr.setX(x - tw - lw);
            else if (d_align & (int) Qt::AlignRight)
               tr.setX(x + lw1);
            else
               tr.setX(x - tw/ 2);
        }

        tr.setHeight(th);
        tr.setWidth(tw);    

        p->drawText(tr, Qt::AlignTop|Qt::AlignHCenter, d_label); 
    }
}
Example #28
0
QImage MorphologyEffect::processImage(const QImage &image, const KoFilterEffectRenderContext &context) const
{
    QImage result = image;

    QPointF radius = context.toUserSpace(m_radius);

    const int rx = static_cast<int>(ceil(radius.x()));
    const int ry = static_cast<int>(ceil(radius.y()));

    const int w = result.width();
    const int h = result.height();

    // setup mask
    const int maskSize = (1+2*rx)*(1+2*ry);
    int * mask = new int[maskSize];
    int index = 0;
    for (int y = -ry; y <= ry; ++y) {
        for (int x = -rx; x <= rx; ++x) {
            mask[index] = y*w+x;
            index++;
        }
    }

    int dstPixel, srcPixel;
    uchar s0, s1, s2, s3;
#if QT_VERSION >= 0x040700
    const uchar * src = image.constBits();
#else
    const uchar * src = image.bits();
#endif
    uchar * dst = result.bits();

    const QRect roi = context.filterRegion().toRect();
    const int minX = qMax(rx, roi.left());
    const int maxX = qMin(w-rx, roi.right());
    const int minY = qMax(ry, roi.top());
    const int maxY = qMin(h-ry, roi.bottom());
    const int defValue = m_operator == Erode ? 255 : 0;

    uchar * d = 0;

    for (int row = minY; row < maxY; ++row) {
        for (int col = minX; col < maxX; ++col) {
            dstPixel = row * w + col;
            s0 = s1 = s2 = s3 = defValue;
            for (int i = 0; i < maskSize; ++i) {
                srcPixel = dstPixel+mask[i];
                const uchar *s = &src[4*srcPixel];
                if (m_operator == Erode ) {
                    s0 = qMin(s0, s[0]);
                    s1 = qMin(s1, s[1]);
                    s2 = qMin(s2, s[2]);
                    s3 = qMin(s3, s[3]);
                } else {
                    s0 = qMax(s0, s[0]);
                    s1 = qMax(s1, s[1]);
                    s2 = qMax(s2, s[2]);
                    s3 = qMax(s3, s[3]);
                }
            }
            d = &dst[4*dstPixel];
            d[0] = s0;
            d[1] = s1;
            d[2] = s2;
            d[3] = s3;
        }
    }

    delete [] mask;

    return result;
}
void FancyTabProxyStyle::drawControl(
    ControlElement element, const QStyleOption* option,
    QPainter* p, const QWidget* widget) const {

  const QStyleOptionTabV3* v_opt = qstyleoption_cast<const QStyleOptionTabV3*>(option);

  if (element != CE_TabBarTab || !v_opt) {
    QProxyStyle::drawControl(element, option, p, widget);
    return;
  }

  const QRect rect = v_opt->rect;
  const bool selected = v_opt->state & State_Selected;
  const bool vertical_tabs = v_opt->shape == QTabBar::RoundedWest;
  const QString text = v_opt->text;

  if (selected) {
    //background
    p->save();
    QLinearGradient grad(rect.topLeft(), rect.topRight());
    grad.setColorAt(0, QColor(255, 255, 255, 140));
    grad.setColorAt(1, QColor(255, 255, 255, 210));
    p->fillRect(rect.adjusted(0, 0, 0, -1), grad);
    p->restore();

    //shadows
    p->setPen(QColor(0, 0, 0, 110));
    p->drawLine(rect.topLeft() + QPoint(1,-1), rect.topRight() - QPoint(0,1));
    p->drawLine(rect.bottomLeft(), rect.bottomRight());
    p->setPen(QColor(0, 0, 0, 40));
    p->drawLine(rect.topLeft(), rect.bottomLeft());

    //highlights
    p->setPen(QColor(255, 255, 255, 50));
    p->drawLine(rect.topLeft() + QPoint(0, -2), rect.topRight() - QPoint(0,2));
    p->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(0,1));
    p->setPen(QColor(255, 255, 255, 40));
    p->drawLine(rect.topLeft() + QPoint(0, 0), rect.topRight());
    p->drawLine(rect.topRight() + QPoint(0, 1), rect.bottomRight() - QPoint(0, 1));
    p->drawLine(rect.bottomLeft() + QPoint(0,-1), rect.bottomRight()-QPoint(0,1));
  }

  QTransform m;
  if (vertical_tabs) {
    m = QTransform::fromTranslate(rect.left(), rect.bottom());
    m.rotate(-90);
  } else {
    m = QTransform::fromTranslate(rect.left(), rect.top());
  }

  const QRect draw_rect(QPoint(0, 0), m.mapRect(rect).size());

  p->save();
  p->setTransform(m);

  QRect icon_rect(QPoint(8, 0), v_opt->iconSize);
  QRect text_rect(icon_rect.topRight() + QPoint(4, 0), draw_rect.size());
  text_rect.setRight(draw_rect.width());
  icon_rect.translate(0, (draw_rect.height() - icon_rect.height()) / 2);

  QFont boldFont(p->font());
  boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
  boldFont.setBold(true);
  p->setFont(boldFont);
  p->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
  int textFlags = Qt::AlignHCenter | Qt::AlignVCenter;
  p->drawText(text_rect, textFlags, text);
  p->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor());
#ifndef Q_WS_MAC
  if (widget) {
    const QString fader_key = "tab_" + text + "_fader";
    const QString animation_key = "tab_" + text + "_animation";

    const QString tab_hover = widget->property("tab_hover").toString();
    int fader = widget->property(fader_key.toUtf8().constData()).toInt();
    QPropertyAnimation* animation = widget->property(animation_key.toUtf8().constData()).value<QPropertyAnimation*>();

    if (!animation) {
      QWidget* mut_widget = const_cast<QWidget*>(widget);
      fader = 0;
      mut_widget->setProperty(fader_key.toUtf8().constData(), fader);
      animation = new QPropertyAnimation(mut_widget, fader_key.toUtf8(), mut_widget);
      connect(animation, SIGNAL(valueChanged(QVariant)), mut_widget, SLOT(update()));
      mut_widget->setProperty(animation_key.toUtf8().constData(), QVariant::fromValue(animation));
    }

    if (text == tab_hover) {
      if (animation->state() != QAbstractAnimation::Running && fader != 40) {
        animation->stop();
        animation->setDuration(80);
        animation->setEndValue(40);
        animation->start();
      }
    } else {
      if (animation->state() != QAbstractAnimation::Running && fader != 0) {
        animation->stop();
        animation->setDuration(160);
        animation->setEndValue(0);
        animation->start();
      }
    }

    if (!selected) {
      p->save();
      QLinearGradient grad(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
      grad.setColorAt(0, Qt::transparent);
      grad.setColorAt(0.5, QColor(255, 255, 255, fader));
      grad.setColorAt(1, Qt::transparent);
      p->fillRect(draw_rect, grad);
      p->setPen(QPen(grad, 1.0));
      p->drawLine(draw_rect.topLeft(), vertical_tabs ? draw_rect.bottomLeft() : draw_rect.topRight());
      p->drawLine(draw_rect.bottomRight(), vertical_tabs ? draw_rect.topRight() : draw_rect.bottomLeft());
      p->restore();
    }
  }
#endif

  Utils::StyleHelper::drawIconWithShadow(v_opt->icon, icon_rect, p, QIcon::Normal);

  p->drawText(text_rect.translated(0, -1), textFlags, text);

  p->restore();
}
void LibVNCServer::setDirty(const QRect &rect)
{
    // End up with artifacts if not increasing the size
    rfbMarkRectAsModified( m_screenInfo, rect.left(), rect.top(), rect.right()+1, rect.bottom()+1 );
}