-
-
Notifications
You must be signed in to change notification settings - Fork 970
Expand file tree
/
Copy pathcanvas.py
More file actions
3678 lines (3393 loc) · 140 KB
/
canvas.py
File metadata and controls
3678 lines (3393 loc) · 140 KB
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
"""This module defines Canvas widget - the core component for drawing image labels"""
import copy
import math
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QWheelEvent
from anylabeling.services.auto_labeling.types import AutoLabelingMode
from anylabeling.views.labeling.utils.colormap import label_colormap
from anylabeling.views.labeling.utils.theme import get_theme
from .. import utils
from ..shape import Shape
CURSOR_DEFAULT = QtCore.Qt.CursorShape.ArrowCursor
CURSOR_POINT = QtCore.Qt.CursorShape.PointingHandCursor
CURSOR_DRAW = QtCore.Qt.CursorShape.CrossCursor
CURSOR_MOVE = QtCore.Qt.CursorShape.ClosedHandCursor
CURSOR_GRAB = QtCore.Qt.CursorShape.OpenHandCursor
AUTO_DECODE_DELAY_MS = 100
MAX_AUTO_DECODE_MARKS = 42
AUTO_DECODE_MOVE_THRESHOLD = 5.0
MOVE_SPEED = 5.0
LARGE_ROTATION_INCREMENT = math.radians(1.0)
SMALL_ROTATION_INCREMENT = math.radians(0.1)
CUBOID_FRONT_EDGE_CENTER_INDICES = {
Shape.CUBOID_FRONT_LEFT_EDGE_CENTER,
Shape.CUBOID_FRONT_RIGHT_EDGE_CENTER,
Shape.CUBOID_FRONT_TOP_EDGE_CENTER,
Shape.CUBOID_FRONT_BOTTOM_EDGE_CENTER,
}
CUBOID_BACK_EDGE_CENTER_INDICES = {
Shape.CUBOID_BACK_LEFT_EDGE_CENTER,
Shape.CUBOID_BACK_RIGHT_EDGE_CENTER,
}
CUBOID_FACE_FRONT = "front"
CUBOID_FACE_RIGHT = "right"
CUBOID_FACE_LEFT = "left"
CUBOID_FACE_TOP = "top"
CUBOID_FACE_BOTTOM = "bottom"
CUBOID_FACE_BACK = "back"
LABEL_COLORMAP = label_colormap()
class Canvas(
QtWidgets.QWidget
): # pylint: disable=too-many-public-methods, too-many-instance-attributes
"""Canvas widget to handle label drawing"""
zoom_request = QtCore.pyqtSignal(int, QtCore.QPoint)
scroll_request = QtCore.pyqtSignal(float, object, int)
# [Feature] support for automatically switching to editing mode
# when the cursor moves over an object
mode_changed = QtCore.pyqtSignal()
new_shape = QtCore.pyqtSignal()
show_shape = QtCore.pyqtSignal(int, int, QtCore.QPointF)
selection_changed = QtCore.pyqtSignal(list)
shape_moved = QtCore.pyqtSignal()
shape_rotated = QtCore.pyqtSignal()
drawing_polygon = QtCore.pyqtSignal(bool)
vertex_selected = QtCore.pyqtSignal(bool)
auto_labeling_marks_updated = QtCore.pyqtSignal(list)
auto_decode_requested = QtCore.pyqtSignal(list)
auto_decode_finish_requested = QtCore.pyqtSignal()
shape_hover_changed = QtCore.pyqtSignal()
split_position_changed = QtCore.pyqtSignal(float)
edit_label_requested = QtCore.pyqtSignal()
CREATE, EDIT = 0, 1
# polygon, rectangle, rotation, line, or point
_create_mode = "polygon"
_fill_drawing = False
def __init__(self, *args, **kwargs):
self.epsilon = kwargs.pop("epsilon", 10.0)
self.double_click = kwargs.pop("double_click", "close")
if self.double_click not in [None, "close"]:
raise ValueError(
f"Unexpected value for double_click event: {self.double_click}"
)
self.double_click_edit_label = kwargs.pop(
"double_click_edit_label", True
)
self.num_backups = kwargs.pop("num_backups", 10)
self.wheel_rectangle_editing = kwargs.pop(
"wheel_rectangle_editing", {}
)
self.enable_wheel_rectangle_editing = self.wheel_rectangle_editing.get(
"enable", False
)
self.rect_adjust_step = self.wheel_rectangle_editing.get(
"adjust_step", 2.0
)
self.rect_scale_step = self.wheel_rectangle_editing.get(
"scale_step", 0.05
)
self.auto_highlight_shape = kwargs.pop("auto_highlight_shape", False)
self.attributes_config = kwargs.pop("attributes", {})
self.rotation_config = kwargs.pop("rotation", {})
self.mask_config = kwargs.pop("mask", {})
self.brush_config = kwargs.pop("brush", {})
self.cuboid_config = kwargs.pop("cuboid", {})
self.parent = kwargs.pop("parent")
super().__init__(*args, **kwargs)
self.setAutoFillBackground(True)
palette = self.palette()
palette.setColor(
QtGui.QPalette.ColorRole.Window,
QtGui.QColor(get_theme()["background"]),
)
self.setPalette(palette)
# Initialise local state.
self.mode = self.EDIT
self.is_auto_labeling = False
self.is_move_editing = False
self.auto_labeling_mode: AutoLabelingMode = None
self.shapes = []
self.shapes_backups = []
self.current = None
self.selected_shapes = [] # save the selected shapes here
self.selected_shapes_copy = []
# self.line represents:
# - create_mode == 'polygon': edge from last point to current
# - create_mode == 'rectangle': diagonal line of the rectangle
# - create_mode == 'line': the line
# - create_mode == 'point': the point
self.line = Shape()
self.prev_point = QtCore.QPointF()
self.prev_pan_point = QtCore.QPointF()
self.prev_move_point = QtCore.QPointF()
self.offsets = QtCore.QPointF(), QtCore.QPointF()
self.scale = 1.0
self.pixmap = QtGui.QPixmap()
self.visible = {}
self._hide_backround = False
self.hide_backround = False
self.h_shape = None
self.prev_h_shape = None
self.h_vertex = None
self.prev_h_vertex = None
self.h_edge = None
self.prev_h_edge = None
self.h_cuboid_face = None
self.prev_h_cuboid_face = None
self.moving_shape = False
self._pending_edge_point = None
self.rotating_shape = False
self.snapping = True
self.h_shape_is_selected = False
self.h_shape_is_hovered = None
self.allowed_oop_shape_types = ["rotation", "quadrilateral", "cuboid"]
default_cuboid_depth_vector = self.cuboid_config.get(
"default_depth_vector", [24.0, -24.0]
)
if (
not isinstance(default_cuboid_depth_vector, (list, tuple))
or len(default_cuboid_depth_vector) != 2
):
default_cuboid_depth_vector = [24.0, -24.0]
self.cuboid_default_depth_vector = [
float(default_cuboid_depth_vector[0]),
float(default_cuboid_depth_vector[1]),
]
self.cuboid_min_depth = float(self.cuboid_config.get("min_depth", 5.0))
self._painter = QtGui.QPainter()
self._cursor = CURSOR_DEFAULT
# Menus:
# 0: right-click without selection and dragging of shapes
# 1: right-click with selection and dragging of shapes
self.menus = (QtWidgets.QMenu(), QtWidgets.QMenu())
# Set widget options.
self.setMouseTracking(True)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.WheelFocus)
self.show_groups = False
self.show_masks = True
self.show_texts = True
self.show_labels = True
self.show_scores = True
self.show_degrees = False
self.show_attributes = True
self.show_linking = True
# Set cross line options.
self.cross_line_show = True
self.cross_line_width = 2.0
self.cross_line_color = "#00FF00"
self.cross_line_opacity = 0.5
# Set attributes color options.
self.attr_background_color = self.attributes_config.get(
"background_color", [33, 33, 33, 255]
)
self.attr_border_color = self.attributes_config.get(
"border_color", [66, 66, 66, 255]
)
self.attr_text_color = self.attributes_config.get(
"text_color", [33, 150, 243, 255]
)
# Set rotation increment options.
self.large_rotation_increment = math.radians(
self.rotation_config.get("large_increment", 1.0)
)
self.small_rotation_increment = math.radians(
self.rotation_config.get("small_increment", 0.1)
)
# Set mask opacity options.
self.mask_opacity = self.mask_config.get("opacity", 80)
self.is_loading = False
self.loading_text = self.tr("Loading...")
self.loading_angle = 0
# Auto mask decode mode
self.auto_decode_mode = False
self.auto_decode_timer = QTimer()
self.auto_decode_timer.timeout.connect(self.on_auto_decode_timeout)
self.auto_decode_timer.setSingleShot(True)
self.auto_decode_tracklet = []
self.last_mouse_pos = None
# Brush drawing mode for polygon
self._brush_drawing = False
self.brush_point_distance = self.brush_config.get(
"point_distance", 25.0
)
# Compare view support
self.compare_pixmap = None
self.split_position = 0.5
def set_loading(self, is_loading: bool, loading_text: str = None):
"""Set loading state"""
self.is_loading = is_loading
if loading_text:
self.loading_text = loading_text
self.update()
def set_auto_labeling_mode(self, mode: AutoLabelingMode):
"""Set auto labeling mode"""
if mode == AutoLabelingMode.NONE:
self.is_auto_labeling = False
self.auto_labeling_mode = mode
else:
self.is_auto_labeling = True
self.auto_labeling_mode = mode
self.create_mode = mode.shape_type
self.parent.toggle_draw_mode(
False, mode.shape_type, disable_auto_labeling=False
)
def set_auto_decode_mode(self, enabled: bool):
"""Set auto decode mode"""
if self.auto_decode_mode and not enabled:
self.reset_auto_decode_state()
self.auto_decode_mode = enabled
def reset_auto_decode_state(self):
"""Reset auto decode state"""
if self.auto_decode_timer.isActive():
self.auto_decode_timer.stop()
self.auto_decode_tracklet.clear()
self.last_mouse_pos = None
def fill_drawing(self):
"""Get option to fill shapes by color"""
return self._fill_drawing
def set_fill_drawing(self, value):
"""Set shape filling option"""
self._fill_drawing = value
self.update()
@property
def create_mode(self):
"""Create mode for canvas - Modes: polygon, rectangle, rotation, circle,..."""
return self._create_mode
@create_mode.setter
def create_mode(self, value):
"""Set create mode for canvas"""
if value not in Shape.get_supported_shape():
raise ValueError(f"Unsupported create_mode: {value}")
self._create_mode = value
def store_shapes(self):
"""Store shapes for restoring later (Undo feature)"""
shapes_backup = []
for shape in self.shapes:
shapes_backup.append(shape.copy())
if len(self.shapes_backups) > self.num_backups:
self.shapes_backups = self.shapes_backups[-self.num_backups - 1 :]
self.shapes_backups.append(shapes_backup)
def store_moving_shape(self):
"""Store a moving shape"""
if self.moving_shape:
moving_shapes = (
[self.h_shape] + self.selected_shapes
if self.h_shape and self.h_shape not in self.selected_shapes
else self.selected_shapes.copy()
)
for shape in moving_shapes:
if shape in self.shapes:
index = self.shapes.index(shape)
if (
len(self.shapes_backups) > 0
and index < len(self.shapes_backups[-1])
and self.shapes_backups[-1][index].points
!= self.shapes[index].points
):
self.store_shapes()
self.shape_moved.emit()
break
self.moving_shape = False
def clip_rectangle_to_pixmap(self, shape):
"""Clip rectangle shape to pixmap boundaries"""
if self.pixmap is None or shape.shape_type != "rectangle":
return True
w, h = self.pixmap.width(), self.pixmap.height()
points = shape.points
if len(points) != 4:
return True
x_coords = [p.x() for p in points]
y_coords = [p.y() for p in points]
min_x, max_x = min(x_coords), max(x_coords)
min_y, max_y = min(y_coords), max(y_coords)
clipped_min_x = max(0, min_x)
clipped_min_y = max(0, min_y)
clipped_max_x = min(w - 1, max_x)
clipped_max_y = min(h - 1, max_y)
if clipped_max_x <= clipped_min_x or clipped_max_y <= clipped_min_y:
return False
shape.points = [
QtCore.QPointF(clipped_min_x, clipped_min_y),
QtCore.QPointF(clipped_max_x, clipped_min_y),
QtCore.QPointF(clipped_max_x, clipped_max_y),
QtCore.QPointF(clipped_min_x, clipped_max_y),
]
return True
def clip_rotation_to_pixmap(self, shape):
"""Clip an axis-aligned rotation shape's bounding box to pixmap boundaries.
Only clamps shapes whose direction is zero, i.e. freshly drawn in
manual mode before any rotation has been applied.
Args:
shape (Shape): The rotation shape to clip.
Returns:
bool: True if the resulting shape is valid, False if it degenerates
to zero area and should be discarded.
"""
if self.pixmap is None or shape.shape_type != "rotation":
return True
if shape.direction != 0:
return True
if len(shape.points) != 4:
return True
w, h = self.pixmap.width(), self.pixmap.height()
x_coords = [p.x() for p in shape.points]
y_coords = [p.y() for p in shape.points]
min_x, max_x = min(x_coords), max(x_coords)
min_y, max_y = min(y_coords), max(y_coords)
clipped_min_x = max(0, min_x)
clipped_min_y = max(0, min_y)
clipped_max_x = min(w - 1, max_x)
clipped_max_y = min(h - 1, max_y)
if clipped_max_x <= clipped_min_x or clipped_max_y <= clipped_min_y:
return False
shape.points = [
QtCore.QPointF(clipped_min_x, clipped_min_y),
QtCore.QPointF(clipped_max_x, clipped_min_y),
QtCore.QPointF(clipped_max_x, clipped_max_y),
QtCore.QPointF(clipped_min_x, clipped_max_y),
]
shape.center = QtCore.QPointF(
(clipped_min_x + clipped_max_x) / 2,
(clipped_min_y + clipped_max_y) / 2,
)
return True
@property
def is_shape_restorable(self):
"""Check if shape can be restored from backup"""
# We save the state AFTER each edit (not before) so for an
# edit to be undoable, we expect the CURRENT and the PREVIOUS state
# to be in the undo stack.
if len(self.shapes_backups) < 2:
return False
return True
def restore_shape(self):
"""Restore/Undo a shape"""
# This does _part_ of the job of restoring shapes.
# The complete process is also done in app.py::undoShapeEdit
# and app.py::load_shapes and our own Canvas::load_shapes function.
if not self.is_shape_restorable:
return
self.shapes_backups.pop() # latest
# The application will eventually call Canvas.load_shapes which will
# push this right back onto the stack.
shapes_backup = self.shapes_backups.pop()
self.shapes = shapes_backup
self.selected_shapes = []
for shape in self.shapes:
shape.selected = False
self.update()
def enterEvent(self, _):
"""Mouse enter event"""
self.override_cursor(self._cursor)
def leaveEvent(self, _):
"""Mouse leave event"""
self.store_moving_shape()
self.un_highlight()
self.restore_cursor()
self.shape_hover_changed.emit()
def focusOutEvent(self, _):
"""Window out of focus event"""
self.restore_cursor()
def is_visible(self, shape):
"""Check if a shape is visible"""
return self.visible.get(shape, True)
def drawing(self):
"""Check if user is drawing (mode==CREATE)"""
return self.mode == self.CREATE
def editing(self):
"""Check if user is editing (mode==EDIT)"""
return self.mode == self.EDIT
def set_auto_labeling(self, value=True):
"""Set auto labeling mode"""
self.is_auto_labeling = value
if self.auto_labeling_mode is None:
self.auto_labeling_mode = AutoLabelingMode.NONE
self.parent.toggle_draw_mode(
True, "rectangle", disable_auto_labeling=True
)
def get_mode(self):
"""Get current mode"""
if (
self.is_auto_labeling
and self.auto_labeling_mode != AutoLabelingMode.NONE
):
return self.tr("Auto Labeling")
if self.mode == self.CREATE:
return self.tr("Drawing")
elif self.mode == self.EDIT:
return self.tr("Editing")
else:
return self.tr("Unknown")
def set_editing(self, value=True):
"""Set editing mode. Editing is set to False, user is drawing"""
self.mode = self.EDIT if value else self.CREATE
if not value: # Create
self.un_highlight()
self.deselect_shape()
self.is_move_editing = False
self.shape_hover_changed.emit()
def un_highlight(self):
"""Unhighlight shape/vertex/edge"""
if self.h_shape:
self.h_shape.highlight_clear()
self.update()
self.prev_h_shape = self.h_shape
self.prev_h_vertex = self.h_vertex
self.prev_h_edge = self.h_edge
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_shape = self.h_vertex = self.h_edge = self.h_cuboid_face = None
def selected_vertex(self):
"""Check if selected a vertex"""
return self.h_vertex is not None
def selected_edge(self):
"""Check if selected an edge"""
return self.h_edge is not None
def selected_cuboid_face(self):
return self.h_cuboid_face is not None
@staticmethod
def _snap_line_pos(anchor, pos):
"""Snap line endpoint to horizontal or vertical direction."""
dx = abs(pos.x() - anchor.x())
dy = abs(pos.y() - anchor.y())
if dx >= dy:
return QtCore.QPointF(pos.x(), anchor.y())
return QtCore.QPointF(anchor.x(), pos.y())
def _should_trigger_auto_decode(self, pos):
"""Check if mouse movement exceeds threshold to trigger auto decode"""
if not self.auto_decode_tracklet:
return True
last_point = self.auto_decode_tracklet[-1]["data"]
distance = (
(pos.x() - last_point[0]) ** 2 + (pos.y() - last_point[1]) ** 2
) ** 0.5
return distance >= AUTO_DECODE_MOVE_THRESHOLD
# QT Overload
def mouseMoveEvent(self, ev): # noqa: C901
"""Update line with last point and current coordinates"""
if self.is_loading:
return
try:
pos = self.transform_pos(ev.position())
except AttributeError:
return
prev_hover_shape = self.h_shape
self.prev_move_point = pos
self.repaint()
# Handle auto decode mode
if (
self.auto_decode_mode
and self.is_auto_labeling
and self.auto_decode_tracklet
):
if self._should_trigger_auto_decode(pos):
self.last_mouse_pos = pos
if not self.auto_decode_timer.isActive():
self.auto_decode_timer.start(AUTO_DECODE_DELAY_MS)
# Polygon drawing.
if self.drawing():
line_color = utils.hex_to_rgb(self.cross_line_color)
self.line.line_color = QtGui.QColor(*line_color)
self.line.shape_type = self.create_mode
if self.create_mode == "cuboid":
self.line.shape_type = "rectangle"
if not self.current:
self.override_cursor(CURSOR_DRAW)
return
if self.create_mode in ["rectangle", "cuboid"]:
shape_width = int(abs(self.current[0].x() - pos.x()))
shape_height = int(abs(self.current[0].y() - pos.y()))
self.show_shape.emit(shape_height, shape_width, pos)
color = QtGui.QColor(0, 0, 255)
if self.out_off_pixmap(pos) and self.create_mode not in [
"rectangle",
"rotation",
"quadrilateral",
"cuboid",
]:
pos = self.intersection_point(self.current[-1], pos)
elif (
self.snapping
and len(self.current) > 1
and self.create_mode == "polygon"
and self.close_enough(pos, self.current[0])
):
# Attract line to starting point and
# colorise to alert the user.
pos = self.current[0]
self.override_cursor(CURSOR_POINT)
self.current.highlight_vertex(0, Shape.NEAR_VERTEX)
elif (
self.create_mode == "rotation"
and len(self.current) > 0
and self.close_enough(pos, self.current[0])
):
pos = self.current[0]
color = self.current.line_color
self.override_cursor(CURSOR_POINT)
self.current.highlight_vertex(0, Shape.NEAR_VERTEX)
elif (
self.create_mode == "quadrilateral"
and len(self.current) >= 3
and self.close_enough(pos, self.current[0])
):
pos = self.current[0]
self.override_cursor(CURSOR_POINT)
self.current.highlight_vertex(0, Shape.NEAR_VERTEX)
else:
self.override_cursor(CURSOR_DRAW)
if (
self.create_mode in ["line", "linestrip"]
and ev.modifiers() & QtCore.Qt.KeyboardModifier.ShiftModifier
):
pos = self._snap_line_pos(self.current[-1], pos)
if self.create_mode in ["polygon", "linestrip", "quadrilateral"]:
self.line[0] = self.current[-1]
self.line[1] = pos
elif self.create_mode == "rectangle":
self.line.points = [self.current[0], pos]
self.line.close()
elif self.create_mode == "rotation":
self.line[1] = pos
self.line.line_color = color
elif self.create_mode == "circle":
self.line.points = [self.current[0], pos]
self.line.shape_type = "circle"
elif self.create_mode == "line":
self.line.points = [self.current[0], pos]
self.line.close()
elif self.create_mode == "point":
self.line.points = [self.current[0]]
self.line.close()
elif self.create_mode == "cuboid":
self.line.points = [self.current[0], pos]
self.line.close()
if self._brush_drawing and self.create_mode == "polygon":
if (
self.snapping
and len(self.current) > 2
and self.close_enough(pos, self.current[0])
):
self.current.highlight_clear()
self.finalise()
return
point_dist = utils.distance(pos - self.current[-1])
if point_dist * self.scale >= self.brush_point_distance:
self.current.add_point(pos)
self.line[0] = self.current[-1]
self.repaint()
self.current.highlight_clear()
return
# Polygon copy moving.
if QtCore.Qt.MouseButton.RightButton & ev.buttons():
if self.selected_shapes_copy and self.prev_point:
self.override_cursor(CURSOR_MOVE)
self.bounded_move_shapes(self.selected_shapes_copy, pos)
self.repaint()
elif self.selected_shapes:
self.selected_shapes_copy = [
s.copy() for s in self.selected_shapes
]
self.repaint()
return
# Polygon/Vertex moving.
if QtCore.Qt.MouseButton.LeftButton & ev.buttons():
if self.selected_vertex():
self.h_cuboid_face = None
self.is_move_editing = False
try:
self.bounded_move_vertex(pos)
self.repaint()
self.moving_shape = True
except IndexError:
return
if self.h_shape.shape_type == "rectangle":
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif (
self.h_shape.shape_type == "cuboid"
and len(self.h_shape) >= 4
):
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif (
self.selected_cuboid_face()
and self.h_shape is not None
and self.h_shape.shape_type == "cuboid"
and self.prev_point is not None
):
self.is_move_editing = False
offset = pos - self.prev_point
self.move_cuboid_face_by(
self.h_shape, self.h_cuboid_face, offset
)
self.prev_point = pos
self.repaint()
self.moving_shape = True
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif self.selected_shapes and self.prev_point:
self.h_cuboid_face = None
self.override_cursor(CURSOR_MOVE)
self.bounded_move_shapes(self.selected_shapes, pos)
self.repaint()
self.moving_shape = True
if self.selected_shapes[-1].shape_type == "rectangle":
p1 = self.selected_shapes[-1][0]
p2 = self.selected_shapes[-1][2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif (
self.selected_shapes[-1].shape_type == "cuboid"
and len(self.selected_shapes[-1]) >= 4
):
p1 = self.selected_shapes[-1][0]
p2 = self.selected_shapes[-1][2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
else:
if (
self.pixmap
and self.pixmap.width()
and self.pixmap.height()
):
self.override_cursor(CURSOR_MOVE)
delta = ev.position() - self.prev_pan_point
self.scroll_request.emit(
delta.x() / (self.pixmap.width() * self.scale),
Qt.Orientation.Horizontal,
1,
)
self.scroll_request.emit(
delta.y() / (self.pixmap.height() * self.scale),
Qt.Orientation.Vertical,
1,
)
self.repaint()
return
if self.editing() and self.is_move_editing:
self.override_cursor(CURSOR_MOVE)
if self.selected_vertex():
self.h_cuboid_face = None
try:
self.bounded_move_vertex(pos)
self.repaint()
self.moving_shape = True
except IndexError:
return
if self.h_shape.shape_type == "rectangle":
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif (
self.h_shape.shape_type == "cuboid"
and len(self.h_shape) >= 4
):
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif (
self.selected_cuboid_face()
and self.h_shape is not None
and self.h_shape.shape_type == "cuboid"
and self.prev_point is not None
):
offset = pos - self.prev_point
self.move_cuboid_face_by(
self.h_shape, self.h_cuboid_face, offset
)
self.prev_point = pos
self.repaint()
self.moving_shape = True
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
else:
self.is_move_editing = False
return
self.show_shape.emit(-1, -1, pos)
# Just hovering over the canvas, 2 possibilities:
# - Highlight shapes
# - Highlight vertex
# Update shape/vertex fill and tooltip value accordingly.
# self.setToolTip(self.tr("Image"))
for shape in reversed([s for s in self.shapes if self.is_visible(s)]):
if shape.shape_type == "cuboid" and len(shape.points) == 8:
index = self.nearest_cuboid_control(
shape, pos, self.epsilon / self.scale
)
if index is not None:
if self.selected_vertex():
self.h_shape.highlight_clear()
self.prev_h_vertex = self.h_vertex
self.h_vertex = index
self.prev_h_shape = self.h_shape = shape
self.prev_h_edge = self.h_edge
self.h_edge = None
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_cuboid_face = None
shape.highlight_vertex(index, shape.MOVE_VERTEX)
self.override_cursor(CURSOR_POINT)
if index in CUBOID_BACK_EDGE_CENTER_INDICES:
self.setToolTip(
self.tr(
"Click & drag to adjust cuboid depth of shape '%s'"
)
% shape.label
)
elif index in [4, 5, 6, 7]:
self.setToolTip(
self.tr(
"Click & drag to adjust rear edge of cuboid shape '%s'"
)
% shape.label
)
else:
self.setToolTip(
self.tr("Click & drag to move point of shape '%s'")
% shape.label
)
self.setStatusTip(self.toolTip())
self.update()
break
front_path = self.cuboid_face_path(shape, CUBOID_FACE_FRONT)
if front_path is not None and front_path.contains(pos):
if self.selected_vertex():
self.h_shape.highlight_clear()
self.prev_h_vertex = self.h_vertex
self.h_vertex = None
self.prev_h_shape = self.h_shape = shape
self.prev_h_edge = self.h_edge
self.h_edge = None
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_cuboid_face = None
self.setToolTip(
self.tr("Click & drag to move shape '%s'")
% shape.label
)
self.setStatusTip(self.toolTip())
self.override_cursor(CURSOR_GRAB)
self.update()
break
face_name = self.cuboid_face_hit_test(shape, pos)
if face_name and face_name != CUBOID_FACE_FRONT:
if self.selected_vertex():
self.h_shape.highlight_clear()
self.prev_h_vertex = self.h_vertex
self.h_vertex = None
self.prev_h_shape = self.h_shape = shape
self.prev_h_edge = self.h_edge
self.h_edge = None
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_cuboid_face = face_name
self.override_cursor(CURSOR_POINT)
self.setToolTip(
self.tr(
"Click & drag to adjust cuboid %s face of shape '%s'"
)
% (face_name, shape.label)
)
self.setStatusTip(self.toolTip())
self.update()
break
# Look for a nearby vertex to highlight. If that fails,
# check if we happen to be inside a shape.
index = shape.nearest_vertex(pos, self.epsilon / self.scale)
index_edge = shape.nearest_edge(pos, self.epsilon / self.scale)
if index is not None:
if self.selected_vertex():
self.h_shape.highlight_clear()
self.prev_h_vertex = self.h_vertex = index
self.prev_h_shape = self.h_shape = shape
self.prev_h_edge = self.h_edge
self.h_edge = None
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_cuboid_face = None
shape.highlight_vertex(index, shape.MOVE_VERTEX)
self.override_cursor(CURSOR_POINT)
self.setToolTip(
self.tr("Click & drag to move point of shape '%s'")
% shape.label
)
self.setStatusTip(self.toolTip())
self.update()
break
if (
index_edge is not None
and shape.can_add_point()
and shape.shape_type != "quadrilateral"
):
if self.selected_vertex():
self.h_shape.highlight_clear()
self.prev_h_vertex = self.h_vertex
self.h_vertex = None
self.prev_h_shape = self.h_shape = shape
self.prev_h_edge = self.h_edge = index_edge
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_cuboid_face = None
self.override_cursor(CURSOR_POINT)
self.setToolTip(
self.tr("Click to create point of shape '%s'")
% shape.label
)
self.setStatusTip(self.toolTip())
self.update()
break
shape_hit = False
if shape.shape_type in ["point", "line", "linestrip"]:
nearest_index = shape.nearest_vertex(
pos, self.epsilon * 3 / self.scale
)
if nearest_index is not None:
shape_hit = True
elif shape.shape_type == "cuboid" and len(shape.points) == 8:
front_path = self.cuboid_face_path(shape, CUBOID_FACE_FRONT)
shape_hit = front_path is not None and front_path.contains(pos)
elif len(shape.points) > 1 and shape.contains_point(pos):
shape_hit = True
if shape_hit:
if self.selected_vertex():
self.h_shape.highlight_clear()
self.prev_h_vertex = self.h_vertex
self.h_vertex = None
self.prev_h_shape = self.h_shape = shape
self.prev_h_edge = self.h_edge
self.h_edge = None
self.prev_h_cuboid_face = self.h_cuboid_face
self.h_cuboid_face = None
if shape.group_id and shape.shape_type == "rectangle":
tooltip_text = "Click & drag to move shape '{label} {group_id}'".format(
label=shape.label, group_id=shape.group_id
)
self.setToolTip(self.tr(tooltip_text))
else:
self.setToolTip(
self.tr("Click & drag to move shape '%s'")
% shape.label
)
self.setStatusTip(self.toolTip())
self.override_cursor(CURSOR_GRAB)
# [Feature] Automatically highlight shape when the mouse is moved inside it
if self.h_shape_is_hovered:
group_mode = (
ev.modifiers()
== QtCore.Qt.KeyboardModifier.ControlModifier
)
self.select_shape_point(
pos, multiple_selection_mode=group_mode
)
self.update()
if shape.shape_type == "rectangle":
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
elif shape.shape_type == "cuboid" and len(self.h_shape) >= 4:
p1 = self.h_shape[0]
p2 = self.h_shape[2]
shape_width = int(abs(p2.x() - p1.x()))
shape_height = int(abs(p2.y() - p1.y()))
self.show_shape.emit(shape_height, shape_width, pos)
break
else: # Nothing found, clear highlights, reset state.
self.un_highlight()
self.override_cursor(CURSOR_DEFAULT)
self.setToolTip("")
self.setStatusTip("")
self.vertex_selected.emit(self.h_vertex is not None)
if prev_hover_shape != self.h_shape:
self.shape_hover_changed.emit()
def add_point_to_edge(self):