QGIS API Documentation 4.3.0-Master (91d4a333d5d)
Loading...
Searching...
No Matches
qgsmaptoolselectannotation.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmaptoolselectannotation.cpp
3 ----------------
4 copyright : (C) 2025 by Mathieu Pellerin
5 email : mathieu at opengis dot ch
6 ***************************************************************************/
7
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
18
19#include <algorithm>
20#include <limits>
21
22#include "qgsannotationitem.h"
25#include "qgsannotationlayer.h"
27#include "qgsapplication.h"
29#include "qgsgeometry.h"
30#include "qgslogger.h"
31#include "qgsmapcanvas.h"
33#include "qgsmaptopixel.h"
34#include "qgsproject.h"
35#include "qgsrendercontext.h"
39#include "qgsrubberband.h"
40#include "qgssnapindicator.h"
41
42#include <QGraphicsSceneHoverEvent>
43#include <QKeySequence>
44#include <QScreen>
45#include <QString>
46#include <QTransform>
47#include <QWindow>
48
49#include "moc_qgsmaptoolselectannotation.cpp"
50
51using namespace Qt::StringLiterals;
52
54 : QgsRubberBand( canvas, Qgis::GeometryType::Line )
55 , mLayerId( layerId )
56 , mItemId( itemId )
57{
58 setFlags( flags() | QGraphicsItem::ItemIsSelectable );
59
60 setWidth( canvas->fontMetrics().xHeight() * .2 );
61 setSecondaryStrokeColor( QColor( 255, 255, 255, 100 ) );
62 setColor( QColor( 50, 50, 50, 200 ) );
63 setZValue( 10 );
64 setSelected( false );
65}
66
68{
69 QgsAnnotationLayer *lyr = qobject_cast<QgsAnnotationLayer *>( QgsProject::instance()->mapLayer( mLayerId ) );
70 if ( !lyr && mLayerId == QgsProject::instance()->mainAnnotationLayer()->id() )
71 {
73 }
74 return lyr;
75}
76
78{
80 return lyr ? lyr->item( mItemId ) : nullptr;
81}
82
84{
85 mBoundingBox = boundingBox;
86 QgsAnnotationItem *annotationItem = item();
87 mNeedsUpdatedBoundingBox = annotationItem && ( annotationItem->flags() & Qgis::AnnotationItemFlag::ScaleDependentBoundingBox );
88
90
91 const QgsMapToPixel *transform = mMapCanvas->getCoordinateTransform();
92
93 const QgsAnnotationRectItem *rectItem = dynamic_cast< const QgsAnnotationRectItem * >( annotationItem );
94 const double mapRotation = mMapCanvas->mapSettings().rotation();
95 const double frameRotation = rectItem ? rectItem->appliedRotation( mapRotation ) - mapRotation : 0;
96
97 if ( rectItem && !qgsDoubleNear( frameRotation, 0 ) )
98 {
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() );
108 };
109
110 // rotated item corners, as drawn on screen
111 if ( QgsAnnotationLayer *lyr = layer() )
112 {
113 const QgsCoordinateTransform layerToMap( lyr->crs(), mMapCanvas->mapSettings().destinationCrs(), mMapCanvas->mapSettings().transformContext() );
114 const QgsRenderContext renderContext = QgsRenderContext::fromMapSettings( mMapCanvas->mapSettings() );
115 const QPolygonF corners = rectItem->rotatedBoundsGeometry( rectItem->bounds(), renderContext ).asQPolygonF();
116 for ( const QPointF &corner : corners )
117 {
118 QgsPointXY mapPoint;
119 try
120 {
121 mapPoint = layerToMap.transform( QgsPointXY( corner.x(), corner.y() ) );
122 }
123 catch ( QgsCsException & )
124 {
125 // the band is still bounded by the item bounding box corners below
126 QgsDebugError( u"Error transforming annotation item corner"_s );
127 continue;
128 }
129 includePixel( toCanvasCoordinates( mapPoint ) );
130 }
131 }
132
133 // callout anchor and everything else reported by the incoming bounding box
134 const QgsPointXY bboxCorners[4] = {
135 QgsPointXY( boundingBox.xMinimum(), boundingBox.yMinimum() ),
136 QgsPointXY( boundingBox.xMaximum(), boundingBox.yMinimum() ),
137 QgsPointXY( boundingBox.xMaximum(), boundingBox.yMaximum() ),
138 QgsPointXY( boundingBox.xMinimum(), boundingBox.yMaximum() ),
139 };
140 for ( const QgsPointXY &corner : bboxCorners )
141 includePixel( toCanvasCoordinates( corner ) );
142
143 const QgsPointXY topLeft = transform->toMapCoordinates( minX, minY );
144 const QgsPointXY topRight = transform->toMapCoordinates( maxX, minY );
145 const QgsPointXY bottomRight = transform->toMapCoordinates( maxX, maxY );
146 const QgsPointXY bottomLeft = transform->toMapCoordinates( minX, maxY );
147 addPoint( topLeft );
148 addPoint( topRight );
149 addPoint( bottomRight );
150 addPoint( bottomLeft );
151 addPoint( topLeft );
152 }
153 else
154 {
155 // Build the rubber band as a screen-aligned rectangle matching the item's
156 // on-screen size.
157 const QPointF centerCanvas = toCanvasCoordinates( boundingBox.center() );
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;
161 const QgsPointXY topLeft = transform->toMapCoordinates( centerCanvas.x() - halfWidth, centerCanvas.y() - halfHeight );
162 const QgsPointXY topRight = transform->toMapCoordinates( centerCanvas.x() + halfWidth, centerCanvas.y() - halfHeight );
163 const QgsPointXY bottomRight = transform->toMapCoordinates( centerCanvas.x() + halfWidth, centerCanvas.y() + halfHeight );
164 const QgsPointXY bottomLeft = transform->toMapCoordinates( centerCanvas.x() - halfWidth, centerCanvas.y() + halfHeight );
165 addPoint( topLeft );
166 addPoint( topRight );
167 addPoint( bottomRight );
168 addPoint( bottomLeft );
169 addPoint( topLeft );
170 }
171
172 show();
173 setSelected( true );
174}
175
180
181
184{
185 connect( QgsMapToolSelectAnnotation::canvas(), &QgsMapCanvas::mapCanvasRefreshed, this, &QgsMapToolSelectAnnotation::onCanvasRefreshed );
186
188 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
189 selectedItem->updateBoundingBox( selectedItem->boundingBox() );
190 } );
191
193}
194
196{
197 mSelectionRubberBand.reset();
198 mMouseHandles.reset();
199}
200
207
209{
210 mSelectionRubberBand.reset();
211 mMouseHandles.reset();
212
213 mSelectedItems.clear();
214
215 mCopiedItems.clear();
216 mCopiedItemsTopLeft = QPointF();
217
219}
220
222{
223 const QPointF scenePos = mCanvas->mapToScene( event->pos() );
224
225 if ( event->buttons() == Qt::NoButton )
226 {
227 if ( mMouseHandles->isDragging() )
228 {
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 );
235 }
236 else
237 {
238 if ( mMouseHandles->sceneBoundingRect().contains( scenePos ) )
239 {
240 QGraphicsSceneHoverEvent forwardedEvent( QEvent::GraphicsSceneHoverMove );
241 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
242 forwardedEvent.setScenePos( scenePos );
243 mMouseHandles->hoverMoveEvent( &forwardedEvent );
244 mHoveringMouseHandles = true;
245 }
246 else if ( mHoveringMouseHandles )
247 {
248 QGraphicsSceneHoverEvent forwardedEvent( QEvent::GraphicsSceneHoverLeave );
249 forwardedEvent.setPos( mMouseHandles->mapFromScene( scenePos ) );
250 forwardedEvent.setScenePos( scenePos );
251 mMouseHandles->hoverMoveEvent( &forwardedEvent );
252 mHoveringMouseHandles = false;
253 }
254 }
255 }
256 else if ( event->buttons() == Qt::LeftButton )
257 {
258 if ( mMouseHandles->shouldBlockEvent( event ) )
259 {
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 );
266 }
267 else
268 {
269 if ( mCanceled )
270 {
271 mDragging = false;
272 return;
273 }
274
275 if ( !mDragging )
276 {
277 mDragging = true;
279 QColor color( Qt::blue );
280 color.setAlpha( 63 );
281 mSelectionRubberBand->setColor( color );
282 mSelectionRect.setTopLeft( event->pos() );
283 }
284
285 mSelectionRect.setBottomRight( event->pos() );
286 if ( mSelectionRubberBand )
287 {
288 mSelectionRubberBand->setToCanvasRectangle( mSelectionRect );
289 mSelectionRubberBand->show();
290 }
291 }
292 }
293
294 mLastScenePos = scenePos;
295}
296
298{
299 if ( event->button() != Qt::LeftButton )
300 {
301 return;
302 }
303
304 QPointF scenePos = mCanvas->mapToScene( event->pos() );
305 const bool toggleSelection = event->modifiers() & Qt::ShiftModifier;
306
307 if ( !toggleSelection && !mSelectedItems.empty() && mMouseHandles->sceneBoundingRect().contains( scenePos ) )
308 {
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 );
315 }
316 else
317 {
318 mSelectionRect.setTopLeft( event->pos() );
319 mSelectionRect.setBottomRight( event->pos() );
320 }
321
322 mLastScenePos = scenePos;
323 mCanceled = false;
324}
325
327{
328 if ( event->button() == Qt::RightButton )
329 {
330 mMouseHandles->reset();
331 mSelectionRubberBand.reset();
332 mCanceled = true;
333 return;
334 }
335
336 if ( event->button() != Qt::LeftButton )
337 {
338 return;
339 }
340
341 QPointF scenePos = mCanvas->mapToScene( event->pos() );
342
343 if ( mMouseHandles->shouldBlockEvent( event ) )
344 {
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 );
351 }
352 else
353 {
354 if ( mCanceled )
355 {
356 mCanceled = false;
357 mDragging = false;
358 return;
359 }
360
361 if ( mDragging )
362 {
363 mDragging = false;
364 mSelectionRubberBand.reset();
365
366 const QgsPointXY topLeft = toMapCoordinates( mSelectionRect.topLeft() );
367 const QgsPointXY bottomRight = toMapCoordinates( mSelectionRect.bottomRight() );
368 const QgsRectangle searchRect( topLeft, bottomRight );
369
370 setSelectedItemsFromRect( searchRect, ( event->modifiers() & Qt::ShiftModifier ) );
371 }
372 else
373 {
374 setSelectedItemFromPoint( event->mapPoint(), ( event->modifiers() & Qt::ShiftModifier ) );
375 }
376
377 mMouseHandles->setSelected( !mSelectedItems.empty() );
378 }
379}
380
382{
383 if ( mMouseHandles->isDragging() || mMouseHandles->isResizing() || mMouseHandles->isRotating() )
384 {
385 if ( event->key() == Qt::Key_Escape )
386 {
387 mMouseHandles->reset();
388 mSelectionRubberBand.reset();
389 mCanceled = true;
390 }
391 return;
392 }
393
394 if ( mSelectedItems.empty() )
395 {
396 return;
397 }
398
399 if ( event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete )
400 {
401 while ( !mSelectedItems.empty() )
402 {
403 if ( QgsAnnotationLayer *annotationLayer = mSelectedItems.back()->layer() )
404 {
405 annotationLayer->removeItem( mSelectedItems.back()->itemId() );
406 }
407 mSelectedItems.pop_back();
408 }
410 updateSelectedItem();
411 event->ignore();
412 }
413 else if ( event->key() == Qt::Key_Left || event->key() == Qt::Key_Right || event->key() == Qt::Key_Up || event->key() == Qt::Key_Down )
414 {
415 const int pixels = ( event->modifiers() & Qt::ShiftModifier ) ? 1 : 50;
416 int deltaX = 0;
417 int deltaY = 0;
418 if ( event->key() == Qt::Key_Up )
419 {
420 deltaY = -pixels;
421 }
422 else if ( event->key() == Qt::Key_Down )
423 {
424 deltaY = pixels;
425 }
426 else if ( event->key() == Qt::Key_Left )
427 {
428 deltaX = -pixels;
429 }
430 else if ( event->key() == Qt::Key_Right )
431 {
432 deltaX = pixels;
433 }
434
435 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
436 {
437 attemptMoveBy( selectedItem.get(), deltaX, deltaY );
438 }
439 event->ignore();
440 }
441}
442
444{
445 if ( mMouseHandles->isDragging() || mMouseHandles->isResizing() || mMouseHandles->isRotating() )
446 {
447 return true;
448 }
449 // NOLINTBEGIN(bugprone-narrowing-conversions)
450 QKeySequence keySequence( event->key() | event->modifiers() );
451 // NOLINTEND(bugprone-narrowing-conversions)
452 if ( keySequence == QKeySequence::Copy || keySequence == QKeySequence::Cut )
453 {
454 mCopiedItems.clear();
455 mCopiedItemsTopLeft = toMapCoordinates( QPoint( mMouseHandles->sceneBoundingRect().topLeft().x(), mMouseHandles->sceneBoundingRect().topLeft().y() ) );
456 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
457 {
458 if ( QgsAnnotationItem *annotationItem = selectedItem->item() )
459 {
460 std::unique_ptr<QgsAnnotationItem> copiedItem;
461 copiedItem.reset( annotationItem->clone() );
462 mCopiedItems.push_back( std::move( copiedItem ) );
463 }
464 }
465
466 if ( keySequence == QKeySequence::Cut )
467 {
468 while ( !mSelectedItems.empty() )
469 {
470 if ( QgsAnnotationLayer *annotationLayer = mSelectedItems.back()->layer() )
471 {
472 annotationLayer->removeItem( mSelectedItems.back()->itemId() );
473 }
474 mSelectedItems.pop_back();
475 }
477 }
478
479 return true;
480 }
481 else if ( keySequence == QKeySequence::Paste )
482 {
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() )
487 {
488 mSelectedItems.clear();
489 }
490
491 for ( std::unique_ptr<QgsAnnotationItem> &copiedItem : mCopiedItems )
492 {
493 QgsAnnotationLayer *annotationLayer = dynamic_cast<QgsAnnotationLayer *>( layer() );
494 if ( !annotationLayer )
495 {
496 annotationLayer = QgsProject::instance()->mainAnnotationLayer();
497 }
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 );
502 }
504
505 return true;
506 }
507
508 return false;
509}
510
511QList<QgsAnnotationItemRubberBand *> QgsMapToolSelectAnnotation::selectedItems() const
512{
513 QList<QgsAnnotationItemRubberBand *> items;
514 for ( const std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
515 {
516 if ( !selectedItem.get()->boundingBox().isEmpty() )
517 {
518 items << selectedItem.get();
519 }
520 }
521 return items;
522}
523
524void QgsMapToolSelectAnnotation::onCanvasRefreshed()
525{
526 const QgsRenderedItemResults *renderedItemResults = canvas()->renderedItemResults( false );
527 if ( !renderedItemResults )
528 {
529 return;
530 }
531
532 const bool interactiveOperation = mMouseHandles && ( mMouseHandles->isDragging() || mMouseHandles->isResizing() || mMouseHandles->isRotating() );
533
534 const QList<QgsRenderedItemDetails *> items = renderedItemResults->renderedItems();
535 bool needsSelectedItemsUpdate = false;
536 for ( std::unique_ptr<QgsAnnotationItemRubberBand> &selectedItem : mSelectedItems )
537 {
538 if ( interactiveOperation && !selectedItem->needsUpdatedBoundingBox() )
539 continue;
540
541 auto it = std::find_if( items.begin(), items.end(), [&selectedItem]( const QgsRenderedItemDetails *item ) {
542 if ( const QgsRenderedAnnotationItemDetails *annotationItem = dynamic_cast<const QgsRenderedAnnotationItemDetails *>( item ) )
543 {
544 if ( annotationItem->itemId() == selectedItem->itemId() && annotationItem->layerId() == selectedItem->layerId() )
545 {
546 return true;
547 }
548 }
549 return false;
550 } );
551
552 if ( it != items.end() )
553 {
554 needsSelectedItemsUpdate = true;
555 selectedItem->updateBoundingBox( ( *it )->boundingBox() );
556 }
557 }
558
559 if ( needsSelectedItemsUpdate )
560 {
561 emit selectedItemsChanged();
562 }
563}
564
565long long QgsMapToolSelectAnnotation::annotationItemRubberBandIndexFromId( const QString &layerId, const QString &itemId )
566{
567 if ( mSelectedItems.empty() )
568 {
569 return -1;
570 }
571
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;
574}
575
576void QgsMapToolSelectAnnotation::setSelectedItemsFromRect( const QgsRectangle &mapRect, bool toggleSelection )
577{
578 const QgsRenderedItemResults *renderedItemResults = canvas()->renderedItemResults( false );
579 if ( !renderedItemResults )
580 {
581 if ( !toggleSelection )
582 {
583 clearSelectedItems();
584 }
585 return;
586 }
587
588 const QList<const QgsRenderedAnnotationItemDetails *> items = renderedItemResults->renderedAnnotationItemsInBounds( mapRect );
589 if ( items.empty() )
590 {
591 if ( !toggleSelection )
592 {
593 clearSelectedItems();
594 }
595 return;
596 }
597
598 if ( !toggleSelection )
599 {
600 mSelectedItems.clear();
601 }
602 for ( const QgsRenderedAnnotationItemDetails *item : items )
603 {
604 QgsAnnotationItem *annotationItem = annotationItemFromId( item->layerId(), item->itemId() );
605 if ( annotationItem )
606 {
607 if ( toggleSelection )
608 {
609 long long index = annotationItemRubberBandIndexFromId( item->layerId(), item->itemId() );
610 if ( index >= 0 )
611 {
612 mSelectedItems.erase( mSelectedItems.begin() + index );
613 continue;
614 }
615 }
616 mSelectedItems.push_back( std::make_unique<QgsAnnotationItemRubberBand>( item->layerId(), item->itemId(), mCanvas ) );
617 mSelectedItems.back()->updateBoundingBox( item->boundingBox() );
618 }
619 }
621 updateSelectedItem();
622}
623
624void QgsMapToolSelectAnnotation::setSelectedItemFromPoint( const QgsPointXY &mapPoint, bool toggleSelection )
625{
626 QgsRectangle searchRect = QgsRectangle( mapPoint.x(), mapPoint.y(), mapPoint.x(), mapPoint.y() );
627 searchRect.grow( searchRadiusMU( canvas() ) );
628
629 const QgsRenderedItemResults *renderedItemResults = canvas()->renderedItemResults( false );
630 if ( !renderedItemResults )
631 {
632 clearSelectedItems();
633 return;
634 }
635
636 const QList<const QgsRenderedAnnotationItemDetails *> items = renderedItemResults->renderedAnnotationItemsInBounds( searchRect );
637 if ( items.empty() )
638 {
639 if ( !toggleSelection )
640 {
641 clearSelectedItems();
642 }
643 return;
644 }
645
646 QgsRectangle itemBounds;
647 const QgsRenderedAnnotationItemDetails *closestItem = findClosestItemToPoint( mapPoint, items, itemBounds );
648 if ( !closestItem )
649 {
650 if ( !toggleSelection )
651 {
652 clearSelectedItems();
653 }
654 return;
655 }
656
657 long long index = annotationItemRubberBandIndexFromId( closestItem->layerId(), closestItem->itemId() );
658 if ( index >= 0 )
659 {
660 if ( toggleSelection )
661 {
662 mSelectedItems.erase( mSelectedItems.begin() + index );
663 }
664 }
665 else
666 {
667 if ( !toggleSelection )
668 {
669 mSelectedItems.clear();
670 }
671
672 mSelectedItems.push_back( std::make_unique<QgsAnnotationItemRubberBand>( closestItem->layerId(), closestItem->itemId(), mCanvas ) );
673 mSelectedItems.back()->updateBoundingBox( closestItem->boundingBox() );
674 }
676 updateSelectedItem();
677}
678
679void QgsMapToolSelectAnnotation::updateSelectedItem()
680{
681 if ( mSelectedItems.size() > 1 )
682 {
684 }
685 else if ( mSelectedItems.size() == 1 )
686 {
687 emit singleItemSelected( mSelectedItems[0]->layer(), mSelectedItems[0]->itemId() );
688 }
689 else
690 {
691 emit selectionCleared();
692 }
693}
694
695void QgsMapToolSelectAnnotation::clearSelectedItems()
696{
697 const bool hadSelection = !mSelectedItems.empty();
698 mSelectedItems.clear();
699
700 if ( hadSelection )
701 {
703 updateSelectedItem();
704 }
705}
706
707void QgsMapToolSelectAnnotation::attemptMoveBy( QgsAnnotationItemRubberBand *annotationItemRubberBand, double deltaX, double deltaY )
708{
709 if ( QgsAnnotationItem *annotationItem = annotationItemRubberBand->item() )
710 {
711 QgsRectangle boundingBox = annotationItemRubberBand->boundingBox();
712 // take map rotation into account in translation
713 const QgsMapToPixel *transform = mCanvas->getCoordinateTransform();
714 const QgsPointXY mapOrigin = transform->toMapCoordinates( 0.0, 0.0 );
715 const QgsPointXY mapMoved = transform->toMapCoordinates( deltaX, deltaY );
716 const QgsVector translation( mapMoved.x() - mapOrigin.x(), mapMoved.y() - mapOrigin.y() );
717 QgsAnnotationLayer *annotationLayer = annotationItemRubberBand->layer();
718
720 context.setCurrentItemBounds( boundingBox );
722
723 const QList<QgsAnnotationItemNode> itemNodes = annotationItem->nodesV2( context );
724 for ( const QgsAnnotationItemNode &node : itemNodes )
725 {
726 QgsPointXY mapPoint = mCanvas->mapSettings().layerToMapCoordinates( annotationLayer, node.point() );
727 mapPoint += translation;
728 QgsPointXY modifiedPoint = mCanvas->mapSettings().mapToLayerCoordinates( annotationLayer, mapPoint );
729
730 QgsAnnotationItemEditOperationMoveNode operation( annotationItemRubberBand->itemId(), node.id(), QgsPoint( node.point() ), QgsPoint( modifiedPoint ) );
731 switch ( annotationLayer->applyEditV2( &operation, context ) )
732 {
735 annotationItemRubberBand->setNeedsUpdatedBoundingBox( true );
736 break;
737
740 break;
741 }
742 }
743 boundingBox += translation;
744 annotationItemRubberBand->updateBoundingBox( boundingBox );
745 }
746}
747
748void QgsMapToolSelectAnnotation::attemptRotateBy( QgsAnnotationItemRubberBand *annotationItemRubberBand, double deltaDegree )
749{
750 if ( QgsAnnotationLayer *annotationLayer = annotationItemRubberBand->layer() )
751 {
752 const QgsRectangle boundingBox = mCanvas->mapSettings().mapToLayerCoordinates( annotationLayer, annotationItemRubberBand->boundingBox() );
754 context.setCurrentItemBounds( boundingBox );
756
757 QgsAnnotationItemEditOperationRotateItem operation( annotationItemRubberBand->itemId(), deltaDegree );
758 switch ( annotationLayer->applyEditV2( &operation, context ) )
759 {
762 annotationItemRubberBand->setNeedsUpdatedBoundingBox( true );
763 break;
764
767 break;
768 }
769 }
770}
771
772void QgsMapToolSelectAnnotation::attemptSetSceneRect( QgsAnnotationItemRubberBand *annotationItemRubberBand, const QRectF &rect )
773{
774 QgsAnnotationItem *annotationItem = annotationItemRubberBand->item();
775 if ( !annotationItem )
776 return;
777
778 QgsAnnotationLayer *annotationLayer = annotationItemRubberBand->layer();
779
780 // on-screen rotation = the item's own rotation plus the map rotation when
781 // the item follows it.
782 double rotation = 0;
783 if ( const QgsAnnotationRectItem *rectItem = dynamic_cast<const QgsAnnotationRectItem *>( annotationItem ) )
784 {
785 rotation = rectItem->appliedRotation( mCanvas->mapSettings().rotation() );
786 }
787
788 // Rebuild the unrotated (screen-aligned) rectangle so that, after rotating
789 // around its center, the dragged corner stays where the user placed it.
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 ) );
797
798 // Derive the bounds from the center and pixel size, which stays correct
799 // when the map is rotated.
800 const QgsMapToPixel *transform = mCanvas->getCoordinateTransform();
801 const QgsRectangle newMapBounds = QgsAnnotationRectItem::boundsFromPixelRect( transform, newSceneRect.center(), w, h );
802
803 const QgsRectangle oldBounds = mCanvas->mapSettings().mapToLayerCoordinates( annotationLayer, annotationItemRubberBand->boundingBox() );
804 const QgsRectangle newBounds = mCanvas->mapSettings().mapToLayerCoordinates( annotationLayer, newMapBounds );
805
806 if ( oldBounds.width() == 0 || oldBounds.height() == 0 )
807 return;
808
810 context.setCurrentItemBounds( oldBounds );
812
813 const QList<QgsAnnotationItemNode> itemNodes = annotationItem->nodesV2( context );
814 for ( const QgsAnnotationItemNode &node : itemNodes )
815 {
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 );
819 QgsAnnotationItemEditOperationMoveNode operation( annotationItemRubberBand->itemId(), node.id(), QgsPoint( node.point() ), QgsPoint( modifiedPoint ) );
820 switch ( annotationLayer->applyEditV2( &operation, context ) )
821 {
824 annotationItemRubberBand->setNeedsUpdatedBoundingBox( true );
825 break;
826
829 break;
830 }
831 }
832
833 annotationItemRubberBand->updateBoundingBox( newMapBounds );
834}
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:62
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
Definition qgis.h:2672
@ Invalid
Operation has invalid parameters for the item, no change occurred.
Definition qgis.h:2728
@ Success
Item was modified successfully.
Definition qgis.h:2727
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
Definition qgis.h:2729
@ Line
Lines.
Definition qgis.h:401
@ Polygon
Polygons.
Definition qgis.h:402
A dockable widget used to handle the CAD tools on top of a selection of map tools.
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.
QgsAnnotationMapTool(QgsMapCanvas *canvas, QgsAdvancedDigitizingDockWidget *cadDockWidget)
Constructor for QgsAnnotationMapTool.
const QgsRenderedAnnotationItemDetails * findClosestItemToPoint(const QgsPointXY &mapPoint, const QList< const QgsRenderedAnnotationItemDetails * > &items, QgsRectangle &bounds)
Returns the closest item from a list of annotation items to a given map point.
QgsAnnotationItem * annotationItemFromId(const QString &layerId, const QString &itemId)
Returns the annotation item matching a given pair of layer and item IDs.
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 &centerPixel, 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.
Handles coordinate transforms between two coordinate systems.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
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.
QString id
Definition qgsmaplayer.h:87
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.
void deactivate() override
Unregisters this maptool from the cad dock widget.
virtual QgsMapLayer * layer() const
Returns the layer associated with the map tool.
QgsAdvancedDigitizingDockWidget * cadDockWidget() const
void setAdvancedDigitizingAllowed(bool allowed)
Sets whether functionality of advanced digitizing dock widget is currently allowed.
void activate() override
Registers this maptool with the cad dock widget.
QList< QgsAnnotationItemRubberBand * > selectedItems() const
Returns the current list of selected annotation item rubberband items.
void cadCanvasReleaseEvent(QgsMapMouseEvent *event) override
Override this method when subclassing this class.
void singleItemSelected(QgsAnnotationLayer *layer, const QString &itemId)
Emitted when the selected items list has changed and a single item is selected.
void attemptRotateBy(QgsAnnotationItemRubberBand *annotationItemRubberBand, double deltaDegree)
Attempts to rotate am annotation item.
void keyPressEvent(QKeyEvent *event) override
Key event for overriding. Default implementation does nothing.
void activate() override
Registers this maptool with the cad dock widget.
void attemptSetSceneRect(QgsAnnotationItemRubberBand *annotationItemRubberBand, const QRectF &rect)
Attempts to move and resize an annotation item.
QgsMapToolSelectAnnotation(QgsMapCanvas *canvas, QgsAdvancedDigitizingDockWidget *cadDockWidget)
Constructor for QgsMapToolSelectAnnotation.
void multipleItemsSelected()
Emitted when the selected items list has changed and multiple items are selected.
void cadCanvasMoveEvent(QgsMapMouseEvent *event) override
Override this method when subclassing this class.
void attemptMoveBy(QgsAnnotationItemRubberBand *annotationItemRubberBand, double deltaX, double deltaY)
Attempts to move an annotation item.
void cadCanvasPressEvent(QgsMapMouseEvent *event) override
Override this method when subclassing this class.
void selectedItemsChanged()
Emitted when the selected items list has changed.
void selectionCleared()
Emitted when the selected items list is cleared.
void deactivate() override
Unregisters this maptool from the cad dock widget.
bool shortcutEvent(QKeyEvent *event) override
Shortcut events coming from the application for overriding.
QgsMapCanvas * canvas() const
returns pointer to the tool's map canvas
QgsPointXY toMapCoordinates(QPoint point)
Transforms a point from screen coordinates to map coordinates.
QPointer< QgsMapCanvas > mCanvas
The pointer to the map canvas.
Definition qgsmaptool.h:403
static double searchRadiusMU(const QgsRenderContext &context)
Gets search radius in map units for given context.
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
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.
double xMinimum
void grow(double delta)
Grows the rectangle in place by the specified amount.
double yMaximum
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.
Definition qgsvector.h:34
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
#define QgsDebugError(str)
Definition qgslogger.h:71
constexpr QObjectUniquePtr< Tp > make_qobject_unique(Args &&...args)
Create an object owned by a QObjectUniquePtr.