// if painter is nullptr, the method calculate the bounding rectangle of the text and save it to textRect void FolderItemDelegate::drawText(QPainter* painter, QStyleOptionViewItemV4& opt, QRectF& textRect) const { QTextLayout layout(opt.text, opt.font); QTextOption textOption; textOption.setAlignment(opt.displayAlignment); textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); textOption.setTextDirection(opt.direction); layout.setTextOption(textOption); qreal height = 0; qreal width = 0; int visibleLines = 0; layout.beginLayout(); QString elidedText; textRect.adjust(2, 2, -2, -2); // a 2-px margin is considered at FolderView::updateGridSize() for(;;) { QTextLine line = layout.createLine(); if(!line.isValid()) break; line.setLineWidth(textRect.width()); height += opt.fontMetrics.leading(); line.setPosition(QPointF(0, height)); if((height + line.height() + textRect.y()) > textRect.bottom()) { // if part of this line falls outside the textRect, ignore it and quit. QTextLine lastLine = layout.lineAt(visibleLines - 1); elidedText = opt.text.mid(lastLine.textStart()); elidedText = opt.fontMetrics.elidedText(elidedText, opt.textElideMode, textRect.width()); if(visibleLines == 1) // this is the only visible line width = textRect.width(); break; } height += line.height(); width = qMax(width, line.naturalTextWidth()); ++ visibleLines; } layout.endLayout(); width = qMax(width, (qreal)opt.fontMetrics.width(elidedText)); // draw background for selected item QRectF boundRect = layout.boundingRect(); //qDebug() << "bound rect: " << boundRect << "width: " << width; boundRect.setWidth(width); boundRect.setHeight(height); boundRect.moveTo(textRect.x() + (textRect.width() - width)/2, textRect.y()); QRectF selRect = boundRect.adjusted(-2, -2, 2, 2); if(!painter) { // no painter, calculate the bounding rect only textRect = selRect; return; } QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if(opt.state & QStyle::State_Selected) { painter->fillRect(selRect, opt.palette.highlight()); painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else painter->setPen(opt.palette.color(cg, QPalette::Text)); // draw text for(int i = 0; i < visibleLines; ++i) { QTextLine line = layout.lineAt(i); if(i == (visibleLines - 1) && !elidedText.isEmpty()) { // the last line, draw elided text QPointF pos(boundRect.x() + line.position().x(), boundRect.y() + line.y() + line.ascent()); painter->drawText(pos, elidedText); } else { line.draw(painter, textRect.topLeft()); } } if(opt.state & QStyle::State_HasFocus) { // draw focus rect QStyleOptionFocusRect o; o.QStyleOption::operator=(opt); o.rect = selRect.toRect(); // subElementRect(SE_ItemViewItemFocusRect, vopt, widget); o.state |= QStyle::State_KeyboardFocusChange; o.state |= QStyle::State_Item; QPalette::ColorGroup cg = (opt.state & QStyle::State_Enabled) ? QPalette::Normal : QPalette::Disabled; o.backgroundColor = opt.palette.color(cg, (opt.state & QStyle::State_Selected) ? QPalette::Highlight : QPalette::Window); if (const QWidget* widget = opt.widget) { QStyle* style = widget->style() ? widget->style() : qApp->style(); style->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter, widget); } } }
/*! \brief Draw the knob \param painter painter \param knobRect Bounding rectangle of the knob (without scale) */ void QwtKnob::drawKnob( QPainter *painter, const QRectF &knobRect ) const { double dim = qMin( knobRect.width(), knobRect.height() ); dim -= d_data->borderWidth * 0.5; QRectF aRect( 0, 0, dim, dim ); aRect.moveCenter( knobRect.center() ); QPen pen( Qt::NoPen ); if ( d_data->borderWidth > 0 ) { QColor c1 = palette().color( QPalette::Light ); QColor c2 = palette().color( QPalette::Dark ); QLinearGradient gradient( aRect.topLeft(), aRect.bottomRight() ); gradient.setColorAt( 0.0, c1 ); gradient.setColorAt( 0.3, c1 ); gradient.setColorAt( 0.7, c2 ); gradient.setColorAt( 1.0, c2 ); pen = QPen( gradient, d_data->borderWidth ); } QBrush brush; switch( d_data->knobStyle ) { case QwtKnob::Raised: { double off = 0.3 * knobRect.width(); QRadialGradient gradient( knobRect.center(), knobRect.width(), knobRect.topLeft() + QPointF( off, off ) ); gradient.setColorAt( 0.0, palette().color( QPalette::Midlight ) ); gradient.setColorAt( 1.0, palette().color( QPalette::Button ) ); brush = QBrush( gradient ); break; } case QwtKnob::Styled: { QRadialGradient gradient(knobRect.center().x() - knobRect.width() / 3, knobRect.center().y() - knobRect.height() / 2, knobRect.width() * 1.3, knobRect.center().x(), knobRect.center().y() - knobRect.height() / 2); const QColor c = palette().color( QPalette::Button ); gradient.setColorAt(0, c.lighter(110)); gradient.setColorAt(qreal(0.5), c); gradient.setColorAt(qreal(0.501), c.darker(102)); gradient.setColorAt(1, c.darker(115)); brush = QBrush( gradient ); break; } case QwtKnob::Sunken: { QLinearGradient gradient( knobRect.topLeft(), knobRect.bottomRight() ); gradient.setColorAt( 0.0, palette().color( QPalette::Mid ) ); gradient.setColorAt( 0.5, palette().color( QPalette::Button ) ); gradient.setColorAt( 1.0, palette().color( QPalette::Midlight ) ); brush = QBrush( gradient ); break; } case QwtKnob::Flat: default: brush = palette().brush( QPalette::Button ); } painter->setPen( pen ); painter->setBrush( brush ); painter->drawEllipse( aRect ); }
void renderCodeEAN8(OROPage * page, const QRectF & r, const QString & _str, ORBarcodeData * bc) { int val[8]; int i = 0; // initialize all the values just so we can be predictable for(i = 0; i < 8; i++) val[i] = -1; // verify that the passed in string is valid // if it's not either twelve or thirteen characters // then it must be invalid to begin with if(_str.length() != 7 && _str.length() != 8) return; // loop through and convert each char to a digit. // if we can't convert all characters then this is // an invalid number for(i = 0; i < _str.length(); i++) { val[i] = ((QChar)_str.at(i)).digitValue(); if(val[i] == -1) return; } // calculate and append the checksum value int old_sum = val[7]; // get the old check sum value (-1 if none was set) int checksum = 0; for(i = 0; i < 7; i++) checksum += val[i] * (i % 2 ? 1 : 3); checksum = (checksum % 10); if(checksum) checksum = 10 - checksum; val[7] = checksum; // if we had an old checksum value and if it doesn't match what we came // up with then the string must be invalid so we will bail if(old_sum != -1 && old_sum != checksum) return; // lets determine some core attributes about this barcode qreal bar_width = bc->narrowBarWidth; // the width of the base unit bar // this is are mandatory minimum quiet zone qreal quiet_zone = bar_width * 10; if(quiet_zone < 0.10) quiet_zone = 0.10; // what kind of area do we have to work with qreal draw_width = r.width(); qreal draw_height = r.height() - 0.02; // L = 60X // L length of barcode (excluding quite zone) in units same as X and I // X the width of a bar (pixels in our case) qreal L; qreal X = bar_width; L = (67.0 * X); // now we have the actual width the barcode will be so can determine the actual // size of the quiet zone (we assume we center the barcode in the given area // what should we do if the area is too small???? // At the moment the way the code is written is we will always start at the minimum // required quiet zone if we don't have enough space.... I guess we'll just have over-run // to the right // // calculate the starting position based on the alignment option // for left align we don't need to do anything as the values are already setup for it if(bc->align == 1) // center { qreal nqz = (draw_width - L) / 2; if(nqz > quiet_zone) quiet_zone = nqz; } else if(bc->align > 1) // right quiet_zone = draw_width - (L + quiet_zone); // else if(align < 1) {} // left : do nothing qreal pos = r.left() + quiet_zone; qreal top = r.top(); QPen pen(Qt::NoPen); QBrush brush(QColor("black")); int b = 0; int w = 0; // render open guard ORORect * rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += bar_width; // render first set for(i = 0; i < 4; i++) { b = val[i]; for(w = 0; w < 7; w++) { if(_encodings[b][LEFTHAND_ODD][w]) { ORORect * rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height - 0.06)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); } pos += bar_width; } } // render center guard pos += bar_width; rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); // render last set for(i = 0; i < 4; i++) { b = val[i+4]; for(w = 0; w < 7; w++) { if(_encodings[b][RIGHTHAND][w]) { ORORect * rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height - 0.06)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); } pos += bar_width; } } // render close guard rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); QString leftstr = QString().sprintf("%d%d%d%d", val[0], val[1], val[2], val[3]); QString rightstr = QString().sprintf("%d%d%d%d", val[4], val[5], val[6], val[7]); QFont font("Arial",6); OROTextBox * tb = new OROTextBox(bc); tb->setPosition(QPointF(r.left() + quiet_zone + 3*bar_width, (r.top() + draw_height) - 0.06)); tb->setSize(QSizeF(28*bar_width, 0.10)); tb->setFont(font); tb->setText(leftstr); tb->setFlags(Qt::AlignHCenter | Qt::AlignTop); tb->setRotationAxis(r.topLeft()); page->addPrimitive(tb); tb = new OROTextBox(bc); tb->setPosition(QPointF(r.left() + quiet_zone + 36*bar_width, (r.top() + draw_height) - 0.06)); tb->setSize(QSizeF(28*bar_width, 0.10)); tb->setFont(font); tb->setText(rightstr); tb->setFlags(Qt::AlignHCenter | Qt::AlignTop); tb->setRotationAxis(r.topLeft()); page->addPrimitive(tb); return; }
QList<KWViewMode::ViewMap> KWViewModeNormal::clipRectToDocument(const QRect &viewRect) const { QList<ViewMap> answer; if (m_pageTops.isEmpty()) return answer; KWPage page = m_pageManager->begin(); qreal offsetX = 0.0; const int pageOffset = page.pageNumber(); int begin = 0; int end = m_pageTops.count() - 1; int index = 0; const qreal value = m_viewConverter->viewToDocument(viewRect.topLeft()).y(); if (m_pageTops.value(end) <= value) { // check extremes. Only end is needed since begin is zero. begin = end; index = end; } while (end - begin > 1) { // binary search for page-index using our m_pageTops cache. index = begin + (end - begin) / 2; qreal diff = m_pageTops.value(index) - value; if (diff < 0) begin = index; else if (diff > 0) end = index; else break; } while (index > 1) { // 1 since we might hit a pagespread in the binary search, so start one page early page = page.next(); --index; if (page.pageSide() == KWPage::PageSpread) --index; } int emptyPages = 0; while (page.isValid()) { #ifndef NDEBUG if (page.pageNumber() - pageOffset >= m_pageTops.count()) { kWarning(32003) << "ERROR; pagemanager has more pages than viewmode (" << m_pageManager->pageCount() << ">" << m_pageTops.count() << "). Make sure you add pages via the document!"; break; } #endif const QRectF pageRect = page.rect(); const QRectF zoomedPage = m_viewConverter->documentToView(pageRect); ViewMap vm; vm.page = page; //kDebug(32003) <<"page" << page.pageNumber(); const qreal offsetY = m_pageTops[page.pageNumber() - pageOffset] - pageRect.top(); vm.distance = m_viewConverter->documentToView(QPointF(offsetX, offsetY)); const QRectF targetPage(zoomedPage.x() + vm.distance.x(), zoomedPage.y() + vm.distance.y(), zoomedPage.width() , zoomedPage.height()); QRectF intersection = targetPage.intersect(viewRect); if (! intersection.isEmpty()) { intersection.moveTopLeft(intersection.topLeft() - vm.distance); vm.clipRect = intersection.toRect(); answer.append(vm); emptyPages = 0; } else { emptyPages++; } if (emptyPages > 2) // Since we show at max 2 pages side by side this is an easy rule break; if (m_pageSpreadMode) { if (page.pageSide() == KWPage::Left) offsetX = page.width() + GAP; else offsetX = 0.0; } page = page.next(); } return answer; }
QRectF FixedRatioTransform::dataToScene(QRectF dataRect) const { return QRectF(dataToScene(dataRect.topLeft()), dataToScene(dataRect.size())); }
void ColorPalette::setDrawArea(QRectF rect) { draw_erae_.setTopLeft(rect.topLeft()); draw_erae_.setBottomRight(rect.bottomRight()); }
void TextEditorOverlay::paintSelection(QPainter *painter, const OverlaySelection &selection) { QTextCursor begin = selection.m_cursor_begin; const QTextCursor &end= selection.m_cursor_end; const QColor &fg = selection.m_fg; const QColor &bg = selection.m_bg; if (begin.isNull() || end.isNull() || begin.position() > end.position()) return; QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect()); painter->save(); QColor penColor = fg; if (m_alpha) penColor.setAlpha(220); QPen pen(penColor, m_borderWidth); painter->translate(-.5, -.5); QRectF pathRect = path.controlPointRect(); if (bg.isValid()) { if (!m_alpha || begin.blockNumber() != end.blockNumber()) { // gradients are too slow for larger selections :( QColor col = bg; if (m_alpha) col.setAlpha(50); painter->setBrush(col); } else { QLinearGradient linearGrad(pathRect.topLeft(), pathRect.bottomLeft()); QColor col1 = fg.lighter(150); col1.setAlpha(20); QColor col2 = fg; col2.setAlpha(80); linearGrad.setColorAt(0, col1); linearGrad.setColorAt(1, col2); painter->setBrush(QBrush(linearGrad)); } } else { painter->setBrush(QBrush()); } painter->setRenderHint(QPainter::Antialiasing); if (selection.m_dropShadow) { painter->save(); QPainterPath shadow = path; shadow.translate(m_dropShadowWidth, m_dropShadowWidth); QPainterPath clip; clip.addRect(m_editor->viewport()->rect()); painter->setClipPath(clip - path); painter->fillPath(shadow, QColor(0, 0, 0, 100)); painter->restore(); } pen.setJoinStyle(Qt::RoundJoin); painter->setPen(pen); painter->drawPath(path); painter->restore(); }
/*! \return Bounding interval of the radial scale that is visible on the canvas. */ QwtInterval QwtPolarPlot::visibleInterval() const { const QwtScaleDiv *sd = scaleDiv( QwtPolar::Radius ); const QRectF cRect = canvas()->contentsRect(); const QRectF pRect = plotRect( cRect ); if ( cRect.contains( pRect ) || !cRect.intersects( pRect ) ) { return QwtInterval( sd->lowerBound(), sd->upperBound() ); } const QPointF pole = pRect.center(); const QRectF scaleRect = pRect & cRect; const QwtScaleMap map = scaleMap( QwtPolar::Radius ); double dmin = 0.0; double dmax = 0.0; if ( scaleRect.contains( pole ) ) { dmin = 0.0; QPointF corners[4]; corners[0] = scaleRect.bottomRight(); corners[1] = scaleRect.topRight(); corners[2] = scaleRect.topLeft(); corners[3] = scaleRect.bottomLeft(); dmax = 0.0; for ( int i = 0; i < 4; i++ ) { const double dist = qwtDistance( pole, corners[i] ); if ( dist > dmax ) dmax = dist; } } else { if ( pole.x() < scaleRect.left() ) { if ( pole.y() < scaleRect.top() ) { dmin = qwtDistance( pole, scaleRect.topLeft() ); dmax = qwtDistance( pole, scaleRect.bottomRight() ); } else if ( pole.y() > scaleRect.bottom() ) { dmin = qwtDistance( pole, scaleRect.bottomLeft() ); dmax = qwtDistance( pole, scaleRect.topRight() ); } else { dmin = scaleRect.left() - pole.x(); dmax = qMax( qwtDistance( pole, scaleRect.bottomRight() ), qwtDistance( pole, scaleRect.topRight() ) ); } } else if ( pole.x() > scaleRect.right() ) { if ( pole.y() < scaleRect.top() ) { dmin = qwtDistance( pole, scaleRect.topRight() ); dmax = qwtDistance( pole, scaleRect.bottomLeft() ); } else if ( pole.y() > scaleRect.bottom() ) { dmin = qwtDistance( pole, scaleRect.bottomRight() ); dmax = qwtDistance( pole, scaleRect.topLeft() ); } else { dmin = pole.x() - scaleRect.right(); dmax = qMax( qwtDistance( pole, scaleRect.bottomLeft() ), qwtDistance( pole, scaleRect.topLeft() ) ); } } else if ( pole.y() < scaleRect.top() ) { dmin = scaleRect.top() - pole.y(); dmax = qMax( qwtDistance( pole, scaleRect.bottomLeft() ), qwtDistance( pole, scaleRect.bottomRight() ) ); } else if ( pole.y() > scaleRect.bottom() ) { dmin = pole.y() - scaleRect.bottom(); dmax = qMax( qwtDistance( pole, scaleRect.topLeft() ), qwtDistance( pole, scaleRect.topRight() ) ); } } const double radius = pRect.width() / 2.0; if ( dmax > radius ) dmax = radius; QwtInterval interval; interval.setMinValue( map.invTransform( dmin ) ); interval.setMaxValue( map.invTransform( dmax ) ); return interval; }
/*!\reimp */ void QLabel::paintEvent(QPaintEvent *) { Q_D(QLabel); QStyle *style = QWidget::style(); QPainter painter(this); drawFrame(&painter); QRect cr = contentsRect(); cr.adjust(d->margin, d->margin, -d->margin, -d->margin); int align = QStyle::visualAlignment(layoutDirection(), QFlag(d->align)); #ifndef QT_NO_MOVIE if (d->movie) { if (d->scaledcontents) style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size())); else style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap()); } else #endif if (d->isTextLabel) { QRectF lr = d->layoutRect(); if (d->control) { #ifndef QT_NO_SHORTCUT const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0); if (d->shortcutId != 0 && underline != d->shortcutCursor.charFormat().fontUnderline()) { QTextCharFormat fmt; fmt.setFontUnderline(underline); d->shortcutCursor.mergeCharFormat(fmt); } #endif d->ensureTextLayouted(); QAbstractTextDocumentLayout::PaintContext context; QStyleOption opt(0); opt.init(this); if (!isEnabled() && style->styleHint(QStyle::SH_EtchDisabledText, &opt, this)) { context.palette = palette(); context.palette.setColor(QPalette::Text, context.palette.light().color()); painter.save(); painter.translate(lr.x() + 1, lr.y() + 1); painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1)); QAbstractTextDocumentLayout *layout = d->control->document()->documentLayout(); layout->draw(&painter, context); painter.restore(); } // Adjust the palette context.palette = palette(); #ifndef QT_NO_STYLE_STYLESHEET if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) { cssStyle->focusPalette(this, &opt, &context.palette); } #endif if (foregroundRole() != QPalette::Text && isEnabled()) context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole())); painter.save(); painter.translate(lr.topLeft()); painter.setClipRect(lr.translated(-lr.x(), -lr.y())); d->control->setPalette(context.palette); d->control->drawContents(&painter, QRectF(), this); painter.restore(); } else { int flags = align; if (d->hasShortcut) { flags |= Qt::TextShowMnemonic; QStyleOption opt; opt.initFrom(this); if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this)) flags |= Qt::TextHideMnemonic; } style->drawItemText(&painter, lr.toRect(), flags, palette(), isEnabled(), d->text, foregroundRole()); } } else #ifndef QT_NO_PICTURE if (d->picture) { QRect br = d->picture->boundingRect(); int rw = br.width(); int rh = br.height(); if (d->scaledcontents) { painter.save(); painter.translate(cr.x(), cr.y()); painter.scale((double)cr.width()/rw, (double)cr.height()/rh); painter.drawPicture(-br.x(), -br.y(), *d->picture); painter.restore(); } else { int xo = 0; int yo = 0; if (align & Qt::AlignVCenter) yo = (cr.height()-rh)/2; else if (align & Qt::AlignBottom) yo = cr.height()-rh; if (align & Qt::AlignRight) xo = cr.width()-rw; else if (align & Qt::AlignHCenter) xo = (cr.width()-rw)/2; painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture); } } else #endif if (d->pixmap && !d->pixmap->isNull()) { QPixmap pix; if (d->scaledcontents) { if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) { if (!d->cachedimage) d->cachedimage = new QImage(d->pixmap->toImage()); delete d->scaledpixmap; d->scaledpixmap = new QPixmap(QPixmap::fromImage(d->cachedimage->scaled(cr.size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation))); } pix = *d->scaledpixmap; } else pix = *d->pixmap; QStyleOption opt; opt.initFrom(this); if (!isEnabled()) pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt); style->drawItemPixmap(&painter, cr, align, pix); } }
bool GeometryUtilities::placeRectAtLine(const QRectF &rect, const QLineF &line, double lineOffset, double distance, const QLineF &intersectionLine, QPointF *placement, Side *horizontalAlignedSide) { QMT_CHECK(placement); QList<Candidate> candidates; candidates << Candidate(QVector2D(rect.topRight() - rect.topLeft()), QPointF(0.0, 0.0), SideTop) << Candidate(QVector2D(rect.topLeft() - rect.topRight()), rect.topRight() - rect.topLeft(), SideTop) << Candidate(QVector2D(rect.bottomLeft() - rect.topLeft()), QPointF(0.0, 0.0), SideLeft) << Candidate(QVector2D(rect.topLeft() - rect.bottomLeft()), rect.bottomLeft() - rect.topLeft(), SideLeft) << Candidate(QVector2D(rect.bottomRight() - rect.bottomLeft()), rect.bottomLeft() - rect.topLeft(), SideBottom) << Candidate(QVector2D(rect.bottomLeft() - rect.bottomRight()), rect.bottomRight() - rect.topLeft(), SideBottom) << Candidate(QVector2D(rect.bottomRight() - rect.topRight()), rect.topRight() - rect.topLeft(), SideRight) << Candidate(QVector2D(rect.topRight() - rect.bottomRight()), rect.bottomRight() - rect.topLeft(), SideRight); QVector<QVector2D> rectEdgeVectors; rectEdgeVectors << QVector2D(rect.topLeft() - rect.topLeft()) << QVector2D(rect.topRight() - rect.topLeft()) << QVector2D(rect.bottomLeft() - rect.topLeft()) << QVector2D(rect.bottomRight() -rect.topLeft()); QVector2D directionVector(line.p2() - line.p1()); directionVector.normalize(); QVector2D sideVector(directionVector.y(), -directionVector.x()); QVector2D intersectionVector(intersectionLine.p2() - intersectionLine.p1()); intersectionVector.normalize(); QVector2D outsideVector = QVector2D(intersectionVector.y(), -intersectionVector.x()); double p = QVector2D::dotProduct(directionVector, outsideVector); if (p < 0.0) outsideVector = outsideVector * -1.0; double smallestA = -1.0; QPointF rectTranslation; Side side = SideUnspecified; int bestSign = 0; foreach (const Candidate &candidate, candidates) { // solve equation a * directionVector + candidate.first = b * intersectionVector to find smallest a double r = directionVector.x() * intersectionVector.y() - directionVector.y() * intersectionVector.x(); if (r <= -1e-5 || r >= 1e-5) { double a = (candidate.first.y() * intersectionVector.x() - candidate.first.x() * intersectionVector.y()) / r; if (a >= 0.0 && (smallestA < 0.0 || a < smallestA)) { // verify that all rectangle edges lay outside of shape (by checking for positiv projection to intersection) bool ok = true; int sign = 0; QVector2D rectOriginVector = directionVector * a - QVector2D(candidate.second); foreach (const QVector2D &rectEdgeVector, rectEdgeVectors) { QVector2D edgeVector = rectOriginVector + rectEdgeVector; double aa = QVector2D::dotProduct(outsideVector, edgeVector); if (aa < 0.0) { ok = false; break; } int s = sgn(QVector2D::dotProduct(sideVector, edgeVector)); if (s) { if (sign) { if (s != sign) { ok = false; break; } } else { sign = s; } } }
/*! \internal */ void QGeoMapPolygonGeometry::updateScreenPoints(const QGeoMap &map) { if (!screenDirty_) return; if (map.width() == 0 || map.height() == 0) { clear(); return; } QPointF origin = map.coordinateToScreenPosition(srcOrigin_, false); // Create the viewport rect in the same coordinate system // as the actual points QRectF viewport(0, 0, map.width(), map.height()); viewport.translate(-1 * origin); QPainterPath vpPath; vpPath.addRect(viewport); QPainterPath ppi; if (clipToViewport_) ppi = srcPath_.intersected(vpPath); // get the clipped version of the path else ppi = srcPath_; clear(); // a polygon requires at least 3 points; if (ppi.elementCount() < 3) return; // Intersection between the viewport and a concave polygon can create multiple polygons // joined by a line at the viewport border, and poly2tri does not triangulate this very well // so use the full src path if the resulting polygon is concave. if (clipToViewport_) { int changeInX = 0; int changeInY = 0; QPainterPath::Element e1 = ppi.elementAt(1); QPainterPath::Element e = ppi.elementAt(0); QVector2D edgeA(e1.x - e.x ,e1.y - e.y); for (int i = 2; i <= ppi.elementCount(); ++i) { e = ppi.elementAt(i % ppi.elementCount()); if (e.x == e1.x && e.y == e1.y) continue; QVector2D edgeB(e.x - e1.x, e.y - e1.y); if ((edgeA.x() < 0) == (edgeB.x() >= 0)) changeInX++; if ((edgeA.y() < 0) == (edgeB.y() >= 0)) changeInY++; edgeA = edgeB; e1 = e; } if (changeInX > 2 || changeInY > 2) // polygon is concave ppi = srcPath_; } // translate the path into top-left-centric coordinates QRectF bb = ppi.boundingRect(); ppi.translate(-bb.left(), -bb.top()); firstPointOffset_ = -1 * bb.topLeft(); ppi.closeSubpath(); screenOutline_ = ppi; std::vector<p2t::Point*> curPts; curPts.reserve(ppi.elementCount()); for (int i = 0; i < ppi.elementCount(); ++i) { const QPainterPath::Element e = ppi.elementAt(i); if (e.isMoveTo() || i == ppi.elementCount() - 1 || (qAbs(e.x - curPts.front()->x) < 0.1 && qAbs(e.y - curPts.front()->y) < 0.1)) { if (curPts.size() > 2) { p2t::CDT *cdt = new p2t::CDT(curPts); cdt->Triangulate(); std::vector<p2t::Triangle*> tris = cdt->GetTriangles(); screenVertices_.reserve(screenVertices_.size() + int(tris.size())); for (size_t i = 0; i < tris.size(); ++i) { p2t::Triangle *t = tris.at(i); for (int j = 0; j < 3; ++j) { p2t::Point *p = t->GetPoint(j); screenVertices_ << Point(p->x, p->y); } } delete cdt; } curPts.clear(); curPts.reserve(ppi.elementCount() - i); curPts.push_back(new p2t::Point(e.x, e.y)); } else if (e.isLineTo()) { curPts.push_back(new p2t::Point(e.x, e.y)); } else { qWarning("Unhandled element type in polygon painterpath"); } } if (curPts.size() > 0) { qDeleteAll(curPts.begin(), curPts.end()); curPts.clear(); } screenBounds_ = ppi.boundingRect(); }
void uploadCoordAsTriangles(int i, const QRectF &rect) { uploadRectAsTriangles(m_vCoords.data(), i, rect.topLeft(), rect.bottomRight()); }
void uploadPositionAsTriangles(int i, const QRectF &rect) { uploadRectAsTriangles(m_vPositions.data(), i, rect.topLeft(), rect.bottomRight()); }
void TriggerPoint::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QRectF rect = boundingRect(); painter->save(); BasicBox *box = nullptr; if (_abstract->boxID() != NO_ID) { if ((box = _scene->getBox(_abstract->boxID())) != nullptr) { QPen pen = painter->pen(); QBrush brush = painter->brush(); // selection if (isSelected()) { QPen penBlue(QColor(60,60,255)); // same blue as box selected penBlue.setWidth(BasicBox::LINE_WIDTH); painter->setPen(penBlue); QPainterPath path; path = shape(); painter->drawPath(path); } pen.setColor(box->color().darker()); pen.setWidth(BasicBox::LINE_WIDTH / 2); painter->setPen(pen); if (_scene->playing()) { if (!isWaiting()) { drawFlag(painter, QColor("red")); } else { if(!_scene->triggersQueueList()->isEmpty()) { if (_scene->triggersQueueList()->first() == this && !box->isConditioned()) { drawFlag(painter, QColor("green")); this->setFocus(); } else { drawFlag(painter, QColor("orange")); } } } if (_abstract->waiting()) { BasicBox *box = _scene->getBox(_abstract->boxID()); box->update(); switch (_abstract->boxExtremity()) { case BOX_START: painter->drawText(rect.topRight() + QPointF(0, rect.height() / 2), QString::fromStdString(_abstract->message())); break; case BOX_END: painter->drawText(rect.topLeft() + QPointF(-QString::fromStdString(_abstract->message()).length() * 7, rect.height() / 2), QString::fromStdString(_abstract->message())); break; default: break; } } } else { drawFlag(painter, QColor(Qt::darkGray)); } } } painter->restore(); }
void QwtPainter::drawRoundedFrame( QPainter *painter, const QRectF &rect, double xRadius, double yRadius, const QPalette &palette, int lineWidth, int frameStyle ) { painter->save(); painter->setRenderHint( QPainter::Antialiasing, true ); painter->setBrush( Qt::NoBrush ); double lw2 = lineWidth * 0.5; QRectF r = rect.adjusted( lw2, lw2, -lw2, -lw2 ); QPainterPath path; path.addRoundedRect( r, xRadius, yRadius ); enum Style { Plain, Sunken, Raised }; Style style = Plain; if ( (frameStyle & QFrame::Sunken) == QFrame::Sunken ) style = Sunken; else if ( (frameStyle & QFrame::Raised) == QFrame::Raised ) style = Raised; if ( style != Plain && path.elementCount() == 17 ) { // move + 4 * ( cubicTo + lineTo ) QPainterPath pathList[8]; for ( int i = 0; i < 4; i++ ) { const int j = i * 4 + 1; pathList[ 2 * i ].moveTo( path.elementAt(j - 1).x, path.elementAt( j - 1 ).y ); pathList[ 2 * i ].cubicTo( path.elementAt(j + 0).x, path.elementAt(j + 0).y, path.elementAt(j + 1).x, path.elementAt(j + 1).y, path.elementAt(j + 2).x, path.elementAt(j + 2).y ); pathList[ 2 * i + 1 ].moveTo( path.elementAt(j + 2).x, path.elementAt(j + 2).y ); pathList[ 2 * i + 1 ].lineTo( path.elementAt(j + 3).x, path.elementAt(j + 3).y ); } QColor c1( palette.color( QPalette::Dark ) ); QColor c2( palette.color( QPalette::Light ) ); if ( style == Raised ) qSwap( c1, c2 ); for ( int i = 0; i < 4; i++ ) { QRectF r = pathList[2 * i].controlPointRect(); QPen arcPen; arcPen.setWidth( lineWidth ); QPen linePen; linePen.setWidth( lineWidth ); switch( i ) { case 0: { arcPen.setColor( c1 ); linePen.setColor( c1 ); break; } case 1: { QLinearGradient gradient; gradient.setStart( r.topLeft() ); gradient.setFinalStop( r.bottomRight() ); gradient.setColorAt( 0.0, c1 ); gradient.setColorAt( 1.0, c2 ); arcPen.setBrush( gradient ); linePen.setColor( c2 ); break; } case 2: { arcPen.setColor( c2 ); linePen.setColor( c2 ); break; } case 3: { QLinearGradient gradient; gradient.setStart( r.bottomRight() ); gradient.setFinalStop( r.topLeft() ); gradient.setColorAt( 0.0, c2 ); gradient.setColorAt( 1.0, c1 ); arcPen.setBrush( gradient ); linePen.setColor( c1 ); break; } } painter->setPen( arcPen ); painter->drawPath( pathList[ 2 * i] ); painter->setPen( linePen ); painter->drawPath( pathList[ 2 * i + 1] ); } } else { QPen pen( palette.color( QPalette::WindowText ), lineWidth ); painter->setPen( pen ); painter->drawPath( path ); } painter->restore(); }
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); } }
void CachedSvgItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { if (painter->paintEngine()->type() != QPaintEngine::OpenGL && painter->paintEngine()->type() != QPaintEngine::OpenGL2) { // Fallback to direct painting QGraphicsSvgItem::paint(painter, option, widget); return; } QRectF br = boundingRect(); QTransform transform = painter->worldTransform(); qreal sceneScale = transform.map(QLineF(0, 0, 1, 0)).length(); bool stencilTestEnabled = glIsEnabled(GL_STENCIL_TEST); bool scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST); painter->beginNativePainting(); if (stencilTestEnabled) { glEnable(GL_STENCIL_TEST); } if (scissorTestEnabled) { glEnable(GL_SCISSOR_TEST); } bool dirty = false; if (!m_texture) { glGenTextures(1, &m_texture); m_context = const_cast<QGLContext *>(QGLContext::currentContext()); dirty = true; } if (!qFuzzyCompare(sceneScale, m_scale)) { m_scale = sceneScale; dirty = true; } int textureWidth = (int(br.width() * m_scale) + 3) & ~3; int textureHeight = (int(br.height() * m_scale) + 3) & ~3; if (dirty) { // qDebug() << "re-render image"; QImage img(textureWidth, textureHeight, QImage::Format_ARGB32); { img.fill(Qt::transparent); QPainter p; p.begin(&img); p.setRenderHints(painter->renderHints()); p.translate(br.topLeft()); p.scale(m_scale, m_scale); QGraphicsSvgItem::paint(&p, option, 0); p.end(); img = img.rgbSwapped(); } glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, textureWidth, textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glDisable(GL_TEXTURE_2D); dirty = false; } glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, m_texture); // texture may be slightly large than svn image, ensure only used area is rendered qreal tw = br.width() * m_scale / textureWidth; qreal th = br.height() * m_scale / textureHeight; glBegin(GL_QUADS); glTexCoord2d(0, 0); glVertex3d(br.left(), br.top(), -1); glTexCoord2d(tw, 0); glVertex3d(br.right(), br.top(), -1); glTexCoord2d(tw, th); glVertex3d(br.right(), br.bottom(), -1); glTexCoord2d(0, th); glVertex3d(br.left(), br.bottom(), -1); glEnd(); glDisable(GL_TEXTURE_2D); painter->endNativePainting(); }
void EmbeddedLinker::takePosition(int index, int maxIndex) { const float Pi = 3.141592; QRectF bounding = master->boundingRect(); float top = bounding.topLeft().y(); float left = bounding.topLeft().x(); float right = bounding.bottomRight().x(); float bottom = bounding.bottomRight().y(); float height = bottom - top; float width = right - left; float angle = 2*Pi*index/maxIndex; int rW = width; int rH = height; if (rW < 150) rW *= 1.5; else rW += 5; if (rH < 150) rH *= 1.5; else rH += 5; float px = left + width/2 + rW*cos(angle - Pi/2)/2; float py = bottom - height/2 + rH*sin(angle - Pi/2)/2; //if linker covers master node: float min = py - top; if (min > bottom - py) min = bottom - py; if (min > px - left) min = px - left; if (min > right - px) min = right - px; float fx; float fy; //obviously, top != left != right != bottom if ((bottom - py == min) || (py - top == min)) { fx = px; if (bottom - py == min) fy = bottom + indent; else fy = top - indent; } else { fy = py; if (right - px == min) fx = right + indent; else fx = left - indent; } setPos(fx,fy); //useful for debug: //scene()->addPolygon(master->mapToScene(master->boundingRect().left(),master->boundingRect().top(), // master->boundingRect().width(),master->boundingRect().height())); }
QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, const QTextCursor &end, const QRect &clip) { if (begin.isNull() || end.isNull() || begin.position() > end.position()) return QPainterPath(); QPointF offset = m_editor->contentOffset(); QRect viewportRect = rect(); QTextDocument *document = m_editor->document(); if (m_editor->blockBoundingGeometry(begin.block()).translated(offset).top() > clip.bottom() + 10 || m_editor->blockBoundingGeometry(end.block()).translated(offset).bottom() < clip.top() - 10 ) return QPainterPath(); // nothing of the selection is visible QTextBlock block = begin.block(); if (block.blockNumber() < m_editor->firstVisibleBlock().blockNumber() - 4) block = m_editor->document()->findBlockByNumber(m_editor->firstVisibleBlock().blockNumber() - 4); bool inSelection = false; QVector<QRectF> selection; if (begin.position() == end.position()) { // special case empty selections const QRectF blockGeometry = m_editor->blockBoundingGeometry(block); QTextLayout *blockLayout = block.layout(); int pos = begin.position() - begin.block().position(); QTextLine line = blockLayout->lineForTextPosition(pos); QRectF lineRect = line.naturalTextRect(); int x = line.cursorToX(pos); lineRect.setLeft(x - m_borderWidth); lineRect.setRight(x + m_borderWidth); selection += lineRect.translated(blockGeometry.topLeft()); } else { for (; block.isValid() && block.blockNumber() <= end.blockNumber(); block = block.next()) { if (! block.isVisible()) continue; const QRectF blockGeometry = m_editor->blockBoundingGeometry(block); QTextLayout *blockLayout = block.layout(); QTextLine line = blockLayout->lineAt(0); bool firstOrLastBlock = false; int beginChar = 0; if (!inSelection) { if (block == begin.block()) { beginChar = begin.positionInBlock(); line = blockLayout->lineForTextPosition(beginChar); firstOrLastBlock = true; } inSelection = true; } else { // while (beginChar < block.length() && document->characterAt(block.position() + beginChar).isSpace()) // ++beginChar; // if (beginChar == block.length()) // beginChar = 0; } int lastLine = blockLayout->lineCount()-1; int endChar = -1; if (block == end.block()) { endChar = end.positionInBlock(); lastLine = blockLayout->lineForTextPosition(endChar).lineNumber(); inSelection = false; firstOrLastBlock = true; } else { endChar = block.length(); while (endChar > beginChar && document->characterAt(block.position() + endChar - 1).isSpace()) --endChar; } QRectF lineRect = line.naturalTextRect(); if (beginChar < endChar) { lineRect.setLeft(line.cursorToX(beginChar)); if (line.lineNumber() == lastLine) lineRect.setRight(line.cursorToX(endChar)); selection += lineRect.translated(blockGeometry.topLeft()); for (int lineIndex = line.lineNumber()+1; lineIndex <= lastLine; ++lineIndex) { line = blockLayout->lineAt(lineIndex); lineRect = line.naturalTextRect(); if (lineIndex == lastLine) lineRect.setRight(line.cursorToX(endChar)); selection += lineRect.translated(blockGeometry.topLeft()); } } else { // empty lines const int emptyLineSelectionSize = 16; if (!firstOrLastBlock && !selection.isEmpty()) { // middle lineRect.setLeft(selection.last().left()); } else if (inSelection) { // first line lineRect.setLeft(line.cursorToX(beginChar)); } else { // last line if (endChar == 0) break; lineRect.setLeft(line.cursorToX(endChar) - emptyLineSelectionSize); } lineRect.setRight(lineRect.left() + emptyLineSelectionSize); selection += lineRect.translated(blockGeometry.topLeft()); } if (!inSelection) break; if (blockGeometry.translated(offset).y() > 2*viewportRect.height()) break; } } if (selection.isEmpty()) return QPainterPath(); QVector<QPointF> points; const int margin = m_borderWidth/2; const int extra = 0; const QRectF &firstSelection = selection.at(0); points += (firstSelection.topLeft() + firstSelection.topRight()) / 2 + QPointF(0, -margin); points += firstSelection.topRight() + QPointF(margin+1, -margin); points += firstSelection.bottomRight() + QPointF(margin+1, 0); const int count = selection.count(); for (int i = 1; i < count-1; ++i) { #define MAX3(a,b,c) qMax(a, qMax(b,c)) qreal x = MAX3(selection.at(i-1).right(), selection.at(i).right(), selection.at(i+1).right()) + margin; points += QPointF(x+1, selection.at(i).top()); points += QPointF(x+1, selection.at(i).bottom()); } const QRectF &lastSelection = selection.at(count-1); points += lastSelection.topRight() + QPointF(margin+1, 0); points += lastSelection.bottomRight() + QPointF(margin+1, margin+extra); points += lastSelection.bottomLeft() + QPointF(-margin, margin+extra); points += lastSelection.topLeft() + QPointF(-margin, 0); for (int i = count-2; i > 0; --i) { #define MIN3(a,b,c) qMin(a, qMin(b,c)) qreal x = MIN3(selection.at(i-1).left(), selection.at(i).left(), selection.at(i+1).left()) - margin; points += QPointF(x, selection.at(i).bottom()+extra); points += QPointF(x, selection.at(i).top()); } points += firstSelection.bottomLeft() + QPointF(-margin, extra); points += firstSelection.topLeft() + QPointF(-margin, -margin); QPainterPath path; const int corner = 4; path.moveTo(points.at(0)); points += points.at(0); QPointF previous = points.at(0); for (int i = 1; i < points.size(); ++i) { QPointF point = points.at(i); if (point.y() == previous.y() && qAbs(point.x() - previous.x()) > 2*corner) { QPointF tmp = QPointF(previous.x() + corner * ((point.x() > previous.x())?1:-1), previous.y()); path.quadTo(previous, tmp); previous = tmp; i--; continue; } else if (point.x() == previous.x() && qAbs(point.y() - previous.y()) > 2*corner) { QPointF tmp = QPointF(previous.x(), previous.y() + corner * ((point.y() > previous.y())?1:-1)); path.quadTo(previous, tmp); previous = tmp; i--; continue; } QPointF target = (previous + point) / 2; path.quadTo(previous, target); previous = points.at(i); } path.closeSubpath(); path.translate(offset); return path; }
std::pair<casa::Vector<casa::Quantity>,casa::Vector<casa::Quantity> > ImageRegionGenerator::_getEllipsePositionRadii( Carta::Lib::Regions::Ellipse* ellipse, const casa::CoordinateSystem &cs ){ QRectF outlineBox = ellipse->outlineBox(); QPointF topLeftPt = outlineBox.topLeft(); QPointF centerPt = outlineBox.center(); bool validCenter = false; casa::Vector<casa::Double> centerWorld = _toWorld( cs, centerPt.x(), centerPt.y(), &validCenter ); bool validTopLeft = false; casa::Vector<casa::Double> topLeft = _toWorld( cs, topLeftPt.x(), topLeftPt.y(), &validTopLeft ); casa::Vector<casa::Quantum<casa::Double> > qcenter, qtlc; casa::Vector<casa::Quantity> radii_(2); if ( validCenter && validTopLeft ){ qcenter.resize(2); qtlc.resize(2); casa::String units( RAD_UNITS.toStdString().c_str() ); qcenter[0] = casa::Quantum<casa::Double>(centerWorld[0], units); qcenter[1] = casa::Quantum<casa::Double>(centerWorld[1], units); qtlc[0] = casa::Quantum<casa::Double>(topLeft[0], units); qtlc[1] = casa::Quantum<casa::Double>(topLeft[1], units); int directionIndex = cs.directionCoordinateNumber(); casa::MDirection::Types cccs = casa::MDirection::N_Types; if ( directionIndex < 0 ){ // no direction coordinate was found... double c0 = qcenter[0].getValue(); double lc0 = qtlc[0].getValue(); double c1 = qcenter[1].getValue(); double lc1 = qtlc[1].getValue(); radii_[0] = qAbs( c0 - lc0 ); radii_[1] = qAbs( c1 - lc1 ); } else { cccs = cs.directionCoordinate( directionIndex).directionType( true ); // a direction coordinate was found... casa::Vector<casa::Double> center_rad(2); center_rad[0] = qcenter[0].getValue( units ); center_rad[1] = qcenter[1].getValue( units ); casa::MDirection mdcenter( casa::Quantum<casa::Vector<casa::Double> > (center_rad,units), cccs ); casa::Vector<casa::Double> tlc_rad_x(2); tlc_rad_x[0] = qtlc[0].getValue( units); tlc_rad_x[1] = qcenter[1].getValue( units ); casa::MDirection mdtlc_x( casa::Quantum<casa::Vector<casa::Double> >(tlc_rad_x,units),cccs ); casa::Vector<casa::Double> tlc_rad_y(2); tlc_rad_y[0] = qcenter[0].getValue(units); tlc_rad_y[1] = qtlc[1].getValue(units); casa::MDirection mdtlc_y( casa::Quantum<casa::Vector<casa::Double> >(tlc_rad_y,units),cccs ); double xdistance = mdcenter.getValue( ).separation(mdtlc_x.getValue( )); double ydistance = mdcenter.getValue( ).separation(mdtlc_y.getValue( )); radii_[0] = casa::Quantity(xdistance, units); radii_[1] = casa::Quantity(ydistance, units); } } return std::make_pair(qcenter,radii_); }
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(); }
SCgPointObject::PointFVector SCgContour::minimizedPoints() const { // Collect items which is a scgObject: QSet<SCgObject *> scgObjects; foreach(QGraphicsItem* item, childItems()) { if (SCgObject::isSCgObjectType(item->type())) { SCgObject *scgObject = static_cast<SCgObject*>(item); scgObjects.insert(scgObject); } } if (!scgObjects.isEmpty()) { // Find min and max points: qreal minX, minY, maxX, maxY; QSet<SCgObject *>::const_iterator it; it = scgObjects.begin(); SCgObject *firstObj = *it; QRectF firstObjRect = firstObj->boundingRect(); minX = firstObj->mapToScene(firstObjRect.topLeft()).x(); minY = firstObj->mapToScene(firstObjRect.topLeft()).y(); maxX = firstObj->mapToScene(firstObjRect.bottomRight()).x(); maxY = firstObj->mapToScene(firstObjRect.bottomRight()).y(); for (++it; it != scgObjects.end(); ++it) { SCgObject *obj = *it; QRectF objRect = obj->boundingRect(); QPointF topLeft = obj->mapToScene(objRect.topLeft()); QPointF bottomRight = obj->mapToScene(objRect.bottomRight()); if (topLeft.x() < minX) { minX = topLeft.x(); } if (topLeft.y() < minY) { minY = topLeft.y(); } if (bottomRight.x() > maxX) { maxX = bottomRight.x(); } if (bottomRight.y() > maxY) { maxY = bottomRight.y(); } } // Increase distance from borders: minX -= borderDistance; minY -= borderDistance; maxX += borderDistance; maxY += borderDistance; // Remove all points and set only 4 corner points: PointFVector newPoints; newPoints << QPointF(minX, minY) << QPointF(maxX, minY) << QPointF(maxX, maxY) << QPointF(minX, maxY); return newPoints; } }
QRectF FixedRatioTransform::sceneToData(QRectF sceneRect) const { return QRectF(sceneToData(sceneRect.topLeft()), sceneToData(sceneRect.size())); }
void OverlayEditorScene::mouseMoveEvent(QGraphicsSceneMouseEvent *e) { QGraphicsScene::mouseMoveEvent(e); if (e->isAccepted()) return; if (qgpiSelected && (e->buttons() & Qt::LeftButton)) { e->accept(); if (wfsHover == Qt::NoSection) return; QPointF delta = e->scenePos() - e->buttonDownScenePos(Qt::LeftButton); bool square = e->modifiers() & Qt::ShiftModifier; QRectF orig = selectedRect(); switch (wfsHover) { case Qt::TitleBarArea: orig.translate(delta); break; case Qt::TopSection: orig.setTop(orig.top() + delta.y()); if (orig.height() < 8.0f) orig.setTop(orig.bottom() - 8.0f); if (square) orig.setRight(orig.left() + orig.height()); break; case Qt::BottomSection: orig.setBottom(orig.bottom() + delta.y()); if (orig.height() < 8.0f) orig.setBottom(orig.top() + 8.0f); if (square) orig.setRight(orig.left() + orig.height()); break; case Qt::LeftSection: orig.setLeft(orig.left() + delta.x()); if (orig.width() < 8.0f) orig.setLeft(orig.right() - 8.0f); if (square) orig.setBottom(orig.top() + orig.width()); break; case Qt::RightSection: orig.setRight(orig.right() + delta.x()); if (orig.width() < 8.0f) orig.setRight(orig.left() + 8.0f); if (square) orig.setBottom(orig.top() + orig.width()); break; case Qt::TopLeftSection: orig.setTopLeft(orig.topLeft() + delta); if (orig.height() < 8.0f) orig.setTop(orig.bottom() - 8.0f); if (orig.width() < 8.0f) orig.setLeft(orig.right() - 8.0f); if (square) { qreal size = qMin(orig.width(), orig.height()); QPointF sz(-size, -size); orig.setTopLeft(orig.bottomRight() + sz); } break; case Qt::TopRightSection: orig.setTopRight(orig.topRight() + delta); if (orig.height() < 8.0f) orig.setTop(orig.bottom() - 8.0f); if (orig.width() < 8.0f) orig.setRight(orig.left() + 8.0f); if (square) { qreal size = qMin(orig.width(), orig.height()); QPointF sz(size, -size); orig.setTopRight(orig.bottomLeft() + sz); } break; case Qt::BottomLeftSection: orig.setBottomLeft(orig.bottomLeft() + delta); if (orig.height() < 8.0f) orig.setBottom(orig.top() + 8.0f); if (orig.width() < 8.0f) orig.setLeft(orig.right() - 8.0f); if (square) { qreal size = qMin(orig.width(), orig.height()); QPointF sz(-size, size); orig.setBottomLeft(orig.topRight() + sz); } break; case Qt::BottomRightSection: orig.setBottomRight(orig.bottomRight() + delta); if (orig.height() < 8.0f) orig.setBottom(orig.top() + 8.0f); if (orig.width() < 8.0f) orig.setRight(orig.left() + 8.0f); if (square) { qreal size = qMin(orig.width(), orig.height()); QPointF sz(size, size); orig.setBottomRight(orig.topLeft() + sz); } break; case Qt::NoSection: // Handled above, but this makes the compiler happy. return; } qgriSelected->setRect(orig); } else { updateCursorShape(e->scenePos()); } }
void Window::setGeometry(const QRectF &geometry) { qDebug() << "WINDOW: set geometry" << geometry << m_surface.key(); m_size = geometry.size(); setPos(geometry.topLeft()); }
void ORPrintRender::renderPage(ORODocument * pDocument, int pageNb, QPainter *painter, qreal xDpi, qreal yDpi, QSize margins, int printResolution) { OROPage * p = pDocument->page(pageNb); if(((!p->backgroundImage().isNull()) && (p->backgroundOpacity() != 0)) || ((!p->watermarkText().isEmpty()) && (p->watermarkOpacity() != 0))) { // Do some simple processing used by both Background and Watermark const int resolution = 100; bool doBgWm = false; int printMarginWidth = margins.width(); int printMarginHeight = margins.height(); QString pageSize = pDocument->pageOptions().getPageSize(); int pageWidth = 0; int pageHeight = 0; if(pageSize == "Custom") { // if this is custom sized sheet of paper we will just use those values pageWidth = (int)(pDocument->pageOptions().getCustomWidth() * resolution); pageHeight = (int)(pDocument->pageOptions().getCustomHeight() * resolution); } else { // lookup the correct size information for the specified size paper PageSizeInfo pi = PageSizeInfo::getByName(pageSize); if(!pi.isNull()) { pageWidth = (int)((pi.width() / 100.0) * resolution); pageHeight = (int)((pi.height() / 100.0) * resolution); } } if(!pDocument->pageOptions().isPortrait()) { int tmp = pageWidth; pageWidth = pageHeight; pageHeight = tmp; } if(pageWidth < 1 || pageHeight < 1) { // whoops we couldn't find it.... we will use the values from the painter // and add in the margins of the printer to get what should be the correct // size of the sheet of paper we are printing to. pageWidth = (int)(((painter->viewport().width() + printMarginWidth + printMarginWidth) / xDpi) * resolution); pageHeight = (int)(((painter->viewport().height() + printMarginHeight + printMarginHeight) / yDpi) * resolution); } QImage image = QImage(pageWidth, pageHeight, QImage::Format_RGB32); QPainter gPainter; if(gPainter.begin(&image)) gPainter.fillRect(gPainter.viewport(), QColor(Qt::white)); // Render Background if((!p->backgroundImage().isNull()) && (p->backgroundOpacity() != 0)) { doBgWm = true; QPointF ps = p->backgroundPosition(); QSizeF sz = p->backgroundSize(); QRectF rc = QRectF(ps.x() * resolution, ps.y() * resolution, sz.width() * resolution, sz.height() * resolution); renderBackground(image, p->backgroundImage(), rc.toRect(), p->backgroundScale(), p->backgroundScaleMode(), p->backgroundAlign(), p->backgroundOpacity()); } // Render Watermark if((!p->watermarkText().isEmpty()) && (p->watermarkOpacity() != 0)) { doBgWm = true; renderWatermark(image, p->watermarkText(), p->watermarkFont(), p->watermarkOpacity(), ((pDocument->pageOptions().getMarginLeft() + pDocument->pageOptions().getMarginRight()) * resolution), ((pDocument->pageOptions().getMarginTop() + pDocument->pageOptions().getMarginBottom()) * resolution), pDocument->pageOptions().getMarginLeft() * resolution, pDocument->pageOptions().getMarginTop() * resolution); } if(doBgWm) { QRectF target(-printMarginWidth, -printMarginHeight, (painter->viewport().width() + printMarginWidth + printMarginWidth), (painter->viewport().height() + printMarginHeight + printMarginHeight)); QRectF source(0, 0, image.width(), image.height()); painter->drawImage(target, image, source); } } // Render Page Objects for(int i = 0; i < p->primitives(); i++) { OROPrimitive * prim = p->primitive(i); QPen pen(prim->pen()); painter->save(); painter->setPen(pen); painter->setBrush(prim->brush()); QPointF ps = prim->position(); if(prim->rotationAxis().isNull()) { painter->translate(ps.x() * xDpi, ps.y() * yDpi); painter->rotate(prim->rotation()); // rotation around the origin of the primitive (not the center) } else { // rotation around the defined axis qreal xRot = prim->rotationAxis().x(); qreal yRot = prim->rotationAxis().y(); painter->translate(xRot * xDpi, yRot * yDpi); painter->rotate(prim->rotation()); painter->translate((ps.x() - xRot) * xDpi, (ps.y() - yRot) * yDpi); } if(prim->type() == OROTextBox::TextBox) { OROTextBox * tb = (OROTextBox*)prim; painter->setFont(tb->font()); QSizeF sz = tb->size(); QRectF rc = QRectF(0, 0, sz.width() * xDpi, sz.height() * yDpi); painter->drawText(rc, tb->flags(), tb->text()); } else if(prim->type() == OROLine::Line) { OROLine * ln = (OROLine*)prim; QPointF s = ln->startPoint(); QPointF e = ln->endPoint(); pen.setWidthF((ln->weight() / 100) * printResolution); painter->setPen(pen); painter->drawLine(QLineF(0, 0, (e.x()-s.x()) * xDpi, (e.y()-s.y()) * yDpi)); } else if(prim->type() == OROImage::Image) { OROImage * im = (OROImage*)prim; QSizeF sz = im->size(); QRectF rc = QRectF(0, 0, sz.width() * xDpi, sz.height() * yDpi); QImage img = im->image(); if(im->scaled()) img = img.scaled(rc.size().toSize(), (Qt::AspectRatioMode)im->aspectRatioMode(), (Qt::TransformationMode)im->transformationMode()); QRectF sr = QRectF(QPointF(0.0, 0.0), rc.size().boundedTo(img.size())); painter->drawImage(rc.topLeft(), img, sr); } else if(prim->type() == ORORect::Rect) { ORORect * re = (ORORect*)prim; QSizeF sz = re->size(); QRectF rc = QRectF(0, 0, sz.width() * xDpi, sz.height() * yDpi); pen.setWidthF((re->weight() / 100) * printResolution); painter->setPen(pen); painter->drawRect(rc); } else { qDebug("unrecognized primitive type"); } painter->restore(); } }
void WebViewCache::draw(QPainter * painter, QGraphicsEffectSource * source) { const QGraphicsItem *item = source->graphicsItem(); QSizeF itemSize = item->boundingRect().size(); if (!qFuzzyCompare(itemSize.width(), m_itemSize.width()) || !qFuzzyCompare(itemSize.height(), m_itemSize.height())) { qDebug() << "Refresh tile cache, for new size" << itemSize; for (int i = 0; i < m_tilePixmaps.size(); i++) { QPixmapCache::remove(m_tilePixmaps[i]); } m_tilePixmaps.clear(); m_tileRects.clear(); int itemWidth = itemSize.width() + 0.5; int itemHeight = itemSize.height() + 0.5; int tilesX = itemWidth / TileSideLength; int tilesY = itemHeight / TileSideLength; if ((itemWidth % TileSideLength) != 0) { ++tilesX; } if ((itemHeight % TileSideLength) != 0) { ++tilesY; } int tilesCount = tilesX * tilesY; m_tilePixmaps.resize(tilesCount); m_tileRects.resize(tilesCount); for (int i = 0; i < tilesX; i++) { for (int j = 0; j < tilesY; j++) { int x = i * TileSideLength; int y = j * TileSideLength; m_tileRects[i + j * tilesX] = QRectF(x, y, TileSideLength, TileSideLength); } } m_itemSize = itemSize; } const QGraphicsItem *parentItem = item->parentItem(); QPointF itemPos = item->pos(); QRectF parentRect = parentItem->boundingRect(); for (int i = 0; i < m_tileRects.size(); i++) { QRectF tileRect = m_tileRects[i].translated(itemPos); if (!tileRect.intersects(parentRect) && !tileRect.contains(parentRect)) { continue; } QPixmap tilePixmap; if (!QPixmapCache::find(m_tilePixmaps[i], &tilePixmap)) { tilePixmap = QPixmap(TileSideLength, TileSideLength); QWebFrame *webFrame = m_webView->page()->mainFrame(); QPainter tilePainter(&tilePixmap); tilePainter.translate(-m_tileRects[i].left(), -m_tileRects[i].top()); webFrame->render(&tilePainter, m_tileRects[i].toRect()); tilePainter.end(); m_tilePixmaps[i] = QPixmapCache::insert(tilePixmap); } tileRect = tileRect.translated(-itemPos); painter->drawPixmap(tileRect.topLeft(), tilePixmap); } }
void TextPrinter::paintPage(QPainter *painter, QTextDocument *document, int pagenum) { QRectF rect; double onepoint = painter->device()->logicalDpiY() / 72.0; // header if (headersize_ > 0) { rect = headerRect(painter->device()); if (headerrule_ > 0.0) { painter->save(); // allow space between rule and header painter->translate(0, onepoint + (headerrule_ * onepoint / 2.0)); painter->setPen(QPen(Qt::black, headerrule_ * onepoint)); painter->drawLine(rect.bottomLeft(), rect.bottomRight()); painter->restore(); } // replace page variables QString header = headertext_; header.replace("&page;", QString::number(pagenum)); if (dateformat_.isEmpty()) { header.replace("&date;", QDate::currentDate().toString()); } else { header.replace("&date;", QDate::currentDate().toString(dateformat_)); } painter->save(); painter->translate(rect.left(), rect.top()); QRectF clip(0, 0, rect.width(), rect.height()); QTextDocument doc; doc.setUseDesignMetrics(true); doc.setHtml(header); doc.documentLayout()->setPaintDevice(painter->device()); doc.setPageSize(rect.size()); // align text to bottom double newtop = clip.bottom() - doc.size().height(); clip.setHeight(doc.size().height()); painter->translate(0, newtop); doc.drawContents(painter, clip); painter->restore(); } // footer if (footersize_ > 0) { rect = footerRect(painter->device()); if (footerrule_ > 0.0) { painter->save(); // allow space between rule and footer painter->translate(0, -onepoint + (-footerrule_ * onepoint / 2.0)); painter->setPen(QPen(Qt::black, footerrule_ * onepoint)); painter->drawLine(rect.topLeft(), rect.topRight()); painter->restore(); } // replace page variables QString footer = footertext_; footer.replace("&page;", QString::number(pagenum)); if (dateformat_.isEmpty()) { footer.replace("&date;", QDate::currentDate().toString()); } else { footer.replace("&date;", QDate::currentDate().toString(dateformat_)); } painter->save(); painter->translate(rect.left(), rect.top()); QRectF clip(0, 0, rect.width(), rect.height()); QTextDocument doc; doc.setUseDesignMetrics(true); doc.setHtml(footer); doc.documentLayout()->setPaintDevice(painter->device()); doc.setPageSize(rect.size()); doc.drawContents(painter, clip); painter->restore(); } // content painter->save(); rect = contentRect(painter->device()); painter->translate(rect.left(), rect.top() - (pagenum-1) * rect.height()); QRectF clip(0, (pagenum-1) * rect.height(), rect.width(), rect.height()); document->drawContents(painter, clip); painter->restore(); }
void renderCodeUPCE(OROPage * page, const QRectF & r, const QString & _str, ORBarcodeData * bc) { int val[8]; int i = 0; // initialize all the values just so we can be predictable for(i = 0; i < 8; i++) val[i] = -1; // verify that the passed in string is valid // if it's not either twelve or thirteen characters // then it must be invalid to begin with if(_str.length() != 8) return; // loop through and convert each char to a digit. // if we can't convert all characters then this is // an invalid number for(i = 0; i < _str.length(); i++) { val[i] = ((QChar)_str.at(i)).digitValue(); if(val[i] == -1) return; } // calculate and append the checksum value // because everything is so messed up we don't calculate // the checksum and require that it be passed in already // however we do have to verify that the first digit is // either 0 or 1 as that is our parity if(val[0] != 0 && val[0] != 1) return; // lets determine some core attributes about this barcode qreal bar_width = bc->narrowBarWidth; // the width of the base unit bar // this is are mandatory minimum quiet zone qreal quiet_zone = bar_width * 0.10; if(quiet_zone < 0.10) quiet_zone = 0.10; // what kind of area do we have to work with qreal draw_width = r.width(); qreal draw_height = r.height() - 0.02; // L = 51X // L length of barcode (excluding quite zone) in units same as X and I // X the width of a bar (pixels in our case) qreal L; qreal X = bar_width; L = (51.0 * X); // now we have the actual width the barcode will be so can determine the actual // size of the quiet zone (we assume we center the barcode in the given area // what should we do if the area is too small???? // At the moment the way the code is written is we will always start at the minimum // required quiet zone if we don't have enough space.... I guess we'll just have over-run // to the right // // calculate the starting position based on the alignment option // for left align we don't need to do anything as the values are already setup for it if(bc->align == 1) // center { qreal nqz = (draw_width - L) / 2; if(nqz > quiet_zone) quiet_zone = nqz; } else if(bc->align > 1) // right quiet_zone = draw_width - (L + quiet_zone); // else if(align < 1) {} // left : do nothing qreal pos = r.left() + quiet_zone; qreal top = r.top(); QPen pen(Qt::NoPen); QBrush brush(QColor("black")); int b = 0; int w = 0; // render open guard ORORect * rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += bar_width; // render first set for(i = 0; i < 6; i++) { b = val[i+1]; for(w = 0; w < 7; w++) { if(_encodings[b][_upcparenc[val[7]][val[0]][i]][w]) { rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height - 0.07)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); } pos += bar_width; } } // render center guard pos += bar_width; rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); pos += (bar_width * 2.0); // render close guard rect = new ORORect(bc); rect->setPen(pen); rect->setBrush(brush); rect->setRect(QRectF(pos,top, bar_width,draw_height)); rect->setRotationAxis(r.topLeft()); page->addPrimitive(rect); QString parstr = QString("%1").arg(val[0]); QString chkstr = QString("%1").arg(val[7]); QString leftstr = QString().sprintf("%d%d%d%d%d%d", val[1], val[2], val[3], val[4], val[5], val[6]); QFont font("Arial",6); OROTextBox * tb = new OROTextBox(bc); tb->setPosition(QPointF(r.left(), r.top() + draw_height - 0.12)); tb->setSize(QSizeF(quiet_zone - 2*bar_width, 0.12)); tb->setFont(font); tb->setText(parstr); tb->setFlags(Qt::AlignRight | Qt::AlignTop); tb->setRotationAxis(r.topLeft()); page->addPrimitive(tb); tb = new OROTextBox(bc); tb->setPosition(QPointF(r.left() + quiet_zone + 0.03, (r.top() + draw_height) - 0.07)); tb->setSize(QSizeF(42*bar_width, 0.10)); tb->setFont(font); tb->setText(leftstr); tb->setFlags(Qt::AlignHCenter | Qt::AlignTop); tb->setRotationAxis(r.topLeft()); page->addPrimitive(tb); tb = new OROTextBox(bc); tb->setPosition(QPointF(r.left() + quiet_zone + L + 0.02, r.top() + draw_height - 0.12)); tb->setSize(QSizeF(8*bar_width, 0.12)); tb->setFont(font); tb->setText(chkstr); tb->setFlags(Qt::AlignLeft | Qt::AlignTop); tb->setRotationAxis(r.topLeft()); page->addPrimitive(tb); return; }
void MapRenderer::render( QPainter* P, const QMap<RenderPriority, QSet <Feature*> >& theFeatures, const QRectF& pViewport, const QRect& screen, const qreal pixelPerM, const RendererOptions& options ) { // #ifndef NDEBUG // QTime Start(QTime::currentTime()); // #endif theViewport = pViewport; theScreen = screen; thePixelPerM = pixelPerM; qreal Aspect = (double)screen.width() / screen.height(); qreal pAspect = fabs(pViewport.width() / pViewport.height()); qreal wv, hv; if (pAspect > Aspect) { wv = fabs(pViewport.width()); hv = fabs(pViewport.height() * pAspect / Aspect); } else { wv = fabs(pViewport.width() * Aspect / pAspect); hv = fabs(pViewport.height()); } qreal ScaleLon = screen.width() / wv; qreal ScaleLat = screen.height() / hv; theTransform.reset(); theTransform.scale(ScaleLon, -ScaleLat); theTransform.translate(-pViewport.topLeft().x(), -pViewport.topLeft().y()); // qDebug() << "render transform: " << theTransform; theOptions = options; theGlobalPainter = M_STYLE->getGlobalPainter(); if (theGlobalPainter.DrawNodes) { NodeWidth = thePixelPerM*theGlobalPainter.NodesProportional+theGlobalPainter.NodesFixed; } else { NodeWidth = thePixelPerM * M_PREFS->getNodeSize(); if (NodeWidth > M_PREFS->getNodeSize()) NodeWidth = M_PREFS->getNodeSize(); } bool bgLayerVisible = TEST_RFLAGS(RendererOptions::BackgroundVisible); bool fgLayerVisible = TEST_RFLAGS(RendererOptions::ForegroundVisible); bool tchpLayerVisible = TEST_RFLAGS(RendererOptions::TouchupVisible); bool lblLayerVisible = TEST_RFLAGS(RendererOptions::NamesVisible); QMap<RenderPriority, QSet<Feature*> >::const_iterator itm; QMap<RenderPriority, QSet<Feature*> >::const_iterator itmCur; QSet<Feature*>::const_iterator it; thePainter = P; thePainter->save(); thePainter->translate(screen.left(), screen.top()); itm = theFeatures.constBegin(); while (itm != theFeatures.constEnd()) { int curLayer = (itm.key()).layer(); itmCur = itm; while (itm != theFeatures.constEnd() && (itm.key()).layer() == curLayer) { if (bgLayerVisible) { for (it = itm.value().constBegin(); it != itm.value().constEnd(); ++it) { qreal alpha = (*it)->getAlpha(); if ((*it)->isReadonly() && !TEST_RFLAGS(RendererOptions::ForPrinting)) alpha /= 2.0; if (alpha != 1.) { P->save(); P->setOpacity(alpha); } if (CHECK_WAY(*it)) { Way * R = STATIC_CAST_WAY(*it); for (int i=0; i<R->sizeParents(); ++i) if (!R->getParent(i)->isDeleted() && R->getParent(i)->hasPainter(thePixelPerM)) continue; bglayer.draw(R); } else if (CHECK_NODE(*it)) bglayer.draw(STATIC_CAST_NODE(*it)); else if (CHECK_RELATION(*it)) bglayer.draw(STATIC_CAST_RELATION(*it)); if (alpha != 1.) { P->restore(); } } } ++itm; } itm = itmCur; while (itm != theFeatures.constEnd() && (itm.key()).layer() == curLayer) { if (fgLayerVisible) { for (it = itm.value().constBegin(); it != itm.value().constEnd(); ++it) { qreal alpha = (*it)->getAlpha(); if ((*it)->isReadonly() && !TEST_RFLAGS(RendererOptions::ForPrinting)) alpha /= 2.0; if (alpha != 1.) { P->save(); P->setOpacity(alpha); } if (CHECK_WAY(*it)) { Way * R = STATIC_CAST_WAY(*it); for (int i=0; i<R->sizeParents(); ++i) if (!R->getParent(i)->isDeleted() && R->getParent(i)->hasPainter(thePixelPerM)) continue; fglayer.draw(R); } else if (CHECK_NODE(*it)) fglayer.draw(STATIC_CAST_NODE(*it)); else if (CHECK_RELATION(*it)) fglayer.draw(STATIC_CAST_RELATION(*it)); if (alpha != 1.) { P->restore(); } } } ++itm; } } if (tchpLayerVisible) { for (itm = theFeatures.constBegin() ;itm != theFeatures.constEnd(); ++itm) { for (it = itm.value().constBegin(); it != itm.value().constEnd(); ++it) { qreal alpha = (*it)->getAlpha(); if ((*it)->isReadonly() && !TEST_RFLAGS(RendererOptions::ForPrinting)) alpha /= 2.0; if (alpha != 1.) { P->save(); P->setOpacity(alpha); } if (CHECK_WAY(*it)) { Way * R = STATIC_CAST_WAY(*it); for (int i=0; i<R->sizeParents(); ++i) if (!R->getParent(i)->isDeleted() && R->getParent(i)->hasPainter(thePixelPerM)) continue; tchuplayer.draw(R); } else if (CHECK_NODE(*it)) tchuplayer.draw(STATIC_CAST_NODE(*it)); else if (CHECK_RELATION(*it)) tchuplayer.draw(STATIC_CAST_RELATION(*it)); if (alpha != 1.) { P->restore(); } } } } if (lblLayerVisible) { for (itm = theFeatures.constBegin() ;itm != theFeatures.constEnd(); ++itm) { for (it = itm.value().constBegin(); it != itm.value().constEnd(); ++it) { P->save(); qreal alpha = (*it)->getAlpha(); if ((*it)->isReadonly() && !TEST_RFLAGS(RendererOptions::ForPrinting)) alpha /= 2.0; P->setOpacity(alpha); if (CHECK_WAY(*it)) { Way * R = STATIC_CAST_WAY(*it); for (int i=0; i<R->sizeParents(); ++i) if (!R->getParent(i)->isDeleted() && R->getParent(i)->hasPainter(thePixelPerM)) continue; lbllayer.draw(R); } else if (CHECK_NODE(*it)) lbllayer.draw(STATIC_CAST_NODE(*it)); else if (CHECK_RELATION(*it)) lbllayer.draw(STATIC_CAST_RELATION(*it)); P->restore(); } } } thePainter->restore(); // #ifndef NDEBUG // QTime Stop(QTime::currentTime()); // qDebug() << Start.msecsTo(Stop) << "ms"; // #endif }