void KDPluginsListBoxItem::paint( QPainter *p )
{
  QFontMetrics fm = p->fontMetrics();

  p->drawText( 1, fm.ascent() + fm.leading()/2, text() );
}
Beispiel #2
0
    QString descr = index.data(KAtomic::LevelSetDescriptionRole).toString();
    if (!descr.isEmpty())
    {
        if (option.state & QStyle::State_Selected)
            p->setPen(option.palette.color(QPalette::Normal, QPalette::HighlightedText));
        else
            p->setPen(option.palette.color(QPalette::Normal, QPalette::Text));

        r = opt.rect.adjusted(textStartX, fm.lineSpacing()*2, -marginH*2, -marginV*2);
        flags = Qt::AlignLeft | Qt::AlignBottom | Qt::TextSingleLine;
        p->setFont(opt.font);
        QString elided = fm.elidedText(descr, Qt::ElideMiddle, r.width(), flags);
        p->drawText(r, flags, descr);
    }

    p->restore();
}

QSize LevelSetDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(index)

    if (m_lineHeight == -1)
    {
        QFontMetrics fm(option.font);
        m_lineHeight = fm.lineSpacing();
    }

    return QSize(option.rect.width(), qMax(m_lineHeight*3, 64));
}
Beispiel #3
0
void kpok::paintEvent( QPaintEvent *)
{
   /* This was shamelessy stolen from the "hello world" example coming with Qt
      Thanks to the Qt-Guys for doing such a cool example 8-)
   */
   
   
   QString t;

   if (!waveActive) {
      return;
   }

   t = wonLabel->text();

   static int sin_tbl[16] = {
      0, 38, 71, 92, 100, 92, 71, 38,  0, -38, -71, -92, -100, -92, -71, -38};

   if ( t.isEmpty() )
      return;


   QFont wonFont("Helvetica", 18, QFont::Bold);
   
   QFontMetrics fm = QFontMetrics(wonFont);

   int w = fm.width(t) + 20;
   int h = fm.height() * 2;
   
   int pmx = this->width() / 2 - w / 2;
   int pmy = wonLabelVDist - h / 4;

   QPixmap pm( w, h );
   pm.fill( this, pmx, pmy );

   if (fCount == -1) { /* clear area */
      bitBlt( this, pmx, pmy, &pm );
      return;
   }

   QPainter p;
   int x = 10;
   int y = h/2 + fm.descent();
   int i = 0;
   p.begin( &pm );
   p.setFont( wonFont );
   p.setPen( QColor(0,0,0) );
   
   while ( t[i] ) {
      int i16 = (fCount+i) & 15;
      
      p.drawText( x, y-sin_tbl[i16]*h/800, &t[i], 1 );
      x += fm.width( t[i] );
      i++;
   }
   p.end();

// 4: Copy the pixmap to the Hello widget
   bitBlt( this, pmx, pmy, &pm );

}
void OrthogonalRenderer::drawMapObject(QPainter *painter,
                                       const MapObject *object,
                                       const QColor &color) const
{
    painter->save();

    const QRectF bounds = object->bounds();
    QRectF rect(tileToPixelCoords(bounds.topLeft()),
                tileToPixelCoords(bounds.bottomRight()));

    painter->translate(rect.topLeft());
    rect.moveTopLeft(QPointF(0, 0));

    if (!object->cell().isEmpty()) {
        const Cell &cell = object->cell();

        CellRenderer(painter).render(cell, QPointF(),
                                     CellRenderer::BottomLeft);

        if (testFlag(ShowTileObjectOutlines)) {
            const QRect rect = cell.tile->image().rect();
            QPen pen(Qt::SolidLine);
            pen.setWidth(0);
            painter->setPen(pen);
            painter->drawRect(rect);
            pen.setStyle(Qt::DotLine);
            pen.setColor(color);
            painter->setPen(pen);
            painter->drawRect(rect);
        }
    } else {
        const qreal lineWidth = objectLineWidth();
        const QPen linePen(color, lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
        const QPen shadowPen(Qt::black, lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
        const qreal shadowDist = lineWidth == 0 ? (1 / painter->transform().m11()) :
                                                  qMin(qreal(2), lineWidth);
        const QPointF shadowOffset = QPointF(shadowDist * 0.5,
                                             shadowDist * 0.5);

        QColor brushColor = color;
        brushColor.setAlpha(50);
        const QBrush fillBrush(brushColor);

        painter->setRenderHint(QPainter::Antialiasing);

        switch (object->shape()) {
        case MapObject::Rectangle: {
            if (rect.isNull())
                rect = QRectF(QPointF(-10, -10), QSizeF(20, 20));

            const QFontMetrics fm = painter->fontMetrics();
            QString name = fm.elidedText(object->name(), Qt::ElideRight,
                                         rect.width() + 2);

            // Draw the shadow
            painter->setPen(shadowPen);
            painter->drawRect(rect.translated(shadowOffset));
            if (!name.isEmpty())
                painter->drawText(QPointF(0, -4 - lineWidth / 2) + shadowOffset, name);

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawRect(rect);
            if (!name.isEmpty())
                painter->drawText(QPointF(0, -4 - lineWidth / 2), name);

            break;
        }

        case MapObject::Polyline: {
            QPolygonF screenPolygon = tileToPixelCoords(object->polygon());

            painter->setPen(shadowPen);
            painter->drawPolyline(screenPolygon.translated(shadowOffset));

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawPolyline(screenPolygon);
            break;
        }

        case MapObject::Polygon: {
            QPolygonF screenPolygon = tileToPixelCoords(object->polygon());

            painter->setPen(shadowPen);
            painter->drawPolygon(screenPolygon.translated(shadowOffset));

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawPolygon(screenPolygon);
            break;
        }

        case MapObject::Ellipse: {
            if (rect.isNull())
                rect = QRectF(QPointF(-10, -10), QSizeF(20, 20));

            const QFontMetrics fm = painter->fontMetrics();
            QString name = fm.elidedText(object->name(), Qt::ElideRight,
                                         rect.width() + 2);

            // Draw the shadow
            painter->setPen(shadowPen);
            painter->drawEllipse(rect.translated(shadowOffset));
            if (!name.isEmpty())
                painter->drawText(QPoint(1, -5 + 1), name);

            painter->setPen(linePen);
            painter->setBrush(fillBrush);
            painter->drawEllipse(rect);
            if (!name.isEmpty())
                painter->drawText(QPoint(0, -5), name);

            break;
        }
        }
    }

    painter->restore();
}
Beispiel #5
0
QString K3b::cutToWidth( const QFontMetrics& fm, const QString& fullText, int cutWidth )
{
    return fm.elidedText( fullText, Qt::ElideRight, cutWidth );
}
Beispiel #6
0
SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) :
    QWidget(0, f), curAlignment(0)
{
    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;
    float devicePixelRatio      = 1.0;
#if QT_VERSION > 0x050100
    devicePixelRatio = ((QGuiApplication*)QCoreApplication::instance())->devicePixelRatio();
#endif

    // define text to place
    QString titleText       = tr("Bitcoin Core");
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers"));
    QString titleAddText    = networkStyle->getTitleAddText();

    QString font            = QApplication::font().toString();

    // create a bitmap according to device pixelratio
    QSize splashSize(480*devicePixelRatio,320*devicePixelRatio);
    pixmap = QPixmap(splashSize);

#if QT_VERSION > 0x050100
    // change to HiDPI if it makes sense
    pixmap.setDevicePixelRatio(devicePixelRatio);
#endif

    QPainter pixPaint(&pixmap);
    pixPaint.setPen(QColor(100,100,100));

    // draw a slightly radial gradient
    QRadialGradient gradient(QPoint(0,0), splashSize.width()/devicePixelRatio);
    gradient.setColorAt(0, Qt::white);
    gradient.setColorAt(1, QColor(247,247,247));
    QRect rGradient(QPoint(0,0), splashSize);
    pixPaint.fillRect(rGradient, gradient);

    // draw the bitcoin icon, expected size of PNG: 1024x1024
    QRect rectIcon(QPoint(-150,-122), QSize(430,430));

    const QSize requiredSize(1024,1024);
    QPixmap icon(networkStyle->getAppIcon().pixmap(requiredSize));

    pixPaint.drawPixmap(rectIcon, icon);

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(pixmap.width()/devicePixelRatio-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);

    // draw additional text if special network
    if(!titleAddText.isEmpty()) {
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int titleAddTextWidth  = fm.width(titleAddText);
        pixPaint.drawText(pixmap.width()/devicePixelRatio-titleAddTextWidth-10,15,titleAddText);
    }

    pixPaint.end();

    // Set window title
    setWindowTitle(titleText + " " + titleAddText);

    // Resize window and move to center of desktop, disallow resizing
    QRect r(QPoint(), QSize(pixmap.size().width()/devicePixelRatio,pixmap.size().height()/devicePixelRatio));
    resize(r.size());
    setFixedSize(r.size());
    move(QApplication::desktop()->screenGeometry().center() - r.center());

    subscribeToCoreSignals();
}
Beispiel #7
0
void VibratoTimeAxis::paintEvent( QPaintEvent * )
{
  beginDrawing(false);

  fillBackground(colorGroup().background());

  doUpdate();

  if (currentChunkToUse >= 0) {
    QFontMetrics fm = p.fontMetrics();
    QString s;
    p.setBrush(Qt::black);
    p.setFont(QFont("AnyStyle", 12));

    int polyLengthInPixels = toInt((endChunkToUse - startChunkToUse) * zoomFactorX);
    float pixelsPerSecond = polyLengthInPixels / noteLengthToUse;
    int notchesDivider = 2;
    double secondsPerNotch = 5;
    int calculationStep = 1;

    // Calculate which notches and labels to draw
    for (int pixelsPerSecondThreshold = 25; ;pixelsPerSecondThreshold *= 2) {
      if (pixelsPerSecond < pixelsPerSecondThreshold) {
        break;
      } else {
        switch (calculationStep) {
          case 1:
            notchesDivider = 5;
            secondsPerNotch /= 5;
            calculationStep = 2;
            break;
          case 2:
            notchesDivider = 2;
            secondsPerNotch = secondsPerNotch;
            calculationStep = 3;
            break;
          case 3:
            notchesDivider = 2;
            secondsPerNotch /= 2;
            calculationStep = 1;
            break;
        }
      }
    }

    // Draw the notches + labels
    for (int i = 0; i < (noteLengthToUse / secondsPerNotch); i++) {
      int x = toInt((((endChunkToUse - startChunkToUse) * zoomFactorX) / noteLengthToUse) * i * secondsPerNotch - windowOffsetToUse);
      if ((x >= 0) && (x < width())) {
        if (i % notchesDivider == 0) {  // Even: bigger notch + label
          p.drawLine(x, height()-6, x, height()-1);
          // The 1.000001 factors in the following statements prevent freaky rounding/floor errors...
          int minutes = intFloor(i*secondsPerNotch*1.000001) / 60;
          int seconds = intFloor(i*secondsPerNotch*1.000001) % 60;
          int thousandthseconds = intFloor(1000*i*secondsPerNotch*1.000001) % 1000;
          if (thousandthseconds == 0) {  // Label: m:ss
            s.sprintf("%1d:%02d", minutes, seconds);
          } else if (thousandthseconds % 100 == 0) {  // Label: m:ss.h
            s.sprintf("%1d:%02d.%01d", minutes, seconds, thousandthseconds / 100);
          } else if (thousandthseconds % 10 == 0) {  // Label: m:ss.hh
            s.sprintf("%1d:%02d.%02d", minutes, seconds, thousandthseconds / 10);
          } else {  // Label: m:ss.hhh
            s.sprintf("%1d:%02d.%03d", minutes, seconds, thousandthseconds);
          }
          p.drawText(x - fm.width(s)/2, 12, s);
          } else {  // Odd: smaller notch
          p.drawLine(x, height()-3, x, height()-1);
        }
      }
    }

    // Draw the horizontal line at the bottom of the axis
    p.drawLine(0, height()-1, width(), height()-1);
  }
  endDrawing();
}
Beispiel #8
0
void Avatar::renderDisplayName() {

    if (_displayName.isEmpty() || _displayNameAlpha == 0.0f) {
        return;
    }
       
    glDisable(GL_LIGHTING);
    
    glPushMatrix();
    glm::vec3 textPosition = getPosition() + getBodyUpDirection() * ((getSkeletonHeight() + getHeadHeight()) / 1.5f);
    glTranslatef(textPosition.x, textPosition.y, textPosition.z); 

    // we need "always facing camera": we must remove the camera rotation from the stack
    glm::quat rotation = Application::getInstance()->getCamera()->getRotation();
    glm::vec3 axis = glm::axis(rotation);
    glRotatef(glm::angle(rotation), axis.x, axis.y, axis.z);

    // We need to compute the scale factor such as the text remains with fixed size respect to window coordinates
    // We project a unit vector and check the difference in screen coordinates, to check which is the 
    // correction scale needed
    // save the matrices for later scale correction factor 
    glm::dmat4 modelViewMatrix;
    glm::dmat4 projectionMatrix;
    GLint viewportMatrix[4];
    Application::getInstance()->getModelViewMatrix(&modelViewMatrix);
    Application::getInstance()->getProjectionMatrix(&projectionMatrix);
    glGetIntegerv(GL_VIEWPORT, viewportMatrix);
    GLdouble result0[3], result1[3];

    glm::dvec3 upVector(modelViewMatrix[1]);
    
    glm::dvec3 testPoint0 = glm::dvec3(textPosition);
    glm::dvec3 testPoint1 = glm::dvec3(textPosition) + upVector;
    
    bool success;
    success = gluProject(testPoint0.x, testPoint0.y, testPoint0.z,
        (GLdouble*)&modelViewMatrix, (GLdouble*)&projectionMatrix, viewportMatrix, 
        &result0[0], &result0[1], &result0[2]);
    success = success && 
        gluProject(testPoint1.x, testPoint1.y, testPoint1.z,
        (GLdouble*)&modelViewMatrix, (GLdouble*)&projectionMatrix, viewportMatrix, 
        &result1[0], &result1[1], &result1[2]);

    if (success) {
        double textWindowHeight = abs(result1[1] - result0[1]);
        float scaleFactor = (textWindowHeight > EPSILON) ? 1.0f / textWindowHeight : 1.0f;
        glScalef(scaleFactor, scaleFactor, 1.0);  

        // draw a gray background
        QFontMetrics metrics = textRenderer(DISPLAYNAME)->metrics();
        int bottom = -metrics.descent(), top = bottom + metrics.height();
        int left = -_displayNameWidth/2, right = _displayNameWidth/2;
        const int border = 5;
        bottom -= border;
        left -= border;
        top += border;
        right += border;

        // We are drawing coplanar textures with depth: need the polygon offset
        glEnable(GL_POLYGON_OFFSET_FILL);
        glPolygonOffset(1.0f, 1.0f);

        glColor4f(0.2f, 0.2f, 0.2f, _displayNameAlpha);
        glBegin(GL_QUADS);
        glVertex2f(left, bottom);
        glVertex2f(right, bottom);
        glVertex2f(right, top);
        glVertex2f(left, top);
        glEnd();
        
        glScalef(1.0f, -1.0f, 1.0f);  // TextRenderer::draw paints the text upside down in y axis
        glColor4f(0.93f, 0.93f, 0.93f, _displayNameAlpha);
               
        QByteArray ba = _displayName.toLocal8Bit();
        const char* text = ba.data();
        
        glDisable(GL_POLYGON_OFFSET_FILL);
        textRenderer(DISPLAYNAME)->draw(-_displayNameWidth / 2, 0, text); 
     

    }

    glPopMatrix();

    glEnable(GL_LIGHTING);
}
Beispiel #9
0
/*!
    Returns the size that will be used if the width of the label is \a
    w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned
*/
QSize QLabelPrivate::sizeForWidth(int w) const
{
    Q_Q(const QLabel);
    if(q->minimumWidth() > 0)
        w = qMax(w, q->minimumWidth());
    QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin);

    QRect br;

    int hextra = 2 * margin;
    int vextra = hextra;
    QFontMetrics fm = q->fontMetrics();

    if (pixmap && !pixmap->isNull())
        br = pixmap->rect();
#ifndef QT_NO_PICTURE
    else if (picture && !picture->isNull())
        br = picture->boundingRect();
#endif
#ifndef QT_NO_MOVIE
    else if (movie && !movie->currentPixmap().isNull())
        br = movie->currentPixmap().rect();
#endif
    else if (isTextLabel) {
        int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align));
        // Add indentation
        int m = indent;

        if (m < 0 && q->frameWidth()) // no indent, but we do have a frame
            m = fm.width(QLatin1Char('x')) - margin*2;
        if (m > 0) {
            if ((align & Qt::AlignLeft) || (align & Qt::AlignRight))
                hextra += m;
            if ((align & Qt::AlignTop) || (align & Qt::AlignBottom))
                vextra += m;
        }

        if (control) {
            ensureTextLayouted();
            const qreal oldTextWidth = control->textWidth();
            // Calculate the length of document if w is the width
            if (align & Qt::TextWordWrap) {
                if (w >= 0) {
                    w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent
                    control->setTextWidth(w);
                } else {
                    control->adjustSize();
                }
            } else {
                control->setTextWidth(-1);
            }
            br = QRect(QPoint(0, 0), control->size().toSize());

            // restore state
            control->setTextWidth(oldTextWidth);
        } else {
            // Turn off center alignment in order to avoid rounding errors for centering,
            // since centering involves a division by 2. At the end, all we want is the size.
            int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter);
            if (hasShortcut) {
                flags |= Qt::TextShowMnemonic;
                QStyleOption opt;
                opt.initFrom(q);
                if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q))
                    flags |= Qt::TextHideMnemonic;
            }

            bool tryWidth = (w < 0) && (align & Qt::TextWordWrap);
            if (tryWidth)
                w = fm.averageCharWidth() * 80;
            else if (w < 0)
                w = 2000;
            w -= (hextra + contentsMargin.width());
            br = fm.boundingRect(0, 0, w ,2000, flags, text);
            if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2)
                br = fm.boundingRect(0, 0, w/2, 2000, flags, text);
            if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4)
                br = fm.boundingRect(0, 0, w/4, 2000, flags, text);
        }
    } else {
        br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing()));
    }

    const QSize contentsSize(br.width() + hextra, br.height() + vextra);
    return (contentsSize + contentsMargin).expandedTo(q->minimumSize());
}
QSize QwtRichTextEngine::textSize(const QFont &font,
    int flags, const QString& text) const
{
    QwtRichTextDocument doc(text, flags, font);

#if QT_VERSION < 0x040000
    doc.setWidth(QWIDGETSIZE_MAX);

    const int w = doc.widthUsed();
    const int h = doc.height();
    return QSize(w, h);

#else // QT_VERSION >= 0x040000

#if QT_VERSION < 0x040200
    /*
      Unfortunately offering the bounding rect calculation in the
      API of QTextDocument has been forgotten in Qt <= 4.1.x. It
      is planned to come with Qt 4.2.x.
      In the meantime we need a hack with a temporary QLabel,
      to reengineer the internal calculations.
    */

    static int off = 0;
    static QLabel *label = NULL;
    if ( label == NULL )
    {
        label = new QLabel;
        label->hide();

        const char *s = "XXXXX";
        label->setText(s);
        int w1 = label->sizeHint().width();
        const QFontMetrics fm(label->font());
        int w2 = fm.width(s);
        off = w1 - w2;
    }
    label->setFont(doc.defaultFont());
    label->setText(text);

    int w = qwtMax(label->sizeHint().width() - off, 0);
    doc.setPageSize(QSize(w, QWIDGETSIZE_MAX));

    int h = qRound(doc.documentLayout()->documentSize().height());
    return QSize(w, h);

#else // QT_VERSION >= 0x040200

#if QT_VERSION >= 0x040300
    QTextOption option = doc.defaultTextOption();
    if ( option.wrapMode() != QTextOption::NoWrap )
    {
        option.setWrapMode(QTextOption::NoWrap);
        doc.setDefaultTextOption(option);
        doc.adjustSize();
    }
#endif

    return doc.size().toSize();
#endif
#endif
}
Beispiel #11
0
SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle) :
    QWidget(0, f), curAlignment(0)
{
    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = tr("Viacoin Core");
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")) + QChar(0xA9)+QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Viacoin Core developers"));
    QString titleAddText    = networkStyle->getTitleAddText();

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    pixmap     = networkStyle->getSplashImage();

    QPainter pixPaint(&pixmap);
    pixPaint.setPen(QColor(100,100,100));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(pixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(pixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(pixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);

    // draw additional text if special network
    if(!titleAddText.isEmpty()) {
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int titleAddTextWidth  = fm.width(titleAddText);
        pixPaint.drawText(pixmap.width()-titleAddTextWidth-10,15,titleAddText);
    }

    pixPaint.end();

    // Set window title
    setWindowTitle(titleText + " " + titleAddText);

    // Resize window and move to center of desktop, disallow resizing
    QRect r(QPoint(), pixmap.size());
    resize(r.size());
    setFixedSize(r.size());
    move(QApplication::desktop()->screenGeometry().center() - r.center());

    subscribeToCoreSignals();
}
Beispiel #12
0
int TextFactory::stringHeight(const QString &string, const QFontMetrics &metrics) {
  const int count_lines = string.split(QL1C('\n')).size();
  return metrics.height() * count_lines;
}
Beispiel #13
0
void JumpButtonBar::updateButtons()
{
  int currentButton = mGroupBox->selectedId();

  // the easiest way to remove all buttons ;)
  mButtons.setAutoDelete( true );
  mButtons.clear();
  mButtons.setAutoDelete( false );

  QStringList characters;

  // calculate how many buttons are possible
  QFontMetrics fm = fontMetrics();
  QPushButton *btn = new QPushButton( "", this );
  btn->hide();
  QSize buttonSize = style().sizeFromContents( QStyle::CT_PushButton, btn,
                     fm.size( ShowPrefix, "X - X") ).
                     expandedTo( QApplication::globalStrut() );
  delete btn;

  int buttonHeight = buttonSize.height() + 8;
  uint possibleButtons = (height() / buttonHeight) - 1;

  QString character;
  KABC::AddressBook *ab = mCore->addressBook();
  KABC::AddressBook::Iterator it;
  for ( it = ab->begin(); it != ab->end(); ++it ) {
    KABC::Field *field = 0;
    field = mCore->currentSortField();
    if ( field ) {
      setEnabled( true );
      if ( !field->value( *it ).isEmpty() )
        character = field->value( *it )[ 0 ].lower();
    } else {
      setEnabled( false );
      return;
    }

    if ( !character.isEmpty() && !characters.contains( character ) )
      characters.append( character );
  }

  sortListLocaleAware( characters );

  if ( characters.count() <= possibleButtons ) {
    // at first the easy case: all buttons fits in window
    for ( uint i = 0; i < characters.count(); ++i ) {
      JumpButton *button = new JumpButton( characters[ i ], QString::null,
                                           mGroupBox );
      connect( button, SIGNAL( clicked() ), this, SLOT( letterClicked() ) );
      mButtons.append( button );
      button->show();
    }
  } else {
    if ( possibleButtons == 0 ) // to avoid crashes on startup
      return;
    int offset = characters.count() / possibleButtons;
    int odd = characters.count() % possibleButtons;
    if ( odd )
      offset++;

    int current = 0;
    for ( uint i = 0; i < possibleButtons; ++i ) {
      if ( characters.count() - current == 0 )
        continue;
      if ( characters.count() - current <= possibleButtons - i ) {
        JumpButton *button = new JumpButton( characters[ current ],
                                             QString::null, mGroupBox );
        connect( button, SIGNAL( clicked() ), this, SLOT( letterClicked() ) );
        mButtons.append( button );
        button->show();
        current++;
      } else {
        int pos = ( current + offset >= (int)characters.count() ?
                    characters.count() - 1 : current + offset - 1 );
        QString range;
        for ( int j = current; j < pos + 1; ++j )
          range.append( characters[ j ] );
        JumpButton *button = new JumpButton( characters[ current ],
                                             characters[ pos ], mGroupBox );
        connect( button, SIGNAL( clicked() ), this, SLOT( letterClicked() ) );
        mButtons.append( button );
        button->show();
        current = ( i + 1 ) * offset;
      }
    }
  }

  if ( currentButton != -1 )
    mGroupBox->setButton( currentButton );
  else
    mGroupBox->setButton( 0 );

  int maxWidth = 0;
  QPushButton *button;
  for ( button = mButtons.first(); button; button = mButtons.next() )
    maxWidth = QMAX( maxWidth, button->sizeHint().width() );

  setFixedWidth( maxWidth );
}
Beispiel #14
0
/*!
  Resets the tab box to display the active client in TabBoxWindowsMode, or the
  current desktop in TabBoxDesktopListMode
 */
void TabBox::reset( bool partial_reset )
    {
    int w, h, cw = 0, wmax = 0;
    qreal left, top, right, bottom;
    frame.getMargins( left, top, right, bottom );

    QRect r = workspace()->screenGeometry( workspace()->activeScreen());

    // calculate height of 1 line
    // fontheight + 2 pixel above + 2 pixel below, or 32x32 icon + 4 pixel above + below
    lineHeight = qMax(QFontMetrics( KGlobalSettings::smallestReadableFont() ).height() + 2, 32 + 8);

    if ( mode() == TabBoxWindowsMode )
        {
        Client* starting_client = 0;
        if( partial_reset && clients.count() != 0 )
            starting_client = clients.first();
        else
            client = starting_client = workspace()->activeClient();

        // get all clients to show
        createClientList(clients, options_traverse_all ? -1 : workspace()->currentDesktop(), starting_client, true);

        // calculate maximum caption width
        cw = fontMetrics().width(no_tasks) + 20;
        QFont f = font();
        f.setPointSize( KGlobalSettings::smallestReadableFont().pointSize() );
        QFontMetrics fm = QFontMetrics( f );
        for (ClientList::ConstIterator it = clients.constBegin(); it != clients.constEnd(); ++it)
          {
          cw = fm.width( (*it)->caption() );
          if( (*it)->desktop() != wspace->currentDesktop() )
            cw += fm.width( QString( wspace->desktopName((*it)->desktop()) + ": " ) );
          if ( cw > wmax ) wmax = cw;
          }

        // calculate height for the popup
        if ( clients.count() == 0 )  // height for the "not tasks" text
          {
          QFont f = font();
          f.setBold( true );
          f.setPointSize( 14 );

          h = QFontMetrics(f).height()*4;
          }
        else
          {
          showMiniIcon = false;
          h = clients.count() * lineHeight;

          if ( h > (r.height()-(top + bottom)) )  // if too high, use mini icons
            {
            showMiniIcon = true;
            // fontheight + 1 pixel above + 1 pixel below, or 16x16 icon + 2 pixel above + below
            lineHeight = qMax(QFontMetrics( KGlobalSettings::smallestReadableFont() ).height() + 2, 16 + 4);

            h = clients.count() * lineHeight;

            if ( h > (r.height()-(top + bottom)) ) // if still too high, remove some clients
              {
                // how many clients to remove
                int howMany = (h - (r.height()-(top + bottom)))/lineHeight + 1;
                for (; howMany; howMany--)
                  clients.removeAll(clients.last());

                h = clients.count() * lineHeight;
              }
            }
          }
        }
    else
        {
        int starting_desktop;
        if( mode() == TabBoxDesktopListMode )
            {
            starting_desktop = 1;
            createDesktopList(desktops, starting_desktop, StaticOrder );
            }
        else
            { // TabBoxDesktopMode
            starting_desktop = workspace()->currentDesktop();
            createDesktopList(desktops, starting_desktop, MostRecentlyUsedOrder );
            }

        if( !partial_reset )
            desk = workspace()->currentDesktop();

        showMiniIcon = false;

        foreach (int it, desktops)
          {
          cw = fontMetrics().width( workspace()->desktopName(it) );
          if ( cw > wmax ) wmax = cw;
          }

        // calculate height for the popup (max. 16 desktops always fit in a 800x600 screen)
        h = desktops.count() * lineHeight;
        }
Beispiel #15
0
void SpeedPlotView::paintEvent(QPaintEvent *)
{
    QPainter painter(viewport());

    QRect fullRect = viewport()->rect();
    QRect rect = viewport()->rect();
    QFontMetrics fontMetrics = painter.fontMetrics();

    rect.adjust(4, 4, 0, -4); // Add padding

    int maxY = maxYValue();

    rect.adjust(0, fontMetrics.height(), 0, 0); // Add top padding for top speed text

    // draw Y axis speed labels
    QVector<QString> speedLabels = {
        Utils::Misc::friendlyUnit(maxY, true),
        Utils::Misc::friendlyUnit(0.75 * maxY, true),
        Utils::Misc::friendlyUnit(0.5 * maxY, true),
        Utils::Misc::friendlyUnit(0.25 * maxY, true),
        Utils::Misc::friendlyUnit(0, true)
    };

    int yAxeWidth = 0;
    for (const QString &label : speedLabels)
        if (fontMetrics.width(label) > yAxeWidth)
            yAxeWidth = fontMetrics.width(label);

    int i = 0;
    for (const QString &label : speedLabels) {
        QRectF labelRect(rect.topLeft() + QPointF(-yAxeWidth, (i++) * 0.25 * rect.height() - fontMetrics.height()),
                         QSizeF(2 * yAxeWidth, fontMetrics.height()));
        painter.drawText(labelRect, label, Qt::AlignRight | Qt::AlignTop);
    }

    // draw grid lines
    rect.adjust(yAxeWidth + 4, 0, 0, 0);

    QPen gridPen;
    gridPen.setStyle(Qt::DashLine);
    gridPen.setWidthF(1);
    gridPen.setColor(QColor(128, 128, 128, 128));
    painter.setPen(gridPen);

    painter.drawLine(fullRect.left(), rect.top(), rect.right(), rect.top());
    painter.drawLine(fullRect.left(), rect.top() + 0.25 * rect.height(), rect.right(), rect.top() + 0.25 * rect.height());
    painter.drawLine(fullRect.left(), rect.top() + 0.50 * rect.height(), rect.right(), rect.top() + 0.50 * rect.height());
    painter.drawLine(fullRect.left(), rect.top() + 0.75 * rect.height(), rect.right(), rect.top() + 0.75 * rect.height());
    painter.drawLine(fullRect.left(), rect.bottom(), rect.right(), rect.bottom());

    painter.drawLine(rect.left(), fullRect.top(), rect.left(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.2 * rect.width(), fullRect.top(), rect.left() + 0.2 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.4 * rect.width(), fullRect.top(), rect.left() + 0.4 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.6 * rect.width(), fullRect.top(), rect.left() + 0.6 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.8 * rect.width(), fullRect.top(), rect.left() + 0.8 * rect.width(), fullRect.bottom());

    // Set antialiasing for graphs
    painter.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing);

    // draw graphs
    rect.adjust(3, 0, 0, 0); // Need, else graphs cross left gridline

    double yMultiplier = (maxY == 0) ? 0.0 : static_cast<double>(rect.height()) / maxY;
    double xTickSize = static_cast<double>(rect.width()) / m_viewablePointsCount;

    boost::circular_buffer<PointData> &queue = getCurrentData();

    for (int id = UP; id < NB_GRAPHS; ++id) {

        if (!m_properties[static_cast<GraphID>(id)].enable)
            continue;

        QVector<QPoint> points;

        for (int i = int(queue.size()) - 1, j = 0; i >= 0 && j <= m_viewablePointsCount; --i, ++j) {

            int new_x = rect.right() - j * xTickSize;
            int new_y = rect.bottom() - queue[i].y[id] * yMultiplier;

            points.push_back(QPoint(new_x, new_y));
        }

        painter.setPen(m_properties[static_cast<GraphID>(id)].pen);
        painter.drawPolyline(points.data(), points.size());
    }

    // draw legend
    QPoint legendTopLeft(rect.left() + 4, fullRect.top() + 4);

    double legendHeight = 0;
    int legendWidth = 0;
    for (const auto &property : m_properties) {

        if (!property.enable)
            continue;

        if (fontMetrics.width(property.name) > legendWidth)
            legendWidth =  fontMetrics.width(property.name);
        legendHeight += 1.5 * fontMetrics.height();
    }

    QRectF legendBackgroundRect(QPoint(legendTopLeft.x() - 4, legendTopLeft.y() - 4), QSizeF(legendWidth + 8, legendHeight + 8));
    QColor legendBackgroundColor = QWidget::palette().color(QWidget::backgroundRole());
    legendBackgroundColor.setAlpha(128);  // 50% transparent
    painter.fillRect(legendBackgroundRect, legendBackgroundColor);

    i = 0;
    for (const auto &property : m_properties) {

        if (!property.enable)
            continue;

        int nameSize = fontMetrics.width(property.name);
        double indent = 1.5 * (i++) * fontMetrics.height();

        painter.setPen(property.pen);
        painter.drawLine(legendTopLeft + QPointF(0, indent + fontMetrics.height()),
                         legendTopLeft + QPointF(nameSize, indent + fontMetrics.height()));
        painter.drawText(QRectF(legendTopLeft + QPointF(0, indent), QSizeF(2 * nameSize, fontMetrics.height())),
                         property.name, QTextOption(Qt::AlignVCenter));
    }
}
Beispiel #16
0
void SessionButton::redraw()
{
    bool snd;


    X2goSettings *st;

    if (par->brokerMode)
        st=new X2goSettings(par->config.iniFile,QSettings::IniFormat);
    else
        st= new X2goSettings( "sessions" );

    QString name=st->setting()->value ( sid+"/name",
                                        ( QVariant ) tr ( "New Session" ) ).toString();

    QStringList tails=name.split("/",QString::SkipEmptyParts);
    if(tails.count()>0)
    {
        name=tails.last();
        tails.pop_back();
        path=tails.join("/");
    }

    sessName->setText (name);

    QString status=st->setting()->value ( sid+"/status",
                                          ( QVariant ) QString::null ).toString();
    if (status == "R")
    {
        sessStatus->setText("("+tr("running")+")");
    }
    if (status == "S")
    {
        sessStatus->setText("("+tr("suspended")+")");
    }

    QString sessIcon = wrap_legacy_resource_URIs (st->setting()->value (sid+"/icon",
                                                                        (QVariant) ":/img/icons/128x128/x2gosession.png"
                                                                       ).toString ());
    sessIcon = expandHome(sessIcon);
    QPixmap* pix;

    x2goDebug << "Creating QPixmap with session icon: " << sessIcon.toAscii () << ".";
    if (!par->brokerMode || sessIcon == ":/img/icons/128x128/x2gosession.png")
        pix=new QPixmap( sessIcon );
    else
    {
        pix=new QPixmap;
        pix->loadFromData(QByteArray::fromBase64(sessIcon.toAscii()));
    }
    if ( !par->retMiniMode() )
        icon->setPixmap ( pix->scaled ( 64,64,Qt::IgnoreAspectRatio,
                                        Qt::SmoothTransformation ) );
    else
        icon->setPixmap ( pix->scaled ( 48,48,Qt::IgnoreAspectRatio,
                                        Qt::SmoothTransformation ) );

    delete pix;
    QString sv=st->setting()->value ( sid+"/host", ( QVariant )
                                      QString::null ).toString();
    QString uname=st->setting()->value ( sid+"/user", ( QVariant )
                                         QString::null ).toString();
    server->setText ( uname+"@"+sv );

    QString command=st->setting()->value ( sid+"/command",
                                           ( QVariant )
                                           tr (
                                                   "KDE" ) ).
                    toString();
    rootless=st->setting()->value ( sid+"/rootless",
                                    false ).toBool();
    published=st->setting()->value ( sid+"/published",
                                     false ).toBool();


    cmdBox->clear();
    cmdBox->addItem ( "KDE" );
    cmdBox->addItem ( "GNOME" );
    cmdBox->addItem ( "LXDE" );
    cmdBox->addItem ( "XFCE" );
    cmdBox->addItem ( "MATE" );
    cmdBox->addItem ( "UNITY" );
    cmdBox->addItem ( "CINNAMON" );
    cmdBox->addItem ( "TRINITY" );
    cmdBox->addItem ( "OPENBOX" );
    cmdBox->addItem ( "ICEWM" );
    cmdBox->addItem ( tr ( "RDP connection" ) );
    cmdBox->addItem ( tr ( "XDMCP" ) );
    cmdBox->addItem ( tr ( "Connection to local desktop" ) );
    cmdBox->addItem ( tr ( "Published applications" ) );

    cmdBox->addItems ( par->transApplicationsNames() );

    bool directRDP=false;
    QPixmap cmdpix;
    if ( command=="KDE" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/kde.png" ) );
        cmdBox->setCurrentIndex ( KDE );
    }
    else if ( command =="GNOME" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/gnome.png" ) );
        cmdBox->setCurrentIndex ( GNOME );
    }
    else if ( command =="UNITY" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/unity.png" ) );
        cmdBox->setCurrentIndex ( UNITY );
    }
    else if ( command == "XFCE" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/xfce.png" ) );
        cmdBox->setCurrentIndex ( XFCE );
    }
    else if ( command == "MATE" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/mate.png" ) );
        cmdBox->setCurrentIndex ( MATE );
    }
    else if ( command =="LXDE" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/lxde.png" ) );
        cmdBox->setCurrentIndex ( LXDE );
    }
    else if ( command == "CINNAMON" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/cinnamon.png" ) );
        cmdBox->setCurrentIndex ( CINNAMON );
    }
    else if ( command == "TRINITY" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/trinity.png" ) );
        cmdBox->setCurrentIndex ( TRINITY );
    }
    else if ( command == "OPENBOX" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/openbox.png" ) );
        cmdBox->setCurrentIndex ( OPENBOX );
    }
    else if ( command == "ICEWM" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/icewm.png" ) );
        cmdBox->setCurrentIndex ( ICEWM );
    }
    else if ( command =="SHADOW" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/X.png" ) );
        cmdBox->setCurrentIndex ( SHADOW );
        command=tr ( "Connection to local desktop" );
    }
    else if ( command =="RDP" )
    {
        if (st->setting()->value ( sid+"/directrdp",
                                   ( QVariant ) false ).toBool())
            directRDP=true;
        cmdpix.load ( par->iconsPath ( "/16x16/rdp.png" ) );
        cmdBox->setCurrentIndex ( RDP );
        command=tr ( "RDP connection" );
    }
    else if ( command =="XDMCP" )
    {
        cmdpix.load ( par->iconsPath ( "/16x16/X.png" ) );
        cmdBox->setCurrentIndex ( XDMCP );
        command=tr ( "XDMCP" );
    }
    else if (published)
    {
        cmdpix.load ( par->iconsPath ( "/16x16/X.png" ) );
        command=tr ("Published applications");
        cmdBox->setCurrentIndex (PUBLISHED);
    }
    else
    {
        cmdpix.load ( par->iconsPath ( "/16x16/X.png" ) );
        command=par->transAppName ( command );
        int id= cmdBox->findText ( command );
        if ( id ==-1 )
        {
            cmdBox->addItem ( command );
            cmdBox->setCurrentIndex ( cmdBox->count()-1 );
        }
        else
            cmdBox->setCurrentIndex ( id );
    }



    cmdIcon->setPixmap ( cmdpix );
    cmd->setText ( command );


    geomBox->clear();
    geomBox->addItem ( tr ( "fullscreen" ) );
    uint displays=QApplication::desktop()->numScreens();
    if (!directRDP)
        for (uint i=0; i<displays; ++i)
        {
            geomBox->addItem ( tr( "Display " )+QString::number(i+1));

            //add maximun available area
            geomBox->addItem( QString::number(QApplication::desktop()->availableGeometry(i).width()) + "x" + QString::number(QApplication::desktop()->availableGeometry(i).height()));


        }
#ifndef Q_WS_HILDON


    geomBox->addItem ( "1440x900" );
    geomBox->addItem ( "1280x1024" );
    geomBox->addItem ( "1024x768" );
    geomBox->addItem ( "800x600" );
#else
    geomBox->addItem ( tr ( "window" ) );
#endif
    if ( st->setting()->value ( sid+"/fullscreen",
                                ( QVariant ) false ).toBool() )
    {
        geom->setText ( tr ( "fullscreen" ) );
    }
    else if (st->setting()->value ( sid+"/multidisp",
                                    ( QVariant ) false ).toBool() && !directRDP)
    {
        uint disp=st->setting()->value ( sid+"/display",
                                         ( QVariant ) 1 ).toUInt();
        if (disp<=displays)
        {
            geom->setText( tr( "Display " )+QString::number(disp));
        }
        else
        {
            geom->setText( tr( "Display " )+QString::number(1));
        }
        for (int i=0; i<geomBox->count(); ++i)
            if (geomBox->itemText(i)==geom->text())
            {
                geomBox->setCurrentIndex(i);
                break;
            }
    }
    else
    {
#ifndef	Q_WS_HILDON
        QString g=QString::number ( st->setting()->value (
                                        sid+"/width" ).toInt() );
        g+="x"+QString::number ( st->setting()->value (
                                     sid+"/height" ).toInt() );
        geom->setText ( g );
        if ( geomBox->findText ( g ) ==-1 )
            geomBox->addItem ( g );
        geomBox->setCurrentIndex ( geomBox->findText ( g ) );
#else
        geom->setText ( tr ( "window" ) );
        geomBox->setCurrentIndex ( 1 );
#endif
    }

    if (directRDP)
    {
        geomBox->addItem ( tr("Maximum") );
        if (st->setting()->value ( sid+"/maxdim",
                                   ( QVariant ) false ).toBool())
        {
            geom->setText ( tr("Maximum") );
            geomBox->setCurrentIndex ( geomBox->findText ( tr("Maximum") ));
        }
    }


    snd=st->setting()->value ( sid+"/sound", ( QVariant ) true ).toBool();
    if ( snd )
        sound->setText ( tr ( "Enabled" ) );
    else
        sound->setText ( tr ( "Disabled" ) );
    soundIcon->setEnabled ( snd );
    QFontMetrics fm ( sound->font() );
    sound->setFixedSize ( fm.size ( Qt::TextSingleLine,sound->text() ) +
                          QSize ( 8,4 ) );

    sessName->setMinimumSize ( sessName->sizeHint() );
    geom->setMinimumSize ( geom->sizeHint() );
    cmd->setMinimumSize ( cmd->sizeHint() );
    server->setMinimumSize ( server->sizeHint() );
    delete st;
}
Beispiel #17
0
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f, bool isTestNet) :
    QSplashScreen(pixmap, f)
{
    setAutoFillBackground(true);

    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = tr("naturacoin Core");
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers\n")) + QChar(0xA9)+QString(" 2013-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The naturacoin Core developers"));
    QString testnetAddText  = QString(tr("[testnet]")); // define text to place as single text object

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(isTestNet) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(100,100,100));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    QRect copyrightRect = QRect(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,fm.width(copyrightText),fm.height()*2);
    pixPaint.drawText(copyrightRect,Qt::TextWordWrap,copyrightText);

    // draw testnet string if testnet is on
    if(isTestNet) {
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int testnetAddTextWidth  = fm.width(testnetAddText);
        pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    }

    pixPaint.end();

    this->setPixmap(newPixmap);

    subscribeToCoreSignals();
}
Beispiel #18
0
void TimelineBar::paintEvent(QPaintEvent *e)
{
  QPainter p(viewport());

  p.setFont(font());
  p.setRenderHint(QPainter::TextAntialiasing);

  // draw boundaries and background
  {
    QRectF r = viewport()->rect();

    p.fillRect(r, palette().brush(QPalette::Window));

    r = r.marginsRemoved(QMargins(borderWidth + margin, borderWidth + margin, borderWidth + margin,
                                  borderWidth + margin));

    p.fillRect(r, palette().brush(QPalette::Base));
    p.drawRect(r);
  }

  QTextOption to;

  to.setWrapMode(QTextOption::NoWrap);
  to.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

  QFontMetrics fm = p.fontMetrics();

  {
    QRectF titleRect = m_eidAxisRect;
    titleRect.setLeft(titleRect.left() - m_titleWidth);
    titleRect.setWidth(m_titleWidth);

    p.setPen(QPen(palette().brush(QPalette::Text), 1.0));

    // add an extra margin for the text
    p.drawText(titleRect.marginsRemoved(QMarginsF(margin, 0, 0, 0)), eidAxisTitle, to);

    titleRect.setLeft(titleRect.left() - margin);
    titleRect.setTop(titleRect.top() - margin);
    p.drawLine(titleRect.bottomLeft(), titleRect.bottomRight());
    p.drawLine(titleRect.topRight(), titleRect.bottomRight());
  }

  QRectF eidAxisRect = m_eidAxisRect;

  p.drawLine(eidAxisRect.bottomLeft(), eidAxisRect.bottomRight() + QPointF(margin, 0));

  p.drawLine(m_highlightingRect.topLeft(), m_highlightingRect.topRight());

  if(m_Draws.isEmpty())
    return;

  eidAxisRect.setLeft(m_eidAxisRect.left() + m_pan);

  uint32_t maxEID = m_Draws.isEmpty() ? 0 : m_Draws.back();

  to.setAlignment(Qt::AlignCenter | Qt::AlignVCenter);

  p.setFont(Formatter::PreferredFont());

  QRectF hoverRect = eidAxisRect;

  // clip labels to the visible section
  p.setClipRect(m_eidAxisRect.marginsAdded(QMargins(0, margin, margin, 0)));

  // draw where we're hovering
  {
    QPoint pos = viewport()->mapFromGlobal(QCursor::pos());

    if(m_dataArea.contains(pos))
    {
      uint32_t hoverEID = eventAt(pos.x());

      hoverRect.setLeft(offsetOf(hoverEID));
      hoverRect.setWidth(m_eidAxisLabelWidth);

      // recentre
      hoverRect.moveLeft(hoverRect.left() - m_eidAxisLabelWidth / 2 + m_eidWidth / 2);

      QColor backCol = palette().color(QPalette::Base);

      if(getLuminance(backCol) < 0.2f)
        backCol = backCol.lighter(120);
      else
        backCol = backCol.darker(120);

      QRectF backRect = hoverRect.marginsAdded(QMargins(0, margin - borderWidth, 0, 0));

      backRect.setLeft(qMax(backRect.left(), m_eidAxisRect.left() + 1));

      p.fillRect(backRect, backCol);

      p.drawText(hoverRect, QString::number(hoverEID), to);

      // re-add the top margin so the lines match up with the border around the EID axis
      hoverRect = hoverRect.marginsAdded(QMargins(0, margin, 0, 0));

      if(hoverRect.left() >= m_eidAxisRect.left())
        p.drawLine(hoverRect.topLeft(), hoverRect.bottomLeft());
      p.drawLine(hoverRect.topRight(), hoverRect.bottomRight());

      // shrink the rect a bit for clipping against labels below
      hoverRect.setX(qRound(hoverRect.x() + 0.5));
      hoverRect.setWidth(int(hoverRect.width()));
    }
    else
    {
      hoverRect = QRectF();
    }
  }

  QRectF labelRect = eidAxisRect;
  labelRect.setWidth(m_eidAxisLabelWidth);

  // iterate through the EIDs from 0, starting from possible a negative offset if the user has
  // panned to the right.
  for(uint32_t i = 0; i <= maxEID; i += m_eidAxisLabelStep)
  {
    labelRect.moveLeft(offsetOf(i) - labelRect.width() / 2 + m_eidWidth / 2);

    // check if this label is visible at all, but don't draw labels that intersect with the hovered
    // number
    if(labelRect.right() >= 0 && !labelRect.intersects(hoverRect))
      p.drawText(labelRect, QString::number(i), to);

    // check if labelRect is off the edge of the screen
    if(labelRect.left() >= m_eidAxisRect.right())
      break;
  }

  // stop clipping
  p.setClipRect(viewport()->rect());

  // clip the markers
  p.setClipRect(m_markerRect);

  {
    QPen pen = p.pen();
    paintMarkers(p, m_RootMarkers, m_RootDraws, m_markerRect);
    p.setPen(pen);
  }

  // stop clipping
  p.setClipRect(viewport()->rect());

  QRectF currentRect = eidAxisRect;

  // draw the current label and line
  {
    uint32_t curEID = m_Ctx.CurEvent();

    currentRect.setLeft(offsetOf(curEID));
    currentRect.setWidth(
        qMax(m_eidAxisLabelWidth, m_eidAxisLabelTextWidth + dataBarHeight + margin * 2));

    // recentre
    currentRect.moveLeft(currentRect.left() - currentRect.width() / 2 + m_eidWidth / 2);

    // remember where the middle would have been, without clamping
    qreal realMiddle = currentRect.center().x();

    // clamp the position from the left or right side
    if(currentRect.left() < eidAxisRect.left())
      currentRect.moveLeft(eidAxisRect.left());
    else if(currentRect.right() > eidAxisRect.right())
      currentRect.moveRight(eidAxisRect.right());

    // re-add the top margin so the lines match up with the border around the EID axis
    QRectF currentBackRect = currentRect.marginsAdded(QMargins(0, margin, 0, 0));

    p.fillRect(currentBackRect, palette().brush(QPalette::Base));
    p.drawRect(currentBackRect);

    // draw the 'current marker' pixmap
    const QPixmap &px = Pixmaps::flag_green(devicePixelRatio());
    p.drawPixmap(currentRect.topLeft() + QPointF(margin, 1), px, px.rect());

    // move to where the text should be and draw it
    currentRect.setLeft(currentRect.left() + margin * 2 + dataBarHeight);
    p.drawText(currentRect, QString::number(curEID), to);

    // draw a line from the bottom of the shadow downwards
    QPointF currentTop = currentRect.center();
    currentTop.setX(int(qBound(eidAxisRect.left(), realMiddle, eidAxisRect.right() - 2.0)) + 0.5);
    currentTop.setY(currentRect.bottom());

    QPointF currentBottom = currentTop;
    currentBottom.setY(m_markerRect.bottom());

    p.drawLine(currentTop, currentBottom);
  }

  to.setAlignment(Qt::AlignLeft | Qt::AlignTop);

  if(!m_UsageTarget.isEmpty() || !m_HistoryTarget.isEmpty())
  {
    p.setRenderHint(QPainter::Antialiasing);

    QRectF highlightLabel = m_highlightingRect.marginsRemoved(uniformMargins(margin));

    highlightLabel.setX(highlightLabel.x() + margin);

    QString text;

    if(!m_HistoryTarget.isEmpty())
      text = tr("Pixel history for %1").arg(m_HistoryTarget);
    else
      text = tr("Usage for %1:").arg(m_UsageTarget);

    p.drawText(highlightLabel, text, to);

    const int triRadius = fm.averageCharWidth();
    const int triHeight = fm.ascent();

    QPainterPath triangle;
    triangle.addPolygon(
        QPolygonF({QPoint(0, triHeight), QPoint(triRadius * 2, triHeight), QPoint(triRadius, 0)}));
    triangle.closeSubpath();

    enum
    {
      ReadUsage,
      WriteUsage,
      ReadWriteUsage,
      ClearUsage,
      BarrierUsage,

      HistoryPassed,
      HistoryFailed,

      UsageCount,
    };

    const QColor colors[UsageCount] = {
        // read
        QColor(Qt::red),
        // write
        QColor(Qt::green),
        // read/write
        QColor(Qt::yellow),
        // clear
        QColor(Qt::blue),
        // barrier
        QColor(Qt::magenta),

        // pass
        QColor(Qt::green),
        // fail
        QColor(Qt::red),
    };

    // draw the key
    if(m_HistoryTarget.isEmpty())
    {
      // advance past the first text to draw the key
      highlightLabel.setLeft(highlightLabel.left() + fm.width(text));

      text = lit(" Reads ( ");
      p.drawText(highlightLabel, text, to);
      highlightLabel.setLeft(highlightLabel.left() + fm.width(text));

      QPainterPath path = triangle.translated(aliasAlign(highlightLabel.topLeft()));
      p.fillPath(path, colors[ReadUsage]);
      p.drawPath(path);
      highlightLabel.setLeft(highlightLabel.left() + triRadius * 2);

      text = lit(" ), Writes ( ");
      p.drawText(highlightLabel, text, to);
      highlightLabel.setLeft(highlightLabel.left() + fm.width(text));

      path = triangle.translated(aliasAlign(highlightLabel.topLeft()));
      p.fillPath(path, colors[WriteUsage]);
      p.drawPath(path);
      highlightLabel.setLeft(highlightLabel.left() + triRadius * 2);

      text = lit(" ), Read/Write ( ");
      p.drawText(highlightLabel, text, to);
      highlightLabel.setLeft(highlightLabel.left() + fm.width(text));

      path = triangle.translated(aliasAlign(highlightLabel.topLeft()));
      p.fillPath(path, colors[ReadWriteUsage]);
      p.drawPath(path);
      highlightLabel.setLeft(highlightLabel.left() + triRadius * 2);

      if(m_Ctx.CurPipelineState().SupportsBarriers())
      {
        text = lit(" ) Barriers ( ");
        p.drawText(highlightLabel, text, to);
        highlightLabel.setLeft(highlightLabel.left() + fm.width(text));

        path = triangle.translated(aliasAlign(highlightLabel.topLeft()));
        p.fillPath(path, colors[BarrierUsage]);
        p.drawPath(path);
        highlightLabel.setLeft(highlightLabel.left() + triRadius * 2);
      }

      text = lit(" ), and Clears ( ");
      p.drawText(highlightLabel, text, to);
      highlightLabel.setLeft(highlightLabel.left() + fm.width(text));

      path = triangle.translated(aliasAlign(highlightLabel.topLeft()));
      p.fillPath(path, colors[ClearUsage]);
      p.drawPath(path);
      highlightLabel.setLeft(highlightLabel.left() + triRadius * 2);

      text = lit(" )");
      p.drawText(highlightLabel, text, to);
    }

    PipRanges pipranges[UsageCount];

    QRectF pipsRect = m_highlightingRect.marginsRemoved(uniformMargins(margin));

    pipsRect.setX(pipsRect.x() + margin + m_titleWidth);
    pipsRect.setHeight(triHeight + margin);
    pipsRect.moveBottom(m_highlightingRect.bottom());

    p.setClipRect(pipsRect);

    qreal leftClip = -triRadius * 2.0;
    qreal rightClip = pipsRect.width() + triRadius * 10.0;

    if(!m_HistoryEvents.isEmpty())
    {
      for(const PixelModification &mod : m_HistoryEvents)
      {
        qreal pos = offsetOf(mod.eventId) + m_eidWidth / 2 - triRadius;

        if(pos < leftClip || pos > rightClip)
          continue;

        if(mod.Passed())
          pipranges[HistoryPassed].push(pos, triRadius);
        else
          pipranges[HistoryFailed].push(pos, triRadius);
      }
    }
    else
    {
      for(const EventUsage &use : m_UsageEvents)
      {
        qreal pos = offsetOf(use.eventId) + m_eidWidth / 2 - triRadius;

        if(pos < leftClip || pos > rightClip)
          continue;

        if(((int)use.usage >= (int)ResourceUsage::VS_RWResource &&
            (int)use.usage <= (int)ResourceUsage::All_RWResource) ||
           use.usage == ResourceUsage::GenMips || use.usage == ResourceUsage::Copy ||
           use.usage == ResourceUsage::Resolve)
        {
          pipranges[ReadWriteUsage].push(pos, triRadius);
        }
        else if(use.usage == ResourceUsage::StreamOut || use.usage == ResourceUsage::ResolveDst ||
                use.usage == ResourceUsage::ColorTarget ||
                use.usage == ResourceUsage::DepthStencilTarget || use.usage == ResourceUsage::CopyDst)
        {
          pipranges[WriteUsage].push(pos, triRadius);
        }
        else if(use.usage == ResourceUsage::Clear)
        {
          pipranges[ClearUsage].push(pos, triRadius);
        }
        else if(use.usage == ResourceUsage::Barrier)
        {
          pipranges[BarrierUsage].push(pos, triRadius);
        }
        else
        {
          pipranges[ReadUsage].push(pos, triRadius);
        }
      }
    }

    for(int i = 0; i < UsageCount; i++)
    {
      QPainterPath path = pipranges[i].makePath(triRadius, triHeight, pipsRect.y());

      if(!path.isEmpty())
      {
        p.drawPath(path);
        p.fillPath(path, colors[i]);
      }
    }
  }
  else
  {
    QRectF highlightLabel = m_highlightingRect;
    highlightLabel = highlightLabel.marginsRemoved(uniformMargins(margin));

    highlightLabel.setX(highlightLabel.x() + margin);

    p.drawText(highlightLabel, tr("No resource selected for highlighting."), to);
  }
}
Beispiel #19
0
void
MarkerRuler::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    painter.setFont(*m_barFont);

    if (getHScaleFactor() != 1.0)
        painter.scale(getHScaleFactor(), 1.0);

    // See note elsewhere...
    QRect clipRect = visibleRegion().boundingRect();

    // In a stylesheet world, we have to paint our our own background to rescue
    // it from the muddle of QWidget background style hacks
    QBrush bg = QBrush(GUIPalette::getColour(GUIPalette::RulerBackground));
    painter.fillRect(clipRect, bg);

    // Now we set the pen dungle flungy to the newly defined foreground color in
    // GUIPalette to make the text all pretty like again.  (Whew.)
    painter.setPen(GUIPalette::getColour(GUIPalette::RulerForeground));

    int firstBar = m_rulerScale->getBarForX(clipRect.x() -
                                            m_currentXOffset -
                                            m_xorigin);
    int lastBar = m_rulerScale->getLastVisibleBar();
    if (firstBar < m_rulerScale->getFirstVisibleBar()) {
        firstBar = m_rulerScale->getFirstVisibleBar();
    }

    painter.drawLine(m_currentXOffset, 0, static_cast<int>(clipRect.width() / getHScaleFactor()), 0);

    float minimumWidth = 25.0;
    float testSize = ((float)(m_rulerScale->getBarPosition(firstBar + 1) -
                              m_rulerScale->getBarPosition(firstBar)))
                     / minimumWidth;

    int every = 0;
    int count = 0;

    if (testSize < 1.0) {
        every = (int(1.0 / testSize));

        if (every % 2 == 0)
            every++;
    }

    for (int i = firstBar; i <= lastBar; ++i) {

        double x = m_rulerScale->getBarPosition(i) + m_xorigin + m_currentXOffset;

        if ((x * getHScaleFactor()) > clipRect.x() + clipRect.width())
            break;

        // always the first bar number
        if (every && i != firstBar) {
            if (count < every) {
                count++;
                continue;
            }

            // reset count if we passed
            count = 0;
        }

        // adjust count for first bar line
        if (every == firstBar)
            count++;

        if (i != lastBar) {
            painter.drawLine(static_cast<int>(x), 0, static_cast<int>(x), m_barHeight);

            // disable worldXForm for text
            //QPoint textDrawPoint = painter.xForm(QPoint(static_cast<int>(x + 4), 12));
            QPoint textDrawPoint = QPoint(static_cast<int>(x + 4), 12) * painter.combinedTransform();

            bool enableXForm = painter.worldMatrixEnabled();
            painter.setWorldMatrixEnabled(false);

            if (i >= 0)
                painter.drawText(textDrawPoint, QString("%1").arg(i + 1));

            painter.setWorldMatrixEnabled(enableXForm);
        } else {
            const QPen normalPen = painter.pen();
            ;
            QPen endPen(Qt::black, 2);
            painter.setPen(endPen);
            painter.drawLine(static_cast<int>(x), 0, static_cast<int>(x), m_barHeight);
            painter.setPen(normalPen);
        }
    }

    if (m_doc) {
        Composition &comp = m_doc->getComposition();
        Composition::markercontainer markers = comp.getMarkers();
        Composition::markerconstiterator it;

        timeT start = comp.getBarStart(firstBar);
        timeT end = comp.getBarEnd(lastBar);

        QFontMetrics metrics = painter.fontMetrics();

        for (it = markers.begin(); it != markers.end(); ++it) {
            if ((*it)->getTime() >= start && (*it)->getTime() < end) {
                QString name(strtoqstr((*it)->getName()));

                double x = m_rulerScale->getXForTime((*it)->getTime())
                           + m_xorigin + m_currentXOffset;

                painter.fillRect(static_cast<int>(x), 1,
                                 static_cast<int>(metrics.width(name) + 5),
                                 m_barHeight - 2,
                                 QBrush(GUIPalette::getColour(GUIPalette::MarkerBackground)));

                painter.drawLine(int(x), 1, int(x), m_barHeight - 2);
                painter.drawLine(int(x) + 1, 1, int(x) + 1, m_barHeight - 2);

                // NO_QT3 NOTE:  This next bit is a complete shot in the dark,
                // and is likely to be wrong.

                // was:
                //
                //QPoint textDrawPoint = painter.xForm
                //                       (QPoint(static_cast<int>(x + 3), m_barHeight - 4));
                //

                QPoint textDrawPoint = QPoint(static_cast<int>(x + 3), m_barHeight - 4) * painter.combinedTransform();

                // disable worldXForm for text
                bool enableXForm = painter.worldMatrixEnabled();
                painter.setWorldMatrixEnabled(false);
                
                painter.drawText(textDrawPoint, name);

                painter.setWorldMatrixEnabled(enableXForm);
            }
        }
    }
}
Beispiel #20
0
void MarkListTable::paintCell( QPainter *p, int row, int col)
{
	QColorGroup cg = QApplication::palette()->normal();
	
	if ( col == 0  )
	{
	
		if ( items.at( row )->select() )
			{
				//p->setBrush( selectColor );
				//p->setPen( selectColor );
				p->setBrush(cg.base());
				p->setPen(cg.base());
			}
		else {
			p->setBrush(cg.base());
				p->setPen(cg.base());
		}	
		p->drawRect(0,0,cellWidth(0),cellHeight());
		
		if( items.at( row )->mark() ) {
		
		int xOffset=6; int yOffset=3;
		
		if ( items.at( row )->select() )
			p->setPen( cg.text() ); //p->setPen( selectTextColor );
		else
			p->setPen( cg.text() );
		p->drawLine( xOffset+4, yOffset, xOffset+4, yOffset+9 );
		p->setPen( red );
		p->drawLine( xOffset+3, yOffset+1, xOffset, yOffset+4 );
		p->drawLine( xOffset+3, yOffset+1, xOffset+3, yOffset+4 );
		p->drawLine( xOffset, yOffset+4, xOffset+3, yOffset+4 );
		} else {
			int xOffset=4; int yOffset=5;
			
			p->setPen( cg.dark() );
			p->setBrush( cg.dark() );
			p->drawEllipse( xOffset+4, yOffset, 4, 4 );
			
			//p->setPen( cg.mid() );
			//p->setBrush( cg.mid() );
			//p->drawEllipse( xOffset+5, yOffset+1, 2, 2 );
			
			p->setPen( white );
			p->drawPoint( xOffset+5, yOffset+1);
		}	
	}

	/*if ( col == 1 )
	{
		if ( items.at( row )->select() )
		{
			p->setBrush(selectColor);
			p->setPen(selectColor);
			p->drawRect(0,0,cellWidth(1),cellHeight());
			
			//qDrawShadePanel( p, 3, 2, cellHeight( 1 ) - 6, cellHeight(1)-4,
			//	cg, FALSE, 1, &QBrush(colorGroup().light()));
			
			p->setBrush(white);
			p->setPen(black);	
			p->drawRect(3,2,cellHeight( 1 ) - 7, cellHeight(1)-5);
			
		} else {
			
			p->setBrush(cg.base());
				p->setPen(cg.base());
			p->drawRect(0,0,cellWidth(1),cellHeight());
			
			//qDrawShadePanel( p, 3, 2, cellHeight( 1 ) - 6, cellHeight(1)-4,
			//	cg, FALSE,1 );
				
			p->setBrush(white);
			p->setPen(black);	
			p->drawRect(3,2,cellHeight( 1 ) - 7, cellHeight(1)-5);
			
		}

		//QFontMetrics fm = p->fontMetrics();
		//int yPos;   // vertical text position
		//if ( 10 < fm.height() )
		//	yPos = fm.ascent() + fm.leading()/2;
		//else
		//	yPos = 5 - fm.height()/2 + fm.ascent();
		//p->drawText( 4, yPos, items.at( row )->text() );
	}*/
	
	if ( col == 1 )
	{
		if ( items.at( row )->select() )
			{
				p->setBrush(selectColor);
				p->setPen(selectColor);
			}
		else {
			p->setBrush(cg.base());
				p->setPen(cg.base());
		}	
		p->drawRect(0,0,cellWidth(2),cellHeight());
		
		
		/*  if ( items.at( row )->select() )
		{
			QColorGroup cg = QApplication::palette()->normal();
			qDrawShadePanel( p, 0, 0, cellWidth( 1 ) - 1, cellHeight(),
				cg, FALSE, 1, &QBrush(colorGroup().light()));
		}*/
		
		if ( items.at( row )->select() )
			p->setPen(selectTextColor);
		else
			p->setPen(cg.text());
		QFontMetrics fm = p->fontMetrics();
		int yPos;   // vertical text position
		/*if ( 10 < fm.height() )
			yPos = fm.ascent() + fm.leading()/2;
		else*/
			yPos = cellHeight()-fm.leading()/2;
			yPos = fm.ascent() + fm.leading()/2+1;
		p->drawText( 4, yPos, items.at( row )->text() );
	}
}
void MeasureToolPlugin::drawSegments( GeoPainter* painter )
{
    for ( int segmentIndex = 0; segmentIndex < m_measureLineString.size() - 1; ++segmentIndex ) {
        GeoDataLineString segment( Tessellate );
        segment << m_measureLineString[segmentIndex] ;
        segment << m_measureLineString[segmentIndex + 1];

        QPen shadowPen( Oxygen::aluminumGray5 );
        shadowPen.setWidthF(4.0);
        painter->setPen( shadowPen );
        painter->drawPolyline( segment );

        QString infoString;

        if ( (m_paintMode == Polygon && m_showDistanceLabel)
             || (m_paintMode == Circular && m_showRadius) ) {
            const qreal segmentLength = segment.length( marbleModel()->planet()->radius() );
            m_radius = segmentLength;

            infoString = meterToPreferredUnit(segmentLength);
        }

        if ( m_showBearingLabel && m_paintMode != Circular ) {
            GeoDataCoordinates coordinates = segment.first();
            qreal bearing = coordinates.bearing( segment.last(), GeoDataCoordinates::Degree );

            if ( bearing < 0 ) {
                bearing += 360;
            }
            QString bearingString = QString::fromUtf8( "%1°" ).arg( bearing, 0, 'f', 2 );
            if ( !infoString.isEmpty() ) {
                infoString.append( "\n" );
            }
            infoString.append( bearingString );
        }

        if ( m_showBearingChangeLabel && segmentIndex != 0 ) {
            GeoDataCoordinates currentCoordinates = m_measureLineString[segmentIndex];
            qreal currentBearing = currentCoordinates.bearing(m_measureLineString[segmentIndex+1]);
            qreal previousBearing = currentCoordinates.bearing( m_measureLineString[segmentIndex-1]);

            GeoDataLinearRing ring;
            painter->setPen( Qt::NoPen );
            painter->setBrush( QBrush ( QColor ( 127, 127, 127, 127 ) ) );

            if (currentBearing < previousBearing) currentBearing += 2 * M_PI;
            ring << currentCoordinates;

            qreal angleLength = qAbs(m_latLonAltBox.north() - m_latLonAltBox.south()) / 20;

            qreal iterBearing = previousBearing;
            while ( iterBearing < currentBearing ) {
                ring << currentCoordinates.moveByBearing( iterBearing, angleLength );;
                iterBearing += 0.1;
            }

            ring << currentCoordinates.moveByBearing( currentBearing, angleLength );;

            painter->drawPolygon( ring );

            qreal currentBearingChange = (currentBearing - previousBearing) * RAD2DEG;
            if (currentBearingChange < 0) currentBearingChange += 360;
            QString bearingChangedString = QString::fromUtf8( "%1°" ).arg( currentBearingChange, 0, 'f', 2 );
            painter->setPen( Qt::black );
            GeoDataCoordinates textPosition = ring.latLonAltBox().center();
            qreal deltaEast = ring.latLonAltBox().east() - currentCoordinates.longitude();
            qreal deltaWest = currentCoordinates.longitude() - ring.latLonAltBox().west();
            if (deltaEast > deltaWest) {
                textPosition.setLongitude(currentCoordinates.longitude() + deltaEast / 2);
            }
            else {
                textPosition.setLongitude(currentCoordinates.longitude() - deltaWest);
            }
            painter->drawText(textPosition, bearingChangedString );
       }

        // Drawing ellipse around 1st point towards the 2nd
        if ( m_paintMode == Circular ) {
            GeoDataCoordinates currentCoordinates = m_measureLineString[segmentIndex];

            GeoDataLinearRing ring;

            // planetRadius - planet radius
            // d - distance between points
            // S - area of the painted circle
            qreal planetRadius = marbleModel()->planet()->radius();
            qreal d = m_measureLineString.length(1);
            m_circularArea = 2 * M_PI * planetRadius * planetRadius * (1 - qCos(d));

            qreal iterBearing = 0;
            while ( iterBearing < 2 * M_PI ) {
                ring << currentCoordinates.moveByBearing(iterBearing, d);
                iterBearing += 0.1;
            }

            painter->setPen( Qt::NoPen );
            painter->setBrush( QBrush ( QColor ( 127, 127, 127, 127 ) ) );
            painter->drawPolygon(ring);

            if ( m_showCircularArea ) {
                painter->setPen(Qt::white);
                GeoDataCoordinates textPosition = ring.latLonAltBox().center();

                QString areaText = tr("Area:\n%1").arg(meterToPreferredUnit(m_circularArea, true));

                QFontMetrics fontMetrics = painter->fontMetrics();
                QRect boundingRect = fontMetrics.boundingRect(QRect(), Qt::AlignCenter, areaText);

                painter->drawText(textPosition,
                                  areaText,
                                  -boundingRect.width()/2, -boundingRect.height()*1.5,
                                  boundingRect.width(), boundingRect.height(),
                                  QTextOption(Qt::AlignCenter));
            }

            if ( m_showCircumference ) {
                painter->setPen(Qt::white);
                GeoDataCoordinates textPosition = ring.latLonAltBox().center();

                m_circumference = 2 * M_PI * planetRadius * qSin(d);

                QString circumferenceText = tr("Circumference:\n%1").arg(meterToPreferredUnit(m_circumference));

                QFontMetrics fontMetrics = painter->fontMetrics();
                QRect boundingRect = fontMetrics.boundingRect(QRect(),Qt::AlignCenter,
                                                              circumferenceText);

                painter->drawText(textPosition,
                                  circumferenceText,
                                  -boundingRect.width()/2, boundingRect.height(),
                                  boundingRect.width(), boundingRect.height(),
                                  QTextOption(Qt::AlignCenter));
            }
        }

        if ( !infoString.isEmpty() ) {
            QPen linePen;

            // have three alternating colors for the segments
            switch ( segmentIndex % 3 ) {
            case 0:
                linePen.setColor( Oxygen::brickRed4 );
                break;
            case 1:
                linePen.setColor( Oxygen::forestGreen4 );
                break;
            case 2:
                linePen.setColor( Oxygen::skyBlue4 );
                break;
            }

            linePen.setWidthF(2.0);
            painter->setPen( linePen );
            painter->drawPolyline( segment, infoString, LineCenter );
        }
    }

    if (m_paintMode == Polygon && m_measureLineString.size() > 2) {
        GeoDataLinearRing measureRing = m_measureLineString;

        if (m_showPolygonArea || m_showPerimeter) {
            painter->setPen( Qt::NoPen );
            painter->setBrush( QBrush ( QColor ( 127, 127, 127, 127 ) ) );
            painter->drawPolygon(measureRing);

            QPen shadowPen( Oxygen::aluminumGray5 );
            shadowPen.setStyle(Qt::DashLine);
            shadowPen.setWidthF(3.0);
            painter->setPen( shadowPen );
            painter->drawPolyline(GeoDataLineString( Tessellate ) << m_measureLineString.first()
                                                      << m_measureLineString.last());
        }

        if (m_showPolygonArea) {
            qreal theta1 = 0.0;
            qreal n = m_measureLineString.size();

            for (int segmentIndex = 1; segmentIndex < m_measureLineString.size()-1; segmentIndex++) {
                GeoDataCoordinates current = m_measureLineString[segmentIndex];
                qreal prevBearing = current.bearing(m_measureLineString[segmentIndex-1]);
                qreal nextBearing = current.bearing(m_measureLineString[segmentIndex+1]);
                if (nextBearing < prevBearing)
                    nextBearing += 2 * M_PI;

                qreal angle = nextBearing - prevBearing;
                theta1 += angle;
            }

            // Traversing first vertex
            GeoDataCoordinates current = m_measureLineString[0];
            qreal prevBearing = current.bearing(m_measureLineString[n-1]);
            qreal nextBearing = current.bearing(m_measureLineString[1]);
            if (nextBearing < prevBearing)
                nextBearing += 2 * M_PI;
            qreal angle = nextBearing - prevBearing;
            theta1 += angle;

            // And the last one
            current = m_measureLineString[n-1];
            prevBearing = current.bearing(m_measureLineString[n-2]);
            nextBearing = current.bearing(m_measureLineString[0]);
            if (nextBearing < prevBearing)
                nextBearing += 2 * M_PI;
            angle = nextBearing - prevBearing;
            theta1 += angle;

            qreal theta2 = 2 * M_PI * n - theta1;

            // theta = smaller of theta1 and theta2
            qreal theta = (theta1 < theta2) ? theta1 : theta2;

            qreal planetRadius = marbleModel()->planet()->radius();
            qreal S = qAbs((theta - (n-2) * M_PI) * planetRadius * planetRadius);
            m_polygonArea = S;

            painter->setPen(Qt::white);
            GeoDataCoordinates textPosition = measureRing.latLonAltBox().center();

            QString areaText = tr("Area:\n%1").arg(meterToPreferredUnit(S, true));

            QFontMetrics fontMetrics = painter->fontMetrics();
            QRect boundingRect = fontMetrics.boundingRect(QRect(), Qt::AlignCenter, areaText);

            painter->drawText(textPosition,
                              areaText,
                              -boundingRect.width()/2, -(boundingRect.height()+fontMetrics.height()*0.25),
                              boundingRect.width(), boundingRect.height(),
                              QTextOption(Qt::AlignCenter));
        }

        if (m_showPerimeter) {
            painter->setPen(Qt::white);
            GeoDataCoordinates textPosition = measureRing.latLonAltBox().center();

            qreal P = measureRing.length(marbleModel()->planet()->radius());
            m_perimeter = P;
            QString perimeterText = tr("Perimeter:\n%1").arg(meterToPreferredUnit(P));

            QFontMetrics fontMetrics = painter->fontMetrics();
            QRect boundingRect = fontMetrics.boundingRect(QRect(),Qt::AlignCenter,
                                                          perimeterText);

            painter->drawText(textPosition,
                              perimeterText,
                              -boundingRect.width()/2, 0,
                              boundingRect.width(), boundingRect.height(),
                              QTextOption(Qt::AlignCenter));
        }
    }
}
Beispiel #22
0
// --------------------------------------------------
void ctkSearchBox::paintEvent(QPaintEvent * event)
{
  Q_D(ctkSearchBox);

  // Draw the line edit with text.
  // Text has already been shifted to the right (in resizeEvent()) to leave
  // space for the search icon.
  this->Superclass::paintEvent(event);

  QPainter p(this);

  QRect cRect = d->clearRect();
  QRect sRect = d->showSearchIcon ? d->searchRect() : QRect();

#if QT_VERSION >= 0x040700
  QRect r = rect();
  QPalette pal = palette();

  QStyleOptionFrameV2 panel;
  initStyleOption(&panel);
  r = this->style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
  r.setX(r.x() + this->textMargins().left());
  r.setY(r.y() + this->textMargins().top());
  r.setRight(r.right() - this->textMargins().right());
  r.setBottom(r.bottom() - this->textMargins().bottom());
  p.setClipRect(r);

  QFontMetrics fm = fontMetrics();
  Qt::Alignment va = QStyle::visualAlignment(this->layoutDirection(),
                                             QFlag(this->alignment()));
  int vscroll = 0;
  const int verticalMargin = 1;
  const int horizontalMargin = 2;
  switch (va & Qt::AlignVertical_Mask) {
   case Qt::AlignBottom:
       vscroll = r.y() + r.height() - fm.height() - verticalMargin;
       break;
   case Qt::AlignTop:
       vscroll = r.y() + verticalMargin;
       break;
   default:
       //center
       vscroll = r.y() + (r.height() - fm.height() + 1) / 2;
       break;
  }
  QRect lineRect(r.x() + horizontalMargin, vscroll,
                 r.width() - 2*horizontalMargin, fm.height());

  int minLB = qMax(0, -fm.minLeftBearing());

  if (this->text().isEmpty())
    {
    if (!this->hasFocus() && !this->placeholderText().isEmpty())
      {
      QColor col = pal.text().color();
      col.setAlpha(128);
      QPen oldpen = p.pen();
      p.setPen(col);
      lineRect.adjust(minLB, 0, 0, 0);
      QString elidedText = fm.elidedText(this->placeholderText(), Qt::ElideRight, lineRect.width());
      p.drawText(lineRect, va, elidedText);
      p.setPen(oldpen);
      }
    }
  p.setClipRect(this->rect());
#endif

  // Draw clearIcon
  if (!d->hideClearIcon)
    {
    QPixmap closePixmap = d->clearIcon.pixmap(cRect.size(),this->isEnabled() ? QIcon::Normal : QIcon::Disabled);
    this->style()->drawItemPixmap(&p, cRect, Qt::AlignCenter, closePixmap);
    }

  // Draw searchIcon
  if (d->showSearchIcon)
    {
    QPixmap searchPixmap = d->searchIcon.pixmap(sRect.size(), this->isEnabled() ? QIcon::Normal : QIcon::Disabled);
    this->style()->drawItemPixmap(&p, sRect, Qt::AlignCenter, searchPixmap);
    }
}
SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
    QSplashScreen(pixmap, f)
{
    // set reference point, paddings
    int paddingRight            = 50;
    int paddingTop              = 50;
    int titleVersionVSpace      = 17;
    int titleCopyrightVSpace    = 40;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
    QString versionText     = QString("Version %1").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
    QString copyrightText2  = QChar(0xA9)+QString(" 2014 ") + QString(tr("The Photon developers"));
    QString copyrightText3  = QChar(0xA9)+QString(" 2014 ") + QString(tr("The UniversalMolecule developers"));
    QString testnetAddText  = QString(tr("[testnet]")); // define text to place as single text object

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(100,100,100));

    // check font size and drawing with
    pixPaint.setFont(QFont(font, 33*fontFactor));
    QFontMetrics fm = pixPaint.fontMetrics();
    int titleTextWidth  = fm.width(titleText);
    if(titleTextWidth > 160) {
        // strange font rendering, Arial probably not found
        fontFactor = 0.75;
    }

    pixPaint.setFont(QFont(font, 33*fontFactor));
    fm = pixPaint.fontMetrics();
    titleTextWidth  = fm.width(titleText);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop,titleText);

    pixPaint.setFont(QFont(font, 15*fontFactor));

    // if the version string is to long, reduce size
    fm = pixPaint.fontMetrics();
    int versionTextWidth  = fm.width(versionText);
    if(versionTextWidth > titleTextWidth+paddingRight-10) {
        pixPaint.setFont(QFont(font, 10*fontFactor));
        titleVersionVSpace -= 5;
    }
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight+2,paddingTop+titleVersionVSpace,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 10*fontFactor));
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace,copyrightText);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace+12,copyrightText2);
    pixPaint.drawText(newPixmap.width()-titleTextWidth-paddingRight,paddingTop+titleCopyrightVSpace+24,copyrightText3);

    // draw testnet string if -testnet is on
    if(QApplication::applicationName().contains(QString("-testnet"))) {
        // draw copyright stuff
        QFont boldFont = QFont(font, 10*fontFactor);
        boldFont.setWeight(QFont::Bold);
        pixPaint.setFont(boldFont);
        fm = pixPaint.fontMetrics();
        int testnetAddTextWidth  = fm.width(testnetAddText);
        pixPaint.drawText(newPixmap.width()-testnetAddTextWidth-10,15,testnetAddText);
    }

    pixPaint.end();

    this->setPixmap(newPixmap);
}
Beispiel #24
0
static void computeSizeBasedOnStyle(RenderStyle* renderStyle)
{
    // If the width and height are both specified, then we have nothing to do.
    if (!renderStyle->width().isIntrinsicOrAuto() && !renderStyle->height().isAuto())
        return;

    QSize size(0, 0);
    const QFontMetrics fm(renderStyle->font().font());
    QStyle* applicationStyle = QApplication::style();

    switch (renderStyle->appearance()) {
    case CheckboxPart: {
        QStyleOption styleOption;
        styleOption.state |= QStyle::State_Small;
        int checkBoxWidth = applicationStyle->pixelMetric(QStyle::PM_IndicatorWidth,
                                                          &styleOption);
        size = QSize(checkBoxWidth, checkBoxWidth);
        break;
    }
    case RadioPart: {
        QStyleOption styleOption;
        styleOption.state |= QStyle::State_Small;
        int radioWidth = applicationStyle->pixelMetric(QStyle::PM_ExclusiveIndicatorWidth,
                                                       &styleOption);
        size = QSize(radioWidth, radioWidth);
        break;
    }
    case PushButtonPart:
    case ButtonPart: {
        QStyleOptionButton styleOption;
        styleOption.state |= QStyle::State_Small;
        QSize contentSize = fm.size(Qt::TextShowMnemonic, QString::fromLatin1("X"));
        QSize pushButtonSize = applicationStyle->sizeFromContents(QStyle::CT_PushButton,
                                                                  &styleOption,
                                                                  contentSize,
                                                                  0);
        styleOption.rect = QRect(0, 0, pushButtonSize.width(), pushButtonSize.height());
        QRect layoutRect = applicationStyle->subElementRect(QStyle::SE_PushButtonLayoutItem,
                                                                  &styleOption,
                                                                  0);
        // If the style supports layout rects we use that, and
        // compensate accordingly in paintButton() below.
        if (!layoutRect.isNull()) {
            size.setHeight(layoutRect.height());
        } else {
            size.setHeight(pushButtonSize.height());
        }

        break;
    }
    case MenulistPart: {
        QStyleOptionComboBox styleOption;
        styleOption.state |= QStyle::State_Small;
        int contentHeight = qMax(fm.lineSpacing(), 14) + 2;
        QSize menuListSize = applicationStyle->sizeFromContents(QStyle::CT_ComboBox,
                                                        &styleOption,
                                                        QSize(0, contentHeight),
                                                        0);
        size.setHeight(menuListSize.height());
        break;
    }
    case TextFieldPart: {
        const int verticalMargin = 1;
        const int horizontalMargin = 2;
        int h = qMax(fm.lineSpacing(), 14) + 2*verticalMargin;
        int w = fm.width(QLatin1Char('x')) * 17 + 2*horizontalMargin;
        QStyleOptionFrameV2 opt;
        opt.lineWidth = applicationStyle->pixelMetric(QStyle::PM_DefaultFrameWidth,
                                                           &opt, 0);
        QSize sz = applicationStyle->sizeFromContents(QStyle::CT_LineEdit,
                                                           &opt,
                                                           QSize(w, h).expandedTo(QApplication::globalStrut()),
                                                           0);
        size.setHeight(sz.height());
        break;
    }
    default:
        break;
    }

    // FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
    if (renderStyle->width().isIntrinsicOrAuto() && size.width() > 0)
        renderStyle->setWidth(Length(size.width(), Fixed));
    if (renderStyle->height().isAuto() && size.height() > 0)
        renderStyle->setHeight(Length(size.height(), Fixed));
}
Beispiel #25
0
QString K3b::squeezeTextToWidth( const QFontMetrics& fm, const QString& fullText, int cutWidth )
{
    return fm.elidedText( fullText, Qt::ElideMiddle, cutWidth );
}
// ---
// drawGrid() - draws the overlay grid lines
// ---
void MapItem::drawGrid(QPainter* painter)
{
   // smaller font for easy viewing
   QFont font(painter->font());
   font.setPointSize(10);
   painter->setFont(font);

   QFontMetrics fm = painter->fontMetrics();
   // setup our pen
   // the color of our pen will be the complement of the strength of our intensity
   QPen pen(Qt::white, 2.0f);
   painter->setPen(pen);

   if (heading > 0 && !northUp) {
       setRotation(heading);
   }

   // get the nearest starting lat and lon lines to draw
   const int centerLat = oe::base::nint(refLat);
   const int centerLon = oe::base::nint(refLon);

   // calculate the number of latitude lines
   const int numLinesLat = (range / 60.0) + 1;

   // calculate EW range
   double rangeEW(1.0);
   if (northUp) {
      rangeEW = (bRect.width() * pixWERes);
   } else {
      rangeEW = (bRect.width() * pixWERes / cosineLatReference);
   }
   const int numLinesLon = (rangeEW / 60.0) + 1;

   int startLat = centerLat - (numLinesLat / 2);
   int endLat = centerLat + (numLinesLat / 2);
   // top side (or bottom, depending on hemisphere)
   double py = 0.0;
   double px = 0.0;
   const int wid = bRect.width();
   const int hei = bRect.height();
   if (endLat >= 90)     { endLat = 90;     }
   if (startLat <= -90)  { startLat = -90;  }

   QVector<QLine> lines;

   for (int i = startLat; i <= endLat; i++) {
      llToPixels(i, 0, py, px);
      QLine line(-wid/2, py, wid, py);
      //painter->drawLine(-wid/2, py, wid, py);
      lines << line;
   }

   painter->drawLines(lines);
   lines.clear();

   const int startLon = centerLon - (numLinesLon / 2);
   const int endLon = centerLon + (numLinesLon / 2);
   // top side (or bottom, depending on hemisphere)
   for (int i = startLon; i <= endLon; i++) {
      llToPixels(0, i, py, px);
      QLine line(px, -hei / 2, px, hei / 2);
      //painter->drawLine(px, -hei / 2, px, hei / 2);
      lines << line;
   }

   painter->drawLines(lines);
   lines.clear();

   // now for the text
   QString string;
   double adjustHeight = fm.height();
   std::ostringstream stream;
   for (int i = startLat; i <= endLat; i++) {
      string.clear();
      stream.str("");
      int aI = abs(i);
      llToPixels(i, 0, py, px);

      if (i > 0)          { stream << "N" << aI;  }
      else if (i < 0)     { stream << "S" << aI;  }
      else                { stream << aI;         }

      string = stream.str().c_str();
      // Lee - have to use the unicode code for a degree symbol
      string.append(0x00B0);
      const double adjustWidth = fm.width(string);
      painter->drawText(-(wid/2) + 5, py - adjustHeight, adjustWidth, adjustHeight, 0, string);
   }

   for (int i = startLon; i <= endLon; i++) {
      string.clear();
      stream.str("");
      llToPixels(0, i, py, px);
      int aI = std::abs(i);

      if (i > 180)         { aI = (180 - i) + 180; }
      else if (i < -180)   { aI = (180 + i) + 180; }

      if (i != 0 && i != 180 && i != -180) {
         if (i > 0 || i < -180)       { stream << "E" << aI;  }
         else if (i < 0 || i > 180)   { stream << "W" << aI;  }
         else                         { stream << aI;         }
      }
      string = stream.str().c_str();
      // Lee - have to use the unicode code for a degree symbol
      string.append(0x00B0);
      const double adjustWidth = fm.width(string);
      painter->drawText(px + 5, -hei/2, adjustWidth, adjustHeight, 0, string);
   }
}
Beispiel #27
0
void DCategoryDrawer::drawCategory(const QModelIndex& index,
                                   int /*sortRole*/,
                                   const QStyleOption& option,
                                   QPainter* painter) const
{
    painter->setRenderHint(QPainter::Antialiasing);

    const QString category = index.model()->data(index, DCategorizedSortFilterProxyModel::CategoryDisplayRole).toString();
    const QRect optRect    = option.rect;
    QFont font(QApplication::font());
    font.setBold(true);
    const QFontMetrics fontMetrics = QFontMetrics(font);
    QColor outlineColor            = option.palette.text().color();
    outlineColor.setAlphaF(0.35);

    //BEGIN: top left corner
    {
        painter->save();
        painter->setPen(outlineColor);
        const QPointF topLeft(optRect.topLeft());
        QRectF arc(topLeft, QSizeF(4, 4));
        arc.translate(0.5, 0.5);
        painter->drawArc(arc, 1440, 1440);
        painter->restore();
    }
    //END: top left corner

    //BEGIN: left vertical line
    {
        QPoint start(optRect.topLeft());
        start.ry() += 3;
        QPoint verticalGradBottom(optRect.topLeft());
        verticalGradBottom.ry() += fontMetrics.height() + 5;
        QLinearGradient gradient(start, verticalGradBottom);
        gradient.setColorAt(0, outlineColor);
        gradient.setColorAt(1, Qt::transparent);
        painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient);
    }
    //END: left vertical line

    //BEGIN: horizontal line
    {
        QPoint start(optRect.topLeft());
        start.rx() += 3;
        QPoint horizontalGradTop(optRect.topLeft());
        horizontalGradTop.rx() += optRect.width() - 6;
        painter->fillRect(QRect(start, QSize(optRect.width() - 6, 1)), outlineColor);
    }
    //END: horizontal line

    //BEGIN: top right corner
    {
        painter->save();
        painter->setPen(outlineColor);
        QPointF topRight(optRect.topRight());
        topRight.rx() -= 4;
        QRectF arc(topRight, QSizeF(4, 4));
        arc.translate(0.5, 0.5);
        painter->drawArc(arc, 0, 1440);
        painter->restore();
    }
    //END: top right corner

    //BEGIN: right vertical line
    {
        QPoint start(optRect.topRight());
        start.ry() += 3;
        QPoint verticalGradBottom(optRect.topRight());
        verticalGradBottom.ry() += fontMetrics.height() + 5;
        QLinearGradient gradient(start, verticalGradBottom);
        gradient.setColorAt(0, outlineColor);
        gradient.setColorAt(1, Qt::transparent);
        painter->fillRect(QRect(start, QSize(1, fontMetrics.height() + 5)), gradient);
    }
    //END: right vertical line

    //BEGIN: text
    {
        QRect textRect(option.rect);
        textRect.setTop(textRect.top() + 7);
        textRect.setLeft(textRect.left() + 7);
        textRect.setHeight(fontMetrics.height());
        textRect.setRight(textRect.right() - 7);

        painter->save();
        painter->setFont(font);
        QColor penColor(option.palette.text().color());
        penColor.setAlphaF(0.6);
        painter->setPen(penColor);
        painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, category);
        painter->restore();
    }
    //END: text
}
Beispiel #28
0
void renderWatermark(QImage & image, const QString & wmText, const QFont & wmFont, const unsigned int wmOpacity, double pA, double pB, double pC, double pD)
{
  const double pi = 3.14159265358979323846;

  double w = ((double)image.width() - pA);
  double h = ((double)image.height() - pB);
  double theta = (pi/-2.0) + atan(w / h);
  double l = sqrt((w * w) + (h * h));

  const double sintheta = sin(theta);
  const double costheta = cos(theta);

  double margin_width = pC;
  double margin_height = pD;

  int offset = (int)(l * 0.05);
  int l2 = (int)(l * 0.9);

  int x = (int)(sintheta * h) + offset;
  int y = (int)(costheta * h);

  QFont fnt = wmFont;
  QFontMetrics fm = QFontMetrics(fnt);
  QFontInfo fi(fnt);
  QString family = fi.family();
  QList<int> sizes = QFontDatabase().pointSizes(family);
  qSort(sizes);

  for(int i = sizes.size() - 1; i > 0; i--)
  {
    fnt.setPointSize(sizes[i]);
    fm = QFontMetrics(fnt);
    if(fm.boundingRect(wmText).width() < l2)
      break;
  }
  int fh = fm.height();

  y = y - (fh/2);

  //NB QPixmap not safe outside of main thread, using QImage instead
  QImage wm(image.width(), image.height(), QImage::Format_RGB32);
  wm.fill(0xFFFFFFFF);
  QPainter pPainter;
  pPainter.begin(&wm);
  pPainter.setFont(fnt);
  pPainter.translate(margin_width, margin_height);
  pPainter.rotate((theta/pi)*180);
  pPainter.drawText(x, y, l2, fh, Qt::AlignCenter, wmText);
  pPainter.end();

  double opacity = wmOpacity / 255.0;
  double opacity_inv = 1.0 - opacity;

  QRgb s = 0;
  QRgb d = 0;
  for(y = 0; y < image.height(); y++) {
    for(x = 0; x < image.width(); x++) {
      s = wm.pixel(x, y);
      if((s & 0x00ffffff) == 0x00ffffff) continue; // if it's white just skip it
      d = image.pixel(x, y);
      image.setPixel(x, y, qRgb( (int)((qRed(s) * opacity) + (qRed(d) * opacity_inv)),
                                 (int)((qGreen(s) * opacity) + (qGreen(d) * opacity_inv)),
                                 (int)((qBlue(s) * opacity) + (qBlue(d) * opacity_inv)) ));
    }
  }
}
int TabButton::normalWidth() const {
    QFontMetrics metrics = qApp->fontMetrics();

    return LABELWIDTH*2+metrics.width(text())+margin*3;
}
int khtml::computeLength(DOM::CSSPrimitiveValueImpl *val, RenderStyle *style, QPaintDeviceMetrics *devMetrics, Metrics m)
{
    unsigned short type = val->primitiveType();

    int dpiY = 72; // fallback
    if ( devMetrics )
        dpiY = devMetrics->logicalDpiY();

    float factor = 1.;
    switch(type)
    {
    case CSSPrimitiveValue::CSS_EMS:
    case CSSPrimitiveValue::CSS_EXS:
    {
        if(type == CSSPrimitiveValue::CSS_EMS)
        {
            factor = style->font().pixelSize();

            //kdDebug( 6080 ) << "EM = " << factor << endl;
        }
        else
        {
            QFontMetrics fm = khtml::fontMetrics(style->font());
            QRect b = fm.boundingRect('x');
            factor = b.height();
        }
        break;
    }
    case CSSPrimitiveValue::CSS_PX:
        break;
    case CSSPrimitiveValue::CSS_CM:
        if(m == MetricScreen)
            factor = dpiY/2.54; //72dpi/(2.54 cm/in)
        else
            factor = 300./2.54; //300dpi/(2.54 cm/in)
        break;
    case CSSPrimitiveValue::CSS_MM:
        if(m == MetricScreen)
            factor = dpiY/25.4;
        else
            factor = 300./25.4;
        break;
    case CSSPrimitiveValue::CSS_IN:
        if(m == MetricScreen)
            factor = dpiY;
        else
            factor = 300.;
        break;
    case CSSPrimitiveValue::CSS_PT:
        if(m == MetricScreen)
            factor = dpiY/72.;
        else
            factor = 300./72.;
        break;
    case CSSPrimitiveValue::CSS_PC:
        // 1 pc == 12 pt
        if(m == MetricScreen)
            factor = dpiY*12./72.;
        else
            factor = 300./72.*12.;
        break;
    default:
        return -1;
    }
    return (int)(val->getFloatValue(type)*factor);
}