-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathform_builder.py
More file actions
1036 lines (849 loc) · 39.4 KB
/
Copy pathform_builder.py
File metadata and controls
1036 lines (849 loc) · 39.4 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
# form_builder.py
import tkinter as tk
from tkinter import ttk, filedialog
from pathlib import Path
import calendar
import datetime
import re
from constants import FileConstants, ValidationConstants
from logger_config import logger
# Optional validator import
try:
import validators
VALIDATORS_AVAILABLE = True
except ImportError:
VALIDATORS_AVAILABLE = False
class FormBuilder:
"""Builds UI widgets from command definitions"""
def __init__(self, theme_config, on_change_callback):
self.theme = theme_config
self.on_change = on_change_callback
self.widget_vars = []
self.permission_vars = {}
def build_form(self, parent_frame, field_definitions):
"""
Build form widgets from field definitions.
Args:
parent_frame: ttk.Frame - Parent container
field_definitions: list - Field specs from JSON
Returns:
list - Widget data items
"""
self.widget_vars.clear()
for field_data in field_definitions:
frame = ttk.Frame(parent_frame)
frame.pack(fill=tk.X, pady=4)
widget_frame = ttk.Frame(frame)
widget_frame.pack(fill=tk.X)
widget_data = field_data.copy()
if 'type' not in widget_data:
widget_data['type'] = 'text'
# Build the appropriate widget
self._build_widget(widget_frame, widget_data)
# Add tooltip if present
if "tooltip" in field_data:
tooltip_label = ttk.Label(frame, text=field_data["tooltip"],
style="Tooltip.TLabel")
tooltip_label.pack(fill=tk.X, padx=(25, 10), pady=(0, 0))
return self.widget_vars
def _build_widget(self, parent_frame, widget_data):
"""Dispatch to appropriate widget builder"""
widget_type = widget_data['type']
builders = {
"permission_grid": self._build_permission_grid,
"checkbox": self._build_checkbox,
"dropdown": self._build_dropdown,
"text": self._build_text,
"size_input": self._build_size_input,
"relative_time_input": self._build_relative_time_input,
"notable_text_input": self._build_notable_text_input,
"permission_input": self._build_permission_input,
"date_input": self._build_date_input,
"url": self._build_url,
"file_w_ext": self._build_file_w_ext,
"file_picker": self._build_file_picker,
"dir_picker": self._build_dir_picker,
"file_save_as": self._build_file_save_as,
"number_input": self._build_number_input,
}
builder = builders.get(widget_type, self._build_text)
builder(parent_frame, widget_data)
# ========== WIDGET BUILDERS ==========
def _build_permission_grid(self, parent_frame, widget_data):
"""Build chmod permission grid (User/Group/Other x R/W/X)"""
try:
# Validate widget_data
if not isinstance(widget_data, dict):
raise ValueError("widget_data must be a dictionary")
# Initialize permission variables
self.permission_vars = {
'user': {'r': tk.BooleanVar(), 'w': tk.BooleanVar(), 'x': tk.BooleanVar()},
'group': {'r': tk.BooleanVar(), 'w': tk.BooleanVar(), 'x': tk.BooleanVar()},
'other': {'r': tk.BooleanVar(), 'w': tk.BooleanVar(), 'x': tk.BooleanVar()}
}
main_frame = ttk.Frame(parent_frame)
main_frame.pack(fill=tk.X)
categories = {'User': 'user', 'Group': 'group', 'Other': 'other'}
permissions = {'Read': 'r', 'Write': 'w', 'Execute': 'x'}
# Store all checkbuttons for enable/disable
all_checkbuttons = []
for cat_label, cat_key in categories.items():
labelframe = ttk.LabelFrame(main_frame, text=cat_label)
labelframe.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
for perm_label, perm_key in permissions.items():
chk = ttk.Checkbutton(
labelframe,
text=perm_label,
variable=self.permission_vars[cat_key][perm_key],
command=self.on_change
)
chk.pack(anchor="w", padx=10)
all_checkbuttons.append(chk)
# Store reference in widget_data
widget_data.update({
"permission_vars": self.permission_vars,
"widget": main_frame,
"checkbuttons": all_checkbuttons
})
self.widget_vars.append(widget_data)
except tk.TclError as e:
logger.error(f"Error creating permission grid widget: {e}")
# Create fallback simple text
ttk.Label(parent_frame,
text=f"{widget_data.get('label', 'Permissions')}: (Widget creation failed)",
foreground="red").pack()
except (ValueError, KeyError) as e:
logger.error(f"Configuration error in permission grid: {e}")
ttk.Label(parent_frame,
text=f"{widget_data.get('label', 'Permissions')}: (Configuration error)",
foreground="red").pack()
except Exception as e:
logger.exception(f"Unexpected error in _build_permission_grid:")
ttk.Label(parent_frame,
text=f"{widget_data.get('label', 'Permissions')}: (Error)",
foreground="red").pack()
def _build_checkbox(self, parent_frame, widget_data):
"""Build a simple checkbox"""
var = tk.BooleanVar()
chk = ttk.Checkbutton(
parent_frame,
text=widget_data["label"],
variable=var,
command=self.on_change
)
chk.pack(anchor="w")
widget_data.update({"var": var, "widget": chk})
self.widget_vars.append(widget_data)
def _build_dropdown(self, parent_frame, widget_data):
"""Build a dropdown/combobox"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
var = tk.StringVar()
combo = ttk.Combobox(
parent_frame,
textvariable=var,
values=widget_data.get("options", []),
state="readonly",
width=30
)
combo.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
widget_data.update({"var": var, "widget": combo})
self.widget_vars.append(widget_data)
def _build_text(self, parent_frame, widget_data):
"""Build a text entry widget with validation"""
# Container to prevent expansion
container = ttk.Frame(parent_frame)
container.pack(fill=tk.X)
label = ttk.Label(container, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
# Right side container for entry + feedback
right_container = ttk.Frame(container)
right_container.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
var = tk.StringVar()
entry = ttk.Entry(right_container, textvariable=var)
entry.pack(fill=tk.X)
# Add validation feedback label (hidden by default)
feedback_label = ttk.Label(right_container, text="", style="Tooltip.TLabel")
# DON'T pack it yet - only pack when needed
# Debounce timer to prevent lag
validation_timer = [None]
def validate_on_change(*args):
if validation_timer[0]:
container.after_cancel(validation_timer[0])
value = var.get()
max_len = widget_data.get("max_length", FileConstants.DEFAULT_MAX_TEXT_LENGTH)
if len(value) > max_len:
feedback_label.config(
text=f"⚠️ Too long ({len(value)}/{max_len})",
foreground=self.theme["ERROR_RED"]
)
entry.config(style="Invalid.TEntry")
# Show the feedback label
if not feedback_label.winfo_ismapped():
feedback_label.pack(fill=tk.X, anchor="w")
else:
feedback_label.config(text="")
entry.config(style="TEntry")
# Hide the feedback label
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
validation_timer[0] = container.after(300, self.on_change)
var.trace_add("write", validate_on_change)
widget_data.update({"var": var, "widget": entry})
self.widget_vars.append(widget_data)
def _build_size_input(self, parent_frame, widget_data):
"""Build size input (operator + number + unit) - e.g., +100M"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
size_frame = ttk.Frame(parent_frame)
size_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Operator dropdown (+, -, or exact)
op_var = tk.StringVar()
op_combo = ttk.Combobox(
size_frame,
textvariable=op_var,
values=["", "+", "-"],
state="readonly",
width=3
)
op_combo.pack(side=tk.LEFT)
op_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
# Number entry
num_var = tk.StringVar()
num_var.trace_add("write", lambda n, i, m: self.on_change())
num_entry = ttk.Entry(size_frame, textvariable=num_var, width=10)
num_entry.pack(side=tk.LEFT, padx=(5, 0))
# Unit dropdown (bytes, KB, MB, GB)
unit_var = tk.StringVar()
unit_options = widget_data.get("options", ["c", "k", "M", "G"])
unit_combo = ttk.Combobox(
size_frame,
textvariable=unit_var,
values=unit_options,
state="readonly",
width=5
)
unit_combo.pack(side=tk.LEFT, padx=(5, 0))
unit_combo.set(unit_options[0] if unit_options else "")
unit_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
widget_data.update({
"op_var": op_var,
"num_var": num_var,
"unit_var": unit_var,
"widget": num_entry
})
self.widget_vars.append(widget_data)
def _build_relative_time_input(self, parent_frame, widget_data):
"""Build relative time input (operator + number) - e.g., -7 days"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
time_frame = ttk.Frame(parent_frame)
time_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Operator dropdown (+, -, or exact)
op_var = tk.StringVar()
op_combo = ttk.Combobox(
time_frame,
textvariable=op_var,
values=["", "+", "-"],
state="readonly",
width=3
)
op_combo.pack(side=tk.LEFT)
op_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
# Number entry
num_var = tk.StringVar()
num_var.trace_add("write", lambda n, i, m: self.on_change())
num_entry = ttk.Entry(time_frame, textvariable=num_var, width=10)
num_entry.pack(side=tk.LEFT, padx=(5, 0))
widget_data.update({
"op_var": op_var,
"num_var": num_var,
"widget": num_entry
})
self.widget_vars.append(widget_data)
def _build_notable_text_input(self, parent_frame, widget_data):
"""Build text input with NOT operator - e.g., ! -name "*.txt" """
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
not_frame = ttk.Frame(parent_frame)
not_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# NOT operator dropdown
not_var = tk.StringVar()
not_combo = ttk.Combobox(
not_frame,
textvariable=not_var,
values=["", "!"],
state="readonly",
width=3
)
not_combo.pack(side=tk.LEFT)
not_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
# Text entry
var = tk.StringVar()
var.trace_add("write", lambda n, i, m: self.on_change())
entry = ttk.Entry(not_frame, textvariable=var, width=20)
entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 0))
widget_data.update({
"not_var": not_var,
"var": var,
"widget": entry
})
self.widget_vars.append(widget_data)
def _build_permission_input(self, parent_frame, widget_data):
"""Build permission input (mode + permission string) - e.g., -644"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
perm_frame = ttk.Frame(parent_frame)
perm_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Mode dropdown (exact, at least, any of)
mode_var = tk.StringVar()
mode_options = [" (exact)", "- (at least)", "/ (any of)"]
mode_combo = ttk.Combobox(
perm_frame,
textvariable=mode_var,
values=mode_options,
state="readonly",
width=12
)
mode_combo.pack(side=tk.LEFT)
mode_combo.set(mode_options[0])
mode_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
# Permission entry
var = tk.StringVar()
var.trace_add("write", lambda n, i, m: self.on_change())
entry = ttk.Entry(perm_frame, textvariable=var, width=15)
entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 0))
widget_data.update({
"mode_var": mode_var,
"var": var,
"widget": entry
})
self.widget_vars.append(widget_data)
def _build_date_input(self, parent_frame, widget_data):
"""Build date input (NOT + Year/Month/Day dropdowns)"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
date_frame = ttk.Frame(parent_frame)
date_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# NOT operator
not_var = tk.StringVar()
not_combo = ttk.Combobox(
date_frame,
textvariable=not_var,
values=["", "!"],
state="readonly",
width=3
)
not_combo.pack(side=tk.LEFT)
# Year dropdown
year_var = tk.StringVar()
current_year = datetime.date.today().year
# Handle special "current" keyword or convert to int
raw_min = widget_data.get("min_year", current_year - 50)
raw_max = widget_data.get("max_year", current_year + 5)
# Convert min_year, handling "current" keyword
if isinstance(raw_min, str) and raw_min.lower() == "current":
min_year = current_year
elif isinstance(raw_min, str):
try:
min_year = int(raw_min)
except ValueError:
min_year = current_year - 50
else:
min_year = int(raw_min)
# Convert max_year, handling "current" keyword
if isinstance(raw_max, str) and raw_max.lower() == "current":
max_year = current_year
elif isinstance(raw_max, str):
try:
max_year = int(raw_max)
except ValueError:
max_year = current_year + 5
else:
max_year = int(raw_max)
year_list = [""] + list(range(max_year, min_year - 1, -1))
year_combo = ttk.Combobox(
date_frame,
textvariable=year_var,
values=year_list,
state="readonly",
width=6
)
year_combo.pack(side=tk.LEFT, padx=(5, 0))
# Month dropdown
month_var = tk.StringVar()
month_list = ["", "01-Jan", "02-Feb", "03-Mar", "04-Apr", "05-May", "06-Jun",
"07-Jul", "08-Aug", "09-Sep", "10-Oct", "11-Nov", "12-Dec"]
month_combo = ttk.Combobox(
date_frame,
textvariable=month_var,
values=month_list,
state="readonly",
width=8
)
month_combo.pack(side=tk.LEFT, padx=(5, 0))
# Day dropdown
day_var = tk.StringVar()
day_list = [""] + [f"{i:02d}" for i in range(1, 32)]
day_combo = ttk.Combobox(
date_frame,
textvariable=day_var,
values=day_list,
state="readonly",
width=4
)
day_combo.pack(side=tk.LEFT, padx=(5, 0))
# Bind events to update days based on selected month/year
def update_days(*args):
self._update_days_for_date_widget(year_var, month_var, day_var, day_combo)
year_combo.bind("<<ComboboxSelected>>", update_days)
month_combo.bind("<<ComboboxSelected>>", update_days)
day_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
not_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
widget_data.update({
"not_var": not_var,
"year_var": year_var,
"month_var": month_var,
"day_var": day_var,
"widget": year_combo,
"day_combo_widget": day_combo
})
self.widget_vars.append(widget_data)
def _update_days_for_date_widget(self, year_var, month_var, day_var, day_combo):
"""Helper to update day dropdown based on selected month/year"""
try:
year_str = year_var.get()
month_str = month_var.get()
if year_str and month_str:
year = int(year_str)
month = int(month_str.split("-")[0]) # "02-Feb" -> 02
num_days = calendar.monthrange(year, month)[1]
new_day_list = [""] + [f"{i:02d}" for i in range(1, num_days + 1)]
current_day = day_var.get()
day_combo['values'] = new_day_list
if current_day not in new_day_list:
day_var.set("")
else:
default_days = [""] + [f"{i:02d}" for i in range(1, 32)]
day_combo['values'] = default_days
except ValueError:
default_days = [""] + [f"{i:02d}" for i in range(1, 32)]
day_combo['values'] = default_days
self.on_change()
def _build_url(self, parent_frame, widget_data):
"""Build URL input (protocol dropdown + URL entry)"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
url_frame = ttk.Frame(parent_frame)
url_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Protocol dropdown
protocol_var = tk.StringVar(value="https://")
protocol_combo = ttk.Combobox(
url_frame,
textvariable=protocol_var,
values=["https://", "http://"],
width=8,
state="readonly"
)
protocol_combo.pack(side=tk.LEFT)
protocol_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
# URL entry
url_var = tk.StringVar()
url_entry = ttk.Entry(url_frame, textvariable=url_var)
url_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
# Real-time validation function
def validate_on_change(*args):
url_part = url_var.get().strip()
protocol = protocol_var.get()
if not url_part:
# Empty field - normal style
url_entry.configure(style='TEntry')
else:
# Build full URL and validate
if url_part.startswith(("http://", "https://")):
full_url = url_part
else:
full_url = f"{protocol}{url_part}"
# Validate URL
if VALIDATORS_AVAILABLE:
is_valid = validators.url(full_url) is True
else:
# Fallback validation
is_valid = self._validate_url_manual(full_url)
if is_valid:
url_entry.configure(style='TEntry')
else:
url_entry.configure(style='Invalid.TEntry')
# Trigger command regeneration
self.on_change()
# Bind validation to variable changes
url_var.trace_add("write", validate_on_change)
protocol_var.trace_add("write", validate_on_change)
widget_data.update({
"protocol_var": protocol_var,
"url_var": url_var,
"widget": url_entry
})
self.widget_vars.append(widget_data)
def _validate_url_manual(self, url):
"""
Fallback URL validation without validators library.
Basic validation - not as comprehensive as validators package.
"""
if not url.strip():
return True
# No whitespace allowed
if any(c in url for c in [' ', '\n', '\t', '\r']):
return False
# Must start with http:// or https://
if not url.startswith(('http://', 'https://')):
return False
# Basic URL pattern
import re
pattern = r'^https?://[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*(\.[a-zA-Z]{2,})(:[0-9]{1,5})?(/.*)?$'
if not re.match(pattern, url, re.IGNORECASE):
return False
# Validate port number if present
if '://' in url:
try:
after_protocol = url.split('://')[1]
domain_part = after_protocol.split('/')[0]
if ':' in domain_part:
port_str = domain_part.split(':')[1]
port = int(port_str)
if not (1 <= port <= 65535):
return False
except (ValueError, IndexError):
return False
return True
def _is_valid_path_syntax(self, path):
"""
Check if path has valid syntax (not if it exists).
Attempts to find a balance for both Windows and Unix.
Allows shell wildcards like * and ?.
Returns:
(bool, str): (is_valid, error_message)
"""
import re
# 1. Block the only universally invalid character
if '\0' in path:
return False, "Invalid NUL character"
# 2. Check for empty/whitespace-only paths
# (The caller should handle this, but good to double-check)
if not path or path.isspace():
return False, "" # Empty is not "invalid", just empty
# 3. Block Windows-specific invalid characters that are NOT
# shell wildcards. We allow *, ?, <, >, | because shlex.quote()
# will handle them for the command.
#
# The main culprits are ':' (in the wrong place) and '"'.
if '"' in path:
return False, "Path cannot contain double quotes"
if ':' in path:
# A colon is ONLY allowed as the second character (e.g., "C:")
# and must be followed by a separator.
colon_indices = [i for i, char in enumerate(path) if char == ':']
for i in colon_indices:
if i != 1:
# This is a colon *not* in the 'C:' position (e.g., "my:file.txt")
return False, f"Invalid character ':'"
if i == 1:
if len(path) > 2 and path[2] not in ('/', '\\'):
# This is "C:file" (invalid) instead of "C:\file" or "C:/file"
return False, r"Drive letter must be followed by \ or /"
if len(path) == 2 and path[0].isalpha():
# This is just "C:" which is fine
pass
elif not path[0].isalpha():
return False, "Drive letter must be a letter"
# 4. Check for Windows Reserved Names (as the *final* part of the path)
# We need to get the filename/directory name, not the whole path.
# Replace both types of slashes with a standard one
normalized_path = path.replace('\\', '/')
# Get the last component
last_component = normalized_path.split('/')[-1]
# Get the "name" part before any extension
name_only = last_component.split('.')[0].upper()
invalid_names = [
'CON', 'PRN', 'AUX', 'NUL', 'COM1', 'COM2', 'COM3', 'COM4',
'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2',
'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
]
if name_only in invalid_names:
return False, f"'{last_component}' is a reserved system name"
# 5. Check for consecutive slashes
if '///' in path or r'\\\\' in path: # check both
return False, "Too many consecutive separators"
# If it passed all checks, it's valid
return True, ""
def _build_file_w_ext(self, parent_frame, widget_data):
"""Build file with extension (basename + extension dropdown)"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
file_frame = ttk.Frame(parent_frame)
file_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
# Base filename entry
base_var = tk.StringVar()
base_var.trace_add("write", lambda n, i, m: self.on_change())
base_entry = ttk.Entry(file_frame, textvariable=base_var)
base_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
# Extension dropdown
ext_var = tk.StringVar()
options = widget_data.get("options", [])
if options:
ext_combo = ttk.Combobox(
file_frame,
textvariable=ext_var,
values=options,
state="readonly",
width=10
)
ext_combo.pack(side=tk.LEFT)
ext_combo.set(options[0])
ext_combo.bind("<<ComboboxSelected>>", lambda e: self.on_change())
widget_data.update({
"base_var": base_var,
"ext_var": ext_var,
"widget": base_entry
})
self.widget_vars.append(widget_data)
def _build_file_picker(self, parent_frame, widget_data):
"""Build file picker (entry + browse button)"""
# Main container
container = ttk.Frame(parent_frame)
container.pack(fill=tk.X)
label = ttk.Label(container, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
# Right side for entry + button + feedback
right_container = ttk.Frame(container)
right_container.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
var = tk.StringVar()
picker_frame = ttk.Frame(right_container)
picker_frame.pack(fill=tk.X)
entry = ttk.Entry(picker_frame, textvariable=var)
entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
def browse_file():
path = filedialog.askopenfilename()
if path:
var.set(Path(path).as_posix())
button = ttk.Button(picker_frame, text="Browse...", command=browse_file)
button.pack(side=tk.LEFT, padx=(5, 0))
# Feedback label (hidden by default)
feedback_label = ttk.Label(right_container, text="",
style="Tooltip.TLabel",
foreground=self.theme["ERROR_RED"])
def validate_path_syntax(*args):
"""Validate path syntax (not existence)"""
path = var.get()
if not path:
entry.configure(style='TEntry')
# Hide feedback
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
else:
is_valid, error_message = self._is_valid_path_syntax(path)
if is_valid:
entry.configure(style='TEntry')
# Hide feedback
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
else:
entry.configure(style='Invalid.TEntry')
feedback_label.config(text=f"⚠️ {error_message}")
# Show feedback
if not feedback_label.winfo_ismapped():
feedback_label.pack(fill=tk.X, anchor="w")
self.on_change()
var.trace_add("write", validate_path_syntax)
widget_data.update({"var": var, "widget": entry})
self.widget_vars.append(widget_data)
def _build_dir_picker(self, parent_frame, widget_data):
"""Build directory picker (entry + browse button)"""
# Main container
container = ttk.Frame(parent_frame)
container.pack(fill=tk.X)
label = ttk.Label(container, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
# Right side for entry + button + feedback
right_container = ttk.Frame(container)
right_container.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
var = tk.StringVar()
picker_frame = ttk.Frame(right_container)
picker_frame.pack(fill=tk.X)
entry = ttk.Entry(picker_frame, textvariable=var)
entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
def browse_dir():
path = filedialog.askdirectory()
if path:
var.set(Path(path).as_posix())
button = ttk.Button(picker_frame, text="Browse...", command=browse_dir)
button.pack(side=tk.LEFT, padx=(5, 0))
# Feedback label (hidden by default)
feedback_label = ttk.Label(right_container, text="",
style="Tooltip.TLabel",
foreground=self.theme["ERROR_RED"])
def validate_path_syntax(*args):
"""Validate path syntax (not existence)"""
path = var.get()
if not path:
entry.configure(style='TEntry')
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
else:
is_valid, error_message = self._is_valid_path_syntax(path)
if is_valid:
entry.configure(style='TEntry')
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
else:
entry.configure(style='Invalid.TEntry')
feedback_label.config(text=f"⚠️ {error_message}")
if not feedback_label.winfo_ismapped():
feedback_label.pack(fill=tk.X, anchor="w")
self.on_change()
var.trace_add("write", validate_path_syntax)
widget_data.update({"var": var, "widget": entry})
self.widget_vars.append(widget_data)
def _build_file_save_as(self, parent_frame, widget_data):
"""Build save-as file picker (entry + save button)"""
# Main container
container = ttk.Frame(parent_frame)
container.pack(fill=tk.X)
label = ttk.Label(container, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
# Right side for entry + button + feedback
right_container = ttk.Frame(container)
right_container.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
var = tk.StringVar()
picker_frame = ttk.Frame(right_container)
picker_frame.pack(fill=tk.X)
entry = ttk.Entry(picker_frame, textvariable=var)
entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
def save_as():
path = filedialog.asksaveasfilename()
if path:
var.set(Path(path).as_posix())
button = ttk.Button(picker_frame, text="Save As...", command=save_as)
button.pack(side=tk.LEFT, padx=(5, 0))
# Feedback label (hidden by default)
feedback_label = ttk.Label(right_container, text="",
style="Tooltip.TLabel",
foreground=self.theme["ERROR_RED"])
def validate_path_syntax(*args):
"""Validate path syntax (not existence)"""
path = var.get()
if not path:
entry.configure(style='TEntry')
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
else:
is_valid, error_message = self._is_valid_path_syntax(path)
if is_valid:
entry.configure(style='TEntry')
if feedback_label.winfo_ismapped():
feedback_label.pack_forget()
else:
entry.configure(style='Invalid.TEntry')
feedback_label.config(text=f"⚠️ {error_message}")
if not feedback_label.winfo_ismapped():
feedback_label.pack(fill=tk.X, anchor="w")
self.on_change()
var.trace_add("write", validate_path_syntax)
widget_data.update({"var": var, "widget": entry})
self.widget_vars.append(widget_data)
def _build_number_input(self, parent_frame, widget_data):
"""Build number-only input with validation"""
label = ttk.Label(parent_frame, text=f"{widget_data['label']}:")
label.pack(side=tk.LEFT, anchor="w")
var = tk.StringVar()
var.trace_add("write", lambda n, i, m: self.on_change())
# Get bounds from widget_data
min_val = widget_data.get("min", 0)
max_val = widget_data.get("max", 999999)
# Validation function
def validate_number(P):
if P == "":
return True
if not P.isdigit():
return False
try:
num = int(P)
return min_val <= num <= max_val
except ValueError:
return False
vcmd = (parent_frame.register(validate_number), '%P')
entry = ttk.Entry(
parent_frame,
textvariable=var,
validate="key",
validatecommand=vcmd
)
entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
widget_data.update({"var": var, "widget": entry})
self.widget_vars.append(widget_data)
# ========== CLEARING METHODS ==========
def clear_form(self):
"""Reset all widget values"""
for item in self.widget_vars:
self._clear_widget(item)
if self.permission_vars:
for category in self.permission_vars.values():
for perm_var in category.values():
perm_var.set(False)
def _clear_widget(self, item):
"""Clear a single widget's value"""
item_type = item.get("type", "text")
clearers = {
"checkbox": self._clear_checkbox,
"text": self._clear_text,
"dropdown": self._clear_text,
"size_input": self._clear_size_input,
"relative_time_input": self._clear_relative_time_input,
"notable_text_input": self._clear_notable_text_input,
"permission_input": self._clear_permission_input,
"date_input": self._clear_date_input,
"url": self._clear_url,
"file_w_ext": self._clear_file_w_ext,
"file_picker": self._clear_text,
"dir_picker": self._clear_text,
"file_save_as": self._clear_text,
"number_input": self._clear_text,
"permission_grid": lambda item: None,
}
clearer = clearers.get(item_type, self._clear_text)
clearer(item)
def _clear_checkbox(self, item):
item["var"].set(False)
def _clear_text(self, item):
if "var" in item:
item["var"].set("")