Example #1
0
void RelationshipView::configureDescriptor(void)
{
	QLineF lin;
	QPolygonF pol;
	BaseRelationship *base_rel=this->getSourceObject();
	Relationship *rel=dynamic_cast<Relationship *>(base_rel);
	unsigned rel_type=base_rel->getRelationshipType();
  float x, y, x1, y1, factor=font_config[ParsersAttributes::GLOBAL].font().pointSizeF()/DEFAULT_FONT_SIZE;
	QPen pen;
	QPointF pnt;
	vector<QPointF> points=base_rel->getPoints();
	QColor line_color=base_rel->getCustomColor();
  QGraphicsPolygonItem *pol_item=nullptr;

	//Configuring the relationship descriptor 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);

	if(rel_type==BaseRelationship::RELATIONSHIP_DEP)
		pen.setStyle(Qt::DashLine);

	descriptor->setPen(pen);

	if(line_color!=Qt::transparent)
	{
		QColor colors[2];
		QLinearGradient grad;
		BaseObjectView::getFillStyle(ParsersAttributes::RELATIONSHIP, colors[0], colors[1]);

		for(unsigned i=0; i < 2; i++)
		{
			colors[i].setRed((colors[i].red() + line_color.red() + 255)/3);
			colors[i].setGreen((colors[i].green() + line_color.green() + 255)/3);
			colors[i].setBlue((colors[i].blue() + line_color.blue() + 255)/3);
			grad.setColorAt(i, colors[i]);
		}

		grad.setCoordinateMode(QGradient::ObjectBoundingMode);;
		descriptor->setBrush(grad);
	}
	else
		descriptor->setBrush(BaseObjectView::getFillStyle(ParsersAttributes::RELATIONSHIP));


	if(rel_type==BaseRelationship::RELATIONSHIP_DEP ||
		 rel_type==BaseRelationship::RELATIONSHIP_GEN)
	{
		pol.append(QPointF(0,0)); pol.append(QPointF(21,13));
		pol.append(QPointF(0,26)); pol.append(QPointF(0,13));
	}
	else
	{
		pol.append(QPointF(13,0)); pol.append(QPointF(26,13));
		pol.append(QPointF(13,26)); pol.append(QPointF(0,13));
	}

	//Resizes the polygon according the font factor
	if(factor!=1.0f)
		this->resizePolygon(pol,
												pol.boundingRect().width() * factor ,
												pol.boundingRect().height() * factor);

	if(base_rel->isSelfRelationship())
		pnt=points.at(points.size()/2);
	else
	{
		lin=lines.at(lines.size()/2)->line();

		if(rel && rel->isIdentifier())
			pnt=lin.p1();
		else
		{
			pnt.setX((lin.p1().x() + lin.p2().x()) / 2.0f);
			pnt.setY((lin.p1().y() + lin.p2().y()) / 2.0f);
		}

		descriptor->setRotation(-lin.angle());
		obj_selection->setRotation(-lin.angle());
		obj_shadow->setRotation(-lin.angle());
	}

  x=x1=pnt.x() - (pol.boundingRect().width()/2.0f);
  y=y1=pnt.y() - (pol.boundingRect().height()/2.0f);

	protected_icon->setPos(x + ((pol.boundingRect().width()/2.0f) * 0.60f),
												 y + ((pol.boundingRect().height()/2.0f) * 0.55f));

  configureSQLDisabledInfo();
  x1+=6 * HORIZ_SPACING;
  y1-=3 * VERT_SPACING;
  sql_disabled_box->setPos(x1, y1);
  sql_disabled_txt->setPos(x1 + HORIZ_SPACING, y1 + VERT_SPACING);

	descriptor->setPolygon(pol);
	descriptor->setTransformOriginPoint(descriptor->boundingRect().center());
	descriptor->setPos(x, y);

  pol_item=dynamic_cast<QGraphicsPolygonItem *>(obj_selection);
  pol_item->setPolygon(pol);
  pol_item->setTransformOriginPoint(obj_selection->boundingRect().center());
  pol_item->setPos(x,y);
  pol_item->setBrush(this->getFillStyle(ParsersAttributes::OBJ_SELECTION));
  pol_item->setPen(this->getBorderStyle(ParsersAttributes::OBJ_SELECTION));

  pol_item=dynamic_cast<QGraphicsPolygonItem *>(obj_shadow);
  pol_item->setPolygon(pol);
  pol_item->setTransformOriginPoint(obj_shadow->boundingRect().center());
  pol_item->setPos(x + 2.5f, y + 3.5f);
  pol_item->setPen(Qt::NoPen);
  pol_item->setBrush(QColor(50,50,50,60));

	this->configureAttributes();
	this->configurePositionInfo();
}
Example #2
0
void DataCurve::loadData()
{
    Graph *g = (Graph *)plot();
    if (!g)
        return;

    int xcol = d_x_table->colIndex(d_x_column);
    int ycol = d_table->colIndex(title().text());
    if (xcol < 0 || ycol < 0) {
        remove();
        return;
    }

    int rows = d_table->numRows();
    if (d_end_row < 0 || d_end_row >= rows)
        d_end_row = rows - 1;

    int xColType = d_x_table->columnType(xcol);
    int yColType = d_table->columnType(ycol);
    int r = abs(d_end_row - d_start_row) + 1;

    QPolygonF data;
    data.reserve(r);

    QStringList xLabels, yLabels;// store text labels

    int xAxis = QwtPlot::xBottom;
    if (d_type == Graph::HorizontalBars)
        xAxis = QwtPlot::yLeft;

    QString date_time_fmt = d_table->columnFormat(xcol);
    int size = 0, from = 0;
    d_data_ranges.clear();
    for (int i = d_start_row; i <= d_end_row; i++ ) {
        QString xval = d_x_table->text(i, xcol);
        QString yval = d_table->text(i, ycol);
        if (!xval.isEmpty() && !yval.isEmpty()) {
            bool valid_data = true;
            QPointF p;
            if (xColType == Table::Text) {
                xLabels << xval;
                p.setX((double)(size + 1));
            } else if (xColType == Table::Time)
                p.setX(Table::fromTime(QTime::fromString(xval.trimmed(), date_time_fmt)));
            else if (xColType == Table::Date)
                p.setX(Table::fromDateTime(QDateTime::fromString(xval.trimmed(), date_time_fmt)));
            else
                p.setX(g->locale().toDouble(xval, &valid_data));

            if (yColType == Table::Text) {
                yLabels << yval;
                p.setY((double)(size + 1));
            } else
                p.setY(g->locale().toDouble(yval, &valid_data));

            if (valid_data) {
                data << p;
                size++;
            }
        } else if (from < size) {
            DataRange range;
            range.from = from;
            range.to = size - 1;
            d_data_ranges.push_back(range);
            from = size;
        }
    }

    if (d_data_ranges.size() && from < size) {
        DataRange range;
        range.from = from;
        range.to = size - 1;
        d_data_ranges.push_back(range);
    }

    if (!size) {
        remove();
        return;
    }
    data.resize(size);

    if (g->isWaterfallPlot()) {
        int index = g->curveIndex(this);
        int curves = g->curveCount();
        DataCurve *c = g->dataCurve(0);
        if (index > 0 && c) {
            double xmin = c->minXValue();
            double dx = index*g->waterfallXOffset()*0.01*g->canvas()->width()/(double)(curves - 1);
            d_x_offset = g->invTransform(xAxis, g->transform(xAxis, xmin) + dx) - xmin;

            double ymin = c->minYValue();
            double dy = index*g->waterfallYOffset()*0.01*g->canvas()->height()/(double)(curves - 1);
            d_y_offset = ymin - g->invTransform(yAxis(), g->transform(yAxis(), ymin) + dy);

            setZ(-index);
            setBaseline(d_y_offset);
            data.translate(d_x_offset, d_y_offset);
        } else {
            setZ(0);
            setBaseline(0.0);
        }
        if (g->grid())
            g->grid()->setZ(-g->curveCount() - 1);
    }

    double speedTol = g->getDouglasPeukerTolerance();
    if (speedTol != 0.0 && size >= g->speedModeMaxPoints()) {
        QwtWeedingCurveFitter *fitter = new QwtWeedingCurveFitter(speedTol);
        data = fitter->fitCurve(data);
        delete fitter;
    }

    if (d_type == Graph::HorizontalBars) {
        size = data.size();
        for (int i = 0; i < size; i++) {
            QPointF p = data.at(i);
            data[i] = QPointF(p.y(), p.x());
        }
    }

    setData(data);
    foreach(ErrorBarsCurve *c, d_error_bars)
        c->setData(data);

    if (xColType == Table::Text)
        g->setLabelsTextFormat(xAxis, ScaleDraw::Text, d_x_column, xLabels);
    if (yColType == Table::Text)
        g->setLabelsTextFormat(QwtPlot::yLeft, ScaleDraw::Text, title().text(), yLabels);

    setRenderHint(QwtPlotItem::RenderAntialiased, g->isCurveAntialiasingEnabled(this));

    if (!d_labels_list.isEmpty()) {
        ((Graph*)plot())->updatePlot();
        loadLabels();
    }
}
void TwoPlayerTimingGameWidget2::addEffect(
#ifdef USE_PIXMAP
      QPixmap& pixmap,
#else
      QPainter* painter,
#endif
                                  int width,
                                  int height)
{
#ifdef USE_PIXMAP
  // Get the painter
  QPainter *painter = new QPainter(&pixmap);
#endif

//  if (startAnimCount <= START_ANIM_LAST_TIME)
//  {
//    QPointF center = gameboardInfo->centerPos();
//    double size = qMax(1,
//                       qMin(FONT_DIGIT_SIZE *
//                            startAnimCount /
//                            START_ANIM_SEP_TIME,
//                            FONT_DIGIT_SIZE));
//    double opacity = startAnimCount < START_ANIM_SEP_TIME ?
//                     1.0 * startAnimCount / START_ANIM_SEP_TIME :
//                     1 - 1.0 * (startAnimCount - START_ANIM_SEP_TIME) /
//                     (START_ANIM_LAST_TIME - START_ANIM_SEP_TIME);
//    painter->setOpacity(opacity);
//    QPainterPath path;
//    path.addText(- size * 2 / 3, 0, goFont(size), "GO");

//    painter->scale(1.0 * gameboardInfo->width() / width,
//                   1.0 * gameboardInfo->height() / height);

//    QPen pen = QPen(QColor( 50, 255, 255, 100));
//    pen.setWidth(PEN_WIDTH * startAnimCount / START_ANIM_SEP_TIME);
//    painter->setPen(pen);

//    QPointF pos1 = game1ToGlobal(center);
//    painter->translate(pos1.x(), pos1.y());
//    painter->rotate(90);

//    painter->drawPath(path);
//    painter->fillPath(path, QBrush(QColor(0, 0, 0)));

//    painter->rotate(-90);
//    painter->translate(-pos1.x(), -pos1.y());

//    pos1 = game2ToGlobal(center);
//    painter->translate(pos1.x(), pos1.y());
//    painter->rotate(-90);

//    painter->drawPath(path);
//    painter->fillPath(path, QBrush(QColor(0, 0, 0)));

//    painter->rotate(90);
//    painter->translate(-pos1.x(), -pos1.y());

//    painter->setOpacity(1);

//    painter->scale(1.0 * width / gameboardInfo->width(),
//                   1.0 * height / gameboardInfo->height());
//  }

  if (timeUp)
  {
    QPointF pos;
    for (QList<int>::Iterator itr1 = endAnimCount1.begin(),
                              itr2 = endAnimBonusKind1.begin();
         itr1 != endAnimCount1.end();
         ++itr1, ++itr2)
    {
      painter->setOpacity(1.0 * (END_BONUS_ANIM_LAST_TIME - *itr1) / END_BONUS_ANIM_LAST_TIME);
      AbstractBonusItem *bonusItem = ((*itr2) == 0) ? flame1 : star1;
      pos.setX((currentScore1->getPos().x() * (*itr1) +
                bonusItem->getPos().x() * (END_BONUS_ANIM_LAST_TIME - *itr1)) /
               END_BONUS_ANIM_LAST_TIME *
               width);
      pos.setY((currentScore1->getPos().y() * (*itr1) +
                bonusItem->getPos().y() * (END_BONUS_ANIM_LAST_TIME - *itr1)) /
               END_BONUS_ANIM_LAST_TIME *
               height);
      bonusItem->paintLocatingIcon(painter, width, height, pos, frameCount);
      painter->setOpacity(1);
    }
    for (QList<int>::Iterator itr1 = endAnimCount2.begin(),
                              itr2 = endAnimBonusKind2.begin();
         itr1 != endAnimCount2.end();
         ++itr1, ++itr2)
    {
      painter->setOpacity(1.0 * (END_BONUS_ANIM_LAST_TIME - *itr1) / END_BONUS_ANIM_LAST_TIME);
      AbstractBonusItem *bonusItem = ((*itr2) == 0) ? flame2 : star2;
      pos.setX((currentScore2->getPos().x() * (*itr1) +
                bonusItem->getPos().x() * (END_BONUS_ANIM_LAST_TIME - *itr1)) /
               END_BONUS_ANIM_LAST_TIME *
               width);
      pos.setY((currentScore2->getPos().y() * (*itr1) +
                bonusItem->getPos().y() * (END_BONUS_ANIM_LAST_TIME - *itr1)) /
               END_BONUS_ANIM_LAST_TIME *
               height);
      bonusItem->paintLocatingIcon(painter, width, height, pos, frameCount);
      painter->setOpacity(1);
    }
  }

  double xRate = 1.0 * width / LOGICAL_WIDTH;
  double yRate = 1.0 * height / LOGICAL_HEIGHT;

  if (endAnimCount >= 0)
  {
    BasicPainter::darken(painter, width, height);
    painter->scale(xRate, yRate);
    painter->setOpacity(qMin(1.0, 1.0 * endAnimCount / END_ANIM_LAST_TIME));
    QPointF gFrom = QPointF(frameCount * 8, 0);
    QPointF gTo = QPointF(frameCount * 8 - 100, -100);
    QLinearGradient gradient = QLinearGradient(gFrom, gTo);
    gradient.setColorAt(0, LINENEAR_COLOR_0);
    gradient.setColorAt(1, LINENEAR_COLOR_1);
    gradient.setSpread(QGradient::ReflectSpread);
    QBrush brush = QBrush(gradient);
    painter->setPen(QPen(brush, 4));

    painter->translate((GAME1_X_FROM + GAME1_X_TO) / 2,
                       LOGICAL_HEIGHT / 2);
    painter->rotate(90);
    if (currentScore1->getValue() > currentScore2->getValue())
    {
      painter->drawPath(youWin);
      painter->fillPath(youWin, brush);
    }
    else if (currentScore1->getValue() < currentScore2->getValue())
    {
      painter->drawPath(youLose);
      painter->fillPath(youLose, brush);
    }
    else
    {
      painter->drawPath(drawGame);
      painter->fillPath(drawGame, brush);
    }
    painter->rotate(-90);
    painter->translate(-(GAME1_X_FROM + GAME1_X_TO) / 2,
                       -LOGICAL_HEIGHT / 2);

    painter->translate((GAME2_X_FROM + GAME2_X_TO) / 2,
                       LOGICAL_HEIGHT / 2);
    painter->rotate(-90);
    if (currentScore1->getValue() < currentScore2->getValue())
    {
      painter->drawPath(youWin);
      painter->fillPath(youWin, brush);
    }
    else if (currentScore1->getValue() > currentScore2->getValue())
    {
      painter->drawPath(youLose);
      painter->fillPath(youLose, brush);
    }
    else
    {
      painter->drawPath(drawGame);
      painter->fillPath(drawGame, brush);
    }
    painter->rotate(90);
    painter->translate(-(GAME2_X_FROM + GAME2_X_TO) / 2,
                       -LOGICAL_HEIGHT / 2);
    painter->scale(1 / xRate, 1 / yRate);
  }

  if (endAnimCount != -1)
  {
    ++endAnimCount;
  }

  ++startAnimCount;

#ifdef USE_PIXMAP
  // End the paint and release the space
  painter->end();
  delete painter;
#endif
}
Example #4
0
//Latest and most updated version
int calcBoundFromShapes(QString shapeConstraint,QSqlDatabase db, double &dbCellSize, double &xllCenter, double &yllCenter, int &ncols, int &nrows, int &bottom, int &left)
{
    //ShapeDataSet:shapeID,ShapeID,
    if (shapeConstraint.count(":") != 1)
    {
        gbtLog(QObject::tr("Error in shape constraint"));
        return 1;
    }

    int pos;
    pos = shapeConstraint.indexOf(":");

    QString dataset = shapeConstraint.left(pos);

    QSqlQuery qry(db);
    QString sql;

    dbCellSize = 0.0;

    sql = "SELECT cellSize FROM gbtconfig";
    if (qry.exec(sql))
    {
        if (qry.first())
            dbCellSize = qry.value(0).toDouble();
        else
            return 1;
    }
    else
        return 1;

    sql = "SELECT count(*) FROM datasetinfo WHERE dataset_id = '" + dataset + "' and dataset_type = 2";

    if (qry.exec(sql))
    {
        if (qry.first())
        {
            if (qry.value(0).toInt() == 0)
            {
                gbtLog(QObject::tr(" is not a shape dataset"));
                return 1;
            }
        }
        else
            return 1;
    }
    else
        return 1;

    sql = "SELECT shapeid,AsText(max(envelope(ogc_geom))) as boundbox FROM " + dataset + " WHERE ";
    QString shapes = shapeConstraint.mid(pos+1,shapeConstraint.length()-pos+1);
    QString shape;

    pos =0;
    while (pos <= shapes.length()-1)
    {
        if (shapes[pos] != ',')
        {
            shape = shape + shapes[pos];
            pos++;
        }
        else
        {
            sql = sql + " shapeid = " + shape + " OR ";
            shape = "";
            shapes = shapes.mid(pos+1,shapes.length()-pos+1);
            pos = 0;
        }
    }
    sql = sql + "shapeid = " + shape;
    sql = sql + " GROUP BY shapeid";

    double maxX;
    double maxY;
    double minX;
    double minY;

    maxX = -3000;
    maxY = -3000;
    minX = 3000;
    minY = 3000;


    QString cadena;
    QString geopos;

    double temp;
    if (qry.exec(sql))
    {
        while (qry.next())
        {
            cadena = qry.value(1).toString();
            pos = cadena.indexOf("(");
            cadena = cadena.mid(pos+1,cadena.length()-pos+1); //Remove the type of shape
            cadena = cadena.replace("(","");
            cadena = cadena.replace(")","");
            pos = 0;
            while (pos <= cadena.length()-1)
            {
                if (cadena[pos] != ',')
                {
                    geopos = geopos + cadena[pos];
                    pos++;
                }
                else
                {
                    cadena = cadena.mid(pos+1,cadena.length()-pos+1);

                    pos = geopos.indexOf(" ");
                    temp = geopos.left(pos).toDouble();
                    if (temp > maxX)
                        maxX = temp;
                    if (temp < minX)
                        minX = temp;

                    temp = geopos.mid(pos+1,geopos.length()-pos+1).toDouble();

                    if (temp > maxY)
                        maxY = temp;
                    if (temp < minY)
                        minY = temp;

                    pos = 0;
                    geopos = "";
                }
            }

            //Final string
            pos = geopos.indexOf(" ");
            temp = geopos.left(pos).toDouble();
            if (temp > maxX)
                maxX = temp;
            if (temp < minX)
                minX = temp;

            temp = geopos.mid(pos+1,geopos.length()-pos+1).toDouble();

            if (temp > maxY)
                maxY = temp;
            if (temp < minY)
                minY = temp;

        }
        QPointF UL;
        QPointF LR;

        UL.setX(minX);
        UL.setY(maxY);

        LR.setX(maxX);
        LR.setY(minY);


        double v_xMin,v_xMax,v_yMin,v_yMax;
        double halfx;
        int v_cols,v_rows;

        v_xMin = trunc(UL.x() / dbCellSize) * dbCellSize;
        v_yMin = trunc(LR.y() / dbCellSize) * dbCellSize;
        v_cols = trunc((LR.x() -  UL.x()) / dbCellSize) + 1;
        v_rows = trunc((UL.y() -  LR.y()) / dbCellSize) + 1;
        v_xMax = v_xMin + v_cols * dbCellSize;
        v_yMax = v_yMin + v_rows * dbCellSize;

        halfx = dbCellSize / 2;
        xllCenter = v_xMin + halfx;
        yllCenter = (v_yMin + halfx) - 0.0200;
        ncols = trunc(fabs(v_xMax - v_xMin) / dbCellSize);
        nrows = trunc(fabs(v_yMax - v_yMin) / dbCellSize);

        left = ceil((UL.x() + 180) / dbCellSize);
        bottom = ceil((90 - UL.y()) / dbCellSize);


        return 0;

    }
    else
        return 1;
}
Example #5
0
void KoTextShapeContainerModel::proposeMove(KoShape *child, QPointF &move)
{
    Relation *relation = d->children.value(child);
    if (relation == 0 || relation->anchor == 0)
        return;

    QPointF newPosition = child->position() + move;
    QRectF parentShapeRect(QPointF(0, 0), child->parent()->size());
//kDebug(32500) <<"proposeMove:" << move <<" |" << newPosition <<" |" << parentShapeRect;

    if (qAbs(newPosition.x()) < 10) // align left
        relation->anchor->setAlignment(KoTextAnchor::Left);
    else if (qAbs(parentShapeRect.width() - newPosition.x()) < 10.0)
        relation->anchor->setAlignment(KoTextAnchor::Right);
    else if (qAbs(parentShapeRect.width() / 2.0 - newPosition.x()) < 10.0)
        relation->anchor->setAlignment(KoTextAnchor::Center);
    /*else {
        relation->anchor->setAlignment(KoTextAnchor::HorizontalOffset);
        // TODO
        //QPointF offset = relation->anchor->offset();
        //offset.setX(offset.x() + move.x());
        //relation->anchor->setOffset(offset);
    } */

    if (qAbs(newPosition.y()) < 10.0) // TopOfFrame
    {
        kDebug(32500) <<"  TopOfFrame";
        relation->anchor->setAlignment(KoTextAnchor::TopOfFrame);
    } else if (qAbs(parentShapeRect.height() - newPosition.y()) < 10.0) {
        kDebug(32500) <<"  BottomOfFrame";
        relation->anchor->setAlignment(KoTextAnchor::BottomOfFrame); // TODO
    } else { // need layout info..
        QTextBlock block = relation->anchor->document()->findBlock(relation->anchor->positionInDocument());
        QTextLayout *layout = block.layout();
        if (layout->lineCount() > 0) {
            KoTextShapeData *data = dynamic_cast<KoTextShapeData*>(child->parent()->userData());
            Q_ASSERT(data);
            QTextLine tl = layout->lineAt(0);
            qreal y = tl.y() - data->documentOffset() - newPosition.y();
            if (y >= 0 && y < 10) {
                kDebug(32500) <<"  TopOfParagraph" << y <<"";
                relation->anchor->setAlignment(KoTextAnchor::TopOfParagraph);
            } else {
                tl = layout->lineAt(layout->lineCount() - 1);
                y = newPosition.y() - tl.y() - data->documentOffset() - tl.ascent();
                if (y >= 0 && y < 10) {
                    kDebug(32500) <<"  BottomOfParagraph" << y;
                    relation->anchor->setAlignment(KoTextAnchor::BottomOfParagraph); // TODO
                } else {
                    tl = layout->lineForTextPosition(relation->anchor->positionInDocument() - block.position());
                    y = tl.y() - data->documentOffset() - newPosition.y();
                    if (y >= 0 && y < 10) {
                        kDebug(32500) <<"  AboveCurrentLine";
                        relation->anchor->setAlignment(KoTextAnchor::AboveCurrentLine);
                    }
                    //else  do VerticalOffset here as well?
                }
            }
        }
    }

    move.setX(0); // let the text layout move it.
    move.setY(0);
}
Example #6
0
/**
 * Calcul les coordonnnées des différents points
 *
 * @brief   Fleche::CalculerCoordonnees()
 */
void Fleche::CalculerCoordonnees()
{
    QPointF PointDepart     (pItemDepart->pos()) ;
    QPointF PointArrivee    (pItemArrivee->pos()) ;

    //Si les deux item sont parfaitement allignés
    if(PointDepart.x() == PointArrivee.x())
    {
        if(this->bSortieDecaleeCondition)
        {
            this->CreerFlecheDecalleeVide(PointDepart, PointArrivee);
        }
        else
        {
            qreal   YDepart     (PointDepart.y() + TAILLE_V/2) ;
            qreal   YArrivee    (PointArrivee.y() - TAILLE_V/2) ;

            PointDepart.setY(YDepart) ;
            PointArrivee.setY(YArrivee) ;

            this->ListePoints.append(PointDepart);
            this->ListePoints.append(PointArrivee);
        }
    }
    else
    {
        //Sinon, si c'est un décalage vers la droite
        if(PointDepart.x() < PointArrivee.x())
        {
            qreal   XDepart     (PointDepart.x() + TAILLE_H/2) ;
            qreal   YArrivee    (PointArrivee.y() - TAILLE_V/2) ;

            PointDepart.setX(XDepart) ;
            PointArrivee.setY(YArrivee) ;

            QPointF Intermediraire  (PointArrivee.x(), PointDepart.y()) ;

            this->ListePoints.append(PointDepart);
            this->ListePoints.append(Intermediraire);
            this->ListePoints.append(PointArrivee);

        }
        else //Sinon c'est un décalage vers la gauche
        {
            if(this->bSortieDecaleeCondition)
            {
                this->CreerFlecheDecalleeVide(PointDepart, PointArrivee);
            }
            else
            {
                qreal   YDepart     (PointDepart.y() + TAILLE_V/2) ;
                qreal   YArrivee    (PointArrivee.y() - TAILLE_V) ;

                PointDepart.setY(YDepart) ;
                PointArrivee.setY(YArrivee) ;

                QPointF Intermediraire  (PointDepart.x(), PointArrivee.y()) ;

                this->ListePoints.append(PointDepart);
                this->ListePoints.append(Intermediraire);
                this->ListePoints.append(PointArrivee);
            }

        }
    }
}
Example #7
0
//Latest version
int getGridValuesFromExtent(QString extent,QSqlDatabase db, double &dbCellSize, double &xllCenter, double &yllCenter, int &ncols, int &nrows, int &bottom, int &left)
{
    //(1.3333,32.1212321) (-4.12121,41.212121)
    if (!extent.count(" ") == 1)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return 1;
    }
    if (!extent.count(",") == 2)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return 1;
    }
    if (!extent.count("(") == 2)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return 1;
    }
    if (!extent.count(")") == 2)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return 1;
    }
    int pos;
    pos = extent.indexOf(" ");
    QString from;
    QString to;
    from = extent.left(pos);
    to = extent.mid(pos+1,extent.length()-pos+1);
    from.replace("(","");
    from.replace(")","");
    to.replace("(","");
    to.replace(")","");

    //Get UpperLeft
    QPointF dupperLeft;
    pos = from.indexOf(",");
    dupperLeft.setX(from.left(pos).toDouble());
    dupperLeft.setY(from.mid(pos+1,from.length()-pos+1).toDouble());


    //Get lower right
    QPointF dlowerRight;
    pos = to.indexOf(",");
    dlowerRight.setX(to.left(pos).toDouble());
    dlowerRight.setY(to.mid(pos+1,to.length()-pos+1).toDouble());

    QSqlQuery qry(db);
    QString sql;

    dbCellSize = 0.0;

    sql = "SELECT cellSize FROM gbtconfig";
    if (qry.exec(sql))
    {
        if (qry.first())
            dbCellSize = qry.value(0).toDouble();
        else
            return 1;
    }
    else
        return 1;

    if (dbCellSize == 0.0)
        return 1;



    //*************************
    double v_xMin;
    double v_xMax;
    double v_yMin;
    double v_yMax;
    double halfx;
    int v_cols;
    int v_rows;


    v_xMin = trunc(( dupperLeft.x() *1.0/ dbCellSize )) * dbCellSize;
    v_yMin = trunc(( dlowerRight.y() *1.0/ dbCellSize )) * dbCellSize;
    v_cols = trunc( ( dlowerRight.x() - dupperLeft.x() ) *1.0/ dbCellSize ) + 1;
    v_rows = trunc( ( dupperLeft.y() - dlowerRight.y() ) *1.0/ dbCellSize ) + 1;
    v_xMax = v_xMin + v_cols * dbCellSize;
    v_yMax = v_yMin + v_rows * dbCellSize;

    halfx = dbCellSize *1.0/ 2;

    xllCenter = v_xMin + halfx;
    yllCenter = (v_yMin + halfx) - 0.0200;
    nrows = trunc( fabs( v_yMax - v_yMin ) *1.0/ dbCellSize );
    ncols = trunc(fabs(v_xMax - v_xMin) / dbCellSize);

    //*******************

    left = ceil((dupperLeft.x() + 180) / dbCellSize);
    bottom = ceil((90 - dupperLeft.y()) / dbCellSize);

    return 0;


}
Example #8
0
//virtual
QVariant AbstractGroupItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedChange) {
        if (value.toBool()) setZValue(3);
        else setZValue(1);
    }
    CustomTrackScene *scene = NULL;
    if (change == ItemPositionChange && parentItem() == 0) {
        scene = projectScene();
    }
    if (scene) {
        // calculate new position.
        if (scene->isZooming) {
            // For some reason, mouse wheel on selected itm sometimes triggered
            // a position change event corrupting timeline, so discard it
            return pos();
        }
        // calculate new position.
        const int trackHeight = KdenliveSettings::trackheight();
        QPointF start = sceneBoundingRect().topLeft();
        QPointF newPos = value.toPointF();
        int xpos = projectScene()->getSnapPointForPos((int)(start.x() + newPos.x() - pos().x()), KdenliveSettings::snaptopoints());

        xpos = qMax(xpos, 0);
        ////qDebug()<<"GRP XPOS:"<<xpos<<", START:"<<start.x()<<",NEW:"<<newPos.x()<<"; SCENE:"<<scenePos().x()<<",POS:"<<pos().x();
        newPos.setX((int)(pos().x() + xpos - (int) start.x()));
        QStringList lockedTracks = property("locked_tracks").toStringList();
	
        int proposedTrack = trackForPos(property("y_absolute").toInt() + newPos.y());
        // Check if top item is a clip or a transition
        int offset = 0;
        int topTrack = -1;
        QList<int> groupTracks;
        QList<QGraphicsItem *> children = childItems();
        for (int i = 0; i < children.count(); ++i) {
            int currentTrack = 0;
            if (children.at(i)->type() == AVWidget || children.at(i)->type() == TransitionWidget) {
                currentTrack = static_cast <AbstractClipItem*> (children.at(i))->track();
                if (!groupTracks.contains(currentTrack)) groupTracks.append(currentTrack);
            }
            else if (children.at(i)->type() == GroupWidget) {
                currentTrack = static_cast <AbstractGroupItem*> (children.at(i))->track();
            }
            else continue;
            if (children.at(i)->type() == AVWidget) {
                if (topTrack == -1 || currentTrack >= topTrack) {
                    offset = 0;
                    topTrack = currentTrack;
                }
            } else if (children.at(i)->type() == TransitionWidget) {
                if (topTrack == -1 || currentTrack > topTrack) {
                    offset = (int)(trackHeight / 3 * 2 - 1);
                    topTrack = currentTrack;
                }
            } else if (children.at(i)->type() == GroupWidget) {
                QList<QGraphicsItem *> subchildren = children.at(i)->childItems();
                bool clipGroup = false;
                for (int j = 0; j < subchildren.count(); ++j) {
                    if (subchildren.at(j)->type() == AVWidget || subchildren.at(j)->type() == TransitionWidget) {
                        int subTrack = static_cast <AbstractClipItem*> (subchildren.at(j))->track();
                        if (!groupTracks.contains(subTrack)) groupTracks.append(subTrack);
                        clipGroup = true;
                    }
                }
                if (clipGroup) {
                    if (topTrack == -1 || currentTrack >= topTrack) {
                        offset = 0;
                        topTrack = currentTrack;
                    }
                } else {
                    if (topTrack == -1 || currentTrack > topTrack) {
                        offset = (int)(trackHeight / 3 * 2 - 1);
                        topTrack = currentTrack;
                    }
                }
            }
        }
        // Check no clip in the group goes outside of existing tracks
        int maximumTrack = projectScene()->tracksCount();
        int groupHeight = 0;
        for (int i = 0; i < groupTracks.count(); ++i) {
            int trackOffset = topTrack - groupTracks.at(i) + 1;
            if (trackOffset > groupHeight) groupHeight = trackOffset;
        }
        proposedTrack = qBound(groupHeight, proposedTrack, maximumTrack);
        int groupOffset = proposedTrack - topTrack;
        if (!lockedTracks.isEmpty()) {
            for (int i = 0; i < groupTracks.count(); ++i) {
                if (lockedTracks.contains(QString::number(groupTracks.at(i) + groupOffset))) {
                    return pos();
                }
            }
        }
        newPos.setY(posForTrack(proposedTrack) + offset);
        //if (newPos == start) return start;

        /*if (newPos.x() < 0) {
            // If group goes below 0, adjust position to 0
            return QPointF(pos().x() - start.x(), pos().y());
        }*/

        QList<QGraphicsItem*> collidingItems;
        QPainterPath shape;
        if (projectScene()->editMode() == NormalEdit) {
            shape = clipGroupShape(newPos - pos());
            collidingItems = scene->items(shape, Qt::IntersectsItemShape);
            collidingItems.removeAll(this);
            for (int i = 0; i < children.count(); ++i) {
                if (children.at(i)->type() == GroupWidget) {
                    QList<QGraphicsItem *> subchildren = children.at(i)->childItems();
                    for (int j = 0; j < subchildren.count(); ++j) {
                        collidingItems.removeAll(subchildren.at(j));
                    }
                }
                collidingItems.removeAll(children.at(i));
            }
        }
        if (!collidingItems.isEmpty()) {
            bool forwardMove = xpos > start.x();
            int offset = 0;
            for (int i = 0; i < collidingItems.count(); ++i) {
                QGraphicsItem *collision = collidingItems.at(i);
                if (collision->type() == AVWidget) {
                    // Collision
                    if (newPos.y() != pos().y()) {
                        // Track change results in collision, restore original position
                        return pos();
                    }
                    AbstractClipItem *item = static_cast <AbstractClipItem *>(collision);
                    // Determine best pos
                    QPainterPath clipPath;
                    clipPath.addRect(item->sceneBoundingRect());
                    QPainterPath res = shape.intersected(clipPath);
                    offset = qMax(offset, (int)(res.boundingRect().width() + 0.5));
                }
            }
            if (offset > 0) {
                if (forwardMove) {
                    newPos.setX(newPos.x() - offset);
                } else {
                    newPos.setX(newPos.x() + offset);
                }
                // If there is still a collision after our position adjust, restore original pos
                collidingItems = scene->items(clipGroupShape(newPos - pos()), Qt::IntersectsItemShape);
                collidingItems.removeAll(this);
                for (int i = 0; i < children.count(); ++i) {
                    if (children.at(i)->type() == GroupWidget) {
                        QList<QGraphicsItem *> subchildren = children.at(i)->childItems();
                        for (int j = 0; j < subchildren.count(); ++j) {
                            collidingItems.removeAll(subchildren.at(j));
                        }
                    }
                    collidingItems.removeAll(children.at(i));
                }
                for (int i = 0; i < collidingItems.count(); ++i)
                    if (collidingItems.at(i)->type() == AVWidget) return pos();
            }
        }

        if (projectScene()->editMode() == NormalEdit) {
            shape = transitionGroupShape(newPos - pos());
            collidingItems = scene->items(shape, Qt::IntersectsItemShape);
            collidingItems.removeAll(this);
            for (int i = 0; i < children.count(); ++i) {
                if (children.at(i)->type() == GroupWidget) {
                    QList<QGraphicsItem *> subchildren = children.at(i)->childItems();
                    for (int j = 0; j < subchildren.count(); ++j) {
                        collidingItems.removeAll(subchildren.at(j));
                    }
                }
                collidingItems.removeAll(children.at(i));
            }
        }
        if (collidingItems.isEmpty()) return newPos;
        else {
            bool forwardMove = xpos > start.x();
            int offset = 0;
            for (int i = 0; i < collidingItems.count(); ++i) {
                QGraphicsItem *collision = collidingItems.at(i);
                if (collision->type() == TransitionWidget) {
                    // Collision
                    if (newPos.y() != pos().y()) {
                        // Track change results in collision, restore original position
                        return pos();
                    }
                    AbstractClipItem *item = static_cast <AbstractClipItem *>(collision);
                    // Determine best pos
		    QPainterPath clipPath;
		    clipPath.addRect(item->sceneBoundingRect());
		    QPainterPath res = shape.intersected(clipPath);
		    offset = qMax(offset, (int)(res.boundingRect().width() + 0.5));
                }
            }
            if (offset > 0) {
                if (forwardMove) {
                    newPos.setX(newPos.x() - offset);
                } else {
                    newPos.setX(newPos.x() + offset);
                }
                // If there is still a collision after our position adjust, restore original pos
                collidingItems = scene->items(transitionGroupShape(newPos - pos()), Qt::IntersectsItemShape);
                for (int i = 0; i < children.count(); ++i) {
                    collidingItems.removeAll(children.at(i));
                }
                for (int i = 0; i < collidingItems.count(); ++i)
                    if (collidingItems.at(i)->type() == TransitionWidget) return pos();
            }
        }
        return newPos;
    }
    return QGraphicsItemGroup::itemChange(change, value);
}
Example #9
0
void RawDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList<RowVectorPair>& listPairs, double channelMean) const
{
    //get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value)
    qint32 kind = (static_cast<const RawModel*>(index.model()))->m_chInfolist[index.row()].kind;
    double dMaxValue = 1e-9;

    switch(kind) {
    case FIFFV_MEG_CH: {
        qint32 unit = (static_cast<const RawModel*>(index.model()))->m_pfiffIO->m_qlistRaw[0]->info.chs[index.row()].unit;
        if(unit == FIFF_UNIT_T_M) {
            dMaxValue = m_scaleMap["MEG_grad"];
        }
        else if(unit == FIFF_UNIT_T)
            dMaxValue = m_scaleMap["MEG_mag"];
        break;
    }
    case FIFFV_EEG_CH: {
        dMaxValue = m_scaleMap["MEG_EEG"];
        break;
    }
    case FIFFV_EOG_CH: {
        dMaxValue = m_scaleMap["MEG_EOG"];
        break;
    }
    case FIFFV_STIM_CH: {
        dMaxValue = m_scaleMap["MEG_STIM"];
        break;
    }
    case FIFFV_EMG_CH: {
        dMaxValue = m_scaleMap["MEG_EMG"];
        break;
    }
    case FIFFV_MISC_CH: {
        dMaxValue = m_scaleMap["MEG_MISC"];
        break;
    }
    }

    double dValue;
    double dScaleY = option.rect.height()/(2*dMaxValue);

    double y_base = -path.currentPosition().y();
    QPointF qSamplePosition;

    path.moveTo(path.currentPosition().x(), -(y_base + ((*(listPairs[0].first) - channelMean)*dScaleY)));

    //plot all rows from list of pairs
    for(qint8 i=0; i < listPairs.size(); ++i) {
        //create lines from one to the next sample
        for(qint32 j=0; j < listPairs[i].second; ++j)
        {
            double val = *(listPairs[i].first+j);

            //subtract mean of the channel here (if wanted by the user)
            dValue = (val - channelMean)*dScaleY;

            double newY = y_base+dValue;

            qSamplePosition.setY(-newY);
            qSamplePosition.setX(path.currentPosition().x()+m_dDx);

            path.lineTo(qSamplePosition);
        }
    }

//    qDebug("Plot-PainterPath created!");
}
Example #10
0
File: Tile.cpp Project: DTRAIN/td
/**
  * Sets the bounding area for a tile.
  *
  * The logic for taking a blocking type and converting it to a bounding area.
  * Closed type will use a box based on the size of the tile, semiclosed tiles
  * will have a triangle. Open type will not have a bounding box. The
  * coordinates will be based on the position of the tile in the map.
  *
  * @author Luke Queenan
  */
void Tile::setInitialBounds(int row, int column, BlockingType type)
{
    QPointF point = QPointF();
    QVector<QPointF> points = QVector<QPointF>();
    switch (type) {
    case CLOSED:
        // Top left corner
        point.setX(column * width_ + width_);
        point.setY(row * height_);
        points.append(point);
        // Top right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_);
        points.append(point);

        // Bottom right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Bottom left corner
        point.setX(column * width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Create bounding box
        myBounds_ = QPolygonF(points);
        break;

    case NORTH_WEST:
        // Top right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_);
        points.append(point);
        // Bottom left corner
        point.setX(column * width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Bottom right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Create bounding box
        myBounds_ = QPolygonF(points);
        break;

    case NORTH_EAST:
        // Top left corner
        point.setX(column * width_);
        point.setY(row * height_);
        points.append(point);
        // Bottom left corner
        point.setX(column * width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Bottom right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Create bounding box
        myBounds_ = QPolygonF(points);
        break;

    case SOUTH_WEST:
        // Top left corner
        point.setX(column * width_);
        point.setY(row * height_);
        points.append(point);
        // Top right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_);
        points.append(point);
        // Bottom right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Create bounding box
        myBounds_ = QPolygonF(points);
        break;

    case SOUTH_EAST:
        // Top left corner
        point.setX(column * width_);
        point.setY(row * height_);
        points.append(point);
        // Top right corner
        point.setX(column * width_ + width_);
        point.setY(row * height_);
        points.append(point);
        // Bottom left corner
        point.setX(column * width_);
        point.setY(row * height_ + height_);
        points.append(point);
        // Create bounding box
        myBounds_ = QPolygonF(points);
        break;

    default:
        break;
    }
}
void CustomGraphicsScene::appendCard(int _cardType, const QString& _title, const QString& _description)
{
	QPointF scenePosition = sceneRect().center();

	//
	// Если выделена карточка
	//
	CardShape* selectedCard = nullptr;
	CardShape* previousCard = nullptr;
	CardShape* nextCard = nullptr;
	CardShape* parentCard = nullptr;
	if (!selectedItems().isEmpty()
		&& selectedItems().size() == 1
		&& (selectedCard = dynamic_cast<CardShape*>(selectedItems().last()))) {
		//
		// Если карточка вложена в группирующую, то расширяем родителя и вкладываем карту в него
		//
		if (selectedCard->parentItem() != nullptr) {
			//
			// Запомним родителя
			//
			parentCard = dynamic_cast<CardShape*>(selectedCard->parentItem());
		}

		//
		// Если выделен группирующий элемент, то соединять будем с последним из его детей
		//
		if (hasCards(selectedCard)) {
			selectedCard = dynamic_cast<CardShape*>(lastCard(selectedCard));
		}

		//
		// Предыдущей будет выделенная
		//
		previousCard = selectedCard;

		//
		// Настроим позицию для добавления новой карточки
		//
		scenePosition = previousCard->scenePos();
		scenePosition.setX(scenePosition.x() + previousCard->boundingRect().width() + SHAPE_MOVE_DELTA);
		scenePosition.setY(scenePosition.y() + previousCard->boundingRect().height() + SHAPE_MOVE_DELTA);

		//
		// Определим карточку, которая будет следовать за новой
		//
		Flow* flow = cardFlow(previousCard, CARD_ON_FLOW_START);
		if (flow != nullptr) {
			nextCard = dynamic_cast<CardShape*>(flow->endShape());
			removeShape(flow);
		}
	}
	//
	// В противном случае добавляем карточку после самой последней карточки, если карточки уже есть
	//
	else if (hasCards()) {
		//
		// Определим последнюю карточку
		//
		Shape* lastCardShape = lastCard();
		previousCard = dynamic_cast<CardShape*>(lastCardShape);

		//
		// Настроим позицию для добавления новой карточки
		//
		scenePosition = previousCard->scenePos();
		scenePosition.setX(scenePosition.x() + previousCard->boundingRect().width() + SHAPE_MOVE_DELTA);
		scenePosition.setY(scenePosition.y() + previousCard->boundingRect().height() + SHAPE_MOVE_DELTA);
	}
	//
	// В противном случае добавляем карточку по середине видимой части сцены, если подключены представления
	//
	else if (!views().isEmpty()) {
		if (QGraphicsView* view = views().last()) {
			const QRect viewportRect(0, 0, view->viewport()->width(), view->viewport()->height());
			const QRectF visibleSceneRect = view->mapToScene(viewportRect).boundingRect();
			scenePosition = visibleSceneRect.center();
		}
	}

	//
	// Добавляем карточку
	//
	CardShape* newCard = new CardShape((CardShape::CardType)_cardType, _title, _description, scenePosition, parentCard);
	insertShape(newCard, previousCard);
	//
	// ... корректируем позицию вкладываемой карточки
	//
	if (parentCard != nullptr) {
		const QPointF newPos = parentCard->mapFromScene(newCard->scenePos());
		const QPointF newBottomRightPos = newPos + QPointF(newCard->boundingRect().width(), newCard->boundingRect().height());
		//
		newCard->setParentItem(parentCard);
		newCard->setPos(newPos);
		//
		// ... и масштабируем родителя, если нужно
		//
		if (!parentCard->contains(newBottomRightPos)) {
			QSizeF newSize = parentCard->size();
			if (newSize.width() <= newBottomRightPos.x()) {
				newSize.setWidth(newBottomRightPos.x() + SHAPE_MICROMOVE_DELTA);
			}
			if (newSize.height() <= newBottomRightPos.y()) {
				newSize.setHeight(newBottomRightPos.y() + SHAPE_MICROMOVE_DELTA);
			}
			parentCard->setSize(newSize);
		}
	}

	//
	// Соединяем с предыдущей
	//
	if (previousCard != nullptr) {
		appendShape(new ArrowFlow(previousCard, newCard, parentCard));
	}

	//
	// Соединяем со следующей
	//
	if (nextCard != nullptr) {
		appendShape(new ArrowFlow(newCard, nextCard, parentCard));
	}
}
void RealTimeButterflyPlot::createPlotPath(qint32 row, QPainterPath& path) const
{
    //get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value)
    qint32 kind = m_pRealTimeEvokedModel->getKind(row);
    float fMaxValue = 1e-9f;

    switch(kind) {
        case FIFFV_MEG_CH: {
            qint32 unit =m_pRealTimeEvokedModel->getUnit(row);
            if(unit == FIFF_UNIT_T_M) { //gradiometers
                fMaxValue = 1e-10f;
                if(m_pRealTimeEvokedModel->getScaling().contains(FIFF_UNIT_T_M))
                    fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFF_UNIT_T_M];
            }
            else if(unit == FIFF_UNIT_T) //magnitometers
            {
                if(m_pRealTimeEvokedModel->getCoil(row) == FIFFV_COIL_BABY_MAG)
                    fMaxValue = 1e-11f;
                else
                    fMaxValue = 1e-11f;

                if(m_pRealTimeEvokedModel->getScaling().contains(FIFF_UNIT_T))
                    fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFF_UNIT_T];
            }
            break;
        }

        case FIFFV_REF_MEG_CH: {  /*11/04/14 Added by Limin: MEG reference channel */
            fMaxValue = 1e-11f;
            if(m_pRealTimeEvokedModel->getScaling().contains(FIFF_UNIT_T))
                fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFF_UNIT_T];
            break;
        }
        case FIFFV_EEG_CH: {
            fMaxValue = 1e-4f;
            if(m_pRealTimeEvokedModel->getScaling().contains(FIFFV_EEG_CH))
                fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFFV_EEG_CH];
            break;
        }
        case FIFFV_EOG_CH: {
            fMaxValue = 1e-3f;
            if(m_pRealTimeEvokedModel->getScaling().contains(FIFFV_EOG_CH))
                fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFFV_EOG_CH];
            break;
        }
        case FIFFV_STIM_CH: {
            fMaxValue = 5;
            if(m_pRealTimeEvokedModel->getScaling().contains(FIFFV_STIM_CH))
                fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFFV_STIM_CH];
            break;
        }
        case FIFFV_MISC_CH: {
            fMaxValue = 1e-3f;
            if(m_pRealTimeEvokedModel->getScaling().contains(FIFFV_MISC_CH))
                fMaxValue = m_pRealTimeEvokedModel->getScaling()[FIFFV_MISC_CH];
            break;
        }
    }

    float fValue;
    float fScaleY = this->height()/(2*fMaxValue);

    //restrictions for paint performance
    float fWinMaxVal = ((float)this->height()-2)/2.0f;
    qint32 iDownSampling = (m_pRealTimeEvokedModel->getNumSamples() * 4 / (this->width()-2));
    if(iDownSampling < 1)
        iDownSampling = 1;

    float y_base = path.currentPosition().y();
    QPointF qSamplePosition;

    float fDx = (float)(this->width()-2) / ((float)m_pRealTimeEvokedModel->getNumSamples()-1.0f);//((float)option.rect.width()) / m_pRealTimeEvokedModel->getMaxSamples();
//    fDx *= iDownSampling;

    RowVectorXd rowVec = m_pRealTimeEvokedModel->data(row,1).value<RowVectorXd>();
    //Move to initial starting point
    if(rowVec.size() > 0)
    {
        float val = rowVec[0];
        fValue = (val/*-rowVec[m_pRealTimeEvokedModel->getNumPreStimSamples()-1]*/)*fScaleY;//ToDo -> -2 PreStim is one too short

        float newY = y_base+fValue;

        qSamplePosition.setY(-newY);
        qSamplePosition.setX(path.currentPosition().x());

        path.moveTo(qSamplePosition);
    }

    //create lines from one to the next sample
    qint32 i;
    for(i = 1; i < rowVec.size(); ++i) {

//        if(i != m_pRealTimeEvokedModel->getNumPreStimSamples() - 2)
//        {
            float val = /*rowVec[m_pRealTimeEvokedModel->getNumPreStimSamples()-1] - */rowVec[i]; //remove first sample data[0] as offset
            fValue = val*fScaleY;

            fValue = fValue > fWinMaxVal ? fWinMaxVal : fValue < -fWinMaxVal ? -fWinMaxVal : fValue;

            float newY = y_base+fValue;

            qSamplePosition.setY(-newY);
//        }
//        else
//            qSamplePosition.setY(y_base);


        qSamplePosition.setX(path.currentPosition().x()+fDx);

        path.lineTo(qSamplePosition);
    }

//    //create lines from one to the next sample for last path
//    qint32 sample_offset = m_pRealTimeEvokedModel->numVLines() + 1;
//    qSamplePosition.setX(qSamplePosition.x() + fDx*sample_offset);
//    lastPath.moveTo(qSamplePosition);

//    for(i += sample_offset; i < lastData.size(); ++i) {
//        float val = lastData[i] - lastData[0]; //remove first sample lastData[0] as offset
//        fValue = val*fScaleY;

//        float newY = y_base+fValue;

//        qSamplePosition.setY(newY);
//        qSamplePosition.setX(lastPath.currentPosition().x()+fDx);

//        lastPath.lineTo(qSamplePosition);
//    }
}
Example #13
0
bool OpenGL_Widget::loadConfigFromJson(QString filename)
{
    FILE *f = fopen(filename.toStdString().c_str(), "r");
    if (f == NULL) {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Can't load from to %s",
            filename.toStdString().c_str());
        return false;
    }

    // Lines and parameters to read
    char line[1024];
    char param[1024];
    float val;
    QPointF cop;

    // Skip the first three lines.
    char* unused;
    unused = fgets(line, sizeof(line), f);
    unused = fgets(line, sizeof(line), f);
    unused = fgets(line, sizeof(line), f);

    // Try and read the red term
    if (fgets(line, sizeof(line), f) == NULL) {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Can't read red line");
        return false;
    }
    if (sscanf(line, "%s %g", param, &val) != 2)  {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Bad red line: %s",
            line);
        return false;
    }
    d_k1_red = val;

    // Try and read the green term
    if (fgets(line, sizeof(line), f) == NULL) {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Can't read green line");
        return false;
    }
    if (sscanf(line, "%s %g", param, &val) != 2)  {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Bad green line: %s",
            line);
        return false;
    }
    d_k1_green = val;

    // Try and read the blue term
    if (fgets(line, sizeof(line), f) == NULL) {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Can't read blue line");
        return false;
    }
    if (sscanf(line, "%s %g", param, &val) != 2)  {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Bad blue line: %s",
            line);
        return false;
    }
    d_k1_blue = val;

    // Skip the next three lines
    unused = fgets(line, sizeof(line), f);
    unused = fgets(line, sizeof(line), f);
    unused = fgets(line, sizeof(line), f);

    // Try and read the eye X COP term
    if (fgets(line, sizeof(line), f) == NULL) {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Can't read COP x line");
        return false;
    }
    if (sscanf(line, "%s %f", param, &val) != 2)  {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Bad COP x line: %s",
            line);
        return false;
    }
    cop.setX(val);

    // Try and read the eye Y COP term
    if (fgets(line, sizeof(line), f) == NULL) {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Can't read COP y line");
        return false;
    }
    if (sscanf(line, "%s %f", param, &val) != 2)  {
        fprintf(stderr, "OpenGL_Widget::loadConfigFromJson(): Bad COP y line: %s",
            line);
        return false;
    }
    cop.setY(val);

    if (fullscreen){
        d_cop = relativeToPixel(cop);
    }
    else{
        d_cop_l = relativeToPixel(cop);
        // Find the mirror of the left-eye's center of projection
        // around the screen center to find the right eye's COP.
        d_cop_r = QPoint(d_width - d_cop_l.x(), d_cop_l.y());
    }

    fclose(f);
    return true;
}
Example #14
0
void NetworkGraphics::updateNetwork(){
	qDebug() << "NetworkGraphics::updateNetwork()";

	scene->clear();
	linkMap.clear();
	rebuildNetwork();

	QPointF position = QPointF(0.0, 0.0);
	QList<raw_address> rootAddrs = network->getTopLevelAddresses();

	for(int i=0; i<rootAddrs.size(); i++){
		if(positionBranch(rootAddrs[i], position)){
			QSizeF size = computeSize(rootAddrs[i]);

			QRectF rect = QRectF(position, size);
			//scene->addRect(rect);*/

			position.setX( position.x() + size.width() + (3.0*CLOUD_X_MARGIN) );

			//scene->update(rect);
		}
	}

	//Draw links
	QList<NetLink*> links = network->getLinks();

	QPen blackPen = QPen();
	blackPen.setColor(Qt::gray);
	blackPen.setWidth(2);


	for(int i=0; i<links.size(); i++){
		NetLink* link = links[i];

		GraphicNetCloud* firstCloud = cloudMap[nodeMap[link->getFirst()]];
		GraphicNetCloud* secondCloud = cloudMap[nodeMap[link->getSecond()]];

		if(firstCloud != secondCloud){

			QPointF startPoint = firstCloud->boundingRect().center();
			QPointF endPoint = secondCloud->boundingRect().center();

			startPoint.setX(firstCloud->pos().x() + startPoint.x());
			startPoint.setY(firstCloud->pos().y() + startPoint.y());

			endPoint.setX(secondCloud->pos().x() + endPoint.x());
			endPoint.setY(secondCloud->pos().y() + endPoint.y());

			QLineF line(startPoint, endPoint);

			QGraphicsLineItem* lineItem = new QGraphicsLineItem(line);
			lineItem->setPen(blackPen);
			lineItem->setZValue(1);
			lineItem->setOpacity(.8);

			scene->addItem(lineItem);

			//qDebug() << "Line: " << line ;

			linkMap.insert(link, lineItem);
		}
	}
}
Example #15
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 );
  }

  //rasterize svg
  QSvgRenderer r;
  if ( type == StartMarker )
  {
    if ( mStartMarkerFile.isEmpty() || !r.load( mStartMarkerFile ) )
    {
      return;
    }
  }
  else //end marker
  {
    if ( mEndMarkerFile.isEmpty() || !r.load( mEndMarkerFile ) )
    {
      return;
    }
  }

  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 #16
0
void ButterflySceneItem::paintAveragePaths(QPainter *painter)
{
    //Create path for all channels
    for(int i = 0; i<m_pFiffInfo->chs.size() ;i++) {

        FiffChInfo fiffChInfoTemp = m_pFiffInfo->chs.at(i);

        if(m_pFiffInfo->bads.contains(fiffChInfoTemp.ch_name) == false) {
            //Only plot EEG or MEG channels
            if((fiffChInfoTemp.kind == FIFFV_MEG_CH && m_iSetKind == FIFFV_MEG_CH && fiffChInfoTemp.unit == FIFF_UNIT_T_M && m_iSetUnit == FIFF_UNIT_T_M) ||    //MEG grad
               (fiffChInfoTemp.kind == FIFFV_MEG_CH && m_iSetKind == FIFFV_MEG_CH && fiffChInfoTemp.unit == FIFF_UNIT_T && m_iSetUnit == FIFF_UNIT_T) ||        //MEG mag
               (fiffChInfoTemp.kind == FIFFV_EEG_CH && m_iSetKind == FIFFV_EEG_CH)) {                                                                           //EEG
                //Determine channel scaling
                double dMaxValue = 1e-09;
                switch(fiffChInfoTemp.kind) {
                    case FIFFV_MEG_CH: {
                        if(fiffChInfoTemp.unit == FIFF_UNIT_T_M) {
                            dMaxValue = m_scaleMap["MEG_grad"];
                        }
                        else if(fiffChInfoTemp.unit == FIFF_UNIT_T)
                            dMaxValue = m_scaleMap["MEG_mag"];
                        break;
                    }
                    case FIFFV_EEG_CH: {
                        dMaxValue = m_scaleMap["MEG_EEG"];
                        break;
                    }
                }

                //Get data pointer for the current channel
                const double* averageData = m_lAverageData.first;
                int totalCols =  m_lAverageData.second; //equals to the number of samples stored in the data matrix

                //Calculate downsampling factor of averaged data in respect to the items width
                int dsFactor;
                QRectF boundingRect = this->boundingRect();
                totalCols / boundingRect.width()<1 ? dsFactor = 1 : dsFactor = totalCols / boundingRect.width();

                //Calculate scaling value
                double dScaleY = (boundingRect.height())/(2*dMaxValue);

                //Setup the painter
                QPainterPath path = QPainterPath(QPointF(boundingRect.x(), *(averageData+(0*m_pFiffInfo->chs.size())+i) * -dScaleY));
                QPen pen;
                pen.setStyle(Qt::SolidLine);
                if(!m_cAverageColors.isEmpty() && i<m_cAverageColors.size())
                    pen.setColor(m_cAverageColors.at(i));
                pen.setWidthF(0.25);
                painter->setPen(pen);

                //Generate plot path
                QPointF qSamplePosition;

                for(int u = 0; u < totalCols && path.elementCount() <= boundingRect.width(); u += dsFactor) {
                    //evoked matrix is stored in column major
                    double val = (*(averageData+(u*m_pFiffInfo->chs.size())+i) * dScaleY);

                    qSamplePosition.setY(-val);
                    qSamplePosition.setX(path.currentPosition().x()+1);

                    path.lineTo(qSamplePosition);
                }

                //Paint the path
                painter->drawPath(path);
            }
        }
    }
}
void KUnitItem::slotMouseMove(QGraphicsSceneMouseEvent *event)
{
    if (myMode == MouseMode_RESIZE)
    {
        QPointF curPoint(event->scenePos());
        QPointF curPointItem = this->mapFromScene(curPoint);

        bool flagx = lastPoint.x() > oppositePos.x();
        bool flagx1 = curPointItem.x() > oppositePos.x();
        bool flagy = lastPoint.y() > oppositePos.y();
        bool flagy1 = curPointItem.y() > oppositePos.y();


        qreal dist = 0;

        QRectF rectf;
        rectf.setRect(m_frame.x()
                      , m_frame.y()
                      , m_frame.width()
                      , m_frame.height());


        KResizeFocus::PosInHost pos = curResizeFocus->getInHost();
        if (pos == KResizeFocus::NORTH_MIDDLE)
        {
            QPointF br = dashRect->rect().bottomRight();
            dist = Util::GetPointDistLine(oppositePos,br,curPointItem);

            if (dist < 20 || flagy != flagy1)
            {
                if (flagy)
                {
                    curPointItem.setY(oppositePos.y() + 20);
                }
                else
                {
                    curPointItem.setY(oppositePos.y() - 20);
                }
                dist = 20;
            }
            rectf.setY(curPointItem.y());
            rectf.setHeight(dist);
        }
        else if(pos == KResizeFocus::SOUTH_MIDDLE)
        {
            QPointF br = dashRect->rect().topRight();
            dist = Util::GetPointDistLine(oppositePos,br,curPointItem);

            if (dist < 20 || flagy != flagy1)
            {
                if (flagy)
                {
                    curPointItem.setY(oppositePos.y() + 20);
                }
                else
                {
                    curPointItem.setY(oppositePos.y() - 20);
                }
                dist = 20;
            }
            rectf.setHeight(dist);
        }
        else if(pos == KResizeFocus::EAST_MIDDLE)
        {
            QPointF br = dashRect->rect().bottomLeft();
            dist = Util::GetPointDistLine(oppositePos,br,curPointItem);

            if (dist < 20 || flagx != flagx1)
            {
                if (flagx)
                {
                    curPointItem.setX(oppositePos.x() + 20);
                }
                else
                {
                    curPointItem.setX(oppositePos.x() - 20);
                }
                dist = 20;
            }
            rectf.setWidth(dist);
        }
        else if(pos == KResizeFocus::WEST_MIDDLE)
        {
            QPointF br = dashRect->rect().bottomRight();
            dist = Util::GetPointDistLine(oppositePos,br,curPointItem);

            if (dist < 20 || flagx != flagx1)
            {
                if (flagx)
                {
                    curPointItem.setX(oppositePos.x() + 20);
                }
                else
                {
                    curPointItem.setX(oppositePos.x() - 20);
                }
                dist = 20;
            }
            rectf.setX(curPointItem.x());
            rectf.setWidth(dist);
        }
        else if(pos == KResizeFocus::NORTH_WEST)
        {
            QPointF topRight = dashRect->rect().topRight();
            QPointF bottomLeft = dashRect->rect().bottomLeft();

            qreal distx = Util::GetPointDistLine(oppositePos,topRight,curPointItem);
            qreal disty = Util::GetPointDistLine(oppositePos,bottomLeft,curPointItem);

            if (distx < 20 || flagx != flagx1)
            {
                if (flagx)
                {
                    curPointItem.setX(oppositePos.x() + 20);
                }
                else
                {
                    curPointItem.setX(oppositePos.x() - 20);
                }
                distx = 20;
            }
            if (disty < 20 || flagy != flagy1)
            {
                if (flagy)
                {
                    curPointItem.setY(oppositePos.y() + 20);
                }
                else
                {
                    curPointItem.setY(oppositePos.y() - 20);
                }
                disty = 20;
            }

            rectf.setTopLeft(curPointItem);
        }
        else if(pos == KResizeFocus::NORTH_EAST)
        {
            QPointF topLeft = dashRect->rect().topLeft();
            QPointF bottomRight = dashRect->rect().bottomRight();

            qreal distx = Util::GetPointDistLine(oppositePos,topLeft,curPointItem);
            qreal disty = Util::GetPointDistLine(oppositePos,bottomRight,curPointItem);

            if (distx < 20 || flagx != flagx1)
            {
                if (flagx)
                {
                    curPointItem.setX(oppositePos.x() + 20);
                }
                else
                {
                    curPointItem.setX(oppositePos.x() - 20);
                }
                distx = 20;
            }
            if (disty < 20 || flagy != flagy1)
            {
                if (flagy)
                {
                    curPointItem.setY(oppositePos.y() + 20);
                }
                else
                {
                    curPointItem.setY(oppositePos.y() - 20);
                }
                disty = 20;
            }

            rectf.setTopRight(curPointItem);
        }
        else if(pos == KResizeFocus::SOUTH_EAST)
        {
            QPointF topRight = dashRect->rect().topRight();
            QPointF bottomLeft = dashRect->rect().bottomLeft();

            qreal disty = Util::GetPointDistLine(oppositePos,topRight,curPointItem);
            qreal distx = Util::GetPointDistLine(oppositePos,bottomLeft,curPointItem);

            if (distx < 20 || flagx != flagx1)
            {
                if (flagx)
                {
                    curPointItem.setX(oppositePos.x() + 20);
                }
                else
                {
                    curPointItem.setX(oppositePos.x() - 20);
                }
                distx = 20;
            }
            if (disty < 20 || flagy != flagy1)
            {
                if (flagy)
                {
                    curPointItem.setY(oppositePos.y() + 20);
                }
                else
                {
                    curPointItem.setY(oppositePos.y() - 20);
                }
                disty = 20;
            }

            rectf.setBottomRight(curPointItem);
        }
        else if(pos == KResizeFocus::SOUTH_WEST)
        {
            QPointF topLeft = dashRect->rect().topLeft();
            QPointF bottomRight = dashRect->rect().bottomRight();

            qreal disty = Util::GetPointDistLine(oppositePos,topLeft,curPointItem);
            qreal distx = Util::GetPointDistLine(oppositePos,bottomRight,curPointItem);

            if (distx < 20 || flagx != flagx1)
            {
                if (flagx)
                {
                    curPointItem.setX(oppositePos.x() + 20);
                }
                else
                {
                    curPointItem.setX(oppositePos.x() - 20);
                }
                distx = 20;
            }
            if (disty < 20 || flagy != flagy1)
            {
                if (flagy)
                {
                    curPointItem.setY(oppositePos.y() + 20);
                }
                else
                {
                    curPointItem.setY(oppositePos.y() - 20);
                }
                disty = 20;
            }
            rectf.setBottomLeft(curPointItem);
        }

        dashRect->setRect(rectf);
    }
    else if(myMode == MouseMode_ROTATE)
    {
        QPointF curPos = event->scenePos();
        QPointF cpos = this->mapToScene(frame().center());
//        qDebug()<<cpos;
		qreal angleLast = Util::ComputeAngle(mLastRotatePoint, cpos);
		qreal angleCur = Util::ComputeAngle(curPos, cpos);
        qreal angle = angleCur - angleLast;

        setAngle(angle);
        mLastRotatePoint = curPos;
        onRotate();
    }
    else if(myMode == MouseMode_MOVE)
    {
        onMoving();
    }
    else
    {
        QGraphicsItem::mouseMoveEvent(event);
    }
}
Example #18
0
//virtual
QVariant Transition::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedChange) {
        if (value.toBool()) setZValue(5);
        else setZValue(4);
    }
    CustomTrackScene *scene = NULL;
    if (change == ItemPositionChange) {
        scene = projectScene();
    }
    if (scene) {
        // calculate new position.
        if (scene->isZooming) {
            // For some reason, mouse wheel on selected itm sometimes triggered
            // a position change event corrupting timeline, so discard it
            return pos();
        }
        QPointF newPos = value.toPointF();
        int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
        xpos = qMax(xpos, 0);
        newPos.setX(xpos);
        int newTrack = trackForPos(newPos.y());
        QStringList lockedTracks = property("locked_tracks").toStringList();
        if (lockedTracks.contains(QString::number(newTrack))) {
            // Trying to move to a locked track
            return pos();
        }
        int maximumTrack = projectScene()->tracksCount();
        newTrack = qMin(newTrack, maximumTrack);
        newTrack = qMax(newTrack, 0);
        newPos.setY(posForTrack(newTrack) + itemOffset());

        // Only one clip is moving
        QRectF sceneShape = rect();
        sceneShape.translate(newPos);
        QList<QGraphicsItem*> items;
        // TODO: manage transitions in OVERWRITE MODE
        //if (projectScene()->editMode() == NORMALEDIT)
        items = scene->items(sceneShape, Qt::IntersectsItemShape);
        items.removeAll(this);

        bool forwardMove = newPos.x() > pos().x();
        if (!items.isEmpty()) {
            for (int i = 0; i < items.count(); ++i) {
                if (!items.at(i)->isEnabled()) continue;
                if (items.at(i)->type() == type()) {
                    int offset = 0;
                    // Collision!
                    QPointF otherPos = items.at(i)->pos();
                    if ((int) otherPos.y() != (int) pos().y()) {
                        return pos();
                    }
                    if (forwardMove) {
                        offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
                    } else {
                        offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
                    }

                    if (offset > 0) {
                        if (forwardMove) {
                            sceneShape.translate(QPointF(-offset, 0));
                            newPos.setX(newPos.x() - offset);
                        } else {
                            sceneShape.translate(QPointF(offset, 0));
                            newPos.setX(newPos.x() + offset);
                        }
                        QList<QGraphicsItem*> subitems = scene->items(sceneShape, Qt::IntersectsItemShape);
                        subitems.removeAll(this);
                        for (int j = 0; j < subitems.count(); ++j) {
                            if (!subitems.at(j)->isEnabled()) continue;
                            if (subitems.at(j)->type() == type()) {
                                // move was not successful, revert to previous pos
                                m_info.startPos = GenTime((int) pos().x(), m_fps);
                                return pos();
                            }
                        }
                    }

                    m_info.track = newTrack;
                    m_info.startPos = GenTime((int) newPos.x(), m_fps);

                    return newPos;
                }
            }
        }

        m_info.track = newTrack;
        m_info.startPos = GenTime((int) newPos.x(), m_fps);
        ////qDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
        return newPos;
    }
    return QGraphicsItem::itemChange(change, value);
}
bool IGraphicsItem::onSceneEventFilter(QGraphicsItem *watched, QEvent *event)
{
    auto *corner = dynamic_cast<CornerGrabber*>(watched);
    if(!corner) return false;

    auto *mevent = dynamic_cast<QGraphicsSceneMouseEvent*>(event);
    if(!mevent) return false;

    switch(event->type()) {
    case QEvent::GraphicsSceneMousePress:
        moving_ = true;
        start_pos_ = mevent->scenePos();
        setGrabbersState(true);
        return true;
    case QEvent::GraphicsSceneMouseRelease:
    case QEvent::GraphicsSceneMouseMove:
        break;
    default:
        return false;
    }

    if(!moving_) return true;

    QPointF delta = mevent->scenePos() - start_pos_;
    if(aspectRatioMode() == Qt::KeepAspectRatio) {
        QSizeF s = size();
        qreal grad = s.height() / s.width();

        if(corner->iX() ^ corner->iY()) {
            grad = -grad;
        }

        if((delta.y() > grad * delta.x()) ^ !corner->iY()) {
            delta.setX(delta.y() / grad);
        } else {
            delta.setY(grad * delta.x());
        }
    }

    QRectF rect = item_->boundingRect();

    qreal x, y, w, h;

    if(corner->iX() == 0) {
        x = rect.x() + delta.x();
        w = rect.width() - delta.x();
    } else {
        x = rect.x();
        w = rect.width() + delta.x();
    }

    if(corner->iY() == 0) {
        y = rect.y() + delta.y();
        h = rect.height() - delta.y();
    } else {
        y = rect.y();
        h = rect.height() + delta.y();
    }

    if(event->type() == QEvent::GraphicsSceneMouseRelease) {
        moving_ = false;
        setSize(QSize(w - 1, h - 1));
        update();
        setGrabbersState(false);
        item_->setPos(item_->pos() + QPointF(x + 0.5, y + 0.5));
        updatePos();
        x = rect.x();
        y = rect.y();
    }
    setGrabbersPosition(QRectF(x,y,w,h));

    return true;

}
Example #20
0
void QtViewportInteractionEngine::zoomToAreaGestureEnded(const QPointF& touchPoint, const QRectF& targetArea)
{
    if (!targetArea.isValid())
        return;

    if (scrollAnimationActive() || scaleAnimationActive())
        return;

    m_hadUserInteraction = true;

    const int margin = 10; // We want at least a little bit of margin.
    QRectF endArea = itemRectFromCSS(targetArea.adjusted(-margin, -margin, margin, margin));

    const QRectF viewportRect = m_viewport->boundingRect();

    qreal targetCSSScale = viewportRect.size().width() / endArea.size().width();
    qreal endCSSScale = innerBoundedCSSScale(qMin(targetCSSScale, qreal(2.5)));
    qreal endItemScale = itemScaleFromCSS(endCSSScale);
    qreal currentScale = m_content->contentsScale();

    // We want to end up with the target area filling the whole width of the viewport (if possible),
    // and centralized vertically where the user requested zoom. Thus our hotspot is the center of
    // the targetArea x-wise and the requested zoom position, y-wise.
    const QPointF hotspot = QPointF(endArea.center().x(), itemCoordFromCSS(touchPoint.y()));
    const QPointF viewportHotspot = viewportRect.center();

    QPointF endPosition = hotspot * endCSSScale - viewportHotspot;

    QRectF endPosRange = computePosRangeForItemAtScale(endItemScale);
    endPosition = boundPosition(endPosRange.topLeft(), endPosition, endPosRange.bottomRight());

    QRectF endVisibleContentRect(endPosition / endItemScale, viewportRect.size() / endItemScale);

    enum { ZoomIn, ZoomBack, ZoomOut, NoZoom } zoomAction = ZoomIn;

    if (!m_scaleStack.isEmpty()) {
        // Zoom back out if attempting to scale to the same current scale, or
        // attempting to continue scaling out from the inner most level.
        // Use fuzzy compare with a fixed error to be able to deal with largish differences due to pixel rounding.
        if (fuzzyCompare(endItemScale, currentScale, 0.01)) {
            // If moving the viewport would expose more of the targetRect and move at least 40 pixels, update position but do not scale out.
            QRectF currentContentRect(m_viewport->contentPos() / currentScale, viewportRect.size() / currentScale);
            QRectF targetIntersection = endVisibleContentRect.intersected(targetArea);
            if (!currentContentRect.contains(targetIntersection) && (qAbs(endVisibleContentRect.top() - currentContentRect.top()) >= 40 || qAbs(endVisibleContentRect.left() - currentContentRect.left()) >= 40))
                zoomAction = NoZoom;
            else
                zoomAction = ZoomBack;
        } else if (fuzzyCompare(endItemScale, m_zoomOutScale, 0.01))
            zoomAction = ZoomBack;
        else if (endItemScale < currentScale)
            zoomAction = ZoomOut;
    }

    switch (zoomAction) {
    case ZoomIn:
        m_scaleStack.append(ScaleStackItem(currentScale, m_viewport->contentPos().x()));
        m_zoomOutScale = endItemScale;
        break;
    case ZoomBack: {
        ScaleStackItem lastScale = m_scaleStack.takeLast();
        endItemScale = lastScale.scale;
        endCSSScale = cssScaleFromItem(lastScale.scale);
        // Recalculate endPosition and bound it according to new scale.
        endPosition.setY(hotspot.y() * endCSSScale - viewportHotspot.y());
        endPosition.setX(lastScale.xPosition);
        endPosRange = computePosRangeForItemAtScale(endItemScale);
        endPosition = boundPosition(endPosRange.topLeft(), endPosition, endPosRange.bottomRight());
        endVisibleContentRect = QRectF(endPosition / endItemScale, viewportRect.size() / endItemScale);
        break;
    }
    case ZoomOut:
        // Unstack all scale-levels deeper than the new level, so a zoom-back won't end up zooming in.
        while (!m_scaleStack.isEmpty() && m_scaleStack.last().scale >= endItemScale)
            m_scaleStack.removeLast();
        m_zoomOutScale = endItemScale;
        break;
    case NoZoom:
        break;
    }

    animateItemRectVisible(endVisibleContentRect);
}
Example #21
0
QString getWhereClauseFromExtent(QString extent,QSqlDatabase db, QString table)
{
    //(1.3333,32.1212321) (-4.12121,41.212121)
    if (!extent.count(" ") == 1)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return QString();
    }
    if (!extent.count(",") == 2)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return QString();
    }
    if (!extent.count("(") == 2)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return QString();
    }
    if (!extent.count(")") == 2)
    {
        gbtLog(QObject::tr("Extent is invalid"));
        return QString();
    }
    int pos;
    pos = extent.indexOf(" ");
    QString from;
    QString to;
    from = extent.left(pos);
    to = extent.mid(pos+1,extent.length()-pos+1);
    from.replace("(","");
    from.replace(")","");
    to.replace("(","");
    to.replace(")","");

    //Get UpperLeft
    QPointF dupperLeft;
    pos = from.indexOf(",");
    dupperLeft.setX(from.left(pos).toDouble());
    dupperLeft.setY(from.mid(pos+1,from.length()-pos+1).toDouble());


    //Get lower right
    QPointF dlowerRight;
    pos = to.indexOf(",");
    dlowerRight.setX(to.left(pos).toDouble());
    dlowerRight.setY(to.mid(pos+1,to.length()-pos+1).toDouble());

    QSqlQuery qry(db);
    QString sql;

    double dbCellSize;
    dbCellSize = 0.0;

    sql = "SELECT cellSize FROM gbtconfig";
    if (qry.exec(sql))
    {
        if (qry.first())
            dbCellSize = qry.value(0).toDouble();
        else
            return QString();
    }
    else
        return QString();

    if (dbCellSize == 0.0)
        return QString();
    double xllCenter;
    double yllCenter;
    int NumberRows;
    sql = "SELECT xllCenter,yllCenter,nrows FROM datasetinfo WHERE dataset_id = '" + table + "'";
    if (qry.exec(sql))
    {
        if (qry.first())
        {
            xllCenter = qry.value(0).toDouble();
            yllCenter = qry.value(1).toDouble();
            NumberRows = qry.value(2).toInt();
        }
        else
            return QString();
    }
    else
        return QString();

    QPoint upperLeft;
    QPoint lowerRight;

    int xpos;
    int ypos;

    if(dbCellSize != 0.0)
    {
        //Plots the bounds in the grid
        upperLeft.setX(round( ( dupperLeft.x() - xllCenter )/dbCellSize ));
        upperLeft.setY(NumberRows - round( ( dupperLeft.y() - yllCenter )/dbCellSize ) - 1);


        QPointF UL;
        UL = dupperLeft;

        lowerRight.setX(round( ( dlowerRight.x() - xllCenter )/dbCellSize ));
        lowerRight.setY(NumberRows - round( ( dlowerRight.y() - yllCenter )/dbCellSize ) - 1);

        QPointF LR;
        LR = dlowerRight;

        //Plots the bounds in the GOBLET coordinate system
        ypos = round((180/dbCellSize) - (fabs((-90 - yllCenter)/dbCellSize) + NumberRows)) + 1;
        xpos = round(fabs((-180 - xllCenter)/dbCellSize))+1;

        upperLeft.setX(xpos + upperLeft.x());
        upperLeft.setY(ypos + upperLeft.y());

        lowerRight.setX(xpos + lowerRight.x());
        lowerRight.setY(ypos + lowerRight.y());

        //Crete the where clause

        QString idsuit;
        idsuit = getStrValue(upperLeft.y()) + getStrValue(upperLeft.x());

        QString where;
        where = " TA.geokey BETWEEN '" + idsuit + "' AND ";

        idsuit = getStrValue(lowerRight.y()) + getStrValue(lowerRight.x());
        where = where + "'" + idsuit + "'";
        return where;

    }

    return QString();
}
Example #22
0
/**
 * Update position the edge
 */
void GuiEdge::updatePosition (bool original_run)
{
	GuiNode* pre = addGui (pred());
	GuiNode* suc = addGui (succ());

	edge_start_point_priv = mapFromItem( pre, pre->width()/2, pre->height()/2);
    edge_end_point_priv = mapFromItem( suc, suc->width()/2, suc->height()/2);//!!!rarely it not work

	if (pre == suc)//mesh edge
	{
		QPointF heigh (0, 2*pre->height());

		QPointF middle (pre->pos().x() - 10, pre->pos().y() + pre->height()/2);
		QPointF middleDirUp = middle + heigh;
		QPointF middleDirDown = middle - heigh;

		edge_start_dir_priv = edge_start_point_priv + heigh;
		edge_end_dir_priv = edge_end_point_priv - heigh;

		QPolygonF polygon = suc->polygon();
		polygon.translate (suc->pos());
		getIntersection (QLineF (edge_start_point_priv, edge_start_dir_priv), polygon, &edge_start_point_priv);
		getIntersection (QLineF (edge_end_point_priv, edge_end_dir_priv), polygon, &edge_end_point_priv);

		QPainterPath path;
		path.moveTo (edge_start_point_priv);
		path.cubicTo (edge_start_dir_priv, middleDirUp, middle);
		path.cubicTo (middleDirDown, edge_end_dir_priv, edge_end_point_priv);
		edge_curve_priv = path;
	}
	else
	{
		edge_valid_priv = true;
		
		QPolygonF headPolygon = suc->polygon();
		headPolygon.translate (suc->pos());
		QPolygonF tailPolygon = pre->polygon();
		tailPolygon.translate (pre->pos());


		if (suc->real())
			edge_valid_priv = edge_valid_priv && getIntersection (QLineF (edge_start_point_priv, edge_end_point_priv), headPolygon, &edge_end_point_priv) == QLineF::BoundedIntersection;
		if (pre->real()) 
			edge_valid_priv = edge_valid_priv && getIntersection (QLineF (edge_start_point_priv, edge_end_point_priv), tailPolygon, &edge_start_point_priv) == QLineF::BoundedIntersection;

		QPointF delta = edge_start_point_priv - edge_end_point_priv;
		delta.setX(0);

		if (pre->real()) 
			edge_start_dir_priv = (edge_start_point_priv + edge_end_point_priv)/2;
		else
		{
			if (pre->firstPred() != 0)
				edge_start_dir_priv = (suc->coor() - pre->firstPred()->pred()->coor())/8 + pre->coor();
			else
				edge_start_dir_priv = edge_start_point_priv - delta/2;
		}

		if (suc->real())
			edge_end_dir_priv = (edge_start_point_priv + edge_end_point_priv)/2;
		else
			if (suc->firstSucc() != 0)
				edge_end_dir_priv = (pre->coor() - suc->firstSucc()->succ()->coor())/8 + suc->coor();
			else
				edge_end_dir_priv = edge_end_point_priv + delta/2;

		QPainterPath path;
		path.moveTo (edge_start_point_priv);
		path.cubicTo (edge_start_dir_priv, edge_end_dir_priv, edge_end_point_priv);

		if (edge_valid_priv) edge_curve_priv = path;
	}

    edge_top_left_priv.setX( min< qreal>( edge_start_point_priv.x(), edge_end_point_priv.x()));
    edge_top_left_priv.setY( min< qreal>( edge_start_point_priv.y(), edge_end_point_priv.y()));
    edge_bottom_right_priv.setX( max< qreal>( edge_start_point_priv.x(), edge_end_point_priv.x()));
    edge_bottom_right_priv.setY( max< qreal>( edge_start_point_priv.y(), edge_end_point_priv.y())); 

	if (original_run)
	{
		if (Edge::succ() && !addAux (Edge::succ())->real() && Edge::succ()->firstSucc())
			addGui (Edge::succ()->firstSucc())->updatePosition (false);//avoidance sharp corners
		
		if (Edge::pred() && !addAux (Edge::pred())->real() && Edge::pred()->firstPred())
			addGui (Edge::pred()->firstPred())->updatePosition (false);//avoidance sharp corners
		
		GuiEdge* i = this;
		for (i; !i->startEdge(); i->pred()->firstPred() && (i = addGui (i->pred()->firstPred())));
		i->updateLabels();
	}
    prepareGeometryChange();
}
Example #23
0
//Most updated version
int calcExtendFromGrid(QString gridName,QSqlDatabase db, double &dbCellSize, double &xllCenter, double &yllCenter, int &ncols, int &nrows, int &bottom, int &left)
{
    QSqlQuery qry(db);
    QString sql;

    dbCellSize = 0.0;

    sql = "SELECT cellSize FROM gbtconfig";
    if (qry.exec(sql))
    {
        if (qry.first())
            dbCellSize = qry.value(0).toDouble();
        else
            return 1;
    }
    else
        return 1;



    sql = "SELECT xllcenter,yllcenter,ncols,nrows FROM datasetinfo WHERE dataset_id = '" + gridName + "' and dataset_type = 1";

    if (qry.exec(sql))
    {
        if (qry.first())
        {
            xllCenter = qry.value(0).toDouble();
            yllCenter = qry.value(1).toDouble() - 0.0200;
            ncols = qry.value(2).toInt();
            nrows = qry.value(3).toInt();
        }
        else
            return 1;
    }
    else
        return 1;

    int xpos;
    int ypos;
    ypos = round((180/dbCellSize) - (fabs((-90 - yllCenter)/dbCellSize) + nrows)) + 1;
    xpos = round(fabs((-180 - xllCenter)/dbCellSize))+1;

    sql = "SELECT max(xpos),max(ypos),min(xpos),min(ypos) FROM " + gridName;
    if (qry.exec(sql))
    {
        if (qry.first())
        {
            //double utx;
            //double uty;

            //utx = ((qry.value(0).toInt() - xpos) * dbCellSize) + xllCenter;
            //uty = (((((qry.value(1).toInt() - ypos) + 1) - nrows) * dbCellSize) - yllCenter) * -1;

            double ltx;
            double lty;

            ltx = ((qry.value(2).toInt() - xpos) * dbCellSize) + xllCenter;
            lty = (((((qry.value(3).toInt() - ypos) + 1) - nrows) * dbCellSize) - yllCenter) * -1;

            QPointF UL;

            UL.setX(ltx);
            UL.setY(lty);


            left = ceil((UL.x() + 180) / dbCellSize);
            bottom = ceil((90 - UL.y()) / dbCellSize);

            return 0;

        }
        else
            return 1;
    }
    else
        return 1;

}
Example #24
0
void QAbstractKineticScrollerPrivate::handleMove(QMouseEvent *me, QPoint &delta)
{
    Q_Q(QAbstractKineticScroller);

    if (mode == QAbstractKineticScroller::AccelerationMode) {
        // we need delta to be the delta to ipos, not pos in this case
        delta = me->globalPos() - ipos;
    }

    if (axisLockThreshold) {
        int dx = qAbs(delta.x());
        int dy = qAbs(delta.y());
        if (dx || dy) {
            bool vertical = (dy > dx);
            qreal alpha = qreal(vertical ? dx : dy) / qreal(vertical ? dy : dx);
            qKSDebug() << "axis lock: " << alpha << " / " << axisLockThreshold << " - isvertical: " << vertical << " - dx: " << dx << " - dy: " << dy;
            if (alpha <= axisLockThreshold) {
                if (vertical)
                    delta.setX(0);
                else
                    delta.setY(0);
            }
        }
    }

    switch (mode) {
    case QAbstractKineticScroller::PushMode:
        // Scroll by the amount of pixels the cursor has moved
        // since the last motion event.
        scrollUpdate(delta);
        pos = me->globalPos();
        break;

    case QAbstractKineticScroller::AccelerationMode: {
        // Set acceleration relative to the initial click
        QSize size = q->viewportSize();
        qreal signX = 0, signY = 0;
        if (delta.x() < 0)
            signX = -1;
        else if (delta.x() > 0)
            signX = 1;
        if (delta.y() < 0)
            signY = -1;
        else if (delta.y() > 0)
            signY = 1;

        velocity.setX(signX * ((qreal(qAbs(delta.x())) / qreal(size.width()) * (maxVelocity - minVelocity)) + minVelocity));
        velocity.setY(signY * ((qreal(qAbs(delta.y())) / qreal(size.height()) * (maxVelocity - minVelocity)) + minVelocity));
        break;
    }
    case QAbstractKineticScroller::AutoMode:
        QPointF newVelocity = calculateVelocity(delta, lastTime.elapsed());
        QPoint maxPos = q->maximumScrollPosition();

        bool alwaysOvershoot = (overshootPolicy == QAbstractKineticScroller::OvershootAlwaysOn);

        if (!maxPos.x() && !alwaysOvershoot) {
            delta.setX(0);
            newVelocity.setX(0);
        }
        if (!maxPos.y() && !alwaysOvershoot) {
            delta.setY(0);
            newVelocity.setY(0);
        }
        velocity = newVelocity;

        scrollUpdate(delta);

        if (maxPos.x() || alwaysOvershoot)
            pos.setX(me->globalPos().x());
        if (maxPos.y() || alwaysOvershoot)
            pos.setY(me->globalPos().y());
        break;
    }
}
Example #25
0
void PageViewportControllerClientQt::zoomToAreaGestureEnded(const QPointF& touchPoint, const QRectF& targetArea)
{
    // This can only happen as a result of a user interaction.
    ASSERT(m_controller->hadUserInteraction());

    if (!targetArea.isValid())
        return;

    if (m_scrollChange.inProgress() || m_scaleChange.inProgress())
        return;

    const float margin = 10; // We want at least a little bit of margin.
    QRectF endArea = targetArea.adjusted(-margin, -margin, margin, margin);

    const QRectF viewportRect = m_viewportItem->boundingRect();

    qreal minViewportScale = qreal(2.5);
    qreal targetScale = viewportRect.size().width() / endArea.size().width();
    targetScale = m_controller->innerBoundedViewportScale(qMin(minViewportScale, targetScale));
    qreal currentScale = m_pageItem->contentsScale();

    // We want to end up with the target area filling the whole width of the viewport (if possible),
    // and centralized vertically where the user requested zoom. Thus our hotspot is the center of
    // the targetArea x-wise and the requested zoom position, y-wise.
    const QPointF hotspot = QPointF(endArea.center().x(), touchPoint.y());
    const QPointF viewportHotspot = viewportRect.center();

    QPointF endPosition = hotspot - viewportHotspot / targetScale;
    endPosition = m_controller->clampViewportToContents(endPosition, targetScale);
    QRectF endVisibleContentRect(endPosition, viewportRect.size() / targetScale);

    enum { ZoomIn, ZoomBack, ZoomOut, NoZoom } zoomAction = ZoomIn;

    // Zoom back out if attempting to scale to the same current scale, or
    // attempting to continue scaling out from the inner most level.
    // Use fuzzy compare with a fixed error to be able to deal with largish differences due to pixel rounding.
    if (!m_scaleStack.isEmpty() && fuzzyCompare(targetScale, currentScale, 0.01)) {
        // If moving the viewport would expose more of the targetRect and move at least 40 pixels, update position but do not scale out.
        QRectF currentContentRect(m_viewportItem->mapRectToWebContent(viewportRect));
        QRectF targetIntersection = endVisibleContentRect.intersected(targetArea);
        if (!currentContentRect.contains(targetIntersection)
            && (qAbs(endVisibleContentRect.top() - currentContentRect.top()) >= 40
            || qAbs(endVisibleContentRect.left() - currentContentRect.left()) >= 40))
            zoomAction = NoZoom;
        else
            zoomAction = ZoomBack;
    } else if (fuzzyCompare(targetScale, m_zoomOutScale, 0.01))
        zoomAction = ZoomBack;
    else if (targetScale < currentScale)
        zoomAction = ZoomOut;

    switch (zoomAction) {
    case ZoomIn:
        m_scaleStack.append(ScaleStackItem(currentScale, m_viewportItem->contentPos().x() / currentScale));
        m_zoomOutScale = targetScale;
        break;
    case ZoomBack: {
        if (m_scaleStack.isEmpty()) {
            targetScale = m_controller->minimumContentsScale();
            endPosition.setY(hotspot.y() - viewportHotspot.y() / targetScale);
            endPosition.setX(0);
            m_zoomOutScale = 0;
        } else {
            ScaleStackItem lastScale = m_scaleStack.takeLast();
            targetScale = lastScale.scale;
            // Recalculate endPosition and clamp it according to the new scale.
            endPosition.setY(hotspot.y() - viewportHotspot.y() / targetScale);
            endPosition.setX(lastScale.xPosition);
        }
        endPosition = m_controller->clampViewportToContents(endPosition, targetScale);
        endVisibleContentRect = QRectF(endPosition, viewportRect.size() / targetScale);
        break;
    }
    case ZoomOut:
        // Unstack all scale-levels deeper than the new level, so a zoom-back won't end up zooming in.
        while (!m_scaleStack.isEmpty() && m_scaleStack.last().scale >= targetScale)
            m_scaleStack.removeLast();
        m_zoomOutScale = targetScale;
        break;
    case NoZoom:
        break;
    }

    animateContentRectVisible(endVisibleContentRect);
}
void FieldView::drawRobot(QPainter& painter, bool blueRobot, int ID,
                          QPointF pos, float theta, bool hasBall, bool faulty) {
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::NoBrush);

    painter.save();

    painter.translate(pos.x(), pos.y());

    if (faulty) {
        painter.save();
        painter.setPen(redPen);
        painter.setBrush(QBrush{Qt::red, Qt::SolidPattern});
        auto r = Robot_Radius + 0.025;
        painter.drawEllipse(QPointF(0, 0), r, r);
        painter.restore();
    }

    if (blueRobot) {
        painter.setPen(bluePen);
        painter.setBrush(Qt::blue);
    } else {
        painter.setPen(yellowPen);
        painter.setBrush(Qt::yellow);
    }

    painter.rotate(RadiansToDegrees(theta) + 90);

    int span = 40;

    int start = span * 16 + 90 * 16;
    int end = 360 * 16 - (span * 2) * 16;
    const float r = Robot_Radius;
    painter.drawChord(QRectF(-r, -r, r * 2, r * 2), start, end);

    if (showDotPatterns) {
        painter.setPen(Qt::NoPen);
        for (int i = 0; i < 4; i++) {
            painter.setBrush(QBrush(Dot_Pattern_Colors[ID][i]));
            QPointF center;
            center.setX((i >= 2) ? Dots_Small_Offset : Dots_Large_Offset);
            center.setX(center.x() * ((i == 1 || i == 2) ? -1 : 1));
            center.setY((i <= 1) ? Dots_Small_Offset : Dots_Large_Offset);
            center.setY(center.y() * ((i <= 1) ? -1 : 1));
            painter.drawEllipse(center, Dots_Radius, Dots_Radius);
        }
    }

    if (hasBall) {
        painter.setPen(redPen);
        const float r = Robot_Radius * 0.75f;
        painter.drawChord(QRectF(-r, -r, r * 2, r * 2), start, end);
    }

    painter.restore();

    // draw shell number
    painter.save();
    painter.translate(pos.x(), pos.y());
    if (blueRobot) {
        painter.setPen(whitePen);
    } else {
        painter.setPen(blackPen);
    }
    drawText(painter, QPointF(), QString::number(ID));
    painter.restore();
}
Example #27
0
void PolarGrid::drawGrid( PaintContext* context )
{
//    if ( d->coordinateTransformations.size () <= 0 ) return;

    PolarCoordinatePlane* plane = dynamic_cast<PolarCoordinatePlane*>(context->coordinatePlane());
    Q_ASSERT_X ( plane, "PolarGrid::drawGrid",
                 "Bad function call: PaintContext::coodinatePlane() NOT a polar plane." );

    const GridAttributes gridAttrsCircular( plane->gridAttributes( true ) );
    const GridAttributes gridAttrsSagittal( plane->gridAttributes( false ) );

    //qDebug() << "OK:";
    if ( !gridAttrsCircular.isGridVisible() && !gridAttrsSagittal.isGridVisible() ) return;
    //qDebug() << "A";

    // FIXME: we paint the rulers to the settings of the first diagram for now:
    AbstractPolarDiagram* dgr = dynamic_cast<AbstractPolarDiagram*> (plane->diagrams().first() );
    Q_ASSERT ( dgr ); // only polar diagrams are allowed here


    // Do not draw a grid for pie diagrams
    if( dynamic_cast<PieDiagram*> (plane->diagrams().first() ) ) return;


    context->painter()->setPen ( PrintingParameters::scalePen( QColor ( Qt::lightGray ) ) );
    const double min = dgr->dataBoundaries().first.y();
    QPointF origin = plane->translate( QPointF( min, 0 ) ) + context->rectangle().topLeft();
    //qDebug() << "origin" << origin;

    const double r = qAbs( min ) + dgr->dataBoundaries().second.y(); // use the full extents

    if ( gridAttrsSagittal.isGridVisible() ){
        const int numberOfSpokes = ( int ) ( 360 / plane->angleUnit() );
        for ( int i = 0; i < numberOfSpokes ; ++i ) {
            context->painter()->drawLine( origin, plane->translate( QPointF( r - qAbs( min ), i ) ) + context->rectangle().topLeft() );
        }
    }

    if ( gridAttrsCircular.isGridVisible() )
    {
        const qreal startPos = plane->startPosition();
        plane->setStartPosition( 0.0 );
        const int numberOfGridRings = ( int )dgr->numberOfGridRings();
        for ( int j = 0; j < numberOfGridRings; ++j ) {
            const double rad = min - ( ( j + 1) * r / numberOfGridRings );
    
            if ( rad == 0 )
                continue;
    
            QRectF rect;
            QPointF topLeftPoint;
            QPointF bottomRightPoint;

            topLeftPoint = plane->translate( QPointF( rad, 0 ) );
            topLeftPoint.setX( plane->translate( QPointF( rad, 90 / plane->angleUnit() ) ).x() );
            bottomRightPoint = plane->translate( QPointF( rad, 180 / plane->angleUnit() ) );
            bottomRightPoint.setX( plane->translate( QPointF( rad, 270 / plane->angleUnit() ) ).x() );

            rect.setTopLeft( topLeftPoint + context->rectangle().topLeft() );
            rect.setBottomRight( bottomRightPoint + context->rectangle().topLeft() );

            context->painter()->drawEllipse( rect );
        }
        plane->setStartPosition( startPos );
    }
}
NonPdfFrameHandle::NonPdfFrameHandle (QGraphicsScene &scene,
                                      QGraphicsView &view,
                                      const QPointF &pointReference,
                                      int orientationFlags,
                                      NonPdfCropping &nonPdfCropping,
                                      int zValue) :
  m_nonPdfCropping (nonPdfCropping),
  m_orientationFlags (orientationFlags),
  m_disableEventsWhileMovingAutomatically (false),
  m_scene (scene),
  m_view (view)
{
  const double SUBTLE_OPACITY = 0.2;

  // Advantages of using ItemIgnoresTransformations:
  //   1) handles do not get bigger or smaller depending on the size of the image
  //   2) handles never get ugly when zoomed in
  //   3) handles never get too tiny when zoomed out
  // Disadvantages of using ItemIgnoresTransformation:
  //   1) Resizing the preview window with ItemIgnoresTransformations moves the handles out of position
  //   2) More conversions back and forth between untransformed and transformed coordinates. This was the deal breaker since
  //      the transformations were undocumented and ultimately too difficult
  // The solution is to have constant-size handles WITHOUT ItemIgnoresTransformations. This means resizing the window
  // also involves resizing the handles, but everything else is pretty easy
  //
  // ItemIgnoresTransformations flag must agree with the QGraphicsRectItem used for the frame box by PdfCropping
  setFlags (QGraphicsItem::ItemIsMovable |
            QGraphicsItem::ItemIsSelectable |
            QGraphicsItem::ItemSendsScenePositionChanges);

  // Fill with nice color for better visibility. Note that the pen is disabled by overriding the paint method
  setBrush (QBrush (Qt::blue));
  setVisible (true);
  setZValue (zValue);
  setOpacity (SUBTLE_OPACITY);
  setPos (pointReference); // Point position is handled in scene/view coordinates

  // Add to scene
  scene.addItem (this);

  QSize handleSize = m_nonPdfCropping.windowSize() / HANDLE_SIZE_AS_FRACTION_OF_WINDOW_SIZE;

  // Adjust positions of handles that are not at the top left so handles are laid out symmetrically
  QPointF pointPos = pointReference;
  if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_LEFT) != 0) {
    pointPos.setX (pointPos.x() - handleSize.width() / 2.0);
  } else if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_RIGHT) != 0) {
    pointPos.setX (pointPos.x() + handleSize.width() / 2.0);
  }
  if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_TOP) != 0) {
    pointPos.setY (pointPos.y() - handleSize.height() / 2.0);
  } else if ((orientationFlags & NonPdfCropping::NON_PDF_CROPPING_BOTTOM) != 0) {
    pointPos.setY (pointPos.y() + handleSize.height() / 2.0);
  }

  // Start with geometry. Since point positions are handled in scene/view coordinates, we have to convert
  // to local coordinates for the rectangle
  QPointF topLeftLocal = mapFromScene (pointPos);

  setRect (QRectF (topLeftLocal,
                   handleSize));
}
Example #29
0
// Update the painter path
void GLEEllipse::updateEllipse()
{
	QPointF p;
	QPair<QPointF,int> snap;
	double angle;

	// Only do this if both the centre and radius have been set
	if (isSet(CentrePoint) && isSet(RadiusX) && isSet(RadiusY) && isSet(Angle))
	{
		// This is guaranteed to have been created in the constructor
		// of GLEDrawingObject
		delete(paintPath);
		// Create a new path starting at ellipseCentre
		paintPath = new QPainterPath(getQtPoint(CentrePoint));
		// Add the ellipse based on the qrect
		// This needs to be modified to suit the angle!
		// CHECK: I think we only use this for bounding boxes,
		// so just make a rectangle of the bounding box

		angle = getGLEAngle(Angle);

		// Get the bounding box of the ellipse
		QRectF rect;
		rect.setTopLeft(getQtPoint(BBoxCornerA));
		rect.setBottomRight(getQtPoint(BBoxCornerB));
		paintPath->addRect(rect);

		// Update GLE object
		GLEEllipseDO* ellipse = (GLEEllipseDO*)getGLEObject();
		if (ellipse != NULL) {
			ellipse->setCenter(QGLE::QPointFToGLEPoint(getGLEPoint(CentrePoint)));
			ellipse->setRadiusX(getGLELength(RadiusX));
			ellipse->setRadiusY(getGLELength(RadiusY));
		}

		// Update the calculated equation parameters
		updateEquationParameters();

		// Now we add the osnap handles
		osnapHandles.clear();

		p.setX(getQtLength(RadiusX)*cos(M_PI-angle));
		p.setY(getQtLength(RadiusX)*sin(M_PI-angle));
		p += getQtPoint(CentrePoint);
		snap.first = p;
		snap.second = QGLE::QuadrantSnap;
		osnapHandles.append(snap);

		p.setX(-getQtLength(RadiusX)*cos(M_PI-angle));
		p.setY(-getQtLength(RadiusX)*sin(M_PI-angle));
		p += getQtPoint(CentrePoint);
		snap.first = p;
		snap.second = QGLE::QuadrantSnap;
		osnapHandles.append(snap);

		p.setX(-getQtLength(RadiusY)*sin(angle));
		p.setY(-getQtLength(RadiusY)*cos(angle));
		p += getQtPoint(CentrePoint);
		snap.first = p;
		snap.second = QGLE::QuadrantSnap;
		osnapHandles.append(snap);

		p.setX(getQtLength(RadiusY)*sin(angle));
		p.setY(getQtLength(RadiusY)*cos(angle));
		p += getQtPoint(CentrePoint);
		snap.first = p;
		snap.second = QGLE::QuadrantSnap;
		osnapHandles.append(snap);

		snap.first = getQtPoint(CentrePoint);
		snap.second = QGLE::CentreSnap;
		osnapHandles.append(snap);
	}
}
/**
  Internal method that draws the surface of one of the pies in a pie chart.

  \param painter the QPainter to draw in
  \param dataset the dataset to draw the pie for
  \param pie the pie to draw
  */
void PieDiagram::drawPieSurface( QPainter* painter,
        DataValueTextInfoList* list,
        uint dataset, uint pie,
        qreal granularity )
{
    // Is there anything to draw at all?
    qreal angleLen = d->angleLens[ pie ];
    if ( angleLen ) {
        qreal startAngle = d->startAngles[ pie ];

        QModelIndex index( model()->index( 0, pie, rootIndex() ) );
        const PieAttributes attrs( pieAttributes( index ) );
        const ThreeDPieAttributes threeDAttrs( threeDPieAttributes( index ) );

        QRectF drawPosition = piePosition( dataset, pie );

        painter->setRenderHint ( QPainter::Antialiasing );
        QBrush br = brush( index );
        if( threeDAttrs.isEnabled() ) {
            br = threeDAttrs.threeDBrush( br, drawPosition );
        }
        painter->setBrush( br );

        painter->setPen( pen( index ) );

        if ( angleLen == 360 ) {
            // full circle, avoid nasty line in the middle
            painter->drawEllipse( drawPosition );

            //Add polygon to Reverse mapper for showing tool tips.
            QPolygonF poly( drawPosition );
            d->reverseMapper.addPolygon( index.row(), index.column(), poly );
        } else {
            // draw the top of this piece
            // Start with getting the points for the arc.
            const int arcPoints = static_cast<int>(trunc( angleLen / granularity ));
            QPolygonF poly( arcPoints+2 );
            qreal degree=0.0;
            int iPoint = 0;
            bool perfectMatch = false;

            while ( degree <= angleLen ){
                poly[ iPoint ] = pointOnCircle( drawPosition, startAngle + degree );
                //qDebug() << degree << angleLen << poly[ iPoint ];
                perfectMatch = (degree == angleLen);
                degree += granularity;
                ++iPoint;
            }
            // if necessary add one more point to fill the last small gap
            if( ! perfectMatch ){
                poly[ iPoint ] = pointOnCircle( drawPosition, startAngle + angleLen );

                // add the center point of the piece
                poly.append( drawPosition.center() );
            }else{
                poly[ iPoint ] = drawPosition.center();
            }
            //find the value and paint it
            //fix value position
            d->reverseMapper.addPolygon( index.row(), index.column(), poly );
			
            painter->drawPolygon( poly );
        }
        // the new code is setting the needed position points according to the slice:
        // all is calculated as if the slice were 'standing' on it's tip and the border
        // were on top, so North is the middle of the curved outside line and South is the tip
        //
        const qreal sum = valueTotals();
        const QPointF south = drawPosition.center();
        const QPointF southEast = south;
        const QPointF southWest = south;
        const QPointF north = pointOnCircle( drawPosition, startAngle + angleLen/2.0 );

        const QPointF northEast = pointOnCircle( drawPosition, startAngle );
        const QPointF northWest = pointOnCircle( drawPosition, startAngle + angleLen );
        QPointF center    = (south + north) / 2.0;
        const QPointF east      = (south + northEast) / 2.0;
        const QPointF west      = (south + northWest) / 2.0;

        CartesianDiagramDataCompressor::DataValueAttributesList allAttrs( d->aggregatedAttrs( this, index, 0 ) );
        const QFontMetrics * fm = (d->cachedFontMetrics( allAttrs.value(index).textAttributes().calculatedFont(d->plane,KDChartEnums::MeasureOrientationMinimum ), this ));
        if(!list->isEmpty())
        {
                QRect textRect = fm->boundingRect(QString::number(list->last().value));
                textRect.translated(center.toPoint());
                QPoint textRectCenter = textRect.center();
                qreal newX = center.x() - textRectCenter.x();
                qreal newY =  center.y() - textRectCenter.y();
                center.setX(newX);
                center.setY(newY);
        }

        PositionPoints points( center, northWest, north, northEast, east, southEast, south, southWest, west);
        qreal topAngle = startAngle - 90;
        if( topAngle < 0.0 )
            topAngle += 360;
        points.setDegrees(KDChartEnums::PositionEast,      topAngle);
        points.setDegrees(KDChartEnums::PositionNorthEast, topAngle);
        points.setDegrees(KDChartEnums::PositionWest,      topAngle + angleLen);
        points.setDegrees(KDChartEnums::PositionNorthWest, topAngle + angleLen);
        points.setDegrees(KDChartEnums::PositionCenter,    topAngle + angleLen/2.0);
        points.setDegrees(KDChartEnums::PositionNorth,     topAngle + angleLen/2.0);

        //painter->drawText(points.mPositionCenter,QLatin1String("P"));

        d->appendDataValueTextInfoToList(
                this, *list, index, 0,
                points, Position::Center, Position::Center,
                angleLen*sum / 360 );

        // The following, old code (since kdc 2.0.0) was not correct:
        // Settings made for the position had been totally ignored,
        // AND the center was NOT the center - except for pieces of 45 degrees size
        //
        // QLineF centerLine(  drawPosition.center(),
        //                 QPointF( (poly[ last - 2].x() + poly.first().x())/2,
        //                          ( poly.first().y() + poly[last-2].y() )/2 ) );
        // QPointF valuePos( ( centerLine.x1() + centerLine.x2() )/2,
        //                       ( centerLine.y1() + centerLine.y2() )/2 ) ;
        //
        // paintDataValueText( painter, index, valuePos, angleLen*sum / 360  );
    }
}