42#include <QGraphicsSceneHoverEvent>
43#include <QKeySequence>
49#include "moc_qgsmaptoolselectannotation.cpp"
51using namespace Qt::StringLiterals;
58 setFlags( flags() | QGraphicsItem::ItemIsSelectable );
62 setColor( QColor( 50, 50, 50, 200 ) );
80 return lyr ? lyr->
item( mItemId ) :
nullptr;
94 const double mapRotation =
mMapCanvas->mapSettings().rotation();
95 const double frameRotation = rectItem ? rectItem->
appliedRotation( mapRotation ) - mapRotation : 0;
99 double minX = std::numeric_limits<double>::max();
100 double minY = std::numeric_limits<double>::max();
101 double maxX = std::numeric_limits<double>::lowest();
102 double maxY = std::numeric_limits<double>::lowest();
103 auto includePixel = [&](
const QPointF &p ) {
104 minX = std::min( minX, p.x() );
105 minY = std::min( minY, p.y() );
106 maxX = std::max( maxX, p.x() );
107 maxY = std::max( maxY, p.y() );
116 for (
const QPointF &corner : corners )
126 QgsDebugError( u
"Error transforming annotation item corner"_s );
140 for (
const QgsPointXY &corner : bboxCorners )
158 const double mupp =
mMapCanvas->mapSettings().mapUnitsPerPixel();
159 const double halfWidth = 0.5 *
boundingBox.width() / mupp;
160 const double halfHeight = 0.5 *
boundingBox.height() / mupp;
188 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
189 selectedItem->updateBoundingBox( selectedItem->boundingBox() );
197 mSelectionRubberBand.reset();
198 mMouseHandles.reset();
210 mSelectionRubberBand.reset();
211 mMouseHandles.reset();
213 mSelectedItems.clear();
215 mCopiedItems.clear();
216 mCopiedItemsTopLeft = QPointF();
223 const QPointF scenePos =
mCanvas->mapToScene( event->pos() );
225 if ( event->buttons() == Qt::NoButton )
227 if ( mMouseHandles->isDragging() )
229 QGraphicsSceneMouseEvent forwardedEvent( QEvent::GraphicsSceneMouseMove );
230 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
231 forwardedEvent.setScenePos( scenePos );
232 forwardedEvent.setLastScenePos( mLastScenePos );
233 forwardedEvent.setButton( Qt::LeftButton );
234 mMouseHandles->mouseMoveEvent( &forwardedEvent );
238 if ( mMouseHandles->sceneBoundingRect().contains( scenePos ) )
240 QGraphicsSceneHoverEvent forwardedEvent( QEvent::GraphicsSceneHoverMove );
241 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
242 forwardedEvent.setScenePos( scenePos );
243 mMouseHandles->hoverMoveEvent( &forwardedEvent );
244 mHoveringMouseHandles =
true;
246 else if ( mHoveringMouseHandles )
248 QGraphicsSceneHoverEvent forwardedEvent( QEvent::GraphicsSceneHoverLeave );
249 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
250 forwardedEvent.setScenePos( scenePos );
251 mMouseHandles->hoverMoveEvent( &forwardedEvent );
252 mHoveringMouseHandles =
false;
256 else if ( event->buttons() == Qt::LeftButton )
258 if ( mMouseHandles->shouldBlockEvent( event ) )
260 QGraphicsSceneMouseEvent forwardedEvent( QEvent::GraphicsSceneMouseMove );
261 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
262 forwardedEvent.setScenePos( scenePos );
263 forwardedEvent.setLastScenePos( mLastScenePos );
264 forwardedEvent.setButton( Qt::LeftButton );
265 mMouseHandles->mouseMoveEvent( &forwardedEvent );
279 QColor color( Qt::blue );
280 color.setAlpha( 63 );
281 mSelectionRubberBand->setColor( color );
282 mSelectionRect.setTopLeft( event->pos() );
285 mSelectionRect.setBottomRight( event->pos() );
286 if ( mSelectionRubberBand )
288 mSelectionRubberBand->setToCanvasRectangle( mSelectionRect );
289 mSelectionRubberBand->show();
294 mLastScenePos = scenePos;
299 if ( event->button() != Qt::LeftButton )
304 QPointF scenePos =
mCanvas->mapToScene( event->pos() );
305 const bool toggleSelection =
event->modifiers() & Qt::ShiftModifier;
307 if ( !toggleSelection && !mSelectedItems.empty() && mMouseHandles->sceneBoundingRect().contains( scenePos ) )
309 QGraphicsSceneMouseEvent forwardedEvent( QEvent::GraphicsSceneMousePress );
310 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
311 forwardedEvent.setScenePos( scenePos );
312 forwardedEvent.setLastScenePos( mLastScenePos );
313 forwardedEvent.setButton( Qt::LeftButton );
314 mMouseHandles->mousePressEvent( &forwardedEvent );
318 mSelectionRect.setTopLeft( event->pos() );
319 mSelectionRect.setBottomRight( event->pos() );
322 mLastScenePos = scenePos;
328 if ( event->button() == Qt::RightButton )
330 mMouseHandles->reset();
331 mSelectionRubberBand.reset();
336 if ( event->button() != Qt::LeftButton )
341 QPointF scenePos =
mCanvas->mapToScene( event->pos() );
343 if ( mMouseHandles->shouldBlockEvent( event ) )
345 QGraphicsSceneMouseEvent forwardedEvent( QEvent::GraphicsSceneMouseRelease );
346 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
347 forwardedEvent.setScenePos( scenePos );
348 forwardedEvent.setLastScenePos( mLastScenePos );
349 forwardedEvent.setButton( Qt::LeftButton );
350 mMouseHandles->mouseReleaseEvent( &forwardedEvent );
364 mSelectionRubberBand.reset();
370 setSelectedItemsFromRect( searchRect, ( event->modifiers() & Qt::ShiftModifier ) );
374 setSelectedItemFromPoint( event->
mapPoint(), ( event->modifiers() & Qt::ShiftModifier ) );
377 mMouseHandles->setSelected( !mSelectedItems.empty() );
383 if ( mMouseHandles->isDragging() || mMouseHandles->isResizing() || mMouseHandles->isRotating() )
385 if ( event->key() == Qt::Key_Escape )
387 mMouseHandles->reset();
388 mSelectionRubberBand.reset();
394 if ( mSelectedItems.empty() )
399 if ( event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete )
401 while ( !mSelectedItems.empty() )
405 annotationLayer->removeItem( mSelectedItems.back()->itemId() );
407 mSelectedItems.pop_back();
410 updateSelectedItem();
413 else if ( event->key() == Qt::Key_Left || event->key() == Qt::Key_Right || event->key() == Qt::Key_Up || event->key() == Qt::Key_Down )
415 const int pixels = (
event->modifiers() & Qt::ShiftModifier ) ? 1 : 50;
418 if ( event->key() == Qt::Key_Up )
422 else if ( event->key() == Qt::Key_Down )
426 else if ( event->key() == Qt::Key_Left )
430 else if ( event->key() == Qt::Key_Right )
435 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
445 if ( mMouseHandles->isDragging() || mMouseHandles->isResizing() || mMouseHandles->isRotating() )
450 QKeySequence keySequence( event->key() | event->modifiers() );
452 if ( keySequence == QKeySequence::Copy || keySequence == QKeySequence::Cut )
454 mCopiedItems.clear();
455 mCopiedItemsTopLeft =
toMapCoordinates( QPoint( mMouseHandles->sceneBoundingRect().topLeft().x(), mMouseHandles->sceneBoundingRect().topLeft().y() ) );
456 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
460 std::unique_ptr<QgsAnnotationItem> copiedItem;
461 copiedItem.reset( annotationItem->clone() );
462 mCopiedItems.push_back( std::move( copiedItem ) );
466 if ( keySequence == QKeySequence::Cut )
468 while ( !mSelectedItems.empty() )
472 annotationLayer->removeItem( mSelectedItems.back()->itemId() );
474 mSelectedItems.pop_back();
481 else if ( keySequence == QKeySequence::Paste )
483 const QgsPointXY copiedItemsSceneTopLeft =
mCanvas->mapSettings().mapToPixel().transform( mCopiedItemsTopLeft );
484 const double deltaX = mLastScenePos.x() - copiedItemsSceneTopLeft.
x();
485 const double deltaY = mLastScenePos.y() - copiedItemsSceneTopLeft.
y();
486 if ( !mSelectedItems.empty() )
488 mSelectedItems.clear();
491 for ( std::unique_ptr<QgsAnnotationItem> &copiedItem : mCopiedItems )
494 if ( !annotationLayer )
498 QString pastedItemId = annotationLayer->
addItem( copiedItem->clone() );
499 mSelectedItems.push_back( std::make_unique<QgsAnnotationItemRubberBand>( annotationLayer->
id(), pastedItemId,
mCanvas ) );
500 attemptMoveBy( mSelectedItems.back().get(), deltaX, deltaY );
501 mSelectedItems.back().get()->setNeedsUpdatedBoundingBox(
true );
513 QList<QgsAnnotationItemRubberBand *> items;
514 for (
const std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
516 if ( !selectedItem.get()->boundingBox().isEmpty() )
518 items << selectedItem.get();
524void QgsMapToolSelectAnnotation::onCanvasRefreshed()
527 if ( !renderedItemResults )
532 const bool interactiveOperation = mMouseHandles && ( mMouseHandles->isDragging() || mMouseHandles->isResizing() || mMouseHandles->isRotating() );
534 const QList<QgsRenderedItemDetails *> items = renderedItemResults->
renderedItems();
535 bool needsSelectedItemsUpdate =
false;
536 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
538 if ( interactiveOperation && !selectedItem->needsUpdatedBoundingBox() )
541 auto it = std::find_if( items.begin(), items.end(), [&selectedItem](
const QgsRenderedItemDetails *item ) {
542 if ( const QgsRenderedAnnotationItemDetails *annotationItem = dynamic_cast<const QgsRenderedAnnotationItemDetails *>( item ) )
544 if ( annotationItem->itemId() == selectedItem->itemId() && annotationItem->layerId() == selectedItem->layerId() )
552 if ( it != items.end() )
554 needsSelectedItemsUpdate =
true;
555 selectedItem->updateBoundingBox( ( *it )->boundingBox() );
559 if ( needsSelectedItemsUpdate )
561 emit selectedItemsChanged();
565long long QgsMapToolSelectAnnotation::annotationItemRubberBandIndexFromId(
const QString &layerId,
const QString &itemId )
567 if ( mSelectedItems.empty() )
572 auto it = std::find_if( mSelectedItems.begin(), mSelectedItems.end(), [&layerId, &itemId](
auto &item ) { return item->layerId() == layerId && item->itemId() == itemId; } );
573 return it != mSelectedItems.end() ? std::distance( mSelectedItems.begin(), it ) : -1;
576void QgsMapToolSelectAnnotation::setSelectedItemsFromRect(
const QgsRectangle &mapRect,
bool toggleSelection )
579 if ( !renderedItemResults )
581 if ( !toggleSelection )
583 clearSelectedItems();
591 if ( !toggleSelection )
593 clearSelectedItems();
598 if ( !toggleSelection )
600 mSelectedItems.clear();
602 for (
const QgsRenderedAnnotationItemDetails *item : items )
605 if ( annotationItem )
607 if ( toggleSelection )
609 long long index = annotationItemRubberBandIndexFromId( item->layerId(), item->itemId() );
612 mSelectedItems.erase( mSelectedItems.begin() + index );
616 mSelectedItems.push_back( std::make_unique<QgsAnnotationItemRubberBand>( item->layerId(), item->itemId(),
mCanvas ) );
617 mSelectedItems.back()->updateBoundingBox( item->boundingBox() );
621 updateSelectedItem();
624void QgsMapToolSelectAnnotation::setSelectedItemFromPoint(
const QgsPointXY &mapPoint,
bool toggleSelection )
626 QgsRectangle searchRect = QgsRectangle( mapPoint.
x(), mapPoint.
y(), mapPoint.
x(), mapPoint.
y() );
630 if ( !renderedItemResults )
632 clearSelectedItems();
639 if ( !toggleSelection )
641 clearSelectedItems();
646 QgsRectangle itemBounds;
647 const QgsRenderedAnnotationItemDetails *closestItem =
findClosestItemToPoint( mapPoint, items, itemBounds );
650 if ( !toggleSelection )
652 clearSelectedItems();
657 long long index = annotationItemRubberBandIndexFromId( closestItem->
layerId(), closestItem->
itemId() );
660 if ( toggleSelection )
662 mSelectedItems.erase( mSelectedItems.begin() + index );
667 if ( !toggleSelection )
669 mSelectedItems.clear();
672 mSelectedItems.push_back( std::make_unique<QgsAnnotationItemRubberBand>( closestItem->
layerId(), closestItem->
itemId(),
mCanvas ) );
673 mSelectedItems.back()->updateBoundingBox( closestItem->
boundingBox() );
676 updateSelectedItem();
679void QgsMapToolSelectAnnotation::updateSelectedItem()
681 if ( mSelectedItems.size() > 1 )
685 else if ( mSelectedItems.size() == 1 )
695void QgsMapToolSelectAnnotation::clearSelectedItems()
697 const bool hadSelection = !mSelectedItems.empty();
698 mSelectedItems.clear();
703 updateSelectedItem();
716 const QgsVector translation( mapMoved.
x() - mapOrigin.
x(), mapMoved.
y() - mapOrigin.
y() );
723 const QList<QgsAnnotationItemNode> itemNodes = annotationItem->
nodesV2( context );
726 QgsPointXY mapPoint =
mCanvas->mapSettings().layerToMapCoordinates( annotationLayer, node.point() );
727 mapPoint += translation;
728 QgsPointXY modifiedPoint =
mCanvas->mapSettings().mapToLayerCoordinates( annotationLayer, mapPoint );
731 switch ( annotationLayer->
applyEditV2( &operation, context ) )
743 boundingBox += translation;
758 switch ( annotationLayer->applyEditV2( &operation, context ) )
775 if ( !annotationItem )
785 rotation = rectItem->appliedRotation(
mCanvas->mapSettings().rotation() );
790 const double w = rect.width();
791 const double h = rect.height();
792 const QPointF halfDiagonal( w / 2.0, h / 2.0 );
793 QTransform itemRotation;
794 itemRotation.rotate( rotation );
795 const QPointF unrotatedTopLeftScene = rect.topLeft() + itemRotation.map( halfDiagonal ) - halfDiagonal;
796 const QRectF newSceneRect( unrotatedTopLeftScene, QSizeF( w, h ) );
804 const QgsRectangle newBounds =
mCanvas->mapSettings().mapToLayerCoordinates( annotationLayer, newMapBounds );
806 if ( oldBounds.
width() == 0 || oldBounds.
height() == 0 )
813 const QList<QgsAnnotationItemNode> itemNodes = annotationItem->
nodesV2( context );
816 const double modifiedX = newBounds.
xMinimum() + newBounds.
width() * ( ( node.point().x() - oldBounds.
xMinimum() ) / oldBounds.
width() );
817 const double modifiedY = newBounds.
yMaximum() - newBounds.
height() * ( ( oldBounds.
yMaximum() - node.point().y() ) / oldBounds.
height() );
818 QgsPointXY modifiedPoint( modifiedX, modifiedY );
820 switch ( annotationLayer->
applyEditV2( &operation, context ) )
Provides global constants and enumerations for use throughout the application.
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
@ Invalid
Operation has invalid parameters for the item, no change occurred.
@ Success
Item was modified successfully.
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
Encapsulates the context for an annotation item edit operation.
void setCurrentItemBounds(const QgsRectangle &bounds)
Sets the current rendered bounds of the item, in the annotation layer's CRS.
void setRenderContext(const QgsRenderContext &context)
Sets the render context associated with the edit operation.
Annotation item edit operation consisting of moving a node.
Annotation item edit operation consisting of rotating an item.
Contains information about a node used for editing an annotation item.
An annotation item rubberband used by QgsMapToolSelectAnnotation to represent selected items.
bool needsUpdatedBoundingBox() const
Returns true if the bounding box requires updating on fresh annotation item rendering.
QgsRectangle boundingBox() const
Returns the item bounding box.
QString itemId() const
Returns the annotation item ID.
QgsAnnotationItemRubberBand(const QString &layerId, const QString &itemId, QgsMapCanvas *canvas)
Constructor for QgsAnnotationItemRubberBand.
QgsAnnotationItem * item() const
Returns a pointer to the annotation item.
QgsAnnotationLayer * layer() const
Returns a pointer to the annotation layer.
void updateBoundingBox(const QgsRectangle &boundingBox)
Update the rubberband using the provided annotation item bounding box.
QString layerId() const
Returns the annotation layer ID.
void setNeedsUpdatedBoundingBox(bool needsUpdatedBoundingBox)
Sets whether the bounding box requires updating on fresh annotation item rendering.
Abstract base class for annotation items which are drawn with QgsAnnotationLayers.
virtual QList< QgsAnnotationItemNode > nodesV2(const QgsAnnotationItemEditContext &context) const
Returns the nodes for the item, used for editing the item.
virtual Qgis::AnnotationItemFlags flags() const
Returns item flags.
Represents a map layer containing a set of georeferenced annotations, e.g.
Qgis::AnnotationItemEditOperationResult applyEditV2(QgsAbstractAnnotationItemEditOperation *operation, const QgsAnnotationItemEditContext &context)
Applies an edit operation to the layer.
QString addItem(QgsAnnotationItem *item)
Adds an item to the layer.
QgsAnnotationItem * item(const QString &id) const
Returns the item with the specified id, or nullptr if no matching item was found.
Abstract base class for annotation items which render annotations in a rectangular shape.
QgsGeometry rotatedBoundsGeometry(const QgsRectangle &layerBounds, const QgsRenderContext &renderContext) const
Returns the polygon geometry (in layer coordinates) for the item occupying the given layerBounds,...
static QgsRectangle boundsFromPixelRect(const QgsMapToPixel *mapToPixel, const QPointF ¢erPixel, double widthPixels, double heightPixels)
Returns the axis-aligned bounds, in map coordinates, of a rectangle centered on centerPixel with size...
double appliedRotation(double mapRotation) const
Returns the effective on-screen rotation of the item, in degrees clockwise.
QgsRectangle bounds() const
Returns the bounds of the item.
Custom exception class for Coordinate Reference System related exceptions.
QPolygonF asQPolygonF() const
Returns contents of the geometry as a QPolygonF.
QPointF toCanvasCoordinates(const QgsPointXY &point) const
transformation from map coordinates to screen coordinates
QgsMapCanvas * mMapCanvas
pointer to map canvas
QgsMapCanvas * canvas() const
Returns the item's associated canvas.
Map canvas is a class for displaying all GIS data types on a canvas.
const QgsRenderedItemResults * renderedItemResults(bool allowOutdatedResults=true) const
Gets access to the rendered item results (may be nullptr), which includes the results of rendering an...
void rotationChanged(double rotation)
Emitted when the rotation of the map changes.
void mapCanvasRefreshed()
Emitted when canvas finished a refresh request.
A mouse event which is the result of a user interaction with a QgsMapCanvas.
QgsPointXY mapPoint() const
mapPoint returns the point in coordinates
Perform transforms between map coordinates and device coordinates.
QgsPointXY toMapCoordinates(int x, int y) const
Transforms device coordinates to map (world) coordinates.
Point geometry type, with support for z-dimension and m-values.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsAnnotationLayer * mainAnnotationLayer()
Returns the main annotation layer associated with the project.
void setDirty(bool b=true)
Flag the project as dirty (modified).
A rectangle specified with double values.
void grow(double delta)
Grows the rectangle in place by the specified amount.
Contains information about the context of a rendering operation.
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
QString itemId() const
Returns the item ID of the associated annotation item.
QString layerId() const
Returns the layer ID of the associated map layer.
QgsRectangle boundingBox() const
Returns the bounding box of the item (in map units).
Stores collated details of rendered items during a map rendering operation.
QList< const QgsRenderedAnnotationItemDetails * > renderedAnnotationItemsInBounds(const QgsRectangle &bounds) const
Returns a list with details of the rendered annotation items within the specified bounds.
QList< QgsRenderedItemDetails * > renderedItems() const
Returns a list of all rendered items.
QgsRubberBand(QgsMapCanvas *mapCanvas, Qgis::GeometryType geometryType=Qgis::GeometryType::Line)
Creates a new RubberBand.
void setWidth(double width)
Sets the width of the line.
void reset(Qgis::GeometryType geometryType=Qgis::GeometryType::Line)
Clears all the geometries in this rubberband.
void setSecondaryStrokeColor(const QColor &color)
Sets a secondary stroke color for the rubberband which will be drawn under the main stroke color.
void setColor(const QColor &color)
Sets the color for the rubberband.
void addPoint(const QgsPointXY &p, bool doUpdate=true, int geometryIndex=0, int ringIndex=0)
Adds a vertex to the rubberband and update canvas.
Represent a 2-dimensional vector.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
#define QgsDebugError(str)
constexpr QObjectUniquePtr< Tp > make_qobject_unique(Args &&...args)
Create an object owned by a QObjectUniquePtr.