void Plugin_Entity::move(QPointF offset){
    entity->move( RS_Vector(offset.x(), offset.y()) );
}
Example #2
0
/** Handle the mouse move event when the line is being dragged
 * @param event mouse event info */
void LineOverlay::handleDrag(QMouseEvent *event) {
  // Is the shift key pressed?
  bool shiftPressed = (event->modifiers() & Qt::ShiftModifier);
  // Currently dragging!
  QPointF current = this->invTransform(event->pos());
  QPointF currentSnap = this->snap(current);
  QPointF diff = m_pointB - m_pointA;
  QPointF dragAmount = current - this->m_dragStart;
  dragAmount = snap(dragAmount);
  double width = 0;

  // Adjust the current mouse position if needed.
  if ((m_snapLength > 0) || shiftPressed || m_angleSnapMode) {
    // This is the distance between the fixed and dragged point
    QPointF currentDiff;
    if (m_dragHandle == HandleA)
      currentDiff = current - m_pointB;
    else if (m_dragHandle == HandleB)
      currentDiff = current - m_pointA;

    // calculate angle
    double angle = atan2(currentDiff.y(), currentDiff.x());

    // Round angle to closest 45 degrees, if in angle snap mode (shift pressed)
    if (shiftPressed || m_angleSnapMode) {
      if (m_angleSnap == 90.0) {
        // special case for 90 snap (axis aligned snapping)
        // use screen coords to determine snap angle
        QPointF currentScreenDiff;
        if (m_dragHandle == HandleA)
          currentScreenDiff = event->pos() - transform(m_pointB);
        else if (m_dragHandle == HandleB)
          currentScreenDiff = event->pos() - transform(m_pointA);

        // Limit angles to 90 based on screen coords, not data coords
        //-y is because the screen y coords are inverted to the data coords
        angle = atan2(-currentScreenDiff.y(), currentScreenDiff.x());
      }
      // convert snap angle to radians
      double angleSnapRad = m_angleSnap / (180.0 / M_PI);
      // round current angle to snap angle
      angle = Utils::rounddbl(angle / angleSnapRad) * angleSnapRad;
    }

    double length;
    // for axis aligned angles just use respective distance for the length
    if (fmod(angle, M_PI) == 0) {
      length = fabs(currentDiff.x());
    } else if (fmod(angle, M_PI) == M_PI / 2) {
      length = fabs(currentDiff.y());
    } else {
      length = sqrt(currentDiff.x() * currentDiff.x() +
                    currentDiff.y() * currentDiff.y());
    }

    // Round length to m_snapLength, if specified
    if (m_snapLength > 0)
      length = Utils::rounddbl(length / m_snapLength) * m_snapLength;

    // Rebuild the mouse position
    currentDiff = QPointF(cos(angle) * length, sin(angle) * length);
    if (m_dragHandle == HandleA)
      currentSnap = snap(m_pointB + currentDiff);
    else if (m_dragHandle == HandleB)
      currentSnap = snap(m_pointA + currentDiff);
  }

  switch (m_dragHandle) {
  case HandleA:
    setPointA(currentSnap);
    break;

  case HandleB:
    setPointB(currentSnap);
    break;

  case HandleWidthBottom:
  case HandleWidthTop:
    // Find the distance between the mouse and the line (see
    // http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html )
    width = fabs(diff.x() * (current.y() - m_pointA.y()) -
                 (current.x() - m_pointA.x()) * diff.y()) /
            sqrt(diff.x() * diff.x() + diff.y() * diff.y());
    setWidth(width);
    break;

  case HandleCenter:
    // Move the whole line around
    m_pointA = m_dragStart_PointA + dragAmount;
    m_pointB = m_dragStart_PointB + dragAmount;
    this->update();
    emit lineChanging(m_pointA, m_pointB, m_width);
    break;

  default:
    break;
  }
}
Example #3
0
int Shell::split(QVariantList points)
{
	QPointF point;

	//omit last value, because it is always zero
	int dataSize = points.size()-1;

	Eigen::MatrixXf x; x.resize(dataSize,2);
	Eigen::VectorXf y(dataSize);

  //create the linear eq system in the form of y = beta1*x + beta2*1
	for( int i = 0; i < dataSize; i++)
	{
		point = points[i].toPointF();
		x(i, 0) = 1.0f; //beta for y-intercept
		x(i, 1) = point.x(); //beta for slope (dependent on x)

		y(i) = point.y(); 
	}

	//Error function (least squares of ax+b)
	auto error = [](Regression reg, int b, int a)->float
	{
		float result = 0;
		for(int i=0 ; i< reg.y.size(); i++)
		{
			float functionValue = a*reg.x(i, 1)+ b;
			float squarederror = std::pow(reg.y(i) - functionValue, 2);
			result+=squarederror;
		}
		return result;

	};

	//Perform all pairs of regressions
	float lowestError = std::numeric_limits<float>::max();
	float r1a, r1b;
	float r2a, r2b;
	int splitIndex = 0;

	for( int i = 2; i < dataSize; i++)
	{
		Regression reg1; reg1.x = x.topRows(i); reg1.y = y.head(i);
		Regression reg2; reg2.x = x.bottomRows(dataSize-i); reg2.y = y.tail(dataSize-i);

		Eigen::MatrixXf reg1Result = ((reg1.x.transpose() * reg1.x).inverse() * reg1.x.transpose()) * reg1.y;
		Eigen::MatrixXf reg2Result = ((reg2.x.transpose() * reg2.x).inverse() * reg2.x.transpose()) * reg2.y;

		float currentError = error(reg1,reg1Result(0),reg1Result(1)) + error(reg2,reg2Result(0),reg2Result(1));
		if (currentError < lowestError)
		{
			r1a = reg1Result(1); r1b = reg1Result(0);
			r2a = reg2Result(1); r2b = reg2Result(0);
			lowestError = currentError;
			splitIndex = i;
		}

	}
	std::cout << "r1:" << r1a << "x + " << r1b << std::endl;
	std::cout << "r2:" << r2a << "x + " << r2b << std::endl;
	std::cout << "(smallest error:" << lowestError << ")" << std::endl;

	return splitIndex;
}
Example #4
0
QPixmap TileWidget::generateTilePixmap()
{
    const QSize currentSize(size());

    if (currentSize.isEmpty())
        return QPixmap();

    const QRect borderRect(0, 0, currentSize.width(), currentSize.height());
    const int maxSideLength = qMax(currentSize.width(), currentSize.height());
    const int borderWidth = 1;

    const QPointF midpoint((double)(currentSize.width() + borderWidth) / 2, (double)(currentSize.height() + borderWidth) / 2);
    const QColor color(tileColor());

    QPixmap ret(currentSize);

    if (PixmapCacher::self()->contains(color))
        ret = PixmapCacher::self()->get(color);
    else
    {
        //UVcout << "cache miss for color " << color.rgb() << endl;
        double radius = maxSideLength / 2 * 1.41 + maxSideLength / 10 + 2;

        // could be used for cool effect -- the color of the bonus square we're obscuring
        //const QColor outerColor(backgroundColor());

        QRadialGradient gradient(QPointF(radius, radius), radius * 3, QPointF(radius / 3, radius / 3));
        gradient.setColorAt(0, color.light(GraphicalBoardFrame::s_highlightFactor));
        gradient.setColorAt(.95, color.dark(GraphicalBoardFrame::s_highlightFactor));

        QPainter painter(&ret);
        painter.setBrush(gradient);
    
        painter.drawEllipse((int)(midpoint.x() - radius), (int)(midpoint.y() - radius), (int)(radius * 2), (int)(radius * 2));

        QPalette customPalette;
        customPalette.setColor(QPalette::Light, color.light(GraphicalBoardFrame::s_highlightFactor));
        customPalette.setColor(QPalette::Dark, color);
        customPalette.setColor(QPalette::Mid, color);

        qDrawShadePanel(&painter, borderRect.x(), borderRect.y(), borderRect.width(), borderRect.height(), customPalette, false, borderWidth);

        PixmapCacher::self()->put(color, ret);
    }

    const QString nanism = miniText();
    const bool hasNanism = !nanism.isEmpty();

    const QString text = letterText();
    if (!text.isEmpty())
    {
        QPainter painter(&ret);
        painter.setFont(letterFont());
        QPen pen(letterTextColor());
        painter.setPen(pen);
        painter.setBrush(Qt::NoBrush);

        const QRectF textSize(painter.boundingRect(borderRect, text));
        const QPointF startPoint(midpoint - textSize.bottomRight() / 2);
        const QPointF roundedStartPoint(floor(startPoint.x()), floor(startPoint.y()));

        QRectF textRect(textSize);
        textRect.moveTo(roundedStartPoint);

        painter.drawText(textRect, Qt::TextDontClip, text);

        if (m_information.isBlank)
        {
            painter.setBrush(Qt::NoBrush);
            pen.setWidth(1);
            painter.setPen(pen);

            const int border = currentSize.width() / 5;
            painter.drawRect(QRect(border, border, currentSize.width() - 2 * border, currentSize.height() - 2 * border));
        }
    }

    if (hasNanism)
    {
        QPainter painter(&ret);
        painter.setFont(miniFont());
        QPen pen(miniTextColor());
        painter.setPen(pen);
        painter.setBrush(Qt::NoBrush);

        const QRectF textSize(painter.boundingRect(borderRect, nanism));
        const QPointF startPoint((midpoint * (nanism.length() > 1? 1.65 : 1.68)) - textSize.bottomRight() / 2);
        const QPointF roundedStartPoint(floor(startPoint.x()), floor(startPoint.y()));

        QRectF textRect(textSize);
        textRect.moveTo(roundedStartPoint);

        painter.drawText(textRect, Qt::TextDontClip, nanism);
    }

    return ret;
}
Example #5
0
/** Tranform from plot coordinates to pixel coordinates
 * @param coords :: coordinate point in plot coordinates
 * @return pixel coordinates */
QPoint LineOverlay::transform(QPointF coords) const {
  int xA = m_plot->transform(QwtPlot::xBottom, coords.x());
  int yA = m_plot->transform(QwtPlot::yLeft, coords.y());
  return QPoint(xA, yA);
}
Example #6
0
QPoint QtfeCanal::listPos2WidgetPos(QPointF pf)
{
	return QPoint(pf.x()*width(), height() * (1.0 - pf.y()));
}
bool QgsEllipseSymbolLayerV2::writeDxf( QgsDxfExport& e, double mmMapUnitScaleFactor, const QString& layerName, const QgsSymbolV2RenderContext* context, const QgsFeature* f, const QPointF& shift ) const
{
  //width
  double symbolWidth = mSymbolWidth;
  QgsExpression* widthExpression = expression( "width" );
  if ( widthExpression ) //1. priority: data defined setting on symbol layer level
  {
    symbolWidth = widthExpression->evaluate( const_cast<QgsFeature*>( f ) ).toDouble();
  }
  else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level
  {
    symbolWidth = mSize;
  }
  if ( mSymbolWidthUnit == QgsSymbolV2::MM )
  {
    symbolWidth *= mmMapUnitScaleFactor;
  }

  //height
  double symbolHeight = mSymbolHeight;
  QgsExpression* heightExpression = expression( "height" );
  if ( heightExpression ) //1. priority: data defined setting on symbol layer level
  {
    symbolHeight =  heightExpression->evaluate( const_cast<QgsFeature*>( f ) ).toDouble();
  }
  else if ( context->renderHints() & QgsSymbolV2::DataDefinedSizeScale ) //2. priority: is data defined size on symbol level
  {
    symbolHeight = mSize;
  }
  if ( mSymbolHeightUnit == QgsSymbolV2::MM )
  {
    symbolHeight *= mmMapUnitScaleFactor;
  }

  //outline width
  double outlineWidth = mOutlineWidth;
  QgsExpression* outlineWidthExpression = expression( "outline_width" );
  if ( outlineWidthExpression )
  {
    outlineWidth = outlineWidthExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toDouble();
  }
  if ( mOutlineWidthUnit == QgsSymbolV2::MM )
  {
    outlineWidth *= outlineWidth;
  }

  //fill color
  QColor fc = mFillColor;
  QgsExpression* fillColorExpression = expression( "fill_color" );
  if ( fillColorExpression )
  {
    fc = QColor( fillColorExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString() );
  }
  int fillColorIndex = e.closestColorMatch( fc.rgb() );

  //outline color
  QColor oc = mOutlineColor;
  QgsExpression* outlineColorExpression = expression( "outline_color" );
  if ( outlineColorExpression )
  {
    oc = QColor( outlineColorExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString() );
  }
  int outlineColorIndex = e.closestColorMatch( oc.rgb() );


  //symbol name
  QString symbolName =  mSymbolName;
  QgsExpression* symbolNameExpression = expression( "symbol_name" );
  if ( symbolNameExpression )
  {
    QgsExpression* symbolNameExpression = expression( "symbol_name" );
    symbolName = symbolNameExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toString();
  }

  //offset
  double offsetX = 0;
  double offsetY = 0;
  markerOffset( *context, offsetX, offsetY );
  QPointF off( offsetX, offsetY );

  //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle)
  double rotation = 0.0;
  QgsExpression* rotationExpression = expression( "rotation" );
  if ( rotationExpression )
  {
    rotation = rotationExpression->evaluate( const_cast<QgsFeature*>( context->feature() ) ).toDouble();
  }
  else if ( !qgsDoubleNear( mAngle, 0.0 ) )
  {
    rotation = mAngle;
  }
  rotation = -rotation; //rotation in Qt is counterclockwise
  if ( rotation )
    off = _rotatedOffset( off, rotation );

  QTransform t;
  t.translate( shift.x() + offsetX, shift.y() + offsetY );

  if ( rotation != 0 )
    t.rotate( rotation );

  double halfWidth = symbolWidth / 2.0;
  double halfHeight = symbolHeight / 2.0;

  if ( symbolName == "circle" )
  {
    if ( qgsDoubleNear( halfWidth, halfHeight ) )
    {
      QPointF pt( t.map( QPointF( 0, 0 ) ) );
      e.writeCircle( layerName, outlineColorIndex, QgsPoint( pt.x(), pt.y() ), halfWidth );
    }
    else
    {
      QgsPolyline line;
      double stepsize = 2 * M_PI / 40;
      for ( int i = 0; i < 39; ++i )
      {
        double angle = stepsize * i;
        double x = halfWidth * cos( angle );
        double y = halfHeight * sin( angle );
        QPointF pt( t.map( QPointF( x, y ) ) );
        line.push_back( QgsPoint( pt.x(), pt.y() ) );
      }
      //close ellipse with first point
      line.push_back( line.at( 0 ) );
      e.writePolyline( line, layerName, "solid", outlineColorIndex, outlineWidth, true );
    }
  }
  else if ( symbolName == "rectangle" )
  {
    QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) );
    QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) );
    QPointF pt3( t.map( QPointF( -halfWidth, halfHeight ) ) );
    QPointF pt4( t.map( QPointF( halfWidth, halfHeight ) ) );
    e.writeSolid( layerName, fillColorIndex, QgsPoint( pt1.x(), pt1.y() ), QgsPoint( pt2.x(), pt2.y() ), QgsPoint( pt3.x(), pt3.y() ), QgsPoint( pt4.x(), pt4.y() ) );
    return true;
  }
  else if ( symbolName == "cross" )
  {
    QgsPolyline line1( 2 );
    QPointF pt1( t.map( QPointF( -halfWidth, 0 ) ) );
    QPointF pt2( t.map( QPointF( halfWidth, 0 ) ) );
    line1[0] = QgsPoint( pt1.x(), pt1.y() );
    line1[1] = QgsPoint( pt2.x(), pt2.y() );
    e.writePolyline( line1, layerName, "CONTINUOUS", outlineColorIndex, outlineWidth, false );
    QgsPolyline line2( 2 );
    QPointF pt3( t.map( QPointF( 0, halfHeight ) ) );
    QPointF pt4( t.map( QPointF( 0, -halfHeight ) ) );
    line2[0] = QgsPoint( pt3.x(), pt3.y() );
    line2[1] = QgsPoint( pt4.x(), pt4.y() );
    e.writePolyline( line2, layerName, "CONTINUOUS", outlineColorIndex, outlineWidth, false );
    return true;
  }
  else if ( symbolName == "triangle" )
  {
    QPointF pt1( t.map( QPointF( -halfWidth, -halfHeight ) ) );
    QPointF pt2( t.map( QPointF( halfWidth, -halfHeight ) ) );
    QPointF pt3( t.map( QPointF( 0, halfHeight ) ) );
    QPointF pt4( t.map( QPointF( 0, halfHeight ) ) );
    e.writeSolid( layerName, fillColorIndex, QgsPoint( pt1.x(), pt1.y() ), QgsPoint( pt2.x(), pt2.y() ), QgsPoint( pt3.x(), pt3.y() ), QgsPoint( pt4.x(), pt4.y() ) );
    return true;
  }

  return false; //soon...
}
Example #8
0
void MainView2D::createFixtureItem(quint32 fxID, quint16 headIndex, quint16 linkedIndex,
                                   QVector3D pos, bool mmCoords)
{
    if (isEnabled() == false)
        return;

    if (m_gridItem == NULL)
       initialize2DProperties();

    qDebug() << "[MainView2D] Creating fixture with ID" << fxID << headIndex << linkedIndex << "pos:" << pos;

    Fixture *fixture = m_doc->fixture(fxID);
    if (fixture == NULL)
        return;

    quint32 itemID = FixtureUtils::fixtureItemID(fxID, headIndex, linkedIndex);
    QLCFixtureMode *fxMode = fixture->fixtureMode();
    QQuickItem *newFixtureItem = qobject_cast<QQuickItem*>(fixtureComponent->create());
    quint32 itemFlags = m_monProps->fixtureFlags(fxID, headIndex, linkedIndex);

    newFixtureItem->setParentItem(m_gridItem);
    newFixtureItem->setProperty("itemID", itemID);

    if (itemFlags & MonitorProperties::HiddenFlag)
        newFixtureItem->setProperty("visible", false);

    if (fxMode != NULL && fixture->type() != QLCFixtureDef::Dimmer)
    {
        QLCPhysical phy = fxMode->physical();

        //qDebug() << "Current mode fixture heads:" << fxMode->heads().count();
        newFixtureItem->setProperty("headsNumber", fxMode->heads().count());

        if (fixture->channelNumber(QLCChannel::Pan, QLCChannel::MSB) != QLCChannel::invalid())
        {
            int panDeg = phy.focusPanMax();
            if (panDeg == 0) panDeg = 360;
            newFixtureItem->setProperty("panMaxDegrees", panDeg);
        }
        if (fixture->channelNumber(QLCChannel::Tilt, QLCChannel::MSB) != QLCChannel::invalid())
        {
            int tiltDeg = phy.focusTiltMax();
            if (tiltDeg == 0) tiltDeg = 270;
            newFixtureItem->setProperty("tiltMaxDegrees", tiltDeg);
        }
    }

    QPointF itemPos;
    QSizeF size = FixtureUtils::item2DDimension(fixture->type() == QLCFixtureDef::Dimmer ? NULL : fxMode,
                                                m_monProps->pointOfView());

    if (mmCoords == false && (pos.x() != 0 || pos.y() != 0))
    {
        float gridUnits = m_monProps->gridUnits() == MonitorProperties::Meters ? 1000.0 : 304.8;
        itemPos.setX((pos.x() * gridUnits) / m_cellPixels);
        itemPos.setY((pos.y() * gridUnits) / m_cellPixels);
    }

    if (m_monProps->containsItem(fxID, headIndex, linkedIndex))
    {
        itemPos = FixtureUtils::item2DPosition(m_monProps, m_monProps->pointOfView(), pos);
        newFixtureItem->setProperty("rotation",
                                    FixtureUtils::item2DRotation(m_monProps->pointOfView(),
                                                                 m_monProps->fixtureRotation(fxID, headIndex, linkedIndex)));
    }
    else
    {
        itemPos = FixtureUtils::available2DPosition(m_doc, m_monProps->pointOfView(),
                                                    QRectF(itemPos.x(), itemPos.y(), size.width(), size.height()));
        // add the new fixture to the Doc monitor properties
        QVector3D newPos = FixtureUtils::item3DPosition(m_monProps, itemPos, 1000.0);
        m_monProps->setFixturePosition(fxID, headIndex, linkedIndex, newPos);
        m_monProps->setFixtureFlags(fxID, headIndex, linkedIndex, 0);
        Tardis::instance()->enqueueAction(Tardis::FixtureSetPosition, itemID, QVariant(QVector3D(0, 0, 0)), QVariant(newPos));
    }

    newFixtureItem->setProperty("mmXPos", itemPos.x());
    newFixtureItem->setProperty("mmYPos", itemPos.y());
    newFixtureItem->setProperty("mmWidth", size.width());
    newFixtureItem->setProperty("mmHeight", size.height());
    newFixtureItem->setProperty("fixtureName", fixture->name());

    // and finally add the new item to the items map
    m_itemsMap[itemID] = newFixtureItem;

    QByteArray values;
    updateFixture(fixture, values);
}
Example #9
0
void ColorRing::setColorFromPoint(float x, float y)
{
	float r2 = x*x + y*y;
	QRect r = contentsRect();
	if(grabring && grabtriangle) {
		grabring = grabtriangle = false;
	}
	if(!grabring && !grabtriangle) {
		if(r2 > RING2) {
			grabring = true;
		} else {
			grabtriangle = true;
		}
	}
	if(grabring) {
		float angle = (atan2f(y,-x)/M_PI);
		angle = (angle * 0.5f) + 0.5f;
		col.setHsvF(angle, col.saturationF(), col.valueF());
	} else if(grabtriangle) {
		QMatrix m;
		m.scale(1.f/RING, 1.f/RING);
		m.rotate(col.hueF() * 360);
		if(triangleMode) {
			QPointF p = m.map(QPointF(x, y)), p2;
			QLineF satL(points[0], points[1]);
			QLineF l1(points[2], p);
			switch(satL.intersect(l1, &p2)) {
			case QLineF::BoundedIntersection:
			case QLineF::UnboundedIntersection:
				{
					float sat = QLineF(points[1], p2).length()/satL.length();
					if(satL.length() < QLineF(points[0], p2).length()) sat = 0;
					float val = QLineF(points[2], p).length()/QLineF(points[2], p2).length();
					if(QLineF(p, p2).length() > QLineF(points[2], p2).length()) val = .0f;
					if(sat > 1.f) sat = 1.f;
					if(sat < .0f) sat = 0.f;
					if(val > 1.f) val = 1.f;
					if(val < .0f) val = .0f;
					col.setHsvF(col.hueF(), sat, val);
					break;
				}
			case QLineF::NoIntersection:
				break;
			}
		} else { // box mode
			QMatrix m2;
			m2.rotate(45);
			m.rotate(45);
			QPointF p = m.map(QPointF(x, y)), p1  = m2.map(points2[1]), p2 = m2.map(points2[2]), p0 = m2.map(points2[0]);
			float sat = (p.x() - p1.x()) / (p0.x() - p1.x());
			float val = (p.y() - p1.y()) / (p2.y() - p1.y());
			if(sat > 1.f) sat = 1.f;
			if(sat < .0f) sat = 0.f;
			if(val > 1.f) val = 1.f;
			if(val < .0f) val = .0f;
			col.setHsvF(col.hueF(), sat, val);
			//QMessageBox::information(0, "", QString("x=%1, y=%2, p1.x=%3, p1.y=%4, p2.x=%5, p2.y=%6").arg(QString::number(p.x())).arg(QString::number(p.y())).arg(QString::number(p1.x())).arg(QString::number(p1.y())).arg(QString::number(p2.x())).arg(QString::number(p2.y())));
		}
	}
	emit hChanged(col.hueF());
	emit colorChanged(col);
	repaint();
}
Example #10
0
void
FormText::moveResizable( const QPointF & delta )
{
	moveBy( delta.x(), delta.y() );
}
Example #11
0
void PlotObject::updatePath()
{
    _path = QPainterPath();
    if (((SelectProperty*) properties()["mode"])->currentIndex() == 0) {
        QList<qreal> xValues;
        QList<qreal> yValues;
        qreal start = ((RealProperty*) properties()["start"])->value();
        qreal end = ((RealProperty*) properties()["end"])->value();
        qreal pointCount = ((IntegerProperty*) properties()["points"])->value();

        qreal step = (end - start) / pointCount;
        if (step > 0) {
            for (qreal x = start; x <= end; x += step) {
                xValues.append(x);
           }
        } else if (step < 0) {
            for (qreal x = start; x >= end; x += step) {
                xValues.append(x);
            }
        } else {
            return;
        }
        if (xValues.isEmpty()) return;


        yValues = MathUtility::parse(((PropertyString*) properties()["formular"])->string(), xValues);
        _path = QPainterPath(QPointF(xValues.first(), yValues.first()));
        for (int i = 1; i < xValues.size(); i++) {
            _path.lineTo(xValues[i], yValues[i]);
        }
    } else {
        QList<qreal> alphas;
        QList<qreal> radius;
        qreal start = ((RealProperty*) properties()["polar-start"])->value() * M_PI/180.0;
        qreal end = ((RealProperty*) properties()["polar-end"])->value() * M_PI/180.0;
        qreal pointCount = ((IntegerProperty*) properties()["points"])->value();
        qreal step = (end - start) / pointCount;
        if (step > 0) {
            for (qreal x = start; x <= end; x += step) {
                alphas.append(x);
           }
        } else if (step < 0) {
            for (qreal x = start; x >= end; x += step) {
                alphas.append(x);
            }
        } else {
            return;
        }
        radius = MathUtility::parse(((PropertyString*) properties()["formular"])->string(), alphas);

        auto polarToCart = [](qreal alpha, qreal radius) {
            return QPointF(qCos(alpha) * radius,
                           qSin(alpha) * radius);
        };

        _path = QPainterPath(polarToCart(alphas.first(), radius.first()));
        for (int i = 1; i < alphas.size(); i++) {
            QPointF p = polarToCart(alphas[i], radius[i]);
            _path.lineTo(p.x(), p.y());
        }

    }
}
Example #12
0
void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
          QWidget *)
{
    qDebug() << "Arrow: paint";

    if (myStartItem->collidesWithItem(myEndItem))
        return;
/*
    QPen myPen = pen();
    myPen.setColor(myColor);
    qreal arrowSize = 20;
    painter->setPen(myPen);
    painter->setBrush(myColor);


    QLineF centerLine(myStartItem->pos(), myEndItem->pos());
    QPolygonF endPolygon = myEndItem->polygon();
    //p1 = coordinates of first pointer of enditem in
    //scene coordinates
    QPointF p1 = endPolygon.first() + myEndItem->pos();
    QPointF p2;
    QPointF intersectPoint;
    QLineF polyLine;
    //.count()=.size()
    for (int i = 1; i < endPolygon.count(); ++i) {
        p2 = endPolygon.at(i) + myEndItem->pos();
        polyLine = QLineF(p1, p2);
        QLineF::IntersectType intersectType =
            polyLine.intersect(centerLine, &intersectPoint);
        if (intersectType == QLineF::BoundedIntersection)
            break;
            p1 = p2;
    }
    */

    //qreal comp1=intersectPoint.x();
    //qreal comp2;

    //TODO:
    //This is my patch to define input and output points for lines
    //All code above this point is rendered useless and should be removed

    QPointF intersectPoint;
    QPen myPen = pen();
    myPen.setColor(myColor);
    qreal arrowSize = 20;
    painter->setPen(myPen);
    painter->setBrush(myColor);

    intersectPoint=myEndItem->pos();
    intersectPoint.setX(intersectPoint.x()-myEndItem->boundingRect().width()/2);

    QPointF otherPoint;
    otherPoint=myStartItem->pos();
    otherPoint.setX(otherPoint.x()+myStartItem->boundingRect().width()/2);
    //original
    setLine(QLineF(otherPoint, intersectPoint));

    if(isZone2()){
        zone2(otherPoint);
    }
    else{
        zone1(otherPoint);
    }

    //double angle = ::acos(line().dx() / line().length());
    double angle=Pi;
    if (line().dy() >= 0)
        angle = (Pi * 2) - angle;


    QPointF arrowP1 = line().p2() + QPointF(sin(angle + Pi / 3) * arrowSize,
                                    cos(angle + Pi / 3) * arrowSize);
    QPointF arrowP2 = line().p2() + QPointF(sin(angle + Pi - Pi / 3) * arrowSize,
                                    cos(angle + Pi - Pi / 3) * arrowSize);

    arrowHead.clear();
    arrowHead << line().p2() << arrowP1 << arrowP2;

    for(int i=0;i<part.size();++i)
        painter->drawLine(*part[i]);

    //setLine(*part[0]);
    //painter->drawLine(line());
    painter->drawPolygon(arrowHead);
    if (isSelected()) {
        painter->setPen(QPen(myColor, 1, Qt::DashLine));

        QLineF myLine = line();
        myLine.translate(0, 4.0);
        painter->drawLine(myLine);
        myLine.translate(0,-8.0);
        painter->drawLine(myLine);
    }

    //qDebug() << "PAINT ORDER FINISH";
}
void Plugin_Entity::scale(QPointF center, QPointF factor){
    entity->scale( RS_Vector(center.x(), center.y()),
                RS_Vector(factor.x(), factor.y()) );
}
void Plugin_Entity::rotate(QPointF center, double angle){
    entity->rotate( RS_Vector(center.x(), center.y()) , angle);
}
void paintValueTracker( PaintContext* ctx, const ValueTrackerAttributes& vt, const QPointF& at )
{
    CartesianCoordinatePlane* plane = qobject_cast<CartesianCoordinatePlane*>( ctx->coordinatePlane() );
    if ( !plane )
        return;

    DataDimensionsList gridDimensions = ctx->coordinatePlane()->gridDimensionsList();
    const QPointF bottomLeft( ctx->coordinatePlane()->translate(
                              QPointF( plane->isHorizontalRangeReversed() ?
                                           gridDimensions.at( 0 ).end :
                                           gridDimensions.at( 0 ).start,
                                       plane->isVerticalRangeReversed() ?
                                           gridDimensions.at( 1 ).end :
                                           gridDimensions.at( 1 ).start ) ) );
    const QPointF topRight( ctx->coordinatePlane()->translate(
                            QPointF( plane->isHorizontalRangeReversed() ?
                                         gridDimensions.at( 0 ).start :
                                         gridDimensions.at( 0 ).end,
                                     plane->isVerticalRangeReversed() ?
                                         gridDimensions.at( 1 ).start :
                                         gridDimensions.at( 1 ).end ) ) );
    const QPointF markerPoint = at;

    QPointF startPoint;
    if ( vt.orientations() & Qt::Horizontal ) {
        startPoint = QPointF( bottomLeft.x(), at.y() );
    } else {
        startPoint = QPointF( at.x(), topRight.y() );
    }

    QPointF endPoint;
    if ( vt.orientations() & Qt::Vertical ) {
        endPoint = QPointF( at.x(), bottomLeft.y() );
    } else {
        endPoint = QPointF( topRight.x(), at.y() );
    }

    const QSizeF markerSize = vt.markerSize();
    const QRectF ellipseMarker = QRectF( at.x() - markerSize.width() / 2,
                                         at.y() - markerSize.height() / 2,
                                         markerSize.width(), markerSize.height() );

    QPointF startMarker[3];
    if ( vt.orientations() & Qt::Horizontal ) {
        startMarker[0] = startPoint + QPointF( 0,  markerSize.height() / 2 );
        startMarker[1] = startPoint + QPointF( markerSize.width() / 2, 0 );
        startMarker[2] = startPoint - QPointF( 0, markerSize.height() / 2 );
    } else {
        startMarker[0] = startPoint + QPointF( 0, markerSize.height() / 2 );
        startMarker[1] = startPoint + QPointF( markerSize.width() / 2, 0 );
        startMarker[2] = startPoint - QPointF( markerSize.width() / 2, 0 );
    }

    QPointF endMarker[3];

    if ( vt.orientations() & Qt::Vertical ) {
        endMarker[0] = endPoint + QPointF( markerSize.width() / 2, 0 );
        endMarker[1] = endPoint - QPointF( 0, markerSize.height() / 2 );
        endMarker[2] = endPoint - QPointF( markerSize.width() / 2, 0 );
    } else {
        endMarker[0] = endPoint + QPointF( 0,  markerSize.width() / 2 );
        endMarker[1] = endPoint - QPointF( 0, markerSize.height() / 2 );
        endMarker[2] = endPoint - QPointF( markerSize.width() / 2, 0 );
    }

    QPointF topLeft = startPoint;
    QPointF bottomRightOffset = endPoint - topLeft;
    QSizeF size( bottomRightOffset.x(), bottomRightOffset.y() );
    QRectF area( topLeft, size );

    PainterSaver painterSaver( ctx->painter() );
    ctx->painter()->setPen( PrintingParameters::scalePen( vt.linePen() ) );
    ctx->painter()->setBrush( QBrush() );
    ctx->painter()->drawLine( markerPoint, startPoint );
    ctx->painter()->drawLine( markerPoint, endPoint );

    ctx->painter()->fillRect( area, vt.areaBrush() );

    ctx->painter()->setPen( PrintingParameters::scalePen( vt.markerPen() ) );
    ctx->painter()->setBrush( vt.markerBrush() );
    ctx->painter()->drawEllipse( ellipseMarker );

    ctx->painter()->setPen( PrintingParameters::scalePen( vt.arrowBrush().color() ) );
    ctx->painter()->setBrush( vt.arrowBrush() );
    ctx->painter()->drawPolygon( startMarker, 3 );
    ctx->painter()->drawPolygon( endMarker, 3 );
}
Example #16
0
QRectF QtGradientWidgetPrivate::pointRect(const QPointF &point, double size) const
{
    return QRectF(point.x() - size / 2, point.y() - size / 2, size, size);
}
Example #17
0
void QtfeCanal::mouseMoveEvent ( QMouseEvent * event )
{
  if (bAllowInteraction)
  {
    QPointF pf = WidgetPos2listPos(event->pos());

    if (pressed)
    {
      if (selected)
      {
        if (selected != &first && selected != &last)
        {
          selected->setX(qMin(qMax(pf.x(), pMin), pMax));
        }
        selected->setY(qMin(qMax(pf.y(), 0.0), 1.0));
        this->repaint();
        emit canalChanged();
        return;
      }
    }
    else
    {
      qreal d_min = circleSizePixel*circleSizePixel;
      qreal W = width()*width();
      qreal H = height()*height();
      QPointF* nearest = NULL;

      for (int i = 0; i < list.size(); ++i)
      {
        qreal x = list[i]->x() - pf.x();
        qreal y = list[i]->y() - pf.y();

        qreal d = x*x*W + y*y*H;
        if (d < d_min)
        {
          nearest = list[i];
          d_min = d;
          if (i == 0)
          {
            pMin = 0.0;
            pMax = 0.0;
          }
          else if (i == list.size() - 1)
          {
            pMin = 1.0;
            pMax = 1.0;
          }
          else
          {
            pMin = list[i - 1]->x() + 0.01;
            pMax = list[i + 1]->x() - 0.01;
          }
        }
      }

      if (nearest != selected)
      {
        selected = nearest;
        this->repaint();
      }
    }
  }
}
Example #18
0
QPointF QtGradientWidgetPrivate::toViewport(const QPointF &point) const
{
    QSize size = q_ptr->size();
    return QPointF(point.x() * size.width(), point.y() * size.height());
}
Example #19
0
void QgsEllipseSymbolLayerV2::renderPoint( const QPointF& point, QgsSymbolV2RenderContext& context )
{
  QgsExpression* outlineWidthExpression = expression( "outline_width" );
  QgsExpression* fillColorExpression = expression( "fill_color" );
  QgsExpression* outlineColorExpression = expression( "outline_color" );
  QgsExpression* widthExpression = expression( "width" );
  QgsExpression* heightExpression = expression( "height" );
  QgsExpression* symbolNameExpression = expression( "symbol_name" );
  QgsExpression* rotationExpression = expression( "rotation" );

  if ( outlineWidthExpression )
  {
    double width = outlineWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
    width *= QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mOutlineWidthUnit, mOutlineWidthMapUnitScale );
    mPen.setWidthF( width );
  }
  if ( fillColorExpression )
  {
    QString colorString = fillColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    mBrush.setColor( QColor( QgsSymbolLayerV2Utils::decodeColor( colorString ) ) );
  }
  if ( outlineColorExpression )
  {
    QString colorString = outlineColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    mPen.setColor( QColor( QgsSymbolLayerV2Utils::decodeColor( colorString ) ) );
  }
  double scaledWidth = mSymbolWidth;
  double scaledHeight = mSymbolHeight;
  if ( widthExpression || heightExpression || symbolNameExpression )
  {
    QString symbolName =  mSymbolName;
    if ( symbolNameExpression )
    {
      symbolName = symbolNameExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    }
    preparePath( symbolName, context, &scaledWidth, &scaledHeight, context.feature() );
  }

  //offset
  double offsetX = 0;
  double offsetY = 0;
  markerOffset( context, scaledWidth, scaledHeight, mSymbolWidthUnit, mSymbolHeightUnit, offsetX, offsetY, mSymbolWidthMapUnitScale, mSymbolHeightMapUnitScale );
  QPointF off( offsetX, offsetY );

  QPainter* p = context.renderContext().painter();
  if ( !p )
  {
    return;
  }

  //priority for rotation: 1. data defined symbol level, 2. symbol layer rotation (mAngle)
  double rotation = 0.0;
  if ( rotationExpression )
  {
    rotation = rotationExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }
  else if ( !qgsDoubleNear( mAngle, 0.0 ) )
  {
    rotation = mAngle;
  }
  if ( rotation )
    off = _rotatedOffset( off, rotation );

  QMatrix transform;
  transform.translate( point.x() + off.x(), point.y() + off.y() );
  if ( !qgsDoubleNear( rotation, 0.0 ) )
  {
    transform.rotate( rotation );
  }

  p->setPen( mPen );
  p->setBrush( mBrush );
  p->drawPath( transform.map( mPainterPath ) );
}
Example #20
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;
        }
    }
}
Example #21
0
void OnMonitorRectItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    /*if (event->buttons() != Qt::NoButton && (event->screenPos() - m_screenClickPoint).manhattanLength() < QApplication::startDragDistance()) {
     *   event->accept();
     *   return;
    }*/

    if (event->buttons() & Qt::LeftButton) {
        QRectF r = rect().normalized();
        QPointF p = pos();
        QPointF mousePos = event->scenePos();
        QPointF mousePosInRect = event->pos();
        QPointF diff = mousePos - m_lastPoint;
        m_lastPoint = mousePos;

        switch (m_mode) {
        case ResizeTopLeft:
            if (mousePos.x() < p.x() + r.height() && mousePos.y() < p.y() + r.height()) {
                r.adjust(0, 0, -mousePosInRect.x(), -mousePosInRect.y());
                setPos(mousePos);
                m_modified = true;
            }
            break;
        case ResizeTop:
            if (mousePos.y() < p.y() + r.height()) {
                r.setBottom(r.height() - mousePosInRect.y());
                setPos(QPointF(p.x(), mousePos.y()));
                m_modified = true;
            }
            break;
        case ResizeTopRight:
            if (mousePos.x() > p.x() && mousePos.y() < p.y() + r.height()) {
                r.setBottomRight(QPointF(mousePosInRect.x(), r.bottom() - mousePosInRect.y()));
                setPos(QPointF(p.x(), mousePos.y()));
                m_modified = true;
            }
            break;
        case ResizeLeft:
            if (mousePos.x() < p.x() + r.width()) {
                r.setRight(r.width() - mousePosInRect.x());
                setPos(QPointF(mousePos.x(), p.y()));
                m_modified = true;
            }
            break;
        case ResizeRight:
            if (mousePos.x() > p.x()) {
                r.setRight(mousePosInRect.x());
                m_modified = true;
            }
            break;
        case ResizeBottomLeft:
            if (mousePos.x() < p.x() + r.width() && mousePos.y() > p.y()) {
                r.setBottomRight(QPointF(r.width() - mousePosInRect.x(), mousePosInRect.y()));
                setPos(QPointF(mousePos.x(), p.y()));
                m_modified = true;
            }
            break;
        case ResizeBottom:
            if (mousePos.y() > p.y()) {
                r.setBottom(mousePosInRect.y());
                m_modified = true;
            }
            break;
        case ResizeBottomRight:
            if (mousePos.x() > p.x() && mousePos.y() > p.y()) {
                r.setBottomRight(mousePosInRect);
                m_modified = true;
            }
            break;
        case Move:
            moveBy(diff.x(), diff.y());
            m_modified = true;
            break;
        default:
            break;
        }

        // Keep aspect ratio
        if (event->modifiers() == Qt::ControlModifier) {
            // compare to rect during mouse press:
            // if we subtract rect() we'll get a whole lot of flickering
            // because of diffWidth > diffHeight changing all the time
            int diffWidth = qAbs(r.width() - m_oldRect.width());
            int diffHeight = qAbs(r.height() - m_oldRect.height());

            if (diffHeight != 0 || diffWidth != 0) {
                if (diffWidth > diffHeight)
                    r.setBottom(r.width() / m_dar);
                else
                    r.setRight(r.height() * m_dar);

                // the rect's position changed
                if (p - pos() != QPointF()) {
                    if (diffWidth > diffHeight) {
                        if (m_mode != ResizeBottomLeft)
                            setY(p.y() - r.height() + rect().normalized().height());
                    } else {
                        if (m_mode != ResizeTopRight)
                            setX(p.x() - r.width() + rect().normalized().width());
                    }
                }
            }
        }

        setRect(r);
    }

    if (m_modified) {
        event->accept();
        if (KdenliveSettings::monitorscene_directupdate()) {
            emit changed();
            m_modified = false;
        }
    } else {
        event->ignore();
    }
}
Example #22
0
void QtGradientWidget::mouseMoveEvent(QMouseEvent *e)
{
    if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::NoHandle)
        return;

    QPointF newPos = QPointF((double)e->pos().x() - d_ptr->m_dragOffset.x(),
                (double)e->pos().y() - d_ptr->m_dragOffset.y());
    QPointF newPoint = d_ptr->fromViewport(newPos);
    if (newPoint.x() < 0)
        newPoint.setX(0);
    else if (newPoint.x() > 1)
        newPoint.setX(1);
    if (newPoint.y() < 0)
        newPoint.setY(0);
    else if (newPoint.y() > 1)
        newPoint.setY(1);

    if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::StartLinearHandle) {
        d_ptr->m_startLinear = newPoint;
        emit startLinearChanged(newPoint);
    } else if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::EndLinearHandle) {
        d_ptr->m_endLinear = newPoint;
        emit endLinearChanged(newPoint);
    } else if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralRadialHandle) {
        d_ptr->m_centralRadial = newPoint;
        emit centralRadialChanged(newPoint);
    } else if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::FocalRadialHandle) {
        d_ptr->m_focalRadial = newPoint;
        emit focalRadialChanged(newPoint);
    } else if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::RadiusRadialHandle) {
        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralRadial);
        QPointF pF(e->pos().x(), e->pos().y());
        double x = pF.x() - centralPoint.x();
        double y = pF.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            if (d_ptr->m_radiusRadial != d_ptr->m_dragRadius) {
                d_ptr->m_radiusRadial = d_ptr->m_dragRadius;
                emit radiusRadialChanged(d_ptr->m_radiusRadial);
            }
        } else {
            x = pF.x() / size().width() - d_ptr->m_centralRadial.x();
            y = pF.y() / size().height() - d_ptr->m_centralRadial.y();
            double moveRadius = sqrt(x * x + y * y);
            //double newRadius = moveRadius + d_ptr->m_radiusOffset;
            double newRadius = moveRadius * d_ptr->m_radiusFactor;
            if (newRadius > 2)
                newRadius = 2;
            d_ptr->m_radiusRadial = newRadius;
            emit radiusRadialChanged(d_ptr->m_radiusRadial);
        }
    } else if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralConicalHandle) {
        d_ptr->m_centralConical = newPoint;
        emit centralConicalChanged(newPoint);
    } else if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::AngleConicalHandle) {
        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralConical);
        QPointF pF(e->pos().x(), e->pos().y());
        double x = pF.x() - centralPoint.x();
        double y = pF.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            if (d_ptr->m_angleConical != d_ptr->m_dragAngle) {
                d_ptr->m_angleConical = d_ptr->m_dragAngle;
                emit angleConicalChanged(d_ptr->m_angleConical);
            }
        } else {
            QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);
            QPointF current = pF;
            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;
            }

            angle += d_ptr->m_angleOffset;

            d_ptr->setAngleConical(angle);
        }
    }
    update();
}
Example #23
0
Scenario::Point ToolPalette::ScenePointToScenarioPoint(QPointF point)
{
    return {TimeValue::fromMsecs(point.x() * m_presenter.zoomRatio()) , 0};
}
Example #24
0
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();

        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());
        p.setClipRect(r1);
        p.setClipRect(r2, Qt::UniteClip);
        p.setClipRect(r3, Qt::UniteClip);
        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;
}
Example #25
0
//----------------------------------------------------------------------------------------------
/// Paint the overlay
void LineOverlay::paintEvent(QPaintEvent * /*event*/) {
  // Don't paint until created
  // Also, don't paint while right-click dragging (panning) the underlying pic
  if (m_creation || m_rightButton || !m_shown)
    return;

  QPainter painter(this);
  //    int r = rand() % 255;
  //    int g = rand() % 255;
  //    int b = rand() % 255;

  //    painter.setBrush(QBrush(QColor(r,g,b)));

  QPointF diff = m_pointB - m_pointA;
  // Angle of the "width" perpendicular to the line
  double angle = atan2(diff.y(), diff.x()) + M_PI / 2.0;
  QPointF widthOffset(m_width * cos(angle), m_width * sin(angle));

  // Rectangle with a rotation
  QPointF pA1 = m_pointA + widthOffset;
  QPointF pA2 = m_pointA - widthOffset;
  QPointF pB1 = m_pointB + widthOffset;
  QPointF pB2 = m_pointB - widthOffset;

  QPen boxPenLight(QColor(255, 255, 255, 200));
  QPen boxPenDark(QColor(0, 0, 0, 200));
  QPen centerPen(QColor(192, 192, 192, 128));

  // Special XOR pixel drawing
  // painter.setCompositionMode( QPainter::RasterOp_SourceXorDestination ); //
  // RHEL5 has an old version of QT?

  boxPenLight.setDashPattern(QVector<qreal>() << 5 << 5);
  boxPenDark.setDashPattern(QVector<qreal>() << 0 << 5 << 5 << 0);

  // --- Draw the box ---
  boxPenLight.setWidthF(1.0);
  boxPenDark.setWidthF(1.0);

  //    QPoint points[4] = {transform(pA1), transform(pB1), transform(pB2),
  //    transform(pA2)};
  //    painter.drawPolygon(points, 4);

  painter.setPen(boxPenLight);
  painter.drawLine(transform(pA1), transform(pB1));
  painter.drawLine(transform(pB1), transform(pB2));
  painter.drawLine(transform(pA2), transform(pB2));
  painter.drawLine(transform(pA2), transform(pA1));
  painter.setPen(boxPenDark);
  painter.drawLine(transform(pA1), transform(pB1));
  painter.drawLine(transform(pB1), transform(pB2));
  painter.drawLine(transform(pA2), transform(pB2));
  painter.drawLine(transform(pA2), transform(pA1));

  // Go back to normal drawing mode
  painter.setCompositionMode(QPainter::CompositionMode_SourceOver);

  // --- Draw the central line ---
  if (m_showLine) {
    centerPen.setWidth(2);
    centerPen.setCapStyle(Qt::FlatCap);
    painter.setPen(centerPen);
    painter.drawLine(transform(m_pointA), transform(m_pointB));
  }

  // --- Draw and store the rects of the 4 handles ---
  m_handles.clear();
  m_handles.push_back(drawHandle(painter, m_pointA, QColor(0, 0, 0)));
  m_handles.push_back(drawHandle(painter, m_pointB, QColor(255, 255, 255)));
  m_handles.push_back(drawHandle(
      painter, (m_pointA + m_pointB) / 2 + widthOffset, QColor(0, 255, 255)));
  m_handles.push_back(drawHandle(
      painter, (m_pointA + m_pointB) / 2 - widthOffset, QColor(0, 255, 255)));
}
Example #26
0
void MavPlot::fwd_markerData(const Data *const d) {
    if (!d || !_data_marker_visible) return;
    const double markerx = _data_marker.xValue();
    double markerx_next = markerx;
#if 0
    /*******************
     * SCAN IN Data
     *******************/
#else
    /*******************
     * SCAN IN Plot
     *******************/
    // FIXME: heavy code clone from rev_markerData()
    QPointF xy;
    QString value;
    bool found = false;
    // find out what it is, then scan for data
    const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
    if (s) {
        // it's a series
        const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
        if (curve) {
            for (unsigned int k=0; k<curve->dataSize(); k++) {
                xy = curve->sample(k);
                double x = xy.x();
                if (x > markerx) {
                    found = true;
                    markerx_next = x;
                    value = QString::number(xy.y());
                    break;
                }
            }

        }
    }
    // annotation
    std::vector<QwtPlotItem*>*v = _get_annotations(d);
    if (v && !found) {
        // it's an annotation...we have to go through all of them
        for (std::vector<QwtPlotItem*>::const_iterator it = v->begin(); it != v->end(); ++it) {
            // only support marker annotations
            const QwtPlotMarker * m = dynamic_cast<const QwtPlotMarker*>(*it);
            if (m) {
                // we only handle vertical markers
                if (QwtPlotMarker::VLine == m->lineStyle()) {
                    xy = m->value();
                    double x = xy.x();
                    if (x > markerx) {
                        found = true;
                        markerx_next = x;
                        value = m->label().text();
                        break;
                    }
                }
            }
        }
    }
#endif

    // set marker to found location
    if (found) {
        _data_marker_label = value;
        _data_marker.setValue(markerx_next, 0);
        replot();        
    }
    updateStatusbar();
}
Example #27
0
void QgsComposerArrow::drawSVGMarker( QPainter* p, MarkerType type, const QString &markerPath )
{
  Q_UNUSED( markerPath );
  double ang = QgsComposerUtils::angle( mStartPoint, mStopPoint );

  double arrowHeadHeight;
  if ( type == StartMarker )
  {
    arrowHeadHeight = mStartArrowHeadHeight;
  }
  else
  {
    arrowHeadHeight = mStopArrowHeadHeight;
  }
  if ( mArrowHeadWidth <= 0 || arrowHeadHeight <= 0 )
  {
    //bad image size
    return;
  }

  QPointF imageFixPoint;
  imageFixPoint.setX( mArrowHeadWidth / 2.0 );
  QPointF canvasPoint;
  if ( type == StartMarker )
  {
    canvasPoint = QPointF( mStartPoint.x() - pos().x(), mStartPoint.y() - pos().y() );
    imageFixPoint.setY( mStartArrowHeadHeight );
  }
  else //end marker
  {
    canvasPoint = QPointF( mStopPoint.x() - pos().x(), mStopPoint.y() - pos().y() );
    imageFixPoint.setY( 0 );
  }

  QString svgFileName = ( type == StartMarker ? mStartMarkerFile : mEndMarkerFile );
  if ( svgFileName.isEmpty() )
    return;

  QSvgRenderer r;
  const QByteArray &svgContent = QgsSvgCache::instance()->svgContent( svgFileName, mArrowHeadWidth, mArrowHeadFillColor, mArrowHeadOutlineColor, mArrowHeadOutlineWidth,
                                 1.0, 1.0 );
  r.load( svgContent );

  p->save();
  p->setRenderHint( QPainter::Antialiasing );
  if ( mBoundsBehaviour == 22 )
  {
    //if arrow was created in versions prior to 2.4, use the old rendering style
    //rotate image fix point for backtransform
    QPointF fixPoint;
    if ( type == StartMarker )
    {
      fixPoint.setX( 0 );
      fixPoint.setY( arrowHeadHeight / 2.0 );
    }
    else
    {
      fixPoint.setX( 0 );
      fixPoint.setY( -arrowHeadHeight / 2.0 );
    }
    QPointF rotatedFixPoint;
    double angleRad = ang / 180 * M_PI;
    rotatedFixPoint.setX( fixPoint.x() * cos( angleRad ) + fixPoint.y() * -sin( angleRad ) );
    rotatedFixPoint.setY( fixPoint.x() * sin( angleRad ) + fixPoint.y() * cos( angleRad ) );
    p->translate( canvasPoint.x() - rotatedFixPoint.x(), canvasPoint.y() - rotatedFixPoint.y() );
  }
  else
  {
    p->translate( canvasPoint.x(), canvasPoint.y() );
  }

  p->rotate( ang );
  p->translate( -mArrowHeadWidth / 2.0, -arrowHeadHeight / 2.0 );
  r.render( p, QRectF( 0, 0, mArrowHeadWidth, arrowHeadHeight ) );
  p->restore();

  return;
}
Example #28
0
bool MavPlot::set_markerData(const Data *const d, unsigned long idx) {
    if (!d ) return false;
    if (idx >= d->size()) return false; // out of range

    bool found = false;
    double markerx = 0;
#if 0
    /*******************
     * SCAN IN Data
     *******************/
#else
    /*******************
     * SCAN IN Plot
     *******************/
    // FIXME: heavy code clone from rev_markerData()
    QPointF xy;
    QString value;
    // find out what it is, then scan for data
    const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
    if (s) {
        // it's a series
        const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
        if (curve) {
            xy = curve->sample(idx);
            markerx = xy.x();
            value = QString::number(xy.y());
            found = true;
        }
    }
    // annotation
    std::vector<QwtPlotItem*>*v = _get_annotations(d);
    if (v && !found) {
        // it's an annotation...we have to go through all of them
        if (v->size() > idx) {
            QwtPlotItem*tmp1 = (*v)[idx];
            const QwtPlotMarker * m = dynamic_cast<const QwtPlotMarker*>(tmp1);
            if (m) {
                // we only handle vertical markers
                if (QwtPlotMarker::VLine == m->lineStyle()) {
                    xy = m->value();
                    markerx = xy.x();
                    found = true;
                    value = m->label().text();
                }
            }
        }
    }
#endif

    // set marker to found location
    if (found) {
        _data_marker_label = value;
        _data_marker.setValue(markerx, 0);
        if (!_data_marker_visible) {
            _data_marker.attach(this);
            _data_marker_visible = true;
        }
        replot();        
    }
    updateStatusbar();
    return found;
}
Example #29
0
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);
    }
}
Example #30
0
void QDeclarativePinchArea::updatePinch()
{
    Q_D(QDeclarativePinchArea);
    if (d->touchPoints.count() == 0) {
        if (d->inPinch) {
            d->stealMouse = false;
            setKeepMouseGrab(false);
            d->inPinch = false;
            QPointF pinchCenter = mapFromScene(d->sceneLastCenter);
            QDeclarativePinchEvent pe(pinchCenter, d->pinchLastScale, d->pinchLastAngle, d->pinchRotation);
            pe.setStartCenter(d->pinchStartCenter);
            pe.setPreviousCenter(pinchCenter);
            pe.setPreviousAngle(d->pinchLastAngle);
            pe.setPreviousScale(d->pinchLastScale);
            pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
            pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
            pe.setPoint1(mapFromScene(d->lastPoint1));
            pe.setPoint2(mapFromScene(d->lastPoint2));
            emit pinchFinished(&pe);
            d->pinchStartDist = 0;
            d->pinchActivated = false;
            if (d->pinch && d->pinch->target())
                d->pinch->setActive(false);
        }
        return;
    }
    QTouchEvent::TouchPoint touchPoint1 = d->touchPoints.at(0);
    QTouchEvent::TouchPoint touchPoint2 = d->touchPoints.at(d->touchPoints. count() >= 2 ? 1 : 0);
    if (d->touchPoints.count() == 2
        && (touchPoint1.state() & Qt::TouchPointPressed || touchPoint2.state() & Qt::TouchPointPressed)) {
        d->id1 = touchPoint1.id();
        d->sceneStartPoint1 = touchPoint1.scenePos();
        d->sceneStartPoint2 = touchPoint2.scenePos();
        d->inPinch = false;
        d->pinchRejected = false;
        d->pinchActivated = true;
    } else if (d->pinchActivated && !d->pinchRejected) {
        const int dragThreshold = QApplication::startDragDistance();
        QPointF p1 = touchPoint1.scenePos();
        QPointF p2 = touchPoint2.scenePos();
        qreal dx = p1.x() - p2.x();
        qreal dy = p1.y() - p2.y();
        qreal dist = sqrt(dx*dx + dy*dy);
        QPointF sceneCenter = (p1 + p2)/2;
        qreal angle = QLineF(p1, p2).angle();
        if (d->touchPoints.count() == 1) {
            // If we only have one point then just move the center
            if (d->id1 == touchPoint1.id())
                sceneCenter = d->sceneLastCenter + touchPoint1.scenePos() - d->lastPoint1;
            else
                sceneCenter = d->sceneLastCenter + touchPoint2.scenePos() - d->lastPoint2;
            angle = d->pinchLastAngle;
        }
        d->id1 = touchPoint1.id();
        if (angle > 180)
            angle -= 360;
        if (!d->inPinch) {
            if (d->touchPoints.count() >= 2
                    && (qAbs(p1.x()-d->sceneStartPoint1.x()) > dragThreshold
                    || qAbs(p1.y()-d->sceneStartPoint1.y()) > dragThreshold
                    || qAbs(p2.x()-d->sceneStartPoint2.x()) > dragThreshold
                    || qAbs(p2.y()-d->sceneStartPoint2.y()) > dragThreshold)) {
                d->sceneStartCenter = sceneCenter;
                d->sceneLastCenter = sceneCenter;
                d->pinchStartCenter = mapFromScene(sceneCenter);
                d->pinchStartDist = dist;
                d->pinchStartAngle = angle;
                d->pinchLastScale = 1.0;
                d->pinchLastAngle = angle;
                d->pinchRotation = 0.0;
                d->lastPoint1 = p1;
                d->lastPoint2 = p2;
                QDeclarativePinchEvent pe(d->pinchStartCenter, 1.0, angle, 0.0);
                pe.setStartCenter(d->pinchStartCenter);
                pe.setPreviousCenter(d->pinchStartCenter);
                pe.setPreviousAngle(d->pinchLastAngle);
                pe.setPreviousScale(d->pinchLastScale);
                pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
                pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
                pe.setPoint1(mapFromScene(d->lastPoint1));
                pe.setPoint2(mapFromScene(d->lastPoint2));
                pe.setPointCount(d->touchPoints.count());
                emit pinchStarted(&pe);
                if (pe.accepted()) {
                    d->inPinch = true;
                    d->stealMouse = true;
                    QGraphicsScene *s = scene();
                    if (s && s->mouseGrabberItem() != this)
                        grabMouse();
                    setKeepMouseGrab(true);
                    if (d->pinch && d->pinch->target()) {
                        d->pinchStartPos = pinch()->target()->pos();
                        d->pinchStartScale = d->pinch->target()->scale();
                        d->pinchStartRotation = d->pinch->target()->rotation();
                        d->pinch->setActive(true);
                    }
                } else {
                    d->pinchRejected = true;
                }
            }
        } else if (d->pinchStartDist > 0) {
            qreal scale = dist ? dist / d->pinchStartDist : d->pinchLastScale;
            qreal da = d->pinchLastAngle - angle;
            if (da > 180)
                da -= 360;
            else if (da < -180)
                da += 360;
            d->pinchRotation += da;
            QPointF pinchCenter = mapFromScene(sceneCenter);
            QDeclarativePinchEvent pe(pinchCenter, scale, angle, d->pinchRotation);
            pe.setStartCenter(d->pinchStartCenter);
            pe.setPreviousCenter(mapFromScene(d->sceneLastCenter));
            pe.setPreviousAngle(d->pinchLastAngle);
            pe.setPreviousScale(d->pinchLastScale);
            pe.setStartPoint1(mapFromScene(d->sceneStartPoint1));
            pe.setStartPoint2(mapFromScene(d->sceneStartPoint2));
            pe.setPoint1(touchPoint1.pos());
            pe.setPoint2(touchPoint2.pos());
            pe.setPointCount(d->touchPoints.count());
            d->pinchLastScale = scale;
            d->sceneLastCenter = sceneCenter;
            d->pinchLastAngle = angle;
            d->lastPoint1 = touchPoint1.scenePos();
            d->lastPoint2 = touchPoint2.scenePos();
            emit pinchUpdated(&pe);
            if (d->pinch && d->pinch->target()) {
                qreal s = d->pinchStartScale * scale;
                s = qMin(qMax(pinch()->minimumScale(),s), pinch()->maximumScale());
                pinch()->target()->setScale(s);
                QPointF pos = sceneCenter - d->sceneStartCenter + d->pinchStartPos;
                if (pinch()->axis() & QDeclarativePinch::XAxis) {
                    qreal x = pos.x();
                    if (x < pinch()->xmin())
                        x = pinch()->xmin();
                    else if (x > pinch()->xmax())
                        x = pinch()->xmax();
                    pinch()->target()->setX(x);
                }
                if (pinch()->axis() & QDeclarativePinch::YAxis) {
                    qreal y = pos.y();
                    if (y < pinch()->ymin())
                        y = pinch()->ymin();
                    else if (y > pinch()->ymax())
                        y = pinch()->ymax();
                    pinch()->target()->setY(y);
                }
                if (d->pinchStartRotation >= pinch()->minimumRotation()
                        && d->pinchStartRotation <= pinch()->maximumRotation()) {
                    qreal r = d->pinchRotation + d->pinchStartRotation;
                    r = qMin(qMax(pinch()->minimumRotation(),r), pinch()->maximumRotation());
                    pinch()->target()->setRotation(r);
                }
            }
        }
    }
}