-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_tk.py
More file actions
3460 lines (3107 loc) · 136 KB
/
Copy pathgui_tk.py
File metadata and controls
3460 lines (3107 loc) · 136 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
"""
DropGain CustomTkinter GUI.
The GUI owns user interaction, progress display, threading, and settings.
Background job execution (including audio processing and CSV report writing)
is delegated to jobs.py.
"""
from __future__ import annotations
import faulthandler
import json
import logging
import logging.handlers
import math
import os
import queue
import subprocess
import sys
import threading
import time
import traceback
import webbrowser
from typing import Any, Callable
import tkinter as tk
import tkinter.font as tkfont
from tkinter import filedialog, messagebox, scrolledtext, ttk
try:
import customtkinter as ctk
except ImportError as exc:
raise RuntimeError(
"Required Python package customtkinter was not found.\n\n"
"Install it with:\n\n"
" pip install customtkinter\n\n"
"Then start DropGain again."
) from exc
try:
from PIL import Image, ImageDraw, ImageFont, ImageTk
except ImportError as exc:
raise RuntimeError(
"Required Python package Pillow was not found.\n\n"
"Install it with:\n\n"
" pip install pillow\n\n"
"Then start DropGain again."
) from exc
from analysis import (
APP_WINDOW_TITLE,
DEFAULT_BOOST_PEAK_CEILING_DBFS,
DEFAULT_LIMITER_ENGINE,
DEFAULT_LOUD_SECTION_HOP_SECONDS,
DEFAULT_LOUD_SECTION_WINDOW_SECONDS,
DEFAULT_MAX_REDUCTION_DB,
DEFAULT_BASS_MAX_BOOST_REDUCTION_DB,
MIN_BASS_MAX_BOOST_REDUCTION_DB,
MAX_BASS_MAX_BOOST_REDUCTION_DB,
DEFAULT_BASS_PENALTY_START_DB,
DEFAULT_BASS_PENALTY_FULL_DB,
DEFAULT_SUB_PENALTY_START_DB,
DEFAULT_SUB_PENALTY_FULL_DB,
MIN_BASS_PENALTY_THRESHOLD_DB,
MAX_BASS_PENALTY_THRESHOLD_DB,
DEFAULT_NORMALIZATION_MODE,
DEFAULT_APPLY_RENDER_GAIN_THRESHOLD,
DEFAULT_OUTPUT_FORMAT_MODE,
DEFAULT_TARGET_HIGH_LUFS,
DEFAULT_TARGET_LOW_LUFS,
DEFAULT_ANALYSIS_WORKER_THREADS,
DEFAULT_RENDER_WORKER_THREADS,
LIMITER_ENGINE_LOUDMAX,
LOSSLESS_MIN_ABS_GAIN_DB,
MAX_ANALYSIS_WORKER_THREADS,
MIN_ANALYSIS_WORKER_THREADS,
MP3_MIN_ABS_GAIN_DB,
OUTPUT_FORMAT_ALL_TO_MP3,
OUTPUT_FORMAT_ALL_TO_AIFF,
OUTPUT_FORMAT_MP3_TO_AIFF,
OUTPUT_FORMAT_PRESERVE,
PROCESSED_SUFFIX,
benchmark_timer,
check_ffmpeg_available,
default_csv_path,
format_peak_control_display,
hidden_subprocess_kwargs,
normalize_limiter_engine,
normalize_normalization_mode,
normalize_output_format_mode,
output_format_mode_description,
output_format_mode_ui_hint,
script_folder,
)
from jobs import (
AnalyzedWorkItem,
DropGainSettings,
eligible_render_indices,
refresh_analyzed_render_statuses,
recompute_rows_for_settings,
run_analysis_job,
run_batch_job,
run_processing_job,
)
from processing import (
find_loudmax_plugin_path,
find_prol2_plugin_path,
shutdown_prol2_render_host,
verify_loudmax_plugin,
verify_prol2_plugin,
)
from gui_waveform import WaveformMixin
from gui_process import RESULTS_EMPTY_PLACEHOLDER
from gui_theme import * # noqa: F403
from gui_utils import ( # noqa: F401
ContentFadeTransition,
DropGainTooltip,
GuiQueueLogHandler,
TreeviewHeadingTooltip,
apply_hand_cursor,
enable_macos_ctk_scaling,
enable_windows_dpi_awareness,
fit_window_bounds,
logical_screen_size,
logical_widget_width,
make_tooltip_label,
pointer_inside_widget,
position_tooltip_window,
register_app_fonts,
resolve_body_font_family,
resolve_brand_display_family,
resolve_metric_value_family,
resolve_ui_accent_family,
scaled_px,
scaled_px_from_float,
telemetry_caption,
telemetry_plain,
treeview_column_width_px,
treeview_rowheight_px,
ui_scale_for,
wire_ctk_button_press,
)
from platform_utils import open_in_file_manager
GUI_TICK_MIN_INTERVAL_SEC = 0.35
PROGRESS_TWEEN_INTERVAL_MS = 16
PROGRESS_TWEEN_DURATION_SEC = 0.2
SETTING_CHANGE_DEBOUNCE_MS = 200
SAVE_SETTINGS_DEBOUNCE_MS = 500
RESULTS_TABLE_RESIZE_DEBOUNCE_MS = 50
SETTINGS_FILE_NAME = "dropgain_settings.json"
SETTINGS_SCHEMA_VERSION = 1
LOG_FILE_NAME = "dropgain.log"
CRASH_LOG_FILE_NAME = "dropgain_crash.log"
START_MAXIMIZED = True
def enable_crash_diagnostics() -> None:
"""Write hard-crash tracebacks to a log file next to the app."""
crash_log = script_folder() / CRASH_LOG_FILE_NAME
try:
handle = open(crash_log, "a", encoding="utf-8")
except OSError:
return
try:
faulthandler.enable(file=handle, all_threads=True)
except Exception:
try:
handle.close()
except OSError:
pass
RUN_COUNT_KEYS = (
"processed",
"would_process",
"analyzed_only",
"skipped",
"warnings",
"errors",
)
class App(WaveformMixin, ctk.CTk):
def __init__(self) -> None:
ctk.set_appearance_mode("dark")
super().__init__(fg_color=BG_MAIN)
self._registered_font_families = register_app_fonts(self)
enable_macos_ctk_scaling(self)
self._brand_display_family = resolve_brand_display_family(self, self._registered_font_families)
self._metric_value_family = resolve_metric_value_family(self, self._registered_font_families)
self._ui_accent_family = resolve_ui_accent_family(self, self._registered_font_families)
self._body_font_family = resolve_body_font_family(self, self._registered_font_families)
self.title(APP_WINDOW_TITLE)
self._last_ui_scale = ui_scale_for(self)
self._dpi_refresh_after_id: str | None = None
self._app_icon: ImageTk.PhotoImage | None = None
self._settings = self._load_settings()
self._run_counts = self._empty_run_counts()
self._analyzed_rows: list[dict[str, object]] = []
self._analyzed_work_items: dict[str, AnalyzedWorkItem] = {}
self._analysis_signature: dict[str, object] | None = None
self._active_run_signature: dict[str, object] | None = None
self._progress_max = 1
self._active_pipeline: str | None = None
self._active_phase = "idle"
self._run_completed = False
self._progress_done = 0
self._progress_total = 1
self._batch_analysis_total = 0
self._batch_analysis_done = 0
self._batch_render_total = 0
self._batch_render_done = 0
self._busy_button: ctk.CTkButton | None = None
self._busy_button_idle_text = ""
self._operation_started_at: float | None = None
self._operation_elapsed_after_id: str | None = None
self._operation_last_rate = 0.0
self._operation_last_eta = ""
self._operation_last_errors = 0
self._progress_target = 0.0
self._progress_display = 0.0
self._progress_tween_after_id: str | None = None
self._progress_indeterminate = False
self._building_ui = True
self._suspend_setting_traces = False
self._analysis_setting_after_id: str | None = None
self._decision_setting_after_id: str | None = None
self._render_rule_setting_after_id: str | None = None
self._save_settings_after_id: str | None = None
self._results_table_resize_after_id: str | None = None
self._main_page_visuals_dirty = False
self._init_waveform_state()
self._queue: queue.Queue[tuple[str, object]] = queue.Queue()
self._log_record_queue: queue.Queue[logging.LogRecord] = queue.Queue()
self._cancel_flag = threading.Event()
self._worker_thread: threading.Thread | None = None
self._close_requested = False
self._previous_thread_excepthook: Callable[[threading.ExceptHookArgs], Any] | None = None
self._panel_fade = ContentFadeTransition(self)
self._logger = logging.getLogger("dropgain")
self._log_listener: logging.handlers.QueueListener | None = None
self.preferences_page = None
self.lbl_output_format_hint = None
self.mode_menu = None
self.limiter_engine_menu = None
self.output_format_menu = None
self.chk_allow_risky_true_peak_boost = None
self.chk_apply_render_gain_threshold = None
self.chk_write_csv = None
self._number_inputs: list[Any] = []
self._init_settings_variables()
self._configure_logging()
self._install_exception_handlers()
self._configure_treeview_style()
self._build_ui()
self._building_ui = False
self._install_window_icon()
self._wire_setting_traces()
self._validate_paths()
self.after(100, self._poll_queue)
self.protocol("WM_DELETE_WINDOW", self._close_app)
self.bind("<Configure>", self._on_root_configure_for_dpi, add="+")
self.update_idletasks()
actual_scale = self._ui_scale()
if abs(actual_scale - self._last_ui_scale) >= 0.05:
self._last_ui_scale = actual_scale
self._configure_treeview_style()
if hasattr(self, "results_table"):
try:
self._resize_results_table_columns()
except Exception:
pass
self._apply_window_bounds(reposition=True)
if START_MAXIMIZED:
self.after(0, self._maximize_window)
if os.path.exists(default_csv_path(self.var_folder.get().strip())):
self._apply_action_button_state(self.btn_open_csv, "normal")
self._logger.info("Logging to %s", script_folder() / LOG_FILE_NAME)
# ---------------------------------------------------------------------
# Settings and setup
# ---------------------------------------------------------------------
def _maximize_window(self) -> None:
try:
self.state("zoomed")
return
except tk.TclError:
pass
try:
self.attributes("-zoomed", True)
return
except tk.TclError:
pass
self.geometry(f"{self.winfo_screenwidth()}x{self.winfo_screenheight()}+0+0")
def _apply_window_bounds(self, *, reposition: bool = False) -> None:
width, height, min_w, min_h = fit_window_bounds(self)
self.minsize(min_w, min_h)
if not reposition:
return
if self._is_window_maximized():
return
screen_height = self.winfo_screenheight()
x = (self.winfo_screenwidth() - width) // 2
y = max(0, (screen_height - height) // 2)
self.geometry(f"{width}x{height}+{x}+{y}")
def _is_window_maximized(self) -> bool:
try:
if str(self.state()) == "zoomed":
return True
except tk.TclError:
pass
try:
return bool(self.attributes("-zoomed"))
except tk.TclError:
return False
def _ui_scale(self) -> float:
return ui_scale_for(self)
def _scaled(self, value: float | int) -> int:
return scaled_px(self, value)
def _on_root_configure_for_dpi(self, _event: tk.Event | None = None) -> None:
if self._dpi_refresh_after_id is not None:
try:
self.after_cancel(self._dpi_refresh_after_id)
except Exception:
pass
self._dpi_refresh_after_id = self.after(200, self._refresh_scaled_ui)
def _refresh_scaled_ui(self) -> None:
self._dpi_refresh_after_id = None
new_scale = self._ui_scale()
if abs(new_scale - self._last_ui_scale) < 0.05:
return
self._last_ui_scale = new_scale
self._apply_window_bounds()
self._configure_treeview_style()
if hasattr(self, "results_table"):
try:
self._resize_results_table_columns()
except Exception:
pass
if hasattr(self, "waveform_canvas"):
try:
if self._current_waveform_data is not None:
self._draw_waveform_canvas()
except Exception:
pass
if self.library_tuning_page is not None:
try:
self.library_tuning_page._redraw_charts()
except Exception:
pass
try:
self._update_folder_entry_width()
except Exception:
pass
process_page = getattr(self, "process_page", None)
if process_page is not None:
try:
process_page.refresh_layout()
except Exception:
pass
if self.preferences_page is not None:
try:
self.preferences_page.refresh_layout()
except Exception:
pass
@staticmethod
def _empty_run_counts() -> dict[str, int]:
return {key: 0 for key in RUN_COUNT_KEYS}
@staticmethod
def _format_run_counts(counts: dict[str, int]) -> str:
return (
f"Processed: {counts.get('processed', 0)} | "
f"Would process: {counts.get('would_process', 0)} | "
f"Analyzed only: {counts.get('analyzed_only', 0)} | "
f"Skipped: {counts.get('skipped', 0)} | "
f"Warnings: {counts.get('warnings', 0)} | "
f"Errors: {counts.get('errors', 0)}"
)
@staticmethod
def _settings_path() -> str:
return str(script_folder() / SETTINGS_FILE_NAME)
@staticmethod
def _setting_float(settings: dict[str, Any], key: str, default: float) -> float:
try:
return float(settings.get(key, default))
except Exception:
return default
@staticmethod
def _setting_int(settings: dict[str, Any], key: str, default: int) -> int:
try:
return int(float(settings.get(key, default)))
except Exception:
return default
@staticmethod
def _setting_bool(settings: dict[str, Any], key: str, default: bool) -> bool:
try:
value = settings.get(key, default)
if isinstance(value, bool):
return value
return str(value).lower() in {"true", "1", "yes"}
except Exception:
return default
def _upgrade_settings(self, settings: dict[str, Any]) -> dict[str, Any]:
upgraded = dict(settings)
if "output_format_mode" not in upgraded:
upgraded["output_format_mode"] = DEFAULT_OUTPUT_FORMAT_MODE
upgraded["output_format_mode"] = normalize_output_format_mode(upgraded.get("output_format_mode"))
if "apply_render_gain_threshold" not in upgraded:
upgraded["apply_render_gain_threshold"] = DEFAULT_APPLY_RENDER_GAIN_THRESHOLD
upgraded["settings_schema_version"] = SETTINGS_SCHEMA_VERSION
return upgraded
def _load_settings(self) -> dict[str, Any]:
path = self._settings_path()
try:
if not os.path.exists(path):
return {}
with open(path, "r", encoding="utf-8") as handle:
data = json.load(handle)
if isinstance(data, dict):
return self._upgrade_settings(data)
except Exception:
pass
return {}
def _schedule_debounced(self, attr_name: str, callback: Callable[[], None], delay_ms: int) -> None:
after_id = getattr(self, attr_name, None)
if after_id is not None:
try:
self.after_cancel(after_id)
except Exception:
pass
setattr(self, attr_name, self.after(delay_ms, callback))
def _setting_change_blocked(self) -> bool:
return (
getattr(self, "_building_ui", False)
or getattr(self, "_suspend_setting_traces", False)
or self._is_run_busy()
)
def _schedule_save_settings(self) -> None:
if not hasattr(self, "var_folder"):
return
self._schedule_debounced(
"_save_settings_after_id",
self._save_settings,
SAVE_SETTINGS_DEBOUNCE_MS,
)
def _save_settings(self) -> None:
self._save_settings_after_id = None
if not hasattr(self, "var_folder"):
return
try:
data = {
"settings_schema_version": SETTINGS_SCHEMA_VERSION,
"last_folder": self.var_folder.get().strip(),
"last_output_folder": self.var_output_folder.get().strip(),
"target_low": float(self.var_target_low.get()),
"target_high": float(self.var_target_high.get()),
"window_seconds": float(self.var_window.get()),
"hop_seconds": float(self.var_hop.get()),
"workers": int(float(self.var_workers.get())),
"max_reduction": float(self.var_max_reduction.get()),
"bass_max_reduction": float(self.var_bass_max_reduction.get()),
"bass_penalty_start": float(self.var_bass_penalty_start.get()),
"bass_penalty_full": float(self.var_bass_penalty_full.get()),
"sub_penalty_start": float(self.var_sub_penalty_start.get()),
"sub_penalty_full": float(self.var_sub_penalty_full.get()),
"peak_ceiling": float(self.var_peak_ceiling.get()),
"normalization_mode": normalize_normalization_mode(self.var_normalization_mode.get()),
"limiter_engine": normalize_limiter_engine(self.var_limiter_engine.get()),
"mp3_threshold": float(self.var_mp3_threshold.get()),
"lossless_threshold": float(self.var_lossless_threshold.get()),
"output_format_mode": normalize_output_format_mode(self.var_output_format_mode.get()),
"allow_risky_true_peak_boost": bool(self.var_allow_risky_true_peak_boost.get()),
"apply_render_gain_threshold": bool(self.var_apply_render_gain_threshold.get()),
"write_csv": bool(self.var_write_csv.get()),
}
except Exception:
return
try:
with open(self._settings_path(), "w", encoding="utf-8") as handle:
json.dump(data, handle, indent=2)
except Exception:
self._logger.exception("Failed to save settings")
def _configure_logging(self) -> None:
self._logger.setLevel(logging.INFO)
self._logger.propagate = False
self._logger.handlers.clear()
queue_handler = logging.handlers.QueueHandler(self._log_record_queue)
self._logger.addHandler(queue_handler)
gui_handler = GuiQueueLogHandler(self._queue)
gui_handler.setLevel(logging.INFO)
gui_handler.setFormatter(logging.Formatter("%(message)s"))
file_handler = logging.FileHandler(script_folder() / LOG_FILE_NAME, encoding="utf-8")
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(
logging.Formatter("%(asctime)s [%(levelname)s] [%(threadName)s] %(message)s")
)
self._log_listener = logging.handlers.QueueListener(
self._log_record_queue,
gui_handler,
file_handler,
respect_handler_level=True,
)
self._log_listener.start()
def _shutdown_logging(self) -> None:
if self._log_listener is not None:
self._log_listener.stop()
self._log_listener = None
self._logger.handlers.clear()
def _install_exception_handlers(self) -> None:
previous = threading.excepthook
self._previous_thread_excepthook = previous
def thread_excepthook(args: threading.ExceptHookArgs) -> None:
if args.exc_value is None:
previous(args)
return
thread_name = args.thread.name if args.thread is not None else "unknown"
detail = "".join(
traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback)
)
try:
self._logger.error("Uncaught exception in thread %s:\n%s", thread_name, detail)
self._queue.put(("thread_error", (thread_name, detail)))
except Exception:
previous(args)
threading.excepthook = thread_excepthook
def _restore_exception_handlers(self) -> None:
if self._previous_thread_excepthook is not None:
threading.excepthook = self._previous_thread_excepthook
self._previous_thread_excepthook = None
def report_callback_exception(
self,
exc: type[BaseException],
val: BaseException,
tb: Any,
) -> None:
detail = "".join(traceback.format_exception(exc, val, tb))
self._logger.error("Unhandled Tk callback error:\n%s", detail)
try:
self._queue.put(("callback_error", detail))
except Exception:
self._show_unexpected_error_dialog("Unexpected error")
def _log_file_path(self) -> str:
return str(script_folder() / LOG_FILE_NAME)
def _show_unexpected_error_dialog(self, title: str, *, thread_name: str | None = None) -> None:
if self._close_requested:
return
log_path = self._log_file_path()
if thread_name:
body = (
f"Thread {thread_name} failed unexpectedly.\n\n"
f"Details are in the log:\n{log_path}"
)
else:
body = (
"An unexpected error occurred.\n\n"
f"Details are in the log:\n{log_path}"
)
messagebox.showerror(title, body)
def _show_fatal_job_error_dialog(self) -> None:
if self._close_requested:
return
messagebox.showerror(
"Processing error",
"The current operation failed unexpectedly.\n\n"
f"Details are in the log:\n{self._log_file_path()}",
)
def _install_window_icon(self) -> None:
try:
size = 64
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
margin = 8
draw.rounded_rectangle(
(margin, margin, size - margin, size - margin),
radius=14,
fill=ICE_FILL,
)
bar_w = 8
bar_bottom = size - margin - 10
bar_top = margin + 14
draw.rounded_rectangle(
(size // 2 - bar_w // 2, bar_top, size // 2 + bar_w // 2, bar_bottom),
radius=3,
fill=BUTTON_TEXT_DARK,
)
draw.polygon(
[
(size // 2 - 12, bar_top + 6),
(size // 2 + 12, bar_top + 6),
(size // 2, bar_top - 4),
],
fill=BUTTON_TEXT_DARK,
)
self._app_icon = ImageTk.PhotoImage(img)
self.iconphoto(True, self._app_icon)
except Exception:
self._app_icon = None
def _resolve_table_font(self, size: int, *, weight: str | None = None) -> tkfont.Font:
available = {str(name).lower(): str(name) for name in self.tk.call("font", "families")}
for family in (TABLE_CELL_FONT_FAMILY, *TABLE_CELL_FONT_FALLBACKS):
resolved = available.get(family.lower())
if resolved:
return tkfont.Font(family=resolved, size=size, weight=weight or "normal")
return tkfont.Font(family=self._body_font_family, size=size, weight=weight or "normal")
def _resolve_ui_accent_tkfont(self, size: int, *, weight: str | None = None) -> tkfont.Font:
return tkfont.Font(
family=self._ui_accent_family,
size=size,
weight=weight or "normal",
)
def _configure_treeview_style(self) -> None:
style = ttk.Style()
try:
style.theme_use("clam")
except tk.TclError:
pass
self._treeview_heading_font = self._resolve_ui_accent_tkfont(TABLE_HEADING_SIZE, weight="bold")
self._treeview_cell_font = self._resolve_table_font(TABLE_CELL_SIZE)
rowheight = treeview_rowheight_px(
self._treeview_cell_font.metrics("linespace"),
self._ui_scale(),
)
style.configure(
"DropGain.Treeview",
background=BG_FIELD,
fieldbackground=BG_FIELD,
foreground=FG_MAIN,
bordercolor=BORDER_COLOR,
lightcolor=BG_FIELD,
darkcolor=BG_FIELD,
font=self._treeview_cell_font,
rowheight=rowheight,
)
self._neutralize_treeview_selected_style(style)
style.configure(
"DropGain.Treeview.Heading",
background=HEADER_BG,
foreground=FG_MUTED,
bordercolor=BORDER_COLOR,
lightcolor=BORDER_COLOR,
darkcolor=HEADER_BG,
font=self._treeview_heading_font,
relief="raised",
borderwidth=1,
)
style.map(
"DropGain.Treeview.Heading",
background=[("active", BORDER_COLOR)],
foreground=[("active", FG_MAIN)],
)
style.configure("DropGain.Vertical.TScrollbar", background=BG_CARD, troughcolor=BG_FIELD)
style.configure("DropGain.Horizontal.TScrollbar", background=BG_CARD, troughcolor=BG_FIELD)
style.map(
"DropGain.Vertical.TScrollbar",
background=[("active", BORDER_COLOR), ("pressed", BORDER_COLOR)],
)
style.map(
"DropGain.Horizontal.TScrollbar",
background=[("active", BORDER_COLOR), ("pressed", BORDER_COLOR)],
)
if hasattr(self, "results_table"):
self.results_table.configure(style="DropGain.Treeview")
def _neutralize_treeview_selected_style(self, style: ttk.Style) -> None:
for option in ("foreground", "background"):
mapped = list(style.map("DropGain.Treeview", queryopt=option))
filtered = [entry for entry in mapped if not str(entry[0]).startswith("selected")]
style.map("DropGain.Treeview", **{option: filtered})
def _results_row_base_tag(self, tag: str) -> str:
if tag.endswith("_selected"):
return tag[: -len("_selected")]
return tag
def _results_row_display_tag(self, base_tag: str, *, selected: bool) -> str:
return f"{base_tag}_selected" if selected else base_tag
def _sync_results_table_selection_appearance(self) -> None:
if not hasattr(self, "results_table"):
return
table = self.results_table
selected = set(table.selection())
for item in table.get_children():
tags = table.item(item, "tags")
if not tags:
continue
base_tag = self._results_row_base_tag(str(tags[0]))
display_tag = self._results_row_display_tag(base_tag, selected=item in selected)
if tags[0] != display_tag:
table.item(item, tags=(display_tag,))
def _handle_results_table_select(self, event: tk.Event[tk.Widget] | None = None) -> None:
self._sync_results_table_selection_appearance()
self._on_results_table_select(event)
def _configure_results_table_tags(self) -> None:
row_styles: tuple[tuple[str, str, str], ...] = (
("odd", TABLE_ROW_ODD, FG_MAIN),
("even", TABLE_ROW_EVEN, FG_MAIN),
("odd_warn", TABLE_ROW_ODD, WARN_FG),
("even_warn", TABLE_ROW_EVEN, WARN_FG),
("odd_error", TABLE_ROW_ODD, ERROR_FG),
("even_error", TABLE_ROW_EVEN, ERROR_FG),
("odd_ok", TABLE_ROW_ODD, SUCCESS_FG),
("even_ok", TABLE_ROW_EVEN, SUCCESS_FG),
)
for tag_name, background, foreground in row_styles:
self.results_table.tag_configure(tag_name, background=background, foreground=foreground)
self.results_table.tag_configure(
f"{tag_name}_selected",
background=TABLE_SELECTION_BG,
foreground=foreground,
)
def _should_show_results_operation_overlay(self) -> bool:
if not self._analyzed_rows:
return True
return self._active_phase == "render" and self._is_run_busy()
def _refresh_results_empty_message(self) -> None:
if not hasattr(self, "var_results_empty"):
return
if not self._should_show_results_operation_overlay():
return
if self._is_run_busy():
if self._operation_started_at is not None:
message = self._operation_stats_text(
self._operation_last_rate,
self._operation_last_eta,
self._operation_last_errors,
)
else:
message = telemetry_plain(self.var_status.get()) or RESULTS_EMPTY_PLACEHOLDER
self.var_results_empty.set(message)
return
self.var_results_empty.set(RESULTS_EMPTY_PLACEHOLDER)
def _update_results_empty_state(self, *, has_rows: bool) -> None:
if not hasattr(self, "results_empty_label"):
return
if self._should_show_results_operation_overlay():
self.results_empty_label.grid()
self._refresh_results_empty_message()
elif has_rows:
self.results_empty_label.grid_remove()
else:
self.results_empty_label.grid()
self._refresh_results_empty_message()
def _results_table_column_width(self, heading: str, sample_cell: str) -> int:
heading_width = treeview_column_width_px(
self._treeview_heading_font.measure(heading),
TREEVIEW_HEADING_PAD,
)
cell_width = (
treeview_column_width_px(self._treeview_cell_font.measure(sample_cell), TREEVIEW_CELL_PAD)
if sample_cell
else 0
)
return max(heading_width, cell_width)
def _results_table_column_widths_from_content(self) -> dict[str, int]:
widths: dict[str, int] = {}
column_ids: list[str] = []
for column_id, heading, _anchor, sample_cell, _tooltip in RESULTS_TABLE_COLUMNS:
column_ids.append(column_id)
widths[column_id] = self._results_table_column_width(heading, sample_cell)
widths["filename"] = max(widths["filename"], self._scaled(RESULTS_TABLE_FILENAME_MIN))
for item in self.results_table.get_children():
values = self.results_table.item(item, "values")
for column_id, value in zip(column_ids, values, strict=True):
text = str(value or "")
if text:
cell_width = treeview_column_width_px(
self._treeview_cell_font.measure(text),
TREEVIEW_CELL_PAD,
)
widths[column_id] = max(widths[column_id], cell_width)
widths["filename"] = min(widths["filename"], self._scaled(RESULTS_TABLE_FILENAME_ABSOLUTE_MAX))
return widths
# ---------------------------------------------------------------------
# CustomTkinter widget helpers
# ---------------------------------------------------------------------
def _font(self, size: int, weight: str | None = None) -> ctk.CTkFont:
return ctk.CTkFont(family=self._body_font_family, size=size, weight=weight)
def _brand_font(self, size: int) -> ctk.CTkFont:
return ctk.CTkFont(family=self._brand_display_family, size=size, weight="bold")
def _metric_value_font(self, size: int) -> ctk.CTkFont:
return ctk.CTkFont(family=self._metric_value_family, size=size, weight="bold")
def _ui_accent_font(self, size: int, weight: str | None = None) -> ctk.CTkFont:
return ctk.CTkFont(family=self._ui_accent_family, size=size, weight=weight or "normal")
def _mono_font(self, size: int, weight: str | None = None) -> ctk.CTkFont:
resolved = self._resolve_table_font(size, weight=weight)
return ctk.CTkFont(family=resolved.cget("family"), size=size, weight=weight or "normal")
def _entry(
self,
master: Any,
*,
textvariable: tk.Variable | None = None,
width: int | None = None,
height: int = ENTRY_HEIGHT,
size: int = TYPE_BODY,
mono: bool = False,
) -> ctk.CTkEntry:
font = self._mono_font(size) if mono else self._font(size)
kwargs: dict[str, Any] = {
"master": master,
"fg_color": BG_FIELD,
"border_color": BORDER_COLOR,
"text_color": FG_MAIN,
"font": font,
"height": height,
"corner_radius": FIELD_CORNER_RADIUS,
}
if textvariable is not None:
kwargs["textvariable"] = textvariable
if width is not None:
kwargs["width"] = width
return ctk.CTkEntry(**kwargs)
def _section_label(
self,
master: Any,
*,
text: str,
bg: str = BG_MAIN,
anchor: str = "w",
) -> ctk.CTkLabel:
return self._label(
master,
text=text.upper(),
color=FG_MUTED,
bg=bg,
size=TYPE_MICRO,
weight="bold",
anchor=anchor,
)
def _label(
self,
master: Any,
*,
text: str | None = None,
textvariable: tk.Variable | None = None,
color: str = FG_MAIN,
bg: str = BG_CARD,
size: int = TYPE_CAPTION,
weight: str | None = None,
anchor: str = "w",
wraplength: int = 0,
justify: str = "center",
mono: bool = False,
display: bool = False,
accent: bool = False,
) -> ctk.CTkLabel:
if display:
font = self._metric_value_font(size)
elif accent:
font = self._ui_accent_font(size, weight)
elif mono:
font = self._mono_font(size, weight)
else:
font = self._font(size, weight)
kwargs: dict[str, Any] = {
"master": master,
"text": text or "",
"textvariable": textvariable,
"fg_color": "transparent",
"text_color": color,
"font": font,
"anchor": anchor,
"justify": justify,
}
if wraplength > 0:
kwargs["wraplength"] = wraplength
return ctk.CTkLabel(**kwargs)
def _button(
self,
master: Any,
*,
text: str,
command: Any,
accent: bool = False,
state: str = "normal",
) -> ctk.CTkButton:
if accent:
button = ctk.CTkButton(
master,
text=text,
command=command,
fg_color=ACCENT,
hover_color=ACCENT_HOVER,
border_color=ACCENT,
border_width=1,
text_color=BUTTON_TEXT_DARK,
text_color_disabled=BUTTON_DISABLED_TEXT,
font=self._font(TYPE_BODY, "bold"),
height=BUTTON_HEIGHT,
corner_radius=ACTION_BUTTON_CORNER_RADIUS,
)
else:
button = ctk.CTkButton(
master,
text=text,
command=command,
fg_color=BUTTON_SECONDARY_BG,
hover_color=BUTTON_SECONDARY_HOVER,
border_color=BUTTON_SECONDARY_BORDER,
border_width=1,
text_color=FG_MAIN,
text_color_disabled=BUTTON_DISABLED_TEXT,
font=self._font(TYPE_BODY),
height=BUTTON_HEIGHT,
corner_radius=ACTION_BUTTON_CORNER_RADIUS,
)
button._dropgain_accent = accent # type: ignore[attr-defined]
self._apply_action_button_state(button, state)
self._wire_button_hover(button)
def _restore_after_press(b: ctk.CTkButton = button) -> None:
self._apply_action_button_state(b, str(b.cget("state")))
tween = getattr(b, "_dropgain_button_tween", None)
if tween is not None and pointer_inside_widget(b):
tween(True)
wire_ctk_button_press(
button,
lambda b=button: ACCENT_ACTIVE if getattr(b, "_dropgain_accent", False) else BUTTON_SECONDARY_ACTIVE,
restore=_restore_after_press,
)
return button