-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathadvanced_yaw_selector.py
More file actions
1712 lines (1411 loc) · 91.6 KB
/
advanced_yaw_selector.py
File metadata and controls
1712 lines (1411 loc) · 91.6 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
# advanced_yaw_selector.py
import tkinter as tk
from tkinter import ttk, messagebox
import math
import functools # For partial
from strings import S # グローバル文字列インスタンスをインポート
from tooltip_utils import ToolTip
from constants import ( # このモジュール固有の定数をインポート
AYS_INITIAL_CANVAS_SIZE, AYS_MIN_CANVAS_DRAW_SIZE, AYS_DEBOUNCE_DELAY_MS,
AYS_MIN_FOV_DEGREES, AYS_MAX_FOV_DEGREES, AYS_DEFAULT_FOV_INTERNAL,
AYS_MAX_YAW_DIVISIONS, AYS_DEFAULT_YAW_DIVISIONS_P0_INTERNAL,
AYS_DEFAULT_YAW_DIVISIONS_OTHER_INTERNAL, AYS_DEFAULT_PITCHES_STR,
AYS_PREDEFINED_PITCH_ADD_VALUES, AYS_MAX_PITCH_ENTRIES,
AYS_COLOR_CANVAS_BG, AYS_COLOR_TEXT, AYS_FOV_RING_COLORS_BASE,
AYS_C_FOV_BOUNDARY_LINE_COLOR, AYS_COLOR_CENTER_TEXT_BG,
AYS_COLOR_PITCHED_EQUATOR, AYS_FAR_SIDE_LINE_COLOR,
AYS_FAR_SIDE_FILL_COLOR, AYS_BACKFACE_FILL_COLOR, AYS_BACKFACE_STIPPLE,
AYS_BUTTON_NORMAL_BG, AYS_LABEL_TEXT_COLOR,
AYS_COLOR_SECTOR_DESELECTED_FILL, AYS_COLOR_SECTOR_DESELECTED_OUTLINE,
AYS_CANVAS_HELP_TEXT_COLOR
)
# Constants for canvas interaction (consider moving to constants.py if widely used)
AYS_MOUSE_DRAG_SENSITIVITY = 200.0
AYS_MAX_VIEW_X_ROTATION_FACTOR = 0.999 # Prevents gimbal lock visualization issues
AYS_CLICKABLE_LABEL_TAG = "clickable_label_surface"
class AdvancedYawSelector(tk.Frame):
def __init__(self, master, initial_pitches_str=AYS_DEFAULT_PITCHES_STR,
on_selection_change_callback=None, **kwargs):
super().__init__(master, **kwargs)
self.on_selection_change_callback = on_selection_change_callback
self.current_pitch_key_var = tk.StringVar()
self.current_yaw_divisions_var = tk.IntVar()
self.selected_pitch_value_var = tk.DoubleVar()
self.selected_pitch_entry_var = tk.StringVar()
self.selected_pitch_fov_var = tk.DoubleVar(value=AYS_DEFAULT_FOV_INTERNAL)
self.selected_pitch_fov_entry_var = tk.StringVar()
self.pitch_to_add_var = tk.StringVar()
self.pitch_settings = {} # Stores {"pitch_key": {"yaws": [...], "divisions": N, "fov": F}, ...}
self.yaw_to_fixed_ring_assignment = {} # Stores {"pitch_key": {yaw_angle: {"color": ..., "layer": ...}}}
self.yaw_buttons = [] # Stores {"button": widget, "yaw": angle}
self.global_rotation_y_rad = 0.0
self.global_rotation_x_rad = math.pi / 6 # Initial tilt
self.last_mouse_x = 0
self.last_mouse_y = 0
self.is_dragging = False
self._slider_update_active = False # Flag to prevent slider event recursion
self._entry_update_active = False # Flag to prevent entry event recursion
self._fov_slider_update_active = False
self._fov_entry_update_active = False
self._internal_update_active = False # General flag for internal state updates
self._configure_timer_id = None # For debouncing canvas resize
self._pitch_slider_debounce_timer_id = None # For debouncing pitch slider drags
self._fov_slider_debounce_timer_id = None # For debouncing FOV slider drags
self.canvas_actual_width = AYS_INITIAL_CANVAS_SIZE
self.canvas_actual_height = AYS_INITIAL_CANVAS_SIZE
self.controls_enabled = True
self.tooltips = [] # Managed tooltips
self._setup_ui_layout()
# Bind configure event to the canvas for redraws on resize
if hasattr(self, 'yaw_canvas') and self.yaw_canvas: # Ensure canvas exists
self.yaw_canvas.bind("<Configure>", self._on_canvas_configure)
self._parse_and_set_initial_pitches(initial_pitches_str, initial_load=True)
self._select_initial_pitch(initial_load=True)
def add_tooltip_managed(self, widget, text_key, *args, **kwargs):
text = S.get(text_key, *args, **kwargs) if text_key else ""
tip = ToolTip(widget, text)
self.tooltips.append({"instance": tip, "key": text_key, "args": args, "kwargs": kwargs})
return tip
def update_all_tooltips_text(self):
for tip_info in self.tooltips:
new_text = S.get(tip_info["key"], *tip_info["args"], **tip_info["kwargs"]) if tip_info["key"] else ""
tip_info["instance"].update_text(new_text)
def update_ui_texts_for_language_switch(self):
self.add_pitch_button.config(text=S.get("ays_add_pitch_button_label"))
self.remove_pitch_button.config(text=S.get("ays_remove_pitch_button_label"))
self.output_pitch_list_label.config(text=S.get("ays_output_pitch_list_label"))
self.pitch_reset_button.config(text=S.get("ays_pitch_reset_button_label"))
self.fov_reset_button.config(text=S.get("ays_fov_reset_button_label"))
self.yaw_selection_title_label.config(text=S.get("ays_yaw_selection_label"))
self.pitch_adjust_title_label.config(text=S.get("ays_pitch_adjust_label_format"))
self.fov_adjust_title_label.config(text=S.get("ays_fov_adjust_label_format", min_fov=AYS_MIN_FOV_DEGREES, max_fov=AYS_MAX_FOV_DEGREES))
self.yaw_divisions_title_label.config(text=S.get("ays_yaw_divisions_label_format", max_divisions=AYS_MAX_YAW_DIVISIONS))
self.update_all_tooltips_text() # This will re-fetch and apply tooltip texts
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
def _setup_ui_layout(self):
main_paned_window = tk.PanedWindow(self, orient=tk.HORIZONTAL, sashrelief=tk.RAISED, sashwidth=6)
main_paned_window.pack(fill=tk.BOTH, expand=True)
# --- Left Frame (Pitch Controls & Yaw Buttons) ---
left_frame = tk.Frame(main_paned_window, bd=1, relief=tk.SUNKEN)
main_paned_window.add(left_frame, width=220, minsize=200, stretch="never")
pitch_control_frame = tk.Frame(left_frame)
pitch_control_frame.pack(fill=tk.X, padx=5, pady=(5,2))
self.pitch_to_add_combo = ttk.Combobox(pitch_control_frame, textvariable=self.pitch_to_add_var,
values=[str(p) for p in AYS_PREDEFINED_PITCH_ADD_VALUES],
width=5, state="readonly")
self.pitch_to_add_combo.pack(side=tk.LEFT, padx=(0,2))
if AYS_PREDEFINED_PITCH_ADD_VALUES: # Ensure list is not empty
self.pitch_to_add_combo.set("0") # Default selection
self.add_tooltip_managed(self.pitch_to_add_combo, "ays_pitch_to_add_combo_tooltip")
self.add_pitch_button = tk.Button(pitch_control_frame, text=S.get("ays_add_pitch_button_label"), command=self._add_pitch_from_combo, width=4)
self.add_pitch_button.pack(side=tk.LEFT, padx=(0,2))
self.add_tooltip_managed(self.add_pitch_button, "ays_add_pitch_button_tooltip_format", max_entries=AYS_MAX_PITCH_ENTRIES)
self.remove_pitch_button = tk.Button(pitch_control_frame, text=S.get("ays_remove_pitch_button_label"), command=self._remove_selected_pitch, width=4)
self.remove_pitch_button.pack(side=tk.LEFT)
self.add_tooltip_managed(self.remove_pitch_button, "ays_remove_pitch_button_tooltip")
self.output_pitch_list_label = tk.Label(left_frame, text=S.get("ays_output_pitch_list_label"))
self.output_pitch_list_label.pack(anchor="w", padx=5, pady=(5,0))
self.pitch_listbox = tk.Listbox(left_frame, exportselection=False, height=AYS_MAX_PITCH_ENTRIES)
self.pitch_listbox.pack(fill=tk.X, padx=5, pady=(2,5))
self.pitch_listbox.bind("<<ListboxSelect>>", lambda event: self.on_pitch_selected(event, initial_load=False))
self.add_tooltip_managed(self.pitch_listbox, "ays_pitch_listbox_tooltip")
reset_buttons_control_frame_left = tk.Frame(left_frame)
reset_buttons_control_frame_left.pack(pady=(5,2), padx=5, fill=tk.X)
self.pitch_reset_button = tk.Button(reset_buttons_control_frame_left, text=S.get("ays_pitch_reset_button_label"),
command=lambda: self.set_pitches_externally(AYS_DEFAULT_PITCHES_STR))
self.pitch_reset_button.pack(side=tk.LEFT, padx=2, expand=True, fill=tk.X)
self.add_tooltip_managed(self.pitch_reset_button, "ays_pitch_reset_button_tooltip_format", default_pitches=AYS_DEFAULT_PITCHES_STR)
self.fov_reset_button = tk.Button(reset_buttons_control_frame_left, text=S.get("ays_fov_reset_button_label"),
command=self.reset_current_pitch_fov)
self.fov_reset_button.pack(side=tk.LEFT, padx=2, expand=True, fill=tk.X)
self.add_tooltip_managed(self.fov_reset_button, "ays_fov_reset_button_tooltip_format", default_fov=AYS_DEFAULT_FOV_INTERNAL)
self.yaw_selection_title_label = tk.Label(left_frame, text=S.get("ays_yaw_selection_label"))
self.yaw_selection_title_label.pack(anchor="w", padx=5, pady=(5,0))
self.yaw_buttons_outer_frame = tk.Frame(left_frame) # For consistent padding and centering
self.yaw_buttons_outer_frame.pack(pady=(0,5), padx=5, fill=tk.X, expand=True)
self.yaw_buttons_frame = tk.Frame(self.yaw_buttons_outer_frame) # Actual grid for buttons
self.yaw_buttons_frame.pack(anchor="n") # Center the grid of buttons
self.add_tooltip_managed(self.yaw_buttons_outer_frame, "ays_yaw_buttons_tooltip")
# --- Right Frame (Canvas & Adjustment Controls) ---
right_container_frame = tk.Frame(main_paned_window)
main_paned_window.add(right_container_frame, stretch="always", minsize=300)
options_area = tk.Frame(right_container_frame)
options_area.pack(fill=tk.X, pady=(5,0), padx=5)
self.pitch_adjust_title_label = tk.Label(options_area, text=S.get("ays_pitch_adjust_label_format"))
self.pitch_adjust_title_label.grid(row=0, column=0, sticky="w", pady=2)
pitch_adjust_frame = tk.Frame(options_area)
pitch_adjust_frame.grid(row=0, column=1, sticky="ew", padx=5, pady=2)
self.selected_pitch_slider = tk.Scale(pitch_adjust_frame, from_=-90, to=90, orient=tk.HORIZONTAL,
variable=self.selected_pitch_value_var, resolution=0.1,
length=120, command=self._on_selected_pitch_slider_drag,
state=tk.DISABLED, showvalue=0)
self.selected_pitch_slider.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.selected_pitch_slider.bind("<ButtonRelease-1>", self._on_selected_pitch_slider_release)
self.add_tooltip_managed(self.selected_pitch_slider, "ays_pitch_slider_tooltip")
self.selected_pitch_entry = tk.Entry(pitch_adjust_frame, textvariable=self.selected_pitch_entry_var, width=7, justify='right', state=tk.DISABLED)
self.selected_pitch_entry.pack(side=tk.LEFT, padx=(5,0))
self.selected_pitch_entry.bind("<Return>", self._on_selected_pitch_entry_confirm)
self.selected_pitch_entry.bind("<FocusOut>", self._on_selected_pitch_entry_confirm)
self.add_tooltip_managed(self.selected_pitch_entry, "ays_pitch_entry_tooltip")
self.fov_adjust_title_label = tk.Label(options_area, text=S.get("ays_fov_adjust_label_format", min_fov=AYS_MIN_FOV_DEGREES, max_fov=AYS_MAX_FOV_DEGREES))
self.fov_adjust_title_label.grid(row=1, column=0, sticky="w", pady=2)
fov_adjust_frame = tk.Frame(options_area)
fov_adjust_frame.grid(row=1, column=1, sticky="ew", padx=5, pady=2)
self.selected_pitch_fov_slider = tk.Scale(fov_adjust_frame, from_=AYS_MIN_FOV_DEGREES, to=AYS_MAX_FOV_DEGREES, orient=tk.HORIZONTAL,
variable=self.selected_pitch_fov_var, length=120, resolution=0.1,
command=self._on_selected_fov_slider_drag, state=tk.DISABLED, showvalue=0)
self.selected_pitch_fov_slider.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.selected_pitch_fov_slider.bind("<ButtonRelease-1>", self._on_selected_fov_slider_release)
self.add_tooltip_managed(self.selected_pitch_fov_slider, "ays_fov_slider_tooltip_format", min_fov=AYS_MIN_FOV_DEGREES, max_fov=AYS_MAX_FOV_DEGREES)
self.selected_pitch_fov_entry = tk.Entry(fov_adjust_frame, textvariable=self.selected_pitch_fov_entry_var, width=7, justify='right', state=tk.DISABLED)
self.selected_pitch_fov_entry.pack(side=tk.LEFT, padx=(5,0))
self.selected_pitch_fov_entry.bind("<Return>", self._on_selected_fov_entry_confirm)
self.selected_pitch_fov_entry.bind("<FocusOut>", self._on_selected_fov_entry_confirm)
self.add_tooltip_managed(self.selected_pitch_fov_entry, "ays_fov_entry_tooltip")
self.yaw_divisions_title_label = tk.Label(options_area, text=S.get("ays_yaw_divisions_label_format", max_divisions=AYS_MAX_YAW_DIVISIONS))
self.yaw_divisions_title_label.grid(row=2, column=0, sticky="w", pady=2)
self.yaw_divisions_scale = tk.Scale(options_area, from_=1, to=AYS_MAX_YAW_DIVISIONS, orient=tk.HORIZONTAL,
variable=self.current_yaw_divisions_var, length=150, resolution=1,
command=self._on_fov_or_divisions_changed, state=tk.DISABLED)
self.yaw_divisions_scale.grid(row=2, column=1, sticky="ew", padx=5, pady=2)
self.add_tooltip_managed(self.yaw_divisions_scale, "ays_yaw_divisions_scale_tooltip")
options_area.columnconfigure(1, weight=1) # Ensure adjustment controls expand
self.yaw_canvas = tk.Canvas(right_container_frame, width=AYS_INITIAL_CANVAS_SIZE, height=AYS_INITIAL_CANVAS_SIZE,
bg=AYS_COLOR_CANVAS_BG, relief=tk.SUNKEN, borderwidth=1)
self.yaw_canvas.pack(pady=(5,5), padx=5, expand=True, fill=tk.BOTH)
self.yaw_canvas.bind("<ButtonPress-1>", self.on_mouse_press)
self.yaw_canvas.bind("<B1-Motion>", self.on_mouse_motion)
self.yaw_canvas.bind("<ButtonRelease-1>", self.on_mouse_release)
self.yaw_canvas.bind("<Button-3>", lambda event: self._handle_canvas_right_click(event)) # For right-click selection
def on_mouse_press(self, event):
if not self.controls_enabled:
return
# Check if the click is on a label surface; if so, don't start dragging.
# This allows right-click on labels to pass through to _on_label_right_click.
item = self.yaw_canvas.find_withtag(tk.CURRENT)
if item:
tags = self.yaw_canvas.gettags(item[0])
if AYS_CLICKABLE_LABEL_TAG in tags:
return # Let label-specific bindings handle this
self.is_dragging = True
self.last_mouse_x, self.last_mouse_y = event.x, event.y
def on_mouse_motion(self, event):
if not self.controls_enabled or not self.is_dragging:
return
dx = event.x - self.last_mouse_x
dy = event.y - self.last_mouse_y
self.global_rotation_y_rad = (self.global_rotation_y_rad + dx / AYS_MOUSE_DRAG_SENSITIVITY) % (2 * math.pi)
self.global_rotation_x_rad = max(
-math.pi / 2 * AYS_MAX_VIEW_X_ROTATION_FACTOR,
min(math.pi / 2 * AYS_MAX_VIEW_X_ROTATION_FACTOR, self.global_rotation_x_rad - dy / AYS_MOUSE_DRAG_SENSITIVITY)
)
self.last_mouse_x, self.last_mouse_y = event.x, event.y
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
def on_mouse_release(self, event): # pylint: disable=unused-argument
if not self.controls_enabled:
return
self.is_dragging = False
def _on_canvas_configure(self, event):
new_width = event.width
new_height = event.height
# Basic check, drawing might still occur if one dim is small but other is large.
if new_width < AYS_MIN_CANVAS_DRAW_SIZE or new_height < AYS_MIN_CANVAS_DRAW_SIZE:
# Optionally, you could clear the canvas or show a "too small" message here
pass # Drawing will be handled by draw_yaw_selector which checks size again
self.canvas_actual_width = new_width
self.canvas_actual_height = new_height
if self._configure_timer_id is not None:
self.after_cancel(self._configure_timer_id)
self._configure_timer_id = self.after(50, self.draw_yaw_selector) # Debounce redraw
def _select_initial_pitch(self, initial_load=False):
if self.pitch_listbox.size() == 0:
self.current_pitch_key_var.set("")
self.selected_pitch_slider.config(state=tk.DISABLED)
self.selected_pitch_entry.config(state=tk.DISABLED, textvariable=tk.StringVar(value="")) # Reset entry
self.selected_pitch_fov_slider.config(state=tk.DISABLED)
self.selected_pitch_fov_entry.config(state=tk.DISABLED, textvariable=tk.StringVar(value="")) # Reset entry
self.yaw_divisions_scale.config(state=tk.DISABLED)
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
self._create_or_update_yaw_buttons()
if self.on_selection_change_callback and not initial_load:
self.on_selection_change_callback()
return
# Try to select "0.0°" if it exists
found_zero_pitch_idx = -1
for i in range(self.pitch_listbox.size()):
if self.pitch_listbox.get(i) == "0.0°":
found_zero_pitch_idx = i
break
target_idx = 0 # Default to first item
if found_zero_pitch_idx != -1:
target_idx = found_zero_pitch_idx
elif self.pitch_listbox.size() > 0: # if 0.0 not found, but list is not empty
pass # target_idx remains 0
else: # List is empty, should have been caught by the first check
return
if target_idx >= self.pitch_listbox.size() and self.pitch_listbox.size() > 0: # Safety for index
target_idx = 0
if self.pitch_listbox.size() > 0 :
self.pitch_listbox.selection_clear(0, tk.END)
self.pitch_listbox.selection_set(target_idx)
self.pitch_listbox.activate(target_idx)
self.pitch_listbox.see(target_idx)
self.on_pitch_selected(None, initial_load=initial_load)
else: # Should not happen if first check is robust
self.current_pitch_key_var.set("")
self.selected_pitch_entry_var.set("")
self.selected_pitch_fov_entry_var.set("")
def _on_selected_pitch_slider_drag(self, new_val_str):
if self._entry_update_active or self._internal_update_active:
return
try:
val = float(new_val_str)
self.selected_pitch_entry_var.set(f"{val:.1f}") # Update entry during drag
if self._pitch_slider_debounce_timer_id is not None:
self.after_cancel(self._pitch_slider_debounce_timer_id)
self._pitch_slider_debounce_timer_id = self.after(
AYS_DEBOUNCE_DELAY_MS, lambda v=val: self._perform_pitch_update_after_debounce(v)
)
except ValueError:
pass # Ignore if conversion fails during drag
def _perform_pitch_update_after_debounce(self, value_from_slider):
self._pitch_slider_debounce_timer_id = None # Clear timer ID
if self._slider_update_active or self._entry_update_active or self._internal_update_active:
return
# This is where the actual update logic for dragging happens (if not on release)
self._process_pitch_change(value_from_slider)
def _on_selected_pitch_slider_release(self, event=None): # pylint: disable=unused-argument
if self._entry_update_active or self._internal_update_active:
return
# Cancel any pending debounce timer from dragging
if self._pitch_slider_debounce_timer_id is not None:
self.after_cancel(self._pitch_slider_debounce_timer_id)
self._pitch_slider_debounce_timer_id = None
self._slider_update_active = True
try:
new_val = self.selected_pitch_value_var.get()
# Snap to whole number if very close
snapped_val = round(new_val)
if abs(new_val - snapped_val) < 0.25: # Threshold for snapping
new_val = float(snapped_val)
self.selected_pitch_value_var.set(new_val) # Update slider's var
self.selected_pitch_entry_var.set(f"{new_val:.1f}")
self._process_pitch_change(new_val)
except ValueError:
# Restore entry if something went wrong with var.get()
self.selected_pitch_entry_var.set(f"{self.selected_pitch_value_var.get():.1f}")
finally:
self._slider_update_active = False
def _on_selected_fov_slider_drag(self, new_val_str):
if self._fov_entry_update_active or self._internal_update_active:
return
try:
val = float(new_val_str)
self.selected_pitch_fov_entry_var.set(f"{val:.1f}")
if self._fov_slider_debounce_timer_id is not None:
self.after_cancel(self._fov_slider_debounce_timer_id)
self._fov_slider_debounce_timer_id = self.after(
AYS_DEBOUNCE_DELAY_MS, lambda v=val: self._perform_fov_update_after_debounce(v)
)
except ValueError:
pass
def _perform_fov_update_after_debounce(self, value_from_slider):
self._fov_slider_debounce_timer_id = None
if self._fov_slider_update_active or self._fov_entry_update_active or self._internal_update_active:
return
corrected_value = max(AYS_MIN_FOV_DEGREES, min(value_from_slider, AYS_MAX_FOV_DEGREES))
self._process_fov_change(corrected_value)
def _on_selected_fov_slider_release(self, event=None): # pylint: disable=unused-argument
if self._fov_entry_update_active or self._internal_update_active:
return
if self._fov_slider_debounce_timer_id is not None:
self.after_cancel(self._fov_slider_debounce_timer_id)
self._fov_slider_debounce_timer_id = None
self._fov_slider_update_active = True
try:
new_val = self.selected_pitch_fov_var.get()
snapped_val = round(new_val)
if abs(new_val - snapped_val) < 0.25 and AYS_MIN_FOV_DEGREES <= snapped_val <= AYS_MAX_FOV_DEGREES:
new_val = float(snapped_val)
new_val = max(AYS_MIN_FOV_DEGREES, min(new_val, AYS_MAX_FOV_DEGREES)) # Clamp
self.selected_pitch_fov_var.set(new_val)
self.selected_pitch_fov_entry_var.set(f"{new_val:.1f}")
self._process_fov_change(new_val)
except ValueError:
self.selected_pitch_fov_entry_var.set(f"{self.selected_pitch_fov_var.get():.1f}")
finally:
self._fov_slider_update_active = False
def _parse_and_set_initial_pitches(self, pitches_str, initial_load=False):
self._internal_update_active = True
parsed_valid_pitch_keys = set()
current_default_fov = AYS_DEFAULT_FOV_INTERNAL # Use the constant
if pitches_str and pitches_str.strip():
try:
temp_keys_list = []
for p_str_raw in pitches_str.split(','):
p_str = p_str_raw.strip()
if not p_str: continue # Skip empty elements
float_val = float(p_str)
if not (-90 <= float_val <= 90): continue # Skip out-of-range
key_candidate = f"{float_val:.1f}" # Normalize to one decimal place
if key_candidate not in temp_keys_list: # Maintain order of first appearance for unique values
temp_keys_list.append(key_candidate)
parsed_valid_pitch_keys = set(temp_keys_list) # Convert to set for efficient operations later
except ValueError:
messagebox.showerror(S.get("error_title"), S.get("ays_error_pitch_parse_invalid_string_format", pitches_str=pitches_str), parent=self)
self._internal_update_active = False
return # Exit if parsing fails
# Manage pitch limit
all_pitch_keys_to_manage = parsed_valid_pitch_keys
if len(all_pitch_keys_to_manage) > AYS_MAX_PITCH_ENTRIES:
# Sort by float value to ensure consistent truncation
sorted_keys = sorted(list(all_pitch_keys_to_manage), key=float)
all_pitch_keys_to_manage = set(sorted_keys[:AYS_MAX_PITCH_ENTRIES])
if initial_load: # Show warning only on initial load, not on programmatic reset
messagebox.showwarning(S.get("warning_title"), S.get("ays_warning_pitch_limit_exceeded_format", max_entries=AYS_MAX_PITCH_ENTRIES), parent=self)
# Ensure at least one pitch (0.0) if list becomes empty or was empty
if not all_pitch_keys_to_manage:
all_pitch_keys_to_manage.add("0.0")
# Update pitch_settings based on new keys
current_settings_keys = set(self.pitch_settings.keys())
keys_to_add = all_pitch_keys_to_manage - current_settings_keys
keys_to_remove = current_settings_keys - all_pitch_keys_to_manage
for k_rem in keys_to_remove:
if k_rem in self.pitch_settings:
del self.pitch_settings[k_rem]
if k_rem in self.yaw_to_fixed_ring_assignment:
del self.yaw_to_fixed_ring_assignment[k_rem]
for key_str in keys_to_add:
pitch_val_float = float(key_str)
is_zero_pitch = math.isclose(pitch_val_float, 0.0)
divisions = AYS_DEFAULT_YAW_DIVISIONS_P0_INTERNAL if is_zero_pitch else AYS_DEFAULT_YAW_DIVISIONS_OTHER_INTERNAL
yaws = [round(i * (360.0 / divisions), 2) for i in range(divisions)] if divisions > 0 else []
self.pitch_settings[key_str] = {"yaws": yaws, "divisions": divisions, "fov": current_default_fov}
self._update_pitch_listbox_from_settings(initial_load=initial_load)
self._internal_update_active = False
def _update_pitch_listbox_from_settings(self, initial_load=False):
self._internal_update_active = True
current_sel_indices = self.pitch_listbox.curselection()
current_selection_key = ""
if current_sel_indices and current_sel_indices[0] < self.pitch_listbox.size():
try:
current_selection_key = self.pitch_listbox.get(current_sel_indices[0]).replace("°", "")
except tk.TclError: # Listbox might be empty or index out of bounds
current_selection_key = ""
self.pitch_listbox.delete(0, tk.END)
sorted_pitch_keys_float = []
if self.pitch_settings:
try:
sorted_pitch_keys_float = sorted([float(k) for k in self.pitch_settings.keys()])
except ValueError: # Should not happen if keys are well-formed
messagebox.showerror(S.get("error_title"), "Internal error: Invalid pitch key format in settings.", parent=self)
self._internal_update_active = False
return
new_selection_idx = -1
current_selection_found_in_new_list = False
for i, p_float in enumerate(sorted_pitch_keys_float):
display_text = f"{p_float:.1f}°"
self.pitch_listbox.insert(tk.END, display_text)
if f"{p_float:.1f}" == current_selection_key:
new_selection_idx = i
current_selection_found_in_new_list = True
if self.pitch_listbox.size() > 0:
if current_selection_found_in_new_list and new_selection_idx != -1:
self.pitch_listbox.selection_set(new_selection_idx)
self.pitch_listbox.activate(new_selection_idx)
# Call on_pitch_selected, but ensure it knows this is part of an internal update if 'initial_load' is true
self.on_pitch_selected(None, initial_load=initial_load) # Let on_pitch_selected handle UI updates
else:
# If previous selection is gone, or no selection, select initial/default
self._select_initial_pitch(initial_load=initial_load) # This will also call on_pitch_selected
else:
# Listbox is empty, clear/disable relevant controls
self.current_pitch_key_var.set("")
self.selected_pitch_value_var.set(0) # Default value
self.selected_pitch_entry_var.set("")
self.selected_pitch_slider.config(state=tk.DISABLED)
self.selected_pitch_entry.config(state=tk.DISABLED)
self.selected_pitch_fov_var.set(AYS_DEFAULT_FOV_INTERNAL)
self.selected_pitch_fov_entry_var.set(f"{AYS_DEFAULT_FOV_INTERNAL:.1f}")
self.selected_pitch_fov_slider.config(state=tk.DISABLED)
self.selected_pitch_fov_entry.config(state=tk.DISABLED)
self.current_yaw_divisions_var.set(0) # Or a default if applicable
self.yaw_divisions_scale.config(state=tk.DISABLED)
self._create_or_update_yaw_buttons() # Clear buttons
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector() # Update canvas display
if self.on_selection_change_callback and not initial_load:
self.on_selection_change_callback()
self._internal_update_active = False
def _add_pitch_from_combo(self):
if len(self.pitch_settings) >= AYS_MAX_PITCH_ENTRIES:
messagebox.showwarning(S.get("warning_title"), S.get("ays_warning_add_pitch_limit_format", max_entries=AYS_MAX_PITCH_ENTRIES), parent=self)
return
new_pitch_val_str = self.pitch_to_add_var.get()
if not new_pitch_val_str: # No selection in combobox
messagebox.showwarning(S.get("warning_title"), S.get("ays_warning_add_pitch_select_pitch"), parent=self)
return
try:
new_pitch_val_float = float(new_pitch_val_str)
new_pitch_key = f"{new_pitch_val_float:.1f}" # Normalized key
if new_pitch_key not in self.pitch_settings:
is_zero_pitch = math.isclose(new_pitch_val_float, 0.0)
divisions = AYS_DEFAULT_YAW_DIVISIONS_P0_INTERNAL if is_zero_pitch else AYS_DEFAULT_YAW_DIVISIONS_OTHER_INTERNAL
yaws = [round(i * (360.0 / divisions), 2) for i in range(divisions)] if divisions > 0 else []
self.pitch_settings[new_pitch_key] = {"yaws": yaws, "divisions": divisions, "fov": AYS_DEFAULT_FOV_INTERNAL}
self._update_pitch_listbox_from_settings(initial_load=False) # This will re-sort and update listbox
# Find and select the newly added item
newly_added_idx = -1
for i in range(self.pitch_listbox.size()):
if self.pitch_listbox.get(i).replace("°","") == new_pitch_key:
newly_added_idx = i
break
if newly_added_idx != -1:
self.pitch_listbox.selection_clear(0, tk.END)
self.pitch_listbox.selection_set(newly_added_idx)
self.pitch_listbox.activate(newly_added_idx)
self.on_pitch_selected(None, initial_load=False) # Trigger update for the new selection
else:
messagebox.showinfo(S.get("info_title"), S.get("ays_info_pitch_already_exists"), parent=self)
except ValueError:
messagebox.showerror(S.get("error_title"), S.get("ays_error_add_pitch_invalid_value"), parent=self)
def _remove_selected_pitch(self):
sel_idx_tuple = self.pitch_listbox.curselection()
if not sel_idx_tuple:
messagebox.showwarning(S.get("warning_title"), S.get("ays_warning_remove_pitch_select_pitch"), parent=self)
return
idx = sel_idx_tuple[0]
# Ensure index is valid, though curselection should provide a valid one if not empty
if idx >= self.pitch_listbox.size():
return # Should not happen
key_to_remove = self.pitch_listbox.get(idx).replace("°","")
if len(self.pitch_settings) <= 1:
messagebox.showinfo(S.get("info_title"), S.get("ays_info_cannot_remove_last_pitch"), parent=self)
return
if key_to_remove in self.pitch_settings:
del self.pitch_settings[key_to_remove]
if key_to_remove in self.yaw_to_fixed_ring_assignment:
del self.yaw_to_fixed_ring_assignment[key_to_remove]
self.pitch_listbox.delete(idx) # Remove from listbox
if self.pitch_listbox.size() > 0:
new_sel_idx = max(0, min(idx, self.pitch_listbox.size() - 1)) # Select adjacent or last item
self.pitch_listbox.selection_set(new_sel_idx)
self.pitch_listbox.activate(new_sel_idx)
self.on_pitch_selected(None, initial_load=False) # Update based on new selection
else:
# This case should be prevented by len(self.pitch_settings) <= 1 check,
# but as a fallback, refresh everything.
self._update_pitch_listbox_from_settings(initial_load=False)
else:
# This indicates an internal inconsistency
messagebox.showerror(S.get("error_title"), S.get("ays_error_remove_pitch_internal_error"), parent=self)
def _on_selected_pitch_entry_confirm(self, event=None): # pylint: disable=unused-argument
if self._slider_update_active or self._internal_update_active:
return
self._entry_update_active = True
try:
new_val_str = self.selected_pitch_entry_var.get()
new_val_float = float(new_val_str)
new_val_float = max(-90.0, min(90.0, new_val_float)) # Clamp value
# Update the slider's variable first
self.selected_pitch_value_var.set(new_val_float)
# Then update the entry's variable to the (potentially clamped) value
self.selected_pitch_entry_var.set(f"{new_val_float:.1f}")
self._process_pitch_change(new_val_float)
except ValueError:
# Restore entry from slider's current value if input was invalid
current_slider_val = self.selected_pitch_value_var.get()
self.selected_pitch_entry_var.set(f"{current_slider_val:.1f}")
messagebox.showerror(S.get("error_title"), S.get("ays_error_pitch_entry_invalid_numeric"), parent=self)
finally:
self._entry_update_active = False
def _process_pitch_change(self, new_val_float):
if self._internal_update_active: # Prevent processing during internal batch updates
return
sel_idx_tuple = self.pitch_listbox.curselection()
if not sel_idx_tuple: return # No item selected in listbox
idx = sel_idx_tuple[0]
if idx >= self.pitch_listbox.size(): return # Should not happen
old_key = self.pitch_listbox.get(idx).replace("°", "")
new_key_candidate_unsnapped = f"{new_val_float:.1f}"
# Snap to whole number if very close (e.g., 0.05 tolerance)
snapped_new_val_float = round(new_val_float)
final_new_val_float = new_val_float
if math.isclose(new_val_float, snapped_new_val_float, abs_tol=0.05):
final_new_val_float = snapped_new_val_float
new_key_candidate = f"{final_new_val_float:.1f}"
if old_key == new_key_candidate: # Value effectively hasn't changed key
# Ensure internal value and UI are consistent even if key is same
if old_key in self.pitch_settings:
self.selected_pitch_value_var.set(final_new_val_float)
self.selected_pitch_entry_var.set(new_key_candidate) # Display normalized value
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
if self.on_selection_change_callback:
self.on_selection_change_callback()
return
# Check for duplication with other existing pitches
if new_key_candidate in self.pitch_settings and new_key_candidate != old_key:
messagebox.showwarning(S.get("warning_title"), S.get("ays_warning_pitch_entry_duplicate_format", pitch_value=new_key_candidate), parent=self)
# Revert UI to old value
try:
old_val_float = float(old_key)
self.selected_pitch_value_var.set(old_val_float)
self.selected_pitch_entry_var.set(f"{old_val_float:.1f}")
except ValueError: # Should not happen with well-formed old_key
pass
return
# Proceed with changing the key
if old_key in self.pitch_settings:
self._internal_update_active = True # Guard against re-entry during listbox update
settings_to_move = self.pitch_settings.pop(old_key)
self.pitch_settings[new_key_candidate] = settings_to_move
ring_assignment_to_move = None
if old_key in self.yaw_to_fixed_ring_assignment:
ring_assignment_to_move = self.yaw_to_fixed_ring_assignment.pop(old_key)
if ring_assignment_to_move is not None:
self.yaw_to_fixed_ring_assignment[new_key_candidate] = ring_assignment_to_move
self.current_pitch_key_var.set(new_key_candidate) # Update current key var
# Ensure slider and entry vars are also synced to the final processed value
self.selected_pitch_value_var.set(final_new_val_float)
self.selected_pitch_entry_var.set(new_key_candidate)
# Update listbox: delete old, insert new, re-select
# This might change sort order, so a full refresh is safer
# self.pitch_listbox.delete(idx)
# self.pitch_listbox.insert(idx, f"{new_key_candidate}°")
# self.pitch_listbox.selection_set(idx)
# self.pitch_listbox.activate(idx)
self._update_pitch_listbox_from_settings(initial_load=False) # This will re-select and re-sort
# Since key changed, precomputation might be needed if it relied on the key string directly,
# but ring assignments are usually by value. Still, good to ensure.
self.precompute_ring_assignments_for_pitch(new_key_candidate)
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
if self.on_selection_change_callback:
self.on_selection_change_callback()
self._internal_update_active = False
def _on_selected_fov_entry_confirm(self, event=None): # pylint: disable=unused-argument
if self._fov_slider_update_active or self._internal_update_active:
return
self._fov_entry_update_active = True
try:
new_val_str = self.selected_pitch_fov_entry_var.get()
new_val_float = float(new_val_str)
new_val_float = max(AYS_MIN_FOV_DEGREES, min(new_val_float, AYS_MAX_FOV_DEGREES)) # Clamp
self.selected_pitch_fov_var.set(new_val_float) # Update slider's var
self.selected_pitch_fov_entry_var.set(f"{new_val_float:.1f}") # Update entry's var
self._process_fov_change(new_val_float)
except ValueError:
current_slider_fov = self.selected_pitch_fov_var.get()
self.selected_pitch_fov_entry_var.set(f"{current_slider_fov:.1f}")
messagebox.showerror(S.get("error_title"), S.get("ays_error_fov_entry_invalid_numeric"), parent=self)
finally:
self._fov_entry_update_active = False
def _process_fov_change(self, new_fov_float):
if self._internal_update_active: return
pitch_key = self.current_pitch_key_var.get()
if not pitch_key or pitch_key not in self.pitch_settings:
return # No selected pitch or key invalid
# Snap FOV if very close to a whole number
snapped_new_fov_float = round(new_fov_float)
final_new_fov_float = new_fov_float
if math.isclose(new_fov_float, snapped_new_fov_float, abs_tol=0.05): # Tolerance for snapping
final_new_fov_float = snapped_new_fov_float
# Ensure FOV is within defined bounds
final_new_fov_float = max(AYS_MIN_FOV_DEGREES, min(final_new_fov_float, AYS_MAX_FOV_DEGREES))
self._internal_update_active = True # Guard block
self.pitch_settings[pitch_key]["fov"] = final_new_fov_float
self.selected_pitch_fov_var.set(final_new_fov_float) # Sync slider var
self.selected_pitch_fov_entry_var.set(f"{final_new_fov_float:.1f}") # Sync entry var
# FOV change affects visualization and potentially ring assignments if they depend on FOV visuals
self.precompute_ring_assignments_for_pitch(pitch_key) # Re-run if assignments visually depend on FOV
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
if self.on_selection_change_callback:
self.on_selection_change_callback()
self._internal_update_active = False
def reset_current_pitch_fov(self):
pitch_key = self.current_pitch_key_var.get()
if not pitch_key or pitch_key not in self.pitch_settings:
messagebox.showinfo(S.get("info_title"), S.get("ays_info_reset_fov_no_pitch_selected"), parent=self)
return
target_fov = AYS_DEFAULT_FOV_INTERNAL
# Directly update vars and then process, similar to entry confirm
self.selected_pitch_fov_var.set(target_fov)
self.selected_pitch_fov_entry_var.set(f"{target_fov:.1f}")
self._process_fov_change(target_fov)
def on_pitch_selected(self, event, initial_load=False): # pylint: disable=unused-argument
sel_idx_tuple = self.pitch_listbox.curselection()
if not sel_idx_tuple: # No selection
# Disable controls if nothing is selected
self.selected_pitch_slider.config(state=tk.DISABLED)
self.selected_pitch_entry.config(state=tk.DISABLED)
self.selected_pitch_entry_var.set("") # Clear entry
self.selected_pitch_fov_slider.config(state=tk.DISABLED)
self.selected_pitch_fov_entry.config(state=tk.DISABLED)
self.selected_pitch_fov_entry_var.set("") # Clear entry
self.yaw_divisions_scale.config(state=tk.DISABLED)
if self.pitch_listbox.size() == 0: # Listbox is actually empty
self.current_pitch_key_var.set("")
self.current_yaw_divisions_var.set(0) # Or some default
self._create_or_update_yaw_buttons() # Clear/disable yaw buttons
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector() # Update canvas
if self.on_selection_change_callback and not initial_load:
self.on_selection_change_callback()
return
idx = sel_idx_tuple[0]
if idx >= self.pitch_listbox.size(): return # Should not happen
key = self.pitch_listbox.get(idx).replace("°","")
self._internal_update_active = True # Start guarded block
self.current_pitch_key_var.set(key)
try:
val_f = float(key)
self.selected_pitch_value_var.set(val_f)
self.selected_pitch_entry_var.set(f"{val_f:.1f}")
# Enable/disable based on master controls_enabled flag
current_state = tk.NORMAL if self.controls_enabled else tk.DISABLED
self.selected_pitch_slider.config(state=current_state)
self.selected_pitch_entry.config(state=current_state)
except ValueError: # Should not happen if listbox items are well-formed
self.selected_pitch_value_var.set(0) # Fallback
self.selected_pitch_entry_var.set("0.0") # Fallback
self.selected_pitch_slider.config(state=tk.DISABLED)
self.selected_pitch_entry.config(state=tk.DISABLED)
current_div_scale_state = tk.NORMAL if self.controls_enabled else tk.DISABLED
self.yaw_divisions_scale.config(state=current_div_scale_state)
if key in self.pitch_settings:
settings = self.pitch_settings[key]
self.current_yaw_divisions_var.set(settings["divisions"])
current_pitch_fov = settings.get("fov", AYS_DEFAULT_FOV_INTERNAL)
self.selected_pitch_fov_var.set(current_pitch_fov)
self.selected_pitch_fov_entry_var.set(f"{current_pitch_fov:.1f}")
current_fov_controls_state = tk.NORMAL if self.controls_enabled else tk.DISABLED
self.selected_pitch_fov_slider.config(state=current_fov_controls_state)
self.selected_pitch_fov_entry.config(state=current_fov_controls_state)
# Ensure ring assignments are computed for this pitch
if key not in self.yaw_to_fixed_ring_assignment or not self.yaw_to_fixed_ring_assignment.get(key):
self.precompute_ring_assignments_for_pitch(key)
self._create_or_update_yaw_buttons() # Update yaw buttons based on new pitch
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector() # Redraw canvas for new pitch
else:
# Key not in settings, disable controls that depend on it
self.current_yaw_divisions_var.set(0) # Or default
self.yaw_divisions_scale.config(state=tk.DISABLED)
self.selected_pitch_fov_slider.config(state=tk.DISABLED)
self.selected_pitch_fov_entry.config(state=tk.DISABLED)
self.selected_pitch_fov_entry_var.set("") # Clear
self._create_or_update_yaw_buttons() # Clear/disable
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector() # Show default/empty state
# Log error for development/debugging
print(S.get("ays_error_key_not_found_in_settings_format", key=key)) # Use S.get for msg
self._internal_update_active = False # End guarded block
if self.on_selection_change_callback and not initial_load:
self.on_selection_change_callback()
def _on_fov_or_divisions_changed(self,event=None): # pylint: disable=unused-argument
if self._internal_update_active: return
key = self.current_pitch_key_var.get()
if not key or key not in self.pitch_settings: return
new_divs = self.current_yaw_divisions_var.get()
pitch_specific_settings = self.pitch_settings[key]
if pitch_specific_settings["divisions"] != new_divs:
pitch_specific_settings["divisions"] = new_divs
# Recalculate yaws based on new divisions; this also resets selection
yaws = [round(i * (360.0 / new_divs), 2) for i in range(new_divs)] if new_divs > 0 else []
pitch_specific_settings["yaws"] = yaws # Store all potential yaws, selection handled by buttons/canvas
self.precompute_ring_assignments_for_pitch(key) # Divs changed, so ring assignments need update
self._create_or_update_yaw_buttons() # Rebuild buttons for new divisions
# _update_yaw_button_states() will be called by _create_or_update_yaw_buttons
# FOV change is handled by its own dedicated _process_fov_change method
# This method is primarily for division changes.
self._update_yaw_button_states() # Ensure button states reflect current yaws
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector()
if self.on_selection_change_callback:
self.on_selection_change_callback()
def _create_or_update_yaw_buttons(self):
# Clear existing buttons
for widget in self.yaw_buttons_frame.winfo_children():
widget.destroy()
self.yaw_buttons.clear()
key = self.current_pitch_key_var.get()
if not key or key not in self.pitch_settings:
return # No pitch selected or invalid key
settings = self.pitch_settings.get(key)
if not settings: return # Should not happen if key is valid
divisions = settings["divisions"]
if divisions == 0: return # No divisions, no buttons
yaw_angle_step = 360.0 / divisions
max_columns = 3 # Number of buttons per row
for i in range(divisions):
yaw_angle = round(i * yaw_angle_step, 2)
button_text = f"{yaw_angle:.0f}°" # Display as integer
# Use functools.partial to pass the yaw_angle to the command
command = functools.partial(self._toggle_yaw_selection_from_button, yaw_angle)
button_state = tk.NORMAL if self.controls_enabled else tk.DISABLED
button = tk.Button(self.yaw_buttons_frame, text=button_text, command=command,
bg=AYS_BUTTON_NORMAL_BG, width=5, state=button_state)
row, col = i // max_columns, i % max_columns
button.grid(row=row, column=col, padx=2, pady=2, sticky="ew")
# Configure column weights for responsiveness if fewer than max_columns in the last row
if col < max_columns: # Ensure all used columns have weight
self.yaw_buttons_frame.columnconfigure(col, weight=1)
self.yaw_buttons.append({"button": button, "yaw": yaw_angle})
self._update_yaw_button_states() # Set initial state of new buttons
def _toggle_yaw_selection_from_button(self, yaw_angle_to_toggle):
self._toggle_yaw_selection(yaw_angle_to_toggle) # Common logic
def _toggle_yaw_selection(self, yaw_angle_to_toggle):
if self._internal_update_active: return
key = self.current_pitch_key_var.get()
if not key or key not in self.pitch_settings: return
settings = self.pitch_settings[key]
selected_yaws_for_pitch = settings.get("yaws", []) # Current list of selected yaws
yaw_float_to_toggle = float(yaw_angle_to_toggle)
found_and_removed = False
for i, selected_yaw_raw in enumerate(selected_yaws_for_pitch):
if math.isclose(float(selected_yaw_raw), yaw_float_to_toggle):
selected_yaws_for_pitch.pop(i)
found_and_removed = True
break
if not found_and_removed:
selected_yaws_for_pitch.append(yaw_angle_to_toggle) # Add as the original type (could be float or string)
selected_yaws_for_pitch.sort(key=float) # Keep sorted
settings["yaws"] = selected_yaws_for_pitch # Update the stored list
self._update_yaw_button_states() # Reflect change in button appearance
if hasattr(self, 'yaw_canvas') and self.yaw_canvas.winfo_exists():
self.draw_yaw_selector() # Redraw canvas to show selection change
if self.on_selection_change_callback:
self.on_selection_change_callback()
def _update_yaw_button_states(self):
key = self.current_pitch_key_var.get()
if not key or key not in self.pitch_settings:
# If no valid pitch, reset all buttons to default appearance
for btn_info in self.yaw_buttons:
btn_info["button"].config(relief=tk.RAISED, bg=AYS_BUTTON_NORMAL_BG)
return
settings = self.pitch_settings.get(key)
if not settings: # Should not happen if key is valid
for btn_info in self.yaw_buttons:
btn_info["button"].config(relief=tk.RAISED, bg=AYS_BUTTON_NORMAL_BG)
return
selected_yaws = settings.get("yaws", [])
ring_assignments = self.yaw_to_fixed_ring_assignment.get(key, {})
# If ring assignments are missing but should exist (divisions > 0), try to precompute
if not ring_assignments and settings.get("divisions", 0) > 0:
self.precompute_ring_assignments_for_pitch(key)
ring_assignments = self.yaw_to_fixed_ring_assignment.get(key, {})
for btn_info in self.yaw_buttons:
button_widget, button_yaw_angle = btn_info["button"], btn_info["yaw"]
is_selected = any(math.isclose(float(button_yaw_angle), float(sel_yaw)) for sel_yaw in selected_yaws)
bg_color = AYS_BUTTON_NORMAL_BG # Default background
if is_selected:
ring_data = ring_assignments.get(button_yaw_angle) # Match by the exact yaw value
bg_color = ring_data["color"] if ring_data and "color" in ring_data else "lightgray" # Fallback color
button_widget.config(relief=tk.SUNKEN if is_selected else tk.RAISED, bg=bg_color)
def _apply_rotation(self, point, angle_rad, axis_char):