-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraphics_manager.py
2518 lines (1978 loc) · 108 KB
/
graphics_manager.py
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
from dataclasses import dataclass, field
from functools import wraps
from PIL import Image, ImageTk
from typing import Union
from tools import Tools
from tools import TextInsertWindow
class GraphicsManager:
"""
GraphicsManager Class manages the drawing and display of annotations(graphics) that gets drawn onto the images.
"""
def __init__(self, app, canvas, is_overlay=False):
"""
Initialising the Class with a given canvas.
Args:
app: Tkinter main app
canvas: Tkinter Canvas
is_overlay (bool): True if the canvas is the overlay canvas. Default False.
"""
super().__init__()
self.app = app
self.active_canvas = canvas # image_canvas for base and overlay_canvas for the overlay elements.
self.coords_list = []
self.initial = 0
self.last_x = 0
self.last_y = 0
self.x_axis_constraint = None
self.stored_axis_value = None
self.selection_click_position = None
self.is_text_repositioning: bool = False
self.is_text_scaling: bool = False
self.selected_text_item = -1
# Offset so that the text objects anchor point does not snap to the mouse cursor.
self.text_offset_x = 0
self.text_offset_y = 0
self.ready_to_draw = False
self.interior_fill_color = ""
self.outline_fill_color = ""
self.scribble = None
self.scribble_list = []
self.temp_stroke = []
self.scale_to_reset = ""
self.zoom_to_reset = ""
self.annotation_visibility = True
self.insert_text_window = None
self.is_overlay = is_overlay
self.index = None
self.OVERLAY_GRAPHICS_INDEX = -1 # dictionary index of the overlay canvas.
self.OVERLAY_IMAGES_INDEX = -2 # dictionary index where the images.
self.create_text_selection_border()
def draw_graphic_elements_from_project_file(self, is_overlay=False):
"""
Unpacks the loaded_graphics_data_dict and based on the tool used, mimics the events that happens during the normal drawing.
Args:
is_overlay: If True, the graphic elements from OVERLAY_GRAPHICS_INDEX([-1])gets drawn on the overlay_canvas. Default False.
Returns:
None
"""
# Basically feeding in all values to the action that happens when the mouse click is released.
total_images_to_redraw = len(self.app.graphics_data) - 2 # excluding the overlay indexes
graphics_redrawn = 0 # the 0.5 progress from the file indexing.
for image_index, graphic_dict in self.app.loaded_graphics_data.items():
# excluding overlay items. unless specified (overlay elements).
if (image_index >= 0 and graphic_dict) or (image_index == -1 and is_overlay):
for item_id, graphic_object in graphic_dict.items():
self.ready_to_draw = True
Tools.stroke_width = self.convert_width_to_max_size(graphic_object.width)
self.scribble_width = Tools.stroke_width
Tools.current_tool = graphic_object.tool
Tools.stipple = graphic_object.stipple
Tools.endcap = graphic_object.capstyle
Tools.fill_color = graphic_object.fill_color
Tools.shape_fill = graphic_object.shape_fill
TextInsertWindow.selected_font = graphic_object.font_name
TextInsertWindow.selected_font_file = graphic_object.font_file
TextInsertWindow.selected_font_size = self.convert_width_to_max_size(
stroke_width=graphic_object.font_size, item="font")
if Tools.shape_fill:
self.interior_fill_color = Tools.fill_color
self.outline_fill_color = ""
self.offset = 0
else: # only outline
self.interior_fill_color = ""
self.outline_fill_color = Tools.fill_color
self.offset = self.scribble_width / 2
if Tools.current_tool == 8: # if it's a text item.
# Text is saved as tuple in the graphic_object, but as a list when entered.
# so using [] on the graphic_object.coordinates to make it a list.
self.coords_list = self.image_coordinates_to_max_size([graphic_object.coordinates])
self.draw_release(project_override=True, text=graphic_object.text,
image_sized_coordinates=graphic_object.coordinates)
else:
self.coords_list = self.image_coordinates_to_max_size(graphic_object.coordinates)
self.draw_release(project_override=True, image_sized_coordinates=graphic_object.coordinates)
# Break if the redraw happens in overlay canvas, break after iterating -1 index in the dict.
if is_overlay:
return
if image_index >= 0:
graphics_redrawn += 1
# Progress bar fill value.
# 0.5+0.3= 0.8 , remaining .2 is reserved for the progress of overlay items.
progress = graphics_redrawn / total_images_to_redraw * 0.3
# the 0.5 progress from the file indexing.
self.app.file_load_window.update_file_window_progressbar(progress=0.5 + progress)
self.app.show_next_img() # Scrolling through the images to get values based on the loaded image.
self.force_hide_all_canvas_annotations()
# seek to the first image.
self.app.show_first_img(force_first=True)
if self.app.maximized_mode:
self.reveal_parent_annotations()
else:
self.reveal_proxy_annotations()
def peucker_algorithm(self, points, tolerance):
"""
An algorithm that decimates a curve composed of line segments to a similar curve with fewer points.
Args:
points (tuple|list): Points to decimate.
tolerance (float): A float number to control the decimation.
Returns:
list: A list of simplified coordinates.
"""
def perpendicular_distance(point, line_start, line_end):
x, y = point
x1, y1 = line_start
x2, y2 = line_end
numerator = abs((y2 - y1) * x - (x2 - x1) * y + x2 * y1 - y2 * x1)
denominator = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
try:
return numerator / denominator
except ZeroDivisionError:
return 1
if len(points) <= 2:
return points
# Find the point with the maximum distance
max_distance = 0
max_index = 0
for i in range(1, len(points) - 1):
distance = perpendicular_distance(points[i], points[0], points[-1])
if distance > max_distance:
max_distance = distance
max_index = i
# If the maximum distance is greater than the tolerance, recursively simplify
if max_distance > tolerance:
left_part = self.peucker_algorithm(points[:max_index + 1], tolerance)
right_part = self.peucker_algorithm(points[max_index:], tolerance)
return left_part[:-1] + right_part
else:
return [points[0], points[-1]]
def create_text_selection_border(self):
"""
Creates four line segments on the canvas to act as a selection border.
Returns:
None
"""
SCALE_BOX_SIZE = 10
self.text_selection_border = self.active_canvas.create_line(0, 0, 0, 0, 0, 0, 0, 0, fill="#ff66ff", width=2,
tags="gui")
# hides the border.
self.active_canvas.itemconfig(self.text_selection_border, state="hidden")
def select_canvas_item(self, event, item_id=None):
"""
Fetches the clicked item on the canvas. If the item is a text, draw the surrounding border.
Args:
event(tkinter.Event): Mouse Click event
item_id(int):id of the canvas item.
Returns:
None
"""
# Removes any existing selections.
self.remove_text_item_selection()
if not item_id: # if no item_id is provided, fetch the item id closest to the mouse click.
item_id = event.widget.find_closest(event.x, event.y)[0]
item_tags = self.active_canvas.gettags(item_id)
if "text" in item_tags: # all text items have the "text" tag.
self.select_text_item(text_id=item_id) # Selects the text item.
self.set_text_drag_offset(event) # So that the text items anchor does not snap to the mouse position.
def select_text_item(self, text_id=None, enable_scale_slider=True):
"""
Assigns the text item as the selected_text_item and draws the selection border around it.
Args:
text_id (int): id of the text item on the canvas.
enable_scale_slider: True enables the scale slider that controls the scale of the text. Default True.
Returns:
None
"""
text_bounds = self.active_canvas.bbox(text_id)
x1, y1, x2, y2 = text_bounds
border_coordinates = x1, y1, x2, y1, x2, y2, x1, y2, x1, y1
self.active_canvas.coords(self.text_selection_border, border_coordinates)
self.active_canvas.tag_raise("gui") # Pushing the border to the top.
self.active_canvas.itemconfig(self.text_selection_border, state="normal", fill=self.app.selection_color)
self.selected_text_item = text_id
if enable_scale_slider:
self.app.toggle_image_tools_sliders(only_scale=True, toggle=1)
def remove_text_item_selection(self):
"""
Removes the current text item as the selected_text_item.
Returns:
None
"""
self.selected_text_item = None
self.active_canvas.itemconfig(self.text_selection_border, state="hidden")
self.app.toggle_image_tools_sliders(toggle=0)
def hide_text_item_selection_border(self):
"""
Hides the selection border around the selected text item.
Returns:
None
"""
self.active_canvas.itemconfig(self.text_selection_border, state="hidden")
def reveal_text_item_selection_border(self):
"""
Shows the selection border around the selected text item.
Returns:
None
"""
if self.selected_text_item:
self.select_text_item(text_id=self.selected_text_item)
self.is_image_scaling = False
self.is_text_repositioning = False
self.is_image_repositioning = False
self.x_axis_constraint = None
def annotation_visibility_checker(func):
"""
Checks if annotations are allowed to be displayed on the screen.
"""
# Saves time skipping annotation calculations if annotation display is turned off.
# If annotation visibility is disabled, skip the method.
@wraps(func)
def wrapper_function(self, *args, **kwargs):
if self.annotation_visibility:
main_result = func(self, *args, **kwargs)
return main_result
else:
return None
return wrapper_function
def check_if_overlay(func):
"""
Checks if current operations are being done on the overlay canvas.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.is_overlay:
self.index = self.app.image_index
else: # If Overlay set index to the Overlay graphics index.
self.index = self.OVERLAY_GRAPHICS_INDEX
result = func(self, *args, **kwargs)
# Pushing the images to the top. Since images will be added last due to antialiasing process.
self.active_canvas.tag_raise("overlay_img")
self.active_canvas.tag_raise("gui")
return result
return wrapper
# ====================================================
def initial_canvas_click(self, event):
"""
Called on the initial mouse click on the canvas. Stores the mouse coordinates and sets the stroke width based on the display mode.
Args:
event (tkinter.Event):Mouse click event.
Returns:
None
"""
self.active_canvas.focus_set() # Focus set on the active canvas.
self.flush_mouse_events() # Clears all previously stored mouse click events.
if Tools.current_tool == 1: # If the current tool used to click on the canvas is the cursor tool,
# set ready_to_draw to false and exit
self.ready_to_draw = False
return
self.ready_to_draw = True
self.initial_click = self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y)
self.last_x, self.last_y = self.initial_click
self.coords_list.append(self.initial_click)
# Resize the drawing tool to match proxy proportions.
if self.app.maximized_mode: # if maximized mode use the width as is.
self.scribble_width = Tools.stroke_width
else:
self.scribble_width = self.get_proxy_stroke_width() # if windowed mode get the proxy width.
if self.app.display_mode == "default": # if text insert.
if Tools.current_tool == 8: # Text insert.
# Stores text postion stores the mouse event for the quick text insert using hotkeys.
TextInsertWindow.stored_text_position = event
# -ve means the tkinter will use pixels instead of the font size.(for Pillow)
if self.app.maximized_mode:
TextInsertWindow.selected_font_size = TextInsertWindow.new_font_pixel_size
else:
TextInsertWindow.selected_font_size = TextInsertWindow.new_font_pixel_size
self.app.canvas_text_insert.reveal_text_insert_window()
return
# If the Image is actual sized or zoomed, get the stroke width relative to the zoom. #If the Image is actual sized or zoomed, get the stroke width relative to the zoom.
elif self.app.display_mode == "actual":
self.scribble_width = self.get_dynamic_stroke_width(mode="actual")
elif self.app.display_mode == "zoomed":
self.scribble_width = self.get_dynamic_stroke_width(mode="zoomed")
if Tools.shape_fill: # If the shape_fill check box is enabled. set the fill color as the interior_fill_color.for rectangle and oval.
self.interior_fill_color = Tools.fill_color
self.outline_fill_color = ""
self.offset = 0
else: # only outline
self.interior_fill_color = ""
self.outline_fill_color = Tools.fill_color
self.offset = self.scribble_width / 2
def draw_graphics(self, event):
"""
Called on Mouse drag event. Plots a temporary shape using the raw mouse coordinates. Erases the item instantly.
Args:
event (tkinter.Event):Mouse Drag event.
Returns:
None
"""
if self.ready_to_draw:
if Tools.current_tool == 2: # brush , since the coords are raw a simple drawing can have hundreds of coordinates.
self.scribble = self.active_canvas.create_line(
(self.last_x, self.last_y, self.active_canvas.canvasx(event.x),
self.active_canvas.canvasy(event.y)), fill=Tools.fill_color,
width=self.scribble_width, joinstyle="round", capstyle="round",
stipple=Tools.stipple, tags="scribble")
self.coords_list.append((self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y)))
elif Tools.current_tool == 3: # Eraser
self.erase_graphic(event, radius=Tools.stroke_width)
elif Tools.current_tool == 4: # line
if not self.scribble:
self.scribble = self.active_canvas.create_line(self.initial_click[0], self.initial_click[1],
self.active_canvas.canvasx(event.x),
self.active_canvas.canvasy(event.y),
fill=Tools.fill_color, width=self.scribble_width,
joinstyle="round", capstyle=Tools.endcap,
stipple=Tools.stipple, tags="scribble")
else:
self.active_canvas.coords(self.scribble, self.initial_click[0], self.initial_click[1],
self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y))
self.coords_list = [(self.initial_click[0], self.initial_click[1]),
(self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y))]
elif Tools.current_tool == 5: # rectangle
final_point_x, final_point_y = self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y)
# Formula for square.
if Tools.shape_constraint:
side_length = max((final_point_x - self.initial_click[0]), (final_point_y - self.initial_click[1]))
final_point_x, final_point_y = self.initial_click[0], self.initial_click[1]
else:
side_length = 0
if not self.scribble:
self.scribble = self.active_canvas.create_rectangle(self.initial_click[0] + self.offset,
self.initial_click[1] + self.offset,
final_point_x + side_length - self.offset,
final_point_y + side_length - self.offset,
fill=self.interior_fill_color,
outline=self.outline_fill_color,
stipple=Tools.stipple,
width=self.scribble_width, tags="scribble")
else: # modify the rectangle with mouse position.
self.active_canvas.coords(self.scribble, self.initial_click[0] + self.offset,
self.initial_click[1] + self.offset,
final_point_x + side_length - self.offset,
final_point_y + side_length - self.offset)
self.coords_list = [(self.initial_click[0] + self.offset,
self.initial_click[1] + self.offset),
(final_point_x + side_length - self.offset,
final_point_y + side_length - self.offset)]
elif Tools.current_tool == 6: # oval
# self.active_canvas.delete(self.scribble)
final_point_x, final_point_y = self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(
event.y)
# Formula for circle.
if Tools.shape_constraint:
side_length = max((final_point_x - self.initial_click[0]), (final_point_y - self.initial_click[1]))
final_point_x, final_point_y = self.initial_click[0], self.initial_click[1]
else:
side_length = 0
if not self.scribble:
self.scribble = self.active_canvas.create_oval(self.initial_click[0] - side_length,
self.initial_click[1] - side_length,
final_point_x + side_length,
final_point_y + side_length,
fill=self.interior_fill_color,
outline=self.outline_fill_color,
width=self.scribble_width, tags="scribble")
else:
self.active_canvas.coords(self.scribble, self.initial_click[0] - side_length,
self.initial_click[1] - side_length,
final_point_x + side_length,
final_point_y + side_length)
self.coords_list = [(self.initial_click[0] - side_length, self.initial_click[1] - side_length),
(final_point_x + side_length, final_point_y + side_length)]
self.scribble_list.append(self.scribble) # Appends the raw mouse coordinates to the scribble_list.
self.last_x, self.last_y = self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y)
@check_if_overlay
def draw_release(self, event=0, text=None, project_override=False, image_sized_coordinates=None):
"""
Called on Mouse release. Fetches the raw coordinates, cleans it scales it to the maximized and windowed size and plots the shape.
The coordinates and width are also scaled to match the actual image before saving the graphics_cache object to the dictionary.
Args:
event(tkinter.Event):Mouse click release event.
text(str,optional): Text, if using the text insert tool.
project_override (bool): True if the method is being called from a loaded project protocol. Default False.
image_sized_coordinates (list|tuple,optional):Pre-generated coordinates relative to the actual image size.
Returns:
None
"""
# p49= proxy tag with 49 as the id of its master, linking them to delete both at same time.
# m1=maximized master tag with image index 1
# w1=windowed proxy tag with image index 1
# Graphics items gets drawn in max window size,even if drawn in windowed mode.
if self.ready_to_draw or Tools.current_tool == 8: # text tool
current_tool = Tools.current_tool
if len(self.coords_list) > 1 or (Tools.current_tool == 8 and text) or project_override:
item = None
self.active_canvas.delete("scribble")
self.scribble = None
if self.app.maximized_mode or project_override:
released_coordinates = self.coords_list
else:
released_coordinates = self.scale_coordinates(scale_mode="+") # upscale the cords to be maxed
if self.app.display_mode == "default":
pass
elif self.app.display_mode == "actual":
released_coordinates = self.get_dynamic_coordinates(coordinate_list=released_coordinates,
mode="actual")
elif self.app.display_mode == "zoomed":
released_coordinates = self.get_dynamic_coordinates(coordinate_list=released_coordinates,
mode="zoomed")
tags = (f"m{self.index}", "master", "2d")
if current_tool == 2: # brush
if Tools.decimate_factor != 0:
released_coordinates = self.peucker_algorithm(released_coordinates, Tools.decimate_factor)
current_stroke = self.active_canvas.create_line(released_coordinates, fill=Tools.fill_color,
width=Tools.stroke_width,
joinstyle="round", capstyle="round",
stipple=Tools.stipple, tags=tags)
elif current_tool == 4: # line
current_stroke = self.active_canvas.create_line(released_coordinates, fill=Tools.fill_color,
width=Tools.stroke_width,
joinstyle="round", capstyle=Tools.endcap,
stipple=Tools.stipple, tags=tags)
elif current_tool == 5: # rectangle
current_stroke = self.active_canvas.create_rectangle(released_coordinates,
fill=self.interior_fill_color,
outline=self.outline_fill_color,
width=Tools.stroke_width,
stipple=Tools.stipple,
tags=tags)
elif current_tool == 6: # oval
current_stroke = self.active_canvas.create_oval(released_coordinates,
fill=self.interior_fill_color,
outline=self.outline_fill_color,
width=Tools.stroke_width,
tags=tags)
elif current_tool == 8: # text
item = "text"
selection_color = self.get_selection_color(hex_color=Tools.fill_color)
if Tools.stipple:
selection_color = "#ecff16"
tags = (f"m{self.index}", "master", "text")
if isinstance(released_coordinates, list): # text coordinates are saved as tuples.
# Failsafe for slow systems.
if released_coordinates:
released_coordinates = released_coordinates[0]
else:
self.app.error_prompt.display_error_prompt(error_msg="Text insertion failed,Try Again.",
priority=2)
self.flush_mouse_events()
return
current_stroke = self.active_canvas.create_text(released_coordinates, text=text,
fill=Tools.fill_color,
activefill=selection_color,
font=(TextInsertWindow.selected_font,
TextInsertWindow.selected_font_size),
tags=tags, anchor="sw")
# Graphic object gets created here.
# Save time reusing image size coords from the project file, if not called from project calculate the coords.
if not image_sized_coordinates:
image_sized_coordinates = self.coordinates_to_image_size(released_coordinates, item=item)
self.app.graphics_data[self.index][current_stroke] = GraphicsCache(
coordinates=image_sized_coordinates,
width=self.width_to_image_size(stroke_width=Tools.stroke_width, item="width"),
fill_color=Tools.fill_color,
shape_fill=Tools.shape_fill,
joinstyle="round",
capstyle=Tools.endcap,
tags=tags,
interior_fill_color=self.interior_fill_color,
outline_fill_color=self.outline_fill_color,
tool=Tools.current_tool,
stipple=Tools.stipple,
text=text,
font_name=TextInsertWindow.selected_font,
font_file=TextInsertWindow.selected_font_file,
font_size=self.width_to_image_size(TextInsertWindow.selected_font_size, item="font"))
if current_tool == 8:
# p is for parent, p12 means parent stroke id is 12
proxy_tags = (f"p{current_stroke}", f"w{self.index}", "text", "proxy")
else:
proxy_tags = (f"p{current_stroke}", f"w{self.index}", "2d", "proxy")
self.create_proxy_annotation(tags=proxy_tags, text=text, project_override=project_override)
# hide large size strokes in windowed mode.
if not self.app.maximized_mode:
self.active_canvas.itemconfig(current_stroke, state="hidden")
else:
if self.app.display_mode == "actual":
self.scale_item_to_current_scale(item_id=current_stroke, mode="actual")
elif self.app.display_mode == "zoomed":
self.scale_item_to_current_scale(item_id=current_stroke, mode="zoomed")
self.flush_mouse_events()
@check_if_overlay
def erase_graphic(self, event=None, radius=0, current_item=None):
"""
Removes an item from the canvas and deletes the object from the dictionaries.
Args:
event (tkinter.Event): Mouse event.
radius (int): Search radius.
current_item(int,optional): Item id of the element in the canvas to remove.
Returns:
None
"""
# If True delete any given element irrespective of type.Default False.
if Tools.stroke_width == 50 and Tools.current_tool == 3: # Maxed out. and eraser tool
self.wipe_current_annotations()
delete_mode = False
OVERLAY_IMAGE_TAG = "overlay_img"
if not current_item:
current_item = self.find_item(event, radius)
else:
current_item = current_item
delete_mode = True
tag = self.active_canvas.gettags(current_item)
tag_id = tag[0]
# Deletes the 2d drawing along with all stored data. if delete_mode delete any element irrespective of tags.
if "2d" in tag or delete_mode:
if self.app.maximized_mode:
self.active_canvas.delete(current_item) # The selected item.
del self.app.graphics_data[self.index][current_item]
proxy_id = self.active_canvas.find_withtag(f"p{current_item}")[0]
del self.app.proxy_data[self.index][proxy_id]
self.active_canvas.delete(f"p{current_item}") # proxy of the parent item.
else: # delete the rescaled proxy strokes, and remove parent from graphic dict as well as delete from screen.
self.active_canvas.delete(current_item) # removes the proxy
self.active_canvas.delete(int(tag_id[1:])) # eg p101
del self.app.proxy_data[self.index][current_item] # deletes proxy item from dict
del self.app.graphics_data[self.index][int(tag_id[1:])] # removes the p
if delete_mode:
self.remove_text_item_selection()
def delete_item(self, event=None):
"""
Calls the erase_graphic method with an item id passed.
Args:
event (tkinter.Event): Keypress event.
Returns:
None
"""
if self.selected_text_item:
self.erase_graphic(current_item=self.selected_text_item)
def wipe_current_annotations(self):
"""
Wipes all annotations (including text) drawn on the currently loaded image.
Returns:
"""
master_items_to_delete = list(self.app.graphics_data[self.index].keys())
for item in master_items_to_delete:
self.active_canvas.delete(item)
del self.app.graphics_data[self.index][item] # removes the p
proxy_items_to_delete = list(self.app.proxy_data[self.index].keys())
for item in proxy_items_to_delete: # Clearing proxy annotations
self.active_canvas.delete(item)
del self.app.proxy_data[self.index][item]
self.remove_text_item_selection()
def flush_mouse_events(self):
"""
Clears the stored mouse events and temporary coordinates, and sets the state of ready_to_draw to False.
Returns:
None
"""
self.scribble_list = []
self.coords_list = []
self.initial_click = None
self.is_text_repositioning = False
self.ready_to_draw = False
def create_proxy_annotation(self, tags, fill_color=None,
coordinates=None, width=None,
joinstyle="round", stipple=None,
capstyle=None, text=None, tool=None, project_override=False):
"""
Creates a proxy version of the drawing to be displayed on the windowed mode.
Args:
tags:
fill_color:
coordinates:
width:
joinstyle:
stipple:
capstyle:
text:
tool:
project_override (bool): True if method being called from load project protocol.
Returns:
None
"""
if not coordinates:
coordinates = self.coords_list
if not width:
width = Tools.stroke_width
if not capstyle:
capstyle = Tools.endcap
if not tool:
tool = Tools.current_tool
if not fill_color:
fill_color = Tools.fill_color
if not stipple:
stipple = Tools.stipple
if self.app.maximized_mode or project_override:
scaled_coords = self.scale_coordinates(scale_mode="-")
else:
scaled_coords = self.coords_list
if self.app.display_mode == "actual":
scaled_coords = self.get_dynamic_coordinates(coordinate_list=scaled_coords, mode="actual")
elif self.app.display_mode == "zoomed":
scaled_coords = self.get_dynamic_coordinates(coordinate_list=scaled_coords, mode="zoomed")
if Tools.decimate_factor != 0:
scaled_coords = self.peucker_algorithm(scaled_coords, Tools.decimate_factor)
if tool == 2: # Brush
proxy_drawing = self.active_canvas.create_line(scaled_coords, fill=fill_color
, width=self.get_proxy_stroke_width(),
joinstyle="round", capstyle="round", stipple=stipple,
tags=tags)
elif tool == 4: # line
proxy_drawing = self.active_canvas.create_line(scaled_coords, fill=fill_color
, width=self.get_proxy_stroke_width(),
joinstyle=joinstyle, capstyle=capstyle, stipple=stipple,
tags=tags)
elif tool == 5: # rectangle
proxy_drawing = self.active_canvas.create_rectangle(scaled_coords, fill=self.interior_fill_color,
outline=self.outline_fill_color, stipple=stipple,
width=self.get_proxy_stroke_width(), tags=tags)
elif tool == 6: # oval
proxy_drawing = self.active_canvas.create_oval(scaled_coords, fill=self.interior_fill_color,
outline=self.outline_fill_color,
width=self.get_proxy_stroke_width(), tags=tags)
elif tool == 8: # Insert text
selection_color = self.get_selection_color(hex_color=Tools.fill_color)
if Tools.stipple:
selection_color = "#ecff16"
proxy_drawing = self.active_canvas.create_text(scaled_coords[0], text=text, fill=Tools.fill_color,
activefill=selection_color,
font=(TextInsertWindow.selected_font,
self.get_proxy_stroke_width(
TextInsertWindow.selected_font_size,
is_font_size=True)),
tags=tags, anchor="sw")
self.app.proxy_data[self.index][proxy_drawing] = GraphicsCache(coordinates=scaled_coords,
fill_color=Tools.fill_color,
width=self.get_proxy_stroke_width(),
joinstyle="round",
capstyle=Tools.endcap,
shape_fill=Tools.shape_fill,
tags=tags,
interior_fill_color=self.interior_fill_color,
outline_fill_color=self.outline_fill_color,
tool=Tools.current_tool,
stipple=Tools.stipple,
text=text,
font_name=TextInsertWindow.selected_font,
font_file=TextInsertWindow.selected_font_file,
font_size=self.get_proxy_stroke_width(
TextInsertWindow.selected_font_size,
is_font_size=True))
if self.app.maximized_mode:
self.active_canvas.itemconfig(proxy_drawing, state="hidden")
else: # If the image is zoomed , match the width and coordinates to match the zoomed image.
if self.app.display_mode == "actual":
self.scale_item_to_current_scale(item_id=proxy_drawing, mode="actual")
elif self.app.display_mode == "zoomed":
self.scale_item_to_current_scale(item_id=proxy_drawing, mode="zoomed")
def find_item(self, event, radius=0, filter=None):
"""
Returns the canvas item closest to the Mouse Click event.
Args:
event (tkinter.Event): Mouse click event
radius (int): Radius to search for. Default 0
filter (str): Specific item to look for. eg- "text"
Returns:
int: Id of the canvas item.
"""
selected_item = self.active_canvas.find_closest(self.active_canvas.canvasx(event.x),
self.active_canvas.canvasy(event.y),
halo=radius)[0]
if not filter:
# self.selected_text_item = None
return selected_item
elif filter == "text":
tags = self.active_canvas.gettags(selected_item)
if filter in tags:
self.selected_text_item = selected_item
return selected_item
else:
self.selected_text_item = None
def set_text_drag_offset(self, event):
"""
Sets the initial position of the text item before repositioning.
Args:
event(tkinter.Event): Mouse click event.
Returns:
None
"""
if self.app.display_mode == "default":
self.ready_to_draw = False
# if text item is clicked get its bounding box.
if self.find_item(event, filter="text"):
self.selection_click_position = self.active_canvas.canvasx(event.x), self.active_canvas.canvasy(event.y)
current_item_bbox = self.active_canvas.bbox(self.selected_text_item)
# Since the anchor is "sw" we use x1 and y2
self.text_offset_x = self.selection_click_position[0] - current_item_bbox[0] # x1
self.text_offset_y = self.selection_click_position[1] - current_item_bbox[3] # y2
return
def reposition_text_item(self, event, constraint=False):
"""
Reposition the text item based on coordinates from the mouse drag event.
Args:
event (tkinter.Event): Mouse Drag event.
constraint (bool): True constraints the text to an axis. False allows free repositioning.
Returns:
None
"""
if self.selected_text_item:
self.is_text_repositioning = True
self.hide_text_item_selection_border()
# Offset so that text anchor won't snap to mouse position.
current_mousex = self.active_canvas.canvasx(event.x)
current_mousey = self.active_canvas.canvasx(event.y)
new_x = current_mousex - self.text_offset_x
new_y = current_mousey - self.text_offset_y
if constraint:
dx = current_mousex - self.selection_click_position[0]
dy = current_mousey - self.selection_click_position[1]
if self.x_axis_constraint == None: # None means no X or Y.
if abs(dx) > abs(dy):
self.x_axis_constraint = True
else:
self.x_axis_constraint = False
if self.x_axis_constraint:
new_y = self.selection_click_position[1] - self.text_offset_y
self.active_canvas.coords(self.selected_text_item, (new_x, new_y))
else:
new_x = self.selection_click_position[0] - self.text_offset_x
self.active_canvas.coords(self.selected_text_item, (new_x, new_y))
else:
self.active_canvas.coords(self.selected_text_item, (new_x, new_y))
event.x = new_x
event.y = new_y
TextInsertWindow.stored_text_position = event
self.update_text_item_coords()
@check_if_overlay
def update_text_item_coords(self, ):
"""
Updates the text item coordinates in the data dictionaries after conversion.
Args:
Returns:
None
"""
if self.is_text_repositioning and self.app.display_mode == "default":
# Raw coordinates of current window mode.
moved_text_bbox = self.active_canvas.bbox(self.selected_text_item)
new_coords = moved_text_bbox[0], moved_text_bbox[3] # (x1,y2)
if self.app.maximized_mode:
proxy_id = self.active_canvas.find_withtag(f"p{self.selected_text_item}")[0]
new_proxy_coords = self.scale_coordinates(coordinate_list=new_coords,
scale_mode="-", scale_item="text")
self.active_canvas.coords(proxy_id, new_proxy_coords)
# Converting the max coordinates to image scale.
image_sized_coords = self.coordinates_to_image_size(coordinate_list=new_coords, item="text")
self.app.graphics_data[self.index][self.selected_text_item].coordinates = image_sized_coords
# Updates the proxy with scaled down coordinates from max view.
self.app.proxy_data[self.index][proxy_id].coordinates = new_proxy_coords
else:
tag = self.active_canvas.gettags(self.selected_text_item)[0]
new_max_coords = self.scale_coordinates(coordinate_list=new_coords,
scale_mode="+", scale_item="text")
# Converting the max cords to proxy cords to get near pixel perfect accuracy.
new_proxy_coords = self.scale_coordinates(coordinate_list=new_max_coords,
scale_mode="-", scale_item="text")
self.active_canvas.coords(int(tag[1:]), new_max_coords)
# update the proxy data as is.
self.app.proxy_data[self.index][self.selected_text_item].coordinates = new_proxy_coords
# Converting the max coordinates to image scale.
image_sized_coords = self.coordinates_to_image_size(coordinate_list=new_max_coords, item="text")
self.app.graphics_data[self.index][int(tag[1:])].coordinates = image_sized_coords
# self.select_text_item(text_id=self.selected_text_item)
@check_if_overlay
def update_text_item_scale(self, value: float = None, increment: str = None):
"""
Updates the scale of the selected text item using the provided value.
Args:
value (float, optional): A multiplier number.
increment(str, optional):"+" adds +1 to the current scale, "-" subtracts -1 from the current scale., optional
Returns:
None
"""
MIN_TEXT_SIZE = -10
if self.selected_text_item:
if self.app.maximized_mode:
parent_id = self.selected_text_item
proxy_id = self.active_canvas.find_withtag(f"p{self.selected_text_item}")[0]
else:
proxy_id = self.selected_text_item
tag = self.active_canvas.gettags(self.selected_text_item)[0]
parent_id = int(tag[1:])
current_text_item_object = self.app.graphics_data[self.index][parent_id]
current_font_family = current_text_item_object.font_name