void QgsMapToolAnnotation::canvasMoveEvent( QMouseEvent * e )
{
  QgsAnnotationItem* sItem = selectedItem();
  if ( sItem && ( e->buttons() & Qt::LeftButton ) )
  {
    if ( mCurrentMoveAction == QgsAnnotationItem::MoveMapPosition )
    {
      sItem->setMapPosition( toMapCoordinates( e->pos() ) );
      sItem->update();
    }
    else if ( mCurrentMoveAction == QgsAnnotationItem::MoveFramePosition )
    {
      if ( sItem->mapPositionFixed() )
      {
        sItem->setOffsetFromReferencePoint( sItem->offsetFromReferencePoint() + ( e->posF() - mLastMousePosition ) );
      }
      else
      {
        QPointF newCanvasPos = sItem->pos() + ( e->posF() - mLastMousePosition );
        sItem->setMapPosition( toMapCoordinates( newCanvasPos.toPoint() ) );
      }
      sItem->update();
    }
    else if ( mCurrentMoveAction != QgsAnnotationItem::NoAction )
    {
      //handle the frame resize actions
      QSizeF size = sItem->frameSize();
      double xmin = sItem->offsetFromReferencePoint().x();
      double ymin = sItem->offsetFromReferencePoint().y();
      double xmax = xmin + size.width();
      double ymax = ymin + size.height();

      if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRight ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightDown ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightUp )
      {
        xmax += e->posF().x() - mLastMousePosition.x();
      }
      if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeft ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftDown ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftUp )
      {
        xmin += e->posF().x() - mLastMousePosition.x();
      }
      if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameUp ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftUp ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightUp )
      {
        ymin += e->posF().y() - mLastMousePosition.y();
      }
      if ( mCurrentMoveAction == QgsAnnotationItem::ResizeFrameDown ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameLeftDown ||
           mCurrentMoveAction == QgsAnnotationItem::ResizeFrameRightDown )
      {
        ymax += e->posF().y() - mLastMousePosition.y();
      }

      //switch min / max if necessary
      double tmp;
      if ( xmax < xmin )
      {
        tmp = xmax; xmax = xmin; xmin = tmp;
      }
      if ( ymax < ymin )
      {
        tmp = ymax; ymax = ymin; ymin = tmp;
      }

      sItem->setOffsetFromReferencePoint( QPointF( xmin, ymin ) );
      sItem->setFrameSize( QSizeF( xmax - xmin, ymax - ymin ) );
      sItem->update();
    }
  }
  else if ( sItem )
  {
    QgsAnnotationItem::MouseMoveAction moveAction = sItem->moveActionForPosition( e->posF() );
    if ( mCanvas )
    {
      mCanvas->setCursor( QCursor( sItem->cursorShapeForAction( moveAction ) ) );
    }
  }
  mLastMousePosition = e->posF();
}
Example #2
0
void Viewer::mouseDoubleClickEvent(QMouseEvent * e){
    if (e->button() == Qt::LeftButton && (e->modifiers() == Qt::NoButton)){
        QPointF point = e->posF();
        bool found;

        int tid = curTerr;
        if (tid <0 || tid > terrains.size())
            return;

        Terrain* terrain = terrains[tid];

        qglviewer::Vec selectedPoint = camera()->pointUnderPixel(point.toPoint(), found); //QVector3D(orig.x,orig.y,orig.z)+10000*QVector3D(dir.x,dir.y,dir.z);//
        if (!found) return;

        QVector3D I2 = QVector3D(selectedPoint.x,selectedPoint.y,selectedPoint.z);
        float sc = terrain->wsc/terrain->width;
        I2/=sc;
        float xs = I2.x()+terrain->width/2;
        float ys = I2.y()+terrain->height/2;
        xs = (int) xs;
        ys = (int) ys;

        //qWarning("Intersection is %d %d", (int)xs, (int)ys);
        //qWarning("Selected point is %f %f %f\n",selectedPoint.x,selectedPoint.y,selectedPoint.z);

        int id = (xs)+(ys)*terrain->width;
        if (!(xs>0 && ys>0 && xs<terrain->width-1 && ys< terrain->height-1)){
            return;
        }
        QVector3D npoint = terrain->verts[id].location;

        int index = terrain->artifacts.indexOf(npoint);

        if (index==-1 || terrain->verts[id].colour.y()!=DEF_COL.y()){
            for (int j=-5; j<5; j++){
                for (int i=-5; i<5; i++){
                    id = (xs+i)+(ys+j)*terrains[tid]->width;
                    if (xs+i>0 && ys+j>0 && xs+i<terrain->width-1 && ys+j< terrain->height-1){
                        index = terrain->artifacts.indexOf(terrain->verts[id].location);
                        if (index!=-1){
                            xs += i; ys += j;
                            npoint = terrain->verts[id].location;
                            break;
                        }
                    }
                }
            if (index!=-1)
                break;
        }
        }
        if (index==-1){
            QMenu menu("Severity", this );
            QMap<QAction*, float> menuMap;
            menuMap[menu.addAction("Slightly severe ")] = 1.1;
            menuMap[menu.addAction("Moderately severe")] = 1.35;
            menuMap[menu.addAction("Very severe")] = 3.0;
            QAction* action = menu.exec(e->globalPos());
            if (!action)
                return;

            terrain->artifacts.push_back(QVector3D( npoint.x(), npoint.y(), npoint.z()));
            terrain->severity.push_back(menuMap[action]);
            for (int j=-10; j<10; j++)
                for (int i=-10; i<10; i++){
                    id = (xs+i)+(ys+j)*terrain->width;
                    if (xs+i>0 && ys+j>0 && xs+i<terrain->width-1 && ys+j< terrain->height-1){
                        QVector4D& col = terrain->verts[id].colour;
                        col.setY(col.y()*terrain->severity.back());
                        //terrains[tid]->verts[id].colour* //= QVector4D(1.,0,0,0.1);
                    }
            }
        }
        else {
            for (int j=-10; j<10; j++)
                for (int i=-10; i<10; i++){
                    id = (xs+i)+(ys+j)*terrain->width;
                    if (xs+i>0 && ys+j>0 && xs+i<terrain->width-1 && ys+j< terrain->height-1){
                        QVector4D& col = terrain->verts[id].colour;
                        col.setY(col.y()/terrain->severity[index]);
                        //terrains[tid]->verts[id].colour* //= QVector4D(1.,0,0,0.1);
                    }
                }
            terrain->artifacts.erase(terrain->artifacts.begin()+index);
            terrain->severity.erase(terrain->severity.begin()+index);
            terrain->updateVerts();
        }


        QString str = QString::number(xs)+"  " +QString::number(ys);
        //displayMessage(str,5000);
        terrain->updateVerts();

        updateGL();
        return;
    }
    else
        QGLViewer::mouseDoubleClickEvent(e);
}
Example #3
0
void BrushTool::drawStroke()
{
    StrokeTool::drawStroke();
    QList<QPointF> p = m_pStrokeManager->interpolateStroke();

    Layer* layer = mEditor->layers()->currentLayer();

    if ( layer->type() == Layer::BITMAP )
    {
        for ( int i = 0; i < p.size(); i++ )
        {
            p[ i ] = mEditor->view()->mapScreenToCanvas( p[ i ] );
        }

        qreal opacity = mCurrentPressure / 2;
        mCurrentWidth = properties.width;
        qreal brushWidth = mCurrentWidth;

        qreal brushStep = (0.5 * brushWidth) - ((properties.feather/100.0) * brushWidth * 0.5);
        brushStep = qMax( 1.0, brushStep );

        BlitRect rect;

        QPointF a = lastBrushPoint;
        QPointF b = getCurrentPoint();

        qreal distance = 4 * QLineF( b, a ).length();
        int steps = qRound( distance ) / brushStep;

        for ( int i = 0; i < steps; i++ )
        {
            QPointF point = lastBrushPoint + ( i + 1 ) * ( brushStep )* ( b - lastBrushPoint ) / distance;
            rect.extend( point.toPoint() );
            mScribbleArea->drawBrush( point,
                                      brushWidth,
                                      properties.feather,
                                      mEditor->color()->frontColor(),
                                      opacity );

            if ( i == ( steps - 1 ) )
            {
                lastBrushPoint = point;
            }
        }

        int rad = qRound( brushWidth ) / 2 + 2;
        mScribbleArea->refreshBitmap( rect, rad );
    }
    else if ( layer->type() == Layer::VECTOR )
    {
        qreal brushWidth = properties.width * mCurrentPressure;

        int rad = qRound( ( brushWidth / 2 + 2 ) * mEditor->view()->scaling() );

        QPen pen( mEditor->color()->frontColor(),
                  brushWidth * mEditor->view()->scaling(),
                  Qt::SolidLine,
                  Qt::RoundCap,
                  Qt::RoundJoin );

        if ( p.size() == 4 )
        {
            QPainterPath path( p[ 0 ] );
            path.cubicTo( p[ 1 ],
                          p[ 2 ],
                          p[ 3 ] );
            mScribbleArea->drawPath( path, pen, Qt::NoBrush, QPainter::CompositionMode_Source );
            mScribbleArea->refreshVector( path.boundingRect().toRect(), rad );
        }
    }
}
void GraphicsDirectedEdge::
set_stop(QPointF p)
{
	set_stop(p.toPoint());
}
Example #5
0
bool KisZoomAndPanTest::checkInvariants(const QPointF &baseFlakePoint,
                                        const QPoint &oldOffset,
                                        const QPointF &oldPreferredCenter,
                                        qreal oldZoom,
                                        const QPoint &newOffset,
                                        const QPointF &newPreferredCenter,
                                        qreal newZoom,
                                        const QPointF &newTopLeft,
                                        const QSize &oldDocumentSize)
{
    qreal k = newZoom / oldZoom;

    QPointF expectedOffset = oldOffset + (k - 1) * baseFlakePoint;
    QPointF expectedPreferredCenter = oldPreferredCenter + (k - 1) * baseFlakePoint;

    qreal oldPreferredCenterFractionX = 1.0 * oldPreferredCenter.x() / oldDocumentSize.width();
    qreal oldPreferredCenterFractionY = 1.0 * oldPreferredCenter.y() / oldDocumentSize.height();

    qreal roundingTolerance =
        qMax(qreal(1.0), qMax(oldPreferredCenterFractionX, oldPreferredCenterFractionY) / k);

    /**
     * In the computation of the offset two roundings happen:
     * first for the computation of oldOffset and the second
     * for the computation of newOffset. So the maximum tolerance
     * should equal 2.
     */
    bool offsetAsExpected =
        compareWithRounding(expectedOffset, QPointF(newOffset), 2 * roundingTolerance);

    /**
     * Rounding for the preferred center happens due to the rounding
     * of the document size while zooming. The wider the step of the
     * zooming, the bigger tolerance should be
     */
    bool preferredCenterAsExpected =
        compareWithRounding(expectedPreferredCenter, newPreferredCenter,
                            roundingTolerance);

    bool topLeftAsExpected = newTopLeft.toPoint() == -newOffset;

    if (!offsetAsExpected ||
        !preferredCenterAsExpected ||
        !topLeftAsExpected) {

        dbgKrita << "***** ZOOM ****************";

        if(!offsetAsExpected) {
            dbgKrita << " ### Offset invariant broken";
        }

        if(!preferredCenterAsExpected) {
            dbgKrita << " ### Preferred center invariant broken";
        }

        if(!topLeftAsExpected) {
            dbgKrita << " ### TopLeft invariant broken";
        }

        dbgKrita << ppVar(expectedOffset);
        dbgKrita << ppVar(expectedPreferredCenter);
        dbgKrita << ppVar(oldOffset) << ppVar(newOffset);
        dbgKrita << ppVar(oldPreferredCenter) << ppVar(newPreferredCenter);
        dbgKrita << ppVar(oldPreferredCenterFractionX);
        dbgKrita << ppVar(oldPreferredCenterFractionY);
        dbgKrita << ppVar(oldZoom) << ppVar(newZoom);
        dbgKrita << ppVar(baseFlakePoint);
        dbgKrita << ppVar(newTopLeft);
        dbgKrita << ppVar(roundingTolerance);
        dbgKrita << "***************************";
    }

    return offsetAsExpected && preferredCenterAsExpected && topLeftAsExpected;
}
Example #6
0
void CreateObjectTool::mousePressed(QGraphicsSceneMouseEvent *event)
{
    // Check if we are already creating a new map object
    if (mNewMapObjectItem) {
        switch (mMode) {
        case CreateRectangle:
        case CreateTile:
        case CreateEllipse:
            if (event->button() == Qt::RightButton)
                cancelNewMapObject();
            break;
        case CreatePolygon:
        case CreatePolyline:
            if (event->button() == Qt::RightButton) {
                finishOrCancelPolygon();
            } else if (event->button() == Qt::LeftButton) {
                QPolygonF current = mNewMapObjectItem->mapObject()->polygon();
                QPolygonF next = mOverlayPolygonObject->polygon();

                // If the last position is still the same, ignore the click
                if (next.last() == current.last())
                    return;

                // Assign current overlay polygon to the new object
                mNewMapObjectItem->setPolygon(next);

                // Add a new editable point to the overlay
                next.append(next.last());
                mOverlayPolygonItem->setPolygon(next);
            }
            break;
        }
        return;
    }

    if (event->button() != Qt::LeftButton) {
        AbstractObjectTool::mousePressed(event);
        return;
    }

    ObjectGroup *objectGroup = currentObjectGroup();
    if (!objectGroup || !objectGroup->isVisible())
        return;

    const MapRenderer *renderer = mapDocument()->renderer();
    QPointF tileCoords;

    if (mMode == CreateTile) {
        if (!mTile)
            return;

        const QPointF diff(-mTile->width() / 2, mTile->height() / 2);
        tileCoords = renderer->screenToTileCoords(event->scenePos() + diff);
    } else {
        tileCoords = renderer->screenToTileCoords(event->scenePos());
    }

    bool snapToGrid = Preferences::instance()->snapToGrid();
    bool snapToFineGrid = Preferences::instance()->snapToFineGrid();
    if (event->modifiers() & Qt::ControlModifier) {
        snapToGrid = !snapToGrid;
        snapToFineGrid = false;
    }

    if (snapToFineGrid) {
        int gridFine = Preferences::instance()->gridFine();
        tileCoords = (tileCoords * gridFine).toPoint();
        tileCoords /= gridFine;
    } else if (snapToGrid)
        tileCoords = tileCoords.toPoint();
    
    const QPointF pixelCoords = renderer->tileToPixelCoords(tileCoords);

    startNewMapObject(pixelCoords, objectGroup);
}
/*!
    \internal
*/
void QGraphicsProxyWidgetPrivate::sendWidgetMouseEvent(QGraphicsSceneMouseEvent *event)
{
    if (!event || !widget || !widget->isVisible())
        return;
    Q_Q(QGraphicsProxyWidget);

    // Find widget position and receiver.
    QPointF pos = event->pos();
    QPointer<QWidget> alienWidget = widget->childAt(pos.toPoint());
    QPointer<QWidget> receiver =  alienWidget ? alienWidget : widget;

    if (QWidgetPrivate::nearestGraphicsProxyWidget(receiver) != q)
        return; //another proxywidget will handle the events

    // Translate QGraphicsSceneMouse events to QMouseEvents.
    QEvent::Type type = QEvent::None;
    switch (event->type()) {
    case QEvent::GraphicsSceneMousePress:
        type = QEvent::MouseButtonPress;
        if (!embeddedMouseGrabber)
            embeddedMouseGrabber = receiver;
        else
            receiver = embeddedMouseGrabber;
        break;
    case QEvent::GraphicsSceneMouseRelease:
        type = QEvent::MouseButtonRelease;
        if (embeddedMouseGrabber)
            receiver = embeddedMouseGrabber;
        break;
    case QEvent::GraphicsSceneMouseDoubleClick:
        type = QEvent::MouseButtonDblClick;
        if (!embeddedMouseGrabber)
            embeddedMouseGrabber = receiver;
        else
            receiver = embeddedMouseGrabber;
        break;
    case QEvent::GraphicsSceneMouseMove:
        type = QEvent::MouseMove;
        if (embeddedMouseGrabber)
            receiver = embeddedMouseGrabber;
        break;
    default:
        Q_ASSERT_X(false, "QGraphicsProxyWidget", "internal error");
        break;
    }

    if (!lastWidgetUnderMouse) {
        QApplicationPrivate::dispatchEnterLeave(embeddedMouseGrabber ? embeddedMouseGrabber : widget, 0);
        lastWidgetUnderMouse = widget;
    }

    // Map event position from us to the receiver
    pos = mapToReceiver(pos, receiver);

    // Send mouse event.
    QMouseEvent *mouseEvent = QMouseEvent::createExtendedMouseEvent(type, pos,
                                                                    receiver->mapToGlobal(pos.toPoint()), event->button(),
                                                                    event->buttons(), event->modifiers());

    QWidget *embeddedMouseGrabberPtr = (QWidget *)embeddedMouseGrabber;
    QApplicationPrivate::sendMouseEvent(receiver, mouseEvent, alienWidget, widget,
                                        &embeddedMouseGrabberPtr, lastWidgetUnderMouse, event->spontaneous());
    embeddedMouseGrabber = embeddedMouseGrabberPtr;

    // Handle enter/leave events when last button is released from mouse
    // grabber child widget.
    if (embeddedMouseGrabber && type == QEvent::MouseButtonRelease && !event->buttons()) {
        Q_Q(QGraphicsProxyWidget);
        if (q->rect().contains(event->pos()) && q->acceptsHoverEvents())
            lastWidgetUnderMouse = alienWidget ? alienWidget : widget;
        else // released on the frame our outside the item, or doesn't accept hover events.
            lastWidgetUnderMouse = 0;

        QApplicationPrivate::dispatchEnterLeave(lastWidgetUnderMouse, embeddedMouseGrabber);
        embeddedMouseGrabber = 0;

#ifndef QT_NO_CURSOR
        // ### Restore the cursor, don't override it.
        if (!lastWidgetUnderMouse)
            q->unsetCursor();
#endif
    }

    event->setAccepted(mouseEvent->isAccepted());
    delete mouseEvent;
}
Example #8
0
void PlacesPanel::slotItemContextMenuRequested(int index, const QPointF& pos)
{
    PlacesItem* item = m_model->placesItem(index);
    if (!item) {
        return;
    }

    QMenu menu(this);

    QAction* emptyTrashAction = nullptr;
    QAction* editAction = nullptr;
    QAction* teardownAction = nullptr;
    QAction* ejectAction = nullptr;

    const QString label = item->text();

    const bool isDevice = !item->udi().isEmpty();
    const bool isTrash = (item->url().scheme() == QLatin1String("trash"));
    if (isDevice) {
        ejectAction = m_model->ejectAction(index);
        if (ejectAction) {
            ejectAction->setParent(&menu);
            menu.addAction(ejectAction);
        }

        teardownAction = m_model->teardownAction(index);
        if (teardownAction) {
            teardownAction->setParent(&menu);
            menu.addAction(teardownAction);
        }

        if (teardownAction || ejectAction) {
            menu.addSeparator();
        }
    } else {
        if (isTrash) {
            emptyTrashAction = menu.addAction(QIcon::fromTheme(QStringLiteral("trash-empty")), i18nc("@action:inmenu", "Empty Trash"));
            emptyTrashAction->setEnabled(item->icon() == QLatin1String("user-trash-full"));
            menu.addSeparator();
        }
    }

    QAction* openInNewWindowAction = menu.addAction(QIcon::fromTheme("window-new"), i18nc("@item:inmenu", "Open in New Window"));
    QAction* openInNewTabAction = menu.addAction(QIcon::fromTheme("tab-new"), i18nc("@item:inmenu", "Open in New Tab"));
    if (!isDevice && !isTrash) {
        menu.addSeparator();
    }

    if (!isDevice) {
        editAction = menu.addAction(QIcon::fromTheme("document-properties"), i18nc("@item:inmenu", "Edit..."));
    }

    QAction* removeAction = nullptr;
    if (!isDevice && !item->isSystemItem()) {
        removeAction = menu.addAction(QIcon::fromTheme(QStringLiteral("edit-delete")), i18nc("@item:inmenu", "Remove"));
    }

    QAction* hideAction = menu.addAction(i18nc("@item:inmenu", "Hide"));
    hideAction->setCheckable(true);
    hideAction->setChecked(item->isHidden());

    buildGroupContextMenu(&menu, index);

    QAction* action = menu.exec(pos.toPoint());
    if (action) {
        if (action == emptyTrashAction) {
            emptyTrash();
        } else {
            // The index might have changed if devices were added/removed while
            // the context menu was open.
            index = m_model->index(item);
            if (index < 0) {
                // The item is not in the model any more, probably because it was an
                // external device that has been removed while the context menu was open.
                return;
            }

            if (action == editAction) {
                editEntry(index);
            } else if (action == removeAction) {
                m_model->deleteItem(index);
            } else if (action == hideAction) {
                item->setHidden(hideAction->isChecked());
            } else if (action == openInNewWindowAction) {
                Dolphin::openNewWindow({KFilePlacesModel::convertedUrl(m_model->data(index).value("url").toUrl())}, this);
            } else if (action == openInNewTabAction) {
                // TriggerItem does set up the storage first and then it will
                // emit the slotItemMiddleClicked signal, because of Qt::MiddleButton.
                triggerItem(index, Qt::MiddleButton);
            } else if (action == teardownAction) {
                m_model->requestTearDown(index);
            } else if (action == ejectAction) {
                m_model->requestEject(index);
            }
        }
    }

    selectClosestItem();
}
Example #9
0
void BrushTool::drawStroke()
{
    StrokeTool::drawStroke();
    QList<QPointF> p = m_pStrokeManager->interpolateStroke();

    Layer* layer = mEditor->layers()->currentLayer();

    if ( layer->type() == Layer::BITMAP )
    {
        for ( int i = 0; i < p.size(); i++ )
        {
            p[ i ] = mEditor->view()->mapScreenToCanvas( p[ i ] );
        }

        qreal opacity = 1.0;
        qreal brushWidth = mCurrentWidth + 0.5 * properties.feather;
        qreal offset = qMax( 0.0, mCurrentWidth - 0.5 * properties.feather ) / brushWidth;
        opacity = mCurrentPressure;
        brushWidth = brushWidth * mCurrentPressure;

        qreal brushStep = 0.5 * mCurrentWidth + 0.5 * properties.feather;
        brushStep = brushStep * mCurrentPressure;

        //        if (usePressure) { brushStep = brushStep * tabletPressure; }
        brushStep = qMax( 1.0, brushStep );

        mCurrentWidth = properties.width;
        BlitRect rect;

        QRadialGradient radialGrad( QPointF( 0, 0 ), 0.5 * brushWidth );
        mScribbleArea->setGaussianGradient( radialGrad,
                                            mEditor->color()->frontColor(),
                                            opacity,
                                            offset );

        QPointF a = lastBrushPoint;
        QPointF b = getCurrentPoint();

        //        foreach (QSegment segment, calculateStroke(brushWidth))
        //        {
        //            QPointF a = lastBrushPoint;
        //            QPointF b = m_pScribbleArea->pixelToPoint(segment.second);

        qreal distance = 4 * QLineF( b, a ).length();
        int steps = qRound( distance ) / brushStep;

        for ( int i = 0; i < steps; i++ )
        {
            QPointF point = lastBrushPoint + ( i + 1 ) * ( brushStep )* ( b - lastBrushPoint ) / distance;
            rect.extend( point.toPoint() );
            mScribbleArea->drawBrush( point,
                                      brushWidth,
                                      offset,
                                      mEditor->color()->frontColor(),
                                      opacity );

            if ( i == ( steps - 1 ) )
            {
                lastBrushPoint = point;
            }
        }

        int rad = qRound( brushWidth ) / 2 + 2;
        mScribbleArea->refreshBitmap( rect, rad );
    }
    else if ( layer->type() == Layer::VECTOR )
    {
        qreal brushWidth = properties.width * mCurrentPressure;

        int rad = qRound( ( brushWidth / 2 + 2 ) * mEditor->view()->scaling() );

        QPen pen( mEditor->color()->frontColor(),
                  brushWidth * mEditor->view()->scaling(),
                  Qt::SolidLine,
                  Qt::RoundCap,
                  Qt::RoundJoin );

        if ( p.size() == 4 )
        {
            QPainterPath path( p[ 0 ] );
            path.cubicTo( p[ 1 ],
                          p[ 2 ],
                          p[ 3 ] );
            mScribbleArea->drawPath( path, pen, Qt::NoBrush, QPainter::CompositionMode_Source );
            mScribbleArea->refreshVector( path.boundingRect().toRect(), rad );
        }
    }
}
/**
  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  );
    }
}
bool ConnectionManager::mousePressEvent(QMouseEvent *event) {
	if (event->button() == Qt::RightButton) {
		if (m_fromPin != -1) {
			m_fromPin = -1;
			m_points.clear();
			return true;
		}

		int point;
		Connection *c = getPoint(NORM(event->x()), NORM(event->y()), point);
		if (point != -1) {
			// User can't remove first or last point like that
			if (point == 0 || point == c->points.size() - 1) {
				return false;
			}
			QList<QAction *> actions;
			actions.append(new QAction("Remove point", 0));
			QAction *action = QMenu::exec(actions, event->globalPos(), 0, 0);
			if (action) {
				removePoint(c, point);
			}
			return true;
		}

		c = getConnection(NORM(event->x()), NORM(event->y()), point);
		if (c) {
			QList<QAction *> actions;
			actions.append(new QAction("Remove connection", 0));
			QAction *action = QMenu::exec(actions, event->globalPos(), 0, 0);
			if (action) {
				removeConnection(c);
			}
			return true;
		}
	}
	else if (event->button() == Qt::LeftButton) {
		if (m_fromPin != -1) {
			QPoint from = QPoint(m_movingX, m_movingY);
			QPoint to(NORM(event->pos().x()), NORM(event->pos().y()));
			ScreenObject *object = m_screen->getObject(NORM(event->x()), NORM(event->y()));
			if (object) {
				int pin = m_screen->getPin(object, NORM(event->x()), NORM(event->y()));
				if (pin != -1) {
					to = object->getPins()[pin].rect.center();
				}
			}

			bool firstPoints = m_points.empty();

			if (firstPoints) {
				m_points.push_back(from);
			}

			if (m_screen->getObject(from.x(), to.y()) == m_fromObject/* &&
				m_screen->getPin(m_moving, from.x(), to.y()) != -1*/) {
				m_points.push_back(QPoint(to.x(), from.y()));
			}
			else {
				m_points.push_back(QPoint(from.x(), to.y()));
			}

// 			if (!firstPoints) {
				m_points.push_back(to);
// 			}

			int point;
			Connection *c = getPoint(NORM(event->x()), NORM(event->y()), point);
			if (point != -1) {
                ScreenObject *object = m_screen->getObject(NORM(event->x()), NORM(event->y()));
                if (object) {
                    m_points.erase(m_points.end() - 1);
                    m_points.erase(m_points.end() - 1);
                    return false;
                }

				addConnectionNode(c, point, event->x(), event->y(), m_points);

				m_fromPin = -1;
				m_points.clear();
// 				qDebug() << newPoints.size() << c->points.size() << "\n";
				return true;
			}
			else {
				QPointF intersectPnt;
				int point;
				c = getConnection(NORM(event->x()), NORM(event->y()), point, &intersectPnt);
				if (c) {
					QPoint p = intersectPnt.toPoint();
					p = QPoint(NORM(p.x()), NORM(p.y()));
					c->points.insert(c->points.begin() + point, p);
					addConnectionNode(c, point, event->x(), event->y(), m_points);
					m_fromPin = -1;
					m_points.clear();
					return true;
				}
			}

			if (object) {
				int pin = m_screen->getPin(object, NORM(event->x()), NORM(event->y()));
				if (pin != -1) {
					addConnection(m_fromObject, m_fromPin, object, pin, m_points);
					m_fromPin = -1;
					m_points.clear();
					return true;
				}
			}

			m_movingX = NORM(event->x());
			m_movingY = NORM(event->y());
			return true;
		}

// 		qDebug() << NORM(event->x()) << NORM(event->y());
		int point;
		Connection *c = getPoint(NORM(event->x()), NORM(event->y()), point);
		if (point != -1) {
			if (point == 0) {
				m_fromObject = c->from;
			}
			else if (point == c->points.size() - 1) {
				m_fromObject = c->to;
			}
			else {
				m_fromObject = 0;
			}
			m_movingConn = c;
			m_moving = &c->points[point];
			m_movingX = NORM(event->x());
			m_movingY = NORM(event->y());
			return true;
		}

		ScreenObject *object = m_screen->getObject(NORM(event->x()), NORM(event->y()));
		if (!object) {
			return false;
		}

		m_fromPin = m_screen->getPin(object, NORM(event->x()), NORM(event->y()));
		if (m_fromPin != -1) {
			m_fromObject = object;
			m_movingX = object->getPins()[m_fromPin].rect.center().x();
			m_movingY = object->getPins()[m_fromPin].rect.center().y();
			return true;
		}
	}
	return false;
}
Example #12
0
void PrimitivePainter::drawLabel(QPainterPath* R, QPainter* thePainter, qreal PixelPerM, QString str, QString strBg) const
{
    if (!DrawLabel)
        return;

    if (str.isEmpty() && strBg.isEmpty())
        return;

    thePainter->save();
    if (getLabelArea()) {
        QPointF C(R->boundingRect().center());
        drawPointLabel(C, str, strBg, thePainter, PixelPerM);
        thePainter->restore();
        return;
    }

    LineParameters lp = labelBoundary();
    qreal WW = PixelPerM*lp.Proportional+lp.Fixed;
    if (WW < 10) return;
    //qreal WWR = qMax(PixelPerM*R->widthOf()*BackgroundScale+BackgroundOffset, PixelPerM*R->widthOf()*ForegroundScale+ForegroundOffset);

    QPainterPath textPath;
    QPainterPath tranformedRoadPath = *R;
    QFont font = getLabelFont();

    if (!str.isEmpty()) {
        QRegion rg = thePainter->clipRegion();
        font.setPixelSize(int(WW));
        QFontMetrics metrics(font);

        if (font.pixelSize() >= 5 && tranformedRoadPath.length() > metrics.width(str)) {
            thePainter->setFont(font);

            int repeat = int((tranformedRoadPath.length() / ((metrics.width(str) * LABEL_PATH_DISTANCE))) - 0.5);
            int numSegment = repeat+1;
            qreal lenSegment = tranformedRoadPath.length() / numSegment;
            qreal startSegment = 0;
            QPainterPath textPath;
            do {
                QRegion rg = thePainter->clipRegion();

                qreal curLen = startSegment + ((lenSegment - metrics.width(str)) / 2);
                int modIncrement = 1;
                qreal modAngle = 0;
                int modY = 0;
                if (cos(angToRad(tranformedRoadPath.angleAtPercent((startSegment+(lenSegment/2))/tranformedRoadPath.length()))) < 0) {
                    modIncrement = -1;
                    modAngle = 180.0;
                    curLen += metrics.width(str);
                }
                for (int i = 0; i < str.length(); ++i) {
                    qreal t = tranformedRoadPath.percentAtLength(curLen);
                    QPointF pt = tranformedRoadPath.pointAtPercent(t);
                    qreal angle = tranformedRoadPath.angleAtPercent(t);
                    modY = (metrics.ascent()/2)-3;

                    QMatrix m;
                    m.translate(pt.x(), pt.y());
                    m.rotate(-angle+modAngle);

                    QPainterPath charPath;
                    charPath.addText(0, modY, font, str.mid(i, 1));
                    charPath = charPath * m;

                    textPath.addPath(charPath);

                    qreal incremenet = metrics.width(str[i]);
                    curLen += (incremenet * modIncrement);
                }
                startSegment += lenSegment;
            } while (--repeat >= 0);

            if (getLabelHalo()) {
                thePainter->setPen(QPen(Qt::white, font.pixelSize()/6));
                thePainter->drawPath(textPath);
            }
            thePainter->setPen(Qt::NoPen);
            thePainter->setBrush(LabelColor);
            thePainter->drawPath(textPath);
            thePainter->setClipRegion(rg);
        }
    }
    if (DrawLabelBackground && !strBg.isEmpty()) {
        QRegion rg = thePainter->clipRegion();
        font.setPixelSize(int(WW));
        QFontMetrics metrics(font);

        int repeat = int((tranformedRoadPath.length() / (metrics.width(strBg) * LABEL_STRAIGHT_DISTANCE)) - 0.5);
        int numSegment = repeat+1;
        qreal lenSegment = tranformedRoadPath.length() / numSegment;
        qreal startSegment = 0;
        do {

            int modX = 0;
            int modY = 0;

            qreal curLen = startSegment + (lenSegment / 2);
            qreal t = tranformedRoadPath.percentAtLength(curLen);
            QPointF pt = tranformedRoadPath.pointAtPercent(t);

            modX = - (metrics.width(strBg)/2);
            //modX = WW;
            modY = (metrics.ascent()/2);

            QPainterPath textPath, bgPath;
            textPath.addText(modX, modY, font, strBg);
            bgPath.addRect(textPath.boundingRect().adjusted(-BG_SPACING, -BG_SPACING, BG_SPACING, BG_SPACING));

            bool rgContains = false;
            for (int i=0; i<rg.rects().size(); i++) {
                if (rg.rects()[i].contains(bgPath.boundingRect().toRect().translated(pt.toPoint()))) {
                    rgContains = true;
                    break;
                }
            }
            if (rgContains) {
                thePainter->translate(pt);

                thePainter->setPen(QPen(LabelColor, BG_PEN_SZ));
                thePainter->setBrush(LabelBackgroundColor);
                thePainter->drawPath(bgPath);

                if (getLabelHalo()) {
                    thePainter->setPen(QPen(Qt::white, font.pixelSize()/5));
                    thePainter->drawPath(textPath);
                }
                thePainter->setPen(Qt::NoPen);
                thePainter->setBrush(LabelColor);
                thePainter->drawPath(textPath);

                rg -= bgPath.boundingRect().toRect().translated(pt.toPoint());
            }

            startSegment += lenSegment;
        } while (--repeat >= 0);

        thePainter->setClipRegion(rg);
    }
    thePainter->restore();
}
Example #13
0
void EditorViewMViface::handleNodeElementsForRowsInserted(
		const QList<QPair<NodeElement *, QPersistentModelIndex> > &nodes
		, const QModelIndex &parent
		)
{
	for (const QPair<NodeElement *, QPersistentModelIndex> &p : nodes) {
		NodeElement *elem = p.first;
		QPersistentModelIndex current = p.second;
		Id currentId = current.data(roles::idRole).value<Id>();
		bool needToProcessChildren = true;

		if (elem) {
			QPointF ePos = model()->data(current, roles::positionRole).toPointF();
			// setting position before parent definition 'itemChange' to work correctly
			elem->setPos(ePos);
			elem->setGeometry(mGraphicalAssistApi->configuration(elem->id()).boundingRect().translated(ePos.toPoint()));
			handleAddingSequenceForRowsInserted(parent, elem, current);
			handleElemDataForRowsInserted(elem, current);

			if (currentId.element() == "Class" && mGraphicalAssistApi->children(currentId).empty())
			{
				needToProcessChildren = false;
				for (int i = 0; i < 2; i++) {
					QString curChildElementType = (i == 0) ? "MethodsContainer" : "FieldsContainer";
					Id newUuid = Id("Kernel_metamodel", "Kernel", curChildElementType, QUuid::createUuid().toString());
					mGraphicalAssistApi->createElement(currentId, newUuid
							, false,  "(anonymous something)", QPointF(0, 0));
				}
			}
		}

		if (needToProcessChildren && model()->hasChildren(current)) {
			rowsInserted(current, 0, model()->rowCount(current) - 1);
		}

		if (elem) {
			elem->alignToGrid();
		}
	}
}
Example #14
0
void GameView::resizeRubberBand(const QPointF &cursorPoint)
{
	if (rubberBand)
		rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), cursorPoint.toPoint()).normalized());
}
/*!
  Draw dots

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param from index of the first point to be painted
  \param to index of the last point to be painted

  \sa draw(), drawCurve(), drawSticks(), drawLines(), drawSteps()
*/
void QwtPlotCurve::drawDots(QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    int from, int to) const
{
    const QRect window = painter->window();
    if ( window.isEmpty() )
        return;

    const bool doFill = d_data->brush.style() != Qt::NoBrush;

    QwtPolygonF polyline;
    if ( doFill )
        polyline.resize(to - from + 1);

    if ( to > from && d_data->paintAttributes & PaintFiltered )
    {
        if ( doFill )
        {
            QPointF pp( xMap.xTransform(x(from)), yMap.xTransform(y(from)) );

            QwtPainter::drawPoint(painter, pp.x(), pp.y());
            polyline[0] = pp;

            int count = 1;
            for (int i = from + 1; i <= to; i++)
            {
                const QPointF pi(xMap.xTransform(x(i)), yMap.xTransform(y(i)));
                if ( pi != pp )
                {
                    QwtPainter::drawPoint(painter, pi.x(), pi.y());

                    polyline[count] = pi;
                    count++;

                    pp = pi;
                }
            }
            if ( int(polyline.size()) != count )
                polyline.resize(count);
        }
        else
        {
            // if we don't need to fill, we can sort out
            // duplicates independent from the order

            PrivateData::PixelMatrix pixelMatrix(window);

            for (int i = from; i <= to; i++)
            {
                const QPointF p( xMap.xTransform(x(i)), yMap.xTransform(y(i)) );

                if ( pixelMatrix.testPixel(p.toPoint()) )
                    QwtPainter::drawPoint(painter, p.x(), p.y());
            }
        }
    }
    else
    {
        for (int i = from; i <= to; i++)
        {
            const double xi = xMap.xTransform(x(i));
            const double yi = yMap.xTransform(y(i));
            QwtPainter::drawPoint(painter, xi, yi);

            if ( doFill )
                polyline[i - from] = QPointF(xi, yi);
        }
    }

    if ( doFill )
    {
        if ( d_data->paintAttributes & ClipPolygons )
            polyline = QwtClipper::clipPolygonF(painter->window(), polyline);

        fillCurve(painter, xMap, yMap, polyline);
    }
}
bool
QGPolylineDrawerInteractor:: drawingStateFilter(QObject * obj, QEvent * evt)
{
  // Flag set if the received event must be trapped by the
  // method (ie. not passed to other filters).
  bool trap = false;

  QMouseEvent * me;
  QPoint pt;
  switch( evt->type() ) {

  case QEvent::MouseMove:
  {
    me = dynamic_cast<QMouseEvent *>(evt);
    
    QRect sceneRect = _view->sceneRect().toRect();

    //-- Keep cursor within the viewport range.

    // This prevent user to modify the view while the segment drawing
    // is not complete.
    // The 1 pixel substracted from the visibleWidth & visibleHeight
    // is mandatory, since viewport ranges is: 
    //    [(0,0), (visibleWidth - 1, visibleHeight - 1)]
    pt = me->pos();
    if (! isOnCanvas(pt) ) {
      pt.setX(max(0, min(pt.x(), sceneRect.width() - 1)));
      pt.setY(max(0, min(pt.y(), sceneRect.height() - 1)));
      pt = _view->viewport()->mapToGlobal( pt );
      QCursor::setPos(pt);
    }


    //-- Bind cursor to the content size.
    
    // WARNING: from here on we work with the 'real' mouse coordinate
    // not the ones fixed with QCursor::setPos()
    QPointF ptf = _view->mapToScene(me->pos());
    pt = ptf.toPoint();
    pt.setX(max(0, min(pt.x(), sceneRect.width() - 1)));
    pt.setY(max(0, min(pt.y(), sceneRect.height() - 1)));

    //-- Draw new line
    _endPoint = pt;

    drawLine( _endPoint );

    // Confirme draw (update the scene)
    _polyline->update();
   
    break;

  }
  case QEvent::MouseButtonPress:
  {
    me = dynamic_cast<QMouseEvent *>(evt);

    // --------------------------------------
    // Qt::Left Button
    // --------------------------------------
    if (me->button() == Qt::LeftButton) {
      
      _pointVect.push_back(_endPoint);
      _startPoint = _endPoint;
    }


    // --------------------------------------
    // Mid Button
    // --------------------------------------
    else if (me->button() == Qt::MidButton) {

      if (_pointVect.size() > 1) {
	
	// Remove last drawn line
	_main->docViewer()->scene()->removeItem(_polyline);

	// Insert segment in the document.
	createAndExecuteCommand();

	// Revert to normal state.(Either a segment is defined or the 
	// drawing is cancelled).
	_view->viewport()->removeEventFilter(_drawingFilter);
	_view->viewport()->installEventFilter(_normalFilter);
      }
    }

    // ----------------------------
    // Right button
    // -----------------------------
    else {

      // Insert segment in the document
      createAndExecuteCommand();

      // The temporary object must be removed from the scene
      _main->docViewer()->scene()->removeItem(_polyline);

      // Switch to normal state.
      _view->viewport()->removeEventFilter(_drawingFilter);
      _view->viewport()->installEventFilter(_normalFilter);

      // Clear point vector
      _pointVect.clear();
    }

    trap = true;  
    break;
  }
  default:
    /* EMPTY DEFAULT */
    break;
  }

  return trap;
}
Example #17
0
void CreateObjectTool::mouseMoved(const QPointF &pos,
                                  Qt::KeyboardModifiers modifiers)
{
    AbstractObjectTool::mouseMoved(pos, modifiers);

    if (!mNewMapObjectItem)
        return;

    const MapRenderer *renderer = mapDocument()->renderer();

    bool snapToGrid = Preferences::instance()->snapToGrid();
    bool snapToFineGrid = Preferences::instance()->snapToFineGrid();
    if (modifiers & Qt::ControlModifier) {
        snapToGrid = !snapToGrid;
        snapToFineGrid = false;
    }

    switch (mMode) {
    case CreateRectangle:
    case CreateEllipse: {
        const QPointF pixelCoords = renderer->screenToPixelCoords(pos);

        // Update the size of the new map object
        const QPointF objectPos = mNewMapObjectItem->mapObject()->position();
        QPointF newSize(qMax(qreal(0), pixelCoords.x() - objectPos.x()),
                        qMax(qreal(0), pixelCoords.y() - objectPos.y()));
        QPointF newTileSize = renderer->pixelToTileCoords(newSize);

        if (snapToFineGrid) {
            int gridFine = Preferences::instance()->gridFine();
            newTileSize = (newTileSize * gridFine).toPoint();
            newTileSize /= gridFine;
        } else if (snapToGrid)
            newTileSize = newTileSize.toPoint();

        // Holding shift creates circle or square
        if (modifiers & Qt::ShiftModifier) {
            qreal max = qMax(newTileSize.x(), newTileSize.y());
            newTileSize.setX(max);
            newTileSize.setY(max);
        }
        
        newSize = renderer->tileToPixelCoords(newTileSize);
        
        mNewMapObjectItem->resizeObject(QSizeF(newSize.x(), newSize.y()));
        break;
    }
    case CreateTile: {
        const QSize imgSize = mNewMapObjectItem->mapObject()->cell().tile->size();
        const QPointF diff(-imgSize.width() / 2, imgSize.height() / 2);
        QPointF tileCoords = renderer->screenToTileCoords(pos + diff);

        if (snapToFineGrid) {
            int gridFine = Preferences::instance()->gridFine();
            tileCoords = (tileCoords * gridFine).toPoint();
            tileCoords /= gridFine;
        } else if (snapToGrid)
            tileCoords = tileCoords.toPoint();
        
        QPointF pixelCoords = renderer->tileToPixelCoords(tileCoords);

        mNewMapObjectItem->mapObject()->setPosition(pixelCoords);
        mNewMapObjectItem->syncWithMapObject();
        mNewMapObjectItem->setZValue(10000); // sync may change it
        break;
    }
    case CreatePolygon:
    case CreatePolyline: {
        QPointF tileCoords = renderer->screenToTileCoords(pos);

        if (snapToFineGrid) {
            int gridFine = Preferences::instance()->gridFine();
            tileCoords = (tileCoords * gridFine).toPoint();
            tileCoords /= gridFine;
        } else if (snapToGrid)
            tileCoords = tileCoords.toPoint();
        
        QPointF pixelCoords = renderer->tileToPixelCoords(tileCoords);
        pixelCoords -= mNewMapObjectItem->mapObject()->position();

        QPolygonF polygon = mOverlayPolygonObject->polygon();
        polygon.last() = pixelCoords;
        mOverlayPolygonItem->setPolygon(polygon);
        break;
    }
    }
}
Example #18
0
void BrushTool::drawStroke()
{
    StrokeTool::drawStroke();
    QList<QPointF> p = m_pStrokeManager->interpolateStroke(currentWidth);

    Layer *layer = m_pEditor->getCurrentLayer();

    if (layer->type == Layer::BITMAP)
    {
        for (int i = 0; i < p.size(); i++) {
            p[i] = m_pScribbleArea->pixelToPoint(p[i]);
        }

        qreal opacity = 1.0;
        qreal brushWidth = currentWidth +  0.5 * properties.feather;
        qreal offset = qMax(0.0, currentWidth - 0.5 * properties.feather) / brushWidth;
        opacity = currentPressure;
        brushWidth = brushWidth * currentPressure;

        //        if (tabletInUse) { opacity = tabletPressure; }
        //        if (usePressure) { brushWidth = brushWidth * tabletPressure; }

        qreal brushStep = 0.5 * currentWidth + 0.5 * properties.feather;
        brushStep = brushStep * currentPressure;

        //        if (usePressure) { brushStep = brushStep * tabletPressure; }
        brushStep = qMax(1.0, brushStep);

        currentWidth = properties.width;
        BlitRect rect;

        QRadialGradient radialGrad(QPointF(0,0), 0.5 * brushWidth);
        m_pScribbleArea->setGaussianGradient(radialGrad,
            m_pEditor->colorManager()->frontColor(),
            opacity,
            offset);

        QPointF a = lastBrushPoint;
        QPointF b = getCurrentPoint();

        //        foreach (QSegment segment, calculateStroke(brushWidth))
        //        {
        //            QPointF a = lastBrushPoint;
        //            QPointF b = m_pScribbleArea->pixelToPoint(segment.second);

        qreal distance = 4 * QLineF(b, a).length();
        int steps = qRound(distance) / brushStep;

        for (int i = 0; i < steps; i++)
        {
            QPointF point = lastBrushPoint + (i + 1) * (brushStep) * (b - lastBrushPoint) / distance;
            rect.extend(point.toPoint());
            m_pScribbleArea->drawBrush( point,
                brushWidth,
                offset,
                m_pEditor->colorManager()->frontColor(),
                opacity);

            if (i == (steps - 1))
            {
                lastBrushPoint = point;
            }
        }
        //        }

        int rad = qRound(brushWidth) / 2 + 2;
        m_pScribbleArea->refreshBitmap(rect, rad);
    }
    else if (layer->type == Layer::VECTOR)
    {
        QPen pen(Qt::gray, 1, Qt::DashLine, Qt::RoundCap, Qt::RoundJoin);
        int rad = qRound((currentWidth / 2 + 2) * qAbs(m_pScribbleArea->getTempViewScaleX()));

        //        foreach (QSegment segment, calculateStroke(currentWidth))
        //        {
        //            QPointF a = segment.first;
        //            QPointF b = segment.second;
        //            m_pScribbleArea->drawLine(a, b, pen, QPainter::CompositionMode_SourceOver);
        //            m_pScribbleArea->refreshVector(QRect(a.toPoint(), b.toPoint()), rad);
        //        }
        if (p.size() == 4) {
            QSizeF size(2,2);
            QPainterPath path(p[0]);
            path.cubicTo(p[1],
                p[2],
                p[3]);
            m_pScribbleArea->drawPath(path, pen, Qt::NoBrush, QPainter::CompositionMode_Source);
            m_pScribbleArea->refreshVector(path.boundingRect().toRect(), rad);
        }
    }
}
Example #19
0
/*!
   Update the axis scale draw geometries

   \param azimuthMap Maps azimuth values to values related to 0.0, M_2PI
   \param radialMap Maps radius values into painter coordinates.
   \param pole Position of the pole in painter coordinates
   \param radius Radius of the complete plot area in painter coordinates

   \sa updateScaleDiv()
*/
void QwtPolarGrid::updateScaleDraws(
    const QwtScaleMap &azimuthMap, const QwtScaleMap &radialMap,
    const QPointF &pole, double radius ) const
{
    const QPoint p = pole.toPoint();

    const QwtInterval interval =
        d_data->gridData[QwtPolar::ScaleRadius].scaleDiv.interval();

    const int min = radialMap.transform( interval.minValue() );
    const int max = radialMap.transform( interval.maxValue() );
    const int l = max - min;

    for ( int axisId = 0; axisId < QwtPolar::AxesCount; axisId++ )
    {
        AxisData &axis = d_data->axisData[axisId];

        if ( axisId == QwtPolar::AxisAzimuth )
        {
            QwtRoundScaleDraw *scaleDraw =
                static_cast<QwtRoundScaleDraw *>( axis.scaleDraw );

            scaleDraw->setRadius( qRound( radius ) );
            scaleDraw->moveCenter( p );

            double from = ::fmod( 90.0 - azimuthMap.p1() * 180.0 / M_PI, 360.0 );
            if ( from < 0.0 )
                from += 360.0;

            scaleDraw->setAngleRange( from, from - 360.0 );

            const QwtTransform *transform = azimuthMap.transformation();
            if ( transform )
                scaleDraw->setTransformation( transform->copy() );
            else
                scaleDraw->setTransformation( NULL );
        }
        else
        {
            QwtScaleDraw *scaleDraw =
                static_cast<QwtScaleDraw *>( axis.scaleDraw );

            switch( axisId )
            {
                case QwtPolar::AxisLeft:
                {
                    scaleDraw->move( p.x() - min, p.y() );
                    scaleDraw->setLength( -l );
                    break;
                }
                case QwtPolar::AxisRight:
                {
                    scaleDraw->move( p.x() + min, p.y() );
                    scaleDraw->setLength( l );
                    break;
                }
                case QwtPolar::AxisTop:
                {
                    scaleDraw->move( p.x(), p.y() - max );
                    scaleDraw->setLength( l );
                    break;
                }
                case QwtPolar::AxisBottom:
                {
                    scaleDraw->move( p.x(), p.y() + max );
                    scaleDraw->setLength( -l );
                    break;
                }
            }
            const QwtTransform *transform = radialMap.transformation();
            if ( transform )
                scaleDraw->setTransformation( transform->copy() );
            else
                scaleDraw->setTransformation( NULL );
        }
    }
}
Example #20
0
void PencilTool::drawStroke()
{
    StrokeTool::drawStroke();
    QList<QPointF> p = strokeManager()->interpolateStroke();

    Layer* layer = mEditor->layers()->currentLayer();

    if (layer->type() == Layer::BITMAP)
    {
        qreal pressure = (properties.pressure) ? mCurrentPressure : 1.0;
        qreal opacity = (properties.pressure) ? (mCurrentPressure * 0.5) : 1.0;
        qreal brushWidth = properties.width * pressure;
        mCurrentWidth = brushWidth;

        qreal fixedBrushFeather = properties.feather;
        qreal brushStep = qMax(1.0, (0.5 * brushWidth));

        BlitRect rect;

        QPointF a = mLastBrushPoint;
        QPointF b = getCurrentPoint();

        qreal distance = 4 * QLineF(b, a).length();
        int steps = qRound(distance / brushStep);

        for (int i = 0; i < steps; i++)
        {
            QPointF point = mLastBrushPoint + (i + 1) * brushStep * (getCurrentPoint() - mLastBrushPoint) / distance;
            rect.extend(point.toPoint());
            mScribbleArea->drawPencil(point,
                                      brushWidth,
                                      fixedBrushFeather,
                                      mEditor->color()->frontColor(),
                                      opacity);

            if (i == (steps - 1))
            {
                mLastBrushPoint = getCurrentPoint();
            }
        }

        int rad = qRound(brushWidth) / 2 + 2;

        mScribbleArea->paintBitmapBufferRect(rect);
        mScribbleArea->refreshBitmap(rect, rad);
    }
    else if (layer->type() == Layer::VECTOR)
    {
        properties.useFeather = false;
        mCurrentWidth = 0; // FIXME: WTF?
        QPen pen(mEditor->color()->frontColor(),
                 1,
                 Qt::DotLine,
                 Qt::RoundCap,
                 Qt::RoundJoin);

        int rad = qRound((mCurrentWidth / 2 + 2) * mEditor->view()->scaling());

        if (p.size() == 4)
        {
            QPainterPath path(p[0]);
            path.cubicTo(p[1],
                         p[2],
                         p[3]);
            mScribbleArea->drawPath(path, pen, Qt::NoBrush, QPainter::CompositionMode_Source);
            mScribbleArea->refreshVector(path.boundingRect().toRect(), rad);
        }
    }
}
Example #21
0
void Canvas::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
    {
        if(enableFill)
        {
            AbstractShape * tmp = currentShape();
            if(tmp->isUnderMouse())
            {
                tmp->setBrush(QBrush(color()));
                currentScene->update();
            }
        }
        else
        {
            QPointF point = mapToScene(event->pos());
            _startX = point.x();
            _startY = point.y();

            QGraphicsItem * item = currentShape();
            QPointF p = event->pos();
            QRectF r = item->boundingRect();

            QPointF tl = mapFromScene(r.topLeft());
            QPointF br = mapFromScene(r.bottomRight());
            QPointF tr = mapFromScene(r.topRight());
            QPointF bl = mapFromScene(r.bottomLeft());

            checkIfProperRect(tl, br, tr, bl);

            if(belongToFirstCorners(p, tl, br))
            {
                _direction = None;
                _normalize = NormalizeLeft;
            }
            /*else if(belongToSecondCorners(p, tl, br))
            {
                _direction = None;
                _normalize = NormalizeRight;
            }*/
            else if((p.x() <= tl.x() && p.x() > tl.x() - 3) &&
                    p.y() > tl.y() - 3 && p.y() < br.y())
            {
                _direction = Left;
                _startY = r.topLeft().y();
            }
            else if((p.x() > br.x() - 3 && p.x() <= br.x()) &&
                    p.y() > tl.y() - 3 && p.y() < br.y())
            {
                _direction = Right;
                _startX = r.topLeft().x();
                _startY = r.topLeft().y();
                _endY = r.bottomRight().y();
            }
            else if((p.y() <= tl.y() && p.y() > tl.y() - 3) &&
                    p.x() > tl.x() - 3 && p.x() < br.x())
            {
                _direction = Top;
                _startX = r.topLeft().x();
            }
            else if((p.y() > br.y() - 3 && p.y() <= br.y()) &&
                    p.x() > tl.x() - 3 && p.x() < br.x())
            {
                _direction = Bottom;
                _startX = r.topLeft().x();
                _startY = r.topLeft().y();
                _endX = r.bottomRight().x();
            }
            else if(p.x() >= tl.x() && p.x() <= br.x()
                    && p.y() >= tl.y() && p.y() <= br.y())
            {
                _direction = None;
                isMoved = true;
                _startX = item->boundingRect().topLeft().x();
                _startY = item->boundingRect().topLeft().y();
                _endX = item->boundingRect().bottomRight().x();
                _endY = item->boundingRect().bottomRight().y();
                coordinatesIterationMove = event->pos();
                linesEnds.clear();
                linesStarts.clear();
                linePointIndexes.clear();
                for(auto & i : currentScene->lines)
                {
                    if(i->boundingRect().intersects(currentShape()->boundingRect()))
                    {
                        QPointF tl = i->boundingRect().topLeft();
                        QPointF br = i->boundingRect().bottomRight();
                        if(currentShape()->boundingRect().contains(br) &&
                                !currentShape()->boundingRect().contains(tl))
                        {
                            linesEnds.append(br.toPoint());
                            linesStarts.append(tl.toPoint());
                            linePointIndexes.append(currentScene->lines.indexOf(i));
                        }
                        else if(currentShape()->boundingRect().contains(tl) &&
                                !currentShape()->boundingRect().contains(br))
                        {
                            linesEnds.append(tl.toPoint());
                            linesStarts.append(br.toPoint());
                            linePointIndexes.append(currentScene->lines.indexOf(i));
                        }
                    }
                }
            }
            else
            {
                _direction = None;

                currentScene->edge()->hide();
                if(point.x() > sceneRect().topLeft().x()
                        && point.y() > sceneRect().topLeft().y()
                        && point.x() < sceneRect().bottomRight().x()
                        && point.y() < sceneRect().bottomRight().y())
                {
                    enableResize = false;
                    buttonPressed = true;
                    if(shapeDrawn)
                    {
                        notifyObservers();
                    }
                }
            }
        }
    }
}
void KisPanAction::mouseMoved(const QPointF &lastPos, const QPointF &pos)
{
    QPointF relMovement = -(pos - lastPos);
    inputManager()->canvas()->canvasController()->pan(relMovement.toPoint());
}
GraphicsDirectedEdge::
GraphicsDirectedEdge(QPointF start, QPointF stop, qreal factor)
: GraphicsDirectedEdge(start.toPoint(), stop.toPoint(), factor) {}
Example #24
0
void SmudgeTool::drawStroke()
{
    if ( !mScribbleArea->isLayerPaintable() ) return;

    Layer* layer = mEditor->layers()->currentLayer();
    if (layer == NULL) { return; }

    BitmapImage *targetImage = ((LayerBitmap *)layer)->getLastBitmapImageAtFrame(mEditor->currentFrame(), 0);
    StrokeTool::drawStroke();
    QList<QPointF> p = m_pStrokeManager->interpolateStroke();

    for (int i = 0; i < p.size(); i++)
    {
        p[ i ] = mEditor->view()->mapScreenToCanvas( p[ i ] );
    }

    qreal opacity = 1.0;
    qreal brushWidth = mCurrentWidth +  0.0 * properties.feather;
    qreal offset = qMax(0.0, mCurrentWidth - 0.5 * properties.feather) / brushWidth;
    //opacity = currentPressure; // todo: Probably not interesting?!
    //brushWidth = brushWidth * opacity;

    BlitRect rect;
    QPointF a = lastBrushPoint;
    QPointF b = getCurrentPoint();


    if (toolMode == 0) // liquify hard (default)
    {
        qreal brushStep = 2;
        qreal distance = QLineF(b, a).length()/2.0;
        int steps = qRound(distance / brushStep);
        int rad = qRound(brushWidth / 2.0) + 2;

        QPointF sourcePoint = lastBrushPoint;
        for (int i = 0; i < steps; i++)
        {
            QPointF targetPoint = lastBrushPoint + (i + 1) * (brushStep) * (b - lastBrushPoint) / distance;
            rect.extend(targetPoint.toPoint());
            mScribbleArea->liquifyBrush( targetImage,
                                                sourcePoint,
                                                targetPoint,
                                                brushWidth,
                                                offset,
                                                opacity);

            if (i == (steps - 1))
            {
                lastBrushPoint = targetPoint;
            }
            sourcePoint = targetPoint;
            mScribbleArea->refreshBitmap(rect, rad);
            mScribbleArea->paintBitmapBuffer();
        }
    }
    else // liquify smooth
    {
        qreal brushStep = 2.0;
        qreal distance = QLineF(b, a).length();
        int steps = qRound(distance / brushStep);
        int rad = qRound(brushWidth / 2.0) + 2;

        QPointF sourcePoint = lastBrushPoint;
        for (int i = 0; i < steps; i++)
        {
            QPointF targetPoint = lastBrushPoint + (i + 1) * (brushStep) * (b - lastBrushPoint) / distance;
            rect.extend(targetPoint.toPoint());
            mScribbleArea->blurBrush( targetImage,
                                                sourcePoint,
                                                targetPoint,
                                                brushWidth,
                                                offset,
                                                opacity);

            if (i == (steps - 1))
            {
                lastBrushPoint = targetPoint;
            }
            sourcePoint = targetPoint;
            mScribbleArea->refreshBitmap(rect, rad);
            mScribbleArea->paintBitmapBuffer();
        }
    }
}
Example #25
0
void KisZoomAndPanTest::testRotation(qreal vastScrolling, qreal zoom)
{
    KisConfig cfg;
    cfg.setVastScrolling(vastScrolling);

    ZoomAndPanTester t;

    QCOMPARE(t.image()->size(), QSize(640,441));
    QCOMPARE(t.image()->xRes(), 1.0);
    QCOMPARE(t.image()->yRes(), 1.0);

    QPointF preferredCenter = zoom * t.image()->bounds().center();

    t.canvasController()->resize(QSize(500,500));
    t.zoomController()->setZoom(KoZoomMode::ZOOM_CONSTANT, zoom);
    t.canvasController()->setPreferredCenter(preferredCenter.toPoint());

    QCOMPARE(t.canvasWidget()->size(), QSize(483,483));
    QCOMPARE(t.canvasWidget()->size(), t.canvasController()->viewportSize());

    QPointF realCenterPoint = t.coordinatesConverter()->widgetToImage(t.coordinatesConverter()->widgetCenterPoint());
    QPointF expectedCenterPoint = QPointF(t.image()->bounds().center());

    if(!compareWithRounding(realCenterPoint, expectedCenterPoint, 2/zoom)) {
        dbgKrita << "Failed to set initial center point";
        dbgKrita << ppVar(expectedCenterPoint) << ppVar(realCenterPoint);
        QFAIL("FAIL: Failed to set initial center point");
    }

    QVERIFY(checkRotation(t, 30));
    QVERIFY(checkRotation(t, 20));
    QVERIFY(checkRotation(t, 10));
    QVERIFY(checkRotation(t, 5));
    QVERIFY(checkRotation(t, 5));
    QVERIFY(checkRotation(t, 5));

    if(vastScrolling < 0.5 && zoom < 1) {
        warnKrita << "Disabling a few tests for vast scrolling ="
                   << vastScrolling << ". See comment for more";
        /**
         * We have to disable a couple of tests here for the case when
         * vastScrolling value is 0.2. The problem is that the centering
         * correction applied  to the offset in
         * KisCanvasController::rotateCanvas pollutes the preferredCenter
         * value, because KoCnvasControllerWidget has no access to this
         * correction and cannot calculate the real value of the center of
         * the image. To fix this bug the calculation of correction
         * (aka "origin") should be moved to the KoCanvasControllerWidget
         * itself which would cause quite huge changes (including the change
         * of the external interface of it). Namely, we would have to
         * *calculate* offset from the value of the scroll bars, but not
         * use their values directly:
         *
         * offset = scrollBarValue - origin
         *
         * So now we just disable these unittests and allow a couple
         * of "jumping" bugs appear in vastScrolling < 0.5 modes, which
         * is, actually, not the default case.
         */

    } else {
        QVERIFY(checkRotation(t, 5));
        QVERIFY(checkRotation(t, 5));
        QVERIFY(checkRotation(t, 5));
    }
}
Example #26
0
/**
 * If we have a selected annotation, move or resize it. Otherwise extend
 * the preview rectangle for the new annotation.
 */
void Annotation::motion(const paintcore::Point& point, bool constrain, bool center)
{
	Q_UNUSED(constrain);
	Q_UNUSED(center);

	QPointF p = point - m_p2;
	m_handle = owner.model()->annotations()->annotationAdjustGeometry(m_selectedId, m_handle, p.toPoint());
	m_p2 = point;
}
void CreateRoundaboutInteraction::mousePressEvent(QMouseEvent * event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        if (!HaveCenter)
        {
            HaveCenter = true;
            view()->setInteracting(true);
            Center = XY_TO_COORD(event->pos());
        }
        else
        {
            calculatePoints();
            if (Points.size() == 0) return;

            QPointF Prev = Points[0];
            Node* First = g_backend.allocNode(theMain->document()->getDirtyOrOriginLayer(), XY_TO_COORD(Prev.toPoint()));
            Way* R = g_backend.allocWay(theMain->document()->getDirtyOrOriginLayer());
            CommandList* L  = new CommandList(MainWindow::tr("Create Roundabout %1").arg(R->id().numId), R);
            L->add(new AddFeatureCommand(theMain->document()->getDirtyOrOriginLayer(),R,true));
            R->add(First);
            L->add(new AddFeatureCommand(theMain->document()->getDirtyOrOriginLayer(),First,true));
            if (M_PREFS->getAutoSourceTag()) {
                QStringList sl = theMain->document()->getCurrentSourceTags();
                if (sl.size())
                    R->setTag("source", sl.join(";"));
            }
            // "oneway" is implied on roundabouts
            //R->setTag("oneway","yes");
            if (DockData.type->currentIndex() == 0)
                R->setTag("junction","roundabout");
            for (int i = 1; i < Points.size(); i++ ) {
                QPointF Next = Points[i];
                Node* New = g_backend.allocNode(theMain->document()->getDirtyOrOriginLayer(), XY_TO_COORD(Next.toPoint()));
                L->add(new AddFeatureCommand(theMain->document()->getDirtyOrOriginLayer(),New,true));
                R->add(New);
            }
            R->add(First);
            for (FeatureIterator it(document()); !it.isEnd(); ++it) {
                Way* W1 = CAST_WAY(it.get());
                if (W1 && (W1 != R))
                    Way::createJunction(theMain->document(), L, R, W1, true);
            }
            theMain->properties()->setSelection(R);
            document()->addHistory(L);
            view()->setInteracting(false);
            view()->invalidate(true, true, false);
            theMain->launchInteraction(0);
        }
    }
    else
        Interaction::mousePressEvent(event);
}
Example #28
0
bool KDChart::TextLayoutItem::intersects( const TextLayoutItem& other, const QPointF& myPos, const QPointF& otherPos ) const
{
    return intersects( other, myPos.toPoint(), otherPos.toPoint() );
}
void QGraphicsWidgetPrivate::windowFrameHoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
    Q_Q(QGraphicsWidget);
    if (!hasDecoration())
        return;

    ensureWindowData();

    if (q->rect().contains(event->pos())) {
        if (windowData->buttonMouseOver || windowData->hoveredSubControl != QStyle::SC_None)
            windowFrameHoverLeaveEvent(event);
        return;
    }

    bool wasMouseOver = windowData->buttonMouseOver;
    QRect oldButtonRect = windowData->buttonRect;
    windowData->buttonRect = QRect();
    windowData->buttonMouseOver = false;
    QPointF pos = event->pos();
    QStyleOptionTitleBar bar;
    // make sure that the coordinates (rect and pos) we send to the style are positive.
    if (windowFrameMargins) {
        pos.rx() += windowFrameMargins[Left];
        pos.ry() += windowFrameMargins[Top];
    }
    initStyleOptionTitleBar(&bar);
    bar.rect = q->windowFrameRect().toRect();
    bar.rect.moveTo(0,0);
    bar.rect.setHeight(int(titleBarHeight(bar)));

    Qt::CursorShape cursorShape = Qt::ArrowCursor;
    bool needsSetCursorCall = true;
    switch (q->windowFrameSectionAt(event->pos())) {
        case Qt::TopLeftSection:
        case Qt::BottomRightSection:
            cursorShape = Qt::SizeFDiagCursor;
            break;
        case Qt::TopRightSection:
        case Qt::BottomLeftSection:
            cursorShape = Qt::SizeBDiagCursor;
            break;
        case Qt::LeftSection:
        case Qt::RightSection:
            cursorShape = Qt::SizeHorCursor;
            break;
        case Qt::TopSection:
        case Qt::BottomSection:
            cursorShape = Qt::SizeVerCursor;
            break;
        case Qt::TitleBarArea:
            windowData->buttonRect = q->style()->subControlRect(
                QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarCloseButton, 0);
#ifdef Q_WS_MAC
            // On mac we should hover if we are in the 'area' of the buttons
            windowData->buttonRect |= q->style()->subControlRect(
                QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMinButton, 0);
            windowData->buttonRect |= q->style()->subControlRect(
                QStyle::CC_TitleBar, &bar, QStyle::SC_TitleBarMaxButton, 0);
#endif
            if (windowData->buttonRect.contains(pos.toPoint()))
                windowData->buttonMouseOver = true;
            event->ignore();
            break;
        default:
            needsSetCursorCall = false;
            event->ignore();
        }
#ifndef QT_NO_CURSOR
    if (needsSetCursorCall)
        q->setCursor(cursorShape);
#endif
    // update buttons if we hover over them
    windowData->hoveredSubControl = q->style()->hitTestComplexControl(QStyle::CC_TitleBar, &bar, pos.toPoint(), 0);
    if (windowData->hoveredSubControl != QStyle::SC_TitleBarCloseButton)
        windowData->hoveredSubControl = QStyle::SC_TitleBarLabel;

    if (windowData->buttonMouseOver != wasMouseOver) {
        if (!oldButtonRect.isNull())
            q->update(QRectF(oldButtonRect).translated(q->windowFrameRect().topLeft()));
        if (!windowData->buttonRect.isNull())
            q->update(QRectF(windowData->buttonRect).translated(q->windowFrameRect().topLeft()));
    }
}
Example #30
0
void SeqDiagramView::mousePressEvent(QMouseEvent * e)
{
    if (!window()->frozen()) {
        if (e->button() == ::Qt::RightButton)
            DiagramView::mousePressEvent(e);
        else {
            QPoint diagramPoint(e->x(), e->y());
            QPointF scenePoint = mapToScene(diagramPoint);
            UmlCode c = window()->buttonOn();

            switch (c) {
            case UmlClass: {
                history_protected = FALSE;
                unselect_all();
                window()->selectOn();
                history_save();

                BrowserNode * parent =
                        ((BrowserNode *) window()->browser_diagram()->parent());
                BrowserClass * b =
                        BrowserClass::get_class(parent);
                if (b != 0) {
                    SdClassInstCanvas * cli =
                            new SdClassInstCanvas(b, the_canvas(), scenePoint.x(), 0);

                    cli->show();
                    cli->moveBy(scenePoint.x() - cli->center().x(), 0);
                    cli->upper();
                    window()->package_modified();
                }
            }
                break;

            case UmlClassInstance: {
                history_protected = TRUE;
                unselect_all();
                window()->selectOn();
                history_save();

                BrowserNode * parent =
                        ((BrowserNode *) window()->browser_diagram()->parent());
                BrowserClassInstance * b =
                        BrowserClassInstance::get_classinstance(parent);
                if (b != 0) {
                    SdClassInstCanvas * cli =
                            new SdClassInstCanvas(b, the_canvas(), scenePoint.x(), 0);

                    cli->show();
                    cli->moveBy(scenePoint.x() - cli->center().x(), 0);
                    cli->upper();
                    window()->package_modified();
                }
            }
                break;

            case UmlSyncSelfMsg:
            case UmlAsyncSelfMsg:
            case UmlSelfReturnMsg: {
                history_protected = TRUE;
                unselect_all();
                window()->selectOn();
                history_save();

                QGraphicsItem * ci = the_canvas()->collision(scenePoint.toPoint());

                if (ci != 0) {
                    DiagramItem * i = QCanvasItemToDiagramItem(ci);

                    if (i != 0) {
                        QString err = i->may_start(c);

                        if (!err.isEmpty())
                            msg_critical("Douml" , err);
                        else {
                            i->connexion(c, i, scenePoint.toPoint(), scenePoint.toPoint());
                            window()->package_modified();
                        }
                    }
                }
            }
                break;

            case UmlContinuation: {
                history_protected = TRUE;
                unselect_all();
                window()->selectOn();
                history_save();
                SdContinuationCanvas * cont =
                        new SdContinuationCanvas(the_canvas(), scenePoint.x(), scenePoint.y(), 0);
                cont->show();
                cont->upper();
                window()->package_modified();
            }
                break;

            default:
                DiagramView::mousePressEvent(e);
                return;
            }

            canvas()->update();
            history_protected = FALSE;
        }
    }
    else
        DiagramView::mousePressEvent(e);
}