-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_project_manager_gui.py
More file actions
1677 lines (1400 loc) · 74.9 KB
/
Copy path_project_manager_gui.py
File metadata and controls
1677 lines (1400 loc) · 74.9 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
import customtkinter as ctk
import json
import os
import shutil
from tkinter import filedialog, messagebox
import subprocess
import sys
import threading
import queue
import ctypes
from project_store import ProjectStore, CleanState, MESH_ALIGNED, MESH_GRADED
# Hide the console window so running as .py looks like .pyw (no terminal).
# A real (hidden) console still exists, so child processes (e.g. NumCalc.exe)
# can inherit it without spawning their own console windows.
if sys.platform == 'win32':
_hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if _hwnd:
ctypes.windll.user32.ShowWindow(_hwnd, 0) # SW_HIDE
CREATE_NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
# Appearance Settings
ctk.set_appearance_mode("Dark")
ctk.set_default_color_theme("blue")
# --- COLOR CONSTANTS ---
COLOR_ACTIVE = "#2CC985"
COLOR_DONE = "#3B8ED0"
COLOR_LOCKED = "gray25"
COLOR_ERROR = "#C0392B"
HOVER_ACTIVE = "#209F69"
HOVER_DONE = "#36719F"
class Tooltip:
"""Lightweight tooltip bound to any tkinter/CTk widget."""
def __init__(self, widget, text):
self._widget = widget
self._text = text
self._tip_win = None
widget.bind("<Enter>", self._show, add="+")
widget.bind("<Leave>", self._hide, add="+")
def _show(self, event=None):
if self._tip_win or not self._text:
return
x = self._widget.winfo_rootx() + 20
y = self._widget.winfo_rooty() + self._widget.winfo_height() + 4
self._tip_win = tw = __import__("tkinter").Toplevel(self._widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{x}+{y}")
import tkinter as tk
lbl = tk.Label(
tw, text=self._text, justify="left",
background="#2b2b2b", foreground="#e0e0e0",
relief="solid", borderwidth=1,
font=("Roboto", 10), wraplength=280, padx=6, pady=4
)
lbl.pack()
def _hide(self, event=None):
if self._tip_win:
self._tip_win.destroy()
self._tip_win = None
class MoveCopyDialog(ctk.CTkToplevel):
"""Dialog to ask user whether to Move or Copy a file."""
def __init__(self, parent, filename, callback):
super().__init__(parent)
self.callback = callback
self.result = None
self.title("Import Mesh")
self.geometry("400x180")
self.resizable(False, False)
# Make modal
self.lift()
self.attributes("-topmost", True)
self.focus()
self.grab_set()
# UI
lbl = ctk.CTkLabel(self, text=f"The file '{filename}' is outside the project folder.\n\nWould you like to MOVE or COPY it\nto the project 'Meshes' folder?", font=("Roboto", 13))
lbl.pack(pady=20, padx=20)
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.pack(pady=10, fill="x")
# Buttons
btn_cancel = ctk.CTkButton(btn_frame, text="Cancel", fg_color="transparent", border_width=1, text_color=("gray10", "#DCE4EE"), command=self.on_cancel)
btn_cancel.pack(side="right", padx=10)
btn_move = ctk.CTkButton(btn_frame, text="Move", fg_color="#C0392B", hover_color="#A93226", command=self.on_move)
btn_move.pack(side="right", padx=10)
btn_copy = ctk.CTkButton(btn_frame, text="Copy", fg_color="#2CC985", hover_color="#209F69", command=self.on_copy)
btn_copy.pack(side="right", padx=10)
def on_copy(self):
self.result = "copy"
self.callback(self.result)
self.destroy()
def on_move(self):
self.result = "move"
self.callback(self.result)
self.destroy()
def on_cancel(self):
self.result = None
self.destroy()
class BlenderOpenDialog(ctk.CTkToplevel):
"""Asks whether to overwrite the existing project .blend or open it as-is."""
def __init__(self, parent, proj_name, callback):
super().__init__(parent)
self.callback = callback
self.title("Open in Blender")
self.geometry("440x190")
self.resizable(False, False)
self.lift()
self.attributes("-topmost", True)
self.focus()
self.grab_set()
lbl = ctk.CTkLabel(self,
text=f"A Blender file for '{proj_name}' already exists.\n\n"
"Open the existing file without changes?\n"
"or Overwrite it (delete and re-import the graded meshes),\n"
,
font=("Roboto", 13))
lbl.pack(pady=20, padx=20)
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.pack(pady=10, fill="x")
ctk.CTkButton(btn_frame, text="Cancel", fg_color="transparent", border_width=1,
text_color=("gray10", "#DCE4EE"), command=self.on_cancel).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Overwrite Existing", fg_color="#C0392B",
hover_color="#A93226", command=self.on_overwrite).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Open Existing", fg_color="#2CC985",
hover_color="#209F69", command=self.on_open).pack(side="right", padx=10)
def on_overwrite(self): self.callback("overwrite"); self.destroy()
def on_open(self): self.callback("open"); self.destroy()
def on_cancel(self): self.destroy()
class NumCalcOptionsDialog(ctk.CTkToplevel):
"""Asks whether to run a stability test, the full simulation, or cancel."""
def __init__(self, parent, freq_label, callback):
super().__init__(parent)
self.callback = callback
self.title("Run NumCalc Simulation")
self.geometry("460x210")
self.resizable(False, False)
self.lift()
self.attributes("-topmost", True)
self.focus()
self.grab_set()
lbl = ctk.CTkLabel(self,
text=f"Run a quick STABILITY TEST ({freq_label}) on both ears,\n"
"or start the FULL simulation?\n\n"
"(The full simulation is very compute-intensive and\n"
"can take 8-24 hours.)",
font=("Roboto", 13))
lbl.pack(pady=20, padx=20)
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.pack(pady=10, fill="x")
ctk.CTkButton(btn_frame, text="Cancel", fg_color="transparent", border_width=1,
text_color=("gray10", "#DCE4EE"), command=self.on_cancel).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Full Sim", fg_color="#C0392B",
hover_color="#A93226", command=self.on_full).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Test Only", fg_color="#2CC985",
hover_color="#209F69", command=self.on_test).pack(side="right", padx=10)
def on_test(self): self.callback("test"); self.destroy()
def on_full(self): self.callback("full"); self.destroy()
def on_cancel(self): self.destroy()
class TiltSettingsDialog(ctk.CTkToplevel):
"""Popup window for DFHRTF Generation (Spectral Tilt)"""
def __init__(self, parent, callback):
super().__init__(parent)
self.callback = callback
self.title("Generate Extras")
self.geometry("400x250")
self.lift()
self.attributes("-topmost", True)
self.focus()
self.lbl = ctk.CTkLabel(self, text="Spectral Tilt Settings", font=("Roboto Medium", 16))
self.lbl.pack(pady=20)
self.frame = ctk.CTkFrame(self)
self.frame.pack(pady=10, padx=20, fill="x")
self.lbl_tilt = ctk.CTkLabel(self.frame, text="Tilt (dB/octave):")
self.lbl_tilt.grid(row=0, column=0, padx=10, pady=20)
self.entry_tilt = ctk.CTkEntry(self.frame, placeholder_text="0.0")
self.entry_tilt.grid(row=0, column=1, padx=10, pady=20)
self.entry_tilt.insert(0, "0.0") # Default
self.btn_run = ctk.CTkButton(self, text="Generate CSV & Plot", fg_color="green", command=self.on_confirm)
self.btn_run.pack(pady=20, padx=20, fill="x")
def on_confirm(self):
try:
val = float(self.entry_tilt.get())
self.callback(val)
self.destroy()
except ValueError:
messagebox.showerror("Error", "Please enter a valid number for tilt (e.g. -1.0 or 0).")
class VTKSettingsDialog(ctk.CTkToplevel):
"""Popup window for VTK Export (Frequency Range)"""
def __init__(self, parent, callback):
super().__init__(parent)
self.callback = callback
self.title("Generate Paraview VTK Files")
self.geometry("400x250")
self.lift()
self.attributes("-topmost", True)
self.focus()
self.lbl = ctk.CTkLabel(self, text="VTK Export Settings", font=("Roboto Medium", 16))
self.lbl.pack(pady=20)
self.frame = ctk.CTkFrame(self)
self.frame.pack(pady=10, padx=20, fill="x")
# Min Freq
self.lbl_min = ctk.CTkLabel(self.frame, text="Min Freq (Hz):")
self.lbl_min.grid(row=0, column=0, padx=10, pady=10, sticky="w")
self.entry_min = ctk.CTkEntry(self.frame, placeholder_text="1000")
self.entry_min.grid(row=0, column=1, padx=10, pady=10, sticky="ew")
self.entry_min.insert(0, "1000")
# Max Freq
self.lbl_max = ctk.CTkLabel(self.frame, text="Max Freq (Hz):")
self.lbl_max.grid(row=1, column=0, padx=10, pady=10, sticky="w")
self.entry_max = ctk.CTkEntry(self.frame, placeholder_text="16000")
self.entry_max.grid(row=1, column=1, padx=10, pady=10, sticky="ew")
self.entry_max.insert(0, "16000")
self.frame.grid_columnconfigure(1, weight=1)
self.btn_run = ctk.CTkButton(self, text="Generate VTK Files", fg_color="green", command=self.on_confirm)
self.btn_run.pack(pady=10, padx=20, fill="x")
def on_confirm(self):
try:
min_freq = float(self.entry_min.get())
max_freq = float(self.entry_max.get())
if min_freq < 0 or max_freq < min_freq:
raise ValueError
self.callback(min_freq, max_freq)
self.destroy()
except ValueError:
messagebox.showerror("Error", "Please enter valid positive numbers (Min <= Max).")
class GridSelectionDialog(ctk.CTkToplevel):
"""Dialog to allow multi-selection of evaluation grids."""
def __init__(self, parent, available_grids, selected_grids_str, callback):
super().__init__(parent)
self.callback = callback
self.title("Select Evaluation Grids")
self.geometry("350x400")
self.attributes('-topmost', True)
self.focus_force()
self.grab_set()
self.lbl_title = ctk.CTkLabel(self, text="Select Grids to Process:", font=("Roboto", 14, "bold"))
self.lbl_title.pack(pady=15)
self.scroll_frame = ctk.CTkScrollableFrame(self, width=300, height=250)
self.scroll_frame.pack(pady=10, padx=20, fill="both", expand=True)
self.checkboxes = {}
selected_list = [g.strip() for g in selected_grids_str.split(",")] if selected_grids_str else []
for grid in available_grids:
var = ctk.StringVar(value="on" if grid in selected_list else "off")
cb = ctk.CTkCheckBox(self.scroll_frame, text=grid, variable=var, onvalue="on", offvalue="off")
cb.pack(pady=5, anchor="w")
self.checkboxes[grid] = var
self.btn_save = ctk.CTkButton(self, text="Save Selection", fg_color="green", command=self.on_save)
self.btn_save.pack(pady=15)
def on_save(self):
selected = [grid for grid, var in self.checkboxes.items() if var.get() == "on"]
self.callback(",".join(selected))
self.destroy()
class MeshQualityDialog(ctk.CTkToplevel):
"""Dialog shown when graded meshes have critical quality issues (blocks Blender)."""
def __init__(self, parent, mesh_path, callback):
super().__init__(parent)
self.callback = callback
self.mesh_path = mesh_path
self.title("Mesh Quality Issues — Blender Blocked")
self.geometry("500x210")
self.resizable(False, False)
self.lift()
self.attributes("-topmost", True)
self.focus()
self.grab_set()
lbl = ctk.CTkLabel(self,
text="One or more graded meshes have critical quality issues.\n"
"The Blender step is blocked until they are resolved.\n\n"
"Repair automatically, or open the problem viewer to inspect.",
font=("Roboto", 13))
lbl.pack(pady=20, padx=20)
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.pack(pady=10, fill="x")
ctk.CTkButton(btn_frame, text="Cancel", fg_color="transparent", border_width=1,
text_color=("gray10", "#DCE4EE"), command=self.on_cancel).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Visualize Problems", fg_color="#C0392B",
hover_color="#A93226", command=self.on_visualize).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Attempt Repair", fg_color="#2CC985",
hover_color="#209F69", command=self.on_repair).pack(side="right", padx=10)
def on_repair(self): self.callback("repair", self.mesh_path); self.destroy()
def on_visualize(self): self.callback("visualize", self.mesh_path); self.destroy()
def on_cancel(self): self.destroy()
class AlignedMeshDialog(ctk.CTkToplevel):
"""Dialog for the standalone 'Inspect & Fix Mesh' step (operates on the
aligned mesh). Repair is suppressed when the only criticals are topological
tunnels (genus>0), which geometric repair cannot fix — those go to the
interactive tunnel viewer for click-to-select + cut & cap."""
def __init__(self, parent, mesh_dir, summary, tunnel_only, callback):
super().__init__(parent)
self.callback = callback
self.mesh_dir = mesh_dir
self.title("Mesh Quality Issues — Inspect & Fix")
self.geometry("560x300")
self.resizable(False, False)
self.lift()
self.attributes("-topmost", True)
self.focus()
self.grab_set()
if tunnel_only:
hint = ("Topological tunnel(s) detected. Geometric repair cannot fix these —\n"
"open the tunnel viewer, click the cut loop, and Apply Cut & Cap.")
else:
hint = ("Critical mesh issues found. Attempt Repair (pymeshfix) to clean\n"
"self-intersections / non-manifold / boundaries, then re-inspect.")
ctk.CTkLabel(self, text=hint, font=("Roboto", 13), justify="left").pack(pady=(16, 6), padx=20)
box = ctk.CTkTextbox(self, height=110, width=520)
box.pack(pady=6, padx=20, fill="both", expand=False)
box.insert("end", summary)
box.configure(state="disabled")
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.pack(pady=10, fill="x")
ctk.CTkButton(btn_frame, text="Cancel", fg_color="transparent", border_width=1,
text_color=("gray10", "#DCE4EE"), command=self.on_cancel).pack(side="right", padx=10)
ctk.CTkButton(btn_frame, text="Fix Tunnels (Viewer)", fg_color="#C0392B",
hover_color="#A93226", command=self.on_visualize).pack(side="right", padx=10)
if not tunnel_only:
ctk.CTkButton(btn_frame, text="Attempt Repair", fg_color="#2CC985",
hover_color="#209F69", command=self.on_repair).pack(side="right", padx=10)
def on_repair(self): self.callback("repair", self.mesh_dir); self.destroy()
def on_visualize(self): self.callback("visualize", self.mesh_dir); self.destroy()
def on_cancel(self): self.destroy()
class HRTFProjectManager(ctk.CTk):
def __init__(self):
super().__init__()
# Window Setup
self.title("Mesh2SOFA")
self.geometry("800x800")
self.app_settings_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app_settings.json")
self.app_settings = {
"mesh2hrtf_path": "C:/Mesh2HRTF/mesh2hrtf",
"blender_path": "",
"grading_bin_path": os.getcwd()
}
self.load_app_settings()
# Data State
self.project_data = {
"base_path": "",
"project_resolution": "standard", # Default: standard or lowres
"scripts_path": os.path.dirname(os.path.abspath(__file__)),
"eval_grid": "",
"raw_scan": "",
"progress": 0
}
# Process Management
self.current_process = None
self.log_queue = queue.Queue()
self.is_running = False
# Layout Configuration
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=0)
self.grid_rowconfigure(1, weight=0)
self.grid_rowconfigure(2, weight=1)
self.create_widgets()
self.update_ui_from_data()
# Start checking the log queue
self.check_log_queue()
def create_widgets(self):
# --- TITLE AREA ---
self.frame_top = ctk.CTkFrame(self, fg_color="transparent")
self.frame_top.grid(row=0, column=0, pady=20, padx=20, sticky="ew")
self.lbl_title = ctk.CTkLabel(self.frame_top, text="No Project Loaded", font=("Roboto Medium", 24))
self.lbl_title.pack(side="left")
self.lbl_title.bind("<Button-1>", self.open_project_folder)
self.lbl_title.bind("<Enter>", lambda e: self.lbl_title.configure(cursor="hand2", text_color="#7ecfad"))
self.lbl_title.bind("<Leave>", lambda e: self.lbl_title.configure(cursor="", text_color="white"))
self.frame_controls = ctk.CTkFrame(self.frame_top, fg_color="transparent")
self.frame_controls.pack(side="right")
self.btn_refresh = ctk.CTkButton(self.frame_controls, text="Refresh", width=80, command=self.manual_refresh)
self.btn_refresh.pack(side="right", padx=5)
self.btn_load = ctk.CTkButton(self.frame_controls, text="Open", width=80, fg_color="#444", command=self.load_project_json)
self.btn_load.pack(side="right", padx=5)
self.btn_new = ctk.CTkButton(self.frame_controls, text="New", width=80, fg_color="#28a745", hover_color="#218838", command=self.create_new_project)
self.btn_new.pack(side="right", padx=5)
# --- SECTION 1: PATHS & CONFIG ---
self.tabview_config = ctk.CTkTabview(self, height=0)
self.tabview_config.grid(row=1, column=0, padx=20, pady=(10, 0), sticky="ew")
self.tabview_config.add(" App Settings ")
self.tabview_config.add(" Project Settings ")
self.tabview_config.set(" App Settings ")
tab_app = self.tabview_config.tab(" App Settings ")
tab_app.grid_columnconfigure(1, weight=1)
tab_proj = self.tabview_config.tab(" Project Settings ")
tab_proj.grid_columnconfigure(1, weight=1)
# APP TAB PATH BUTTONS
self.add_config_row(0, "Mesh2HRTF Root:", "entry_m2h", "C:/Mesh2HRTF", browse_cmd=self.browse_m2h, parent_frame=tab_app)
self.add_config_row(1, "Blender Executable:", "entry_blender", "Path to blender.exe...", browse_cmd=self.browse_blender, parent_frame=tab_app)
self.add_config_row(2, "Mesh Grading Tool Bin:", "entry_bins", os.getcwd(), browse_cmd=self.browse_bins, parent_frame=tab_app)
# PROJECT TAB PATH BUTTONS
# entry_base must exist for all base-path readers (.get()/.insert()), but the
# folder is no longer user-selectable — it is derived from project.json location.
self.entry_base = ctk.CTkEntry(tab_proj, placeholder_text="Select project root...")
# (intentionally not gridded — kept hidden as the base-path store)
# Resolution mode toggle (replaces the old Project Folder row)
_MODE_LABELS = {
"standard": "Standard (18 kHz Max)",
"lowres": "Lowres (16 kHz Max)",
}
self._mode_label_to_value = {v: k for k, v in _MODE_LABELS.items()}
self._mode_value_to_label = _MODE_LABELS
lbl_mode = ctk.CTkLabel(tab_proj, text="Project Mode:")
lbl_mode.grid(row=0, column=0, padx=10, pady=5, sticky="w")
self.seg_mode = ctk.CTkSegmentedButton(
tab_proj,
values=list(_MODE_LABELS.values()),
command=self.on_mode_changed,
)
self.seg_mode.grid(row=0, column=1, padx=10, pady=5, sticky="ew")
self.seg_mode.set(_MODE_LABELS["standard"]) # default; updated in update_ui_from_data
# Tooltips are attached after the widget is rendered so _buttons_dict is populated.
self.after(100, self._attach_mode_tooltips)
lbl_grid = ctk.CTkLabel(tab_proj, text="Evaluation Grid(s):")
lbl_grid.grid(row=1, column=0, padx=10, pady=5, sticky="w")
self.entry_grid = ctk.CTkEntry(tab_proj, placeholder_text="Set Mesh2HRTF Path first...", state="disabled")
self.entry_grid.grid(row=1, column=1, padx=10, pady=5, sticky="ew")
self.btn_select_grids = ctk.CTkButton(tab_proj, text="Select Grids", width=80, command=self.open_grid_dialog)
self.btn_select_grids.grid(row=1, column=2, padx=10, pady=5)
self.add_config_row(2, "Raw Mesh:", "entry_raw", "Browse to import a raw mesh (.obj/.ply/.stl)...", browse_cmd=self.browse_raw, parent_frame=tab_proj)
# Read-only: the only way to set a raw mesh is via Browse → import.
# Freetyping does nothing (the field is only ever read, never triggers
# import), and now disabling the field makes that explicit.
self.entry_raw.configure(state="disabled")
# --- SECTION 2: WORKFLOW ACTIONS ---
self.frame_actions = ctk.CTkFrame(self)
self.frame_actions.grid(row=2, column=0, padx=20, pady=(5, 20), sticky="nsew")
self.lbl_workflow = ctk.CTkLabel(self.frame_actions, text="Workflow Steps", font=("Roboto Medium", 18))
self.lbl_workflow.grid(row=0, column=0, padx=10, pady=5, sticky="w")
# WORKFLOW BUTTONS
self.btn_align = ctk.CTkButton(self.frame_actions, text="1. Align Mesh", command=self.run_alignment)
self.btn_align.grid(row=1, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.btn_inspect = ctk.CTkButton(self.frame_actions, text="2. Inspect & Fix Mesh", command=self.run_inspect_fix)
self.btn_inspect.grid(row=2, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.btn_process = ctk.CTkButton(self.frame_actions, text="3. Process & Grade Mesh", command=self.run_processing)
self.btn_process.grid(row=3, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.btn_blender = ctk.CTkButton(self.frame_actions, text="4. Open Graded Meshes in Blender (Setup Scene)", command=self.run_blender_setup)
self.btn_blender.grid(row=4, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.btn_export = ctk.CTkButton(self.frame_actions, text="5. Export Project Folders (Manual/Script)", state="disabled", fg_color="gray30", text_color="gray")
self.btn_export.grid(row=5, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.btn_numcalc = ctk.CTkButton(self.frame_actions, text="6. Run NumCalc Simulation", command=self.run_numcalc)
self.btn_numcalc.grid(row=6, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.btn_sofa = ctk.CTkButton(self.frame_actions, text="7. Generate Mastered SOFA Files", command=self.run_sofa_generation)
self.btn_sofa.grid(row=7, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
# EXTRAS SECTION
self.lbl_extras_spacer = ctk.CTkLabel(self.frame_actions, text="EXTRAS", font=("Roboto Medium", 12))
self.lbl_extras_spacer.grid(row=8, column=0, columnspan=2, pady=(10, 0))
self.frame_extras = ctk.CTkFrame(self.frame_actions, fg_color="transparent")
self.frame_extras.grid(row=9, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.frame_extras.grid_columnconfigure(0, weight=1)
self.frame_extras.grid_columnconfigure(1, weight=1)
self.btn_extras = ctk.CTkButton(self.frame_extras, text="Generate DFHRTF Files", command=self.open_tilt_dialog)
self.btn_extras.grid(row=0, column=0, padx=(0, 5), sticky="ew")
self.btn_vtk = ctk.CTkButton(self.frame_extras, text="Generate Paraview VTK Files", command=self.open_vtk_dialog)
self.btn_vtk.grid(row=0, column=1, padx=(5, 0), sticky="ew")
# LOGGING AREA
self.textbox = ctk.CTkTextbox(self.frame_actions, height=150)
self.textbox.grid(row=10, column=0, columnspan=2, padx=10, pady=10, sticky="nsew")
self.btn_stop = ctk.CTkButton(self.frame_actions, text="STOP PROCESS", fg_color=COLOR_ERROR, state="disabled", command=self.kill_process)
self.btn_stop.grid(row=11, column=0, columnspan=2, padx=10, pady=5, sticky="ew")
self.frame_actions.grid_rowconfigure(10, weight=1)
self.frame_actions.grid_columnconfigure(0, weight=1)
def add_config_row(self, row, label_text, attr_name, placeholder, browse_cmd=None, parent_frame=None):
parent = parent_frame if parent_frame else self.frame_config
lbl = ctk.CTkLabel(parent, text=label_text)
lbl.grid(row=row, column=0, padx=10, pady=5, sticky="w")
entry = ctk.CTkEntry(parent, placeholder_text=placeholder)
entry.grid(row=row, column=1, padx=10, pady=5, sticky="ew")
setattr(self, attr_name, entry)
if browse_cmd:
btn = ctk.CTkButton(parent, text="Browse", width=80, command=browse_cmd)
btn.grid(row=row, column=2, padx=10, pady=5)
# --- PROCESS & LOGGING ENGINE ---
def run_external_command(self, cmd_list, cwd=None, shell=False):
"""Standard runner for single process"""
if self.is_running: return self.log("[!] Process running...")
def target():
self.is_running = True
self.btn_stop.configure(state="normal")
try:
self.current_process = subprocess.Popen(
cmd_list, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1, universal_newlines=True, shell=shell, creationflags=CREATE_NO_WINDOW
)
for line in iter(self.current_process.stdout.readline, ''):
self.log_queue.put(line.strip())
self.current_process.stdout.close()
rc = self.current_process.wait()
if rc == 0: self.log_queue.put("[+] Success.")
else: self.log_queue.put(f"[X] Failed (Code {rc}).")
except Exception as e:
self.log_queue.put(f"[!] Error: {str(e)}")
finally:
self.current_process = None
self.is_running = False
self.log_queue.put("DONE")
t = threading.Thread(target=target, daemon=True)
t.start()
def run_sequential_commands(self, cmd_list_of_lists):
"""Runs multiple commands sequentially in the same thread (for NumCalc Left then Right)"""
if self.is_running: return self.log("[!] Process running...")
def target():
self.is_running = True
self.btn_stop.configure(state="normal")
for cmd in cmd_list_of_lists:
if not self.is_running: break # Stop requested
try:
# Log which script is starting (e.g. Left or Right)
desc = "NumCalc Step"
if "Left" in str(cmd): desc = "Left Ear Simulation"
elif "Right" in str(cmd): desc = "Right Ear Simulation"
self.log_queue.put(f"--> Starting: {desc}...")
self.current_process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1, universal_newlines=True, creationflags=CREATE_NO_WINDOW
)
for line in iter(self.current_process.stdout.readline, ''):
self.log_queue.put(line.strip())
self.current_process.stdout.close()
rc = self.current_process.wait()
if rc != 0:
self.log_queue.put(f"[!] Step failed with code {rc}")
break
except Exception as e:
self.log_queue.put(f"[!] Execution Error: {e}")
break
self.current_process = None
self.is_running = False
self.log_queue.put("DONE")
t = threading.Thread(target=target, daemon=True)
t.start()
def check_log_queue(self):
try:
while True:
msg = self.log_queue.get_nowait()
if msg == "DONE":
self.manual_refresh()
self.btn_stop.configure(state="disabled")
if getattr(self, '_pending_mesh_check', False):
self._pending_mesh_check = False
self.after(200, self._check_mesh_quality_result)
if getattr(self, '_pending_inspect_check', False):
self._pending_inspect_check = False
self.after(200, self._check_aligned_quality_result)
if getattr(self, '_pending_import_check', False):
self._pending_import_check = False
self.after(200, self._check_import_result)
if getattr(self, '_pending_cutcap_revalidate', False):
self._pending_cutcap_revalidate = False
self.after(200, self._after_cutcap_revalidated)
else:
self.log(msg, timestamp=False)
except queue.Empty:
pass
self.after(100, self.check_log_queue)
def kill_process(self):
self.is_running = False # Flags the loops to stop
if self.current_process:
self.log("[!] Attempting to stop script...")
try: self.current_process.kill()
except: pass
# FORCE KILL NUMCALC (Windows)
if sys.platform == 'win32':
subprocess.run("taskkill /F /IM NumCalc.exe", shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=CREATE_NO_WINDOW)
self.log("[!] Terminated NumCalc.exe background processes.")
def log(self, message, timestamp=True):
self.textbox.configure(state="normal")
if timestamp:
from datetime import datetime
prefix = datetime.now().strftime("[%H:%M:%S] ")
self.textbox.insert("end", f"{prefix}{message}\n")
else:
self.textbox.insert("end", f"{message}\n")
self.textbox.see("end")
self.textbox.configure(state="disabled")
# --- SETTINGS HANDLERS ---
def update_settings(self, new_res):
self.project_data["project_resolution"] = new_res
self.log(f"Project Resolution set to: {new_res.upper()}")
self.save_project_json(silent=True)
def on_mode_changed(self, label):
"""Called when the user clicks a segment on the Project Mode toggle."""
value = self._mode_label_to_value.get(label, "standard")
self.update_settings(value)
def _attach_mode_tooltips(self):
"""Bind tooltips to each internal segment button after they are rendered."""
_tips = {
"Standard (18 kHz Max)": (
"Standard mode: outputs up to 18 kHz.\n"
"Higher mesh resolution — requires more RAM and longer NumCalc simulation time."
),
"Lowres (16 kHz Max)": (
"Lowres mode: outputs up to 16 kHz.\n"
"Lower mesh resolution — uses less RAM and runs faster."
),
}
try:
for label, tip_text in _tips.items():
btn = self.seg_mode._buttons_dict.get(label)
if btn:
Tooltip(btn, tip_text)
except Exception:
pass # Gracefully ignore if internal CTk API changes
def open_project_folder(self, event=None):
"""Open the current project folder in the OS file browser (cross-platform)."""
path = self.entry_base.get()
if not path or not os.path.isdir(path):
self.log("[!] No project folder loaded.")
return
try:
if sys.platform == "win32":
os.startfile(path)
elif sys.platform == "darwin":
subprocess.Popen(["open", path])
else:
subprocess.Popen(["xdg-open", path])
except Exception as e:
self.log(f"[!] Could not open folder: {e}")
# --- PROJECT CREATION & PATHS ---
def create_new_project(self):
target_dir = filedialog.askdirectory(title="Select Folder for New Project")
if not target_dir: return
folders = ["Meshes", "Exports", "Output"]
created_log = []
for folder in folders:
path = os.path.join(target_dir, folder)
if not os.path.exists(path):
try:
os.makedirs(path)
created_log.append(folder)
except Exception as e:
self.log(f"Error creating {folder}: {e}")
self.log(f"Project created at: {target_dir}")
self.entry_base.delete(0, "end")
self.entry_base.insert(0, target_dir)
self._set_entry_raw()
self.save_project_json(silent=True)
self.update_workflow_state()
def get_project_name(self):
base_path = self.entry_base.get()
if base_path and os.path.isdir(base_path):
return os.path.basename(os.path.normpath(base_path))
return "Project"
def get_mesh_dir(self):
return ProjectStore(self.entry_base.get()).mesh_dir
def _set_entry_raw(self, value=""):
"""Write to the read-only Raw Mesh field (briefly enable → set → disable)."""
self.entry_raw.configure(state="normal")
self.entry_raw.delete(0, "end")
if value:
self.entry_raw.insert(0, value)
self.entry_raw.configure(state="disabled")
def _rel_to_base(self, abs_path, base):
"""Convert abs_path to a path relative to base, if it's under base."""
try:
if abs_path and os.path.isabs(abs_path) and base:
rel = os.path.relpath(abs_path, base)
if not rel.startswith(".."): # only if actually inside base
return rel
except ValueError:
pass # different drive on Windows — fall through
return abs_path
def _abs_from_base(self, stored, base):
"""Resolve a stored (possibly relative) raw_scan path back to absolute."""
if stored and not os.path.isabs(stored) and base:
return os.path.normpath(os.path.join(base, stored))
return stored
# --- SMART MESH2HRTF LOGIC ---
def get_valid_m2h_input_path(self):
raw_path = self.entry_m2h.get()
if not raw_path or not os.path.exists(raw_path): return None
candidate_1 = os.path.join(raw_path, "mesh2hrtf", "Mesh2Input")
if os.path.exists(candidate_1): return candidate_1
candidate_2 = os.path.join(raw_path, "Mesh2Input")
if os.path.exists(candidate_2): return candidate_2
return None
def get_available_grids(self):
m2h_input = self.get_valid_m2h_input_path()
if not m2h_input:
self.log("Error: Could not locate 'Mesh2Input' folder in Mesh2HRTF path.")
return []
grid_path = os.path.join(m2h_input, "EvaluationGrids", "Data")
if os.path.exists(grid_path):
folders = [f for f in os.listdir(grid_path) if os.path.isdir(os.path.join(grid_path, f))]
return folders
else:
self.log(f"Error: Could not find grids at {grid_path}")
return []
def open_grid_dialog(self):
available_grids = self.get_available_grids()
if not available_grids:
return
def on_grids_selected(selected_grids_str):
self.entry_grid.configure(state="normal")
self.entry_grid.delete(0, "end")
self.entry_grid.insert(0, selected_grids_str)
self.entry_grid.configure(state="disabled")
self.save_project_json()
GridSelectionDialog(self, available_grids, self.entry_grid.get(), on_grids_selected)
def get_binary_path(self, tool_name):
root = os.path.normpath(self.entry_m2h.get())
candidates = [
os.path.join(root, tool_name, "bin", f"{tool_name}.exe"),
os.path.join(root, "mesh2hrtf", tool_name, "bin", f"{tool_name}.exe"),
os.path.join(root, tool_name, f"{tool_name}.exe")
]
for p in candidates:
if os.path.exists(p): return p
return None
# --- BROWSERS ---
def browse_base(self): self._browse_dir(self.entry_base)
def browse_m2h(self): self._browse_dir(self.entry_m2h)
# --- Hopefully now works on both Mac & Windows ---
def browse_bins(self):
# 1. Determine expected binary name for the title
bin_name = "hrtf_mesh_grading.exe" if sys.platform == "win32" else "hrtf_mesh_grading"
# 2. Set filetypes
if sys.platform == "win32":
filetypes = [("Executables", "*.exe"), ("All Files", "*.*")]
else:
filetypes = [("All Files", "*.*")]
# 3. Ask for the FILE, not the directory
kwargs = {"title": f"Select {bin_name}", "filetypes": filetypes}
current_path = self.entry_bins.get()
if current_path and os.path.exists(os.path.dirname(current_path)):
kwargs["initialdir"] = os.path.dirname(current_path)
path = filedialog.askopenfilename(**kwargs)
if path:
self.entry_bins.delete(0, "end")
self.entry_bins.insert(0, path)
self.save_project_json()
def _browse_dir(self, entry_widget):
kwargs = {}
current_path = entry_widget.get()
if current_path and os.path.isdir(current_path):
kwargs["initialdir"] = current_path
elif current_path and os.path.exists(os.path.dirname(current_path)):
kwargs["initialdir"] = os.path.dirname(current_path)
path = filedialog.askdirectory(**kwargs)
if path:
entry_widget.delete(0, "end")
entry_widget.insert(0, path)
self.update_workflow_state()
# --- Hopefully now works on both Mac & Windows ---
def browse_blender(self):
# 1. Define filetypes based on OS
if sys.platform == "win32":
filetypes = [("Executables", "*.exe"), ("All Files", "*.*")]
else:
# On macOS/Linux, allow all files so we can select binaries with no extension
filetypes = [("All Files", "*.*")]
kwargs = {"title": "Select Blender Executable", "filetypes": filetypes}
current_path = self.entry_blender.get()
if current_path and os.path.exists(os.path.dirname(current_path)):
kwargs["initialdir"] = os.path.dirname(current_path)
path = filedialog.askopenfilename(**kwargs)
if path:
# 2. Smart handling for macOS .app bundles
# If the user selected 'Blender.app', we point to the internal binary
if sys.platform == "darwin" and path.endswith(".app"):
potential_binary = os.path.join(path, "Contents", "MacOS", "Blender")
if os.path.exists(potential_binary):
path = potential_binary
self.entry_blender.delete(0, "end")
self.entry_blender.insert(0, path)
self.save_project_json()
# --- Formal mesh import: Browse → Move/Copy → inspect+dissolve+repair ---
def browse_raw(self):
# 1. Check project folder
if not self.entry_base.get():
return messagebox.showerror("Error", "Please define a Project Folder first.")
# 2. Hard-require Blender (sliver dissolve only works via Blender).
blender_exe = self.entry_blender.get()
if not blender_exe or not os.path.exists(blender_exe):
return messagebox.showerror(
"Blender Required",
"A valid Blender path must be set in App Settings before importing a mesh.\n\n"
"Blender is required to remove tiny sliver triangles that pymeshlab\n"
"cannot fix. Please configure 'Blender Executable' above and try again.",
)
# 3. Open file dialog
kwargs = {"filetypes": [("3D Mesh", "*.obj *.ply *.stl")]}
current_path = self.entry_raw.get()
base_path = self.entry_base.get()
if current_path and os.path.exists(os.path.dirname(current_path)):
kwargs["initialdir"] = os.path.dirname(current_path)
elif base_path and os.path.isdir(base_path):
kwargs["initialdir"] = base_path
src_path = filedialog.askopenfilename(**kwargs)
if not src_path:
return
# 4. Determine destination in Meshes/
project_mesh_dir = self.get_mesh_dir()
if not os.path.exists(project_mesh_dir):
os.makedirs(project_mesh_dir, exist_ok=True)
src_dir = os.path.dirname(os.path.normpath(src_path))
dest_dir = os.path.normpath(project_mesh_dir)
filename = os.path.basename(src_path)
dest_path = os.path.join(dest_dir, filename)
# 4b. Warn before discarding prior pipeline work for this project.
existing_artifacts = self._store(project_mesh_dir).list_mesh_artifacts()
if existing_artifacts:
artifact_list = "\n ".join(existing_artifacts)
if not messagebox.askyesno(
"Replace Current Mesh?",
"Importing a new mesh will DELETE the existing aligned / graded / "
"inspection files in the Meshes folder:\n\n"
f" {artifact_list}\n\n"
"Alignment and Inspect & Fix (cut & cap) must be redone for the "
"new mesh.\n\nContinue?",
):
return
# 5. After the file lands in Meshes/, run the import worker.
def finalize_selection(final_path):
self._set_entry_raw(final_path)
# New base mesh — prior alignment / inspection / grading no longer
# apply. Clear them so Align + Inspect & Fix must be redone.
removed = self._store(project_mesh_dir).reset_mesh_artifacts()
if removed:
self.log(
"--> Cleared prior mesh artifacts: "
+ ", ".join(removed)
)
self.save_project_json(silent=True)
self.update_workflow_state()
# Guard: don't queue a second process if one is already running.
if self.is_running:
self.log("[!] A process is already running — import queued next time.")
return
scripts_dir = os.path.dirname(os.path.abspath(__file__))