-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharGUIments.py
More file actions
1481 lines (1184 loc) · 66.8 KB
/
Copy patharGUIments.py
File metadata and controls
1481 lines (1184 loc) · 66.8 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 os
import tkinter as tk
from tkinter import simpledialog, messagebox, scrolledtext, filedialog
import tkinter.ttk as ttk
from tkinter import PhotoImage
from tkinter.ttk import Progressbar
import tkinter.font as tkFont
import subprocess
import threading
import json
import signal
import configparser
import sys
import shlex
import re
import time
import queue
import webbrowser
from rich.console import Console
from rich.text import Text
console_stream = Console(force_terminal=True)
def get_base_path():
if getattr(sys, 'frozen', False):
# Running as bundled executable
return os.path.dirname(sys.executable)
else:
# Running as normal Python script
return os.path.dirname(os.path.abspath(__file__))
BASE_DIR_SETTINGS = get_base_path()
if hasattr(sys, '_MEIPASS'):
BASE_DIR = sys._MEIPASS
else:
BASE_DIR = os.path.abspath(".")
# PROFILE_FILE = "profiles.json"
# SETTINGS_FILE = "settings.ini"
PROFILE_FILE = os.path.join(BASE_DIR_SETTINGS, "profiles.json")
SETTINGS_FILE = os.path.join(BASE_DIR_SETTINGS, "settings.ini")
yt_process = None
class Tooltip:
instances = []
def __init__(self, widget, text, showtool=None):
self.widget = widget
self.text = text
self.tip = None
# None means: dynamically check settings each time
# True/False means: force on/off always
self.static_override = showtool
Tooltip.instances.append(self)
# Always bind so we can evaluate at hover time
self.widget.bind("<Enter>", self.on_enter)
self.widget.bind("<Leave>", self.on_leave)
def on_enter(self, event=None):
from __main__ import showtipsvalue
should_show = (
self.static_override is True
or (self.static_override is None and showtipsvalue)
)
if should_show:
self.show_tooltip()
def on_leave(self, event=None):
self.hide_tooltip()
def show_tooltip(self):
if self.tip:
return
x = self.widget.winfo_rootx() + 20
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 10
self.tip = tk.Toplevel(self.widget)
self.tip.wm_overrideredirect(True)
self.tip.wm_geometry(f"+{x}+{y}")
label = tk.Label(
self.tip,
text=self.text,
background="lightyellow",
borderwidth=1,
relief="solid",
font=("Segoe UI", 9)
)
label.pack(ipadx=5, ipady=2)
def hide_tooltip(self):
if self.tip:
self.tip.destroy()
self.tip = None
@classmethod
def refresh_all(cls):
for inst in cls.instances:
inst.hide_tooltip()
# ============ SETTINGS =============
def load_settings():
global showtipsvalue
# config = configparser.ConfigParser()
config = configparser.ConfigParser(interpolation=None)
if not os.path.exists(SETTINGS_FILE):
config['DEFAULT'] = {
'software_path': 'yt-dlp',
'output_flag': '--output',
'output_folder': '',
'filename_template': '%(title)s.%(ext)s',
'show_hints': 'True'
}
with open(SETTINGS_FILE, 'w') as f:
config.write(f)
else:
config.read(SETTINGS_FILE)
showtipsvalue = config['DEFAULT'].getboolean('show_hints', '')
return config
def save_settings(config):
global showtipsvalue
showtipsvalue = config['DEFAULT'].getboolean('show_hints', '')
with open(SETTINGS_FILE, 'w') as f:
config.write(f)
settings = load_settings()
# ============ PROFILES =============
def load_profiles():
if os.path.exists(PROFILE_FILE):
with open(PROFILE_FILE, 'r') as f:
return json.load(f)
return {}
def save_profiles(profiles):
with open(PROFILE_FILE, 'w') as f:
json.dump(profiles, f, indent=2)
profiles = load_profiles()
# ============ COMMAND RUNNER ============
def build_command(shortname, user_args):
profile = profiles.get(shortname)
if not profile:
raise ValueError("Profile not found.")
command_template = profile['command_template']
try:
args = shlex.split(command_template.format(*user_args))
except IndexError as e:
raise ValueError(f"Missing arguments: {e}")
path_mode = profile.get("path_mode", "default")
if path_mode == "default":
software_path = settings['DEFAULT'].get('software_path')
elif path_mode == "custom":
software_path = profile.get("program_path")
if not software_path:
raise ValueError("Software path is not defined in settings or in profile.")
command = [software_path] + args
flag = None
exportmode = profile.get("export_output_mode")
if exportmode == "default":
flag = settings['DEFAULT'].get('output_flag')
elif exportmode == "custom":
flag = profile.get("custom_output_flag")
folder = None
mode = profile.get("export_mode", "default")
if mode == "default":
folder = settings['DEFAULT'].get('output_folder')
elif mode == "software":
folder = ''
elif mode == "custom":
folder = profile.get("custom_output_folder", "")
template = None
template_name = profile.get("filename_mode")
if template_name == "default":
template = settings['DEFAULT'].get('filename_template')
elif template_name == "custom":
template = profile.get("custom_filename_template")
if exportmode != "disable":
if folder == "":
command += [flag, f"{template}"]
else:
command += [flag, f"{folder}/{template}"]
return command
def kill_process():
global yt_process
progressvar.set(100)
progress.stop()
# --- DEBUGGING START ---
append_console_output("\n[Stop Button Clicked]\n")
if yt_process:
poll_result = yt_process.poll()
append_console_output(f"[DEBUG] kill_process check. Process object: {yt_process}\n")
append_console_output(f"[DEBUG] PID: {yt_process.pid}. Poll result: {poll_result}\n")
if poll_result is not None:
append_console_output(f"[DEBUG] Conclusion: Process has already terminated with code: {poll_result}.\n")
# else:
# append_console_output("[DEBUG] Conclusion: Global 'yt_process' variable is None.\n")
# --- DEBUGGING END ---
if not yt_process or yt_process.poll() is not None:
append_console_output("\n[No active process to stop]\n")
return
append_console_output("\n[Attempting to stop the process...]\n")
try:
if os.name == 'nt':
subprocess.run(
['taskkill', '/F', '/T', '/PID', str(yt_process.pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW
)
append_console_output("[Process terminated by user]\n")
else:
pgid = os.getpgid(yt_process.pid)
os.killpg(pgid, signal.SIGINT)
append_console_output("[Interruption signal sent (Ctrl+C)]\n")
try:
yt_process.wait(timeout=5)
append_console_output("[Process terminated gracefully]\n")
except subprocess.TimeoutExpired:
append_console_output("[Process did not respond. Forcing termination...]\n")
os.killpg(pgid, signal.SIGKILL)
append_console_output("[Process forcefully terminated]\n")
except Exception as e:
append_console_output(f"[ERROR] Failed to stop process: {e}\n")
finally:
yt_process = None
def center_window(win, width=400, height=300):
win.update_idletasks()
x = root.winfo_x() + (root.winfo_width() - width) // 2
y = root.winfo_y() + (root.winfo_height() - height) // 2
win.geometry(f"{width}x{height}+{x}+{y}")
# --- NEW FUNCTION ---
# This function sends user input to the running process.
def send_to_process(event=None):
global yt_process
# Get text from the input entry and clear it
input_text = console_input_entry.get()
console_input_entry.delete(0, tk.END)
# Echo the input to the console display with a special tag
append_console_output(f"{input_text}\n", "user_input")
# If a process is running, write the input to its stdin
if yt_process and yt_process.poll() is None:
try:
# Add a newline character and flush immediately
yt_process.stdin.write(f"{input_text}\n")
yt_process.stdin.flush()
append_console_output("[Input sent to process]\n")
except (IOError, BrokenPipeError, OSError) as e:
append_console_output(f"\n[ERROR] Failed to send input to process: {e}\n")
# Try to check if process is still alive
if yt_process and yt_process.poll() is not None:
append_console_output(f"[Process has already exited with code: {yt_process.poll()}]\n")
else:
if yt_process:
rc = yt_process.poll()
append_console_output(f"\n[Process has exited with code: {rc}]\n")
else:
append_console_output("\n[No active process to send input to]\n")
def run_command(command, show_output_in_gui=True):
global yt_process
def task():
global yt_process # Add this line to ensure we're modifying the global variable
nonlocal command
# Clear console and start progress bar
console_output.configure(state='normal')
console_output.delete("1.0", tk.END)
console_output.configure(state='disabled')
progressvar.set(0)
progress.start()
append_console_output(f"[DEBUG] Running command: {' '.join(shlex.quote(c) for c in command)}\n")
try:
# Common Popen arguments
popen_args = {
"stdin": subprocess.PIPE,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE, # Separate stderr
"text": True,
"encoding": 'utf-8',
"errors": 'replace',
"bufsize": 1,
}
# if os.name == 'nt':
# # Windows-specific settings
# popen_args['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP
# else:
# # Unix-specific settings
# popen_args['preexec_fn'] = os.setsid
if os.name == 'nt':
# Windows-specific settings:
# CREATE_NEW_PROCESS_GROUP is for sending Ctrl+C/signals.
# CREATE_NO_WINDOW prevents a new console from popping up for the subprocess.
popen_args['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW
else:
# Unix-specific settings
popen_args['preexec_fn'] = os.setsid
yt_process = subprocess.Popen(command, **popen_args)
append_console_output(f"\n[DEBUG] Process started. PID: {yt_process.pid}\n\n")
except Exception as e:
append_console_output(f"[ERROR] Failed to start process: {e}\n")
yt_process = None
return
# Read output using threading for both stdout and stderr
try:
import queue
import threading
output_queue = queue.Queue()
def read_stream(stream, stream_name):
try:
buffer = ""
while True:
char = stream.read(1)
if not char: # End of stream
if buffer:
output_queue.put((stream_name, buffer))
break
buffer += char
# Send output immediately if:
# 1. We hit a newline (complete line)
# 2. We hit a prompt indicator (: or >)
# 3. Buffer gets too long (safety)
# 4. We hit a space after certain prompt words
if (char == '\n' or
char in ':>' or
len(buffer) > 100 or
(char == ' ' and any(word in buffer.lower() for word in ['continue', 'name', 'input', 'enter', 'press', 'choose', 'select']))):
output_queue.put((stream_name, buffer))
buffer = ""
except Exception as e:
if buffer:
output_queue.put((stream_name, buffer))
output_queue.put(('error', f"Error reading {stream_name}: {e}\n"))
# Start threads for reading stdout and stderr
stdout_thread = threading.Thread(target=read_stream, args=(yt_process.stdout, 'stdout'), daemon=True)
stderr_thread = threading.Thread(target=read_stream, args=(yt_process.stderr, 'stderr'), daemon=True)
stdout_thread.start()
stderr_thread.start()
# Process output from both streams
while yt_process and yt_process.poll() is None:
try:
stream_name, line = output_queue.get(timeout=0.1)
append_console_output(line)
except queue.Empty:
continue
except Exception as e:
append_console_output(f"[ERROR] Queue error: {e}\n")
break
# Read any remaining output after process ends
timeout_count = 0
while timeout_count < 10: # Give it 1 second to finish
try:
stream_name, line = output_queue.get(timeout=0.1)
append_console_output(line)
timeout_count = 0 # Reset if we got data
except queue.Empty:
timeout_count += 1
continue
except Exception:
break
except Exception as e:
append_console_output(f"[ERROR] Error reading process output: {e}\n")
finally:
progressvar.set(100)
progress.stop()
append_console_output(f"\n[DEBUG] Process finished reading output.\n")
if yt_process:
# Wait a moment for the process to finish naturally
try:
yt_process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
rc = yt_process.poll()
if rc is not None:
append_console_output(f"\n[Process exited with code: {rc}]\n")
else:
append_console_output(f"\n[Process completed]\n")
# Close stdin properly
try:
if yt_process.stdin:
yt_process.stdin.close()
except:
pass
# Only set to None after everything is done
yt_process = None
threading.Thread(target=task, daemon=True).start()
def count_placeholders(template):
return len(re.findall(r"{[^}]*}", template))
def run_command_threaded(command):
try:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in process.stdout:
console_output.insert(tk.END, line)
console_output.see(tk.END)
process.wait()
append_console_output("\n[Command finished]\n")
progressvar.set(100)
progress.stop()
console_output.insert(tk.END, f"\nDone. Exit code: {process.returncode}\n")
except Exception as e:
console_output.insert(tk.END, f"Error: {str(e)}\n")
# ============ GUI =============
def add_profile():
global showtipsvalue
root.focus_set()
top = tk.Toplevel(root)
top.grab_set()
top.title("Add profile")
top.resizable(False, False)
top.iconbitmap(os.path.join(BASE_DIR, "icon.ico"))
# top.attributes("-topmost", True)
center_window(top, width=642, height=600) # Adjust dimensions as needed ❔ add 20
entries = {}
def labeled_entry(label, row, place, tooptip):
f = tk.Label(place, text=label)
f.grid(row=row, column=0, sticky='w', padx=15, pady=5)
e = tk.Entry(place, width=40)
# Tooltip(entries['name'], "Test" ,showtipsvalue)
Tooltip(f, tooptip, showtipsvalue)
e.grid(row=row, column=1, padx=15, pady=2)
return e
firstpart_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
firstpart_group.grid(row=0, column=0, sticky='nswe')
entries['name'] = labeled_entry("Profile Display Name:", 0, firstpart_group, "Profile name that will be shown on arGUIments' interface.")
entries['short'] = labeled_entry("Profile Shortname:", 1, firstpart_group, "Profile shortname to call this specific profile via arGUIments-console mode, as an argument.")
separator = ttk.Separator(firstpart_group, orient='horizontal')
separator.grid(row=2, column=0, columnspan=3, sticky='nswe', pady=10)
frame_inline = tk.LabelFrame(firstpart_group, text="Program Path")
Tooltip(frame_inline, "Path to the desired program you wish to create a profile for. \nDefault will use the one defined in settings. \nCustom will allow you to chose one specifically for this profile." ,None)
frame_inline.grid(row=3, column=0, sticky='w', padx=15)
path_mode = tk.StringVar(value="default")
rb1 = tk.Radiobutton(frame_inline, text="Default (as per settings)", variable=path_mode, value="default").grid(row=0, column=0, sticky='w', columnspan=2)
rb2 = tk.Radiobutton(frame_inline, text="Custom (for this Profile)", variable=path_mode, value="custom").grid(row=1, column=0, sticky='w', columnspan=2)
entries['custom_soft_entry'] = tk.Entry(firstpart_group, width=40)
# entries['custom_soft_entry'].insert(0, profile['program_path'])
entries['custom_soft_entry'].grid(row=3, column=1, padx=15, pady=(0,5), sticky='sw')
browse_btn = ttk.Button(firstpart_group, text="Browse", command=lambda: choose_file(entries['custom_soft_entry'], top))
browse_btn.grid(row=3, column=2, padx=5, sticky='sw')
def update_custom_path_mode(*args):
entries['custom_soft_entry'].configure(state='normal')
browse_btn.configure(state='normal')
if path_mode.get() == "custom":
entries['custom_soft_entry'].delete(0, tk.END)
# entries['custom_soft_entry'].insert(0, profile['program_path'])
else:
entries['custom_soft_entry'].delete(0, tk.END)
entries['custom_soft_entry'].insert(0, settings['DEFAULT'].get('software_path', ''))
entries['custom_soft_entry'].configure(state='disable')
browse_btn.configure(state='disable')
path_mode.trace_add("write", update_custom_path_mode)
update_custom_path_mode()
entries['template'] = labeled_entry("Command Template:", 4, firstpart_group, "The argument(s) for the command line you wish to create a profile for. \nUse variables as {0}, {1} and so on. \nWhen you run the profile, you will be asked for the values.")
entries['arg_names'] = labeled_entry("Argument(s) Name(s) (comma-separated):", 5, firstpart_group, "The name of the argument(s) you have as variables, so that you can easily identify what they are when you run the profile.")
separator = ttk.Separator(firstpart_group, orient='horizontal')
separator.grid(row=6, column=0, columnspan=3, sticky='nswe', pady=10)
output_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
output_group.grid(row=1, column=0, sticky='nswe')
export_output_mode = tk.StringVar(value="default")
exportparam_group = tk.LabelFrame(output_group, text="Output Parameter")
Tooltip(exportparam_group, "If your software allows for some export/output command, enter here the argument value to trigger such feature. \nThe value will depend and vary from the software you chose in Program Path. \nDefault will use the value from settings. \nDisable will void the feature for this profile (unless it is automatically done so as per the Command Template). \nCustom will allow you to set one specific for this profile." ,None)
exportparam_group.grid(row=0, column=0, sticky='w', padx=15)
tk.Radiobutton(exportparam_group, text="Default (as per settings) ", variable=export_output_mode, value="default").grid(row=0, column=0, sticky='w', columnspan=2)
tk.Radiobutton(exportparam_group, text="Disable Output", variable=export_output_mode, value="disable").grid(row=1, column=0, sticky='w', columnspan=2)
tk.Radiobutton(exportparam_group, text="Custom (for this Profile)", variable=export_output_mode, value="custom").grid(row=2, column=0, sticky='w')
exportparam_groupright = tk.LabelFrame(output_group, borderwidth = 0, highlightthickness = 0)
exportparam_groupright.grid(row=0, column=1, sticky='s')
entries['custom_output_param_entry'] = tk.Entry(exportparam_groupright, width=40)
# entries['custom_output_param_entry'].insert(0, profile['custom_output_flag'])
entries['custom_output_param_entry'].grid(row=0, column=0,sticky='sw', pady=(0,5), padx=(85,0))
secondpart_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
secondpart_group.grid(row=2, column=0, sticky='nswe')
export_mode = tk.StringVar(value="default")
export_group = tk.LabelFrame(secondpart_group, text="Output Path")
Tooltip(export_group, "If Output Parameter is not disabled, Output Path will allow you to chose a specific folder in which the export/output will be created in. \nDefault will use the value as per settings. \nVariable will use the folder from which arGUIments was ran from (note that if you added the path in which arGUIments is installed in, to the PATH environment variable, this will also work). \nCustom will allow you to chose a specific folder for this profile." ,None)
export_group.grid(row=0, column=0, sticky='w', padx=15)
choice_path_1 = tk.Radiobutton(export_group, text="Default (as per settings) ", variable=export_mode, value="default")
choice_path_1.grid(row=0, column=0, sticky='w', columnspan=2)
choice_path_2 = tk.Radiobutton(export_group, text="Variable (as per location)", variable=export_mode, value="software")
choice_path_2.grid(row=1, column=0, sticky='w')
choice_path_3 = tk.Radiobutton(export_group, text="Custom (for this Profile)", variable=export_mode, value="custom")
choice_path_3.grid(row=2, column=0, sticky='w', columnspan=2)
export_groupright = tk.LabelFrame(secondpart_group, borderwidth = 0, highlightthickness = 0)
export_groupright.grid(row=0, column=1, sticky='s')
entries['custom_export_entry'] = tk.Entry(export_groupright, width=40)
# entries['custom_export_entry'].insert(0, profile['custom_output_folder'])
browse_export_btn = ttk.Button(export_groupright, text="Browse", command=lambda: choose_folder(entries['custom_export_entry'], top))
entries['custom_export_entry'].grid(row=0, column=0,sticky='sw', pady=(0,5), padx=(85,0))
browse_export_btn.grid(row=0, column=1, padx=20, sticky='w')
filename_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
filename_group.grid(row=3, column=0, sticky='nswe')
filenametemplate_mode = tk.StringVar(value="default")
template_group = tk.LabelFrame(filename_group, text="Output Filename Template")
Tooltip(template_group, "If Output Parameter is not disabled, Output Filename Template will allow you to chose a specific filename (or filename template) for your export/output. \nThe value you enter here can be a fixed filename (e.g. 'export.csv', 'video.mp4', and so on), or something more generic as per what the software from Program Path allows. \nDefault will use the value from settings. \nCustom will allow you to chose a specific one for this profile." ,None)
template_group.grid(row=0, column=0, sticky='w', padx=15)
choice_filename_1 = tk.Radiobutton(template_group, text="Default (as per settings) ", variable=filenametemplate_mode, value="default")
choice_filename_1.grid(row=0, column=0, sticky='w', columnspan=2)
choice_filename_2 = tk.Radiobutton(template_group, text="Custom (for this Profile)", variable=filenametemplate_mode, value="custom")
choice_filename_2.grid(row=1, column=0, sticky='w')
filenameparam_groupright = tk.LabelFrame(filename_group, borderwidth = 0, highlightthickness = 0)
filenameparam_groupright.grid(row=0, column=1, sticky='s')
entries['filename_template_param_entry'] = tk.Entry(filenameparam_groupright, width=40)
# entries['filename_template_param_entry'].insert(0, profile['custom_filename_template'])
entries['filename_template_param_entry'].grid(row=0, column=0,sticky='sw', pady=(0,5), padx=(85,0))
def update_custom_export_visibility(*args):
entries['custom_export_entry'].configure(state='normal')
browse_export_btn.configure(state='normal')
if export_mode.get() == "custom":
entries['custom_export_entry'].delete(0, tk.END)
# entries['custom_export_entry'].insert(0, profile['custom_output_folder'])
elif export_mode.get() == "default":
entries['custom_export_entry'].delete(0, tk.END)
entries['custom_export_entry'].insert(0, settings['DEFAULT'].get('output_folder', ''))
entries['custom_export_entry'].configure(state='disable')
browse_export_btn.configure(state='disable')
elif export_mode.get() == "software":
entries['custom_export_entry'].delete(0, tk.END)
entries['custom_export_entry'].insert(0, '')
entries['custom_export_entry'].configure(state='disable')
browse_export_btn.configure(state='disable')
export_mode.trace_add("write", update_custom_export_visibility)
update_custom_export_visibility()
def update_custom_filename_visibility(*args):
entries['filename_template_param_entry'].configure(state='normal')
if filenametemplate_mode.get() == "custom":
entries['filename_template_param_entry'].delete(0, tk.END)
# entries['filename_template_param_entry'].insert(0, profile['custom_filename_template'])
elif filenametemplate_mode.get() == "default":
entries['filename_template_param_entry'].delete(0, tk.END)
entries['filename_template_param_entry'].insert(0, settings['DEFAULT'].get('filename_template', ''))
entries['filename_template_param_entry'].configure(state='disable')
filenametemplate_mode.trace_add("write", update_custom_filename_visibility)
update_custom_filename_visibility()
def update_custom_output_visibility(*args):
entries['custom_output_param_entry'].configure(state='normal')
if export_output_mode.get() == "custom":
entries['custom_output_param_entry'].delete(0, tk.END)
# entries['custom_output_param_entry'].insert(0, profile['custom_output_flag'])
update_custom_export_visibility()
update_custom_filename_visibility()
choice_path_1.config(state='normal')
choice_path_2.config(state='normal')
choice_path_3.config(state='normal')
choice_filename_1.config(state='normal')
choice_filename_2.config(state='normal')
elif export_output_mode.get() == "default":
entries['custom_output_param_entry'].delete(0, tk.END)
entries['custom_output_param_entry'].insert(0, settings['DEFAULT'].get('output_flag', ''))
entries['custom_output_param_entry'].configure(state='disable')
update_custom_export_visibility()
update_custom_filename_visibility()
choice_path_1.config(state='normal')
choice_path_2.config(state='normal')
choice_path_3.config(state='normal')
choice_filename_1.config(state='normal')
choice_filename_2.config(state='normal')
elif export_output_mode.get() == "disable":
entries['custom_output_param_entry'].delete(0, tk.END)
entries['custom_output_param_entry'].insert(0, '')
entries['custom_output_param_entry'].configure(state='disable')
entries['custom_export_entry'].configure(state='disable')
entries['filename_template_param_entry'].configure(state='disable')
browse_export_btn.configure(state='disable')
choice_path_1.config(state='disabled')
choice_path_2.config(state='disabled')
choice_path_3.config(state='disabled')
choice_filename_1.config(state='disabled')
choice_filename_2.config(state='disabled')
export_output_mode.trace_add("write", update_custom_output_visibility)
update_custom_output_visibility()
thirdpart_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
thirdpart_group.grid(row=4, column=0, sticky='nswe', padx=15, pady=15)
error_label = tk.Label(thirdpart_group, text="", fg="red")
error_label.grid(row=0, column=0, columnspan=2, sticky='w')
def save():
name = entries['name'].get()
# short_new = entries['short'].get()
short = entries['short'].get()
template = entries['template'].get()
custom_path = entries['custom_soft_entry'].get().strip()
arg_count = count_placeholders(template)
arg_names_str = entries['arg_names'].get()
custom_filename_template = entries['filename_template_param_entry'].get().strip()
custom_output_flag = entries['custom_output_param_entry'].get()
custom_export_entry = entries['custom_export_entry'].get().strip()
arg_names = [s.strip() for s in arg_names_str.split(',') if s.strip()] if arg_names_str else []
# Validate shortname
# if not re.match(r"^[a-zA-Z0-9\-]+$", short_new):
if not re.match(r"^[a-zA-Z0-9\-]+$", short):
error_label.config(text="Profile Shortname must only contain letters, numbers, or dashes.")
return
# Check if the new shortname already exists (and it's not the original shortname)
# if short_new != short and short_new in profiles:
if short in profiles:
error_label.config(text="Profile Shortname must be unique.")
return
if arg_count > 0 and not arg_names_str:
error_label.config(text="Argument names are required for templates with placeholders.")
return
# if export_output_mode.get() != "disable":
# if len(custom_filename_template) == 0:
# error_label.config(text="Custom Output Filename Template cannot be empty.")
# return
if len(name) == 0:
error_label.config(text="Profile Display name cannot be empty.")
return
if len(arg_names) != arg_count:
error_label.config(text=f"Template has {arg_count} arguments placeholders, but {len(arg_names)} argument names were provided.")
return
# if short_new != original_short:
# del profiles[original_short]
if export_mode.get() == "custom":
if len(custom_export_entry) == 0:
error_label.config(text="Custom Output Path cannot be empty.")
return
# custom_output_folder = custom_export_entry
profiles[short] = {
# profiles[short_new] = {
"display_name": name,
"shortname": short,
"path_mode": path_mode.get(),
"program_path": custom_path,
"command_template": template,
"arg_names": arg_names,
"export_output_mode": export_output_mode.get(),
"custom_output_flag": custom_output_flag,
"export_mode": export_mode.get(),
"custom_output_folder": custom_export_entry,
"filename_mode": filenametemplate_mode.get(),
"custom_filename_template": custom_filename_template
}
save_profiles(profiles)
refresh_profiles()
top.destroy()
save_btn = ttk.Button(thirdpart_group, text="Save", command=save)
save_btn.grid(row=1, column=0, pady=10, sticky='w')
def choose_file(entry_field, place):
place.attributes("-topmost", False)
path = filedialog.askopenfilename()
place.attributes("-topmost", True)
if path:
entry_field.delete(0, tk.END)
entry_field.insert(0, path)
def choose_folder(entry_widget, place):
place.attributes("-topmost", False)
path = filedialog.askdirectory()
place.attributes("-topmost", True)
if path:
entry_widget.delete(0, tk.END)
entry_widget.insert(0, path)
def edit_profile():
global showtipsvalue
root.focus_set()
short = get_selected_shortname()
original_short = short
if not short:
custom_info_dialog("Info", "Choose a profile first.")
return
profile = profiles[short]
top = tk.Toplevel(root)
top.grab_set()
top.title("Edit profile")
top.resizable(False, False)
top.iconbitmap(os.path.join(BASE_DIR, "icon.ico"))
# top.attributes("-topmost", True)
center_window(top, width=642, height=600) # Adjust dimensions as needed ❔ add 20
entries = {}
def labeled_entry(label, row, val, place, tooptip):
f = tk.Label(place, text=label)
f.grid(row=row, column=0, sticky='w', padx=15, pady=5)
e = tk.Entry(place, width=40)
e.insert(0, val)
Tooltip(f, tooptip, showtipsvalue)
e.grid(row=row, column=1, padx=15, pady=2)
return e
firstpart_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
firstpart_group.grid(row=0, column=0, sticky='nswe')
entries['name'] = labeled_entry("Profile Display Name:", 0, profile['display_name'], firstpart_group, "Profile name that will be shown on arGUIments' interface.")
entries['short'] = labeled_entry("Profile Shortname:", 1, profile['shortname'], firstpart_group, "Profile shortname to call this specific profile via arGUIments-console mode, as an argument.")
separator = ttk.Separator(firstpart_group, orient='horizontal')
separator.grid(row=2, column=0, columnspan=3, sticky='nswe', pady=10)
frame_inline = tk.LabelFrame(firstpart_group, text="Program Path")
Tooltip(frame_inline, "Path to the desired program you wish to create a profile for. \nDefault will use the one defined in settings. \nCustom will allow you to chose one specifically for this profile." ,None)
frame_inline.grid(row=3, column=0, sticky='w', padx=15)
path_mode = tk.StringVar(value=profile.get("path_mode", "default"))
rb1 = tk.Radiobutton(frame_inline, text="Default (as per settings)", variable=path_mode, value="default").grid(row=0, column=0, sticky='w', columnspan=2)
rb2 = tk.Radiobutton(frame_inline, text="Custom (for this Profile)", variable=path_mode, value="custom").grid(row=1, column=0, sticky='w', columnspan=2)
entries['custom_soft_entry'] = tk.Entry(firstpart_group, width=40)
entries['custom_soft_entry'].insert(0, profile['program_path'])
entries['custom_soft_entry'].grid(row=3, column=1, padx=15, pady=(0,5), sticky='sw')
browse_btn = ttk.Button(firstpart_group, text="Browse", command=lambda: choose_file(entries['custom_soft_entry'], top))
browse_btn.grid(row=3, column=2, padx=5, sticky='sw')
def update_custom_path_mode(*args):
entries['custom_soft_entry'].configure(state='normal')
browse_btn.configure(state='normal')
if path_mode.get() == "custom":
entries['custom_soft_entry'].delete(0, tk.END)
entries['custom_soft_entry'].insert(0, profile['program_path'])
else:
entries['custom_soft_entry'].delete(0, tk.END)
entries['custom_soft_entry'].insert(0, settings['DEFAULT'].get('software_path', ''))
entries['custom_soft_entry'].configure(state='disable')
browse_btn.configure(state='disable')
path_mode.trace_add("write", update_custom_path_mode)
update_custom_path_mode()
entries['template'] = labeled_entry("Command Template:", 4, profile['command_template'], firstpart_group, "The argument(s) for the command line you wish to create a profile for. \nUse variables as {0}, {1} and so on. \nWhen you run the profile, you will be asked for the values.")
entries['arg_names'] = labeled_entry("Argument(s) Name(s) (comma-separated):", 5, ",".join(profile.get("arg_names", [])), firstpart_group, "The name of the argument(s) you have as variables, so that you can easily identify what they are when you run the profile.")
separator = ttk.Separator(firstpart_group, orient='horizontal')
separator.grid(row=6, column=0, columnspan=3, sticky='nswe', pady=10)
output_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
output_group.grid(row=1, column=0, sticky='nswe')
export_output_mode = tk.StringVar(value=profile.get("export_output_mode", "default"))
exportparam_group = tk.LabelFrame(output_group, text="Output Parameter")
Tooltip(exportparam_group, "If your software allows for some export/output command, enter here the argument value to trigger such feature. \nThe value will depend and vary from the software you chose in Program Path. \nDefault will use the value from settings. \nDisable will void the feature for this profile (unless it is automatically done so as per the Command Template). \nCustom will allow you to set one specific for this profile." ,None)
exportparam_group.grid(row=0, column=0, sticky='w', padx=15)
tk.Radiobutton(exportparam_group, text="Default (as per settings) ", variable=export_output_mode, value="default").grid(row=0, column=0, sticky='w', columnspan=2)
tk.Radiobutton(exportparam_group, text="Disable Output", variable=export_output_mode, value="disable").grid(row=1, column=0, sticky='w', columnspan=2)
tk.Radiobutton(exportparam_group, text="Custom (for this Profile)", variable=export_output_mode, value="custom").grid(row=2, column=0, sticky='w')
exportparam_groupright = tk.LabelFrame(output_group, borderwidth = 0, highlightthickness = 0)
exportparam_groupright.grid(row=0, column=1, sticky='s')
entries['custom_output_param_entry'] = tk.Entry(exportparam_groupright, width=40)
entries['custom_output_param_entry'].insert(0, profile['custom_output_flag'])
entries['custom_output_param_entry'].grid(row=0, column=0,sticky='sw', pady=(0,5), padx=(85,0))
secondpart_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
secondpart_group.grid(row=2, column=0, sticky='nswe')
export_mode = tk.StringVar(value=profile.get("export_mode", "default"))
export_group = tk.LabelFrame(secondpart_group, text="Output Path")
Tooltip(export_group, "If Output Parameter is not disabled, Output Path will allow you to chose a specific folder in which the export/output will be created in. \nDefault will use the value as per settings. \nVariable will use the folder from which arGUIments was ran from (note that if you added the path in which arGUIments is installed in, to the PATH environment variable, this will also work). \nCustom will allow you to chose a specific folder for this profile." ,None)
export_group.grid(row=0, column=0, sticky='w', padx=15)
choice_path_1 = tk.Radiobutton(export_group, text="Default (as per settings) ", variable=export_mode, value="default")
choice_path_1.grid(row=0, column=0, sticky='w', columnspan=2)
choice_path_2 = tk.Radiobutton(export_group, text="Variable (as per location)", variable=export_mode, value="software")
choice_path_2.grid(row=1, column=0, sticky='w')
choice_path_3 = tk.Radiobutton(export_group, text="Custom (for this Profile)", variable=export_mode, value="custom")
choice_path_3.grid(row=2, column=0, sticky='w', columnspan=2)
export_groupright = tk.LabelFrame(secondpart_group, borderwidth = 0, highlightthickness = 0)
export_groupright.grid(row=0, column=1, sticky='s')
entries['custom_export_entry'] = tk.Entry(export_groupright, width=40)
entries['custom_export_entry'].insert(0, profile['custom_output_folder'])
browse_export_btn = ttk.Button(export_groupright, text="Browse", command=lambda: choose_folder(entries['custom_export_entry'], top))
entries['custom_export_entry'].grid(row=0, column=0,sticky='sw', pady=(0,5), padx=(85,0))
browse_export_btn.grid(row=0, column=1, padx=20, sticky='w')
filename_group = tk.LabelFrame(top, borderwidth = 0, highlightthickness = 0)
filename_group.grid(row=3, column=0, sticky='nswe')
filenametemplate_mode = tk.StringVar(value=profile.get("filename_mode", "default"))
template_group = tk.LabelFrame(filename_group, text="Output Filename Template")
Tooltip(template_group, "If Output Parameter is not disabled, Output Filename Template will allow you to chose a specific filename (or filename template) for your export/output. \nThe value you enter here can be a fixed filename (e.g. 'export.csv', 'video.mp4', and so on), or something more generic as per what the software from Program Path allows. \nDefault will use the value from settings. \nCustom will allow you to chose a specific one for this profile." ,None)
template_group.grid(row=0, column=0, sticky='w', padx=15)
choice_filename_1 = tk.Radiobutton(template_group, text="Default (as per settings) ", variable=filenametemplate_mode, value="default")
choice_filename_1.grid(row=0, column=0, sticky='w', columnspan=2)
choice_filename_2 = tk.Radiobutton(template_group, text="Custom (for this Profile)", variable=filenametemplate_mode, value="custom")
choice_filename_2.grid(row=1, column=0, sticky='w')
filenameparam_groupright = tk.LabelFrame(filename_group, borderwidth = 0, highlightthickness = 0)
filenameparam_groupright.grid(row=0, column=1, sticky='s')
entries['filename_template_param_entry'] = tk.Entry(filenameparam_groupright, width=40)
entries['filename_template_param_entry'].insert(0, profile['custom_filename_template'])
entries['filename_template_param_entry'].grid(row=0, column=0,sticky='sw', pady=(0,5), padx=(85,0))
def update_custom_export_visibility(*args):
entries['custom_export_entry'].configure(state='normal')
browse_export_btn.configure(state='normal')
if export_mode.get() == "custom":
entries['custom_export_entry'].delete(0, tk.END)
entries['custom_export_entry'].insert(0, profile['custom_output_folder'])
elif export_mode.get() == "default":
entries['custom_export_entry'].delete(0, tk.END)
entries['custom_export_entry'].insert(0, settings['DEFAULT'].get('output_folder', ''))
entries['custom_export_entry'].configure(state='disable')
browse_export_btn.configure(state='disable')
elif export_mode.get() == "software":
entries['custom_export_entry'].delete(0, tk.END)
entries['custom_export_entry'].insert(0, '')
entries['custom_export_entry'].configure(state='disable')
browse_export_btn.configure(state='disable')
export_mode.trace_add("write", update_custom_export_visibility)
update_custom_export_visibility()
def update_custom_filename_visibility(*args):
entries['filename_template_param_entry'].configure(state='normal')
if filenametemplate_mode.get() == "custom":
entries['filename_template_param_entry'].delete(0, tk.END)
entries['filename_template_param_entry'].insert(0, profile['custom_filename_template'])
elif filenametemplate_mode.get() == "default":
entries['filename_template_param_entry'].delete(0, tk.END)
entries['filename_template_param_entry'].insert(0, settings['DEFAULT'].get('filename_template', ''))
entries['filename_template_param_entry'].configure(state='disable')
filenametemplate_mode.trace_add("write", update_custom_filename_visibility)
update_custom_filename_visibility()
def update_custom_output_visibility(*args):
entries['custom_output_param_entry'].configure(state='normal')
if export_output_mode.get() == "custom":
entries['custom_output_param_entry'].delete(0, tk.END)
entries['custom_output_param_entry'].insert(0, profile['custom_output_flag'])
update_custom_export_visibility()
update_custom_filename_visibility()
choice_path_1.config(state='normal')
choice_path_2.config(state='normal')
choice_path_3.config(state='normal')
choice_filename_1.config(state='normal')
choice_filename_2.config(state='normal')
elif export_output_mode.get() == "default":
entries['custom_output_param_entry'].delete(0, tk.END)
entries['custom_output_param_entry'].insert(0, settings['DEFAULT'].get('output_flag', ''))
entries['custom_output_param_entry'].configure(state='disable')
update_custom_export_visibility()
update_custom_filename_visibility()
choice_path_1.config(state='normal')
choice_path_2.config(state='normal')
choice_path_3.config(state='normal')
choice_filename_1.config(state='normal')
choice_filename_2.config(state='normal')
elif export_output_mode.get() == "disable":
entries['custom_output_param_entry'].delete(0, tk.END)
entries['custom_output_param_entry'].insert(0, '')
entries['custom_output_param_entry'].configure(state='disable')
entries['custom_export_entry'].configure(state='disable')
entries['filename_template_param_entry'].configure(state='disable')
browse_export_btn.configure(state='disable')
choice_path_1.config(state='disabled')
choice_path_2.config(state='disabled')
choice_path_3.config(state='disabled')
choice_filename_1.config(state='disabled')
choice_filename_2.config(state='disabled')
export_output_mode.trace_add("write", update_custom_output_visibility)
update_custom_output_visibility()