Ejemplo n.º 1
0
bool KWidget::sizeToChild()
{
    QSizeF mins = minimumSize();
    QSizeF maxs = maximumSize();
    if(mins.isValid() && maxs.isValid())
        return false;
    return true;
}
Ejemplo n.º 2
0
static inline void qwtDrawSvgSymbols( QPainter *painter, 
    const QPointF *points, int numPoints, 
    QSvgRenderer *renderer, const QwtSymbol &symbol )
{
    if ( renderer == NULL || !renderer->isValid() )
        return;

    const QRectF viewBox = renderer->viewBoxF();
    if ( viewBox.isEmpty() )
        return;

    QSizeF sz = symbol.size();
    if ( !sz.isValid() )
        sz = viewBox.size();

    const double sx = sz.width() / viewBox.width();
    const double sy = sz.height() / viewBox.height();

    QPointF pinPoint = viewBox.center();
    if ( symbol.isPinPointEnabled() )
        pinPoint = symbol.pinPoint();

    const double dx = sx * ( pinPoint.x() - viewBox.left() );
    const double dy = sy * ( pinPoint.y() - viewBox.top() );

    for ( int i = 0; i < numPoints; i++ )
    {
        const double x = points[i].x() - dx;
        const double y = points[i].y() - dy;

        renderer->render( painter, 
            QRectF( x, y, sz.width(), sz.height() ) );
    }
}
Ejemplo n.º 3
0
/*!
  Expand the selected rectangle to minZoomSize() and zoom in
  if accepted.

  \sa accept(), minZoomSize()
*/
bool QwtPlotZoomer::end( bool ok )
{
    ok = QwtPlotPicker::end( ok );
    if ( !ok )
        return false;

    QwtPlot *plot = QwtPlotZoomer::plot();
    if ( !plot )
        return false;

    const QPolygon &pa = selection();
    if ( pa.count() < 2 )
        return false;

    QRect rect = QRect( pa[0], pa[int( pa.count() - 1 )] );
    rect = rect.normalized();

    QRectF zoomRect = invTransform( rect ).normalized();

    const QSizeF minSize = minZoomSize();
    if ( minSize.isValid() )
    {
        const QPointF center = zoomRect.center();
        zoomRect.setSize( zoomRect.size().expandedTo( minZoomSize() ) );
        zoomRect.moveCenter( center );
    }

    zoom( zoomRect );

    return true;
}
Ejemplo n.º 4
0
void QGraphicsVideoItem::setSize(const QSizeF &size)
{
    Q_D(QGraphicsVideoItem);

    d->rect.setSize(size.isValid() ? size : QSizeF(0, 0));
    d->updateRects();
}
Ejemplo n.º 5
0
bool ContentLoader::load( const QString& filename,
                          const QPointF& windowCenterPosition,
                          const QSizeF& windowSize )
{
    put_flog( LOG_INFO, "opening: '%s'", filename.toLocal8Bit().constData( ));

    ContentPtr content = ContentFactory::getContent( filename );
    if( !content )
    {
        put_flog( LOG_WARN, "ignoring unsupported file: '%s'",
                  filename.toLocal8Bit().constData( ));
        return false;
    }

    ContentWindowPtr contentWindow( new ContentWindow( content ));
    ContentWindowController controller( *contentWindow, *displayGroup_ );

    if( windowSize.isValid( ))
        controller.resize( windowSize );
    else
        controller.adjustSize( SIZE_LARGE );

    if( windowCenterPosition.isNull( ))
        controller.moveCenterTo( displayGroup_->getCoordinates().center( ));
    else
        controller.moveCenterTo( windowCenterPosition );

    displayGroup_->addContentWindow( contentWindow );

    return true;
}
Ejemplo n.º 6
0
QPixmap StylePainterMobile::findComboButton(const QSize& size, bool multiple, bool enabled) const
{
    if (size.isNull())
        return QPixmap();
    QPixmap result;
    KeyIdentifier id;
    id.type = KeyIdentifier::ComboButton;
    id.width = size.width();
    id.height = size.height();
    id.trait1 = multiple;
    id.trait2 = enabled;

    if (!findCachedControl(id, &result)) {
        result = QPixmap(size);
        const qreal border = painterScale(painter);
        const QSizeF padding(2 * border, 2 * border);
        const QSizeF innerSize = size - padding;
        ASSERT(innerSize.isValid());
        result.fill(Qt::transparent);
        QPainter cachePainter(&result);
        cachePainter.translate(border, border);
        if (multiple)
            drawMultipleComboButton(&cachePainter, innerSize, enabled ? darkColor : Qt::lightGray);
        else
            drawSimpleComboButton(&cachePainter, innerSize, enabled ? darkColor : Qt::lightGray);
        insertIntoCache(id, result);
    }
    return result;
}
Ejemplo n.º 7
0
bool PlotZoomer::end(bool ok)
{
  // Code here is taken from QwtPlotZoomer. The only modification is around the _zoomMode handling.
  ok = QwtPlotPicker::end(ok);
  if (!ok)
  {
    return false;
  }

  QwtPlot *plot = QwtPlotZoomer::plot();
  if (!plot)
  {
    return false;
  }

  const QPolygon &pa = selection();
  if (pa.count() < 2)
  {
    return false;
  }

  QRect rect = QRect(pa[0], pa[int(pa.count() - 1)]);
  rect = rect.normalized();

  QRectF currentZoomRect = zoomRect();
  QRectF zoomRect = invTransform(rect).normalized();

  switch (_zoomMode)
  {
  default:
  case ZoomBoth:
    // nothing.
    break;

  case ZoomX:
    // Maintain current zoom y and height.
    zoomRect.setY(currentZoomRect.y());
    zoomRect.setHeight(currentZoomRect.height());
    break;

  case ZoomY:
    // Maintain current zoom x and width.
    zoomRect.setX(currentZoomRect.x());
    zoomRect.setWidth(currentZoomRect.width());
    break;
  }

  const QSizeF minSize = minZoomSize();
  if (minSize.isValid())
  {
    const QPointF center = zoomRect.center();
    zoomRect.setSize(zoomRect.size().expandedTo(minZoomSize()));
    zoomRect.moveCenter(center);
  }

  zoom(zoomRect);

  return true;
}
void QgsComposerLegend::adjustBoxSize()
{
  QSizeF size = paintAndDetermineSize( 0 );
  if ( size.isValid() )
  {
    setSceneRect( QRectF( transform().dx(), transform().dy(), size.width(), size.height() ) );
  }
}
Ejemplo n.º 9
0
void PhotoView::updatePanner( const QSizeF & vpSize )
{
    QSizeF viewportSize = vpSize;

    if ( ! viewportSize.isValid() )
	viewportSize = size();

    if ( viewportSize.width()  < _panner->size().width()  * 2  ||
	 viewportSize.height() < _panner->size().height() * 2  )
    {
	// If the panner would take up more than half the available space
	// in any direction, don't show it.

	_panner->hide();
    }
    else
    {
	Photo * photo = _photoDir->current();

	if ( ! photo )
	{
	    _panner->hide();
	}
	else
	{
	    QSizeF  origSize   = photo->size();
	    QPointF canvasPos  = _canvas->pos();
	    QSizeF  canvasSize = _canvas->size();

	    qreal   pannerX    = 0.0;
	    qreal   pannerY    = -_panner->size().height();

	    if ( canvasSize.width() < viewportSize.width() )
		pannerX = canvasPos.x();

	    if ( canvasSize.height() < viewportSize.height() )
		pannerY += canvasPos.y() + canvasSize.height();
	    else
		pannerY += viewportSize.height();

	    _panner->setPos( pannerX, pannerY );

	    QPointF visiblePos( -canvasPos.x(), -canvasPos.y() );

	    QSizeF visibleSize( qMin( viewportSize.width(),
				      canvasSize.width()  ),
				qMin( viewportSize.height(),
				      canvasSize.height() ) );

	    QRectF visibleRect( visiblePos  / _zoomFactor,
				visibleSize / _zoomFactor );

	    _panner->updatePanRect( visibleRect, origSize );
	}
    }
}
Ejemplo n.º 10
0
/*!
    Returns the effective size hint for this QGraphicsLayoutItem.

    \a which is the size hint in question.
    \a constraint is an optional argument that defines a special constrain
    when calculating the effective size hint. By default, \a constraint is
    QSizeF(-1, -1), which means there is no constraint to the size hint.

    If you want to specify the widget's size hint for a given width or height,
    you can provide the fixed dimension in \a constraint. This is useful for
    widgets that can grow only either vertically or horizontally, and need to
    set either their width or their height to a special value.

    For example, a text paragraph item fit into a column width of 200 may
    grow vertically. You can pass QSizeF(200, -1) as a constraint to get a
    suitable minimum, preferred and maximum height).

    You can adjust the effective size hint by reimplementing sizeHint()
    in a QGraphicsLayoutItem subclass, or by calling one of the following
    functions: setMinimumSize(), setPreferredSize, or setMaximumSize()
    (or a combination of both).

    This function caches each of the size hints and guarantees that
    sizeHint() will be called only once for each value of \a which - unless
    \a constraint is not specified and updateGeometry() has been called.

    \sa sizeHint()
*/
QSizeF QGraphicsLayoutItem::effectiveSizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
    Q_D(const QGraphicsLayoutItem);

    if (!d->userSizeHints && constraint.isValid())
        return constraint;

    // ### should respect size policy???
    return d_ptr->effectiveSizeHints(constraint)[which];
}
QSizeF ContentWindowController::getMaxContentSize() const
{
    QSizeF maxContentSize = _contentWindow->getContent()->getMaxDimensions();
    if( maxContentSize.isValid( ))
        return maxContentSize;

    maxContentSize = _contentWindow->getContent()->getDimensions();
    return maxContentSize.scaled( _displayGroup->getCoordinates().size(),
                                  Qt::KeepAspectRatioByExpanding );
}
Ejemplo n.º 12
0
void QgsComposerLegend::adjustBoxSize()
{
  QgsLegendRenderer legendRenderer( &mLegendModel, mSettings );
  QSizeF size = legendRenderer.minimumSize();
  QgsDebugMsg( QString( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
  if ( size.isValid() )
  {
    setSceneRect( QRectF( pos().x(), pos().y(), size.width(), size.height() ) );
  }
}
Ejemplo n.º 13
0
void Tagaro::SpriteObjectItem::setSize(const QSizeF& size)
{
	if (d->m_size != size && size.isValid())
	{
		prepareGeometryChange();
		d->m_size = size;
		d->updateTransform();
		emit sizeChanged(size);
		update();
	}
}
Ejemplo n.º 14
0
void MediaPlayerPrivateQt::nativeSizeChanged(const QSizeF& size)
{
    LOG(Media, "MediaPlayerPrivateQt::naturalSizeChanged(%dx%d)",
            size.toSize().width(), size.toSize().height());

    if (!size.isValid())
        return;

    m_naturalSize = size.toSize();
    m_webCorePlayer->sizeChanged();
}
Ejemplo n.º 15
0
void QgsDiagramRendererV2::convertSizeToMapUnits( QSizeF& size, const QgsRenderContext& context ) const
{
  if ( !size.isValid() )
  {
    return;
  }

  double pixelToMap = context.scaleFactor() * context.mapToPixel().mapUnitsPerPixel();
  size.rwidth() *= pixelToMap;
  size.rheight() *= pixelToMap;
}
Ejemplo n.º 16
0
void QgsComposerLegend::adjustBoxSize()
{
  QgsLegendRenderer legendRenderer( mLegendModel2, mSettings );
  QSizeF size = legendRenderer.minimumSize();
  QgsDebugMsg( QString( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
  if ( size.isValid() )
  {
    QRectF targetRect = QRectF( pos().x(), pos().y(), size.width(), size.height() );
    //set new rect, respecting position mode and data defined size/position
    setSceneRect( evalItemRect( targetRect, true ) );
  }
}
Ejemplo n.º 17
0
QSizeF QgsDiagramRenderer::sizeMapUnits( const QgsFeature& feature, const QgsRenderContext& c ) const
{
  QgsDiagramSettings s;
  if ( !diagramSettings( feature, c, s ) )
  {
    return QSizeF();
  }

  QSizeF size = diagramSize( feature, c );
  if ( size.isValid() )
  {
    double width = QgsSymbolLayerUtils::convertToMapUnits( c, size.width(), s.sizeType, s.sizeScale );
    size.rheight() *= width / size.width();
    size.setWidth( width );
  }
  return size;
}
Ejemplo n.º 18
0
void QgsDiagramRendererV2::convertSizeToMapUnits( QSizeF& size, const QgsRenderContext& context ) const
{
    if ( !size.isValid() )
    {
        return;
    }

    int dpi = dpiPaintDevice( context.constPainter() );
    if ( dpi < 0 )
    {
        return;
    }

    double pixelToMap = dpi / 25.4 * context.mapToPixel().mapUnitsPerPixel();
    size.rwidth() *= pixelToMap;
    size.rheight() *= pixelToMap;
}
Ejemplo n.º 19
0
QTextImageFormat EpsRenderer::render(QTextDocument *document, const QUrl &url)
{
    QTextImageFormat epsCharFormat;

    QSizeF s = renderToResource(document, url);

    QUrl internal = url;
    internal.setScheme(QLatin1String("internal"));
    if(s.isValid())
    {
        epsCharFormat.setName(internal.url());
        epsCharFormat.setWidth(s.width());
        epsCharFormat.setHeight(s.height());
    }

    return epsCharFormat;
}
Ejemplo n.º 20
0
static QSizeF qt_convertUnits(const QSizeF &size, QPageSize::Unit fromUnits, QPageSize::Unit toUnits)
{
    if (!size.isValid())
        return QSizeF();

    // If the units are the same or the size is 0, then don't need to convert
    if (fromUnits == toUnits || (qFuzzyIsNull(size.width()) && qFuzzyIsNull(size.height())))
        return size;

    QSizeF newSize = size;
    // First convert to points
    if (fromUnits != QPageSize::Point) {
        const qreal multiplier = qt_pointMultiplier(fromUnits);
        newSize = newSize * multiplier;
    }
    // Then convert from points to required units
    const qreal multiplier = qt_pointMultiplier(toUnits);
    // Try force to 2 decimal places for consistency
    const int width = qRound(newSize.width() * 100 / multiplier);
    const int height = qRound(newSize.height() * 100 / multiplier);
    return QSizeF(width / 100.0, height / 100.0);
}
Ejemplo n.º 21
0
static int slot_QSizeF___bool__(PyObject *sipSelf)
{
    QSizeF *sipCpp = reinterpret_cast<QSizeF *>(sipGetCppPtr((sipSimpleWrapper *)sipSelf,sipType_QSizeF));

    if (!sipCpp)
        return -1;


    {
        {
            int sipRes = 0;

#line 152 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\sip/QtCore/qsize.sip"
        sipRes = sipCpp->isValid();
#line 819 "C:\\Users\\marcus\\Downloads\\PyQt-gpl-5.4\\PyQt-gpl-5.4\\QtCore/sipQtCoreQSizeF.cpp"

            return sipRes;
        }
    }

    return 0;
}
Ejemplo n.º 22
0
/*!
  Rejects selections, when the stack depth is too deep, or
  the zoomed rectangle is minZoomSize().

  \sa minZoomSize(), maxStackDepth()
*/
void QwtPlotZoomer::begin()
{
    if ( d_data->maxStackDepth >= 0 )
    {
        if ( d_data->zoomRectIndex >= uint( d_data->maxStackDepth ) )
            return;
    }

    const QSizeF minSize = minZoomSize();
    if ( minSize.isValid() )
    {
        const QSizeF sz =
            d_data->zoomStack[d_data->zoomRectIndex].size() * 0.9999;

        if ( minSize.width() >= sz.width() &&
            minSize.height() >= sz.height() )
        {
            return;
        }
    }

    QwtPlotPicker::begin();
}
Ejemplo n.º 23
0
void QgsLayoutItemLegend::adjustBoxSize()
{
  if ( !mSizeToContents )
    return;

  if ( !mInitialMapScaleCalculated )
  {
    // this is messy - but until we have painted the item we have no knowledge of the current DPI
    // and so cannot correctly calculate the map scale. This results in incorrect size calculations
    // for marker symbols with size in map units, causing the legends to initially expand to huge
    // sizes if we attempt to calculate the box size first.
    return;
  }

  QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
  QSizeF size = legendRenderer.minimumSize();
  QgsDebugMsg( QStringLiteral( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
  if ( size.isValid() )
  {
    QgsLayoutSize newSize = mLayout->convertFromLayoutUnits( size, sizeWithUnits().units() );
    //set new rect, respecting position mode and data defined size/position
    attemptResize( newSize );
  }
}
Ejemplo n.º 24
0
void QgsComposerLegend::adjustBoxSize()
{
  if ( !mSizeToContents )
    return;

  if ( !mInitialMapScaleCalculated )
  {
    // this is messy - but until we have painted the item we have no knowledge of the current DPI
    // and so cannot correctly calculate the map scale. This results in incorrect size calculations
    // for marker symbols with size in map units, causing the legends to initially expand to huge
    // sizes if we attempt to calculate the box size first.
    return;
  }

  QgsLegendRenderer legendRenderer( mLegendModel.get(), mSettings );
  QSizeF size = legendRenderer.minimumSize();
  QgsDebugMsg( QString( "width = %1 height = %2" ).arg( size.width() ).arg( size.height() ) );
  if ( size.isValid() )
  {
    QRectF targetRect = QRectF( pos().x(), pos().y(), size.width(), size.height() );
    //set new rect, respecting position mode and data defined size/position
    setSceneRect( evalItemRect( targetRect, true ) );
  }
}
Ejemplo n.º 25
0
QVariant KConfigGroup::convertToQVariant(const char *pKey, const QByteArray& value, const QVariant& aDefault)
{
    // if a type handler is added here you must add a QVConversions definition
    // to conversion_check.h, or ConversionCheck::to_QVariant will not allow
    // readEntry<T> to convert to QVariant.
    switch( aDefault.type() ) {
        case QVariant::Invalid:
            return QVariant();
        case QVariant::String:
            // this should return the raw string not the dollar expanded string.
            // imho if processed string is wanted should call
            // readEntry(key, QString) not readEntry(key, QVariant)
            return QString::fromUtf8(value);
        case QVariant::List:
        case QVariant::StringList:
            return KConfigGroupPrivate::deserializeList(QString::fromUtf8(value));
        case QVariant::ByteArray:
            return value;
        case QVariant::Bool: {
            const QByteArray lower(value.toLower());
            if (lower == "false" || lower == "no" || lower == "off" || lower == "0")
                return false;
            return true;
        }
        case QVariant::Double:
        case QMetaType::Float:
        case QVariant::Int:
        case QVariant::UInt:
        case QVariant::LongLong:
        case QVariant::ULongLong: {
            QVariant tmp = value;
            if ( !tmp.convert(aDefault.type()) )
                tmp = aDefault;
            return tmp;
        }
        case QVariant::Point: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            return QPoint(list.at( 0 ), list.at( 1 ));
        }
        case QVariant::PointF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            return QPointF(list.at( 0 ), list.at( 1 ));
        }
        case QVariant::Rect: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 4 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 4, list.count() );
                return aDefault;
            }
            const QRect rect(list.at( 0 ), list.at( 1 ), list.at( 2 ), list.at( 3 ));
            if ( !rect.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return rect;
        }
        case QVariant::RectF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 4 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 4, list.count() );
                return aDefault;
            }
            const QRectF rect(list.at( 0 ), list.at( 1 ), list.at( 2 ), list.at( 3 ));
            if ( !rect.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return rect;
        }
        case QVariant::Size: {
            const QList<int> list = asIntList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            const QSize size(list.at( 0 ), list.at( 1 ));
            if ( !size.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return size;
        }
        case QVariant::SizeF: {
            const QList<qreal> list = asRealList(value);

            if ( list.count() != 2 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 2, list.count() );
                return aDefault;
            }
            const QSizeF size(list.at( 0 ), list.at( 1 ));
            if ( !size.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return size;
        }
        case QVariant::DateTime: {
            const QList<int> list = asIntList(value);
            if ( list.count() != 6 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 6, list.count() );
                return aDefault;
            }
            const QDate date( list.at( 0 ), list.at( 1 ), list.at( 2 ) );
            const QTime time( list.at( 3 ), list.at( 4 ), list.at( 5 ) );
            const QDateTime dt( date, time );
            if ( !dt.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return dt;
        }
        case QVariant::Date: {
            QList<int> list = asIntList(value);
            if ( list.count() == 6 )
                list = list.mid(0, 3); // don't break config files that stored QDate as QDateTime
            if ( list.count() != 3 ) {
                qWarning() << errString( pKey, value, aDefault )
                         << formatError( 3, list.count() );
                return aDefault;
            }
            const QDate date( list.at( 0 ), list.at( 1 ), list.at( 2 ) );
            if ( !date.isValid() ) {
                qWarning() << errString( pKey, value, aDefault );
                return aDefault;
            }
            return date;
        }
        case QVariant::Color:
        case QVariant::Font:
            qWarning() << "KConfigGroup::readEntry was passed GUI type '"
                    << aDefault.typeName()
                    << "' but kdeui isn't linked! If it is linked to your program, "
                    "this is a platform bug. Please inform the KDE developers";
            break;
        case QVariant::Url:
            return QUrl(QString::fromUtf8(value));

        default:
            break;
    }

    qWarning() << "unhandled type " << aDefault.typeName();
    return QVariant();
}
Ejemplo n.º 26
0
void CanvasSize::setSize(const QSizeF & size)
{
    if (!size.isValid())
        return;
    m_size = size;
}
Ejemplo n.º 27
0
void CanvasSize::setResolution(const QSizeF & resolution)
{
    if (!resolution.isValid())
        return;
    m_resolution = resolution;
}
Ejemplo n.º 28
0
QgsLabelFeature *QgsVectorLayerDiagramProvider::registerDiagram( QgsFeature &feat, QgsRenderContext &context, const QgsGeometry &obstacleGeometry )
{
  const QgsMapSettings &mapSettings = mEngine->mapSettings();

  const QgsDiagramRenderer *dr = mSettings.renderer();
  if ( dr )
  {
    QList<QgsDiagramSettings> settingList = dr->diagramSettings();
    if ( !settingList.isEmpty() && settingList.at( 0 ).scaleBasedVisibility )
    {
      double maxScale = settingList.at( 0 ).maximumScale;
      if ( maxScale > 0 && context.rendererScale() < maxScale )
      {
        return nullptr;
      }

      double minScale = settingList.at( 0 ).minimumScale;
      if ( minScale > 0 && context.rendererScale() > minScale )
      {
        return nullptr;
      }
    }
  }

  // data defined show diagram? check this before doing any other processing
  if ( !mSettings.dataDefinedProperties().valueAsBool( QgsDiagramLayerSettings::Show, context.expressionContext(), true ) )
    return nullptr;

  // data defined obstacle?
  bool isObstacle = mSettings.dataDefinedProperties().valueAsBool( QgsDiagramLayerSettings::IsObstacle, context.expressionContext(), mSettings.isObstacle() );

  //convert geom to geos
  QgsGeometry geom = feat.geometry();
  QgsGeometry extentGeom = QgsGeometry::fromRect( mapSettings.visibleExtent() );
  if ( !qgsDoubleNear( mapSettings.rotation(), 0.0 ) )
  {
    //PAL features are prerotated, so extent also needs to be unrotated
    extentGeom.rotate( -mapSettings.rotation(), mapSettings.visibleExtent().center() );
  }

  geos::unique_ptr geomCopy;
  std::unique_ptr<QgsGeometry> scopedPreparedGeom;
  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, mSettings.coordinateTransform(), extentGeom ) )
  {
    scopedPreparedGeom.reset( new QgsGeometry( QgsPalLabeling::prepareGeometry( geom, context, mSettings.coordinateTransform(), extentGeom ) ) );
    QgsGeometry *preparedGeom = scopedPreparedGeom.get();
    if ( preparedGeom->isNull() )
      return nullptr;
    geomCopy = QgsGeos::asGeos( *preparedGeom );
  }
  else
  {
    geomCopy = QgsGeos::asGeos( geom );
  }

  if ( !geomCopy )
    return nullptr; // invalid geometry

  geos::unique_ptr geosObstacleGeomClone;
  std::unique_ptr<QgsGeometry> scopedObstacleGeom;
  if ( isObstacle && obstacleGeometry && QgsPalLabeling::geometryRequiresPreparation( obstacleGeometry, context, mSettings.coordinateTransform(), extentGeom ) )
  {
    QgsGeometry preparedObstacleGeom = QgsPalLabeling::prepareGeometry( obstacleGeometry, context, mSettings.coordinateTransform(), extentGeom );
    geosObstacleGeomClone = QgsGeos::asGeos( preparedObstacleGeom );
  }
  else if ( mSettings.isObstacle() && !obstacleGeometry.isNull() )
  {
    geosObstacleGeomClone = QgsGeos::asGeos( obstacleGeometry );
  }

  double diagramWidth = 0;
  double diagramHeight = 0;
  if ( dr )
  {
    QSizeF diagSize = dr->sizeMapUnits( feat, context );
    if ( diagSize.isValid() )
    {
      diagramWidth = diagSize.width();
      diagramHeight = diagSize.height();
    }
  }

  //  feature to the layer
  bool alwaysShow = mSettings.showAllDiagrams();
  context.expressionContext().setOriginalValueVariable( alwaysShow );
  alwaysShow = mSettings.dataDefinedProperties().valueAsBool( QgsDiagramLayerSettings::AlwaysShow, context.expressionContext(), alwaysShow );

  // new style data defined position
  bool ddPos = false;
  double ddPosX = 0.0;
  double ddPosY = 0.0;
  if ( mSettings.dataDefinedProperties().hasProperty( QgsDiagramLayerSettings::PositionX )
       && mSettings.dataDefinedProperties().property( QgsDiagramLayerSettings::PositionX ).isActive()
       && mSettings.dataDefinedProperties().hasProperty( QgsDiagramLayerSettings::PositionY )
       && mSettings.dataDefinedProperties().property( QgsDiagramLayerSettings::PositionY ).isActive() )
  {
    ddPosX = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::PositionX, context.expressionContext(), std::numeric_limits<double>::quiet_NaN() );
    ddPosY = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::PositionY, context.expressionContext(), std::numeric_limits<double>::quiet_NaN() );

    ddPos = !std::isnan( ddPosX ) && !std::isnan( ddPosY );

    if ( ddPos )
    {
      QgsCoordinateTransform ct = mSettings.coordinateTransform();
      if ( ct.isValid() && !ct.isShortCircuited() )
      {
        double z = 0;
        ct.transformInPlace( ddPosX, ddPosY, z );
      }
      //data defined diagram position is always centered
      ddPosX -= diagramWidth / 2.0;
      ddPosY -= diagramHeight / 2.0;
    }
  }

  QgsDiagramLabelFeature *lf = new QgsDiagramLabelFeature( feat.id(), std::move( geomCopy ), QSizeF( diagramWidth, diagramHeight ) );
  lf->setHasFixedPosition( ddPos );
  lf->setFixedPosition( QgsPointXY( ddPosX, ddPosY ) );
  lf->setHasFixedAngle( true );
  lf->setFixedAngle( 0 );
  lf->setAlwaysShow( alwaysShow );
  lf->setIsObstacle( isObstacle );
  if ( geosObstacleGeomClone )
  {
    lf->setObstacleGeometry( std::move( geosObstacleGeomClone ) );
  }

  if ( dr )
  {
    //append the diagram attributes to lbl
    lf->setAttributes( feat.attributes() );
  }

  // data defined priority?
  if ( mSettings.dataDefinedProperties().hasProperty( QgsDiagramLayerSettings::Priority )
       && mSettings.dataDefinedProperties().property( QgsDiagramLayerSettings::Priority ).isActive() )
  {
    context.expressionContext().setOriginalValueVariable( mSettings.priority() );
    double priorityD = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::Priority, context.expressionContext(), mSettings.priority() );
    priorityD = qBound( 0.0, priorityD, 10.0 );
    priorityD = 1 - priorityD / 10.0; // convert 0..10 --> 1..0
    lf->setPriority( priorityD );
  }

  // z-Index
  double zIndex = mSettings.zIndex();
  if ( mSettings.dataDefinedProperties().hasProperty( QgsDiagramLayerSettings::ZIndex )
       && mSettings.dataDefinedProperties().property( QgsDiagramLayerSettings::ZIndex ).isActive() )
  {
    context.expressionContext().setOriginalValueVariable( zIndex );
    zIndex = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::ZIndex, context.expressionContext(), zIndex );
  }
  lf->setZIndex( zIndex );

  // label distance
  QgsPointXY ptZero = mapSettings.mapToPixel().toMapCoordinates( 0, 0 );
  QgsPointXY ptOne = mapSettings.mapToPixel().toMapCoordinates( 1, 0 );
  double dist = mSettings.distance();

  if ( mSettings.dataDefinedProperties().hasProperty( QgsDiagramLayerSettings::Distance )
       && mSettings.dataDefinedProperties().property( QgsDiagramLayerSettings::Distance ).isActive() )
  {
    context.expressionContext().setOriginalValueVariable( dist );
    dist = mSettings.dataDefinedProperties().valueAsDouble( QgsDiagramLayerSettings::Distance, context.expressionContext(), dist );
  }

  dist *= ptOne.distance( ptZero );

  lf->setDistLabel( dist );
  return lf;
}
Ejemplo n.º 29
0
bool QgsAlignRaster::setParametersFromRaster( const RasterInfo& rasterInfo, const QString& customCRSWkt, QSizeF customCellSize, QPointF customGridOffset )
{
  if ( customCRSWkt.isEmpty() || customCRSWkt == rasterInfo.crs() )
  {
    // use ref. layer to init input
    mCrsWkt = rasterInfo.crs();

    if ( !customCellSize.isValid() )
    {
      mCellSizeX = rasterInfo.cellSize().width();
      mCellSizeY = rasterInfo.cellSize().height();
    }
    else
    {
      mCellSizeX = customCellSize.width();
      mCellSizeY = customCellSize.height();
    }

    if ( customGridOffset.x() < 0 || customGridOffset.y() < 0 )
    {
      if ( !customCellSize.isValid() )
      {
        // using original raster's grid offset to be aligned with origin
        mGridOffsetX = rasterInfo.gridOffset().x();
        mGridOffsetY = rasterInfo.gridOffset().y();
      }
      else
      {
        // if using custom cell size: offset so that we are aligned
        // with the original raster's origin point
        mGridOffsetX = fmod_with_tolerance( rasterInfo.origin().x(), customCellSize.width() );
        mGridOffsetY = fmod_with_tolerance( rasterInfo.origin().y(), customCellSize.height() );
      }
    }
    else
    {
      mGridOffsetX = customGridOffset.x();
      mGridOffsetY = customGridOffset.x();
    }
  }
  else
  {
    QSizeF cs;
    QPointF go;
    if ( !suggestedWarpOutput( rasterInfo, customCRSWkt, &cs, &go ) )
    {
      mCrsWkt = "_error_";
      mCellSizeX = mCellSizeY = 0;
      mGridOffsetX = mGridOffsetY = 0;
      return false;
    }

    mCrsWkt = customCRSWkt;

    if ( !customCellSize.isValid() )
    {
      mCellSizeX = cs.width();
      mCellSizeY = cs.height();
    }
    else
    {
      mCellSizeX = customCellSize.width();
      mCellSizeY = customCellSize.height();
    }

    if ( customGridOffset.x() < 0 || customGridOffset.y() < 0 )
    {
      mGridOffsetX = go.x();
      mGridOffsetY = go.y();
    }
    else
    {
      mGridOffsetX = customGridOffset.x();
      mGridOffsetY = customGridOffset.x();
    }
  }
  return true;
}
QgsLabelFeature* QgsVectorLayerDiagramProvider::registerDiagram( QgsFeature& feat, QgsRenderContext &context, QgsGeometry* obstacleGeometry )
{
  const QgsMapSettings& mapSettings = mEngine->mapSettings();

  const QgsDiagramRenderer* dr = mSettings.getRenderer();
  if ( dr )
  {
    QList<QgsDiagramSettings> settingList = dr->diagramSettings();
    if ( !settingList.isEmpty() && settingList.at( 0 ).scaleBasedVisibility )
    {
      double minScale = settingList.at( 0 ).minScaleDenominator;
      if ( minScale > 0 && context.rendererScale() < minScale )
      {
        return nullptr;
      }

      double maxScale = settingList.at( 0 ).maxScaleDenominator;
      if ( maxScale > 0 && context.rendererScale() > maxScale )
      {
        return nullptr;
      }
    }
  }

  //convert geom to geos
  QgsGeometry geom = feat.geometry();
  QgsGeometry extentGeom = QgsGeometry::fromRect( mapSettings.visibleExtent() );
  if ( !qgsDoubleNear( mapSettings.rotation(), 0.0 ) )
  {
    //PAL features are prerotated, so extent also needs to be unrotated
    extentGeom.rotate( -mapSettings.rotation(), mapSettings.visibleExtent().center() );
  }

  const GEOSGeometry* geos_geom = nullptr;
  QScopedPointer<QgsGeometry> scopedPreparedGeom;
  if ( QgsPalLabeling::geometryRequiresPreparation( geom, context, mSettings.coordinateTransform(), &extentGeom ) )
  {
    scopedPreparedGeom.reset( new QgsGeometry( QgsPalLabeling::prepareGeometry( geom, context, mSettings.coordinateTransform(), &extentGeom ) ) );
    QgsGeometry* preparedGeom = scopedPreparedGeom.data();
    if ( preparedGeom->isEmpty() )
      return nullptr;
    geos_geom = preparedGeom->asGeos();
  }
  else
  {
    geos_geom = geom.asGeos();
  }

  if ( !geos_geom )
    return nullptr; // invalid geometry

  GEOSGeometry* geomCopy = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geos_geom );

  const GEOSGeometry* geosObstacleGeom = nullptr;
  QScopedPointer<QgsGeometry> scopedObstacleGeom;
  if ( mSettings.isObstacle() && obstacleGeometry && QgsPalLabeling::geometryRequiresPreparation( *obstacleGeometry, context, mSettings.coordinateTransform(), &extentGeom ) )
  {
    QgsGeometry preparedObstacleGeom = QgsPalLabeling::prepareGeometry( *obstacleGeometry, context, mSettings.coordinateTransform(), &extentGeom );
    geosObstacleGeom = preparedObstacleGeom.asGeos();
  }
  else if ( mSettings.isObstacle() && obstacleGeometry )
  {
    geosObstacleGeom = obstacleGeometry->asGeos();
  }
  GEOSGeometry* geosObstacleGeomClone = nullptr;
  if ( geosObstacleGeom )
  {
    geosObstacleGeomClone = GEOSGeom_clone_r( QgsGeometry::getGEOSHandler(), geosObstacleGeom );
  }


  double diagramWidth = 0;
  double diagramHeight = 0;
  if ( dr )
  {
    QSizeF diagSize = dr->sizeMapUnits( feat, context );
    if ( diagSize.isValid() )
    {
      diagramWidth = diagSize.width();
      diagramHeight = diagSize.height();
    }
  }

  //  feature to the layer
  bool alwaysShow = mSettings.showAllDiagrams();
  int ddColX = mSettings.xPosColumn;
  int ddColY = mSettings.yPosColumn;
  double ddPosX = 0.0;
  double ddPosY = 0.0;
  bool ddPos = ( ddColX >= 0 && ddColY >= 0 );
  if ( ddPos && ! feat.attribute( ddColX ).isNull() && ! feat.attribute( ddColY ).isNull() )
  {
    bool posXOk, posYOk;
    ddPosX = feat.attribute( ddColX ).toDouble( &posXOk );
    ddPosY = feat.attribute( ddColY ).toDouble( &posYOk );
    if ( !posXOk || !posYOk )
    {
      ddPos = false;
    }
    else
    {
      QgsCoordinateTransform ct = mSettings.coordinateTransform();
      if ( ct.isValid() && !ct.isShortCircuited() )
      {
        double z = 0;
        ct.transformInPlace( ddPosX, ddPosY, z );
      }
      //data defined diagram position is always centered
      ddPosX -= diagramWidth / 2.0;
      ddPosY -= diagramHeight / 2.0;
    }
  }
  else
    ddPos = false;

  int ddColShow = mSettings.showColumn;
  if ( ddColShow >= 0 && ! feat.attribute( ddColShow ).isNull() )
  {
    bool showOk;
    bool ddShow = feat.attribute( ddColShow ).toDouble( &showOk );

    if ( showOk && ! ddShow )
      return nullptr;
  }

  QgsDiagramLabelFeature* lf = new QgsDiagramLabelFeature( feat.id(), geomCopy, QSizeF( diagramWidth, diagramHeight ) );
  lf->setHasFixedPosition( ddPos );
  lf->setFixedPosition( QgsPoint( ddPosX, ddPosY ) );
  lf->setHasFixedAngle( true );
  lf->setFixedAngle( 0 );
  lf->setAlwaysShow( alwaysShow );
  lf->setIsObstacle( mSettings.isObstacle() );
  lf->setZIndex( mSettings.getZIndex() );
  if ( geosObstacleGeomClone )
  {
    lf->setObstacleGeometry( geosObstacleGeomClone );
  }

  if ( dr )
  {
    //append the diagram attributes to lbl
    lf->setAttributes( feat.attributes() );
  }

  QgsPoint ptZero = mapSettings.mapToPixel().toMapCoordinates( 0, 0 );
  QgsPoint ptOne = mapSettings.mapToPixel().toMapCoordinates( 1, 0 );
  lf->setDistLabel( ptOne.distance( ptZero ) * mSettings.distance() );
  return lf;
}