Exemple #1
0
void LabelCanvas::draw(QPainter & p)
{
    if (! isVisible()) return;

    p.setRenderHint(QPainter::Antialiasing, true);
    p.setBackgroundMode(::Qt::TransparentMode);

    QRectF r = boundingRect();
    FILE * fp = svg();
    int index = text().indexOf(Triangle);

    if (fp != 0)
        fputs("<g>\n", fp);

    if (index == 0) {
        // triangle only
        int w = width() / 2 - 1;
        int b = r.bottom();
        int cx = (r.left() + r.right()) / 2;

        p.drawLine(cx - w, b, cx + w, b);
        //p.lineTo(cx, (int) y());
        p.drawLine(cx + w, b, cx, (int) y());
        //p.lineTo(cx - w, b);
        p.drawLine(cx, (int)y(), cx - w, b);

        if (fp != 0)
            fprintf(fp, "\t<polygon fill=\"none\" stroke=\"black\" stroke-opacity=\"1\""
                    " points=\"%d,%d %d,%d %d,%d\" />\n",
                    cx - w, b, cx + w, b, cx, (int) y());
    }
    else if (index != -1) {
        // label then triangle under
        p.setFont(font());
        p.drawText(rect(), ::Qt::AlignHCenter, text().mid(0, index - 1));

        if (fp != 0)
            draw_text(rect(), ::Qt::AlignHCenter, text().mid(0, index - 1),
                      p.font(), fp);

        QFontMetrics fm(font());
        int w = fm.width(Triangle) / 2 - 1;
        int cx = (r.left() + r.right()) / 2;
        int cy = (int) y() + fm.height();
        int b = r.bottom();

        p.drawLine(cx - w, b, cx + w, b);
        //p.lineTo(cx, cy);
        p.drawLine(cx + w, b, cx, cy);
        //p.lineTo(cx - w, b);
        p.drawLine(cx, cy, cx - w, b);

        if (fp != 0)
            fprintf(fp, "\t<polygon fill=\"none\" stroke=\"black\" stroke-opacity=\"1\""
                    " points=\"%d,%d %d,%d %d,%d\" />\n",
                    cx - w, b, cx + w, b, cx, cy);
    }
    else if (text() != Zigzag) {
        // no triangle nor zigzag
        if (text().indexOf('\n') != -1) {
            p.setFont(font());

            int flg = (multi_lines_centered) ? ::Qt::AlignHCenter : 0;

            p.drawText(rect(), flg, text().mid(0, index - 1));

            if (fp != 0)
                draw_text(rect(), flg, text().mid(0, index - 1),
                          p.font(), fp);
        }
        else {
            QStyleOptionGraphicsItem option;
            QGraphicsSimpleTextItem::paint(&p,&option,0);

            if (fp != 0)
                draw_text(rect(), 0, text(), p.font(), fp);
        }
    }
    else {
        // zigzag (only used as stereotype)
        int t = r.top() + 2;
        int h = height() - 2;
        int yb = r.bottom() - h / 4;
        int xr = r.right() - r.width() / 4;

        p.drawLine(r.left(), t, r.right(), t);
        //p.lineTo(r.left(), yb);
        p.drawLine(r.right(), t, r.left(), yb);
        //p.lineTo(r.right(), yb);
        p.drawLine(r.left(), yb, r.right(), yb);
        //p.lineTo(xr, r.bottom() - h / 2);
        p.drawLine(r.right(), yb, xr, r.bottom() - h / 2);
        p.drawLine(r.right(), yb, xr, r.bottom());

        if (fp != 0) {
            fprintf(fp, "\t<polyline fill=\"none\" stroke=\"black\" stroke-opacity=\"1\""
                    " points=\"%f,%d %f,%d %f,%d %f,%d %d,%f\" />\n",
                    r.left(), t, r.right(), t, r.left(), yb, r.right(), yb, xr, r.bottom() - h / 2);
            fprintf(fp, "\t<line stroke=\"black\" stroke-opacity=\"1\""
                    " x1=\"%f\" y1=\"%d\" x2=\"%d\" y2=\"%f\" />\n",
                    r.right(), yb, xr, r.bottom());
        }
    }

    if (fp != 0)
        fputs("</g>\n", fp);

    if (isSelected())
        show_mark(p, r.toRect());
}
 void ScreenSetupDragWidget::setRect(QRectF const& _rect)
 {
   setGeometry(_rect.toRect());
   raise();
 }
bool ScreenGraphicsItem::eventFilter( QObject *object, QEvent *e )
{
    MarbleWidget *widget = dynamic_cast<MarbleWidget*>(object);
    if ( !widget ) {
        return MarbleGraphicsItem::eventFilter( object, e );
    }
    
    if ( !p()->m_floatItemMoving ) {
        if ( MarbleGraphicsItem::eventFilter( object, e ) ) {
            return true;
        }
    
        if ( !visible() || !p()->isMovable() ) {
            return false;
        }
        
        if ( e->type() == QEvent::MouseMove ) {
            return false;
        }
        
        // Move ScreenGraphicsItem
        if ( e->type() == QEvent::MouseButtonPress )
        {
            QMouseEvent *event = static_cast<QMouseEvent*>(e);

            // Click and move above a float item triggers moving the float item
            if ( contains( event->pos() ) ) {
                if ( event->button() == Qt::LeftButton ) {
                    p()->m_floatItemMoveStartPos = event->pos();
                    p()->m_floatItemMoving = true;
                    return true;
                }
            }
        }
        
        return false;
    }
    else {
        // Move ScreenGraphicsItem
        bool cursorAboveFloatItem = false;
        if ( e->type() == QEvent::MouseMove
            || e->type() == QEvent::MouseButtonPress
            || e->type() == QEvent::MouseButtonRelease )
        {
            QMouseEvent *event = static_cast<QMouseEvent*>( e );
            // The rect the item was painted on before. We add one pixel as antialiasing could
            // result into painting on these pixels to.
            QRectF floatItemRect = QRectF( positivePosition() - QPoint( 1, 1 ),
                                           size() + QSize( 2, 2 ) );

            // Click and move above a float item triggers moving the float item
            if ( contains( event->pos() ) ) {
                cursorAboveFloatItem = true;

                if ( e->type() == QEvent::MouseButtonPress && event->button() == Qt::LeftButton ) {
                    p()->m_floatItemMoveStartPos = event->pos();
                    return true;
                }
            }

            if ( e->type() == QEvent::MouseMove && event->buttons() & Qt::LeftButton && p()->isMovable() )
            {
                p()->m_floatItemMoving = true;
                const QPoint &point = event->pos();
                QPointF position = positivePosition();
                qreal newX = position.x()+point.x()-p()->m_floatItemMoveStartPos.x();
                qreal newY = position.y()+point.y()-p()->m_floatItemMoveStartPos.y();
                if ( newX >= 0 && newY >= 0 ) {
                    // docking behavior
                    const qreal dockArea = 60.0; // Alignment area width/height
                    const qreal dockJump = 30.0; // Alignment indicator jump size
                    if ( widget->width()-size().width()-newX < dockArea ) {
                        newX = qMin( qreal( -1.0 ), size().width() + newX-widget->width() );
                        if ( p()->m_floatItemMoveStartPos.x() < event->pos().x() ) {
                            // Indicate change to right alignment with a short jump
                            newX = qMax( newX, -(dockArea-dockJump) );
                        }
                    }
                    if ( widget->height()-size().height()-newY < dockArea ) {
                        newY = qMin( qreal( -1.0 ), size().height() + newY-widget->height() );
                        if (p()->m_floatItemMoveStartPos.y()<event->pos().y()) {
                        // Indicate change to bottom alignment with a short jump
                        newY = qMax( newY, -( dockArea - dockJump ) );
                        }
                    }

                    setPosition( QPointF( newX,newY ) );
                    // The rect the item will be painted on now. We add one pixel as
                    // antialiasing could result into painting on these pixels to.
                    QRect newFloatItemRect = QRectF( positivePosition() - QPoint( 1, 1 ),
                                                     size() + QSize( 2, 2 ) ).toRect();
                    p()->m_floatItemMoveStartPos = event->pos();
                    QRegion dirtyRegion( floatItemRect.toRect() );
                    dirtyRegion = dirtyRegion.united( newFloatItemRect );

                    widget->setAttribute( Qt::WA_NoSystemBackground,  false );
                    widget->update(dirtyRegion);
                    widget->setAttribute( Qt::WA_NoSystemBackground, widget->viewport()->mapCoversViewport() );
                    return true;
                }
            }

            if ( e->type() == QEvent::MouseButtonRelease ) {
                p()->m_floatItemMoving = false;
            }

            // Adjusting Cursor shape
            if ( cursorAboveFloatItem || p()->m_floatItemMoving ) {
                widget->setCursor(QCursor(Qt::SizeAllCursor));
                return true;
            }
        }
        
        return MarbleGraphicsItem::eventFilter( object, e );
    }
}
Exemple #4
0
/*!
  Draw lines

  \param painter Painter
  \param azimuthMap Maps azimuth values to values related to 0.0, M_2PI
  \param radialMap Maps radius values into painter coordinates.
  \param pole Position of the pole in painter coordinates
  \param from index of the first point to be painted
  \param to index of the last point to be painted.
  \sa draw(), drawLines(), setCurveFitter()
*/
void QwtPolarCurve::drawLines( QPainter *painter,
    const QwtScaleMap &azimuthMap, const QwtScaleMap &radialMap,
    const QPointF &pole, int from, int to ) const
{
    int size = to - from + 1;
    if ( size <= 0 )
        return;

    QPolygonF polyline;
    if ( d_data->curveFitter )
    {
        QPolygonF points( size );
        for ( int j = from; j <= to; j++ )
        {
            const QwtPointPolar point = sample( j );
            points[j - from] = QPointF( point.azimuth(), point.radius() );
        }

        points = d_data->curveFitter->fitCurve( points );

        polyline.resize( points.size() );

        QPointF *polylineData = polyline.data();
        QPointF *pointsData = points.data();

        for ( int i = 0; i < points.size(); i++ )
        {
            const QwtPointPolar point( pointsData[i].x(), pointsData[i].y() );

            double r = radialMap.transform( point.radius() );
            const double a = azimuthMap.transform( point.azimuth() );

            polylineData[i] = qwtPolar2Pos( pole, r, a );
        }
    }
    else
    {
        polyline.resize( size );
        QPointF *polylineData = polyline.data();

        for ( int i = from; i <= to; i++ )
        {
            QwtPointPolar point = sample( i );
            if ( !qwtInsidePole( radialMap, point.radius() ) )
            {
                double r = radialMap.transform( point.radius() );
                const double a = azimuthMap.transform( point.azimuth() );
                polylineData[i - from] = qwtPolar2Pos( pole, r, a );
            }
            else
            {
                polylineData[i - from] = pole;
            }
        }
    }

    QRectF clipRect;
    if ( painter->hasClipping() )
        clipRect = painter->clipRegion().boundingRect();
    else
    {
        clipRect = painter->window();
        if ( !clipRect.isEmpty() )
            clipRect = painter->transform().inverted().mapRect( clipRect );
    }

    if ( !clipRect.isEmpty() )
    {
        double off = qCeil( qMax( 1.0, painter->pen().widthF() ) );
        clipRect = clipRect.toRect().adjusted( -off, -off, off, off );
        polyline = QwtClipper::clipPolygonF( clipRect, polyline );
    }

    QwtPainter::drawPolyline( painter, polyline );
    painter->drawPolyline( polyline );
}
QList<KWViewMode::ViewMap> KWViewModeNormal::mapExposedRects(const QRectF &viewRect, KoViewConverter *viewConverter) const
{
    QList<ViewMap> answer;
    if (!viewConverter) return answer;

#if 1
    if (m_pageTops.isEmpty())
        return answer;
    KWPage page  = m_pageManager->begin();
    const int pageOffset = page.pageNumber();

    // Perform a binary search for page-index using our m_pageTops cache.
    int begin = 0;
    int end = m_pageTops.count() - 1;
    int index = 0;
    const qreal value = viewConverter->viewToDocument(viewRect.topLeft()).y();
    if (m_pageTops.value(end) <= value) { // check extremes. Only end is needed since begin is zero.
        begin = end;
        index = end;
    }
    while (end - begin > 1) {
        index = begin + (end - begin) / 2;
        qreal diff = m_pageTops.value(index) - value;
        if (diff < 0)
            begin = index;
        else if (diff > 0)
            end = index;
        else
            break;
    }
    // index is now the number of the first possible page that can
    // contain the viewRect.  The next step is to find the
    // corresponding Page.  Since we have no way to get to the Nth
    // page directly we have to enumerate them from the beginning.
    //
    // We use 1 since we might hit a pagespread in the binary search,
    // so start one page early.
    while (index > 1) { 
        page = page.next();
        --index;
    }

    // From here we loop through some more pages after the found one
    // and see if they intersect with the page in question.  When we
    // have two pages in row that don't intersect we break the loop.
    qreal offsetX = 0.0;
    int emptyPages = 0;
    for(; page.isValid(); page = page.next()) {
        Q_ASSERT_X(page.pageNumber()-pageOffset < m_pageTops.count(), __FUNCTION__,
                   QString("Pagemanager has more pages than viewmode (%1>%2 with pageOffset=%3 and pageNumber=%4 and pageCount=%5). Make sure you add pages via the document!")
                   .arg(page.pageNumber()-pageOffset).arg(m_pageTops.count())
                   .arg(pageOffset).arg(page.pageNumber()).arg(m_pageManager->pageCount()).toLocal8Bit());


        // Some invariants
        const QRectF pageRect = page.rect();
        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();

        bool pageIntersects = false;

        // 1. First handle the page itself.
        const QRectF zoomedPage = viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;
        //kDebug(32003) <<"page" << page.pageNumber();
        vm.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));

        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(),
                                zoomedPage.width(), zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
            pageIntersects = true;
        }

        // 2. Then handle the annotation area if annotations are active.
        //
        //    The reason we don't do them together with the page
        //    itself is because the pages have a gap between them, but
        //    the annotation area should be unbroken.
        //
        // NOTE: 'annotation' below means the annotation area.
        //
        // FIXME: We should only do this if the annotation area is
        //        actually shown. How can we inside the KWViewMode
        //        know if annotations are active?
        if (1 /* annotations are shown */) {
            const QRectF annotationRect = pageRect.adjusted(page.width(), 0,
                                                            KWCanvasBase::AnnotationAreaWidth, GAP);
            const QRectF zoomedAnnotation = viewConverter->documentToView(annotationRect);
            ViewMap vm2;
            vm2.page = page;
            vm2.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));

            const QRectF targetAnnotation(zoomedAnnotation.x() + vm2.distance.x(),
                                          zoomedAnnotation.y() + vm2.distance.y(),
                                          zoomedAnnotation.width(), zoomedAnnotation.height());
            intersection = targetAnnotation.intersect(viewRect);
            if (! intersection.isEmpty()) {
                intersection.moveTopLeft(intersection.topLeft() - vm2.distance);
                vm2.clipRect = intersection.toRect();
                answer.append(vm2);
                pageIntersects = true;
            }
        }

        // Record whether this page had an intersection with the view rect.
        if (pageIntersects) {
            emptyPages = 0;
        } else {
            ++emptyPages;
        }
        if (emptyPages > 2) // Since we show at max 2 pages side by side this is an easy rule
            break;

        if (m_pageSpreadMode) {
            if (page.pageSide() == KWPage::Left)
                offsetX = page.width() + GAP;
            else
                offsetX = 0.0;
        }
    }
#else
    KWPage page  = m_pageManager->begin();
    Q_ASSERT(page.isValid());
    qreal offsetX = 0.0;
    const int pageOffset = page.pageNumber();
    for(; page.isValid(); page = page.next()) {
        const QRectF pageRect = page.rect();
        const QRectF zoomedPage = viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;

        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();
        vm.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));
#if 0
        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
        }
#else
        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height());
        vm.clipRect = targetPage.toRect();
        answer.append(vm);
#endif
    }
#endif
    return answer;
}
/*!
  Render a plot to a file

  Supported formats are:

  - pdf\n
  - ps\n
  - svg\n
  - all image formats supported by Qt, see QImageWriter::supportedImageFormats()

  \param plot Plot widget
  \param fileName Path of the file, where the document will be stored
  \param format Format for the document
  \param sizeMM Size for the document in millimeters.
  \param resolution Resolution in dots per Inch (dpi)

  \sa renderTo(), render(), QwtPainter::setRoundingAlignment()
*/
void QwtPolarRenderer::renderDocument( QwtPolarPlot *plot,
    const QString &fileName, const QString &format,
    const QSizeF &sizeMM, int resolution )
{
    if ( plot == NULL || sizeMM.isEmpty() || resolution <= 0 )
        return;

    QString title = plot->title().text();
    if ( title.isEmpty() )
        title = "Plot Document";

    const double mmToInch = 1.0 / 25.4;
    const QSizeF size = sizeMM * mmToInch * resolution;

    const QRectF documentRect( 0.0, 0.0, size.width(), size.height() );

    const QString fmt = format.toLower();
    if ( format == "pdf" || format == "ps" )
    {
        QPrinter printer;
        printer.setFullPage( true );
        printer.setPaperSize( sizeMM, QPrinter::Millimeter );
        printer.setDocName( title );
        printer.setOutputFileName( fileName );
        printer.setOutputFormat( ( format == "pdf" )
            ? QPrinter::PdfFormat : QPrinter::PostScriptFormat );
        printer.setResolution( resolution );

        QPainter painter( &printer );
        render( plot, &painter, documentRect );
    }
#ifndef QWT_NO_POLAR_SVG
#ifdef QT_SVG_LIB
#if QT_VERSION >= 0x040500
    else if ( format == "svg" )
    {
        QSvgGenerator generator;
        generator.setTitle( title );
        generator.setFileName( fileName );
        generator.setResolution( resolution );
        generator.setViewBox( documentRect );

        QPainter painter( &generator );
        render( plot, &painter, documentRect );
    }
#endif
#endif
#endif
    else
    {
        if ( QImageWriter::supportedImageFormats().indexOf(
            format.toLatin1() ) >= 0 )
        {
            const QRect imageRect = documentRect.toRect();
            const int dotsPerMeter = qRound( resolution * mmToInch * 1000.0 );

            QImage image( imageRect.size(), QImage::Format_ARGB32 );
            image.setDotsPerMeterX( dotsPerMeter );
            image.setDotsPerMeterY( dotsPerMeter );
            image.fill( QColor( Qt::white ).rgb() );

            QPainter painter( &image );
            render( plot, &painter, imageRect );
            painter.end();

            image.save( fileName, format.toLatin1() );
        }
    }
}
static QImage qwtExpandImage(const QImage &image,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &area, const QRectF &area2, const QRectF &paintRect,
    const QwtInterval &xInterval, const QwtInterval &yInterval )
{
    const QRectF strippedRect = qwtStripRect(paintRect, area2,
        xMap, yMap, xInterval, yInterval);
    const QSize sz = strippedRect.toRect().size();

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

    const QRectF r = QwtScaleMap::transform(xMap, yMap, area).normalized();
    const double pw = ( r.width() - 1) / w;
    const double ph = ( r.height() - 1) / h;

    double px0, py0;
    if ( !xMap.isInverting() )
    {
        px0 = xMap.transform( area2.left() );
        px0 = qRound( px0 );
        px0 = px0 - xMap.transform( area.left() );
    }
    else
    {
        px0 = xMap.transform( area2.right() );
        px0 = qRound( px0 );
        px0 -= xMap.transform( area.right() );

        px0 -= 1.0;
    }
    px0 += strippedRect.left() - paintRect.left();

    if ( !yMap.isInverting() )
    {
        py0 = yMap.transform( area2.top() );
        py0 = qRound( py0 );
        py0 -= yMap.transform( area.top() );
    }
    else
    {
        py0 = yMap.transform( area2.bottom() );
        py0 = qRound( py0 );
        py0 -= yMap.transform( area.bottom() );

        py0 -= 1.0;
    }
    py0 += strippedRect.top() - paintRect.top();

    QImage expanded(sz, image.format());

    switch( image.depth() )
    {
        case 32:
        {
            for ( int y1 = 0; y1 < h; y1++ )
            {
                int yy1;
                if ( y1 == 0 )
                {
                    yy1 = 0;
                }
                else
                {
                    yy1 = qRound( y1 * ph - py0 );
                    if ( yy1 < 0 )
                        yy1 = 0;
                }

                int yy2;
                if ( y1 == h - 1 )
                {
                    yy2 = sz.height();
                }
                else
                {
                    yy2 = qRound( ( y1 + 1 ) * ph - py0 );
                    if ( yy2 > sz.height() )
                        yy2 = sz.height();
                }

                const quint32 *line1 = 
                    reinterpret_cast<const quint32 *>( image.scanLine( y1 ) );

                for ( int x1 = 0; x1 < w; x1++ )
                {
                    int xx1;
                    if ( x1 == 0 )
                    {
                        xx1 = 0;
                    }
                    else
                    {
                        xx1 = qRound( x1 * pw - px0 );
                        if ( xx1 < 0 )
                            xx1 = 0;
                    }

                    int xx2;
                    if ( x1 == w - 1 )
                    {
                        xx2 = sz.width();
                    }
                    else
                    {
                        xx2 = qRound( ( x1 + 1 ) * pw - px0 );
                        if ( xx2 > sz.width() )
                            xx2 = sz.width();
                    }

                    const quint32 rgb( line1[x1] );
                    for ( int y2 = yy1; y2 < yy2; y2++ )
                    {
                        quint32 *line2 = reinterpret_cast<quint32 *>( 
                            expanded.scanLine( y2 ) );

                        for ( int x2 = xx1; x2 < xx2; x2++ ) 
                            line2[x2] = rgb;
                    }       
                }   
            }   
            break;
        }
        case 8:
        {
            for ( int y1 = 0; y1 < h; y1++ )
            {
                int yy1;
                if ( y1 == 0 )
                {
                    yy1 = 0;
                }   
                else
                {
                    yy1 = qRound( y1 * ph - py0 );
                    if ( yy1 < 0 )
                        yy1 = 0; 
                }       
                
                int yy2;
                if ( y1 == h - 1 )
                {
                    yy2 = sz.height();
                }   
                else
                {
                    yy2 = qRound( ( y1 + 1 ) * ph - py0 );
                    if ( yy2 > sz.height() )
                        yy2 = sz.height();
                }
    
                const uchar *line1 = image.scanLine( y1 );

                for ( int x1 = 0; x1 < w; x1++ )
                {
                    int xx1;
                    if ( x1 == 0 )
                    {
                        xx1 = 0;
                    }
                    else
                    {
                        xx1 = qRound( x1 * pw - px0 );
                        if ( xx1 < 0 )
                            xx1 = 0;
                    }

                    int xx2;
                    if ( x1 == w - 1 )
                    {
                        xx2 = sz.width();
                    }
                    else
                    {
                        xx2 = qRound( ( x1 + 1 ) * pw - px0 );
                        if ( xx2 > sz.width() )
                            xx2 = sz.width();
                    }

                    for ( int y2 = yy1; y2 < yy2; y2++ )
                    {
                        uchar *line2 = expanded.scanLine( y2 );
                        memset( line2 + xx1, line1[x1], xx2 - xx1 );
                    }       
                }   
            }
            break;
        }
        default:
            expanded = image;
    }
    
    return expanded;
}   
/*!
  Draw the shape item

  \param painter Painter
  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param canvasRect Contents rect of the plot canvas
*/
void QwtPlotShapeItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( d_data->shape.isEmpty() )
        return;

    if ( d_data->pen.style() == Qt::NoPen
        && d_data->brush.style() == Qt::NoBrush )
    {
        return;
    }

    const QRectF cr = QwtScaleMap::invTransform(
        xMap, yMap, canvasRect.toRect() );

    const QRectF &br = d_data->boundingRect;

    if ( ( br.left() > cr.right() ) || ( br.right() < cr.left() )
        || ( br.top() > cr.bottom() ) || ( br.bottom() < cr.top() ) )
    {
        // outside the visisble area
        return;
    }

    const bool doAlign = QwtPainter::roundingAlignment( painter );

    QPainterPath path = qwtTransformPath( xMap, yMap,
        d_data->shape, doAlign );

    if ( testPaintAttribute( QwtPlotShapeItem::ClipPolygons ) )
    {
        const qreal pw = QwtPainter::effectivePenWidth( painter->pen() );
        const QRectF clipRect = canvasRect.adjusted( -pw, -pw, pw, pw );

        QPainterPath clippedPath;
        clippedPath.setFillRule( path.fillRule() );

        QList<QPolygonF> polygons = path.toSubpathPolygons();
        for ( int i = 0; i < polygons.size(); i++ )
        {
            QwtClipper::clipPolygonF( clipRect, polygons[i], true );
            clippedPath.addPolygon( polygons[i] );

        }

        path = clippedPath;
    }

    if ( d_data->renderTolerance > 0.0 )
    {
        QwtWeedingCurveFitter fitter( d_data->renderTolerance );

        QPainterPath fittedPath;
        fittedPath.setFillRule( path.fillRule() );

        const QList<QPolygonF> polygons = path.toSubpathPolygons();
        for ( int i = 0; i < polygons.size(); i++ )
            fittedPath.addPolygon( fitter.fitCurve( polygons[ i ] ) );

        path = fittedPath;
    }

    painter->setPen( d_data->pen );
    painter->setBrush( d_data->brush );

    painter->drawPath( path );
}
void KisTransformMaskTest::testSafeTransform()
{
    QTransform transform(-0.177454, -0.805953, -0.00213713,
                         -1.9295, -0.371835, -0.00290463,
                         3075.05, 2252.32, 7.62371);

    QRectF testRect(0, 1024, 512, 512);
    KisSafeTransform t2(transform, QRect(0, 0, 2048, 2048), testRect.toRect());

    QPolygonF fwdPoly = t2.mapForward(testRect);
    QRectF fwdRect = t2.mapRectForward(testRect);

    QPolygonF bwdPoly = t2.mapBackward(fwdPoly);
    QRectF bwdRect = t2.mapRectBackward(fwdRect);

    QPolygon ref;

    ref.clear();
    ref << QPoint(284, 410);
    ref << QPoint(10, 613);
    ref << QPoint(35, 532);
    ref << QPoint(236, 403);
    ref << QPoint(284, 410);
    QCOMPARE(fwdPoly.toPolygon(), ref);
    QCOMPARE(fwdRect.toRect(), QRect(10,403,274,211));

    ref.clear();
    ref << QPoint(512, 1024);
    ref << QPoint(512, 1536);
    ref << QPoint(0, 1536);
    ref << QPoint(0, 1024);
    ref << QPoint(512, 1024);
    QCOMPARE(bwdPoly.toPolygon(), ref);
    QCOMPARE(bwdRect.toRect(), QRect(0, 994, 1198, 584));

/*
    QImage image(2500, 2500, QImage::Format_ARGB32);
    QPainter gc(&image);
    gc.setPen(Qt::cyan);

    gc.setOpacity(0.7);

    gc.setBrush(Qt::red);
    gc.drawPolygon(t2.srcClipPolygon());

    gc.setBrush(Qt::green);
    gc.drawPolygon(t2.dstClipPolygon());

    dbgKrita << ppVar(testRect);
    dbgKrita << ppVar(fwdPoly);
    dbgKrita << ppVar(fwdRect);
    dbgKrita << ppVar(bwdPoly);
    dbgKrita << ppVar(bwdRect);

    gc.setBrush(Qt::yellow);
    gc.drawPolygon(testRect);

    gc.setBrush(Qt::red);
    gc.drawPolygon(fwdRect);
    gc.setBrush(Qt::blue);
    gc.drawPolygon(fwdPoly);

    gc.setBrush(Qt::magenta);
    gc.drawPolygon(bwdRect);
    gc.setBrush(Qt::cyan);
    gc.drawPolygon(bwdPoly);

    gc.end();
    image.save("polygons_safety.png");
*/
}
Exemple #10
0
QList<KWViewMode::ViewMap> KWViewModeNormal::clipRectToDocument(const QRect &viewRect) const
{
    QList<ViewMap> answer;
    if (m_pageTops.isEmpty())
        return answer;
    KWPage page  = m_pageManager->begin();
    qreal offsetX = 0.0;
    const int pageOffset = page.pageNumber();

    int begin = 0;
    int end = m_pageTops.count() - 1;
    int index = 0;
    const qreal value = m_viewConverter->viewToDocument(viewRect.topLeft()).y();
    if (m_pageTops.value(end) <= value) { // check extremes. Only end is needed since begin is zero.
        begin = end;
        index = end;
    }
    while (end - begin > 1) { // binary search for page-index using our m_pageTops cache.
        index = begin + (end - begin) / 2;
        qreal diff = m_pageTops.value(index) - value;
        if (diff < 0)
            begin = index;
        else if (diff > 0)
            end = index;
        else
            break;
    }
    while (index > 1) { // 1 since we might hit a pagespread in the binary search, so start one page early
        page = page.next();
        --index;
        if (page.pageSide() == KWPage::PageSpread)
            --index;
    }

    int emptyPages = 0;
    while (page.isValid()) {
#ifndef NDEBUG
        if (page.pageNumber() - pageOffset >= m_pageTops.count()) {
            kWarning(32003) << "ERROR; pagemanager has more pages than viewmode ("
                << m_pageManager->pageCount() << ">" << m_pageTops.count()
                << "). Make sure you add pages via the document!";
            break;
        }
#endif
        const QRectF pageRect = page.rect();
        const QRectF zoomedPage = m_viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;
        //kDebug(32003) <<"page" << page.pageNumber();
        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();
        vm.distance = m_viewConverter->documentToView(QPointF(offsetX, offsetY));

        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(),
                zoomedPage.width() , zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
            emptyPages = 0;
        } else {
            emptyPages++;
        }
        if (emptyPages > 2) // Since we show at max 2 pages side by side this is an easy rule
            break;
        if (m_pageSpreadMode) {
            if (page.pageSide() == KWPage::Left)
                offsetX = page.width() + GAP;
            else
                offsetX = 0.0;
        }
        page = page.next();
    }

    return answer;
}
//-----------------------------------------------------------------------------
QRect vktraceviewer_QTimelineView::visualRect(const QModelIndex &index) const
{
    QRectF rectf = viewportRect(index);
    return rectf.toRect();
}
/*!
  Draw the grid and axes

  \param painter Painter
  \param azimuthMap Maps azimuth values to values related to 0.0, M_2PI
  \param radialMap Maps radius values into painter coordinates.
  \param pole Position of the pole in painter coordinates
  \param radius Radius of the complete plot area in painter coordinates
  \param canvasRect Contents rect of the canvas in painter coordinates
*/
void QwtPolarGrid::draw( QPainter *painter,
    const QwtScaleMap &azimuthMap, const QwtScaleMap &radialMap,
    const QPointF &pole, double radius,
    const QRectF &canvasRect ) const
{
    updateScaleDraws( azimuthMap, radialMap, pole, radius );

    painter->save();

    if ( testDisplayFlag( ClipAxisBackground ) )
    {
        QRegion clipRegion( canvasRect.toRect() );
        for ( int axisId = 0; axisId < QwtPolar::AxesCount; axisId++ )
        {
            const AxisData &axis = d_data->axisData[axisId];
            if ( axisId != QwtPolar::AxisAzimuth && axis.isVisible )
            {
                QwtScaleDraw *scaleDraw = static_cast<QwtScaleDraw *>( axis.scaleDraw );
                if ( scaleDraw->hasComponent( QwtScaleDraw::Labels ) )
                {
                    const QList<double> &ticks =
                        scaleDraw->scaleDiv().ticks( QwtScaleDiv::MajorTick );
                    for ( int i = 0; i < int( ticks.size() ); i++ )
                    {
                        if ( !scaleDraw->scaleDiv().contains( ticks[i] ) )
                            continue;

                        QRect labelRect =
                            scaleDraw->boundingLabelRect( axis.font, ticks[i] );

                        const int margin = 2;
                        labelRect.adjust( -margin, -margin, margin, margin );

                        if ( labelRect.isValid() )
                            clipRegion -= QRegion( labelRect );
                    }
                }
            }
        }
        painter->setClipRegion( clipRegion );
    }

    //  draw radial grid

    const GridData &radialGrid = d_data->gridData[QwtPolar::Radius];
    if ( radialGrid.isVisible && radialGrid.isMinorVisible )
    {
        painter->setPen( radialGrid.minorPen );

        drawCircles( painter, canvasRect, pole, radialMap,
            radialGrid.scaleDiv.ticks( QwtScaleDiv::MinorTick ) );
        drawCircles( painter, canvasRect, pole, radialMap,
            radialGrid.scaleDiv.ticks( QwtScaleDiv::MediumTick ) );
    }
    if ( radialGrid.isVisible )
    {
        painter->setPen( radialGrid.majorPen );

        drawCircles( painter, canvasRect, pole, radialMap,
            radialGrid.scaleDiv.ticks( QwtScaleDiv::MajorTick ) );
    }

    // draw azimuth grid

    const GridData &azimuthGrid =
        d_data->gridData[QwtPolar::Azimuth];

    if ( azimuthGrid.isVisible && azimuthGrid.isMinorVisible )
    {
        painter->setPen( azimuthGrid.minorPen );

        drawRays( painter, canvasRect, pole, radius, azimuthMap,
            azimuthGrid.scaleDiv.ticks( QwtScaleDiv::MinorTick ) );
        drawRays( painter, canvasRect, pole, radius, azimuthMap,
            azimuthGrid.scaleDiv.ticks( QwtScaleDiv::MediumTick ) );
    }
    if ( azimuthGrid.isVisible )
    {
        painter->setPen( azimuthGrid.majorPen );

        drawRays( painter, canvasRect, pole, radius, azimuthMap,
            azimuthGrid.scaleDiv.ticks( QwtScaleDiv::MajorTick ) );
    }
    painter->restore();

    for ( int axisId = 0; axisId < QwtPolar::AxesCount; axisId++ )
    {
        const AxisData &axis = d_data->axisData[axisId];
        if ( axis.isVisible )
        {
            painter->save();
            drawAxis( painter, axisId );
            painter->restore();
        }
    }
}
Exemple #13
0
void ORPrintRender::renderPage(ORODocument * pDocument, int pageNb, QPainter *painter, qreal xDpi, qreal yDpi, QSize margins, int printResolution)
{
  OROPage * p = pDocument->page(pageNb);

  if(((!p->backgroundImage().isNull()) && (p->backgroundOpacity() != 0)) ||
     ((!p->watermarkText().isEmpty()) && (p->watermarkOpacity() != 0)))
  {
    // Do some simple processing used by both Background and Watermark
    const int resolution = 100;
    bool doBgWm = false;
    int printMarginWidth = margins.width();
    int printMarginHeight = margins.height();

    QString pageSize = pDocument->pageOptions().getPageSize();
    int pageWidth = 0;
    int pageHeight = 0;
    if(pageSize == "Custom") {
      // if this is custom sized sheet of paper we will just use those values
      pageWidth = (int)(pDocument->pageOptions().getCustomWidth() * resolution);
      pageHeight = (int)(pDocument->pageOptions().getCustomHeight() * resolution);
    } else {
      // lookup the correct size information for the specified size paper
      PageSizeInfo pi = PageSizeInfo::getByName(pageSize);
      if(!pi.isNull())
      {
        pageWidth = (int)((pi.width() / 100.0) * resolution);
        pageHeight = (int)((pi.height() / 100.0) * resolution);
      }
    }
    if(!pDocument->pageOptions().isPortrait()) {
      int tmp = pageWidth;
      pageWidth = pageHeight;
      pageHeight = tmp;
    }
    if(pageWidth < 1 || pageHeight < 1) {
      // whoops we couldn't find it.... we will use the values from the painter
      // and add in the margins of the printer to get what should be the correct
      // size of the sheet of paper we are printing to.
      pageWidth = (int)(((painter->viewport().width() + printMarginWidth + printMarginWidth) / xDpi) * resolution);
      pageHeight = (int)(((painter->viewport().height() + printMarginHeight + printMarginHeight) / yDpi) * resolution);
    }

    QImage image = QImage(pageWidth, pageHeight, QImage::Format_RGB32);
    QPainter gPainter;
    if(gPainter.begin(&image))
      gPainter.fillRect(gPainter.viewport(), QColor(Qt::white));

    // Render Background
    if((!p->backgroundImage().isNull()) && (p->backgroundOpacity() != 0))
    {
      doBgWm = true;
      QPointF ps = p->backgroundPosition();
      QSizeF sz = p->backgroundSize();
      QRectF rc = QRectF(ps.x() * resolution, ps.y() * resolution, sz.width() * resolution, sz.height() * resolution);
      renderBackground(image, p->backgroundImage(), rc.toRect(),
        p->backgroundScale(), p->backgroundScaleMode(),
        p->backgroundAlign(), p->backgroundOpacity());
    }

    // Render Watermark
    if((!p->watermarkText().isEmpty()) && (p->watermarkOpacity() != 0))
    {
      doBgWm = true;
      renderWatermark(image, p->watermarkText(), p->watermarkFont(), p->watermarkOpacity(),
        ((pDocument->pageOptions().getMarginLeft() + pDocument->pageOptions().getMarginRight()) * resolution),
        ((pDocument->pageOptions().getMarginTop() + pDocument->pageOptions().getMarginBottom()) * resolution),
        pDocument->pageOptions().getMarginLeft() * resolution, pDocument->pageOptions().getMarginTop() * resolution);
    }

    if(doBgWm)
    {
      QRectF target(-printMarginWidth, -printMarginHeight, (painter->viewport().width() + printMarginWidth + printMarginWidth), (painter->viewport().height() + printMarginHeight + printMarginHeight));
      QRectF source(0, 0, image.width(), image.height());
      painter->drawImage(target, image, source);
    }
  }

  // Render Page Objects
  for(int i = 0; i < p->primitives(); i++)
  {
    OROPrimitive * prim = p->primitive(i);

    QPen pen(prim->pen());
    painter->save();
    painter->setPen(pen);
    painter->setBrush(prim->brush());

	QPointF ps = prim->position();
	if(prim->rotationAxis().isNull()) {
		painter->translate(ps.x() * xDpi, ps.y() * yDpi); 
		painter->rotate(prim->rotation()); // rotation around the origin of the primitive (not the center)
	}
	else { // rotation around the defined axis
		qreal xRot = prim->rotationAxis().x();
		qreal yRot = prim->rotationAxis().y();
		painter->translate(xRot * xDpi, yRot * yDpi); 
		painter->rotate(prim->rotation());
		painter->translate((ps.x() - xRot) * xDpi, (ps.y() - yRot) * yDpi); 
	}

    if(prim->type() == OROTextBox::TextBox)
    {
      OROTextBox * tb = (OROTextBox*)prim;
	  painter->setFont(tb->font());

      QSizeF sz = tb->size();
      QRectF rc = QRectF(0, 0, sz.width() * xDpi, sz.height() * yDpi);

      painter->drawText(rc, tb->flags(), tb->text());
    }
    else if(prim->type() == OROLine::Line)
    {
		OROLine * ln = (OROLine*)prim;
		QPointF s = ln->startPoint();
		QPointF e = ln->endPoint();
		pen.setWidthF((ln->weight() / 100) * printResolution);
		painter->setPen(pen);
		painter->drawLine(QLineF(0, 0, (e.x()-s.x()) * xDpi, (e.y()-s.y()) * yDpi));
    }
    else if(prim->type() == OROImage::Image)
    {
      OROImage * im = (OROImage*)prim;
      QSizeF sz = im->size();
      QRectF rc = QRectF(0, 0, sz.width() * xDpi, sz.height() * yDpi);

      QImage img = im->image();
      if(im->scaled())
        img = img.scaled(rc.size().toSize(), (Qt::AspectRatioMode)im->aspectRatioMode(), (Qt::TransformationMode)im->transformationMode());

      QRectF sr = QRectF(QPointF(0.0, 0.0), rc.size().boundedTo(img.size()));
      painter->drawImage(rc.topLeft(), img, sr);
    }
    else if(prim->type() == ORORect::Rect)
    {
      ORORect * re = (ORORect*)prim;

      QSizeF sz = re->size();
      QRectF rc = QRectF(0, 0, sz.width() * xDpi, sz.height() * yDpi);
      pen.setWidthF((re->weight() / 100) * printResolution);
	  painter->setPen(pen);
      painter->drawRect(rc);
    }
    else
    {
      qDebug("unrecognized primitive type");
    }

    painter->restore();

  }
}
Exemple #14
0
void DDateTable::paintCell(QPainter* painter, int row, int col)
{
    double w    = (width() / (double) d->numDayColumns) - 1;
    double h    = (height() / (double) d->numWeekRows) - 1;
    QRectF cell = QRectF(0, 0, w, h);
    QString cellText;
    QPen pen;
    QColor cellBackgroundColor, cellTextColor;
    QFont cellFont  = QFontDatabase::systemFont(QFontDatabase::GeneralFont);
    bool workingDay = false;
    int cellWeekDay, pos;

    //Calculate the position of the cell in the grid
    pos = d->numDayColumns * (row - 1) + col;

    //Calculate what day of the week the cell is
    if (col + locale().firstDayOfWeek() <= d->numDayColumns)
    {
        cellWeekDay = col + locale().firstDayOfWeek();
    }
    else
    {
        cellWeekDay = col + locale().firstDayOfWeek() - d->numDayColumns;
    }

    //FIXME This is wrong if the widget is not using the global!
    //See if cell day is normally a working day
    if (locale().weekdays().first() <= locale().weekdays().last())
    {
        if (cellWeekDay >= locale().weekdays().first() &&
            cellWeekDay <= locale().weekdays().last())
        {
            workingDay = true;
        }
    }
    else
    {
        if (cellWeekDay >= locale().weekdays().first() ||
            cellWeekDay <= locale().weekdays().last())
        {
            workingDay = true;
        }
    }

    if (row == 0)
    {
        //We are drawing a header cell

        //If not a normal working day, then use "do not work today" color
        if (workingDay)
        {
            cellTextColor = palette().color(QPalette::WindowText);
        }
        else
        {
            cellTextColor = Qt::darkRed;
        }

        cellBackgroundColor = palette().color(QPalette::Window);

        //Set the text to the short day name and bold it
        cellFont.setBold(true);
        cellText = locale().dayName(cellWeekDay, QLocale::ShortFormat);

    }
    else
    {
        //We are drawing a day cell

        //Calculate the date the cell represents
        QDate cellDate = dateFromPos(pos);
        bool validDay  = cellDate.isValid();

        // Draw the day number in the cell, if the date is not valid then we don't want to show it
        if (validDay)
        {
            cellText = QString::number(cellDate.day());
        }
        else
        {
            cellText = QLatin1String("");
        }

        if (! validDay || cellDate.month() != d->date.month())
        {
            // we are either
            // ° painting an invalid day
            // ° painting a day of the previous month or
            // ° painting a day of the following month or
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor       = palette().color(QPalette::Disabled, QPalette::Text);
        }
        else
        {
            //Paint a day of the current month

            // Background Colour priorities will be (high-to-low):
            // * Selected Day Background Colour
            // * Customized Day Background Colour
            // * Normal Day Background Colour

            // Background Shape priorities will be (high-to-low):
            // * Customized Day Shape
            // * Normal Day Shape

            // Text Colour priorities will be (high-to-low):
            // * Customized Day Colour
            // * Day of Pray Colour (Red letter)
            // * Selected Day Colour
            // * Normal Day Colour

            //Determine various characteristics of the cell date
            bool selectedDay = (cellDate == date());
            bool currentDay  = (cellDate == QDate::currentDate());
            bool dayOfPray   = (cellDate.dayOfWeek() == Qt::Sunday);
            // TODO: Uncomment if QLocale ever gets the feature...
            //bool dayOfPray = ( cellDate.dayOfWeek() == locale().dayOfPray() );
            bool customDay   = (d->useCustomColors && d->customPaintingModes.contains(cellDate.toJulianDay()));

            //Default values for a normal cell
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor = palette().color(foregroundRole());

            // If we are drawing the current date, then draw it bold and active
            if (currentDay)
            {
                cellFont.setBold(true);
                cellTextColor = palette().color(QPalette::LinkVisited);
            }

            // if we are drawing the day cell currently selected in the table
            if (selectedDay)
            {
                // set the background to highlighted
                cellBackgroundColor = palette().color(QPalette::Highlight);
                cellTextColor = palette().color(QPalette::HighlightedText);
            }

            //If custom colors or shape are required for this date
            if (customDay)
            {
                Private::DatePaintingMode mode = d->customPaintingModes[cellDate.toJulianDay()];

                if (mode.bgMode != NoBgMode)
                {
                    if (!selectedDay)
                    {
                        cellBackgroundColor = mode.bgColor;
                    }
                }

                cellTextColor = mode.fgColor;
            }

            //If the cell day is the day of religious observance, then always color text red unless Custom overrides
            if (! customDay && dayOfPray)
            {
                cellTextColor = Qt::darkRed;
            }

        }
    }

    //Draw the background
    if (row == 0)
    {
        painter->setPen(cellBackgroundColor);
        painter->setBrush(cellBackgroundColor);
        painter->drawRect(cell);
    }
    else if (cellBackgroundColor != palette().color(backgroundRole()) || pos == d->hoveredPos)
    {
        QStyleOptionViewItem opt;
        opt.initFrom(this);
        opt.rect = cell.toRect();

        if (cellBackgroundColor != palette().color(backgroundRole()))
        {
            opt.palette.setBrush(QPalette::Highlight, cellBackgroundColor);
            opt.state |= QStyle::State_Selected;
        }

        if (pos == d->hoveredPos && opt.state & QStyle::State_Enabled)
        {
            opt.state |= QStyle::State_MouseOver;
        }
        else
        {
            opt.state &= ~QStyle::State_MouseOver;
        }

        opt.showDecorationSelected = true;
        opt.viewItemPosition       = QStyleOptionViewItem::OnlyOne;
        style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, this);
    }

    //Draw the text
    painter->setPen(cellTextColor);
    painter->setFont(cellFont);
    painter->drawText(cell, Qt::AlignCenter, cellText, &cell);

    //Draw the base line
    if (row == 0)
    {
        painter->setPen(palette().color(foregroundRole()));
        painter->drawLine(QPointF(0, h), QPointF(w, h));
    }

    // If the day cell we just drew is bigger than the current max cell sizes,
    // then adjust the max to the current cell
    if (cell.width() > d->maxCell.width())
    {
        d->maxCell.setWidth(cell.width());
    }

    if (cell.height() > d->maxCell.height())
    {
        d->maxCell.setHeight(cell.height());
    }
}
Exemple #15
0
void drawHalo(QPainter *painter, const QRectF &rect)
{
    HaloPainter::instance()->drawHalo(painter, rect.toRect());
}
Exemple #16
0
void PictureShape::paint(QPainter &painter, const KViewConverter &converter)
{
    QRectF pixelsF = converter.documentToView(QRectF(QPointF(0,0), size()));
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        painter.fillRect(pixelsF, QColor(Qt::gray));
        return;
    }
    const QRect pixels = pixelsF.toRect();
    QSize pixmapSize = pixels.size();

    QString key(generate_key(imageData->key(), pixmapSize));
    QPixmap pixmap;
#if QT_VERSION  >= 0x040600
    if (!QPixmapCache::find(key, &pixmap)) { // first check cache.
#else
    if (!QPixmapCache::find(key, pixmap)) { // first check cache.
#endif
        // no? Does the imageData have it then?
        if (!(imageData->hasCachedPixmap() && imageData->pixmap().size() == pixmapSize)) {
            // ok, not what we want.
            // before asking to render it, make sure the image doesn't get too big
            QSize imageSize = imageData->image().size();
            if (imageSize.width() < pixmapSize.width() || imageSize.height() < pixmapSize.height()) {
                // kDebug() << "clipping size to orig image size" << imageSize;
                pixmapSize.setWidth(imageSize.width());
                pixmapSize.setHeight(imageSize.height());
            }

            if (m_printQualityImage.isNull()) {
                const int MaxSize = 1000; // TODO set the number as a KImageCollection size
                // make sure our pixmap doesn't get too slow.
                // In future we may want to make this action cause a multi-threaded rescale of the pixmap.
                if (pixmapSize.width() > MaxSize) { // resize to max size.
                    pixmapSize.setHeight(qRound(pixelsF.height() / pixelsF.width() * MaxSize));
                    pixmapSize.setWidth(MaxSize);
                }
                if (pixmapSize.height() > MaxSize) {
                    pixmapSize.setWidth(qRound(pixelsF.width() / pixelsF.height() * MaxSize));
                    pixmapSize.setHeight(MaxSize);
                }
            }
            key = generate_key(imageData->key(), pixmapSize);
        }
    }

    if (!m_printQualityImage.isNull() && pixmapSize == m_printQualityImage.size()) { // painting the image as prepared in waitUntilReady()
        painter.drawImage(pixels, m_printQualityImage, QRect(0, 0, pixmapSize.width(), pixmapSize.height()));
        m_printQualityImage = QImage(); // free memory
        return;
    }

#if QT_VERSION  >= 0x040600
    if (!QPixmapCache::find(key, &pixmap)) {
#else
    if (!QPixmapCache::find(key, pixmap)) {
#endif
        m_renderQueue->addSize(pixmapSize);
        QTimer::singleShot(0, m_renderQueue, SLOT(renderImage()));
        if (!imageData->hasCachedPixmap()
            || imageData->pixmap().size().width() > pixmapSize.width()) { // don't scale down
            QTimer::singleShot(0, m_renderQueue, SLOT(updateShape()));
            return;
        }
        pixmap = imageData->pixmap();
    }
    painter.drawPixmap(pixels, pixmap, QRect(0, 0, pixmap.width(), pixmap.height()));
}

void PictureShape::waitUntilReady(const KViewConverter &converter, bool asynchronous) const
{
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        return;
    }

    if (asynchronous) {
        // get pixmap and schedule it if not
        QSize pixels = converter.documentToView(QRectF(QPointF(0,0), size())).size().toSize();
        QImage image = imageData->image();
        if (image.isNull()) {
            return;
        }
        if (image.size().width() < pixels.width()) { // don't scale up.
            pixels = image.size();
        }
        m_printQualityImage = image.scaled(pixels, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    }
    else {
        QSize pixels = converter.documentToView(QRectF(QPointF(0,0), size())).size().toSize();
        QString key(generate_key(imageData->key(), pixels));
        if (QPixmapCache::find(key) == 0) {
            QPixmap pixmap = imageData->pixmap(pixels);
            QPixmapCache::insert(key, pixmap);
        }
    }
}

void PictureShape::saveOdf(KShapeSavingContext &context) const
{
    // make sure we have a valid image data pointer before saving
    KImageData *imageData = qobject_cast<KImageData*>(userData());
    if (imageData == 0) {
        return;
    }

    KXmlWriter &writer = context.xmlWriter();

    writer.startElement("draw:frame");
    saveOdfAttributes(context, OdfAllAttributes);
    writer.startElement("draw:image");
    // In the spec, only the xlink:href attribute is marked as mandatory, cool :)
    QString name = context.imageHref(imageData);
    writer.addAttribute("xlink:type", "simple");
    writer.addAttribute("xlink:show", "embed");
    writer.addAttribute("xlink:actuate", "onLoad");
    writer.addAttribute("xlink:href", name);
    if (parent()) {
        parent()->saveOdfChildElements(context);
    }
    writer.endElement(); // draw:image
    saveOdfCommonChildElements(context);
    writer.endElement(); // draw:frame

    context.addDataCenter(m_imageCollection);
}
void MoonPhaseCalendar::paintCell( QPainter *painter, int row, int col, const KColorScheme &colorScheme )
{
    double w = cellWidth - 1;
    double h = cellHeight - 1;
    QRectF cell = QRectF( 0, 0, w, h );
    QString cellText;
    QPen pen;
    QColor cellBackgroundColor, cellTextColor;
    QFont cellFont = KGlobalSettings::generalFont();
    bool workingDay = false;
    int cellWeekDay, pos;

    //Calculate the position of the cell in the grid
    pos = numDayColumns * ( row - 1 ) + col;

    //Calculate what day of the week the cell is
    cellWeekDay = col + calendar()->weekStartDay();
    if ( cellWeekDay > numDayColumns ) {
        cellWeekDay -= numDayColumns;
    }

    //See if cell day is normally a working day
    if ( KGlobal::locale()->workingWeekStartDay() <= KGlobal::locale()->workingWeekEndDay() ) {
        workingDay = cellWeekDay >= KGlobal::locale()->workingWeekStartDay()
                  && cellWeekDay <= KGlobal::locale()->workingWeekEndDay();
    } else {
        workingDay = cellWeekDay >= KGlobal::locale()->workingWeekStartDay()
                  || cellWeekDay <= KGlobal::locale()->workingWeekEndDay();
    }

    if( row == 0 ) {

        //We are drawing a header cell

        //If not a normal working day, then use "do not work today" color
        if ( workingDay ) {
            cellTextColor = palette().color(QPalette::WindowText);
        } else {
            KColorScheme colorScheme(palette().currentColorGroup(), KColorScheme::Window);
            cellTextColor = colorScheme.foreground(KColorScheme::NegativeText).color();
        }
        cellBackgroundColor = palette().color(QPalette::Window);

        //Set the text to the short day name and bold it
        cellFont.setBold( true );
        cellText = calendar()->weekDayName( cellWeekDay, KCalendarSystem::ShortDayName );

    } else {

        //We are drawing a day cell

        //Calculate the date the cell represents
        QDate cellDate = dateFromPos( pos );

        bool validDay = calendar()->isValid( cellDate );

        // Draw the day number in the cell, if the date is not valid then we don't want to show it
        if ( validDay ) {
            cellText = calendar()->dayString( cellDate, KCalendarSystem::ShortFormat );
        } else {
            cellText = "";
        }

        if( ! validDay || calendar()->month( cellDate ) != calendar()->month( date() ) ) {
            // we are either
            // ° painting an invalid day
            // ° painting a day of the previous month or
            // ° painting a day of the following month or
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor = colorScheme.foreground(KColorScheme::InactiveText).color();
        } else {
            //Paint a day of the current month

            // Background Colour priorities will be (high-to-low):
            // * Selected Day Background Colour
            // * Customized Day Background Colour
            // * Normal Day Background Colour

            // Background Shape priorities will be (high-to-low):
            // * Customized Day Shape
            // * Normal Day Shape

            // Text Colour priorities will be (high-to-low):
            // * Customized Day Colour
            // * Day of Pray Colour (Red letter)
            // * Selected Day Colour
            // * Normal Day Colour

            //Determine various characteristics of the cell date
            bool selectedDay = ( cellDate == date() );
            bool currentDay = ( cellDate == QDate::currentDate() );
            bool dayOfPray = ( calendar()->dayOfWeek( cellDate ) == KGlobal::locale()->weekDayOfPray() );

            //Default values for a normal cell
            cellBackgroundColor = palette().color( backgroundRole() );
            cellTextColor = palette().color( foregroundRole() );

            // If we are drawing the current date, then draw it bold and active
            if ( currentDay ) {
                cellFont.setBold( true );
                cellTextColor = colorScheme.foreground(KColorScheme::ActiveText).color();
            }

            // if we are drawing the day cell currently selected in the table
            if ( selectedDay ) {
                // set the background to highlighted
                cellBackgroundColor = palette().color( QPalette::Highlight );
                cellTextColor = palette().color( QPalette::HighlightedText );
            }

            //If the cell day is the day of religious observance, then always color text red unless Custom overrides
            if ( dayOfPray ) {
                KColorScheme colorScheme(palette().currentColorGroup(),
                                         selectedDay ? KColorScheme::Selection : KColorScheme::View);
                cellTextColor = colorScheme.foreground(KColorScheme::NegativeText).color();
            }

        }
    }

    //Draw the background
    if (row == 0) {
        painter->setPen( cellBackgroundColor );
        painter->setBrush( cellBackgroundColor );
        painter->drawRect( cell );
    } else if (cellBackgroundColor != palette().color(backgroundRole())) {
        QStyleOptionViewItemV4 opt;
        opt.initFrom(this);
        opt.rect = cell.toRect();
        if (cellBackgroundColor != palette().color(backgroundRole())) {
            opt.palette.setBrush(QPalette::Highlight, cellBackgroundColor);
            opt.state |= QStyle::State_Selected;
        }
        if (false && opt.state & QStyle::State_Enabled) {
            opt.state |= QStyle::State_MouseOver;
        } else {
            opt.state &= ~QStyle::State_MouseOver;
        }
        opt.showDecorationSelected = true;
        opt.viewItemPosition = QStyleOptionViewItemV4::OnlyOne;
        style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, this);
    }

    if( row != 0 ) {
        // Paint the moon phase
        QDate cellDate = dateFromPos( pos );
        if( calendar()->isValid( cellDate ) ) {
            int iPhase = computeMoonPhase( KStarsDateTime( cellDate, QTime(0, 0, 0) ) );
            QRect drawRect = cell.toRect();
            painter->drawPixmap( ( drawRect.width() - MoonImageSize )/2, 12 + (( drawRect.height() - 12 ) - MoonImageSize)/2, m_Images[ iPhase ] ); // FIXME: Using hard coded fon
// +            painter
            // painter->drawPixmap( ( drawRect.width() - MoonImageSize )/2,
                                 // 12 + (( drawRect.height() - 12 ) - MoonImageSize)/2,
                                 // m_Images[ iPhase ] );
            // FIXME: Using hard coded fontsize
            //            kDebug() << "Drew moon image " << iPhase;
        }
    }

    //Draw the text
    painter->setPen( cellTextColor );
    painter->setFont( cellFont );
    painter->drawText( cell, (row == 0) ? Qt::AlignCenter : (Qt::AlignTop | Qt::AlignHCenter), cellText, &cell );

    //Draw the base line
    if (row == 0) {
        painter->setPen( palette().color(foregroundRole()) );
        painter->drawLine( QPointF( 0, h ), QPointF( w, h ) );
    }

    // If the day cell we just drew is bigger than the current max cell sizes,
    // then adjust the max to the current cell

    /*
    if ( cell.width() > d->maxCell.width() ) d->maxCell.setWidth( cell.width() );
    if ( cell.height() > d->maxCell.height() ) d->maxCell.setHeight( cell.height() );
    */
}
Exemple #18
0
static void drawTextCommon(GraphicsContext* ctx, const TextRun& run, const FloatPoint& point, int from, int to, const QFont& font, bool isComplexText)
{
    if (to < 0)
        to = run.length();

    QPainter *p = ctx->platformContext();

    QPen textFillPen;
    if (ctx->textDrawingMode() & TextModeFill)
        textFillPen = fillPenForContext(ctx);

    QPen textStrokePen;
    if (ctx->textDrawingMode() & TextModeStroke)
        textStrokePen = strokePenForContext(ctx);

    String sanitized = Font::normalizeSpaces(run.characters(), run.length());
    QString string = fromRawDataWithoutRef(sanitized);
    QPointF pt(point.x(), point.y());

    if (from > 0 || to < run.length()) {
        if (isComplexText) {
            QTextLayout layout(string, font);
            QTextLine line = setupLayout(&layout, run);
            float x1 = line.cursorToX(from);
            float x2 = line.cursorToX(to);
            if (x2 < x1)
                qSwap(x1, x2);

            QFontMetrics fm(font);
            int ascent = fm.ascent();
            QRectF boundingRect(point.x() + x1, point.y() - ascent, x2 - x1, fm.height());
            QRectF clip = boundingRect;

            ContextShadow* ctxShadow = ctx->contextShadow();

            if (ctxShadow->m_type != ContextShadow::NoShadow) {
                qreal dx1 = 0, dx2 = 0, dy1 = 0, dy2 = 0;
                if (ctxShadow->offset().x() > 0)
                    dx2 = ctxShadow->offset().x();
                else
                    dx1 = -ctxShadow->offset().x();
                if (ctxShadow->offset().y() > 0)
                    dy2 = ctxShadow->offset().y();
                else
                    dy1 = -ctxShadow->offset().y();
                // expand the clip rect to include the text shadow as well
                clip.adjust(dx1, dx2, dy1, dy2);
                clip.adjust(-ctxShadow->m_blurDistance, -ctxShadow->m_blurDistance, ctxShadow->m_blurDistance, ctxShadow->m_blurDistance);
            }
            p->save();
            p->setClipRect(clip.toRect(), Qt::IntersectClip);
            pt.setY(pt.y() - ascent);

            if (ctxShadow->m_type != ContextShadow::NoShadow) {
                ContextShadow* ctxShadow = ctx->contextShadow();
                if (!ctxShadow->mustUseContextShadow(ctx)) {
                    p->save();
                    p->setPen(ctxShadow->m_color);
                    p->translate(ctxShadow->offset());
                    line.draw(p, pt);
                    p->restore();
                } else {
                    QPainter* shadowPainter = ctxShadow->beginShadowLayer(ctx, boundingRect);
                    if (shadowPainter) {
                        // Since it will be blurred anyway, we don't care about render hints.
                        shadowPainter->setFont(p->font());
                        shadowPainter->setPen(ctxShadow->m_color);
                        line.draw(shadowPainter, pt);
                        ctxShadow->endShadowLayer(ctx);
                    }
                }
            }
            p->setPen(textFillPen);
            line.draw(p, pt);
            p->restore();
            return;
        }
        int skipWidth = QFontMetrics(font).width(string, from, Qt::TextBypassShaping);
        pt.setX(pt.x() + skipWidth);
        string = fromRawDataWithoutRef(sanitized, from, to - from);
    }

    p->setFont(font);

    int flags = run.rtl() ? Qt::TextForceRightToLeft : Qt::TextForceLeftToRight;
    if (!isComplexText && !(ctx->textDrawingMode() & TextModeStroke))
        flags |= Qt::TextBypassShaping;

    QPainterPath textStrokePath;
    if (ctx->textDrawingMode() & TextModeStroke)
        textStrokePath.addText(pt, font, string);

    ContextShadow* ctxShadow = ctx->contextShadow();
    if (ctxShadow->m_type != ContextShadow::NoShadow) {
        if (ctx->textDrawingMode() & TextModeFill) {
            if (ctxShadow->m_type != ContextShadow::BlurShadow) {
                p->save();
                p->setPen(ctxShadow->m_color);
                p->translate(ctxShadow->offset());
                p->drawText(pt, string, flags, run.expansion());
                p->restore();
            } else {
                QFontMetrics fm(font);
                QRectF boundingRect(pt.x(), point.y() - fm.ascent(), fm.width(string, -1, flags), fm.height());
                QPainter* shadowPainter = ctxShadow->beginShadowLayer(ctx, boundingRect);
                if (shadowPainter) {
                    // Since it will be blurred anyway, we don't care about render hints.
                    shadowPainter->setFont(p->font());
                    shadowPainter->setPen(ctxShadow->m_color);
                    shadowPainter->drawText(pt, string, flags, run.expansion());
                    ctxShadow->endShadowLayer(ctx);
                }
            }
        } else if (ctx->textDrawingMode() & TextModeStroke) {
            if (ctxShadow->m_type != ContextShadow::BlurShadow) {
                p->translate(ctxShadow->offset());
                p->strokePath(textStrokePath, QPen(ctxShadow->m_color));
                p->translate(-ctxShadow->offset());
            } else {
                QFontMetrics fm(font);
                QRectF boundingRect(pt.x(), point.y() - fm.ascent(), fm.width(string, -1, flags), fm.height());
                QPainter* shadowPainter = ctxShadow->beginShadowLayer(ctx, boundingRect);
                if (shadowPainter) {
                    // Since it will be blurred anyway, we don't care about render hints.
                    shadowPainter->setFont(p->font());
                    shadowPainter->strokePath(textStrokePath, QPen(ctxShadow->m_color));
                    ctxShadow->endShadowLayer(ctx);
                }
            }
        }
    }

    if (ctx->textDrawingMode() & TextModeStroke)
        p->strokePath(textStrokePath, textStrokePen);

    if (ctx->textDrawingMode() & TextModeFill) {
        QPen previousPen = p->pen();
        p->setPen(textFillPen);
        p->drawText(pt, string, flags, run.expansion());
        p->setPen(previousPen);
    }
}
Exemple #19
0
void CustomLabel::paintEvent(QPaintEvent *pe)
{
    if ((!text().isEmpty()) &&
            (textFormat() == Qt::PlainText ||
             (textFormat() == Qt::AutoText && !Qt::mightBeRichText(text()))))
    {
        QPainter painter(this);
#ifndef DEBUG_CUSTOMLABEL
        QRectF lr = contentsRect();
        lr.moveBottom(lr.bottom() - 1); // angry and dirty hack!
        QStyleOption opt;
        opt.initFrom(this);

        int align = QStyle::visualAlignment(text().isRightToLeft() ? Qt::RightToLeft : Qt::LeftToRight, alignment());
        int flags = align | (!text().isRightToLeft() ? Qt::TextForceLeftToRight : Qt::TextForceRightToLeft);
        if (wordWrap())
            flags |= Qt::TextWordWrap;
        switch (shadowType)
        {
        case NoShadow:
            flags |= TF_NOSHADOW;
            break;
        case DarkShadow:
            flags |= TF_DARKSHADOW;
            break;
        case LightShadow:
            flags |= TF_LIGHTSHADOW;
            break;
        default:
            break;
        }
        QString textToDraw = elidedText();
        style()->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), textToDraw, QPalette::WindowText);
#else // DEBUG_CUSTOMLABEL
        QTextDocument *doc = textDocument();
        QAbstractTextDocumentLayout::PaintContext ctx = textDocumentPaintContext(doc);
        QString shadowKey;
        switch (shadowType)
        {
        case DarkShadow:
            shadowKey = GFX_TEXTSHADOWS;
            break;
        case LightShadow:
            shadowKey = GFX_NOTICEWIDGET;
            break;
        case NoShadow:
        default:
            break;
        }

        // magic numbers
        int dx = -2;
        int dy = -2;
        // adding margins
        dx += contentsMargins().left();
        dy += contentsMargins().top();

# if 1 // for debug set 0
        QGraphicsDropShadowEffect *shadow = qobject_cast<QGraphicsDropShadowEffect *>(GraphicsEffectsStorage::staticStorage(RSR_STORAGE_GRAPHICSEFFECTS)->getFirstEffect(shadowKey));
# else // debug shadow
        QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect;
        shadow->setColor(Qt::red);
        shadow->setOffset(1, 1);
# endif
        if (shadow)
        {
# if 0 // for "image method" set 1
            QImage shadowedText(size(), QImage::Format_ARGB32_Premultiplied);
#  if defined(Q_WS_MAC) && !defined(__MAC_OS_X_NATIVE_FULLSCREEN)
            // TODO: fix that
            shadowedText.fill(Qt::red); // DUNNO WHY!!!
#  else
            shadowedText.fill(Qt::transparent);
#  endif
            QPainter tmpPainter(&shadowedText);
            tmpPainter.setRenderHint(QPainter::Antialiasing);
            tmpPainter.setRenderHint(QPainter::HighQualityAntialiasing);
            tmpPainter.setRenderHint(QPainter::TextAntialiasing);
            tmpPainter.setRenderHint(QPainter::SmoothPixmapTransform);
            tmpPainter.translate(dx, dy);
            doc->documentLayout()->draw(&tmpPainter, ctx);
            painter.drawImage(0, 0, shadowedText);
# else // text method
            QPalette origPal = ctx.palette;
            ctx.palette.setColor(QPalette::Text, shadow->color());

            // draw shadow
            painter.save();
            painter.translate(dx + shadow->xOffset(), dy + shadow->yOffset());
            doc->documentLayout()->draw(&painter, ctx);
            painter.restore();

            ctx.palette = origPal;

            // draw text
            painter.save();
            painter.translate(dx, dy);
            doc->documentLayout()->draw(&painter, ctx);
            painter.restore();
# endif // shadow method
        }
        else
        {
            painter.save();
            painter.translate(dx, dy);
            doc->documentLayout()->draw(&painter, ctx);
            painter.restore();
        }
        doc->deleteLater();
#endif // DEBUG_CUSTOMLABEL
    }
    else
        QLabel::paintEvent(pe);
}
Exemple #20
0
void
ComboBox::paintEvent(QPaintEvent* /*e*/)
{
    QStyleOption opt;

    opt.initFrom(this);

    QPainter p(this);
    QRectF bRect = rect();

    {
        ///Now draw the frame

        QColor fillColor;
        if (_clicked || _dirty) {
            fillColor = Qt::black;
        } else {
            double r, g, b;
            switch (_animation) {
            case 0:
            default: {
                appPTR->getCurrentSettings()->getRaisedColor(&r, &g, &b);
                break;
            }
            case 1: {
                appPTR->getCurrentSettings()->getInterpolatedColor(&r, &g, &b);
                break;
            }
            case 2: {
                appPTR->getCurrentSettings()->getKeyframeColor(&r, &g, &b);
                break;
            }
            case 3: {
                appPTR->getCurrentSettings()->getExprColor(&r, &g, &b);
                break;
            }
            }
            fillColor.setRgb( Color::floatToInt<256>(r),
                              Color::floatToInt<256>(g),
                              Color::floatToInt<256>(b) );
        }

        double fw = frameWidth();
        QPen pen;
        if ( !hasFocus() ) {
            pen.setColor(Qt::black);
        } else {
            double r, g, b;
            appPTR->getCurrentSettings()->getSelectionColor(&r, &g, &b);
            QColor c;
            c.setRgb( Color::floatToInt<256>(r),
                      Color::floatToInt<256>(g),
                      Color::floatToInt<256>(b) );
            fw = 2;
        }
        p.setPen(pen);


        QRectF roundedRect = bRect.adjusted(fw / 2., fw / 2., -fw, -fw);
        bRect.adjust(fw, fw, -fw, -fw);
        p.fillRect(bRect, fillColor);
        double roundPixels = 3;
        QPainterPath path;
        path.addRoundedRect(roundedRect, roundPixels, roundPixels);
        p.drawPath(path);
    }
    QColor textColor;
    if (_readOnly) {
        textColor.setRgb(100, 100, 100);
    } else if (_altered) {
        double aR, aG, aB;
        appPTR->getCurrentSettings()->getAltTextColor(&aR, &aG, &aB);
        textColor.setRgbF(aR, aG, aB);
    } else if (!_enabled) {
        textColor = Qt::black;
    } else {
        double r, g, b;
        appPTR->getCurrentSettings()->getTextColor(&r, &g, &b);
        textColor.setRgb( Color::floatToInt<256>(r),
                          Color::floatToInt<256>(g),
                          Color::floatToInt<256>(b) );
    }
    {
        Qt::Alignment align = QStyle::visualAlignment( Qt::LeftToRight, QFlag(_align) );
        int flags = align | Qt::TextForceLeftToRight;

        ///Draw the text
        QPen pen = p.pen();
        if (_currentIndex == -1) {
            QFont f = p.font();
            f.setItalic(true);
            p.setFont(f);
        }
        pen.setColor(textColor);
        p.setPen(pen);

        QRectF lr = layoutRect().toAlignedRect();
        p.drawText(lr.toRect(), flags, _currentText);
    }

    {
        ///Draw the dropdown icon
        QPainterPath path;
        QPolygonF poly;
        poly.push_back( QPointF(bRect.right() - DROP_DOWN_ICON_SIZE * 3. / 2., bRect.height() / 2. - DROP_DOWN_ICON_SIZE / 2.) );
        poly.push_back( QPointF(bRect.right() - DROP_DOWN_ICON_SIZE / 2., bRect.height() / 2. - DROP_DOWN_ICON_SIZE / 2.) );
        poly.push_back( QPointF(bRect.right() - DROP_DOWN_ICON_SIZE, bRect.height() / 2. + DROP_DOWN_ICON_SIZE / 2.) );
        path.addPolygon(poly);
        p.fillPath(path, textColor);
    }
} // ComboBox::paintEvent
QImage QwtPlotRasterItem::compose( 
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &imageArea, const QRectF &paintRect, 
    const QSize &imageSize, bool doCache) const
{
    QImage image;
    if ( imageArea.isEmpty() || paintRect.isEmpty() || imageSize.isEmpty() )
        return image;

    if ( doCache )
    {
        if ( !d_data->cache.image.isNull()
            && d_data->cache.area == imageArea
            && d_data->cache.size == paintRect.size() )
        {
            image = d_data->cache.image;
        }
    }

    if ( image.isNull() )
    {
        double dx = 0.0;
        if ( paintRect.toRect().width() > imageSize.width() )
            dx = imageArea.width() / imageSize.width();

        const QwtScaleMap xxMap = 
            imageMap(Qt::Horizontal, xMap, imageArea, imageSize, dx);
        
        double dy = 0.0;
        if ( paintRect.toRect().height() > imageSize.height() )
            dy = imageArea.height() / imageSize.height();

        const QwtScaleMap yyMap = 
            imageMap(Qt::Vertical, yMap, imageArea, imageSize, dy);

        image = renderImage( xxMap, yyMap, imageArea, imageSize );

        if ( doCache )
        {
            d_data->cache.area = imageArea;
            d_data->cache.size = paintRect.size();
            d_data->cache.image = image;
        }
    }

    if ( d_data->alpha >= 0 && d_data->alpha < 255 )
    {
        QImage alphaImage( image.size(), QImage::Format_ARGB32 );

#if QT_VERSION >= 0x040400 && !defined(QT_NO_QFUTURE)
        uint numThreads = renderThreadCount();

        if ( numThreads <= 0 )
            numThreads = QThread::idealThreadCount();

        if ( numThreads <= 0 )
            numThreads = 1;

        const int numRows = image.height() / numThreads;

        QList< QFuture<void> > futures;
        for ( uint i = 0; i < numThreads; i++ )
        {
            QRect tile( 0, i * numRows, image.width(), numRows );
            if ( i == numThreads - 1 )
            {
                tile.setHeight( image.height() - i * numRows );
                qwtToRgba( &image, &alphaImage, tile, d_data->alpha );
            }
            else
            {
                futures += QtConcurrent::run(
                    &qwtToRgba, &image, &alphaImage, tile, d_data->alpha );
            }
        }
        for ( int i = 0; i < futures.size(); i++ )
            futures[i].waitForFinished();
#else
        const QRect tile( 0, 0, image.width(), image.height() );
        qwtToRgba( &image, &alphaImage, tile, d_data->alpha );
#endif
        image = alphaImage;
    }

    return image;
}
// if painter is nullptr, the method calculate the bounding rectangle of the text and save it to textRect
void FolderItemDelegate::drawText(QPainter* painter, QStyleOptionViewItemV4& opt, QRectF& textRect) const {
  QTextLayout layout(opt.text, opt.font);
  QTextOption textOption;
  textOption.setAlignment(opt.displayAlignment);
  textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
  textOption.setTextDirection(opt.direction);
  layout.setTextOption(textOption);
  qreal height = 0;
  qreal width = 0;
  int visibleLines = 0;
  layout.beginLayout();
  QString elidedText;
  for(;;) {
    QTextLine line = layout.createLine();
    if(!line.isValid())
      break;
    line.setLineWidth(textRect.width());
    height += opt.fontMetrics.leading();
    line.setPosition(QPointF(0, height));
    if((height + line.height() + textRect.y()) > textRect.bottom()) {
      // if part of this line falls outside the textRect, ignore it and quit.
      QTextLine lastLine = layout.lineAt(visibleLines - 1);
      elidedText = opt.text.mid(lastLine.textStart());
      elidedText = opt.fontMetrics.elidedText(elidedText, opt.textElideMode, textRect.width());
      if(visibleLines == 1) // this is the only visible line
        width = textRect.width();
      break;
    }
    height += line.height();
    width = qMax(width, line.naturalTextWidth());
    ++ visibleLines;
  }
  layout.endLayout();

  // draw background for selected item
  QRectF boundRect = layout.boundingRect();
  //qDebug() << "bound rect: " << boundRect << "width: " << width;
  boundRect.setWidth(width);
  boundRect.moveTo(textRect.x() + (textRect.width() - width)/2, textRect.y());

  if(!painter) { // no painter, calculate the bounding rect only
    textRect = boundRect;
    return;
  }

  QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled;
  if(opt.state & QStyle::State_Selected) {
    painter->fillRect(boundRect, opt.palette.highlight());
    painter->setPen(opt.palette.color(cg, QPalette::HighlightedText));
  }
  else
    painter->setPen(opt.palette.color(cg, QPalette::Text));

  // draw text
  for(int i = 0; i < visibleLines; ++i) {
    QTextLine line = layout.lineAt(i);
    if(i == (visibleLines - 1) && !elidedText.isEmpty()) { // the last line, draw elided text
      QPointF pos(textRect.x() + line.position().x(), textRect.y() + line.y() + line.ascent());
      painter->drawText(pos, elidedText);
    }
    else {
      line.draw(painter, textRect.topLeft());
    }
  }

  if(opt.state & QStyle::State_HasFocus) {
    // draw focus rect
    QStyleOptionFocusRect o;
    o.QStyleOption::operator=(opt);
    o.rect = boundRect.toRect(); // subElementRect(SE_ItemViewItemFocusRect, vopt, widget);
    o.state |= QStyle::State_KeyboardFocusChange;
    o.state |= QStyle::State_Item;
    QPalette::ColorGroup cg = (opt.state & QStyle::State_Enabled)
                  ? QPalette::Normal : QPalette::Disabled;
    o.backgroundColor = opt.palette.color(cg, (opt.state & QStyle::State_Selected)
                                  ? QPalette::Highlight : QPalette::Window);
    if (const QWidget* widget = opt.widget) {
      QStyle* style = widget->style() ? widget->style() : qApp->style();
      style->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, widget);
    }
  }
}
void KItemListHeaderWidget::paintRole(QPainter* painter,
                                      const QByteArray& role,
                                      const QRectF& rect,
                                      int orderIndex,
                                      QWidget* widget) const
{
    // The following code is based on the code from QHeaderView::paintSection().
    // Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
    QStyleOptionHeader option;
    option.section = orderIndex;
    option.state = QStyle::State_None | QStyle::State_Raised | QStyle::State_Horizontal;
    if (isEnabled()) {
        option.state |= QStyle::State_Enabled;
    }
    if (window() && window()->isActiveWindow()) {
        option.state |= QStyle::State_Active;
    }
    if (m_hoveredRoleIndex == orderIndex) {
        option.state |= QStyle::State_MouseOver;
    }
    if (m_pressedRoleIndex == orderIndex) {
        option.state |= QStyle::State_Sunken;
    }
    if (m_model->sortRole() == role) {
        option.sortIndicator = (m_model->sortOrder() == Qt::AscendingOrder) ?
                                QStyleOptionHeader::SortDown : QStyleOptionHeader::SortUp;
    }
    option.rect = rect.toRect();

    bool paintBackgroundForEmptyArea = false;

    if (m_columns.count() == 1) {
        option.position = QStyleOptionHeader::OnlyOneSection;
    } else if (orderIndex == 0) {
        option.position = QStyleOptionHeader::Beginning;
    } else if (orderIndex == m_columns.count() - 1) {
        // We are just painting the header for the last column. Check if there
        // is some empty space to the right which needs to be filled.
        if (rect.right() < size().width()) {
            option.position = QStyleOptionHeader::Middle;
            paintBackgroundForEmptyArea = true;
        } else {
            option.position = QStyleOptionHeader::End;
        }
    } else {
        option.position = QStyleOptionHeader::Middle;
    }

    option.orientation = Qt::Horizontal;
    option.selectedPosition = QStyleOptionHeader::NotAdjacent;
    option.text = m_model->roleDescription(role);

    style()->drawControl(QStyle::CE_Header, &option, painter, widget);

    if (paintBackgroundForEmptyArea) {
        option.state = QStyle::State_None | QStyle::State_Raised | QStyle::State_Horizontal;
        option.section = m_columns.count();
        option.sortIndicator = QStyleOptionHeader::None;

        qreal backgroundRectX = rect.x() + rect.width();
        QRectF backgroundRect(backgroundRectX, 0.0, size().width() - backgroundRectX, rect.height());
        option.rect = backgroundRect.toRect();
        option.position = QStyleOptionHeader::End;
        option.text = QString();

        style()->drawControl(QStyle::CE_Header, &option, painter, widget);
    }
}
/*!
  Draw the shape item

  \param painter Painter
  \param xMap X-Scale Map
  \param yMap Y-Scale Map
  \param canvasRect Contents rect of the plot canvas
*/
void QwtPlotShapeItem::draw( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect ) const
{
    if ( d_data->shape.isEmpty() )
        return;

    if ( d_data->pen.style() == Qt::NoPen 
        && d_data->brush.style() == Qt::NoBrush )
    {
        return;
    }

    const QRectF cRect = QwtScaleMap::invTransform(
        xMap, yMap, canvasRect.toRect() );

    if ( d_data->boundingRect.intersects( cRect ) )
    {
        const bool doAlign = QwtPainter::roundingAlignment( painter );

        QPainterPath path = qwtTransformPath( xMap, yMap, 
            d_data->shape, doAlign );

        if ( testPaintAttribute( QwtPlotShapeItem::ClipPolygons ) )
        {
            qreal pw = qMax( qreal( 1.0 ), painter->pen().widthF());
            QRectF clipRect = canvasRect.adjusted( -pw, -pw, pw, pw );

            QPainterPath clippedPath;
            clippedPath.setFillRule( path.fillRule() );

            const QList<QPolygonF> polygons = path.toSubpathPolygons();
            for ( int i = 0; i < polygons.size(); i++ )
            {
                const QPolygonF p = QwtClipper::clipPolygonF(
                    clipRect, polygons[i], true );

                clippedPath.addPolygon( p );

            }

            path = clippedPath;
        }

        if ( d_data->renderTolerance > 0.0 )
        {
            QwtWeedingCurveFitter fitter( d_data->renderTolerance );

            QPainterPath fittedPath;
            fittedPath.setFillRule( path.fillRule() );

            const QList<QPolygonF> polygons = path.toSubpathPolygons();
            for ( int i = 0; i < polygons.size(); i++ )
                fittedPath.addPolygon( fitter.fitCurve( polygons[ i ] ) );

            path = fittedPath;
        }

        painter->setPen( d_data->pen );
        painter->setBrush( d_data->brush );

        painter->drawPath( path );
    }
}
//-------------------------------------------------------------------------
void QGuidoItemContainer::resized(const QRectF& newRect)
{
	if ( newRect.toRect() == rect().toRect() )
		return;

	
	if ( mResizeMode == RESIZE_GRID )
	{
		QRectF oldRect = rect();
		mGuidoItem->setGridWidth( mGuidoItem->gridWidth() * newRect.width() / rect().width() + 0.5f );
		mGuidoItem->setGridHeight( mGuidoItem->gridHeight() * newRect.height() / rect().height() + 0.5f );
		guidoGeometryChanged();
		
		QSizeF dSize( rect().size() - oldRect.size() );
		moveBy( dSize.width() * ( newRect.x() ? -1 : 0 ) , dSize.height() * ( newRect.y() ? -1 : 0 ) );
	}
	else if ( mResizeMode == RESIZE_FORMAT )
	{
		QRectF oldRect = rect();
	
		GuidoPageFormat f = mGuidoItem->guidoPageFormat();
		f.width = f.width * newRect.width() / rect().width();
		f.height = f.height * newRect.height() / rect().height();
		mGuidoItem->setGuidoPageFormat(f);

		//Control if how the page format was actually supported,
		//and set it to its actual value.
		if ( rect().toRect() != newRect.toRect() )	//has use int comparison, float isn't reliable
		{
			f = mGuidoItem->guidoPageFormat();
			f.width = f.width * rect().width() / newRect.width();
			f.height = f.height * rect().height() / newRect.height();
			mGuidoItem->setGuidoPageFormat(f);
		}
		
		QSizeF dSize( rect().size() - oldRect.size() );
		
//		moveBy( newRect.x() , newRect.y() );
		moveBy( dSize.width() * ( newRect.x() ? -1 : 0 ) , dSize.height() * ( newRect.y() ? -1 : 0 ) );
	}
	else
	{
		float xScale = mGuidoItem->transform().m11();
		float yScale = mGuidoItem->transform().m22();

		float dx = newRect.x();
		float dy = newRect.y();

		float sx = ( newRect.width() / rect().width() );
		float sy = ( newRect.height() / rect().height() );

		float boundedSx = sx;
		float boundedSy = sy;

		if ( mMaxScale )
			boundedSx = qMin( mMaxScale/xScale , boundedSx );
		boundedSx = qMax( mMinScale/xScale , boundedSx );
		if ( mMaxScale )
			boundedSy = qMin( mMaxScale/yScale , boundedSy );
		boundedSy = qMax( mMinScale/yScale , boundedSy );

		dx = dx * (boundedSx - 1 ) / ( sx - 1 );
		dy = dy * (boundedSy - 1 ) / ( sy - 1 );
		
		moveBy( dx , dy );
		
		mGuidoItem->scale( boundedSx , boundedSy );
		guidoGeometryChanged();

		Q_EMIT scaleChanged( mGuidoItem->transform().m11() );
	}
	mResizeMode = RESIZE_NORMAL;
	if ( mResizer )
		mResizer->setKeepAspectRatio(true);
}
QList<KWViewMode::ViewMap> KWViewModeNormal::mapExposedRects(const QRectF &viewRect, KoViewConverter *viewConverter) const
{
    QList<ViewMap> answer;
    if (!viewConverter) return answer;

#if 1
    if (m_pageTops.isEmpty())
        return answer;
    KWPage page  = m_pageManager->begin();
    qreal offsetX = 0.0;
    const int pageOffset = page.pageNumber();

    int begin = 0;
    int end = m_pageTops.count() - 1;
    int index = 0;
    const qreal value = viewConverter->viewToDocument(viewRect.topLeft()).y();
    if (m_pageTops.value(end) <= value) { // check extremes. Only end is needed since begin is zero.
        begin = end;
        index = end;
    }
    while (end - begin > 1) { // binary search for page-index using our m_pageTops cache.
        index = begin + (end - begin) / 2;
        qreal diff = m_pageTops.value(index) - value;
        if (diff < 0)
            begin = index;
        else if (diff > 0)
            end = index;
        else
            break;
    }
    while (index > 1) { // 1 since we might hit a pagespread in the binary search, so start one page early
        page = page.next();
        --index;
    }

    int emptyPages = 0;
    for(; page.isValid(); page = page.next()) {
        Q_ASSERT_X(page.pageNumber()-pageOffset < m_pageTops.count(), __FUNCTION__,
                   QString("Pagemanager has more pages than viewmode (%1>%2 with pageOffset=%3 and pageNumber=%4 and pageCount=%5). Make sure you add pages via the document!")
                   .arg(page.pageNumber()-pageOffset).arg(m_pageTops.count()).arg(pageOffset).arg(page.pageNumber()).arg(m_pageManager->pageCount()).toLocal8Bit());

        const QRectF pageRect = page.rect();
        const QRectF zoomedPage = viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;
        //kDebug(32003) <<"page" << page.pageNumber();
        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();
        vm.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));

        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(),
                zoomedPage.width() , zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
            emptyPages = 0;
        } else {
            emptyPages++;
        }
        if (emptyPages > 2) // Since we show at max 2 pages side by side this is an easy rule
            break;
        if (m_pageSpreadMode) {
            if (page.pageSide() == KWPage::Left)
                offsetX = page.width() + GAP;
            else
                offsetX = 0.0;
        }
    }
#else
    KWPage page  = m_pageManager->begin();
    Q_ASSERT(page.isValid());
    qreal offsetX = 0.0;
    const int pageOffset = page.pageNumber();
    for(; page.isValid(); page = page.next()) {
        const QRectF pageRect = page.rect();
        const QRectF zoomedPage = viewConverter->documentToView(pageRect);
        ViewMap vm;
        vm.page = page;

        const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top();
        vm.distance = viewConverter->documentToView(QPointF(offsetX, offsetY));
#if 0
        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height());
        QRectF intersection = targetPage.intersect(viewRect);
        if (! intersection.isEmpty()) {
            intersection.moveTopLeft(intersection.topLeft() - vm.distance);
            vm.clipRect = intersection.toRect();
            answer.append(vm);
        }
#else
        const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height());
        vm.clipRect = targetPage.toRect();
        answer.append(vm);
#endif
    }
#endif
    return answer;
}
void AppItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.data(AppsListModel::AppItemIsDragingRole).value<bool>() && !(option.features & QStyleOptionViewItem::HasDisplay))
        return;

    painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
    painter->setPen(Qt::white);
    painter->setBrush(QBrush(Qt::transparent));

    const int leftMargin = 2, radius = 3;
    const int fontPixelSize = index.data(AppsListModel::AppFontSizeRole).value<int>();
    const bool drawBlueDot = index.data(AppsListModel::AppNewInstallRole).toBool();
    const ItemInfo itemInfo = index.data(AppsListModel::AppRawItemInfoRole).value<ItemInfo>();
    const QRect boundingRect = itemBoundingRect(option.rect);
    const QSize iconSize = index.data(AppsListModel::AppIconSizeRole).toSize();

    // draw focus background
   if (CurrentIndex == index && !(option.features & QStyleOptionViewItem::HasDisplay))
    {
        const QColor borderColor(255, 255, 255, 52);
        const QColor brushColor(0, 0, 0, 105);

        QPen pen;
        pen.setColor(borderColor);
        pen.setWidth(2);
        QPainterPath border;
        border.addRoundedRect(boundingRect.marginsRemoved(QMargins(leftMargin/2, leftMargin/2, leftMargin*2/3, leftMargin*2/3)),
                              radius, radius);
        painter->strokePath(border, pen);
        painter->setPen(Qt::transparent);
        painter->setBrush(brushColor);
        painter->drawRoundedRect(boundingRect.marginsRemoved(QMargins(leftMargin, leftMargin, leftMargin*4/3, leftMargin*4/3)),
                                 radius, radius);
    }

    // draw app icon
    const int iconLeftMargins = (boundingRect.width() - iconSize.width()) / 2;
    const int iconTopMargin = qMin(10, int(boundingRect.height() * 0.1));
    const QRect iconRect = QRect(boundingRect.topLeft() + QPoint(iconLeftMargins, iconTopMargin), iconSize);
    painter->drawPixmap(iconRect, index.data(AppsListModel::AppIconRole).value<QPixmap>());

    // draw icon if app is auto startup
    const QPoint autoStartIconPos = iconRect.bottomLeft() - QPoint(0, m_autoStartPixmap.height());
    if (index.data(AppsListModel::AppAutoStartRole).toBool())
        painter->drawPixmap(autoStartIconPos, m_autoStartPixmap);

    // draw app name
    QTextOption appNameOption;
    appNameOption.setAlignment(Qt::AlignHCenter | Qt::AlignTop);
    appNameOption.setWrapMode(QTextOption::WordWrap);
    QFont appNamefont(painter->font());
    appNamefont.setPixelSize(fontPixelSize);

    const QFontMetrics fm(appNamefont);
    const QRectF appNameRect = itemTextRect(boundingRect, iconRect, drawBlueDot);
//    const QRectF appNameBoundingRect = fm.boundingRect(appNameRect.toRect(), appNameOption.alignment() | wrapFlag, itemInfo.m_name);
    const QString appText = holdTextInRect(fm, itemInfo.m_name, appNameRect.toRect());
//    const QString appText = appNameBoundingRect.width() > appNameRect.width() || appNameBoundingRect.height() > appNameRect.height()
//                                ? fm.elidedText(itemInfo.m_name, Qt::ElideRight, appNameRect.width(), appNameOption.alignment() | wrapFlag)
//                                : itemInfo.m_name;

    painter->setFont(appNamefont);
    painter->setBrush(QBrush(Qt::transparent));
    painter->setPen(QColor(0, 0, 0, 80));
    painter->drawText(appNameRect.adjusted(0.8, 1, 0.8, 1), appText, appNameOption);
    painter->drawText(appNameRect.adjusted(-0.8, 1, -0.8, 1), appText, appNameOption);
    painter->setPen(Qt::white);
    painter->drawText(appNameRect, appText, appNameOption);

    // draw blue dot if needed
    if (drawBlueDot)
    {
        const int marginRight = 2;
        const QRectF textRect = fm.boundingRect(appNameRect.toRect(), Qt::AlignTop | Qt::AlignHCenter | Qt::TextWordWrap, appText);

        const QPointF blueDotPos = textRect.topLeft() + QPoint(-m_blueDotPixmap.width() - marginRight, (fm.height() - m_blueDotPixmap.height()) / 2);
        painter->drawPixmap(blueDotPos, m_blueDotPixmap);
    }
}
Exemple #28
0
/*!\reimp
*/
void QLabel::paintEvent(QPaintEvent *)
{
    Q_D(QLabel);
    QStyle *style = QWidget::style();
    QPainter painter(this);
    drawFrame(&painter);
    QRect cr = contentsRect();
    cr.adjust(d->margin, d->margin, -d->margin, -d->margin);
    int align = QStyle::visualAlignment(d->isTextLabel ? d->textDirection()
                                                       : layoutDirection(), QFlag(d->align));

#if QT_CONFIG(movie)
    if (d->movie) {
        if (d->scaledcontents)
            style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size()));
        else
            style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap());
    }
    else
#endif
    if (d->isTextLabel) {
        QRectF lr = d->layoutRect().toAlignedRect();
        QStyleOption opt;
        opt.initFrom(this);
#ifndef QT_NO_STYLE_STYLESHEET
        if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) {
            cssStyle->styleSheetPalette(this, &opt, &opt.palette);
        }
#endif
        if (d->control) {
#ifndef QT_NO_SHORTCUT
            const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0);
            if (d->shortcutId != 0
                && underline != d->shortcutCursor.charFormat().fontUnderline()) {
                QTextCharFormat fmt;
                fmt.setFontUnderline(underline);
                d->shortcutCursor.mergeCharFormat(fmt);
            }
#endif
            d->ensureTextLayouted();

            QAbstractTextDocumentLayout::PaintContext context;
            // Adjust the palette
            context.palette = opt.palette;

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

            painter.save();
            painter.translate(lr.topLeft());
            painter.setClipRect(lr.translated(-lr.x(), -lr.y()));
            d->control->setPalette(context.palette);
            d->control->drawContents(&painter, QRectF(), this);
            painter.restore();
        } else {
            int flags = align | (d->textDirection() == Qt::LeftToRight ? Qt::TextForceLeftToRight
                                                                       : Qt::TextForceRightToLeft);
            if (d->hasShortcut) {
                flags |= Qt::TextShowMnemonic;
                if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this))
                    flags |= Qt::TextHideMnemonic;
            }
            style->drawItemText(&painter, lr.toRect(), flags, opt.palette, isEnabled(), d->text, foregroundRole());
        }
    } else
#ifndef QT_NO_PICTURE
    if (d->picture) {
        QRect br = d->picture->boundingRect();
        int rw = br.width();
        int rh = br.height();
        if (d->scaledcontents) {
            painter.save();
            painter.translate(cr.x(), cr.y());
            painter.scale((double)cr.width()/rw, (double)cr.height()/rh);
            painter.drawPicture(-br.x(), -br.y(), *d->picture);
            painter.restore();
        } else {
            int xo = 0;
            int yo = 0;
            if (align & Qt::AlignVCenter)
                yo = (cr.height()-rh)/2;
            else if (align & Qt::AlignBottom)
                yo = cr.height()-rh;
            if (align & Qt::AlignRight)
                xo = cr.width()-rw;
            else if (align & Qt::AlignHCenter)
                xo = (cr.width()-rw)/2;
            painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture);
        }
    } else
#endif
    if (d->pixmap && !d->pixmap->isNull()) {
        QPixmap pix;
        if (d->scaledcontents) {
            QSize scaledSize = cr.size() * devicePixelRatioF();
            if (!d->scaledpixmap || d->scaledpixmap->size() != scaledSize) {
                if (!d->cachedimage)
                    d->cachedimage = new QImage(d->pixmap->toImage());
                delete d->scaledpixmap;
                QImage scaledImage =
                    d->cachedimage->scaled(scaledSize,
                                           Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                d->scaledpixmap = new QPixmap(QPixmap::fromImage(scaledImage));
                d->scaledpixmap->setDevicePixelRatio(devicePixelRatioF());
            }
            pix = *d->scaledpixmap;
        } else
            pix = *d->pixmap;
        QStyleOption opt;
        opt.initFrom(this);
        if (!isEnabled())
            pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt);
        style->drawItemPixmap(&painter, cr, align, pix);
    }
}
Exemple #29
0
/*!
  Draw a rectangular frame

  \param painter Painter
  \param rect Frame rectangle
  \param palette Palette
  \param foregroundRole Foreground role used for QFrame::Plain
  \param frameWidth Frame width
  \param midLineWidth Used for QFrame::Box
  \param frameStyle bitwise OR´ed value of QFrame::Shape and QFrame::Shadow
*/
void QwtPainter::drawFrame( QPainter *painter, const QRectF &rect,
    const QPalette &palette, QPalette::ColorRole foregroundRole,
    int frameWidth, int midLineWidth, int frameStyle )
{
    if ( frameWidth <= 0 || rect.isEmpty() )
        return;

    const int shadow = frameStyle & QFrame::Shadow_Mask;

    painter->save();

    if ( shadow == QFrame::Plain )
    {
        const QRectF outerRect = rect.adjusted( 0.0, 0.0, -1.0, -1.0 );
        const QRectF innerRect = outerRect.adjusted(
            frameWidth, frameWidth, -frameWidth, -frameWidth );

        QPainterPath path;
        path.addRect( outerRect );
        path.addRect( innerRect );

        painter->setPen( Qt::NoPen );
        painter->setBrush( palette.color( foregroundRole ) );

        painter->drawPath( path );
    }
    else
    {
        const int shape = frameStyle & QFrame::Shape_Mask;

        if ( shape == QFrame::Box )
        {
            const QRectF outerRect = rect.adjusted( 0.0, 0.0, -1.0, -1.0 );
            const QRectF midRect1 = outerRect.adjusted(
                frameWidth, frameWidth, -frameWidth, -frameWidth );
            const QRectF midRect2 = midRect1.adjusted(
                midLineWidth, midLineWidth, -midLineWidth, -midLineWidth );

            const QRectF innerRect = midRect2.adjusted(
                frameWidth, frameWidth, -frameWidth, -frameWidth );

            QPainterPath path1;
            path1.moveTo( outerRect.bottomLeft() );
            path1.lineTo( outerRect.topLeft() );
            path1.lineTo( outerRect.topRight() );
            path1.lineTo( midRect1.topRight() );
            path1.lineTo( midRect1.topLeft() );
            path1.lineTo( midRect1.bottomLeft() );

            QPainterPath path2;
            path2.moveTo( outerRect.bottomLeft() );
            path2.lineTo( outerRect.bottomRight() );
            path2.lineTo( outerRect.topRight() );
            path2.lineTo( midRect1.topRight() );
            path2.lineTo( midRect1.bottomRight() );
            path2.lineTo( midRect1.bottomLeft() );

            QPainterPath path3;
            path3.moveTo( midRect2.bottomLeft() );
            path3.lineTo( midRect2.topLeft() );
            path3.lineTo( midRect2.topRight() );
            path3.lineTo( innerRect.topRight() );
            path3.lineTo( innerRect.topLeft() );
            path3.lineTo( innerRect.bottomLeft() );

            QPainterPath path4;
            path4.moveTo( midRect2.bottomLeft() );
            path4.lineTo( midRect2.bottomRight() );
            path4.lineTo( midRect2.topRight() );
            path4.lineTo( innerRect.topRight() );
            path4.lineTo( innerRect.bottomRight() );
            path4.lineTo( innerRect.bottomLeft() );

            QPainterPath path5;
            path5.addRect( midRect1 );
            path5.addRect( midRect2 );

            painter->setPen( Qt::NoPen );

            QBrush brush1 = palette.dark().color();
            QBrush brush2 = palette.light().color();

            if ( shadow == QFrame::Raised )
                qSwap( brush1, brush2 );

            painter->setBrush( brush1 );
            painter->drawPath( path1 );
            painter->drawPath( path4 );

            painter->setBrush( brush2 );
            painter->drawPath( path2 );
            painter->drawPath( path3 );

            painter->setBrush( palette.mid() );
            painter->drawPath( path5 );
        }
#if 0
        // qDrawWinPanel doesn't result in something nice
        // on a scalable document like PDF. Better draw a
        // Panel.

        else if ( shape == QFrame::WinPanel )
        {
            painter->setRenderHint( QPainter::NonCosmeticDefaultPen, true );
            qDrawWinPanel ( painter, rect.toRect(), palette,
                frameStyle & QFrame::Sunken );
        }
        else if ( shape == QFrame::StyledPanel )
        {
        }
#endif
        else
        {
            const QRectF outerRect = rect.adjusted( 0.0, 0.0, -1.0, -1.0 );
            const QRectF innerRect = outerRect.adjusted(
                frameWidth - 1.0, frameWidth - 1.0,
                -( frameWidth - 1.0 ), -( frameWidth - 1.0 ) );

            QPainterPath path1;
            path1.moveTo( outerRect.bottomLeft() );
            path1.lineTo( outerRect.topLeft() );
            path1.lineTo( outerRect.topRight() );
            path1.lineTo( innerRect.topRight() );
            path1.lineTo( innerRect.topLeft() );
            path1.lineTo( innerRect.bottomLeft() );


            QPainterPath path2;
            path2.moveTo( outerRect.bottomLeft() );
            path2.lineTo( outerRect.bottomRight() );
            path2.lineTo( outerRect.topRight() );
            path2.lineTo( innerRect.topRight() );
            path2.lineTo( innerRect.bottomRight() );
            path2.lineTo( innerRect.bottomLeft() );

            painter->setPen( Qt::NoPen );

            QBrush brush1 = palette.dark().color();
            QBrush brush2 = palette.light().color();

            if ( shadow == QFrame::Raised )
                qSwap( brush1, brush2 );

            painter->setBrush( brush1 );
            painter->drawPath( path1 );

            painter->setBrush( brush2 );
            painter->drawPath( path2 );
        }

    }

    painter->restore();
}
void QVGPixmapConvolutionFilter::draw
        (QPainter *painter, const QPointF &dest,
         const QPixmap &src, const QRectF &srcRect) const
{
    if (src.isNull())
        return;

    if (src.pixmapData()->classId() != QPixmapData::OpenVGClass) {
        // The pixmap data is not an instance of QVGPixmapData, so fall
        // back to the default convolution filter implementation.
        QPixmapConvolutionFilter::draw(painter, dest, src, srcRect);
        return;
    }

    QVGPixmapData *pd = static_cast<QVGPixmapData *>(src.pixmapData());

    VGImage srcImage = pd->toVGImage();
    if (srcImage == VG_INVALID_HANDLE)
        return;

    QSize size = pd->size();
    VGImage dstImage = QVGImagePool::instance()->createTemporaryImage
        (VG_sARGB_8888_PRE, size.width(), size.height(),
         VG_IMAGE_QUALITY_FASTER, pd);
    if (dstImage == VG_INVALID_HANDLE)
        return;

    int kernelWidth = rows();
    int kernelHeight = columns();
    const qreal *kern = convolutionKernel();
    QVarLengthArray<VGshort> kernel;
    for (int i = 0; i < kernelWidth; ++i) {
        for (int j = 0; j < kernelHeight; ++j) {
            kernel.append((VGshort)(kern[j * kernelWidth + i] * 1024.0f));
        }
    }

    VGfloat values[4];
    values[0] = 0.0f;
    values[1] = 0.0f;
    values[2] = 0.0f;
    values[3] = 0.0f;
    vgSetfv(VG_TILE_FILL_COLOR, 4, values);

    vgConvolve(dstImage, srcImage,
               kernelWidth, kernelHeight, 0, 0,
               kernel.constData(), 1.0f / 1024.0f, 0.0f,
               VG_TILE_FILL);

    VGImage child = VG_INVALID_HANDLE;

    if (srcRect.isNull() ||
        (srcRect.topLeft().isNull() && srcRect.size() == size)) {
        child = dstImage;
    } else {
        QRect src = srcRect.toRect();
        child = vgChildImage(dstImage, src.x(), src.y(), src.width(), src.height());
    }

    qt_vg_drawVGImage(painter, dest, child);

    if(child != dstImage)
        vgDestroyImage(child);
    QVGImagePool::instance()->releaseImage(0, dstImage);
}