void ZoneViewWidget::resizeToZoneContents()
{
    QRectF zoneRect = zone->getOptimumRect();
    qreal totalZoneHeight = zoneRect.height();
    if (zoneRect.height() > 500)
        zoneRect.setHeight(500);
    QSizeF newSize(qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), zoneRect.width() + scrollBar->width() + 10), zoneRect.height() + extraHeight + 10);
    setMaximumSize(newSize);
    resize(newSize);
    
    zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight));
    scrollBar->setMaximum(totalZoneHeight - zoneRect.height());
    
    if (layout())
        layout()->invalidate();
}
void QtGradientWidget::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)

    QPainter p(this);

    if (d_ptr->m_backgroundCheckered) {
        int pixSize = 40;
        QPixmap pm(2 * pixSize, 2 * pixSize);

        QPainter pmp(&pm);
        pmp.fillRect(0, 0, pixSize, pixSize, Qt::white);
        pmp.fillRect(pixSize, pixSize, pixSize, pixSize, Qt::white);
        pmp.fillRect(0, pixSize, pixSize, pixSize, Qt::black);
        pmp.fillRect(pixSize, 0, pixSize, pixSize, Qt::black);

        p.setBrushOrigin((size().width() % pixSize + pixSize) / 2, (size().height() % pixSize + pixSize) / 2);
        p.fillRect(rect(), pm);
        p.setBrushOrigin(0, 0);
    }

    QGradient *gradient = 0;
    switch (d_ptr->m_gradientType) {
        case QGradient::LinearGradient:
            gradient = new QLinearGradient(d_ptr->m_startLinear, d_ptr->m_endLinear);
            break;
        case QGradient::RadialGradient:
            gradient = new QRadialGradient(d_ptr->m_centralRadial, d_ptr->m_radiusRadial, d_ptr->m_focalRadial);
            break;
        case QGradient::ConicalGradient:
            gradient = new QConicalGradient(d_ptr->m_centralConical, d_ptr->m_angleConical);
            break;
        default:
            break;
    }
    if (!gradient)
        return;

    gradient->setStops(d_ptr->m_gradientStops);
    gradient->setSpread(d_ptr->m_gradientSpread);

    p.save();
    p.scale(size().width(), size().height());
    p.fillRect(QRect(0, 0, 1, 1), *gradient);
    p.restore();

    p.setRenderHint(QPainter::Antialiasing);

    QColor c = QColor::fromRgbF(0.5, 0.5, 0.5, 0.5);
    QBrush br(c);
    p.setBrush(br);
    QPen pen(Qt::white);
    pen.setWidthF(1);
    p.setPen(pen);
    QPen dragPen = pen;
    dragPen.setWidthF(2);
    if (d_ptr->m_gradientType == QGradient::LinearGradient) {
        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::StartLinearHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_startLinear, d_ptr->m_handleSize);
        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::EndLinearHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_endLinear, d_ptr->m_handleSize);
        p.restore();
    } else if (d_ptr->m_gradientType == QGradient::RadialGradient) {
        QPointF central = d_ptr->toViewport(d_ptr->m_centralRadial);

        p.save();
        QRectF r = d_ptr->pointRect(central, 2 * d_ptr->m_handleSize / 3);
        QRectF r1(0, r.y(), size().width(), r.height());
        QRectF r2(r.x(), 0, r.width(), r.y());
        QRectF r3(r.x(), r.y() + r.height(), r.width(), size().height() - r.y() - r.height());
        p.fillRect(r1, c);
        p.fillRect(r2, c);
        p.fillRect(r3, c);
        p.setBrush(Qt::NoBrush);
        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralRadialHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_centralRadial, d_ptr->m_handleSize);
        p.restore();

        const QRectF rect = QRectF(central.x() - d_ptr->m_radiusRadial * size().width(),
                        central.y() - d_ptr->m_radiusRadial * size().height(),
                        2 * d_ptr->m_radiusRadial * size().width(),
                        2 * d_ptr->m_radiusRadial * size().height());
        QRegion region(r1.toRect());
        region += r2.toRect();
        region += r3.toRect();
        p.setClipRegion(region);

        p.drawEllipse(rect);
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::RadiusRadialHandle) {
            p.save();
            p.setPen(dragPen);
            QRectF rect = QRectF(central.x() - d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().width(),
                    central.y() - d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().height(),
                    2 * d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().width(),
                    2 * d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().height());
            p.drawEllipse(rect);

            p.restore();
        }
        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::FocalRadialHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_focalRadial, 2 * d_ptr->m_handleSize / 3);
        p.restore();
    } else if (d_ptr->m_gradientType == QGradient::ConicalGradient) {
        double radius = size().width();
        if (size().height() < radius)
            radius = size().height();
        radius /= 2;
        double corr = d_ptr->m_handleSize / 3;
        radius -= corr;
        QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);

        p.save();
        p.setBrush(Qt::NoBrush);
        QPen pen2(c);
        pen2.setWidthF(2 * d_ptr->m_handleSize / 3);
        p.setPen(pen2);
        p.drawEllipse(d_ptr->pointRect(central, 2 * radius));
        p.restore();

        p.save();
        p.setBrush(Qt::NoBrush);
        int pointCount = 2;
        for (int i = 0; i < pointCount; i++) {
            QPointF ang(cos(M_PI * (i * 180.0 / pointCount + d_ptr->m_angleConical) / 180) * size().width() / 2,
                    -sin(M_PI * (i * 180.0 / pointCount + d_ptr->m_angleConical) / 180) * size().height() / 2);
            double mod = sqrt(ang.x() * ang.x() + ang.y() * ang.y());
            p.drawLine(QPointF(central.x() + ang.x() * (radius - corr) / mod,
                        central.y() + ang.y() * (radius - corr) / mod),
                    QPointF(central.x() + ang.x() * (radius + corr) / mod,
                        central.y() + ang.y() * (radius + corr) / mod));
            p.drawLine(QPointF(central.x() - ang.x() * (radius - corr) / mod,
                        central.y() - ang.y() * (radius - corr) / mod),
                    QPointF(central.x() - ang.x() * (radius + corr) / mod,
                        central.y() - ang.y() * (radius + corr) / mod));
        }
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::AngleConicalHandle) {
            p.save();
            p.setPen(dragPen);
            QPointF ang(cos(M_PI * (d_ptr->m_angleConical - d_ptr->m_angleOffset) / 180) * size().width() / 2,
                    -sin(M_PI * (d_ptr->m_angleConical - d_ptr->m_angleOffset) / 180) * size().height() / 2);
            double mod = sqrt(ang.x() * ang.x() + ang.y() * ang.y());
            p.drawLine(QPointF(central.x() + ang.x() * (radius - corr) / mod,
                        central.y() + ang.y() * (radius - corr) / mod),
                    QPointF(central.x() + ang.x() * (radius + corr) / mod,
                        central.y() + ang.y() * (radius + corr) / mod));
            p.restore();
        }

        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralConicalHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_centralConical, d_ptr->m_handleSize);
        p.restore();

    }

    delete gradient;
}
void TopologyNode::paint(QPainter *painter,
                         const QStyleOptionGraphicsItem *option,
                         QWidget *widget)
{
    Q_UNUSED(widget)

    QRectF itemRect = boundingRect();

#ifdef POWERLINE_REVISION
    if(m_name == QString("POWERLINE"))
    {
        QString imagePath;
        if(option->state & QStyle::State_MouseOver)
        {
            imagePath = GENIE2_RES("map/devices/PowerLineSelected.png");
        }
        else
        {
            imagePath = GENIE2_RES("map/devices/PowerLineNormal.png");
        }

        QPixmap nodePixmap(imagePath);
        painter->drawPixmap(itemRect.topLeft(),nodePixmap);
        return;
    }
#endif

#ifdef PLUGIN_TARGET
    if((mNodeFlags & NF_ISCENTRALROUTER)||(m_deviceType==MDT_ROUTER))
    {
        Q_ASSERT (m_paintStrategy);
        m_paintStrategy->paint(painter,(option->state & QStyle::State_MouseOver),(mNodeFlags &NF_ISONLINE));
    }
    else
#endif
    {
        int pixmapRole = DTIR_NORMAL;

        if((option->state & QStyle::State_MouseOver) && (mNodeFlags & NF_ISONLINE) && (m_deviceType != MDT_INTERNET))
        {
            pixmapRole = DTIR_SELECTED;
        }
        else if(!(mNodeFlags&NF_ISONLINE))
        {
            pixmapRole = DTIR_OFFLINE;
        }

        QString pixmapPath;

        if(mNodeFlags & NF_ISLOCALHOST)
        {
            pixmapPath = getLocalHostImagePath(pixmapRole);
        }
        else if(mNodeFlags & NF_ISCENTRALROUTER)
        {
            pixmapPath = getCentralRouterImagePath(pixmapRole);
        }
        else
        {
            pixmapPath = getDeviceTypeImagePath(m_deviceType,pixmapRole);
        }

        QPixmap nodePixmap(pixmapPath);
        painter->drawPixmap(itemRect.topLeft(),nodePixmap);

    }

    //draw indicator pixmap

    paintSubIcons(painter,itemRect);

    //draw name
    if(!(mNodeFlags & NF_ISCENTRALROUTER) && (m_deviceType != MDT_INTERNET )
             &&(m_deviceType != MDT_ROUTER))
        {
        QColor penColor = ((mNodeFlags & NF_ISONLINE) ? ((option->state & QStyle::State_MouseOver) ? Qt::white : Qt::black) : QColor(204,204,204));

        painter->setPen(penColor);

        QFont font(painter->font());
#ifdef Q_OS_MACX
        font.setPointSize(10);
#else
        font.setPointSize(8);
#endif
        painter->setFont(font);

        QFontMetrics fm(font);

        QString labelText = m_name;

        if(fm.width(labelText) > (itemRect.width() - 2*fm.width('X')))
        {
            for(int k = 0 ; k < labelText.size() ; ++k)
            {
                if(fm.width(labelText.left(k)) + fm.width("...") >= (itemRect.width() - 2*fm.width('X')))
                {
                    labelText = labelText.left(k) + "...";
                    break;
                }
            }
        }

        int width = fm.width(labelText);
        int x = itemRect.left() + (itemRect.width() - width) / 2;

        painter->drawText(x, itemRect.top() + 62, labelText);
    }
}
void ProfileGraphicsView::plot(struct dive *d, bool forceRedraw)
{
	struct divecomputer *dc;

	if (d)
		dc = select_dc(&d->dc);

	if (!forceRedraw && dive == d && (d && dc == diveDC))
		return;

	clear();
	dive = d;
	diveDC = d ? dc : NULL;

	if (!isVisible() || !dive) {
		return;
	}

	scene()->setSceneRect(0,0, viewport()->width()-50, viewport()->height()-50);

	QSettings s;
	s.beginGroup("ProfileMap");
	QPointF toolTipPos = s.value("tooltip_position", QPointF(0,0)).toPointF();
	s.endGroup();

	toolTip = new ToolTipItem();
	toolTip->setPos(toolTipPos);

	scene()->addItem(toolTip);

	// Fix this for printing / screen later.
	// plot_set_scale(scale_mode_t);

	if (!dc->samples) {
		static struct sample fake[4];
		static struct divecomputer fakedc;
		fakedc = dive->dc;
		fakedc.sample = fake;
		fakedc.samples = 4;

		/* The dive has no samples, so create a few fake ones.  This assumes an
		ascent/descent rate of 9 m/min, which is just below the limit for FAST. */
		int duration = dive->dc.duration.seconds;
		int maxdepth = dive->dc.maxdepth.mm;
		int asc_desc_time = dive->dc.maxdepth.mm*60/9000;
		if (asc_desc_time * 2 >= duration)
			asc_desc_time = duration / 2;
		fake[1].time.seconds = asc_desc_time;
		fake[1].depth.mm = maxdepth;
		fake[2].time.seconds = duration - asc_desc_time;
		fake[2].depth.mm = maxdepth;
		fake[3].time.seconds = duration * 1.00;
		fakedc.events = dc->events;
		dc = &fakedc;
	}

	/*
	 * Set up limits that are independent of
	 * the dive computer
	 */
	calculate_max_limits(dive, dc, &gc);

	QRectF profile_grid_area = scene()->sceneRect();
	gc.maxx = (profile_grid_area.width() - 2 * profile_grid_area.x());
	gc.maxy = (profile_grid_area.height() - 2 * profile_grid_area.y());

	/* This is per-dive-computer. Right now we just do the first one */
	gc.pi = *create_plot_info(dive, dc, &gc);

	/* Depth profile */
	plot_depth_profile();

	plot_events(dc);

	/* Temperature profile */
	plot_temperature_profile();

	/* Cylinder pressure plot */
	plot_cylinder_pressure(dive, dc);

	/* Text on top of all graphs.. */
	plot_temperature_text();

	plot_depth_text();

	plot_cylinder_pressure_text();

	plot_deco_text();

	/* Bounding box */
	QPen pen = defaultPen;
	pen.setColor(profile_color[TIME_GRID].at(0));
	QGraphicsRectItem *rect = new QGraphicsRectItem(profile_grid_area);
	rect->setPen(pen);
	scene()->addItem(rect);

	/* Put the dive computer name in the lower left corner */
	QString nick(get_dc_nickname(dc->model, dc->deviceid));
	if (nick.isEmpty())
		nick = QString(dc->model);

	if (nick.isEmpty())
		nick = tr("unknown divecomputer");

	gc.leftx = 0; gc.rightx = 1.0;
	gc.topy = 0; gc.bottomy = 1.0;

	text_render_options_t computer = {DC_TEXT_SIZE, TIME_TEXT, LEFT, TOP};
	diveComputer = plot_text(&computer, QPointF(gc.leftx, gc.bottomy), nick);
	// The Time ruler should be right after the DiveComputer:
	timeMarkers->setPos(0, diveComputer->y());

	if (PP_GRAPHS_ENABLED) {
		plot_pp_gas_profile();
		plot_pp_text();
	}


	/* now shift the translation back by half the margin;
	 * this way we can draw the vertical scales on both sides */
	//cairo_translate(gc->cr, -drawing_area->x / 2.0, 0);

	//gc->maxx += drawing_area->x;
	//gc->leftx = -(drawing_area->x / drawing_area->width) / 2.0;
	//gc->rightx = 1.0 - gc->leftx;

	plot_depth_scale();

#if 0
	if (gc->printer) {
		free(pi->entry);
		last_pi_entry = pi->entry = NULL;
		pi->nr = 0;
	}
#endif

	QRectF r = scene()->itemsBoundingRect();
	scene()->setSceneRect(r.x() - 15, r.y() -15, r.width() + 30, r.height() + 30);
	if (zoomLevel == 0) {
		fitInView(sceneRect());
	}
}
/*!
  Expand all line breaks in text labels, and calculate the height
  of their widgets in orientation of the text.

  \param options Options how to layout the legend
  \param rect Bounding rectangle for title, footer, axes and canvas.
  \param dimTitle Expanded height of the title widget
  \param dimFooter Expanded height of the footer widget
  \param dimAxis Expanded heights of the axis in axis orientation.

  \sa Options
*/
void QwtPlotLayout::expandLineBreaks( Options options, const QRectF &rect,
    int &dimTitle, int &dimFooter, int dimAxis[QwtPlot::axisCnt] ) const
{
    dimTitle = dimFooter = 0;
    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
        dimAxis[axis] = 0;

    int backboneOffset[QwtPlot::axisCnt];
    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        backboneOffset[axis] = 0;
        if ( !( options & IgnoreFrames ) )
            backboneOffset[axis] += d_data->layoutData.canvas.contentsMargins[ axis ];

        if ( !d_data->alignCanvasToScales[axis] )
            backboneOffset[axis] += d_data->canvasMargin[axis];
    }

    bool done = false;
    while ( !done )
    {
        done = true;

        // the size for the 4 axis depend on each other. Expanding
        // the height of a horizontal axis will shrink the height
        // for the vertical axis, shrinking the height of a vertical
        // axis will result in a line break what will expand the
        // width and results in shrinking the width of a horizontal
        // axis what might result in a line break of a horizontal
        // axis ... . So we loop as long until no size changes.

        if ( !( ( options & IgnoreTitle ) ||
            d_data->layoutData.title.text.isEmpty() ) )
        {
            double w = rect.width();

            if ( d_data->layoutData.scale[QwtPlot::yLeft].isEnabled
                != d_data->layoutData.scale[QwtPlot::yRight].isEnabled )
            {
                // center to the canvas
                w -= dimAxis[QwtPlot::yLeft] + dimAxis[QwtPlot::yRight];
            }

            int d = qCeil( d_data->layoutData.title.text.heightForWidth( w ) );
            if ( !( options & IgnoreFrames ) )
                d += 2 * d_data->layoutData.title.frameWidth;

            if ( d > dimTitle )
            {
                dimTitle = d;
                done = false;
            }
        }

        if ( !( ( options & IgnoreFooter ) ||
            d_data->layoutData.footer.text.isEmpty() ) )
        {
            double w = rect.width();

            if ( d_data->layoutData.scale[QwtPlot::yLeft].isEnabled
                != d_data->layoutData.scale[QwtPlot::yRight].isEnabled )
            {
                // center to the canvas
                w -= dimAxis[QwtPlot::yLeft] + dimAxis[QwtPlot::yRight];
            }

            int d = qCeil( d_data->layoutData.footer.text.heightForWidth( w ) );
            if ( !( options & IgnoreFrames ) )
                d += 2 * d_data->layoutData.footer.frameWidth;

            if ( d > dimFooter )
            {
                dimFooter = d;
                done = false;
            }
        }

        for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
        {
            const struct LayoutData::t_scaleData &scaleData =
                d_data->layoutData.scale[axis];

            if ( scaleData.isEnabled )
            {
                double length;
                if ( axis == QwtPlot::xTop || axis == QwtPlot::xBottom )
                {
                    length = rect.width() - dimAxis[QwtPlot::yLeft]
                        - dimAxis[QwtPlot::yRight];
                    length -= scaleData.start + scaleData.end;

                    if ( dimAxis[QwtPlot::yRight] > 0 )
                        length -= 1;

                    length += qMin( dimAxis[QwtPlot::yLeft],
                        scaleData.start - backboneOffset[QwtPlot::yLeft] );
                    length += qMin( dimAxis[QwtPlot::yRight],
                        scaleData.end - backboneOffset[QwtPlot::yRight] );
                }
                else // QwtPlot::yLeft, QwtPlot::yRight
                {
                    length = rect.height() - dimAxis[QwtPlot::xTop]
                        - dimAxis[QwtPlot::xBottom];
                    length -= scaleData.start + scaleData.end;
                    length -= 1;

                    if ( dimAxis[QwtPlot::xBottom] <= 0 )
                        length -= 1;
                    if ( dimAxis[QwtPlot::xTop] <= 0 )
                        length -= 1;

                    if ( dimAxis[QwtPlot::xBottom] > 0 )
                    {
                        length += qMin(
                            d_data->layoutData.scale[QwtPlot::xBottom].tickOffset,
                            double( scaleData.start - backboneOffset[QwtPlot::xBottom] ) );
                    }
                    if ( dimAxis[QwtPlot::xTop] > 0 )
                    {
                        length += qMin(
                            d_data->layoutData.scale[QwtPlot::xTop].tickOffset,
                            double( scaleData.end - backboneOffset[QwtPlot::xTop] ) );
                    }

                    if ( dimTitle > 0 )
                        length -= dimTitle + d_data->spacing;
                }

                int d = scaleData.dimWithoutTitle;
                if ( !scaleData.scaleWidget->title().isEmpty() )
                {
                    d += scaleData.scaleWidget->titleHeightForWidth( qFloor( length ) );
                }


                if ( d > dimAxis[axis] )
                {
                    dimAxis[axis] = d;
                    done = false;
                }
            }
        }
    }
}
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());
}
/*!
  \brief Draw the identifier representing the curve on the legend

  \param painter Üainter
  \param rect Bounding rectangle for the identifier

  \sa setLegendAttribute
*/
void QwtPlotCurve::drawLegendIdentifier(
    QPainter *painter, const QRectF &rect ) const
{
    if ( rect.isEmpty() )
        return;

    const int dim = qMin( rect.width(), rect.height() );

    QSize size( dim, dim );

    QRectF r( 0, 0, size.width(), size.height() );
    r.moveCenter( rect.center() );

    if ( d_data->legendAttributes == 0 )
    {
        QBrush brush = d_data->brush;
        if ( brush.style() == Qt::NoBrush )
        {
            if ( style() != QwtPlotCurve::NoCurve )
                brush = QBrush( pen().color() );
            else if ( d_data->symbol &&
                ( d_data->symbol->style() != QwtSymbol::NoSymbol ) )
            {
                brush = QBrush( d_data->symbol->pen().color() );
            }
        }
        if ( brush.style() != Qt::NoBrush )
            painter->fillRect( r, brush );
    }
    if ( d_data->legendAttributes & QwtPlotCurve::LegendShowBrush )
    {
        if ( d_data->brush.style() != Qt::NoBrush )
            painter->fillRect( r, d_data->brush );
    }
    if ( d_data->legendAttributes & QwtPlotCurve::LegendShowLine )
    {
        if ( pen() != Qt::NoPen )
        {
            painter->setPen( pen() );
            QwtPainter::drawLine( painter, rect.left(), rect.center().y(),
                                  rect.right() - 1.0, rect.center().y() );
        }
    }
    if ( d_data->legendAttributes & QwtPlotCurve::LegendShowSymbol )
    {
        if ( d_data->symbol &&
            ( d_data->symbol->style() != QwtSymbol::NoSymbol ) )
        {
            QSize symbolSize = d_data->symbol->boundingSize();
            symbolSize -= QSize( 2, 2 );

            // scale the symbol size down if it doesn't fit into rect.

            double xRatio = 1.0;
            if ( rect.width() < symbolSize.width() )
                xRatio = rect.width() / symbolSize.width();
            double yRatio = 1.0;
            if ( rect.height() < symbolSize.height() )
                yRatio = rect.height() / symbolSize.height();

            const double ratio = qMin( xRatio, yRatio );

            painter->save();
            painter->scale( ratio, ratio );

            d_data->symbol->drawSymbol( painter, rect.center() / ratio );

            painter->restore();
        }
    }
}
Exemple #8
0
void IsometricRenderer::drawMapObject(QPainter *painter,
                                      const MapObject *object,
                                      const QColor &color) const
{
    painter->save();

    QPen pen(Qt::black);

    if (object->tile()) {
        const QPixmap &img = object->tile()->image();
        QPointF paintOrigin(-img.width() / 2, -img.height());
        paintOrigin += tileToPixelCoords(object->position()).toPoint();
        painter->drawPixmap(paintOrigin, img);

        const QFontMetrics fm = painter->fontMetrics();
        QString name = fm.elidedText(object->name(), Qt::ElideRight,
                                     img.width() + 2);
        if (!name.isEmpty())
            painter->drawText(QPoint(paintOrigin.x(), paintOrigin.y() - 5 + 1), name);

        pen.setStyle(Qt::SolidLine);
        painter->setPen(pen);
        painter->drawRect(QRectF(paintOrigin, img.size()));
        pen.setStyle(Qt::DotLine);
        pen.setColor(color);
        painter->setPen(pen);
        painter->drawRect(QRectF(paintOrigin, img.size()));

        if (!name.isEmpty())
            painter->drawText(QPoint(paintOrigin.x(), paintOrigin.y() - 5), name);

    } else {
        QColor brushColor = color;
        brushColor.setAlpha(50);
        QBrush brush(brushColor);

        pen.setJoinStyle(Qt::RoundJoin);
        pen.setCapStyle(Qt::RoundCap);
        pen.setWidth(2);

        painter->setPen(pen);
        painter->setRenderHint(QPainter::Antialiasing);

        // TODO: Draw the object name
        // TODO: Do something sensible to make null-sized objects usable

        switch (object->shape()) {
        case MapObject::Ellipse: {
            QPointF topLeft(tileToPixelCoords(object->bounds().topLeft()));
            QPointF bottomLeft(tileToPixelCoords(object->bounds().bottomLeft()));
            QPointF topRight(tileToPixelCoords(object->bounds().topRight()));

            const qreal headerX = bottomLeft.x();
            const qreal headerY = topLeft.y();

            QRectF rect(bottomLeft, topRight);

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

            QPolygonF polygon = tileRectToPolygon(object->bounds());

            float tw = map()->tileWidth();
            float th = map()->tileHeight();
            QPointF transformScale(1, 1);
            if (tw > th)
                transformScale = QPointF(1, th/tw);
            else
                transformScale = QPointF(tw/th, 1);

            QPointF l1 = polygon.at(1) - polygon.at(0);
            QPointF l2 = polygon.at(3) - polygon.at(0);
            QTransform trans;
            trans.scale(transformScale.x(), transformScale.y());
            trans.rotate(45);
            QTransform iTrans = trans.inverted();
            QPointF l1x = iTrans.map(l1);
            QPointF l2x = iTrans.map(l2);
            QSizeF ellipseSize(l1x.manhattanLength(), l2x.manhattanLength());

            painter->save();
            painter->setPen(pen);
            painter->translate(polygon.at(0));
            painter->scale(transformScale.x(), transformScale.y());
            painter->rotate(45);
            painter->drawEllipse(QRectF(QPointF(0, 0), ellipseSize));
            painter->restore();

            painter->setBrush(Qt::NoBrush);
            painter->drawPolygon(polygon);

            if (!name.isEmpty())
                painter->drawText(QPoint(headerX, headerY - 5), name);

            pen.setColor(color);
            painter->setPen(pen);
            painter->setBrush(Qt::NoBrush);
            painter->translate(QPointF(0, -1));
            painter->drawPolygon(polygon);

            painter->setBrush(brush);
            painter->save();
            painter->translate(polygon.at(0));
            painter->scale(transformScale.x(), transformScale.y());
            painter->rotate(45);
            painter->drawEllipse(QRectF(QPointF(0, 0), ellipseSize));
            painter->restore();

            if (!name.isEmpty())
                painter->drawText(QPoint(headerX, headerY - 5), name);
            break;
        }
        case MapObject::Rectangle: {

            QPointF topLeft(tileToPixelCoords(object->bounds().topLeft()));
            QPointF bottomLeft(tileToPixelCoords(object->bounds().bottomLeft()));
            QPointF topRight(tileToPixelCoords(object->bounds().topRight()));

            const qreal headerX = bottomLeft.x();
            const qreal headerY = topLeft.y();

            QRectF rect(bottomLeft, topRight);

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

            QPolygonF polygon = tileRectToPolygon(object->bounds());
            painter->drawPolygon(polygon);
            if (!name.isEmpty())
                painter->drawText(QPoint(headerX, headerY - 5 + 1), name);

            pen.setColor(color);
            painter->setPen(pen);
            painter->setBrush(brush);
            polygon.translate(0, -1);

            painter->drawPolygon(polygon);
            if (!name.isEmpty())
                painter->drawText(QPoint(headerX, headerY - 5), name);
            break;
        }
        case MapObject::Polygon: {
            const QPointF &pos = object->position();
            const QPolygonF polygon = object->polygon().translated(pos);
            QPolygonF screenPolygon = tileToPixelCoords(polygon);

            const QRectF polygonBoundingRect = screenPolygon.boundingRect();

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

            if (!name.isEmpty())
                painter->drawText(QPoint(polygonBoundingRect.left(), polygonBoundingRect.top() - 5 + 1), name);

            painter->drawPolygon(screenPolygon);

            pen.setColor(color);
            painter->setPen(pen);
            painter->setBrush(brush);
            screenPolygon.translate(0, -1);

            painter->drawPolygon(screenPolygon);

            if (!name.isEmpty())
                painter->drawText(QPoint(polygonBoundingRect.left(), polygonBoundingRect.top() - 5), name);

            break;
        }
        case MapObject::Polyline: {
            const QPointF &pos = object->position();
            const QPolygonF polygon = object->polygon().translated(pos);
            QPolygonF screenPolygon = tileToPixelCoords(polygon);

            painter->drawPolyline(screenPolygon);

            pen.setColor(color);
            painter->setPen(pen);
            screenPolygon.translate(0, -1);

            painter->drawPolyline(screenPolygon);
            break;
        }
        }
    }

    painter->restore();
}
Exemple #9
0
bool OsmImport::parseDoc(QDomDocument &doc)
{

    QDomNodeList list = doc.elementsByTagName("node");
    for (int i = 0; i < list.count(); i++)
    {
        nodes.append(new osmNode(list.at(i).toElement()));
    }
    list = doc.elementsByTagName("way");
    for (int i = 0; i < list.count(); i++)
    {
        ways.append(new osmWay(list.at(i).toElement(), nodes));
    }
    
    bool importPrimary();
    bool importSecondary();
    bool importTertiary();
    bool importMotorway();
    bool importService();
    bool importPath();
    bool importSteps();
    bool importTrack();
    bool importFootway();
    bool importResidential();
    bool importLiving_street();
    bool importCycleway();
    bool importTurning_circle();
    bool importPedestrian();
    bool importUnclassified();
    bool doPrimary = ImportSettings::instance()->importPrimary();
    bool doSecondary = ImportSettings::instance()->importSecondary();
    bool doTertiary = ImportSettings::instance()->importTertiary();
    bool doMotorway = ImportSettings::instance()->importMotorway();
    bool doService = ImportSettings::instance()->importService();
    bool doPath = ImportSettings::instance()->importPath();
    bool doSteps = ImportSettings::instance()->importSteps();
    bool doTrack = ImportSettings::instance()->importTrack();
    bool doFootpath = ImportSettings::instance()->importFootway();
    bool doResidential = ImportSettings::instance()->importResidential();
    bool doLiving_street = ImportSettings::instance()->importLiving_street();
    bool doCycleway = ImportSettings::instance()->importCycleway();
    bool doTurning_circle = ImportSettings::instance()->importTurning_circle();
    bool doPedestrian = ImportSettings::instance()->importPedestrian();
    bool doUnclassified = ImportSettings::instance()->importUnclassified();
    for (int i = 0; i < ways.count(); i++)
    {
        osmWay *w = ways.at(i);
        osmWay::wayType t = w->type;

        if ((t == osmWay::primary && doPrimary) ||
            (t == osmWay::secondary && doSecondary) ||
            (t == osmWay::tertiary && doTertiary) ||
            (t == osmWay::motorway && doMotorway) ||
            (t == osmWay::service && doService) ||
            (t == osmWay::path && doPath) ||
            (t == osmWay::steps && doSteps) ||
            (t == osmWay::track && doTrack) ||
            (t == osmWay::footway && doFootpath) ||
            (t == osmWay::residential && doResidential) ||
            (t == osmWay::living_street && doLiving_street) ||
            (t == osmWay::cycleway && doCycleway) ||
            (t == osmWay::turning_circle && doTurning_circle) ||
            (t == osmWay::pedestrian && doPedestrian) ||
            (t == osmWay::unclassified && doUnclassified))
        {
            project->XVector = w->XVector;
            project->YVector = w->YVector;
            project->ZVector = w->ZVector;
            if (project->XVector.size() > 0)
            {
                project->addLineStrip(w->name,w->maxSpeed,w->bridge,w->numLanes,w->type);
            }
        }
    }
    qDeleteAll(ways.begin(), ways.end());
    qDeleteAll(nodes.begin(), nodes.end());
    ways.clear();
    nodes.clear();
    // resize
    BoundingBoxVisitor *visitor = new BoundingBoxVisitor();
    project->getProjectData()->getRoadSystem()->accept(visitor);
    project->getProjectData()->getScenerySystem()->accept(visitor);
    QRectF box = visitor->getBoundingBox();
    SetProjectDimensionsCommand *command = new SetProjectDimensionsCommand(project->getProjectData(), box.bottom() + 0.1 * box.height(), box.top() - 0.1 * box.height(), box.right() + 0.1 * box.width(), box.left() - 0.1 * box.width());
    project->getProjectSettings()->executeCommand(command);

    return true;
}
Exemple #10
0
static ShiftResult shift(const QBezier *orig, QBezier *shifted, qreal offset, qreal threshold)
{
    int map[4];
    bool p1_p2_equal = (orig->x1 == orig->x2 && orig->y1 == orig->y2);
    bool p2_p3_equal = (orig->x2 == orig->x3 && orig->y2 == orig->y3);
    bool p3_p4_equal = (orig->x3 == orig->x4 && orig->y3 == orig->y4);

    QPointF points[4];
    int np = 0;
    points[np] = QPointF(orig->x1, orig->y1);
    map[0] = 0;
    ++np;
    if (!p1_p2_equal) {
        points[np] = QPointF(orig->x2, orig->y2);
        ++np;
    }
    map[1] = np - 1;
    if (!p2_p3_equal) {
        points[np] = QPointF(orig->x3, orig->y3);
        ++np;
    }
    map[2] = np - 1;
    if (!p3_p4_equal) {
        points[np] = QPointF(orig->x4, orig->y4);
        ++np;
    }
    map[3] = np - 1;
    if (np == 1)
        return Discard;

    QRectF b = orig->bounds();
    if (np == 4 && b.width() < .1*offset && b.height() < .1*offset) {
        qreal l = (orig->x1 - orig->x2)*(orig->x1 - orig->x2) +
                  (orig->y1 - orig->y2)*(orig->y1 - orig->y2) *
                  (orig->x3 - orig->x4)*(orig->x3 - orig->x4) +
                  (orig->y3 - orig->y4)*(orig->y3 - orig->y4);
        qreal dot = (orig->x1 - orig->x2)*(orig->x3 - orig->x4) +
                    (orig->y1 - orig->y2)*(orig->y3 - orig->y4);
        if (dot < 0 && dot*dot < 0.8*l)
            // the points are close and reverse dirction. Approximate the whole
            // thing by a semi circle
            return Circle;
    }

    QPointF points_shifted[4];

    QLineF prev = QLineF(QPointF(), points[1] - points[0]);
    QPointF prev_normal = prev.normalVector().unitVector().p2();

    points_shifted[0] = points[0] + offset * prev_normal;

    for (int i = 1; i < np - 1; ++i) {
        QLineF next = QLineF(QPointF(), points[i + 1] - points[i]);
        QPointF next_normal = next.normalVector().unitVector().p2();

        QPointF normal_sum = prev_normal + next_normal;

        qreal r = qreal(1.0) + prev_normal.x() * next_normal.x()
                  + prev_normal.y() * next_normal.y();

        if (qFuzzyIsNull(r)) {
            points_shifted[i] = points[i] + offset * prev_normal;
        } else {
            qreal k = offset / r;
            points_shifted[i] = points[i] + k * normal_sum;
        }

        prev_normal = next_normal;
    }

    points_shifted[np - 1] = points[np - 1] + offset * prev_normal;

    *shifted = QBezier::fromPoints(points_shifted[map[0]], points_shifted[map[1]],
                                   points_shifted[map[2]], points_shifted[map[3]]);

    return good_offset(orig, shifted, offset, threshold);
}
//-------------------------------------------------------------------------
void QGuidoItemContainer::resized(const QRectF& newRect)
{
	if ( newRect.toRect() == rect().toRect() )
		return;

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

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

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

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

		float boundedSx = sx;
		float boundedSy = sy;

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

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

		Q_EMIT scaleChanged( mGuidoItem->transform().m11() );
	}
	mResizeMode = RESIZE_NORMAL;
	if ( mResizer )
		mResizer->setKeepAspectRatio(true);
}
Exemple #12
0
void PixmapCachingSheetView::paintCells(QPainter& painter, const QRectF& paintRect, const QPointF& topLeft, CanvasBase* canvas, const QRect& visibleRect)
{
    if (!canvas) {
        SheetView::paintCells(painter, paintRect, topLeft, canvas, visibleRect);
        return;
    }
    // paintRect:   the canvas area, that should be painted; in document coordinates;
    //              no layout direction consideration; scrolling offset applied;
    //              independent from painter transformations
    // topLeft:     the document coordinate of the top left cell's top left corner;
    //              no layout direction consideration; independent from painter
    //              transformations

    QTransform t = painter.transform();

    // figure out scaling from the transformation... not really perfect, but should work as long as rotation is in 90 degree steps I think
    const qreal cos_sx = t.m11();
    const qreal sin_sx = t.m12();
    const qreal msin_sy = t.m21();
    const qreal cos_sy = t.m22();

    const qreal sx = sqrt(cos_sx*cos_sx + sin_sx*sin_sx);
    const qreal sy = sqrt(cos_sy*cos_sy + msin_sy*msin_sy);
    //const qreal cost = (sx > 1e-10 ? cos_sx / sx : cos_sy / sy);
    //const qreal ang = acos(cost);

    QPointF scale = QPointF(sx, sy);
    if (scale != d->lastScale) {
        d->tileCache.clear();
    }
    d->lastScale = scale;

    QRect tiles;
    const QRect visibleCells = paintCellRange();
    const Sheet * s = sheet();
    const QPointF bottomRight(s->columnPosition(visibleCells.right() + 1), s->rowPosition(visibleCells.bottom() + 1));
    tiles.setLeft(topLeft.x() * sx / TILESIZE);
    tiles.setTop(topLeft.y() * sy / TILESIZE);
    tiles.setRight((bottomRight.x() * sx + TILESIZE-1) / TILESIZE);
    tiles.setBottom((bottomRight.y() * sy + TILESIZE-1) / TILESIZE);

    bool rtl = s->layoutDirection() == Qt::RightToLeft;

    if (rtl) {
        for (int x = qMax(0, tiles.left()); x < tiles.right(); x++) {
            for (int y = qMax(0, tiles.top()); y < tiles.bottom(); y++) {
                QPixmap *p = d->getTile(s, x, y, canvas);
                if (p) {
                    QPointF pt(paintRect.width() - (x+1) * TILESIZE / scale.x(), y * TILESIZE / scale.y());
                    QRectF r(pt, QSizeF(TILESIZE / sx, TILESIZE / sy));
                    painter.drawPixmap(r, *p, p->rect());
                }
            }
        }
    } else {
        for (int x = qMax(0, tiles.left()); x < tiles.right(); x++) {
            for (int y = qMax(0, tiles.top()); y < tiles.bottom(); y++) {
                QPixmap *p = d->getTile(s, x, y, canvas);
                if (p) {
                    QPointF pt(x * TILESIZE / scale.x(), y * TILESIZE / scale.y());
                    QRectF r(pt, QSizeF(TILESIZE / sx, TILESIZE / sy));
                    painter.drawPixmap(r, *p, p->rect());
                }
            }
        }
    }
}
void MScene::drawForeground(QPainter *painter, const QRectF &rect)
{
    Q_D(MScene);

    /* Overlay information on the widgets in development mode */
    if (MApplication::showBoundingRect() || MApplication::showSize() || MApplication::showPosition() || MApplication::showMargins() || MApplication::showObjectNames() || MApplication::showStyleNames()) {
        QList<QGraphicsItem *> itemList = items(rect);
        QList<QGraphicsItem *>::iterator item;

        painter->setFont(TextFont);
        int fontHeight = d->metrics.height();
        QTransform rotationMatrix;
        painter->setTransform(rotationMatrix);

        QList<QGraphicsItem *>::iterator end = itemList.end();
        for (item = itemList.begin(); item != end; ++item) {
            QRectF br = (*item)->boundingRect();
            QPolygonF bp = (*item)->mapToScene(br);

            if (MApplication::showBoundingRect()) {
                if (!dynamic_cast<MApplicationPage *>(*item)) { // filter out page for clarity
                    painter->setOpacity(BoundingRectOpacity);
                    painter->setPen(d->boundingRectLinePen);
                    painter->setBrush(d->boundingRectFillBrush);
                    painter->drawPolygon(bp);
                }
            }

            if (MApplication::showMargins()) {
                // Draw content margins
                QGraphicsLayoutItem *layoutItem = dynamic_cast<QGraphicsLayoutItem *>(*item);
                if (layoutItem) {
                    qreal left, top, right, bottom;
                    layoutItem->getContentsMargins(&left, &top, &right, &bottom);

                    QRectF outerRect = (*item)->mapRectToScene(br);
                    QRectF innerRect = (*item)->mapRectToScene(br.adjusted(left, top, -right, -bottom));

                    QRectF leftRect(outerRect.x(), outerRect.y(), innerRect.x() - outerRect.x(), outerRect.height());
                    QRectF topRect(innerRect.x(), outerRect.y(), innerRect.width(), innerRect.y() - outerRect.y());
                    QRectF rightRect(innerRect.bottomRight().x(), outerRect.y(), outerRect.bottomRight().x() - innerRect.bottomRight().x(), outerRect.height());
                    QRectF bottomRect(innerRect.x(), innerRect.bottomRight().y(), innerRect.width(), outerRect.bottomRight().y() - innerRect.bottomRight().y());

                    painter->setOpacity(0.5);

                    d->fillMarginRectWithPattern(painter, leftRect, leftRect.width());
                    d->fillMarginRectWithPattern(painter, topRect, topRect.height());
                    d->fillMarginRectWithPattern(painter, rightRect, rightRect.width());
                    d->fillMarginRectWithPattern(painter, bottomRect, bottomRect.height());

                }

                painter->setOpacity(1.0);
            }

            if (MApplication::showPosition()) {
                QPointF topLeft = ((*item)->mapToScene(br.topLeft()));
                QString posStr = QString("(%1, %2)").arg(topLeft.x()).arg(topLeft.y());
                painter->setPen(Qt::black);
                painter->drawText(topLeft += QPointF(5, fontHeight), posStr);
                painter->setPen(Qt::white);
                painter->drawText(topLeft -= QPointF(1, 1),  posStr);
            }

            if (MApplication::showSize()) {
                QPointF bottomRight = ((*item)->mapToScene(br.bottomRight()));
                QPointF pos = (*item)->mapToScene(br.topLeft());
                QString sizeStr = QString("%1x%2 (%3,%4)").arg(br.width()).arg(br.height()).arg(pos.x()).arg(pos.y());
                painter->setPen(Qt::black);
                painter->drawText(bottomRight -= QPointF(d->metrics.width(sizeStr), 2), sizeStr);
                painter->setPen(Qt::white);
                painter->drawText(bottomRight -= QPointF(1, 1), sizeStr);
            }

            if (MApplication::showObjectNames()) {
                d->drawObjectNames(painter, item);
            }

            if (MApplication::showStyleNames()) {
                d->drawStyleNames(painter, item);
            }
        }
    }

    bool countingFps = MApplication::logFps() || MApplication::showFps();
    if (countingFps) {
        if (d->fps.frameCount < 0) {
            d->fps.time.restart();
            d->fps.frameCount = 0;
        }
        ++d->fps.frameCount;

        int ms = d->fps.time.elapsed();
        if (ms > FpsRefreshInterval) {
            float fps = d->fps.frameCount * 1000.0f / ms;
            d->fps.time.restart();
            d->fps.frameCount = 0;
            if (MApplication::logFps()) {
                QTime time = d->fps.time.currentTime();
                d->logFpsCounter(&time, fps);
            }
            d->fps.fps = fps;
        }

        if (MApplication::showFps()) {
            d->showFpsCounter(painter, d->fps.fps);
        }

        // this update call makes repainting work as fast
        // as possible, and by that prints useful fps numbers
        QTimer::singleShot(0, this, SLOT(update()));
    } else {
        d->fps.frameCount = -1;
    }

    if (MApplication::emulateTwoFingerGestures() &&
        d->pinchEmulationEnabled)
    {
        static const QPixmap *tapPixmap = MTheme::pixmap("meegotouch-tap");
        QPointF pixmapCenterDelta(tapPixmap->width() / 2, tapPixmap->height() / 2);

        painter->drawPixmap(d->emuPoint1.scenePos() - pixmapCenterDelta, *tapPixmap);
        painter->drawPixmap(d->emuPoint2.scenePos() - pixmapCenterDelta, *tapPixmap);
    }
}
//Update the meaning menu when an item is selected
void SymbolismMenu::updateSymbolism(PaintingItem *item)
{
	m_item = item;

	if (!item)
	{
		hide();
		return;
	}

	QRectF box = item->sceneBoundingRect();


	if (LandscapeContentListing *info = item->getListing())
	{
		m_screen->setText("symbolismName", QString::fromStdString(StringHelper::toUpper(info->getDescription().toStdString())));

		m_screen->setText("symbolismTextOff1", QString::fromStdString(StringHelper::toUpper(info->getMeaning1().toStdString())));
		m_screen->setText("symbolismTextOn1", QString::fromStdString(StringHelper::toUpper(info->getMeaning1().toStdString())));

		m_screen->setText("symbolismTextOff2", QString::fromStdString(StringHelper::toUpper(info->getMeaning2().toStdString())));
		m_screen->setText("symbolismTextOn2", QString::fromStdString(StringHelper::toUpper(info->getMeaning2().toStdString())));

		m_screen->setText("symbolismTextOff3", QString::fromStdString(StringHelper::toUpper(info->getMeaning3().toStdString())));
		m_screen->setText("symbolismTextOn3", QString::fromStdString(StringHelper::toUpper(info->getMeaning3().toStdString())));

			
	}

	switch (m_item->getSymbolSelected())
	{
	case 1:
		m_screen->setToggleGroupOnState("symbolismToggle", "symbolismToggle1");
		break;

	case 2:
		m_screen->setToggleGroupOnState("symbolismToggle", "symbolismToggle2");
		break;

	case 3:
		m_screen->setToggleGroupOnState("symbolismToggle", "symbolismToggle3");
		break;

	case -1:
	default:
		m_screen->setToggleGroupOnState("symbolismToggle", "symbolismToggle1");
		m_item->setSymbolSelected(1);
		break;
	}
	
	//Chaning the menu position based on the item's position
	//TODO- hard coding
	qreal x = box.left() - 289;
	qreal y = box.top() - 20;

	if (x < 0)
	{
		x = box.left() + box.width();
	}

	if (y < 0)
	{
		y = box.bottom() + 10;
		x = box.left() - 20;
	}

	if (y > 588)
	{
		x = box.left() - 20;
		y = box.top() - 289 - 70;
	}

	m_screen->getContainer("symbolismOverlay")->setPosition(vec2(x, y));
	

	show();
	
}
Exemple #15
0
QRectF MyGraphBase::getArea() const
{
  QRectF sceneRect = this->sceneRect();
  return QRectF( sceneRect.x(), sceneRect.y(),
                 sceneRect.width() - 20,  sceneRect.height() );
}
void CameraBinFocus::updateRegionOfInterest(const QRectF &focusRect, int priority)
{
    if (m_cameraState != QCamera::ActiveState)
        return;

    GstElement * const cameraSource = m_session->cameraSource();
    if (!cameraSource)
        return;

    GstStructure *region = gst_structure_new(
                "region",
                "region-x"        , G_TYPE_UINT , uint(m_viewfinderResolution.width()  * focusRect.x()),
                "region-y"        , G_TYPE_UINT,  uint(m_viewfinderResolution.height() * focusRect.y()),
                "region-w"        , G_TYPE_UINT , uint(m_viewfinderResolution.width()  * focusRect.width()),
                "region-h"        , G_TYPE_UINT,  uint(m_viewfinderResolution.height() * focusRect.height()),
                "region-priority" , G_TYPE_UINT,  priority,
                NULL);

    GValue regionValue = G_VALUE_INIT;
    g_value_init(&regionValue, GST_TYPE_STRUCTURE);
    gst_value_set_structure(&regionValue, region);
    gst_structure_free(region);

    GValue regions = G_VALUE_INIT;
    g_value_init(&regions, GST_TYPE_LIST);
    gst_value_list_append_value(&regions, &regionValue);
    g_value_unset(&regionValue);

    GstStructure *regionsOfInterest = gst_structure_new(
                "regions-of-interest",
                "frame-width"     , G_TYPE_UINT , m_viewfinderResolution.width(),
                "frame-height"    , G_TYPE_UINT,  m_viewfinderResolution.height(),
                NULL);
    gst_structure_set_value(regionsOfInterest, "regions", &regions);
    g_value_unset(&regions);

    GstEvent *event = gst_event_new_custom(GST_EVENT_CUSTOM_UPSTREAM, regionsOfInterest);
    gst_element_send_event(cameraSource, event);
}
Exemple #17
0
QString Pad::makeLayerSvg(ViewLayer::ViewLayerID viewLayerID, double mmW, double mmH, double milsW, double milsH) 
{
	Q_UNUSED(milsW);
	Q_UNUSED(milsH);

	switch (viewLayerID) {
		case ViewLayer::Copper0:
		case ViewLayer::Copper1:
			break;
		default:
			return "";
	}

	double wpx = mmW > 0 ? GraphicsUtils::mm2pixels(mmW) : OriginalWidth;
	double hpx = mmH > 0 ? GraphicsUtils::mm2pixels(mmH) : OriginalHeight;

	QString connectAt = m_modelPart->localProp("connect").toString();
	QRectF terminal;
	double minW = qMin((double) 1.0, wpx / 3);
	double minH = qMin((double) 1.0, hpx / 3);
	if (connectAt.compare("center", Qt::CaseInsensitive) == 0) {
		terminal.setRect(2, 2, wpx, hpx);
	}
	else if (connectAt.compare("north", Qt::CaseInsensitive) == 0) {
		terminal.setRect(2, 2, wpx, minH);
	}
	else if (connectAt.compare("south", Qt::CaseInsensitive) == 0) {
		terminal.setRect(2, 2 + hpx - minH, wpx, minH);
	}
	else if (connectAt.compare("east", Qt::CaseInsensitive) == 0) {
		terminal.setRect(2 + wpx - minW, 2, minW, hpx);
	}
	else if (connectAt.compare("west", Qt::CaseInsensitive) == 0) {
		terminal.setRect(2, 2, minW, hpx);
	}

    QString blockerColor = (viewLayerID == ViewLayer::Copper0) ? "#A26A00" : "#aF8B33";
    QString copperColor = (viewLayerID == ViewLayer::Copper0) ? ViewLayer::Copper0Color : ViewLayer::Copper1Color;
	QString svg = QString("<svg version='1.1' xmlns='http://www.w3.org/2000/svg'  x='0px' y='0px' width='%1px' height='%2px' viewBox='0 0 %1 %2'>\n"
							"<g id='%5'>\n"
							"<rect  id='%8pad' x='2' y='2' fill='%6' fill-opacity='%7' stroke='%9' stroke-width='%10' width='%3' height='%4'/>\n"
							)
					.arg(wpx + TheOffset)
					.arg(hpx + TheOffset)
					.arg(wpx)
					.arg(hpx)
					.arg(ViewLayer::viewLayerXmlNameFromID(viewLayerID))
                    .arg(copperBlocker() ? blockerColor : copperColor)
                    .arg(copperBlocker() ? 0.0 : 1.0)
                    .arg(copperBlocker() ? "zzz" : "connector0")
                    .arg(copperBlocker() ? blockerColor : "none")
                    .arg(copperBlocker() ? TheOffset : 0)
					;

    if (copperBlocker()) {
        svg += QString("<line stroke='%5' stroke-width='1' x1='%1' y1='%2' x2='%3'  y2='%4'/>\n")
                    .arg(0)
                    .arg(0)
                    .arg(wpx + TheOffset)
                    .arg(hpx + TheOffset)
                    .arg(blockerColor)
                   ;
        svg += QString("<line stroke='%5' stroke-width='1' x1='%1' y1='%2' x2='%3'  y2='%4'/>\n")
                    .arg(wpx + TheOffset)
                    .arg(0)
                    .arg(0)
                    .arg(hpx + TheOffset)
                    .arg(blockerColor)
                   ;

    }
    else {
        svg += QString("<rect  id='%12terminal' x='%1' y='%2' fill='none' stroke='none' stroke-width='0' width='%3' height='%4'/>\n")
					.arg(terminal.left())
					.arg(terminal.top())
					.arg(terminal.width())
					.arg(terminal.height())
                    ;

    }

    svg += "</g>\n</svg>";

	//DebugDialog::debug("pad svg: " + svg);
	return svg;
}
//! [0]
PadNavigator::PadNavigator(const QSize &size, QWidget *parent)
    : QGraphicsView(parent)
{
//! [0]
//! [1]
    // Splash item
    SplashItem *splash = new SplashItem;
    splash->setZValue(1);
//! [1]

//! [2]
    // Pad item
    FlippablePad *pad = new FlippablePad(size);
    QGraphicsRotation *flipRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *xRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *yRotation = new QGraphicsRotation(pad);
    flipRotation->setAxis(Qt::YAxis);
    xRotation->setAxis(Qt::YAxis);
    yRotation->setAxis(Qt::XAxis);
    pad->setTransformations(QList<QGraphicsTransform *>()
                            << flipRotation
                            << xRotation << yRotation);
//! [2]

//! [3]
    // Back (proxy widget) item
    QGraphicsProxyWidget *backItem = new QGraphicsProxyWidget(pad);
    QWidget *widget = new QWidget;
    form.setupUi(widget);
    form.hostName->setFocus();
    backItem->setWidget(widget);
    backItem->setVisible(false);
    backItem->setFocus();
    backItem->setCacheMode(QGraphicsItem::ItemCoordinateCache);
    const QRectF r = backItem->rect();
    backItem->setTransform(QTransform()
                           .rotate(180, Qt::YAxis)
                           .translate(-r.width()/2, -r.height()/2));
//! [3]

//! [4]
    // Selection item
    RoundRectItem *selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray, pad);
    selectionItem->setZValue(0.5);
//! [4]

//! [5]
    // Splash animations
    QPropertyAnimation *smoothSplashMove = new QPropertyAnimation(splash, "y");
    QPropertyAnimation *smoothSplashOpacity = new QPropertyAnimation(splash, "opacity");
    smoothSplashMove->setEasingCurve(QEasingCurve::InQuad);
    smoothSplashMove->setDuration(250);
    smoothSplashOpacity->setDuration(250);
//! [5]

//! [6]
    // Selection animation
    QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x");
    QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y");
    QPropertyAnimation *smoothXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothYRotation = new QPropertyAnimation(yRotation, "angle");
    smoothXSelection->setDuration(125);
    smoothYSelection->setDuration(125);
    smoothXRotation->setDuration(125);
    smoothYRotation->setDuration(125);
    smoothXSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYRotation->setEasingCurve(QEasingCurve::InOutQuad);
//! [6]

//! [7]
    // Flip animation setup
    QPropertyAnimation *smoothFlipRotation = new QPropertyAnimation(flipRotation, "angle");
    QPropertyAnimation *smoothFlipScale = new QPropertyAnimation(pad, "scale");
    QPropertyAnimation *smoothFlipXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothFlipYRotation = new QPropertyAnimation(yRotation, "angle");
    QParallelAnimationGroup *flipAnimation = new QParallelAnimationGroup(this);
    smoothFlipScale->setDuration(500);
    smoothFlipRotation->setDuration(500);
    smoothFlipXRotation->setDuration(500);
    smoothFlipYRotation->setDuration(500);
    smoothFlipScale->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipYRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipScale->setKeyValueAt(0, qvariant_cast<qreal>(1.0));
    smoothFlipScale->setKeyValueAt(0.5, qvariant_cast<qreal>(0.7));
    smoothFlipScale->setKeyValueAt(1, qvariant_cast<qreal>(1.0));
    flipAnimation->addAnimation(smoothFlipRotation);
    flipAnimation->addAnimation(smoothFlipScale);
    flipAnimation->addAnimation(smoothFlipXRotation);
    flipAnimation->addAnimation(smoothFlipYRotation);
//! [7]

//! [8]
    // Flip animation delayed property assignment
    QSequentialAnimationGroup *setVariablesSequence = new QSequentialAnimationGroup;
    QPropertyAnimation *setFillAnimation = new QPropertyAnimation(pad, "fill");
    QPropertyAnimation *setBackItemVisibleAnimation = new QPropertyAnimation(backItem, "visible");
    QPropertyAnimation *setSelectionItemVisibleAnimation = new QPropertyAnimation(selectionItem, "visible");
    setFillAnimation->setDuration(0);
    setBackItemVisibleAnimation->setDuration(0);
    setSelectionItemVisibleAnimation->setDuration(0);
    setVariablesSequence->addPause(250);
    setVariablesSequence->addAnimation(setBackItemVisibleAnimation);
    setVariablesSequence->addAnimation(setSelectionItemVisibleAnimation);
    setVariablesSequence->addAnimation(setFillAnimation);
    flipAnimation->addAnimation(setVariablesSequence);
//! [8]

//! [9]
    // Build the state machine
    QStateMachine *stateMachine = new QStateMachine(this);
    QState *splashState = new QState(stateMachine);
    QState *frontState = new QState(stateMachine);
    QHistoryState *historyState = new QHistoryState(frontState);
    QState *backState = new QState(stateMachine);
//! [9]
//! [10]
    frontState->assignProperty(pad, "fill", false);
    frontState->assignProperty(splash, "opacity", 0.0);
    frontState->assignProperty(backItem, "visible", false);
    frontState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(0.0));
    frontState->assignProperty(selectionItem, "visible", true);
    backState->assignProperty(pad, "fill", true);
    backState->assignProperty(backItem, "visible", true);
    backState->assignProperty(xRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(yRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(180.0));
    backState->assignProperty(selectionItem, "visible", false);
    stateMachine->addDefaultAnimation(smoothXRotation);
    stateMachine->addDefaultAnimation(smoothYRotation);
    stateMachine->addDefaultAnimation(smoothXSelection);
    stateMachine->addDefaultAnimation(smoothYSelection);
    stateMachine->setInitialState(splashState);
//! [10]

//! [11]
    // Transitions
    QEventTransition *anyKeyTransition = new QEventTransition(this, QEvent::KeyPress, splashState);
    anyKeyTransition->setTargetState(frontState);
    anyKeyTransition->addAnimation(smoothSplashMove);
    anyKeyTransition->addAnimation(smoothSplashOpacity);
//! [11]

//! [12]
    QKeyEventTransition *enterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                   Qt::Key_Enter, backState);
    QKeyEventTransition *returnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                    Qt::Key_Return, backState);
    QKeyEventTransition *backEnterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                       Qt::Key_Enter, frontState);
    QKeyEventTransition *backReturnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Return, frontState);
    enterTransition->setTargetState(historyState);
    returnTransition->setTargetState(historyState);
    backEnterTransition->setTargetState(backState);
    backReturnTransition->setTargetState(backState);
    enterTransition->addAnimation(flipAnimation);
    returnTransition->addAnimation(flipAnimation);
    backEnterTransition->addAnimation(flipAnimation);
    backReturnTransition->addAnimation(flipAnimation);
//! [12]

//! [13]
    // Create substates for each icon; store in temporary grid.
    int columns = size.width();
    int rows = size.height();
    QVector< QVector< QState * > > stateGrid;
    stateGrid.resize(rows);
    for (int y = 0; y < rows; ++y) {
        stateGrid[y].resize(columns);
        for (int x = 0; x < columns; ++x)
            stateGrid[y][x] = new QState(frontState);
    }
    frontState->setInitialState(stateGrid[0][0]);
    selectionItem->setPos(pad->iconAt(0, 0)->pos());
//! [13]

//! [14]
    // Enable key navigation using state transitions
    for (int y = 0; y < rows; ++y) {
        for (int x = 0; x < columns; ++x) {
            QState *state = stateGrid[y][x];
            QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                           Qt::Key_Right, state);
            QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Left, state);
            QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Down, state);
            QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Up, state);
            rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]);
            leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]);
            downTransition->setTargetState(stateGrid[(y + 1) % rows][x]);
            upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]);
//! [14]
//! [15]
            RoundRectItem *icon = pad->iconAt(x, y);
            state->assignProperty(xRotation, "angle", -icon->x() / 6.0);
            state->assignProperty(yRotation, "angle", icon->y() / 6.0);
            state->assignProperty(selectionItem, "x", icon->x());
            state->assignProperty(selectionItem, "y", icon->y());
            frontState->assignProperty(icon, "visible", true);
            backState->assignProperty(icon, "visible", false);

            QPropertyAnimation *setIconVisibleAnimation = new QPropertyAnimation(icon, "visible");
            setIconVisibleAnimation->setDuration(0);
            setVariablesSequence->addAnimation(setIconVisibleAnimation);
        }
    }
//! [15]

//! [16]
    // Scene
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setBackgroundBrush(QPixmap(":/images/blue_angle_swirl.jpg"));
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    scene->addItem(pad);
    scene->setSceneRect(scene->itemsBoundingRect());
    setScene(scene);
//! [16]

//! [17]
    // Adjust splash item to scene contents
    const QRectF sbr = splash->boundingRect();
    splash->setPos(-sbr.width() / 2, scene->sceneRect().top() - 2);
    frontState->assignProperty(splash, "y", splash->y() - 100.0);
    scene->addItem(splash);
//! [17]

//! [18]
    // View
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(50, 50);
    setViewportUpdateMode(FullViewportUpdate);
    setCacheMode(CacheBackground);
    setRenderHints(QPainter::Antialiasing
                   | QPainter::SmoothPixmapTransform
                   | QPainter::TextAntialiasing);
#ifndef QT_NO_OPENGL
    setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
#endif

    stateMachine->start();
//! [18]
}
Exemple #19
0
void PianoView::drawBackground(QPainter* p, const QRectF& r)
      {
      if (staff == 0)
            return;
      Score* _score = staff->score();
      setFrameShape(QFrame::NoFrame);

      QRectF r1;
      r1.setCoords(-1000000.0, 0.0, 480.0, 1000000.0);
      QRectF r2;
      r2.setCoords(ticks + MAP_OFFSET, 0.0, 1000000.0, 1000000.0);
      QColor bg(0x71, 0x8d, 0xbe);

      p->fillRect(r, bg);
      if (r.intersects(r1))
            p->fillRect(r.intersected(r1), bg.darker(150));
      if (r.intersects(r2))
            p->fillRect(r.intersected(r2), bg.darker(150));

      //
      // draw horizontal grid lines
      //
      qreal y1 = r.y();
      qreal y2 = y1 + r.height();
      qreal kh = 13.0;
      qreal x1 = r.x();
      qreal x2 = x1 + r.width();

      // int key = floor(y1 / 75);
      int key = floor(y1 / kh);
      qreal y = key * kh;

      for (; key < 75; ++key, y += kh) {
            if (y < y1)
                  continue;
            if (y > y2)
                  break;
            p->setPen(QPen((key % 7) == 5 ? Qt::lightGray : Qt::gray));
            p->drawLine(QLineF(x1, y, x2, y));
            }

      //
      // draw vertical grid lines
      //
      static const int mag[7] = {
            1, 1, 2, 5, 10, 20, 50
            };

      Pos pos1 = pix2pos(x1);
      Pos pos2 = pix2pos(x2);

      //---------------------------------------------------
      //    draw raster
      //---------------------------------------------------

      int bar1, bar2, beat, tick;
      pos1.mbt(&bar1, &beat, &tick);
      pos2.mbt(&bar2, &beat, &tick);

      int n = mag[magStep < 0 ? 0 : magStep];

      bar1 = (bar1 / n) * n;           // round down
      if (bar1 && n >= 2)
            bar1 -= 1;
      bar2 = ((bar2 + n - 1) / n) * n; // round up

      for (int bar = bar1; bar <= bar2;) {
            Pos stick(_score->tempomap(), _score->sigmap(), bar, 0, 0);
            if (magStep > 0) {
                  double x = double(pos2pix(stick));
                  if (x > 0) {
                        p->setPen(QPen(Qt::lightGray, 0.0));
                        p->drawLine(x, y1, x, y2);
                        }
                  else {
                        p->setPen(QPen(Qt::black, 0.0));
                        p->drawLine(x, y1, x, y1);
                        }
                  }
            else {
                  int z = stick.timesig().timesig().numerator();
                  for (int beat = 0; beat < z; beat++) {
                        if (magStep == 0) {
                              Pos xx(_score->tempomap(), _score->sigmap(), bar, beat, 0);
                              int xp = pos2pix(xx);
                              if (xp < 0)
                                    continue;
                              if (xp > 0) {
                                    p->setPen(QPen(beat == 0 ? Qt::lightGray : Qt::gray, 0.0));
                                    p->drawLine(xp, y1, xp, y2);
                                    }
                              else {
                                    p->setPen(QPen(Qt::black, 0.0));
                                    p->drawLine(xp, y1, xp, y2);
                                    }
                              }
                        else {
                              int k;
                              if (magStep == -1)
                                    k = 2;
                              else if (magStep == -2)
                                    k = 4;
                              else if (magStep == -3)
                                    k = 8;
                              else if (magStep == -4)
                                    k = 16;
                              else
                                    k = 32;

                              int n = (MScore::division * 4) / stick.timesig().timesig().denominator();
                              for (int i = 0; i < k; ++i) {
                                    Pos xx(_score->tempomap(), _score->sigmap(), bar, beat, (n * i)/ k);
                                    int xp = pos2pix(xx);
                                    if (xp < 0)
                                          continue;
                                    if (xp > 0) {
                                          p->setPen(QPen(i == 0 && beat == 0 ? Qt::lightGray : Qt::gray, 0.0));
                                          p->drawLine(xp, y1, xp, y2);
                                          }
                                    else {
                                          p->setPen(QPen(Qt::black, 0.0));
                                          p->drawLine(xp, y1, xp, y2);
                                          }
                                    }
                              }
                        }
                  }
            if (bar == 0 && n >= 2)
                  bar += (n-1);
            else
                  bar += n;
            }
      }
void QgsGCPCanvasItem::paint( QPainter* p )
{
  QgsRenderContext context;
  if ( !setRenderContextVariables( p, context ) )
  {
    return;
  }

  p->setRenderHint( QPainter::Antialiasing );

  bool enabled = true;
  QgsPoint worldCoords;
  int id = -1;

  if ( mDataPoint )
  {
    enabled = mDataPoint->isEnabled();
    worldCoords = mDataPoint->mapCoords();
    id = mDataPoint->id();
  }

  p->setOpacity( enabled ? 1.0 : 0.3 );

  // draw the point
  p->setPen( Qt::black );
  p->setBrush( mPointBrush );
  p->drawEllipse( -2, -2, 5, 5 );

  QSettings s;
  bool showIDs = s.value( "/Plugin-GeoReferencer/Config/ShowId" ).toBool();
  bool showCoords = s.value( "/Plugin-GeoReferencer/Config/ShowCoords" ).toBool();

  QString msg;
  if ( showIDs && showCoords )
  {
    msg = QString( "%1\nX %2\nY %3" ).arg( QString::number( id ) ).arg( QString::number( worldCoords.x(), 'f' ) ).arg( QString::number( worldCoords.y(), 'f' ) );
  }
  else if ( showIDs )
  {
    msg = msg = QString::number( id );
  }
  else if ( showCoords )
  {
    msg = QString( "X %1\nY %2" ).arg( QString::number( worldCoords.x(), 'f' ) ).arg( QString::number( worldCoords.y(), 'f' ) );
  }

  if ( !msg.isEmpty() )
  {
    p->setBrush( mLabelBrush );
    QFont textFont( "helvetica" );
    textFont.setPixelSize( fontSizePainterUnits( 12, context ) );
    p->setFont( textFont );
    QRectF textBounds = p->boundingRect( 3 * context.scaleFactor(), 3 * context.scaleFactor(), 5 * context.scaleFactor(), 5 * context.scaleFactor(), Qt::AlignLeft, msg );
    mTextBoxRect = QRectF( textBounds.x() - context.scaleFactor() * 1, textBounds.y() - context.scaleFactor() * 1, \
                           textBounds.width() + 2 * context.scaleFactor(), textBounds.height() + 2 * context.scaleFactor() );
    p->drawRect( mTextBoxRect );
    p->drawText( textBounds, Qt::AlignLeft, msg );
  }

  if ( data( 0 ) != "composer" ) //draw residuals only on screen
  {
    drawResidualArrow( p, context );
  }
}
Exemple #21
0
void QArcItem::SetPattern(int nPATTERN)
{
    nPatternType = nPATTERN; //样式类型
    //QRectF nrect(0,0,qWidth,qHeight);
    QRectF nrect = this->m_qrcEllipseBndRect;
    QLinearGradient gradient(nrect.topLeft(),nrect.bottomRight());
    QRadialGradient Radial(nrect.center(),nrect.width()/2,nrect.center());
    gradient.setSpread(QGradient::PadSpread);//	RepeatSpread

    QBrush br=brush();
    br.setColor(nFrontColor); //设置前景色即样式颜色

    switch(nPATTERN)
    {
//    case 0:br.setStyle(Qt::NoBrush);break;
//    case 1:br.setColor(nBackColor);br.setStyle(Qt::SolidPattern);break;
//    case 2:br.setStyle(Qt::Dense1Pattern);break;
//    case 3:br.setStyle(Qt::Dense2Pattern);break;
//    case 4:br.setStyle(Qt::Dense3Pattern);break;
//    case 5:br.setStyle(Qt::Dense4Pattern);break;
//    case 6:br.setStyle(Qt::Dense5Pattern);break;
//    case 7:br.setStyle(Qt::Dense6Pattern);break;
//    case 8:br.setStyle(Qt::Dense7Pattern);break;

//    case 9:br.setStyle(Qt::HorPattern);break;//setBrush(Qt::HorPattern);break;
//    case 10:br.setStyle(Qt::VerPattern);break;
//    case 11:br.setStyle(Qt::CrossPattern);break;

//    case 12:br.setStyle(Qt::BDiagPattern);break;
//    case 13:br.setStyle(Qt::FDiagPattern);break;
//    case 14:br.setStyle(Qt::DiagCrossPattern);break;
    case 0:br.setStyle(Qt::NoBrush);break;//透明
    case 1:br.setColor(nBackColor);br.setStyle(Qt::SolidPattern);break;//纯色

    case 2: //横向过度
        gradient.setStart(nrect.x(),nrect.y()+nrect.height());
        gradient.setColorAt(0,nFrontColor );
        gradient.setColorAt(1,nBackColor );
        break;
    case 3: //横向对称过度
        gradient.setStart(nrect.x(),nrect.y()+nrect.height());
        gradient.setColorAt(0,nFrontColor );
        gradient.setColorAt(0.5,nBackColor );
        gradient.setColorAt(1,nFrontColor );
        break;
    case 4: //纵向过度
        gradient.setStart(nrect.x()+nrect.width(),nrect.y());
        gradient.setColorAt(0,nFrontColor  );
        gradient.setColorAt(1,nBackColor);
        break;
    case 5: //纵向对称过度
        gradient.setStart(nrect.x()+nrect.width(),nrect.y());
        gradient.setColorAt(0,nFrontColor  );
        gradient.setColorAt(0.5,nBackColor);
        gradient.setColorAt(1,nFrontColor );
        break;
    case 6: //斜上过度
        gradient.setColorAt(0,nFrontColor );
        gradient.setColorAt(1,nBackColor );
        break;
    case 7: //斜上对称过度
        gradient.setColorAt(0,nFrontColor );
        gradient.setColorAt(0.5,nBackColor );
        gradient.setColorAt(1,nFrontColor );
        break;
    case 8: //斜下过度
        gradient.setStart(nrect.x(),nrect.y()+nrect.height());
        gradient.setFinalStop(nrect.x()+nrect.width(),nrect.y());
        gradient.setColorAt(0,nBackColor );
        gradient.setColorAt(1,nFrontColor);
        break;
    case 9: //斜下对称过度
        gradient.setStart(nrect.x(),nrect.y()+nrect.height());
        gradient.setFinalStop(nrect.x()+nrect.width(),nrect.y());
        gradient.setColorAt(0,nFrontColor );
        gradient.setColorAt(0.5,nBackColor );
        gradient.setColorAt(1,nFrontColor );
        break;
    case 10: //右上角辐射
        gradient.setStart(nrect.x()+nrect.width(),nrect.y());
        gradient.setFinalStop(nrect.x(),nrect.y()+nrect.height());
        gradient.setColorAt(0,nBackColor );
        gradient.setColorAt(1,nFrontColor );
        break;
    case 11: //左上角辐射
        gradient.setColorAt(0,nBackColor );
        gradient.setColorAt(1, nFrontColor);
        break;
    case 12: //中心辐射
        Radial.setColorAt(0,nBackColor );
        Radial.setColorAt(1,nFrontColor );
        setBrush(Radial);
        return;
        break;
    case 13: //待操作
        Radial.setFocalPoint(nrect.x(),nrect.y()+nrect.height()/2);
        Radial.setColorAt(0,nBackColor );
        Radial.setColorAt(1,nFrontColor );
        setBrush(Radial);
        return;
        break;

    default:
        break;
    }

    if(nPATTERN >= 2 )
    {
        setBrush(gradient);
    }
    else
    {
        setBrush(br);
    }
}
Exemple #22
0
void Node::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    QPointF newPos(event->scenePos());

    if (k->notChange) {
        k->notChange = false;
    } else {
        if (k->action == Scale) {
            QRectF rect = k->parent->sceneBoundingRect();
            QRectF parentRect  = k->parent->sceneBoundingRect();
            QRectF parentSquare  = k->parent->boundingRect();
            
            // SQA: Lines for debugging purposes
            /*
            scene()->addRect(rect, QPen(Qt::red));
            scene()->addRect(parentRect, QPen(Qt::green));
            */
            
            switch (k->typeNode) {
                    case TopLeft:
                    {
                         k->manager->setAnchor(parentSquare.bottomRight());
                         rect.setTopLeft(newPos);
                         break;
                    }
                    case TopRight:
                    {
                         k->manager->setAnchor(parentSquare.bottomLeft());
                         rect.setTopRight(newPos);
                         break;
                    }
                    case BottomRight:
                    {
                         k->manager->setAnchor(parentSquare.topLeft());
                         rect.setBottomRight(newPos);
                         break;
                    }
                    case BottomLeft:
                    {
                         k->manager->setAnchor(parentSquare.topRight());
                         rect.setBottomLeft(newPos);
                         break;
                    }
                    case Center:
                    {
                         break;
                    }
            };
            
            float sx = 1, sy = 1;
            sx = static_cast<float>(rect.width()) / static_cast<float>(parentRect.width());
            sy = static_cast<float>(rect.height()) / static_cast<float>(parentRect.height());

            if (k->manager->proportionalScale()) {
                k->manager->scale(sx, sx);
            } else {
                if (sx > 0 && sy > 0) {
                    k->manager->scale(sx, sy);
                } else {
                    if (sx > 0)
                        k->manager->scale(sx, 1);

                    if (sy > 0)
                        k->manager->scale(1, sy);
                }
            }
        } else if (k->action == Rotate) {
                   QPointF p1 = newPos;
                   QPointF p2 = k->parent->sceneBoundingRect().center();
                   k->manager->setAnchor(k->parent->boundingRect().center());
                
                   double a = (180 * TupGraphicalAlgorithm::angleForPos(p1, p2)) / M_PI;
                   k->manager->rotate(a-45);
        }
    }

    if (k->typeNode == Center) {
        k->parent->moveBy(event->scenePos().x() - scenePos().x() , event->scenePos().y() - scenePos().y());
        event->accept();
    }
}
/*
  Extract all layout relevant data from the plot components
*/
void QwtPlotLayout::LayoutData::init( const QwtPlot *plot, const QRectF &rect )
{
    // legend

    if ( plot->legend() )
    {
        legend.frameWidth = plot->legend()->frameWidth();
        legend.hScrollExtent =
            plot->legend()->scrollExtent( Qt::Horizontal );
        legend.vScrollExtent =
            plot->legend()->scrollExtent( Qt::Vertical );

        const QSize hint = plot->legend()->sizeHint();

        int w = qMin( hint.width(), qFloor( rect.width() ) );
        int h = plot->legend()->heightForWidth( w );
        if ( h <= 0 )
            h = hint.height();

        if ( h > rect.height() )
            w += legend.hScrollExtent;

        legend.hint = QSize( w, h );
    }

    // title

    title.frameWidth = 0;
    title.text = QwtText();

    if ( plot->titleLabel() )
    {
        const QwtTextLabel *label = plot->titleLabel();
        title.text = label->text();
        if ( !( title.text.testPaintAttribute( QwtText::PaintUsingTextFont ) ) )
            title.text.setFont( label->font() );

        title.frameWidth = plot->titleLabel()->frameWidth();
    }

    // footer

    footer.frameWidth = 0;
    footer.text = QwtText();

    if ( plot->footerLabel() )
    {
        const QwtTextLabel *label = plot->footerLabel();
        footer.text = label->text();
        if ( !( footer.text.testPaintAttribute( QwtText::PaintUsingTextFont ) ) )
            footer.text.setFont( label->font() );

        footer.frameWidth = plot->footerLabel()->frameWidth();
    }

    // scales

    for ( int axis = 0; axis < QwtPlot::axisCnt; axis++ )
    {
        if ( plot->axisEnabled( axis ) )
        {
            const QwtScaleWidget *scaleWidget = plot->axisWidget( axis );

            scale[axis].isEnabled = true;

            scale[axis].scaleWidget = scaleWidget;

            scale[axis].scaleFont = scaleWidget->font();

            scale[axis].start = scaleWidget->startBorderDist();
            scale[axis].end = scaleWidget->endBorderDist();

            scale[axis].baseLineOffset = scaleWidget->margin();
            scale[axis].tickOffset = scaleWidget->margin();
            if ( scaleWidget->scaleDraw()->hasComponent(
                QwtAbstractScaleDraw::Ticks ) )
            {
                scale[axis].tickOffset +=
                    scaleWidget->scaleDraw()->maxTickLength();
            }

            scale[axis].dimWithoutTitle = scaleWidget->dimForLength(
                QWIDGETSIZE_MAX, scale[axis].scaleFont );

            if ( !scaleWidget->title().isEmpty() )
            {
                scale[axis].dimWithoutTitle -=
                    scaleWidget->titleHeightForWidth( QWIDGETSIZE_MAX );
            }
        }
        else
        {
            scale[axis].isEnabled = false;
            scale[axis].start = 0;
            scale[axis].end = 0;
            scale[axis].baseLineOffset = 0;
            scale[axis].tickOffset = 0.0;
            scale[axis].dimWithoutTitle = 0;
        }
    }

    // canvas

    plot->canvas()->getContentsMargins( 
        &canvas.contentsMargins[ QwtPlot::yLeft ], 
        &canvas.contentsMargins[ QwtPlot::xTop ],
        &canvas.contentsMargins[ QwtPlot::yRight ],
        &canvas.contentsMargins[ QwtPlot::xBottom ] );
}
 QImage render(qreal dpiX, qreal dpiY, const QRectF& rect) {
   return m_page->renderToImage(dpiX, dpiY, rect.x(), rect.y(), rect.width(), rect.height());
 }
Exemple #25
0
void QtGradientWidget::mousePressEvent(QMouseEvent *e)
{
    if (e->button() != Qt::LeftButton)
        return;

    QPoint p = e->pos();
    if (d_ptr->m_gradientType == QGradient::LinearGradient) {
        QPointF startPoint = d_ptr->toViewport(d_ptr->m_startLinear);
        double x = p.x() - startPoint.x();
        double y = p.y() - startPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::StartLinearHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF endPoint = d_ptr->toViewport(d_ptr->m_endLinear);
        x = p.x() - endPoint.x();
        y = p.y() - endPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::EndLinearHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }
    } else if (d_ptr->m_gradientType == QGradient::RadialGradient) {
        QPointF focalPoint = d_ptr->toViewport(d_ptr->m_focalRadial);
        double x = p.x() - focalPoint.x();
        double y = p.y() - focalPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 9) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::FocalRadialHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralRadial);
        x = p.x() - centralPoint.x();
        y = p.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::CentralRadialHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF central = d_ptr->toViewport(d_ptr->m_centralRadial);
        QRectF r = d_ptr->pointRect(central, 2 * d_ptr->m_handleSize / 3);
        QRectF r1(0, r.y(), size().width(), r.height());
        QRectF r2(r.x(), 0, r.width(), r.y());
        QRectF r3(r.x(), r.y() + r.height(), r.width(), size().height() - r.y() - r.height());
        QPointF pF(p.x(), p.y());
        if (r1.contains(pF) || r2.contains(pF) || r3.contains(pF)) {
            x = pF.x() / size().width() - d_ptr->m_centralRadial.x();
            y = pF.y() / size().height() - d_ptr->m_centralRadial.y();
            double clickRadius = sqrt(x * x + y * y);
            //d_ptr->m_radiusOffset = d_ptr->m_radiusRadial - clickRadius;
            d_ptr->m_radiusFactor = d_ptr->m_radiusRadial / clickRadius;
            if (d_ptr->m_radiusFactor == 0)
                d_ptr->m_radiusFactor = 1;
            d_ptr->m_dragRadius = d_ptr->m_radiusRadial;
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::RadiusRadialHandle;
            mouseMoveEvent(e);
            update();
            return;
        }
    } else if (d_ptr->m_gradientType == QGradient::ConicalGradient) {
        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralConical);
        double x = p.x() - centralPoint.x();
        double y = p.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::CentralConicalHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }
        double radius = size().width();
        if (size().height() < radius)
            radius = size().height();
        radius /= 2;
        double corr = d_ptr->m_handleSize / 3;
        radius -= corr;
        QPointF vp = d_ptr->toViewport(d_ptr->m_centralConical);
        x = p.x() - vp.x();
        y = p.y() - vp.y();
        if (((radius - corr) * (radius - corr) < (x * x + y * y)) &&
            ((radius + corr) * (radius + corr) > (x * x + y * y))) {
            QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);
            QPointF current(e->pos().x(), e->pos().y());
            x = current.x() - central.x();
            y = current.y() - central.y();
            x /= size().width() / 2;
            y /= size().height() / 2;
            double r = sqrt(x * x + y * y);

            double arcSin = asin(y / r);
            double arcCos = acos(x / r);

            double angle = arcCos * 180 / M_PI;
            if (arcSin > 0) {
                angle = -angle;
            }

            d_ptr->m_angleOffset = d_ptr->m_angleConical - angle;
            d_ptr->m_dragAngle = d_ptr->m_angleConical;
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::AngleConicalHandle;
            update();
            return;
        }
    }
}
Exemple #26
0
/*!
   Draw the Wheel's ticks

   \param painter Painter
   \param rect Rectangle for the wheel
*/
void QwtWheel::drawTicks( QPainter *painter, const QRectF &rect )
{
    if ( maxValue() == minValue() || d_data->totalAngle == 0.0 )
    {
        return;
    }

    const QPen lightPen( palette().color( QPalette::Light ), 
        0, Qt::SolidLine, Qt::FlatCap );
    const QPen darkPen( palette().color( QPalette::Dark ), 
        0, Qt::SolidLine, Qt::FlatCap );

    const double sign = ( minValue() < maxValue() ) ? 1.0 : -1.0;
    const double cnvFactor = qAbs( d_data->totalAngle / ( maxValue() - minValue() ) );
    const double halfIntv = 0.5 * d_data->viewAngle / cnvFactor;
    const double loValue = value() - halfIntv;
    const double hiValue = value() + halfIntv;
    const double tickWidth = 360.0 / double( d_data->tickCnt ) / cnvFactor;
    const double sinArc = qFastSin( d_data->viewAngle * M_PI / 360.0 );

    if ( orientation() == Qt::Horizontal )
    {
        const double halfSize = rect.width() * 0.5;

        double l1 = rect.top() + d_data->wheelBorderWidth;
        double l2 = rect.bottom() - d_data->wheelBorderWidth - 1;

        // draw one point over the border if border > 1
        if ( d_data->wheelBorderWidth > 1 )
        {
            l1--;
            l2++;
        }

        const double maxpos = rect.right() - 2;
        const double minpos = rect.left() + 2;

        // draw tick marks
        for ( double tickValue = ::ceil( loValue / tickWidth ) * tickWidth;
            tickValue < hiValue; tickValue += tickWidth )
        {
            const double angle = ( tickValue - value() ) * M_PI / 180.0;
            const double s = qFastSin( angle * cnvFactor );

            const double tickPos = 
                rect.right() - halfSize * ( sinArc + sign * s ) / sinArc;

            if ( ( tickPos <= maxpos ) && ( tickPos > minpos ) )
            {
                painter->setPen( darkPen );
                painter->drawLine( QPointF( tickPos - 1 , l1 ), 
                    QPointF( tickPos - 1,  l2 ) );
                painter->setPen( lightPen );
                painter->drawLine( QPointF( tickPos, l1 ), 
                    QPointF( tickPos, l2 ) );
            }
        }
    }
    else // Qt::Vertical
    {
        const double halfSize = rect.height() * 0.5;

        double l1 = rect.left() + d_data->wheelBorderWidth;
        double l2 = rect.right() - d_data->wheelBorderWidth - 1;

        if ( d_data->wheelBorderWidth > 1 )
        {
            l1--;
            l2++;
        }

        const double maxpos = rect.bottom() - 2;
        const double minpos = rect.top() + 2;

        for ( double tickValue = ::ceil( loValue / tickWidth ) * tickWidth;
            tickValue < hiValue; tickValue += tickWidth )
        {
            const double angle = ( tickValue - value() ) * M_PI / 180.0;
            const double s = qFastSin( angle * cnvFactor );

            const double tickPos = 
                rect.y() + halfSize * ( sinArc + sign * s ) / sinArc;

            if ( ( tickPos <= maxpos ) && ( tickPos > minpos ) )
            {
                painter->setPen( darkPen );
                painter->drawLine( QPointF( l1, tickPos - 1 ), 
                    QPointF( l2, tickPos - 1 ) );
                painter->setPen( lightPen );
                painter->drawLine( QPointF( l1, tickPos ), 
                    QPointF( l2, tickPos ) );
            }
        }
    }
}
void RelationshipView::configureLine(void)
{
	if(!configuring_line)
	{
		BaseRelationship *base_rel=this->getSourceObject();
		Relationship *rel=dynamic_cast<Relationship *>(base_rel);
		vector<QPointF> points, fk_points, pk_points;
		QGraphicsLineItem *lin=nullptr;
		QPointF pos, p_int, p_central[2], pk_pnt, fk_pnt;
		QRectF rect;
		QPen pen;
		QGraphicsPolygonItem *pol=nullptr;
		QPolygonF pol_aux;
		QString tool_tip;
		QGraphicsItem *item=nullptr;
		int i, i1, count, idx_lin_desc=0;
		bool bidirectional=base_rel->isBidirectional();

		configuring_line=true;
		pen.setCapStyle(Qt::RoundCap);

		if(base_rel->isSelfRelationship())
		{
			double fator=font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE;

			/* Sefl-relationshihp line format:

						+----<>
						|     |
		 ----------   |
		 | Table  |---+
		 ----------

		 This line cannot be moved or have points added */
			pos=tables[0]->pos();
			rect=tables[0]->boundingRect();

			p_central[0].setX(pos.x() + rect.width());
			p_central[0].setY(pos.y() + (rect.height()/2.5f));

			p_central[1].setX(pos.x() + (rect.width()/1.5f));
			p_central[1].setY(pos.y());

			points.push_back(QPointF(p_central[0].x() + (10 * fator),  p_central[0].y()));
			points.push_back(QPointF(p_central[0].x() + (10 * fator),  p_central[1].y() - (10 * fator)));
			points.push_back(QPointF(p_central[1].x(),  p_central[1].y() - (10 * fator)));
			base_rel->setPoints(points);
		}
		else
		{
			Relationship *rel=dynamic_cast<Relationship *>(base_rel);
			bool rel_1n=( !bidirectional &&
										(base_rel->getRelationshipType()==Relationship::RELATIONSHIP_11 ||
										 base_rel->getRelationshipType()==Relationship::RELATIONSHIP_1N ||
										 base_rel->getRelationshipType()==Relationship::RELATIONSHIP_FK));

			if(rel &&
				 rel->getRelationshipType()==Relationship::RELATIONSHIP_11 &&
				 rel->isIdentifier())
			{
				tables[0]=dynamic_cast<BaseTableView *>(rel->getReferenceTable()->getReceiverObject());
				tables[1]=dynamic_cast<BaseTableView *>(rel->getReceiverTable()->getReceiverObject());
			}

			if(line_conn_mode==CONNECT_CENTER_PNTS || !rel_1n)
			{
				vector<vector<QGraphicsLineItem *> *> ref_lines={ &fk_lines, &pk_lines };

				for(i=0; i < 2; i++)
					p_central[i]=tables[i]->getCenter();

				//Destroying the fk and pk connection lines when the line mode changes
				for(i=0; i < 2; i++)
				{
					while(!ref_lines[i]->empty())
					{
						item=ref_lines[i]->back();
						ref_lines[i]->pop_back();
						this->removeFromGroup(item);
						delete(item);
					}
				}
			}
			else if(line_conn_mode==CONNECT_FK_TO_PK && rel_1n)
			{
				QPointF pnt;
				QRectF rec_tab_rect, ref_tab_rect;
				double fk_py=0, pk_py=0, fk_px=0, pk_px=0;
				vector<Constraint *> fks;
				Table *ref_tab=nullptr, *rec_tab=nullptr;
				TableView *ref_tab_view=nullptr, *rec_tab_view=nullptr;
				unsigned cnt=0, i=0, pk_pnt_type=0, fk_pnt_type=0;

				if(!rel)
				{
					ref_tab=dynamic_cast<Table *>(base_rel->getTable(BaseRelationship::DST_TABLE));
					rec_tab=dynamic_cast<Table *>(base_rel->getTable(BaseRelationship::SRC_TABLE));
				}
				else
				{
					ref_tab=rel->getReferenceTable();
					rec_tab=rel->getReceiverTable();
				}

        rec_tab->getForeignKeys(fks, true, ref_tab);
				ref_tab_view=dynamic_cast<TableView *>(ref_tab->getReceiverObject());
				rec_tab_view=dynamic_cast<TableView *>(rec_tab->getReceiverObject());

				//Create the table's rectangles to detect where to connect the relationship
				ref_tab_rect=QRectF(ref_tab_view->pos(), ref_tab_view->boundingRect().size());

				//In this case the receiver table rect Y must be equal to reference table Y in order to do the correct comparison
				rec_tab_rect=QRectF(QPointF(rec_tab_view->pos().x(),
																		ref_tab_view->pos().y()), rec_tab_view->boundingRect().size());

				if(ref_tab_rect.intersects(rec_tab_rect))
				{
					//Connects the rectangle at the same sides on both tables
					if(rec_tab_rect.center().x() >= ref_tab_rect.center().x())
						pk_pnt_type=fk_pnt_type=BaseTableView::LEFT_CONN_POINT;
					else if(rec_tab_rect.center().x() < ref_tab_rect.center().x())
						pk_pnt_type=fk_pnt_type=BaseTableView::RIGHT_CONN_POINT;
				}
				else
				{
					//Connecting the relationship on the opposite sides depending on the tables' position
					if(ref_tab_rect.right() <= rec_tab_rect.left())
					{
						pk_pnt_type=BaseTableView::RIGHT_CONN_POINT;
						fk_pnt_type=BaseTableView::LEFT_CONN_POINT;
					}
					else
					{
						pk_pnt_type=BaseTableView::LEFT_CONN_POINT;
						fk_pnt_type=BaseTableView::RIGHT_CONN_POINT;
					}
				}

        for(auto &constr : fks)
				{
					cnt=constr->getColumnCount(Constraint::SOURCE_COLS);

					for(i=0; i < cnt; i++)
					{
						pnt=rec_tab_view->getConnectionPoints(constr->getColumn(i, Constraint::SOURCE_COLS), fk_pnt_type);
						fk_py+=pnt.y();
						fk_px=pnt.x();
						fk_points.push_back(this->mapFromItem(rec_tab_view, pnt));

						pnt=ref_tab_view->getConnectionPoints(constr->getColumn(i, Constraint::REFERENCED_COLS), pk_pnt_type);
						pk_py+=pnt.y();
						pk_px=pnt.x();
						pk_points.push_back(this->mapFromItem(ref_tab_view, pnt));
					}
				}

				if(!fks.empty())
				{
					double pk_dx=(pk_pnt_type==BaseTableView::LEFT_CONN_POINT ? -CONN_LINE_LENGTH : CONN_LINE_LENGTH),
								fk_dx=(fk_pnt_type==BaseTableView::LEFT_CONN_POINT ? -CONN_LINE_LENGTH : CONN_LINE_LENGTH);

					pk_pnt=this->mapFromItem(ref_tab_view, QPointF(pk_px + pk_dx, pk_py/pk_points.size()));
					fk_pnt=this->mapFromItem(rec_tab_view, QPointF(fk_px + fk_dx, fk_py/fk_points.size()));

					if(base_rel->getRelationshipType()==Relationship::RELATIONSHIP_FK)
					{
						p_central[1]=pk_pnt;
						p_central[0]=fk_pnt;
					}
					else
					{
						p_central[0]=pk_pnt;
						p_central[1]=fk_pnt;
					}
				}
        else
        {
          /* Fallback configuration: If no fk was found in the receiver table uses
             the tables' center points to configure the line in order to avoid glitched lines.
             This situation may happen when the relationship is being validated and the needed fks was not
             created yet. In a second interaction of the rel. validation they are created
             and the relationship is properly configured */
          if(base_rel->getRelationshipType()==Relationship::RELATIONSHIP_FK)
          {
            p_central[1]=pk_pnt=ref_tab_view->getCenter();
            p_central[0]=fk_pnt=rec_tab_view->getCenter();
          }
          else
          {
            p_central[0]=pk_pnt=ref_tab_view->getCenter();
            p_central[1]=fk_pnt=rec_tab_view->getCenter();
          }
        }
			}

			points=base_rel->getPoints();
			count=points.size();
			pol_aux.append(QPointF(0,0)); pol_aux.append(QPointF(5,0));
			pol_aux.append(QPointF(5,5)); pol_aux.append(QPointF(0,5));

			for(i=0; i < count; i++)
			{
				if(i >= static_cast<int>(graph_points.size()))
				{
					pol=new QGraphicsPolygonItem;
					graph_points.push_back(pol);
					pol->setZValue(0);
					pol->setPolygon(pol_aux);
					pol->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::OBJ_SELECTION));
					pol->setPen(BaseObjectView::getBorderStyle(ParsersAttributes::OBJ_SELECTION));
					this->addToGroup(pol);
				}
				else
					pol=graph_points[i];

        pol->setPos(points[i]);
        pol->moveBy(-GRAPHIC_PNT_RADIUS/2.5, -GRAPHIC_PNT_RADIUS/2.5);
				pol->setVisible(this->isSelected());
			}

			//Destroy the graphical points not used
			i=graph_points.size()-1;
			while(i > count-1)
			{
				item=graph_points.back();
				graph_points.pop_back();
				this->removeFromGroup(item);
				delete(item);
				i--;
			}
		}

		conn_points[0]=p_central[0];
		conn_points[1]=p_central[1];

		//Configuring the relationship line color
		if(base_rel->getCustomColor()!=Qt::transparent)
			//Using custom color
			pen.setColor(base_rel->getCustomColor());
		else
			//Using the default color
			pen=BaseObjectView::getBorderStyle(ParsersAttributes::RELATIONSHIP);

		//For dependency relationships the line is dashed
		if(base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_DEP)
			pen.setStyle(Qt::DashLine);

		points.insert(points.begin(),p_central[0]);
		points.push_back(p_central[1]);

		/* For identifier relationships an additional point is created on the center of the
		 line that supports the descriptor in order to modify the line thickness on the
		 weak entity side */
		if(rel && rel->isIdentifier())
		{
			//Calculates the index of the initial point, on the line that supports the descriptor
			idx_lin_desc=(points.size()/2);
			p_central[0]=points[idx_lin_desc];

			//Gets the second line point
			if(idx_lin_desc + 1 > static_cast<int>(points.size()))
				p_central[1]=points[idx_lin_desc+1];
			else
				p_central[1]=points[idx_lin_desc-1];

			//Calculates the middle point and inserts it on the point vector
			p_int.setX((p_central[0].x() + p_central[1].x())/2.0f);
			p_int.setY((p_central[0].y() + p_central[1].y())/2.0f);
			points.insert(points.begin() + idx_lin_desc, p_int);
		}

		if(line_conn_mode==CONNECT_FK_TO_PK)
		{
			vector<QPointF> ref_points={ fk_pnt, pk_pnt };
			vector<vector<QPointF> *> ref_pnt_vects={ &fk_points, &pk_points };
			vector<vector<QGraphicsLineItem *> *> ref_lines={ &fk_lines, &pk_lines };
			vector<QPointF> *ref_pnt=nullptr;
			vector<QGraphicsLineItem *> *ref_lin=nullptr;

			for(unsigned vet_idx=0; vet_idx < 2; vet_idx++)
			{
				ref_pnt=ref_pnt_vects[vet_idx];
				ref_lin=ref_lines[vet_idx];
				count=ref_pnt->size();

				for(i=0; i < count; i++)
				{
					if(i >= static_cast<int>(ref_lin->size()))
					{
						lin=new QGraphicsLineItem;
						lin->setZValue(-1);
						ref_lin->push_back(lin);
						this->addToGroup(lin);
					}
					else
						lin=ref_lin->at(i);

					//If the relationship is identifier or bidirectional, the line has its thickness modified
					if(rel && (rel->isIdentifier() && vet_idx==0))
						pen.setWidthF(1.75f);
					else
						pen.setWidthF(1.15f);

					lin->setLine(QLineF(ref_pnt->at(i), ref_points[vet_idx]));
					lin->setPen(pen);
				}

				//Destroy the unused pk or fk lines
				i=ref_lin->size()-1;
				while(i > static_cast<int>(count-1))
				{
					item=ref_lin->back();
					ref_lin->pop_back();
					this->removeFromGroup(item);
					delete(item);
					i--;
				}
			}
		}

		//Create the relationship lines
		count=points.size();
		for(i=0; i < count-1; i++)
		{
			if(i >= static_cast<int>(lines.size()))
			{
				lin=new QGraphicsLineItem;
				lin->setZValue(-1);
				lines.push_back(lin);
				this->addToGroup(lin);
			}
			else
				lin=lines[i];

			//If the relationship is identifier or bidirectional, the line has its thickness modified
			if(bidirectional || (rel && (rel->isIdentifier() && i >= idx_lin_desc)))
				pen.setWidthF(1.75f);
			else
				pen.setWidthF(1.15f);

			lin->setLine(QLineF(points[i], points[i+1]));
			lin->setPen(pen);
		}

		//Removing unused lines
		if(!base_rel->isSelfRelationship())
		{
			i=points.size()-1;
			i1=lines.size();
			while(i1 > i)
			{
				item=lines.back();
				lines.pop_back();
				this->removeFromGroup(item);
				delete(item);
				i1--;
			}
		}

    this->configureDescriptor();
		this->configureLabels();
		this->configureProtectedIcon();

    configuring_line=false;

		/* Making a little tweak on the foreign key type name. Despite being of class BaseRelationship,
		for semantics purposes shows the type of this relationship as "Relationship" unlike "Link" */
		if(base_rel->getRelationshipType()==BaseRelationship::RELATIONSHIP_FK)
      tool_tip=base_rel->getName(true) +
               QString(" (") + BaseObject::getTypeName(OBJ_RELATIONSHIP) + QString(")");
		else
      tool_tip=base_rel->getName(true) +
               QString(" (") + base_rel->getTypeName() + QString(")");

    tool_tip += QString("\nId: %1").arg(base_rel->getObjectId());
		this->setToolTip(tool_tip);

		for(i=0; i < 3; i++)
		{
			if(labels[i])
				labels[i]->setToolTip(tool_tip);
		}

		descriptor->setToolTip(tool_tip);
	}
}
	FormComboBoxPrivate( FormComboBox * parent, const QRectF & rect )
		:	q( parent )
		,	m_rect( QRectF( rect.x(), rect.y(), rect.width(), 25.0 ) )
		,	m_proxy( 0 )
	{
	}
void TopologyNode::paintSubIcons(QPainter *painter,const QRectF &itemRect)
{
    if(mNodeFlags & NF_ISVM)
    {
        QPixmap vmPixmap(getImagePath(MII_VMFLAG));
        painter->drawPixmap(itemRect.left() + itemRect.width() - vmPixmap.width() - 5
                            ,itemRect.top() + (itemRect.height() - vmPixmap.height()) / 2 , vmPixmap);
    }
    if(!sBDM)
    {
        sBDM=BlockDeviceManager::GetSingletonPtr();
    }
    if((mNodeFlags & NF_BLOCKED) && sBDM &&
       (sBDM->state()!=BLOCKDEVICE_FSM::FS_CLOSED
        &&sBDM->state()!=BLOCKDEVICE_FSM::FS_CLOSED_ADMIN)
       )
    {
        QPixmap vmPixmap(getImagePath(MII_BLOCKFLAG));
        painter->drawPixmap(itemRect.left() + /*itemRect.width() - vmPixmap.width() -*/+ 5
                            ,itemRect.top() + (itemRect.height() - vmPixmap.height()) / 2 , vmPixmap);

    }

    if(!(mNodeFlags & (NF_ISLOCALHOST|NF_ISCENTRALROUTER)))
    {
#ifdef USE_RDP
        if((mNodeFlags & NF_RDP_ENABLED) &&(sMapFlags & MF_USE_RDP_SCAN))
        {

            QPixmap vmPixmap(getImagePath(MII_RDPFLAG));
            painter->drawPixmap(itemRect.left() + itemRect.width()/2-vmPixmap.width()/2
                                ,itemRect.top() + (itemRect.height() - vmPixmap.height()) / 2 , vmPixmap);

        }
        else
        {
#endif

#ifdef USE_PUTTY
        if((mNodeFlags & NF_PUTTY_ENABLED) && (sMapFlags & MF_USE_PUTTY_SCAN))
        {
            QPixmap vmPixmap(getImagePath(MII_PUTTYFLAG));
            painter->drawPixmap(itemRect.left() + itemRect.width()/2-vmPixmap.width()/2
                                ,itemRect.top() + (itemRect.height() - vmPixmap.height()) / 2 , vmPixmap);

        }
#endif

#ifdef USE_RDP
        }
#endif
    }
//    if((false
//#ifdef USE_RDP
//        ||  ((mNodeFlags & NF_RDP_ENABLED) &&(sMapFlags & MF_USE_RDP_SCAN))
//#endif
//#ifdef USE_PUTTY
//        || ((mNodeFlags & NF_PUTTY_ENABLED) && (sMapFlags & MF_USE_PUTTY_SCAN))
//#endif
//        )&&  !(mNodeFlags & (NF_ISLOCALHOST|NF_ISCENTRALROUTER)))
//    {
//        int img_idx=-1;
//#ifdef USE_RDP
//         img_idx=MII_RDPFLAG;
//#endif
//#ifdef USE_PUTTY
//        img_idx=MII_PUTTYFLAG;
//#endif
//        Q_ASSERT(img_idx != -1);
//        QPixmap vmPixmap(getImagePath(img_idx));
//        painter->drawPixmap(itemRect.left() + itemRect.width()/2-vmPixmap.width()/2
//                            ,itemRect.top() + (itemRect.height() - vmPixmap.height()) / 2 , vmPixmap);

//    }

}
void SAGraphicsLabelItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                                QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->setRenderHints(painter->renderHints() | QPainter::Antialiasing |
                            QPainter::SmoothPixmapTransform);
    painter->setFont(mShrift);

    QRectF r = rect();
    r.setWidth(r.width() - 1);

    if (!mFone) {
        painter->setPen(mCvet);
#if defined(Q_OS_UNIX)
        painter->drawText(r.adjusted(0, 5, 0, 0), mVyiravn, mPodpis);
#elif defined(Q_OS_WIN)
        painter->drawText(r.adjusted(0, 0, 0, 0), mVyiravn, mPodpis);
#endif
        return;
    }

    QColor bgColor(mCvet);
    bool black = bgColor == Qt::black;
    if (black)
        bgColor = QColor(30, 30, 30);

    QColor lighter1 = bgColor.lighter(black ? 400 : 200);
    QColor lighter2 = bgColor.lighter(black ? 320 : 120);
    QColor darker1 = bgColor.darker(115);

    QLinearGradient lgr(r.topLeft(), r.bottomLeft());
    lgr.setColorAt(0, lighter1);
    lgr.setColorAt(0.4, darker1);
    lgr.setColorAt(0.6, darker1);
    lgr.setColorAt(1, lighter2);

    painter->setPen(bgColor);
    painter->setBrush(QBrush(lgr));
    painter->drawRoundedRect(r, 3, 3);

    painter->setBrush(Qt::white);
    painter->setPen(QPen(Qt::white, 0.01));
    painter->setOpacity(0.3);
    painter->drawRoundedRect(r.x(), r.y(), r.width(), r.height() / 2 - 2, 3, 3);

    painter->setPen(mCvet);
    painter->setBrush(QBrush(QColor(mCvet)));
    painter->setOpacity(1);

    QColor textColor(bgColor);
    if (mCvet == "#ffffff")
        textColor = Qt::darkRed;
    else if (mCvet == "#000000")
        textColor = QColor(240, 240, 240);
    else
        textColor =  QColor(mCvet).darker(200);

    painter->setPen(textColor);
#if defined(Q_OS_UNIX)
    painter->drawText(r.adjusted(0, 5, 0, 0), mVyiravn, mPodpis);
#elif defined(Q_OS_WIN)
    painter->drawText(r.adjusted(0, 0, 0, 0), mVyiravn, mPodpis);
#endif
}