-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
qgsvertextool.cpp
3175 lines (2747 loc) · 105 KB
/
qgsvertextool.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgsvertextool.cpp
--------------------------------------
Date : February 2017
Copyright : (C) 2017 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsmessagelog.h"
#include "qgsvertextool.h"
#include "qgsavoidintersectionsoperation.h"
#include "qgsadvanceddigitizingdockwidget.h"
#include "qgscurve.h"
#include "qgslinestring.h"
#include "qgsgeometryutils.h"
#include "qgsgeometryvalidator.h"
#include "qgsguiutils.h"
#include "qgslogger.h"
#include "qgsmapcanvas.h"
#include "qgsmulticurve.h"
#include "qgsmultipoint.h"
#include "qgspointlocator.h"
#include "qgsproject.h"
#include "qgsrubberband.h"
#include "qgssettingsregistrycore.h"
#include "qgssnapindicator.h"
#include "qgssnappingutils.h"
#include "qgsvectorlayer.h"
#include "qgsvertexmarker.h"
#include "qgsstatusbar.h"
#include "qgisapp.h"
#include "qgslockedfeature.h"
#include "qgsvertexeditor.h"
#include "qgsmapmouseevent.h"
#include "qgsexpressioncontextutils.h"
#include "qgsmessagebar.h"
#include "qgssettingsentryimpl.h"
#include <QMenu>
#include <QRubberBand>
#include <QTimer>
uint qHash( const Vertex &v )
{
return qHash( v.layer ) ^ qHash( v.fid ) ^ qHash( v.vertexId );
}
//
// geomutils - may get moved elsewhere
//
//! Find out whether vertex at the given index is an endpoint (assuming linear geometry)
static bool isEndpointAtVertexIndex( const QgsGeometry &geom, int vertexIndex )
{
const QgsAbstractGeometry *g = geom.constGet();
if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve *>( g ) )
{
return vertexIndex == 0 || vertexIndex == curve->numPoints() - 1;
}
else if ( const QgsMultiCurve *multiCurve = qgsgeometry_cast<const QgsMultiCurve *>( g ) )
{
for ( int i = 0; i < multiCurve->numGeometries(); ++i )
{
const QgsCurve *part = multiCurve->curveN( i );
Q_ASSERT( part );
if ( vertexIndex < part->numPoints() )
return vertexIndex == 0 || vertexIndex == part->numPoints() - 1;
vertexIndex -= part->numPoints();
}
Q_ASSERT( false ); // should not get here
return false;
}
else
{
QgsDebugError( QStringLiteral( "is_endpoint_at_vertex_index: unexpected geometry type!" ) );
return false;
}
}
//! Returns the index of vertex adjacent to the given endpoint. Assuming linear geometries.
int adjacentVertexIndexToEndpoint( const QgsGeometry &geom, int vertexIndex )
{
const QgsAbstractGeometry *g = geom.constGet();
if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
{
return vertexIndex == 0 ? 1 : curve->numPoints() - 2;
}
else if ( const QgsMultiCurve *multiCurve = qgsgeometry_cast<const QgsMultiCurve *>( g ) )
{
int offset = 0;
for ( int i = 0; i < multiCurve->numGeometries(); ++i )
{
const QgsCurve *part = multiCurve->curveN( i );
Q_ASSERT( part );
if ( vertexIndex < part->numPoints() )
return vertexIndex == 0 ? offset + 1 : offset + part->numPoints() - 2;
vertexIndex -= part->numPoints();
offset += part->numPoints();
}
}
else
{
QgsDebugError( QStringLiteral( "adjacent_vertex_index_to_endpoint: unexpected geometry type!" ) );
}
return -1;
}
/**
* Determine whether a vertex is in the middle of a circular edge or not
* (wrapper for slightly awkward API)
*/
static bool isCircularVertex( const QgsGeometry &geom, int vertexIndex )
{
QgsVertexId vid;
return geom.vertexIdFromVertexNr( vertexIndex, vid ) && vid.type == Qgis::VertexType::Curve;
}
//! Create a multi-point geometry that can be used to highlight vertices of a feature
static QgsGeometry geometryToMultiPoint( const QgsGeometry &geom )
{
QgsMultiPoint *multiPoint = new QgsMultiPoint();
QgsGeometry outputGeom( multiPoint );
for ( auto pointIt = geom.vertices_begin(); pointIt != geom.vertices_end(); ++pointIt )
multiPoint->addGeometry( ( *pointIt ).clone() );
return outputGeom;
}
//
// snapping match filters
//
//! a filter to allow just one particular feature
class OneFeatureFilter : public QgsPointLocator::MatchFilter
{
public:
OneFeatureFilter( const QgsVectorLayer *layer, QgsFeatureId fid )
: layer( layer )
, fid( fid )
{}
bool acceptMatch( const QgsPointLocator::Match &match ) override
{
return match.layer() == layer && match.featureId() == fid;
}
private:
const QgsVectorLayer *layer = nullptr;
QgsFeatureId fid;
};
//! a filter just to gather all matches at the same place
class MatchCollectingFilter : public QgsPointLocator::MatchFilter
{
public:
QList<QgsPointLocator::Match> matches;
QgsVertexTool *vertextool = nullptr;
MatchCollectingFilter( QgsVertexTool *vertextool )
: vertextool( vertextool ) {}
bool acceptMatch( const QgsPointLocator::Match &match ) override
{
if ( match.distance() > 0 )
return false;
// there may be multiple points at the same location, but we get only one
// result... the locator API needs a new method verticesInRect()
QgsGeometry matchGeom = vertextool->cachedGeometry( match.layer(), match.featureId() );
bool isPolygon = matchGeom.type() == Qgis::GeometryType::Polygon;
QgsVertexId polygonRingVid;
QgsVertexId vid;
QgsPoint pt;
while ( matchGeom.constGet()->nextVertex( vid, pt ) )
{
int vindex = matchGeom.vertexNrFromVertexId( vid );
if ( pt.x() == match.point().x() && pt.y() == match.point().y() )
{
if ( isPolygon )
{
// for polygons we need to handle the case where the first vertex is matching because the
// last point will have the same coordinates and we would have a duplicate match which
// would make subsequent code behave incorrectly (topology editing mode would add a single
// vertex twice)
if ( vid.vertex == 0 )
{
polygonRingVid = vid;
}
else if ( vid.ringEqual( polygonRingVid ) && vid.vertex == matchGeom.constGet()->vertexCount( vid.part, vid.ring ) - 1 )
{
continue;
}
}
QgsPointLocator::Match extra_match( match.type(), match.layer(), match.featureId(),
0, match.point(), vindex );
matches.append( extra_match );
}
}
return true;
}
};
/**
* Keeps the best match from a selected feature so that we can possibly use it with higher priority.
* If we do not encounter any selected feature within tolerance, we use the best match as usual.
*
* There are two kinds of "selected" features... if we have a "locked" feature in vertex tool,
* we get a non-null QgsLockedFeature which has feature's layer and feature id. In such case we
* only allow matches from that feature. The other kind is if some features within layer are
* in the layer's list of selected features - in that case we accept any match from those features
* (but only if we do not have "locked" feature)
*/
class SelectedMatchFilter : public QgsPointLocator::MatchFilter
{
public:
explicit SelectedMatchFilter( double tol, QgsLockedFeature *selectedFeature )
: mTolerance( tol )
, mLockedFeature( selectedFeature ) {}
bool acceptMatch( const QgsPointLocator::Match &match ) override
{
if ( match.distance() <= mTolerance && match.layer() )
{
// option 1: we have "locked" feature - we consider just a match from that feature
// option 2: we do not have "locked" feature - we consider matches from any selected feature
if ( ( mLockedFeature && mLockedFeature->layer() == match.layer() && mLockedFeature->featureId() == match.featureId() )
|| ( !mLockedFeature && match.layer()->selectedFeatureIds().contains( match.featureId() ) ) )
{
if ( !mBestSelectedMatch.isValid() || match.distance() < mBestSelectedMatch.distance() )
mBestSelectedMatch = match;
}
}
return true;
}
bool hasSelectedMatch() const { return mBestSelectedMatch.isValid(); }
QgsPointLocator::Match bestSelectedMatch() const { return mBestSelectedMatch; }
private:
double mTolerance;
QgsLockedFeature *mLockedFeature; // not null in case of selected (locked) feature
QgsPointLocator::Match mBestSelectedMatch;
};
//
//
//
QgsVertexTool::QgsVertexTool( QgsMapCanvas *canvas, QgsAdvancedDigitizingDockWidget *cadDock, VertexToolMode mode )
: QgsMapToolAdvancedDigitizing( canvas, cadDock )
, mMode( mode )
{
setAdvancedDigitizingAllowed( false );
mSnapIndicator.reset( new QgsSnapIndicator( canvas ) );
mEdgeCenterMarker = new QgsVertexMarker( canvas );
mEdgeCenterMarker->setIconType( QgsVertexMarker::ICON_CROSS );
mEdgeCenterMarker->setColor( Qt::red );
mEdgeCenterMarker->setIconSize( QgsGuiUtils::scaleIconSize( 10 ) );
mEdgeCenterMarker->setPenWidth( QgsGuiUtils::scaleIconSize( 3 ) );
mEdgeCenterMarker->setVisible( false );
mFeatureBand = createRubberBand( Qgis::GeometryType::Line );
mFeatureBand->setVisible( false );
QColor color = digitizingStrokeColor();
mFeatureBandMarkers = new QgsRubberBand( canvas );
mFeatureBandMarkers->setIcon( QgsRubberBand::ICON_CIRCLE );
mFeatureBandMarkers->setColor( color );
mFeatureBandMarkers->setWidth( QgsGuiUtils::scaleIconSize( 2 ) );
mFeatureBandMarkers->setBrushStyle( Qt::NoBrush );
mFeatureBandMarkers->setIconSize( QgsGuiUtils::scaleIconSize( 6 ) );
mFeatureBandMarkers->setVisible( false );
mVertexBand = new QgsRubberBand( canvas );
mVertexBand->setIcon( QgsRubberBand::ICON_CIRCLE );
mVertexBand->setColor( color );
mVertexBand->setWidth( QgsGuiUtils::scaleIconSize( 2 ) );
mVertexBand->setBrushStyle( Qt::NoBrush );
mVertexBand->setIconSize( QgsGuiUtils::scaleIconSize( 15 ) );
mVertexBand->setVisible( false );
QColor color2( color );
color2.setAlpha( color2.alpha() / 3 );
mEdgeBand = new QgsRubberBand( canvas );
mEdgeBand->setColor( color2 );
mEdgeBand->setWidth( QgsGuiUtils::scaleIconSize( 10 ) );
mEdgeBand->setVisible( false );
mEndpointMarker = new QgsVertexMarker( canvas );
mEndpointMarker->setIconType( QgsVertexMarker::ICON_CROSS );
mEndpointMarker->setColor( Qt::red );
mEndpointMarker->setIconSize( QgsGuiUtils::scaleIconSize( 10 ) );
mEndpointMarker->setPenWidth( QgsGuiUtils::scaleIconSize( 3 ) );
mEndpointMarker->setVisible( false );
}
QgsVertexTool::~QgsVertexTool()
{
delete mEdgeCenterMarker;
delete mFeatureBand;
delete mFeatureBandMarkers;
delete mVertexBand;
delete mEdgeBand;
delete mEndpointMarker;
}
void QgsVertexTool::activate()
{
if ( QgisApp::instance() && QgsVertexEditor::settingAutoPopupVertexEditorDock->value() )
{
showVertexEditor(); //#spellok
}
if ( QgsVertexEditor *editor = vertexEditor() )
{
connect( editor, &QgsVertexEditor::deleteSelectedRequested, this, &QgsVertexTool::deleteVertexEditorSelection );
connect( editor, &QgsVertexEditor::editorClosed, this, &QgsVertexTool::cleanupVertexEditor );
}
connect( mCanvas, &QgsMapCanvas::currentLayerChanged, this, &QgsVertexTool::currentLayerChanged );
QgsMapToolAdvancedDigitizing::activate();
}
void QgsVertexTool::deactivate()
{
setHighlightedVertices( QList<Vertex>() );
removeTemporaryRubberBands();
cleanupVertexEditor();
if ( QgsVertexEditor *editor = vertexEditor() )
{
disconnect( editor, &QgsVertexEditor::deleteSelectedRequested, this, &QgsVertexTool::deleteVertexEditorSelection );
disconnect( editor, &QgsVertexEditor::editorClosed, this, &QgsVertexTool::cleanupVertexEditor );
}
mSnapIndicator->setMatch( QgsPointLocator::Match() );
QHash< QPair<QgsVectorLayer *, QgsFeatureId>, GeometryValidation>::iterator it = mValidations.begin();
for ( ; it != mValidations.end(); ++it )
it->cleanup();
mValidations.clear();
disconnect( mCanvas, &QgsMapCanvas::currentLayerChanged, this, &QgsVertexTool::currentLayerChanged );
QgsMapToolAdvancedDigitizing::deactivate();
}
void QgsVertexTool::currentLayerChanged( QgsMapLayer *layer )
{
if ( mMode == QgsVertexTool::ActiveLayer )
{
if ( mLockedFeature && mLockedFeature->layer() != layer )
{
cleanupLockedFeature();
}
}
}
void QgsVertexTool::addDragBand( const QgsPointXY &v1, const QgsPointXY &v2 )
{
addDragStraightBand( nullptr, v1, v2, false, true, v2 );
}
void QgsVertexTool::addDragStraightBand( QgsVectorLayer *layer, QgsPointXY v0, QgsPointXY v1, bool moving0, bool moving1, const QgsPointXY &mapPoint )
{
// if layer is not null, the input coordinates are coming in the layer's CRS rather than map CRS
if ( layer )
{
v0 = toMapCoordinates( layer, v0 );
v1 = toMapCoordinates( layer, v1 );
}
StraightBand b;
b.band = createRubberBand( Qgis::GeometryType::Line, true );
b.p0 = v0;
b.p1 = v1;
b.moving0 = moving0;
b.moving1 = moving1;
b.offset0 = v0 - mapPoint;
b.offset1 = v1 - mapPoint;
b.band->addPoint( v0 );
b.band->addPoint( v1 );
mDragStraightBands << b;
}
void QgsVertexTool::addDragCircularBand( QgsVectorLayer *layer, QgsPointXY v0, QgsPointXY v1, QgsPointXY v2, bool moving0, bool moving1, bool moving2, const QgsPointXY &mapPoint )
{
// if layer is not null, the input coordinates are coming in the layer's CRS rather than map CRS
if ( layer )
{
v0 = toMapCoordinates( layer, v0 );
v1 = toMapCoordinates( layer, v1 );
v2 = toMapCoordinates( layer, v2 );
}
CircularBand b;
b.band = createRubberBand( Qgis::GeometryType::Line, true );
b.p0 = v0;
b.p1 = v1;
b.p2 = v2;
b.moving0 = moving0;
b.moving1 = moving1;
b.moving2 = moving2;
b.offset0 = v0 - mapPoint;
b.offset1 = v1 - mapPoint;
b.offset2 = v2 - mapPoint;
b.updateRubberBand( mapPoint );
mDragCircularBands << b;
}
void QgsVertexTool::clearDragBands()
{
qDeleteAll( mDragPointMarkers );
mDragPointMarkers.clear();
mDragPointMarkersOffset.clear();
for ( const StraightBand &b : std::as_const( mDragStraightBands ) )
delete b.band;
mDragStraightBands.clear();
for ( const CircularBand &b : std::as_const( mDragCircularBands ) )
delete b.band;
mDragCircularBands.clear();
}
void QgsVertexTool::cadCanvasPressEvent( QgsMapMouseEvent *e )
{
if ( mSelectionMethod == SelectionRange )
{
rangeMethodPressEvent( e );
return;
}
if ( !mDraggingVertex && !mSelectedVertices.isEmpty() && !( e->modifiers() & Qt::ShiftModifier ) && !( e->modifiers() & Qt::ControlModifier ) )
{
// only remove highlight if not clicked on one of highlighted vertices
bool clickedOnHighlightedVertex = false;
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( m.hasVertex() )
{
for ( const Vertex &selectedVertex : std::as_const( mSelectedVertices ) )
{
if ( selectedVertex.layer == m.layer() && selectedVertex.fid == m.featureId() && selectedVertex.vertexId == m.vertexIndex() )
{
clickedOnHighlightedVertex = true;
break;
}
}
}
if ( !clickedOnHighlightedVertex && e->button() == Qt::LeftButton )
{
setHighlightedVertices( QList<Vertex>() ); // reset selection
updateLockedFeatureVertices();
}
}
if ( e->button() == Qt::LeftButton )
{
if ( e->modifiers() & Qt::ControlModifier || e->modifiers() & Qt::ShiftModifier )
{
// shift or ctrl-click vertices to highlight without entering edit mode
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( m.hasVertex() )
{
Vertex vertex( m.layer(), m.featureId(), m.vertexIndex() );
HighlightMode mode = ModeReset;
if ( e->modifiers() & Qt::ShiftModifier )
{
// Shift+Click to add vertex to highlight
mode = ModeAdd;
}
else if ( e->modifiers() & Qt::ControlModifier )
{
// Ctrl+Click to remove vertex
mode = ModeSubtract;
}
setHighlightedVertices( QList<Vertex>() << vertex, mode );
return;
}
}
// the user may have started dragging a rect to select vertices
if ( !mDraggingVertex && !mDraggingEdge )
mSelectionRubberBandStartPos.reset( new QPoint( e->pos() ) );
}
}
void QgsVertexTool::cadCanvasReleaseEvent( QgsMapMouseEvent *e )
{
if ( mSelectionMethod == SelectionRange )
{
rangeMethodReleaseEvent( e );
return;
}
if ( mNewVertexFromDoubleClick )
{
QgsPointLocator::Match m( *mNewVertexFromDoubleClick );
if ( mLockedFeature && ( mLockedFeature->featureId() != m.featureId() || mLockedFeature->layer() != m.layer() ) )
return; // when a feature is bound to the vector editor, only process actions on that feature
mNewVertexFromDoubleClick.reset();
// dragging of edges and double-clicking on edges to add vertex are slightly overlapping
// so we need to cancel edge moving before we start dragging new vertex
stopDragging();
startDraggingAddVertex( m );
if ( e->modifiers() & Qt::ShiftModifier )
{
// if this was shift + double-click, immediately place the vertex
moveVertex( m.point(), &m );
// force update of rubber bands
mouseMoveNotDragging( e );
}
}
else if ( mSelectionRubberBand &&
( mSelectionMethod == SelectionNormal ||
( mSelectionMethod == SelectionPolygon && e->button() == Qt::RightButton ) ) )
{
// only handling of selection rect being dragged
QList<Vertex> vertices;
QList<Vertex> selectedVertices;
bool showInvisibleFeatureWarning = false;
QgsGeometry rubberBandGeometry = mSelectionRubberBand->asGeometry();
// the logic for selecting vertices using rectangle:
// - if we have a bound (locked) feature, we only allow selection of its vertices
// - if we don't have a bound feature, we can select vertices from any feature,
// but if there are some vertices coming from layer(s) with selected feature,
// we give them precedence.
// for each editable layer, select vertices
const auto editableLayers = editableVectorLayers();
for ( QgsVectorLayer *vlayer : editableLayers )
{
if ( mMode == ActiveLayer && vlayer != currentVectorLayer() )
continue;
if ( mLockedFeature && mLockedFeature->layer() != vlayer )
continue; // with locked feature we only allow selection of its vertices
QgsGeometry layerRubberBandGeometry = rubberBandGeometry;
try
{
QgsCoordinateTransform ct = mCanvas->mapSettings().layerTransform( vlayer );
if ( ct.isValid() )
layerRubberBandGeometry.transform( ct, Qgis::TransformDirection::Reverse );
}
catch ( QgsCsException & )
{
continue;
}
QgsRenderContext context = QgsRenderContext::fromMapSettings( mCanvas->mapSettings() );
context.setExpressionContext( mCanvas->createExpressionContext() );
context.expressionContext() << QgsExpressionContextUtils::layerScope( vlayer );
std::unique_ptr< QgsFeatureRenderer > r;
if ( vlayer->renderer() )
{
r.reset( vlayer->renderer()->clone() );
r->startRender( context, vlayer->fields() );
}
QgsRectangle layerRect = layerRubberBandGeometry.boundingBox();
std::unique_ptr< QgsGeometryEngine > layerRubberBandEngine( QgsGeometry::createGeometryEngine( layerRubberBandGeometry.constGet() ) );
layerRubberBandEngine->prepareGeometry();
QgsFeatureRequest request;
request.setFilterRect( layerRect );
request.setFlags( Qgis::FeatureRequestFlag::ExactIntersect );
if ( r )
request.setSubsetOfAttributes( r->usedAttributes( context ), vlayer->fields() );
else
request.setNoAttributes();
request.setExpressionContext( context.expressionContext() );
QgsFeature f;
QgsFeatureIterator fi = vlayer->getFeatures( request );
while ( fi.nextFeature( f ) )
{
if ( mLockedFeature && mLockedFeature->featureId() != f.id() )
continue; // with locked feature we only allow selection of its vertices
context.expressionContext().setFeature( f );
bool isFeatureInvisible = ( r && !r->willRenderFeature( f, context ) );
// If we've already determined that we have to show users a warning about selecting invisible vertices,
// then we don't need to check through the vertices for other invisible features.
// We'll be showing the warning anyway regardless of the outcome!
if ( isFeatureInvisible && showInvisibleFeatureWarning )
continue;
bool isFeatureSelected = vlayer->selectedFeatureIds().contains( f.id() );
QgsGeometry g = f.geometry();
int i = 0;
for ( auto it = g.constGet()->vertices_begin(); it != g.constGet()->vertices_end(); ++it )
{
QgsPoint pt = *it;
if ( layerRubberBandEngine->contains( &pt ) )
{
// we don't want to select invisible features,
// but if the user tried to selected one we want to warn him
if ( isFeatureInvisible )
{
showInvisibleFeatureWarning = true;
break;
}
vertices << Vertex( vlayer, f.id(), i );
if ( isFeatureSelected )
selectedVertices << Vertex( vlayer, f.id(), i );
}
i++;
}
}
if ( r )
r->stopRender( context );
}
if ( showInvisibleFeatureWarning )
{
QgisApp::instance()->messageBar()->pushMessage(
tr( "Invisible vertices were not selected" ),
tr( "Vertices belonging to features that are not displayed on the map canvas were not selected." ),
Qgis::MessageLevel::Warning );
}
// here's where we give precedence to vertices of selected features in case there's no bound (locked) feature
if ( !mLockedFeature && !selectedVertices.isEmpty() )
{
vertices = selectedVertices;
}
HighlightMode mode = ModeReset;
if ( e->modifiers() & Qt::ShiftModifier )
mode = ModeAdd;
else if ( e->modifiers() & Qt::ControlModifier )
mode = ModeSubtract;
setHighlightedVertices( vertices, mode );
stopSelectionRubberBand();
}
else if ( e->button() == Qt::LeftButton && e->modifiers() & Qt::AltModifier )
{
mSelectionMethod = SelectionPolygon;
initSelectionRubberBand();
mSelectionRubberBand->addPoint( toMapCoordinates( e->pos() ) );
return;
}
else if ( mSelectionRubberBand && mSelectionMethod == SelectionPolygon )
{
mSelectionRubberBand->addPoint( toMapCoordinates( e->pos() ) );
return;
}
else // selection rect is not being dragged
{
if ( e->button() == Qt::LeftButton && !( e->modifiers() & Qt::ShiftModifier ) && !( e->modifiers() & Qt::ControlModifier ) )
{
// accepting action
if ( mDraggingVertex )
{
QgsPointLocator::Match match = e->mapPointMatch();
moveVertex( e->mapPoint(), &match );
}
else if ( mDraggingEdge )
{
// do not use e.mapPoint() as it may be snapped
moveEdge( toMapCoordinates( e->pos() ) );
}
else
{
startDragging( e );
}
}
else if ( e->button() == Qt::RightButton )
{
if ( mDraggingVertex || mDraggingEdge )
{
// cancel action
stopDragging();
}
else if ( !mSelectionRubberBand )
{
// Right-click to select/delect a feature for editing (also gets selected in vertex editor).
// If there are multiple features at one location, cycle through them with subsequent right clicks.
tryToSelectFeature( e );
}
}
}
mSelectionRubberBandStartPos.reset();
}
void QgsVertexTool::cadCanvasMoveEvent( QgsMapMouseEvent *e )
{
if ( mLockedFeatureAlternatives && ( e->pos() - mLockedFeatureAlternatives->screenPoint ).manhattanLength() >= QApplication::startDragDistance() )
{
// as soon as the mouse moves more than just a tiny bit, previously stored alternatives info
// is probably not valid anymore and will need to be re-calculated
mLockedFeatureAlternatives.reset();
}
if ( mSelectionMethod == SelectionRange )
{
rangeMethodMoveEvent( e );
return;
}
if ( mDraggingVertex )
{
mouseMoveDraggingVertex( e );
}
else if ( mDraggingEdge )
{
mouseMoveDraggingEdge( e );
}
else if ( mSelectionRubberBandStartPos )
{
// the user may be dragging a rect to select vertices
if ( !mSelectionRubberBand && ( e->pos() - *mSelectionRubberBandStartPos ).manhattanLength() >= 10 )
{
mSelectionMethod = SelectionNormal;
initSelectionRubberBand();
}
if ( mSelectionRubberBand )
{
updateSelectionRubberBand( e );
}
}
else
{
mouseMoveNotDragging( e );
}
}
void QgsVertexTool::mouseMoveDraggingVertex( QgsMapMouseEvent *e )
{
mSnapIndicator->setMatch( e->mapPointMatch() );
mEdgeCenterMarker->setVisible( false );
moveDragBands( e->mapPoint() );
}
void QgsVertexTool::moveDragBands( const QgsPointXY &mapPoint )
{
for ( int i = 0; i < mDragStraightBands.count(); ++i )
{
StraightBand &b = mDragStraightBands[i];
if ( b.moving0 )
b.band->movePoint( 0, mapPoint + b.offset0 );
if ( b.moving1 )
b.band->movePoint( 1, mapPoint + b.offset1 );
}
for ( int i = 0; i < mDragCircularBands.count(); ++i )
{
CircularBand &b = mDragCircularBands[i];
b.updateRubberBand( mapPoint );
}
// in case of moving of standalone point geometry
for ( int i = 0; i < mDragPointMarkers.count(); ++i )
{
QgsVertexMarker *marker = mDragPointMarkers[i];
QgsVector offset = mDragPointMarkersOffset[i];
marker->setCenter( mapPoint + offset );
}
// make sure the temporary feature rubber band is not visible
removeTemporaryRubberBands();
}
void QgsVertexTool::mouseMoveDraggingEdge( QgsMapMouseEvent *e )
{
mSnapIndicator->setMatch( QgsPointLocator::Match() );
mEdgeCenterMarker->setVisible( false );
QgsPointXY mapPoint = toMapCoordinates( e->pos() ); // do not use e.mapPoint() as it may be snapped
moveDragBands( mapPoint );
}
void QgsVertexTool::canvasDoubleClickEvent( QgsMapMouseEvent *e )
{
if ( e->button() != Qt::LeftButton )
return;
QgsPointLocator::Match m = snapToEditableLayer( e );
if ( !m.hasEdge() )
return;
mNewVertexFromDoubleClick.reset( new QgsPointLocator::Match( m ) );
}
void QgsVertexTool::removeTemporaryRubberBands()
{
mFeatureBand->setVisible( false );
mFeatureBandMarkers->setVisible( false );
mFeatureBandLayer = nullptr;
mFeatureBandFid = QgsFeatureId();
mVertexBand->setVisible( false );
mEdgeBand->setVisible( false );
mEdgeCenterMarker->setVisible( false );
mEndpointMarkerCenter.reset();
mEndpointMarker->setVisible( false );
}
QgsPointLocator::Match QgsVertexTool::snapToEditableLayer( QgsMapMouseEvent *e )
{
QgsSnappingUtils *snapUtils = canvas()->snappingUtils();
QgsSnappingConfig oldConfig = snapUtils->config();
QgsPointLocator::Match m;
QgsPointXY mapPoint = toMapCoordinates( e->pos() );
double tol = QgsTolerance::vertexSearchRadius( canvas()->mapSettings() );
QgsSnappingConfig config = oldConfig;
config.setEnabled( true );
config.setMode( Qgis::SnappingMode::AdvancedConfiguration );
config.setIntersectionSnapping( false ); // only snap to layers
config.clearIndividualLayerSettings();
typedef QHash<QgsVectorLayer *, QgsSnappingConfig::IndividualLayerSettings> SettingsHashMap;
SettingsHashMap oldLayerSettings = oldConfig.individualLayerSettings();
// if there is a current layer, it should have priority over other layers
// because sometimes there may be match from multiple layers at one location
// and selecting current layer is an easy way for the user to prioritize a layer
if ( QgsVectorLayer *currentVlayer = currentVectorLayer() )
{
if ( currentVlayer->isEditable() )
{
const auto layers = canvas()->layers( true );
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer )
continue;
QgsSnappingConfig::IndividualLayerSettings layerSettings;
SettingsHashMap::const_iterator existingSettings = oldLayerSettings.find( vlayer );
if ( existingSettings != oldLayerSettings.constEnd() )
{
layerSettings = existingSettings.value();
layerSettings.setEnabled( vlayer == currentVlayer );
layerSettings.setTolerance( tol );
layerSettings.setTypeFlag( static_cast<Qgis::SnappingTypes>( Qgis::SnappingType::Vertex | Qgis::SnappingType::Segment ) );
layerSettings.setUnits( Qgis::MapToolUnit::Project );
}
else
{
layerSettings = QgsSnappingConfig::IndividualLayerSettings(
vlayer == currentVlayer, static_cast<Qgis::SnappingTypes>( Qgis::SnappingType::Vertex | Qgis::SnappingType::Segment ), tol, Qgis::MapToolUnit::Project, 0.0, 0.0 );
}
config.setIndividualLayerSettings( vlayer, layerSettings );
}
snapUtils->setConfig( config );
SelectedMatchFilter filter( tol, mLockedFeature.get() );
m = snapUtils->snapToMap( mapPoint, &filter, true );
// we give priority to snap matches that are from selected features
if ( filter.hasSelectedMatch() )
{
m = filter.bestSelectedMatch();
mLastSnap.reset();
}
}
}
// if there is no match from the current layer, try to use any editable vector layer
if ( !m.isValid() && mMode == AllLayers )
{
const auto layers = canvas()->layers( true );
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer )
continue;
QgsSnappingConfig::IndividualLayerSettings layerSettings;
SettingsHashMap::const_iterator existingSettings = oldLayerSettings.find( vlayer );
if ( existingSettings != oldLayerSettings.constEnd() )
{
layerSettings = existingSettings.value();
layerSettings.setEnabled( vlayer->isEditable() );
layerSettings.setTolerance( tol );
layerSettings.setTypeFlag( static_cast<Qgis::SnappingTypes>( Qgis::SnappingType::Vertex | Qgis::SnappingType::Segment ) );
layerSettings.setUnits( Qgis::MapToolUnit::Project );
}
else
{
layerSettings = QgsSnappingConfig::IndividualLayerSettings( vlayer->isEditable(), static_cast<Qgis::SnappingTypes>( Qgis::SnappingType::Vertex | Qgis::SnappingType::Segment ), tol, Qgis::MapToolUnit::Project, 0.0, 0.0 );
}
config.setIndividualLayerSettings( vlayer, layerSettings );
}
snapUtils->setConfig( config );
SelectedMatchFilter filter( tol, mLockedFeature.get() );
m = snapUtils->snapToMap( mapPoint, &filter, true );
// we give priority to snap matches that are from selected features
if ( filter.hasSelectedMatch() )
{
m = filter.bestSelectedMatch();
mLastSnap.reset();
}
}
// try to stay snapped to previously used feature
// so the highlight does not jump around at vertices where features are joined
if ( mLastSnap )
{
OneFeatureFilter filterLast( mLastSnap->layer(), mLastSnap->featureId() );
QgsPointLocator::Match lastMatch = snapUtils->snapToMap( mapPoint, &filterLast, true );
// but skip the the previously used feature if it would only snap to segment, while now we have snap to vertex
// so that if there is a point on a line, it gets priority (as is usual with combined vertex+segment snapping)
bool matchHasVertexLastHasEdge = m.hasVertex() && lastMatch.hasEdge();
if ( lastMatch.isValid() && lastMatch.distance() <= m.distance() && !matchHasVertexLastHasEdge )
{
m = lastMatch;
}
}
snapUtils->setConfig( oldConfig );
mLastSnap.reset( new QgsPointLocator::Match( m ) );
return m;
}
QgsPointLocator::Match QgsVertexTool::snapToPolygonInterior( QgsMapMouseEvent *e )
{
QgsSnappingUtils *snapUtils = canvas()->snappingUtils();
QgsPointLocator::Match m;
QgsPointXY mapPoint = toMapCoordinates( e->pos() );
// if there is a current layer, it should have priority over other layers
// because sometimes there may be match from multiple layers at one location
// and selecting current layer is an easy way for the user to prioritize a layer
if ( QgsVectorLayer *currentVlayer = currentVectorLayer() )
{
if ( currentVlayer->isEditable() && currentVlayer->geometryType() == Qgis::GeometryType::Polygon )
{
QgsPointLocator::MatchList matchList = snapUtils->locatorForLayer( currentVlayer )->pointInPolygon( mapPoint, true );
if ( !matchList.isEmpty() )
{
m = matchList.first();
}
}
}
// if there is no match from the current layer, try to use any editable vector layer
if ( !m.isValid() && mMode == AllLayers )
{
const auto layers = canvas()->layers( true );
for ( QgsMapLayer *layer : layers )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( layer );
if ( !vlayer )
continue;
if ( vlayer->isEditable() && vlayer->geometryType() == Qgis::GeometryType::Polygon )
{
QgsPointLocator::MatchList matchList = snapUtils->locatorForLayer( vlayer )->pointInPolygon( mapPoint, true );
if ( !matchList.isEmpty() )
{
m = matchList.first();
break;
}