Ejemplo n.º 1
0
void EncloseElement::layout( const AttributeManager* am )
{
    // TODO: actuarial (how does it look?) - radical - circle (how to determine extends )
    m_enclosePath = QPainterPath();
    QString tmpstring = am->stringOf( "notation", this );
    QList<QString> tmp=tmpstring.split(' ');
    RowElement::layout( am );
    QRectF tmpRect = boundingRect();
/*    if( tmp.contains( "longdiv" ) ) {
        m_enclosePath.moveTo( 0, 0 );
        m_enclosePath.lineTo();
    }*/
    if( tmp.contains( "left" ) ) {
        m_enclosePath.moveTo( 0, 0 );
        m_enclosePath.lineTo( 0, tmpRect.height() );
    }
    if( tmp.contains( "right" ) ) {
        m_enclosePath.moveTo( tmpRect.width(), 0 );
        m_enclosePath.lineTo( tmpRect.width(), tmpRect.height() );
    }
    if( tmp.contains( "top" ) ) {
        m_enclosePath.moveTo( 0, 0 );
        m_enclosePath.lineTo( tmpRect.width(), 0 );
    }
    if( tmp.contains( "bottom" ) ) {
        m_enclosePath.moveTo( 0, tmpRect.height() );
        m_enclosePath.lineTo( tmpRect.width(), tmpRect.height());
    }
    if( tmp.contains( "box" ) ) {        // TODO spacing is missing - might look odd
        m_enclosePath.addRect( 0, 0, tmpRect.width(), tmpRect.height() );
    }
    if( tmp.contains( "roundedbox" ) ) { // TODO spacing is missing - might look odd
    m_enclosePath.addRoundRect( 0, 0, tmpRect.width(), tmpRect.height(), 25 );
    }
    if( tmp.contains( "updiagonalstrike" ) ) {
        m_enclosePath.moveTo( 0, tmpRect.height() );
        m_enclosePath.lineTo( tmpRect.width(), 0 );
    }
    if( tmp.contains( "downdiagonalstrike" ) ) {
        m_enclosePath.moveTo( 0, 0 );
        m_enclosePath.lineTo( tmpRect.width(), tmpRect.height() );
    }
    if( tmp.contains( "verticalstrike" ) ) {
        m_enclosePath.moveTo( tmpRect.width()/2, 0 );
        m_enclosePath.lineTo( tmpRect.width()/2, tmpRect.height() );
    }
    if( tmp.contains( "horizontalstrike" ) ) {
        m_enclosePath.moveTo( 0, tmpRect.height()/2 );
        m_enclosePath.lineTo( tmpRect.width(), tmpRect.height()/2 );
    }
    setWidth( tmpRect.width() );
    setHeight( tmpRect.height() );
}
Ejemplo n.º 2
0
void PanoPreviewPage::startStitching()
{
    QMutexLocker lock(&d->previewBusyMutex);

    if (d->previewBusy)
    {
        // The real beginning of the stitching starts after preview has finished / failed
        connect(this, SIGNAL(signalPreviewFinished()), this, SLOT(slotStartStitching()));
        cleanupPage(lock);
        return;
    }

    connect(d->mngr->thread(), SIGNAL(starting(Digikam::PanoActionData)),
            this, SLOT(slotPanoAction(Digikam::PanoActionData)));

    connect(d->mngr->thread(), SIGNAL(stepFinished(Digikam::PanoActionData)),
            this, SLOT(slotPanoAction(Digikam::PanoActionData)));

    connect(d->mngr->thread(), SIGNAL(jobCollectionFinished(Digikam::PanoActionData)),
            this, SLOT(slotPanoAction(Digikam::PanoActionData)));

    d->canceled      = false;
    d->stitchingBusy = true;
    d->curProgress   = 0;

    if (d->mngr->hugin2015())
    {
        d->totalProgress = 1;
    }
    else
    {
        d->totalProgress = d->mngr->preProcessedMap().size() + 1;
    }

    d->previewWidget->hide();

    QSize panoSize      = d->mngr->viewAndCropOptimisePtoData()->project.size;
    QRect panoSelection = d->mngr->viewAndCropOptimisePtoData()->project.crop;

    if (d->previewDone)
    {
        QSize previewSize = d->mngr->previewPtoData()->project.size;
        QRectF selection  = d->previewWidget->getSelectionArea();
        QRectF proportionSelection(selection.x()      / previewSize.width(),
                                   selection.y()      / previewSize.height(),
                                   selection.width()  / previewSize.width(),
                                   selection.height() / previewSize.height());

        // At this point, if no selection area was created, proportionSelection is null,
        // hence panoSelection becomes a null rectangle
        panoSelection = QRect(proportionSelection.x()      * panoSize.width(),
                              proportionSelection.y()      * panoSize.height(),
                              proportionSelection.width()  * panoSize.width(),
                              proportionSelection.height() * panoSize.height());
    }

    d->title->setText(i18n("<qt>"
                           "<p><h1>Panorama Post-Processing</h1></p>"
                           "</qt>"));

    d->progressBar->reset();
    d->progressBar->setMaximum(d->totalProgress);
    d->progressBar->progressScheduled(i18nc("@title:group", "Panorama Post-Processing"), true, true);
    d->progressBar->progressThumbnailChanged(QIcon::fromTheme(QLatin1String("panorama")).pixmap(22, 22));
    d->progressBar->show();
    d->postProcessing->show();

    d->mngr->resetPanoPto();
    d->mngr->resetMkUrl();
    d->mngr->resetPanoUrl();
    d->mngr->thread()->compileProject(d->mngr->viewAndCropOptimisePtoData(),
                                      d->mngr->panoPtoUrl(),
                                      d->mngr->mkUrl(),
                                      d->mngr->panoUrl(),
                                      d->mngr->preProcessedMap(),
                                      d->mngr->format(),
                                      panoSelection,
                                      d->mngr->makeBinary().path(),
                                      d->mngr->pto2MkBinary().path(),
                                      d->mngr->huginExecutorBinary().path(),
                                      d->mngr->hugin2015(),
                                      d->mngr->enblendBinary().path(),
                                      d->mngr->nonaBinary().path());
}
Ejemplo n.º 3
0
void QFontFamilyDelegate::paint(QPainter *painter,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    QString text = index.data(Qt::DisplayRole).toString();
    QFont font(option.font);
    font.setPointSize(QFontInfo(font).pointSize() * 3 / 2);
    QFont font2 = font;
    font2.setFamily(text);

    bool hasLatin;
    QFontDatabase::WritingSystem system = writingSystemForFont(font2, &hasLatin);
    if (hasLatin)
        font = font2;

    QRect r = option.rect;

    if (option.state & QStyle::State_Selected) {
        painter->save();
        painter->setBrush(option.palette.highlight());
        painter->setPen(Qt::NoPen);
        painter->drawRect(option.rect);
        painter->setPen(QPen(option.palette.highlightedText(), 0));
    }

    const QIcon *icon = &bitmap;
    if (QFontDatabase().isSmoothlyScalable(text)) {
        icon = &truetype;
    }
    QSize actualSize = icon->actualSize(r.size());

    icon->paint(painter, r, Qt::AlignLeft|Qt::AlignVCenter);
    if (option.direction == Qt::RightToLeft)
        r.setRight(r.right() - actualSize.width() - 4);
    else
        r.setLeft(r.left() + actualSize.width() + 4);

    QFont old = painter->font();
    painter->setFont(font);

    // If the ascent of the font is larger than the height of the rect,
    // we will clip the text, so it's better to align the tight bounding rect in this case
    // This is specifically for fonts where the ascent is very large compared to
    // the descent, like certain of the Stix family.
    QFontMetricsF fontMetrics(font);
    if (fontMetrics.ascent() > r.height()) {
        QRectF tbr = fontMetrics.tightBoundingRect(text);
        painter->drawText(r.x(), r.y() + (r.height() + tbr.height()) / 2.0, text);
    } else {
        painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, text);
    }

    if (writingSystem != QFontDatabase::Any)
        system = writingSystem;

    if (system != QFontDatabase::Any) {
        int w = painter->fontMetrics().width(text + QLatin1String("  "));
        painter->setFont(font2);
        QString sample = QFontDatabase().writingSystemSample(system);
        if (option.direction == Qt::RightToLeft)
            r.setRight(r.right() - w);
        else
            r.setLeft(r.left() + w);
        painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, sample);
    }
    painter->setFont(old);

    if (option.state & QStyle::State_Selected)
        painter->restore();

}
Ejemplo n.º 4
0
// Apply a simple variant type to a DOM property
static bool applySimpleProperty(const QVariant &v, bool translateString, DomProperty *dom_prop)
{
    switch (v.type()) {
    case QVariant::String: {
        DomString *str = new DomString();
        str->setText(v.toString());
        if (!translateString)
            str->setAttributeNotr(QLatin1String("true"));
        dom_prop->setElementString(str);
    }
    return true;

    case QVariant::ByteArray:
        dom_prop->setElementCstring(QString::fromUtf8(v.toByteArray()));
        return true;

    case QVariant::Int:
        dom_prop->setElementNumber(v.toInt());
        return true;

    case QVariant::UInt:
        dom_prop->setElementUInt(v.toUInt());
        return true;

    case QVariant::LongLong:
        dom_prop->setElementLongLong(v.toLongLong());
        return true;

    case QVariant::ULongLong:
        dom_prop->setElementULongLong(v.toULongLong());
        return true;

    case QVariant::Double:
        dom_prop->setElementDouble(v.toDouble());
        return true;

    case QVariant::Bool:
        dom_prop->setElementBool(v.toBool() ? QFormBuilderStrings::instance().trueValue : QFormBuilderStrings::instance().falseValue);
        return true;

    case QVariant::Char: {
        DomChar *ch = new DomChar();
        const QChar character = v.toChar();
        ch->setElementUnicode(character.unicode());
        dom_prop->setElementChar(ch);
    }
    return true;

    case QVariant::Point: {
        DomPoint *pt = new DomPoint();
        const QPoint point = v.toPoint();
        pt->setElementX(point.x());
        pt->setElementY(point.y());
        dom_prop->setElementPoint(pt);
    }
    return true;

    case QVariant::PointF: {
        DomPointF *ptf = new DomPointF();
        const QPointF pointf = v.toPointF();
        ptf->setElementX(pointf.x());
        ptf->setElementY(pointf.y());
        dom_prop->setElementPointF(ptf);
    }
    return true;

    case QVariant::Color: {
        DomColor *clr = new DomColor();
        const QColor color = qvariant_cast<QColor>(v);
        clr->setElementRed(color.red());
        clr->setElementGreen(color.green());
        clr->setElementBlue(color.blue());
        const int alphaChannel = color.alpha();
        if (alphaChannel != 255)
            clr->setAttributeAlpha(alphaChannel);
        dom_prop->setElementColor(clr);
    }
    return true;

    case QVariant::Size: {
        DomSize *sz = new DomSize();
        const QSize size = v.toSize();
        sz->setElementWidth(size.width());
        sz->setElementHeight(size.height());
        dom_prop->setElementSize(sz);
    }
    return true;

    case QVariant::SizeF: {
        DomSizeF *szf = new DomSizeF();
        const QSizeF sizef = v.toSizeF();
        szf->setElementWidth(sizef.width());
        szf->setElementHeight(sizef.height());
        dom_prop->setElementSizeF(szf);
    }
    return true;

    case QVariant::Rect: {
        DomRect *rc = new DomRect();
        const QRect rect = v.toRect();
        rc->setElementX(rect.x());
        rc->setElementY(rect.y());
        rc->setElementWidth(rect.width());
        rc->setElementHeight(rect.height());
        dom_prop->setElementRect(rc);
    }
    return true;

    case QVariant::RectF: {
        DomRectF *rcf = new DomRectF();
        const QRectF rectf = v.toRectF();
        rcf->setElementX(rectf.x());
        rcf->setElementY(rectf.y());
        rcf->setElementWidth(rectf.width());
        rcf->setElementHeight(rectf.height());
        dom_prop->setElementRectF(rcf);
    }
    return true;

    case QVariant::Font: {
        DomFont *fnt = new DomFont();
        const QFont font = qvariant_cast<QFont>(v);
        const uint mask = font.resolve();
        if (mask & QFont::WeightResolved) {
            fnt->setElementBold(font.bold());
            fnt->setElementWeight(font.weight());
        }
        if (mask & QFont::FamilyResolved)
            fnt->setElementFamily(font.family());
        if (mask & QFont::StyleResolved)
            fnt->setElementItalic(font.italic());
        if (mask & QFont::SizeResolved)
            fnt->setElementPointSize(font.pointSize());
        if (mask & QFont::StrikeOutResolved)
            fnt->setElementStrikeOut(font.strikeOut());
        if (mask & QFont::UnderlineResolved)
            fnt->setElementUnderline(font.underline());
        if (mask & QFont::KerningResolved)
            fnt->setElementKerning(font.kerning());
        if (mask & QFont::StyleStrategyResolved) {
            const QMetaEnum styleStrategy_enum = metaEnum<QAbstractFormBuilderGadget>("styleStrategy");
            fnt->setElementStyleStrategy(QLatin1String(styleStrategy_enum.valueToKey(font.styleStrategy())));
        }
        dom_prop->setElementFont(fnt);
    }
    return true;

#ifndef QT_NO_CURSOR
    case QVariant::Cursor: {
        const QMetaEnum cursorShape_enum = metaEnum<QAbstractFormBuilderGadget>("cursorShape");
        dom_prop->setElementCursorShape(QLatin1String(cursorShape_enum.valueToKey(qvariant_cast<QCursor>(v).shape())));
    }
    return true;
#endif

    case QVariant::KeySequence: {
        DomString *s = new DomString();
        s->setText(qvariant_cast<QKeySequence>(v).toString(QKeySequence::PortableText));
        dom_prop->setElementString(s);
    }
    return true;

    case QVariant::Locale: {
        DomLocale *dom = new DomLocale();
        const QLocale locale = qvariant_cast<QLocale>(v);

        const QMetaEnum language_enum = metaEnum<QAbstractFormBuilderGadget>("language");
        const QMetaEnum country_enum = metaEnum<QAbstractFormBuilderGadget>("country");

        dom->setAttributeLanguage(QLatin1String(language_enum.valueToKey(locale.language())));
        dom->setAttributeCountry(QLatin1String(country_enum.valueToKey(locale.country())));

        dom_prop->setElementLocale(dom);
    }
    return true;

    case QVariant::SizePolicy: {
        DomSizePolicy *dom = new DomSizePolicy();
        const QSizePolicy sizePolicy = qvariant_cast<QSizePolicy>(v);

        dom->setElementHorStretch(sizePolicy.horizontalStretch());
        dom->setElementVerStretch(sizePolicy.verticalStretch());

        const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType");

        dom->setAttributeHSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.horizontalPolicy())));
        dom->setAttributeVSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.verticalPolicy())));

        dom_prop->setElementSizePolicy(dom);
    }
    return true;

    case QVariant::Date: {
        DomDate *dom = new DomDate();
        const QDate date = qvariant_cast<QDate>(v);

        dom->setElementYear(date.year());
        dom->setElementMonth(date.month());
        dom->setElementDay(date.day());

        dom_prop->setElementDate(dom);
    }
    return true;

    case QVariant::Time: {
        DomTime *dom = new DomTime();
        const QTime time = qvariant_cast<QTime>(v);

        dom->setElementHour(time.hour());
        dom->setElementMinute(time.minute());
        dom->setElementSecond(time.second());

        dom_prop->setElementTime(dom);
    }
    return true;

    case QVariant::DateTime: {
        DomDateTime *dom = new DomDateTime();
        const QDateTime dateTime = qvariant_cast<QDateTime>(v);

        dom->setElementHour(dateTime.time().hour());
        dom->setElementMinute(dateTime.time().minute());
        dom->setElementSecond(dateTime.time().second());
        dom->setElementYear(dateTime.date().year());
        dom->setElementMonth(dateTime.date().month());
        dom->setElementDay(dateTime.date().day());

        dom_prop->setElementDateTime(dom);
    }
    return true;

    case QVariant::Url: {
        DomUrl *dom = new DomUrl();
        const QUrl url = v.toUrl();

        DomString *str = new DomString();
        str->setText(url.toString());
        dom->setElementString(str);

        dom_prop->setElementUrl(dom);
    }
    return true;

    case QVariant::StringList: {
        DomStringList *sl = new DomStringList;
        sl->setElementString(qvariant_cast<QStringList>(v));
        dom_prop->setElementStringList(sl);
    }
    return true;

    default:
        break;
    }

    return false;
}
Ejemplo n.º 5
0
 qreal KRITAIMAGE_EXPORT maxDimensionPortion(const QRectF &bounds, qreal portion, qreal minValue)
 {
     qreal maxDimension = qMax(bounds.width(), bounds.height());
     return qMax(portion * maxDimension, minValue);
 }
Ejemplo n.º 6
0
osgText::Glyph*
QFontImplementation::getGlyph(const osgText::FontResolution &fontRes, unsigned int charcode)
{
    unsigned int fontSize = fontRes.second;

    _font.setPixelSize(fontSize);

    float coord_scale = 1.0f / float(fontSize);

    QFontMetrics  fontMetrics(_font);
    QFontMetricsF fontMetricsF(_font);

    QRect  rect  = fontMetrics.boundingRect(QChar(charcode));
    QRectF rectF = fontMetricsF.boundingRect(QChar(charcode));

    int margin = 1;

    int imageWidth  = rect.width() + 2 * margin;
    int imageHeight = rect.height() + 2 * margin;

    // Now paint the glyph into the image
    QImage image(imageWidth, imageHeight, QImage::Format_ARGB32);
    image.fill(0);
    QPainter painter(&image);
    painter.setRenderHint(QPainter::TextAntialiasing);

    painter.setFont(_font);

    painter.setBackgroundMode(Qt::TransparentMode);
    painter.setBrush(Qt::white);
    painter.setPen(Qt::white);

    painter.drawText(margin - rect.left(), imageHeight - 1 - (margin + rect.bottom()), QString(QChar(charcode)));
    painter.end();

    // Transfer the rendered image to osg
    osg::ref_ptr<osgText::Glyph> glyph = new osgText::Glyph(_facade, charcode);

    unsigned int  dataSize = imageWidth * imageHeight;
    unsigned char *data    = new unsigned char[dataSize];

    // copy the qimage into the texture memory
    for (int x = 0; x < imageWidth; ++x)
    {
        for (int y = 0; y < imageHeight; ++y)
        {
            data[x + y * imageWidth] = qAlpha(image.pixel(x, imageHeight - 1 - y));
        }
    }

    // the glyph texture in osg
    glyph->setImage(imageWidth, imageHeight, 1,
                    OSGTEXT_GLYPH_INTERNALFORMAT,
                    OSGTEXT_GLYPH_FORMAT, GL_UNSIGNED_BYTE,
                    data,
                    osg::Image::USE_NEW_DELETE,
                    1);
    glyph->setInternalTextureFormat(OSGTEXT_GLYPH_INTERNALFORMAT);

    glyph->setWidth((float)imageWidth * coord_scale);
    glyph->setHeight((float)imageHeight * coord_scale);

    // Layout parameters
    float leftBearing  = fontMetricsF.leftBearing(QChar(charcode));
    float rightBearing = fontMetricsF.rightBearing(QChar(charcode));

    // for horizonal layout
    osg::Vec2 bottomLeft(leftBearing - margin, -rectF.bottom() - margin);
    glyph->setHorizontalBearing(bottomLeft * coord_scale);
    glyph->setHorizontalAdvance(fontMetricsF.width(QChar(charcode)) * coord_scale);

    // for vertical layout
    osg::Vec2 topMiddle(-margin + 0.5 * (leftBearing - rect.width() - rightBearing),
                        rectF.top() - margin);
    glyph->setVerticalBearing(topMiddle * coord_scale);
    glyph->setVerticalAdvance((rectF.height() + fontMetricsF.overlinePos() - fontMetricsF.xHeight()) * coord_scale);

    // ... ready
    // addGlyph(fontRes, charcode, glyph.get());

    return glyph.release();
}
Ejemplo n.º 7
0
QSize Text::size() const
{
    QRectF rect = boundingRect();
    return QSize(rect.width() - 1, rect.height() - 1);
}
Ejemplo n.º 8
0
void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseScale, bool outline)
{
    const QPointF* const points = reinterpret_cast<const QPointF*>(path.points());
    const QPainterPath::ElementType* const elements = path.elements();

    if (boundingRectDirty) {
        minX = maxX = points[0].x();
        minY = maxY = points[0].y();
        boundingRectDirty = false;
    }

    if (!outline && !path.isConvex())
        addCentroid(path, 0);

    int lastMoveTo = vertexArray.size();
    vertexArray.add(points[0]); // The first element is always a moveTo

    do {
        if (!elements) {
//             qDebug("QVectorPath has no elements");
            // If the path has a null elements pointer, the elements implicitly
            // start with a moveTo (already added) and continue with lineTos:
            for (int i=1; i<path.elementCount(); ++i)
                lineToArray(points[i].x(), points[i].y());

            break;
        }
//         qDebug("QVectorPath has element types");

        for (int i=1; i<path.elementCount(); ++i) {
            switch (elements[i]) {
            case QPainterPath::MoveToElement:
                if (!outline)
                    addClosingLine(lastMoveTo);
//                qDebug("element[%d] is a MoveToElement", i);
                vertexArrayStops.add(vertexArray.size());
                if (!outline) {
                    if (!path.isConvex()) addCentroid(path, i);
                    lastMoveTo = vertexArray.size();
                }
                lineToArray(points[i].x(), points[i].y()); // Add the moveTo as a new vertex
                break;
            case QPainterPath::LineToElement:
//                qDebug("element[%d] is a LineToElement", i);
                lineToArray(points[i].x(), points[i].y());
                break;
            case QPainterPath::CurveToElement: {
                QBezier b = QBezier::fromPoints(*(((const QPointF *) points) + i - 1),
                                                points[i],
                                                points[i+1],
                                                points[i+2]);
                QRectF bounds = b.bounds();
                // threshold based on same algorithm as in qtriangulatingstroker.cpp
                int threshold = qMin<float>(64, qMax(bounds.width(), bounds.height()) * 3.14f / (curveInverseScale * 6));
                if (threshold < 3) threshold = 3;
                qreal one_over_threshold_minus_1 = qreal(1) / (threshold - 1);
                for (int t=0; t<threshold; ++t) {
                    QPointF pt = b.pointAt(t * one_over_threshold_minus_1);
                    lineToArray(pt.x(), pt.y());
                }
                i += 2;
                break; }
            default:
                break;
            }
        }
    } while (0);

    if (!outline)
        addClosingLine(lastMoveTo);
    vertexArrayStops.add(vertexArray.size());
}
Ejemplo n.º 9
0
void QgsComposerHtml::render( QPainter* p, const QRectF& renderExtent )
{
  if ( !mWebPage )
  {
    return;
  }

  p->save();
  p->scale( 1.0 / mHtmlUnitsToMM, 1.0 / mHtmlUnitsToMM );
  p->translate( 0.0, -renderExtent.top() * mHtmlUnitsToMM );
  mWebPage->mainFrame()->render( p, QRegion( renderExtent.left(), renderExtent.top() * mHtmlUnitsToMM, renderExtent.width() * mHtmlUnitsToMM, renderExtent.height() * mHtmlUnitsToMM ) );
  p->restore();
}
Ejemplo n.º 10
0
void QgsComposerMapWidget::updateGuiElements()
{
  if ( mComposerMap )
  {
    blockAllSignals( true );

    //width, height, scale
    QRectF composerMapRect = mComposerMap->rect();
    mWidthLineEdit->setText( QString::number( composerMapRect.width() ) );
    mHeightLineEdit->setText( QString::number( composerMapRect.height() ) );
    mScaleLineEdit->setText( QString::number( mComposerMap->scale(), 'f', 0 ) );

    //preview mode
    QgsComposerMap::PreviewMode previewMode = mComposerMap->previewMode();
    int index = -1;
    if ( previewMode == QgsComposerMap::Cache )
    {
      index = mPreviewModeComboBox->findText( tr( "Cache" ) );
      mUpdatePreviewButton->setEnabled( true );
    }
    else if ( previewMode == QgsComposerMap::Render )
    {
      index = mPreviewModeComboBox->findText( tr( "Render" ) );
      mUpdatePreviewButton->setEnabled( true );
    }
    else if ( previewMode == QgsComposerMap::Rectangle )
    {
      index = mPreviewModeComboBox->findText( tr( "Rectangle" ) );
      mUpdatePreviewButton->setEnabled( false );
    }
    if ( index != -1 )
    {
      mPreviewModeComboBox->setCurrentIndex( index );
    }

    //composer map extent
    QgsRectangle composerMapExtent = mComposerMap->extent();
    mXMinLineEdit->setText( QString::number( composerMapExtent.xMinimum(), 'f', 3 ) );
    mXMaxLineEdit->setText( QString::number( composerMapExtent.xMaximum(), 'f', 3 ) );
    mYMinLineEdit->setText( QString::number( composerMapExtent.yMinimum(), 'f', 3 ) );
    mYMaxLineEdit->setText( QString::number( composerMapExtent.yMaximum(), 'f', 3 ) );

    mRotationSpinBox->setValue( mComposerMap->rotation() );

    //keep layer list check box
    if ( mComposerMap->keepLayerSet() )
    {
      mKeepLayerListCheckBox->setCheckState( Qt::Checked );
    }
    else
    {
      mKeepLayerListCheckBox->setCheckState( Qt::Unchecked );
    }

    //draw canvas items
    if ( mComposerMap->drawCanvasItems() )
    {
      mDrawCanvasItemsCheckBox->setCheckState( Qt::Checked );
    }
    else
    {
      mDrawCanvasItemsCheckBox->setCheckState( Qt::Unchecked );
    }

    //grid
    if ( mComposerMap->gridEnabled() )
    {
      mGridCheckBox->setChecked( true );
    }
    else
    {
      mGridCheckBox->setChecked( false );
    }

    mIntervalXSpinBox->setValue( mComposerMap->gridIntervalX() );
    mIntervalYSpinBox->setValue( mComposerMap->gridIntervalY() );
    mOffsetXSpinBox->setValue( mComposerMap->gridOffsetX() );
    mOffsetYSpinBox->setValue( mComposerMap->gridOffsetY() );

    QgsComposerMap::GridStyle gridStyle = mComposerMap->gridStyle();
    if ( gridStyle == QgsComposerMap::Cross )
    {
      mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Cross" ) ) );
    }
    else
    {
      mGridTypeComboBox->setCurrentIndex( mGridTypeComboBox->findText( tr( "Solid" ) ) );
    }

    mCrossWidthSpinBox->setValue( mComposerMap->crossLength() );

    QgsComposerMap::GridAnnotationPosition annotationPos = mComposerMap->gridAnnotationPosition();
    if ( annotationPos == QgsComposerMap::InsideMapFrame )
    {
      mAnnotationPositionComboBox->setCurrentIndex( mAnnotationPositionComboBox->findText( tr( "Inside frame" ) ) );
    }
    else
    {
      mAnnotationPositionComboBox->setCurrentIndex( mAnnotationPositionComboBox->findText( tr( "Outside frame" ) ) );
    }

    mDistanceToMapFrameSpinBox->setValue( mComposerMap->annotationFrameDistance() );

    if ( mComposerMap->showGridAnnotation() )
    {
      mDrawAnnotationCheckBox->setCheckState( Qt::Checked );
    }
    else
    {
      mDrawAnnotationCheckBox->setCheckState( Qt::Unchecked );
    }

    QgsComposerMap::GridAnnotationDirection dir = mComposerMap->gridAnnotationDirection();
    if ( dir == QgsComposerMap::Horizontal )
    {
      mAnnotationDirectionComboBox->setCurrentIndex( mAnnotationDirectionComboBox->findText( tr( "Horizontal" ) ) );
    }
    else if ( dir == QgsComposerMap::Vertical )
    {
      mAnnotationDirectionComboBox->setCurrentIndex( mAnnotationDirectionComboBox->findText( tr( "Vertical" ) ) );
    }
    else if ( dir == QgsComposerMap::HorizontalAndVertical )
    {
      mAnnotationDirectionComboBox->setCurrentIndex( mAnnotationDirectionComboBox->findText( tr( "Horizontal and Vertical" ) ) );
    }
    else //BoundaryDirection
    {
      mAnnotationDirectionComboBox->setCurrentIndex( mAnnotationDirectionComboBox->findText( tr( "Boundary direction" ) ) );
    }

    mCoordinatePrecisionSpinBox->setValue( mComposerMap->gridAnnotationPrecision() );

    QPen gridPen = mComposerMap->gridPen();
    mLineWidthSpinBox->setValue( gridPen.widthF() );
    mLineColorButton->setColor( gridPen.color() );

    blockAllSignals( false );
  }
}
Ejemplo n.º 11
0
void SourceWidget::mouseReleaseEvent(QMouseEvent *event)
{
    // Once the user releases the mouse, the selection process is finished. We need to
    // extract the selection and update the glWidget
    if (event->button() == Qt::LeftButton) {
        
        // Draw the last line
        path.lineTo(event->pos());
        path.connectPath(path);
        update();
		
		// TODO: safety due to CGAL fail
//		if (path.length()<20)
//			return;

        QPolygonF selectionPoly = path.toFillPolygon();
        QRectF boundingRect = selectionPoly.boundingRect();
		
		// Don't pass bad selections on
		if (boundingRect.width()>20 && boundingRect.height()>20)
			;
		else
			return;
		
		// adjusted - boundary value will be cut without it
        QImage sourcePatch = image.copy(boundingRect.toRect().adjusted(-1,-1,1,1)); 
        
        // Pass source patch pixels to glWidet
        glWidget->setSourcePatch(sourcePatch);
        
        qreal x0,x1,y0,y1;
        boundingRect.getCoords(&x0,&y0,&x1,&y1);
		
		
		
        // Find a point on the boundary of the selection
        QPoint cPoint(-1,-1);
        for (int x=x0; x<=x1; x++) {
            for (int y=y0; y<=y1; y++) {
                if (selectionPoly.containsPoint(QPointF(x,y),Qt::WindingFill))
                    cPoint = QPoint(x,y);
            }
        }

        //assert(cPoint != QPoint(-1,-1));
		//TODO: No violence please...
		if (cPoint == QPoint(-1,-1)){
			qDebug() << "assert(cPoint != QPoint(-1,-1)) fails";
			return;
		}
		
        // Track the boundary of the selection
        std::vector<Point> boundaryVector;
        
        // TODO: Why does it fail with dir=0 ???
        int dir = 1;
        int x,y;
        int c=0;
        bool cont = true;
        do {
            x = cPoint.x();
            y = cPoint.y();
            cPoint = findStartingFromDir(selectionPoly ,x, y, dir);
            boundaryVector.push_back(Point((cPoint.x()-x0),((y1-y0) - (cPoint.y()-y0))));

            if (boundaryVector.size()>3){
                if(boundaryVector[0]==boundaryVector[c-1] && boundaryVector[1]==boundaryVector[c]){
                    boundaryVector.pop_back();
                    boundaryVector.pop_back();
                    cont = false;
                }
            }
            c++;
        } while (cont);
		
		if (boundaryVector.size()>8192) {
			path = QPainterPath();
			update();
			QMessageBox::warning(this, tr("Boundary Size"),
							   tr("Largest supported boundary size is 8192"));
			return;
		}
		
//		// Subsample
//		std::vector<Point> boundaryVectorNew;
//		bool subs = false;
//		for(std::vector<Point>::const_iterator it = boundaryVector.begin(); it != boundaryVector.end(); ++it){
//			if(subs)
//				boundaryVectorNew.push_back(Point((*it).x(),(*it).y()));
//			subs = 1-subs;
//		}
//		boundaryVector = boundaryVectorNew;
		
//		// Subsample
//		QPolygon selectionPolyNew; 
//		int i = 0;
//		for(std::vector<Point>::const_iterator it = boundaryVector.begin(); it != boundaryVector.end(); ++it){
//			selectionPolyNew.setPoint(i, (*it).x(), (*it).y());
//			i++;
//		}	

        // TODO: Since we didn't figure out the way yet to get from CGAL the information
        // about the whenever triangle inside the boundary, glWidget will do it with
        // the help of selectionPoly
		
//		QPolygon temp(boundaryVector);
//		selectionPoly = QPolygonF(temp);
		
        selectionPoly.translate(-x0,-y0);
//        boundingRect = selectionPoly.boundingRect();
//        boundingRect.getCoords(&x0,&y0,&x1,&y1);
        glWidget->updateSelection(boundaryVector, selectionPoly);
        glWidget->update();
    }
}
void NativeImageViewObject::updateLayout(QRectF rect)
{
	NativeControlObject::updateLayout(rect);
	imageView_->setPreferredSize(rect.width(), rect.height());
}
Ejemplo n.º 13
0
bool GroundPlaneGenerator::getBoardRects(const QString & boardSvg, QGraphicsItem * board, double res, double keepoutSpace, QList<QRect> & rects)
{
	QByteArray boardByteArray;
    QString tempColor("#000000");
	QStringList exceptions;
	exceptions << "none" << "";
    if (!SvgFileSplitter::changeColors(boardSvg, tempColor, exceptions, boardByteArray)) {
		return false;
	}

	QRectF br = board->sceneBoundingRect();
	double bWidth = res * br.width() / FSvgRenderer::printerScale();
	double bHeight = res * br.height() / FSvgRenderer::printerScale();
	QImage image(bWidth, bHeight, QImage::Format_Mono);  
	image.setDotsPerMeterX(res * GraphicsUtils::InchesPerMeter);
	image.setDotsPerMeterY(res * GraphicsUtils::InchesPerMeter);
	image.fill(0xffffffff);

	QSvgRenderer renderer(boardByteArray);
	QPainter painter;
	painter.begin(&image);
	painter.setRenderHint(QPainter::Antialiasing, false);
	renderer.render(&painter);
	painter.end();

#ifndef QT_NO_DEBUG
	image.save("getBoardRects.png");
#endif

	QColor keepaway(255,255,255);

	// now add keepout area to the border
	QImage image2 = image.copy();
	painter.begin(&image2);
	painter.setRenderHint(QPainter::Antialiasing, false);
	painter.fillRect(0, 0, image2.width(), keepoutSpace, keepaway);
	painter.fillRect(0, image2.height() - keepoutSpace, image2.width(), keepoutSpace, keepaway);
	painter.fillRect(0, 0, keepoutSpace, image2.height(), keepaway);
	painter.fillRect(image2.width() - keepoutSpace, 0, keepoutSpace, image2.height(), keepaway);

	for (int y = 0; y < image.height(); y++) {
		for (int x = 0; x < image.width(); x++) {
			QRgb current = image.pixel(x, y);
			if (current != 0xffffffff) {			
				continue;
			}

			painter.fillRect(x - keepoutSpace, y - keepoutSpace, keepoutSpace + keepoutSpace, keepoutSpace + keepoutSpace, keepaway);
		}
	}
	painter.end();

#ifndef QT_NO_DEBUG
	image2.save("getBoardRects2.png");
#endif

	scanLines(image2, bWidth, bHeight, rects);

	// combine parallel equal-sized rects
	int ix = 0;
	while (ix < rects.count()) {
		QRect r = rects.at(ix++);
		for (int j = ix; j < rects.count(); j++) {
			QRect s = rects.at(j);
			if (s.bottom() == r.bottom()) {
				// on same row; keep going
				continue;
			}

			if (s.top() > r.bottom() + 1) {
				// skipped row, can't join
				break;
			}

			if (s.left() == r.left() && s.right() == r.right()) {
				// join these
				r.setBottom(s.bottom());
				rects.removeAt(j);
				ix--;
				rects.replace(ix, r);
				break;
			}
		}
	}

	return true;
}
Ejemplo n.º 14
0
QImage * GroundPlaneGenerator::generateGroundPlaneAux(const QString & boardSvg, QSizeF boardImageSize, const QString & svg, QSizeF copperImageSize, 
													QStringList & exceptions, QGraphicsItem * board, double res, double & bWidth, double & bHeight) 
{
	QByteArray boardByteArray;
    QString tempColor("#ffffff");
    if (!SvgFileSplitter::changeColors(boardSvg, tempColor, exceptions, boardByteArray)) {
		return NULL;
	}

	
	//QFile file0("testGroundFillBoard.svg");
	//file0.open(QIODevice::WriteOnly);
	//QTextStream out0(&file0);
	//out0 << boardByteArray;
	//file0.close();
	
	QByteArray copperByteArray;
	if (!SvgFileSplitter::changeStrokeWidth(svg, m_strokeWidthIncrement, false, copperByteArray)) {
		return NULL;
	}
	
	//QFile file1("testGroundFillCopper.svg");
	//file1.open(QIODevice::WriteOnly);
	//QTextStream out1(&file1);
	//out1 << copperByteArray;
	//file1.close();
	

	double svgWidth = res * qMax(boardImageSize.width(), copperImageSize.width()) / FSvgRenderer::printerScale();
	double svgHeight = res * qMax(boardImageSize.height(), copperImageSize.height()) / FSvgRenderer::printerScale();

	QRectF br =  board->sceneBoundingRect();
	bWidth = res * br.width() / FSvgRenderer::printerScale();
	bHeight = res * br.height() / FSvgRenderer::printerScale();
	QImage * image = new QImage(qMax(svgWidth, bWidth), qMax(svgHeight, bHeight), QImage::Format_Mono); //
	image->setDotsPerMeterX(res * GraphicsUtils::InchesPerMeter);
	image->setDotsPerMeterY(res * GraphicsUtils::InchesPerMeter);
	image->fill(0x0);

	QSvgRenderer renderer(boardByteArray);
	QPainter painter;
	painter.begin(image);
	painter.setRenderHint(QPainter::Antialiasing, false);
	QRectF boardBounds(0, 0, res * boardImageSize.width() / FSvgRenderer::printerScale(), res * boardImageSize.height() / FSvgRenderer::printerScale()); 
	DebugDialog::debug("boardbounds", boardBounds);
	renderer.render(&painter, boardBounds);
	painter.end();

#ifndef QT_NO_DEBUG
	image->save("testGroundFillBoard.png");
#endif

	for (double m = 0; m < BORDERINCHES; m += (1.0 / res)) {   // 1 mm
		QList<QPoint> points;
		collectBorderPoints(*image, points);

#ifndef QT_NO_DEBUG
		/*
		// for debugging
		double pixelFactor = GraphicsUtils::StandardFritzingDPI / res;
		QPolygon polygon;
		foreach(QPoint p, points) {
			polygon.append(QPoint(p.x() * pixelFactor, p.y() * pixelFactor));
		}

		QList<QPolygon> polygons;
		polygons.append(polygon);
		QPointF offset;
		this
		QString pSvg = makePolySvg(polygons, res, bWidth, bHeight, pixelFactor, "#ffffff", false,  NULL, QSizeF(0,0), 0, QPointF(0, 0));
		*/
#endif

		foreach (QPoint p, points) image->setPixel(p, 0);
	}

#ifndef QT_NO_DEBUG
	image->save("testGroundFillBoardBorder.png");
#endif
	
	// "blur" the image a little

	QSvgRenderer renderer2(copperByteArray);
	painter.begin(image);
	painter.setRenderHint(QPainter::Antialiasing, false);
	QRectF bounds(0, 0, res * copperImageSize.width() / FSvgRenderer::printerScale(), res * copperImageSize.height() / FSvgRenderer::printerScale());
	DebugDialog::debug("copperbounds", bounds);
	renderer2.render(&painter, bounds);
	if (m_blurBy != 0) {
		bounds.moveTo(m_blurBy, 0);
		renderer2.render(&painter, bounds);
		bounds.moveTo(-m_blurBy, 0);
		renderer2.render(&painter, bounds);
		bounds.moveTo(0, m_blurBy);
		renderer2.render(&painter, bounds);
		bounds.moveTo(0, -m_blurBy);
		renderer2.render(&painter, bounds);
		bounds.moveTo(m_blurBy, m_blurBy);
		renderer2.render(&painter, bounds);
		bounds.moveTo(-m_blurBy, -m_blurBy);
		renderer2.render(&painter, bounds);
		bounds.moveTo(-m_blurBy, m_blurBy);
		renderer2.render(&painter, bounds);
		bounds.moveTo(m_blurBy, -m_blurBy);
		renderer2.render(&painter, bounds);
	}
	painter.end();

#ifndef QT_NO_DEBUG
	image->save("testGroundFillCopper.png");
#endif

	emit postImageSignal(this, image, board);	

	return image;
}
Ejemplo n.º 15
0
QPointF Unit::generateNextValidPos()
{
    QPointF nextPos(0, 0);
    bool continua;
    QRectF escRect = scene()->sceneRect();
    int intentos = 0;
    do{
        if(intentos < 3){
            nextPos = pos() + generateRandomPosition(100, angRange);
            intentos++;
        }else{
            nextPos = pos() + generateRandomPosition(100, 0, 360);
        }
        continua = !((nextPos.x() > escRect.x()) && (nextPos.x() < escRect.x() + escRect.width()) && (nextPos.y() > escRect.y()) && (nextPos.y() < escRect.y() + escRect.height()));
    }while(continua);
    return nextPos;
}
Ejemplo n.º 16
0
void QgsComposerPicture::setSceneRect( const QRectF& rectangle )
{
  QSizeF currentPictureSize = pictureSize();

  if ( mResizeMode == QgsComposerPicture::Clip )
  {
    QgsComposerItem::setSceneRect( rectangle );
    mPictureWidth = rectangle.width();
    mPictureHeight = rectangle.height();
  }
  else
  {
    QRectF newRect = rectangle;

    if ( mResizeMode == ZoomResizeFrame && !rect().isEmpty() && !( currentPictureSize.isEmpty() ) )
    {
      QSizeF targetImageSize;
      if ( qgsDoubleNear( mPictureRotation, 0.0 ) )
      {
        targetImageSize = currentPictureSize;
      }
      else
      {
        //calculate aspect ratio of bounds of rotated image
        QTransform tr;
        tr.rotate( mPictureRotation );
        QRectF rotatedBounds = tr.mapRect( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ) );
        targetImageSize = QSizeF( rotatedBounds.width(), rotatedBounds.height() );
      }

      //if height has changed more than width, then fix width and set height correspondingly
      //else, do the opposite
      if ( qAbs( rect().width() - rectangle.width() ) <
           qAbs( rect().height() - rectangle.height() ) )
      {
        newRect.setHeight( targetImageSize.height() * newRect.width() / targetImageSize.width() );
      }
      else
      {
        newRect.setWidth( targetImageSize.width() * newRect.height() / targetImageSize.height() );
      }
    }
    else if ( mResizeMode == FrameToImageSize )
    {
      if ( !( currentPictureSize.isEmpty() ) )
      {
        newRect.setWidth( currentPictureSize.width() * 25.4 / mComposition->printResolution() );
        newRect.setHeight( currentPictureSize.height() * 25.4 / mComposition->printResolution() );
      }
    }

    //find largest scaling of picture with this rotation which fits in item
    if ( mResizeMode == Zoom || mResizeMode == ZoomResizeFrame )
    {
      QRectF rotatedImageRect = QgsComposerUtils::largestRotatedRectWithinBounds( QRectF( 0, 0, currentPictureSize.width(), currentPictureSize.height() ), newRect, mPictureRotation );
      mPictureWidth = rotatedImageRect.width();
      mPictureHeight = rotatedImageRect.height();
    }
    else
    {
      mPictureWidth = newRect.width();
      mPictureHeight = newRect.height();
    }

    QgsComposerItem::setSceneRect( newRect );
    emit itemChanged();
  }

  if ( mMode == SVG && !mLoadingSvg )
  {
    mLoadingSvg = true;
    refreshPicture();
    mLoadingSvg = false;
  }
}