-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhackdvb_gui.py
More file actions
4477 lines (3833 loc) · 249 KB
/
hackdvb_gui.py
File metadata and controls
4477 lines (3833 loc) · 249 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 tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinter.scrolledtext import ScrolledText
import json
import subprocess
import os
import sys
import threading
import re
import queue
import tempfile
import shutil
import webbrowser
from datetime import datetime, timedelta
import xml.sax.saxutils
import xml.etree.ElementTree as ET
class TextContextMenu:
"""A class to add a right-click context menu to Text and Entry widgets."""
def __init__(self, master):
self.master = master
self.menu = tk.Menu(master, tearoff=0)
self.menu.add_command(label="Cut", command=self.cut)
self.menu.add_command(label="Copy", command=self.copy)
self.menu.add_command(label="Paste", command=self.paste)
self.master.bind("<Button-3>", self.show_menu)
def show_menu(self, event):
# Disable Cut/Paste for read-only widgets
if self.master.cget('state') == 'disabled' or self.master.cget('state') == 'readonly':
self.menu.entryconfig("Cut", state="disabled")
self.menu.entryconfig("Paste", state="disabled")
else:
self.menu.entryconfig("Cut", state="normal")
self.menu.entryconfig("Paste", state="normal")
self.menu.post(event.x_root, event.y_root)
def cut(self):
self.master.event_generate("<<Cut>>")
def copy(self):
self.master.event_generate("<<Copy>>")
def paste(self):
self.master.event_generate("<<Paste>>")
def make_readonly(widget):
"""Makes a text widget read-only but allows selection and copying."""
widget.bind("<KeyPress>", lambda e: "break")
class ToolTip:
"""
Create a tooltip for a given widget.
"""
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip_window = None
self.id = None
self.x = self.y = 0
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(500, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
try:
# For widgets like Entry, Text with an insert cursor
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
except (tk.TclError, TypeError):
# For other widgets, position relative to the mouse pointer
x = self.widget.winfo_pointerx() + 15
y = self.widget.winfo_pointery() + 10
self.tooltip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{x}+{y}")
label = tk.Label(tw, text=self.text, justify='left',
background="#ffffe0", relief='solid', borderwidth=1,
font=("tahoma", "8", "normal"))
label.pack(ipadx=1)
def hidetip(self):
tw = self.tooltip_window
self.tooltip_window = None
if tw:
tw.destroy()
class HackDvbGui(tk.Tk):
APP_VERSION = "beta 1.00"
def __init__(self):
super().__init__()
self.withdraw() # Hide main window until dependencies are checked
# --- Executable Paths ---
# Define StringVars first, then load persistent settings which will update them.
self.ffmpeg_path = tk.StringVar(value="ffmpeg")
self.tsp_path = tk.StringVar(value="tsp")
self.tdt_path = tk.StringVar(value="tdt.exe")
self.analysis_file_path = tk.StringVar(value="") # Path for the tsp analyze plugin output
# --- Persistent Settings File ---
self._initialize_settings_path() # This will find or set the settings file path
self.title(f"HackDVB GUI - {self.APP_VERSION}")
self.geometry("900x750")
# --- Set Application Icon ---
try:
# Build an absolute path to the icon file relative to the script's location
# self.app_dir is set in _initialize_settings_path()
icon_path = os.path.join(self.app_dir, 'dvb_logo.ico')
self.iconbitmap(icon_path)
except tk.TclError:
print(f"Could not set application icon. '{icon_path}' not found or invalid.")
self.cuda_supported = False # Will be determined after dependency check
self.qsv_supported = False # Will be determined after dependency check
self.process = None
self.log_queue = queue.Queue()
self.country_code_map = { # ISO 3166-1 alpha-3
"afg": "Afghanistan", "ala": "Åland Islands", "alb": "Albania", "dza": "Algeria", "asm": "American Samoa",
"and": "Andorra", "ago": "Angola", "aia": "Anguilla", "ata": "Antarctica", "atg": "Antigua and Barbuda",
"arg": "Argentina", "arm": "Armenia", "abw": "Aruba", "aus": "Australia", "aut": "Austria", "aze": "Azerbaijan",
"bhs": "Bahamas", "bhr": "Bahrain", "bgd": "Bangladesh", "brb": "Barbados", "blr": "Belarus", "bel": "Belgium",
"blz": "Belize", "ben": "Benin", "bmu": "Bermuda", "btn": "Bhutan", "bol": "Bolivia", "bes": "Bonaire, Sint Eustatius and Saba",
"bwa": "Botswana", "bvt": "Bouvet Island", "bra": "Brazil", "iot": "British Indian Ocean Territory", "brn": "Brunei Darussalam",
"bgr": "Bulgaria", "bfa": "Burkina Faso", "bdi": "Burundi", "cpv": "Cabo Verde", "khm": "Cambodia", "cmr": "Cameroon",
"can": "Canada", "cym": "Cayman Islands", "caf": "Central African Republic", "tcd": "Chad", "chl": "Chile", "chn": "China",
"cxr": "Christmas Island", "cck": "Cocos (Keeling) Islands", "col": "Colombia", "com": "Comoros", "cog": "Congo",
"cod": "Congo (DRC)", "cok": "Cook Islands", "cri": "Costa Rica", "civ": "Côte d'Ivoire", "hrv": "Croatia",
"cub": "Cuba", "cuw": "Curaçao", "cyp": "Cyprus", "cze": "Czech Republic", "dnk": "Denmark", "dji": "Djibouti",
"dma": "Dominica", "dom": "Dominican Republic", "ecu": "Ecuador", "egy": "Egypt", "slv": "El Salvador",
"gnq": "Equatorial Guinea", "eri": "Eritrea", "est": "Estonia", "swz": "Eswatini", "eth": "Ethiopia",
"flk": "Falkland Islands (Malvinas)", "fro": "Faroe Islands", "fji": "Fiji", "fin": "Finland", "fra": "France",
"guf": "French Guiana", "pyf": "French Polynesia", "atf": "French Southern Territories", "gab": "Gabon",
"gmb": "Gambia", "geo": "Georgia", "deu": "Germany", "gha": "Ghana", "gib": "Gibraltar", "grc": "Greece",
"grl": "Greenland", "grd": "Grenada", "glp": "Guadeloupe", "gum": "Guam", "gtm": "Guatemala", "ggy": "Guernsey",
"gin": "Guinea", "gnb": "Guinea-Bissau", "guy": "Guyana", "hti": "Haiti", "hmd": "Heard Island and McDonald Islands",
"vat": "Holy See", "hnd": "Honduras", "hkg": "Hong Kong", "hun": "Hungary", "isl": "Iceland", "ind": "India",
"idn": "Indonesia", "irn": "Iran", "irq": "Iraq", "irl": "Ireland", "imn": "Isle of Man", "isr": "Israel",
"ita": "Italy", "jam": "Jamaica", "jpn": "Japan", "jey": "Jersey", "jor": "Jordan", "kaz": "Kazakhstan",
"ken": "Kenya", "kir": "Kiribati", "prk": "Korea (North)", "kor": "Korea (South)", "kwt": "Kuwait",
"kgz": "Kyrgyzstan", "lao": "Laos", "lva": "Latvia", "lbn": "Lebanon", "lso": "Lesotho", "lbr": "Liberia",
"lby": "Libya", "lie": "Liechtenstein", "ltu": "Lithuania", "lux": "Luxembourg", "mac": "Macao", "mdg": "Madagascar",
"mwi": "Malawi", "mys": "Malaysia", "mdv": "Maldives", "mli": "Mali", "mlt": "Malta", "mhl": "Marshall Islands",
"mtq": "Martinique", "mrt": "Mauritania", "mus": "Mauritius", "myt": "Mayotte", "mex": "Mexico",
"fsm": "Micronesia", "mda": "Moldova", "mco": "Monaco", "mng": "Mongolia", "mne": "Montenegro", "msr": "Montserrat",
"mar": "Morocco", "moz": "Mozambique", "mmr": "Myanmar", "nam": "Namibia", "nru": "Nauru", "npl": "Nepal",
"nld": "Netherlands", "ncl": "New Caledonia", "nzl": "New Zealand", "nic": "Nicaragua", "ner": "Niger",
"nga": "Nigeria", "niu": "Niue", "nfk": "Norfolk Island", "mkd": "North Macedonia", "mnp": "Northern Mariana Islands",
"nor": "Norway", "omn": "Oman", "pak": "Pakistan", "plw": "Palau", "pse": "Palestine, State of", "pan": "Panama",
"png": "Papua New Guinea", "pry": "Paraguay", "per": "Peru", "phl": "Philippines", "pcn": "Pitcairn", "pol": "Poland",
"prt": "Portugal", "pri": "Puerto Rico", "qat": "Qatar", "reu": "Réunion", "rou": "Romania", "rus": "Russian Federation",
"rwa": "Rwanda", "blm": "Saint Barthélemy", "shn": "Saint Helena, Ascension and Tristan da Cunha",
"kna": "Saint Kitts and Nevis", "lca": "Saint Lucia", "maf": "Saint Martin (French part)",
"spm": "Saint Pierre and Miquelon", "vct": "Saint Vincent and the Grenadines", "wsm": "Samoa",
"smr": "San Marino", "stp": "Sao Tome and Principe", "sau": "Saudi Arabia", "sen": "Senegal", "srb": "Serbia",
"syc": "Seychelles", "sle": "Sierra Leone", "sgp": "Singapore", "sxm": "Sint Maarten (Dutch part)",
"svk": "Slovakia", "svn": "Slovenia", "slb": "Solomon Islands", "som": "Somalia", "zaf": "South Africa",
"sgs": "South Georgia and the South Sandwich Islands", "ssd": "South Sudan", "esp": "Spain", "lka": "Sri Lanka",
"sdn": "Sudan", "sur": "Suriname", "sjm": "Svalbard and Jan Mayen", "swe": "Sweden", "che": "Switzerland",
"syr": "Syrian Arab Republic", "twn": "Taiwan", "tjk": "Tajikistan", "tza": "Tanzania", "tha": "Thailand",
"tls": "Timor-Leste", "tgo": "Togo", "tkl": "Tokelau", "ton": "Tonga", "tto": "Trinidad and Tobago",
"tun": "Tunisia", "tur": "Turkey", "tkm": "Turkmenistan", "tca": "Turks and Caicos Islands", "tuv": "Tuvalu",
"uga": "Uganda", "ukr": "Ukraine", "are": "United Arab Emirates", "gbr": "United Kingdom",
"usa": "United States of America", "ury": "Uruguay", "uzb": "Uzbekistan", "vut": "Vanuatu",
"ven": "Venezuela", "vnm": "Viet Nam", "vgb": "Virgin Islands (British)", "vir": "Virgin Islands (U.S.)",
"wlf": "Wallis and Futuna", "esh": "Western Sahara", "yem": "Yemen", "zmb": "Zambia", "zwe": "Zimbabwe"
}
self.tdt_process = None
self.channels = []
self.tool_process = None
self.epg_events = [] # To store EPG event data
self.subtitle_size_map = {
"Small": "18",
"Medium": "24",
"Large": "36",
"X-Large": "48"
}
# Register validation commands
self.numeric_validate_cmd = self.register(self._validate_numeric_input)
self.hex_validate_cmd = self.register(self._validate_hex_input)
# --- UI Theme and Style ---
style = ttk.Style(self)
try:
style.theme_use('clam')
except tk.TclError:
# 'clam' theme may not be available on all systems
pass
# -- Colors --
BG_COLOR = "#f7f7f7"
TEXT_COLOR = "#333333"
HEADER_COLOR = "#005f9e"
ACCENT_COLOR = "#0078d4"
SUCCESS_COLOR = "#107c10"
DISABLED_BG = "#e9e9e9"
self.configure(bg=BG_COLOR)
style.configure(".", background=BG_COLOR, foreground=TEXT_COLOR, font=("Segoe UI", 9))
style.configure("TLabel", padding=5)
style.configure("TButton", padding=6, font=("Segoe UI", 9, "bold"))
style.configure("TEntry", padding=5)
style.configure("TCombobox", padding=5)
style.configure("Success.TButton", foreground="white", background=SUCCESS_COLOR)
style.map("Success.TButton", background=[('active', '#0d630d')])
style.configure("TFrame", background=BG_COLOR)
style.configure("TLabelframe", padding=10, background=BG_COLOR)
style.configure("Header.TLabel", font=("Segoe UI", 13, "bold"), foreground=HEADER_COLOR)
style.configure("TLabelframe.Label", font=("Segoe UI", 10, "bold"), foreground=TEXT_COLOR)
style.map("TCombobox", fieldbackground=[('readonly', 'white')])
style.configure("TNotebook.Tab", font=("Segoe UI", 10, "bold"), padding=[10, 5])
style.configure("Action.TFrame", background="#e0e0e0")
style.configure("Action.TLabel", background="#e0e0e0", font=("Segoe UI", 9, "bold"))
style.configure("Card.TLabelframe", borderwidth=1, relief="solid", bordercolor="#dcdcdc")
style.configure("Card.TLabelframe.Label", foreground=TEXT_COLOR)
style.map("TNotebook.Tab", background=[("selected", BG_COLOR)], foreground=[("selected", ACCENT_COLOR)])
# --- Main Frame ---
# --- Menu Bar ---
menubar = tk.Menu(self)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Save Configuration...", command=self.save_configuration)
filemenu.add_command(label="Load Configuration...", command=self.load_configuration)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.quit)
ToolTip(filemenu, "Save the current session to a file, or load a previous session.")
menubar.add_cascade(label="File", menu=filemenu)
# --- Settings Menu ---
settingsmenu = tk.Menu(menubar, tearoff=0)
dep_paths_menu = tk.Menu(settingsmenu, tearoff=0)
dep_paths_menu.add_command(label="FFmpeg Path...", command=lambda: self.browse_for_executable(self.ffmpeg_path, "FFmpeg"))
dep_paths_menu.add_command(label="TSDuck (tsp) Path...", command=lambda: self.browse_for_executable(self.tsp_path, "TSDuck (tsp)"))
dep_paths_menu.add_command(label="TDT Injector Path...", command=lambda: self.browse_for_executable(self.tdt_path, "TDT Injector"))
settingsmenu.add_cascade(label="Dependency Paths", menu=dep_paths_menu)
file_paths_menu = tk.Menu(settingsmenu, tearoff=0)
file_paths_menu.add_command(label="Analysis Report Path...", command=self.browse_for_analysis_file)
file_paths_menu.add_command(label="Settings File Location...", command=self.change_settings_file_location)
settingsmenu.add_cascade(label="File & Folder Paths", menu=file_paths_menu)
menubar.add_cascade(label="Settings", menu=settingsmenu)
# --- Help Menu ---
helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="About...", command=self.show_about_dialog)
helpmenu.add_command(label="Dependencies...", command=self.show_dependencies_dialog)
ToolTip(helpmenu, "View application information and details about required external tools.")
menubar.add_cascade(label="Help", menu=helpmenu)
# --- Wiki Menu ---
wikimenu = tk.Menu(menubar, tearoff=0)
wikimenu.add_command(label="Open Wiki...", command=self.show_wiki)
ToolTip(wikimenu, "Open the in-app wiki for detailed documentation on all features.")
menubar.add_cascade(label="Wiki", menu=wikimenu)
self.config(menu=menubar)
main_frame = ttk.Frame(self, padding=(10, 10, 10, 0))
main_frame.pack(fill=tk.BOTH, expand=True)
main_frame.grid_columnconfigure(0, weight=1) # The main paned window will be in column 0
main_frame.grid_rowconfigure(0, weight=1) # The main paned window will be in row 0
# --- Main Vertical Paned Window ---
# This will hold the notebook (top) and the command/log section (bottom)
self.main_paned_window = ttk.PanedWindow(main_frame, orient=tk.VERTICAL)
self.main_paned_window.grid(row=0, column=0, sticky="nsew")
# --- Tabbed Interface ---
# The notebook is now placed inside the self.main_paned_window instead of main_frame
notebook_frame = ttk.Frame(self.main_paned_window) # A container for the notebook
notebook = ttk.Notebook(notebook_frame)
notebook.pack(fill=tk.BOTH, expand=True)
self.main_paned_window.add(notebook_frame, weight=2) # Give tabs more initial space
# -- Inputs Tab --
self.inputs_tab = self._create_tab(notebook, "Inputs")
self.inputs_tab.grid_rowconfigure(0, weight=1)
self.inputs_tab.grid_columnconfigure(0, weight=1)
inputs_canvas_frame = ttk.Frame(self.inputs_tab)
inputs_canvas_frame.grid(row=0, column=0, sticky='nsew')
inputs_canvas_frame.grid_rowconfigure(0, weight=1)
inputs_canvas_frame.grid_columnconfigure(0, weight=1)
self.inputs_canvas = tk.Canvas(inputs_canvas_frame, borderwidth=0, highlightthickness=0)
self.inputs_scrollbar = ttk.Scrollbar(inputs_canvas_frame, orient="vertical", command=self.inputs_canvas.yview)
self.scrollable_inputs_frame = ttk.Frame(self.inputs_canvas, padding=(0,0))
self.scrollable_inputs_frame.bind("<Configure>", lambda e: self.inputs_canvas.configure(scrollregion=self.inputs_canvas.bbox("all")))
self.inputs_canvas.create_window((0, 0), window=self.scrollable_inputs_frame, anchor="nw")
self.inputs_canvas.configure(yscrollcommand=self.inputs_scrollbar.set)
self.inputs_canvas.grid(row=0, column=0, sticky='nsew')
self.inputs_scrollbar.grid(row=0, column=1, sticky='ns')
self.inputs_frame = ttk.Frame(self.scrollable_inputs_frame, padding=(0,0))
self.inputs_frame.grid(row=0, column=0, sticky='nsew')
# Configure a 4-column grid for the input cards
self.inputs_frame.grid_columnconfigure(0, weight=1)
self.inputs_frame.grid_columnconfigure(1, weight=1)
eit_frame = ttk.Labelframe(self.scrollable_inputs_frame, text="EIT Data", padding=10, style="Card.TLabelframe")
eit_frame.grid(row=1, column=0, sticky='ew', pady=(10,0), padx=(0,15))
eit_frame.grid_columnconfigure(1, weight=1)
eit_frame.grid_rowconfigure(0, pad=5)
eit_filetypes = [("XML files", "*.xml"), ("All files", "*.*")]
_, eit_entry, eit_browse_btn, self.eit_path = self.create_file_input_widgets(eit_frame, "EIT XML File:", 0, filetypes=eit_filetypes)
# Adjust grid to make space for the new button
eit_entry.grid(columnspan=1)
eit_browse_btn.grid(column=2)
epg_editor_btn = ttk.Button(eit_frame, text="Create/Edit EPG...", command=self.open_epg_editor)
epg_editor_btn.grid(row=0, column=3, sticky="w", padx=(5, 5))
ToolTip(epg_editor_btn, "Open the EPG Editor to create or modify a schedule.\nThe generated schedule is saved to a temporary XML file and its path is automatically set here.")
ToolTip(eit_frame.winfo_children()[1], "Path to a TSDuck-compatible XML file for EIT (Event Information Table) data.\nThis provides the Electronic Program Guide (EPG) on the receiver.")
delete_eit_btn = ttk.Button(eit_frame, text="✖", command=self.delete_eit_file, width=3)
delete_eit_btn.grid(row=0, column=4, sticky="w")
ToolTip(delete_eit_btn, "Delete the temporary EPG file generated by the editor and clear this path.")
# -- Services Tab --
self.services_tab = self._create_tab(notebook, "Services")
self.services_tab.grid_rowconfigure(1, weight=1)
self.services_tab.grid_columnconfigure(0, weight=1)
add_channel_button = ttk.Button(self.services_tab, text="✚ Add Channel", command=self.add_channel)
ToolTip(add_channel_button, "Add a new service (channel) to the multiplex.")
add_channel_button.grid(row=0, column=0, sticky='w', pady=(0,10))
# --- Scrollable area for services ---
canvas_frame = ttk.Frame(self.services_tab)
canvas_frame.grid(row=1, column=0, columnspan=3, sticky='nsew')
canvas_frame.grid_rowconfigure(0, weight=1)
canvas_frame.grid_columnconfigure(0, weight=1)
self.service_canvas = tk.Canvas(canvas_frame, borderwidth=0, highlightthickness=0)
self.service_scrollbar = ttk.Scrollbar(canvas_frame, orient="vertical", command=self.service_canvas.yview)
self.scrollable_service_frame = ttk.Frame(self.service_canvas, padding=(10,0))
# Configure a 2-column grid for the service cards
self.scrollable_service_frame.grid_columnconfigure(0, weight=1)
self.scrollable_service_frame.grid_columnconfigure(1, weight=1)
self.scrollable_service_frame.grid_columnconfigure(2, weight=1)
self.scrollable_service_frame.bind("<Configure>", lambda e: self.service_canvas.configure(scrollregion=self.service_canvas.bbox("all")))
self.service_canvas.create_window((0, 0), window=self.scrollable_service_frame, anchor="nw")
self.service_canvas.configure(yscrollcommand=self.service_scrollbar.set)
self.service_canvas.grid(row=0, column=0, sticky='nsew')
self.service_scrollbar.grid(row=0, column=1, sticky='ns')
self.bind_all("<MouseWheel>", self._on_mousewheel)
# -- Encoding Tab --
encoding_tab = self._create_tab(notebook, "Encoding & Muxing")
encoding_tab.grid_columnconfigure(0, weight=1) # Allow content to expand horizontally
encoding_frame = ttk.Labelframe(encoding_tab, text="Bitrates", padding=(15, 10), style="Card.TLabelframe")
encoding_frame.grid(row=0, column=0, sticky='ew', pady=(0, 5))
encoding_frame.grid_columnconfigure(1, weight=1)
_, video_bitrate_entry, self.video_bitrate = self.create_text_input_widgets(encoding_frame, "Video Bitrate (k):", 0, "6000", validation_type="numeric")
ToolTip(video_bitrate_entry, "Target video bitrate in kilobits per second (kbps) for each service.\nHigher values improve quality but use more of the total Mux Rate.\nExample: 6000 for 6 Mbps.")
# The audio bitrate input was moved to the new Audio Encoding frame.
# We can hide the now-empty row to keep the layout clean.
encoding_frame.grid_rowconfigure(1, pad=0) # Hide the old audio bitrate row
# --- Audio Encoding Frame ---
audio_opts_frame = ttk.Labelframe(encoding_tab, text="Audio Encoding", padding=(15, 10))
audio_opts_frame.grid(row=1, column=0, sticky='ew', pady=5)
audio_opts_frame.grid_columnconfigure(1, weight=1)
# --- Data for dynamic audio options ---
self.audio_options_map = {
"mp2": {
"bitrates": ["128", "192", "224", "256", "320", "384"],
"samplerates": ["48000", "44100", "32000"],
"default_bitrate": "192"
},
"ac3": {
"bitrates": ["192", "224", "256", "320", "384", "448", "640"],
"samplerates": ["48000", "44100", "32000"],
"default_bitrate": "384"
},
"aac": {
"bitrates": ["96", "128", "160", "192", "256", "320"],
"samplerates": ["48000", "44100", "32000", "24000", "22050"],
"default_bitrate": "128"
},
"eac3": {
"bitrates": ["192", "224", "256", "384", "448", "640"],
"samplerates": ["48000"],
"default_bitrate": "224"
}
}
default_codec = "mp2"
_, self.audio_codec_combobox, self.audio_codec = self.create_combobox_input_widgets(audio_opts_frame, "Audio Codec:", 0, default_codec, list(self.audio_options_map.keys()))
self.audio_codec.trace_add("write", self.update_audio_options)
ToolTip(self.audio_codec_combobox, "The audio compression standard to use for all services.\n- mp2: The most common standard for DVB-S/T.\n- ac3: Dolby Digital, good for surround sound.\n- aac: Advanced Audio Coding, efficient codec.\n- eac3: Dolby Digital Plus.")
_, self.audio_bitrate_combobox, self.audio_bitrate = self.create_combobox_input_widgets(audio_opts_frame, "Audio Bitrate (k):", 1, "192", [])
ToolTip(self.audio_bitrate_combobox, "Target audio bitrate in kilobits per second (kbps).\n192 kbps is standard for stereo MP2. 384 kbps is common for 5.1 AC3.")
_, self.audio_samplerate_combobox, self.audio_samplerate = self.create_combobox_input_widgets(audio_opts_frame, "Sample Rate (Hz):", 2, "48000", [])
ToolTip(self.audio_samplerate_combobox, "The audio sample rate. 48000 Hz is the standard for digital video broadcasting.")
# Call once to populate initial values
self.update_audio_options()
self.use_loudnorm_var = tk.BooleanVar(value=True)
loudnorm_checkbox = ttk.Checkbutton(audio_opts_frame, text="Enable Loudness Normalization (EBU R128)", variable=self.use_loudnorm_var, command=self.update_command_preview)
loudnorm_checkbox.grid(row=3, column=0, columnspan=3, sticky='w', pady=(5,0))
ToolTip(loudnorm_checkbox, "Applies EBU R128 normalization to ensure consistent audio levels across all content.\nThis prevents viewers from having to adjust the volume between programs.\nCan be CPU intensive; disable if you experience performance issues.")
self.video_format_map = {
# --- PAL/25 FPS Based ---
"720x576i @ 25 fps (PAL SD)": ("720x576", "tt", "25"),
"720x576p @ 25 fps (PAL SD)": ("720x576", "prog", "25"),
"1280x720p @ 25 fps (HD)": ("1280x720", "prog", "25"),
"1920x1080i @ 25 fps (Full HD)": ("1920x1080", "tt", "25"),
"1920x1080p @ 25 fps (Full HD)": ("1920x1080", "prog", "25"),
# --- NTSC/29.97 FPS Based ---
"720x480i @ 29.97 fps (NTSC SD)": ("720x480", "bb", "30000/1001"),
"720x480p @ 29.97 fps (NTSC SD)": ("720x480", "prog", "30000/1001"),
"1280x720p @ 29.97 fps (HD)": ("1280x720", "prog", "30000/1001"),
"1920x1080i @ 29.97 fps (Full HD)": ("1920x1080", "tt", "30000/1001"),
"1920x1080p @ 29.97 fps (Full HD)": ("1920x1080", "prog", "30000/1001"),
# --- Film/24 FPS Based ---
"1920x1080p @ 24 fps (Full HD)": ("1920x1080", "prog", "24"),
"3840x2160p @ 24 fps (4K UHD)": ("3840x2160", "prog", "24"),
"4096x2160p @ 24 fps (DCI 4K)": ("4096x2160", "prog", "24"),
# --- High Frame Rate ---
"1280x720p @ 50 fps (HD)": ("1280x720", "prog", "50"),
"1920x1080p @ 50 fps (Full HD)": ("1920x1080", "prog", "50"),
"1280x720p @ 59.94 fps (HD)": ("1280x720", "prog", "60000/1001"),
"1920x1080p @ 59.94 fps (Full HD)": ("1920x1080", "prog", "60000/1001"),
"3840x2160p @ 50 fps (4K UHD)": ("3840x2160", "prog", "50"),
"3840x2160p @ 59.94 fps (4K UHD)": ("3840x2160", "prog", "60000/1001"),
}
self.language_map = {
# Common European
"English": "eng", "German": "ger", "French": "fre", "Spanish": "spa",
"Italian": "ita", "Portuguese": "por", "Dutch": "dut", "Swedish": "swe",
"Danish": "dan", "Norwegian": "nor", "Finnish": "fin", "Polish": "pol",
"Russian": "rus", "Greek": "gre", "Czech": "cze", "Slovak": "slo",
"Hungarian": "hun", "Romanian": "rum", "Bulgarian": "bul", "Croatian": "hrv",
"Serbian": "srp", "Slovenian": "slv", "Estonian": "est", "Latvian": "lav",
"Lithuanian": "lit", "Icelandic": "ice", "Irish": "gle", "Welsh": "cym",
"Basque": "baq", "Catalan": "cat", "Galician": "glg",
# Common World
"Arabic": "ara", "Chinese": "chi", "Japanese": "jpn", "Korean": "kor",
"Hindi": "hin", "Turkish": "tur", "Hebrew": "heb", "Thai": "tha",
"Vietnamese": "vie", "Indonesian": "ind", "Malay": "msa", "Tagalog": "tgl",
"Persian": "per", "Urdu": "urd", "Bengali": "ben", "Tamil": "tam",
"Telugu": "tel", "Marathi": "mar", "Swahili": "swa",
# Other
"Ukrainian": "ukr",
"Undetermined": "und"
}
# Sort languages alphabetically but keep "Undetermined" at the end
sorted_langs = sorted([lang for lang in self.language_map.keys() if lang != "Undetermined"])
sorted_langs.append("Undetermined")
video_opts_frame = ttk.Labelframe(encoding_tab, text="Video Encoding", padding=(15, 10), style="Card.TLabelframe")
video_opts_frame.grid(row=2, column=0, sticky='ew', pady=5)
video_opts_frame.grid_columnconfigure(1, weight=1)
hw_accel_frame = ttk.Frame(video_opts_frame)
hw_accel_frame.grid(row=0, column=0, columnspan=3, sticky='w', pady=(0,10))
self.use_cuda_var = tk.BooleanVar(value=False)
self.cuda_checkbox = ttk.Checkbutton(hw_accel_frame, text="Use NVIDIA CUDA", variable=self.use_cuda_var, command=self.update_hw_accel_options)
self.cuda_checkbox.pack(side=tk.LEFT, padx=(0, 15))
ToolTip(self.cuda_checkbox, "Enable to use your NVIDIA GPU for video encoding (NVENC).\nThis significantly reduces CPU usage and is highly recommended for real-time broadcasting.\nWill be disabled if no compatible hardware/drivers are found.")
self.use_qsv_var = tk.BooleanVar(value=False)
self.qsv_checkbox = ttk.Checkbutton(hw_accel_frame, text="Use Intel QSV", variable=self.use_qsv_var, command=self.update_hw_accel_options)
self.qsv_checkbox.pack(side=tk.LEFT)
ToolTip(self.qsv_checkbox, "Enable to use your Intel integrated GPU for video encoding (Quick Sync Video).\nThis significantly reduces CPU usage.\nWill be disabled if no compatible hardware/drivers are found.")
self.video_codec_map = {
"software": [
"mpeg2video", # DVB Standard
"libx264", # High-quality H.264/AVC
"libx265", # High-quality H.265/HEVC
"mpeg4", # MPEG-4 Part 2
"libvpx-vp9", # VP9
],
"cuda": [
"h264_nvenc", # H.264/AVC
"hevc_nvenc", # H.265/HEVC
],
"qsv": [
"h264_qsv",
"hevc_qsv",
]
}
self.preset_map = {
"software": [
"ultrafast", "superfast", "veryfast", "faster", "fast",
"medium", "slow", "slower", "veryslow"
],
"cuda": [
"p1 (fastest)", "p2", "p3", "p4 (medium)", "p5", "p6", "p7 (slowest)"
],
"qsv": [
"veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"
]
}
default_video_codec = "mpeg2video"
_, self.video_codec_combobox, self.video_codec = self.create_combobox_input_widgets(video_opts_frame, "Video Codec:", 1, default_video_codec, self.video_codec_map["software"])
ToolTip(self.video_codec_combobox, "The video compression standard (codec) to use for all services.\n- mpeg2video: Standard for DVB-S.\n- h264_nvenc/libx264: H.264 is the standard for DVB-S2, offering better quality for the same bitrate.")
default_preset = "medium"
_, self.preset_combobox, self.preset = self.create_combobox_input_widgets(video_opts_frame, "Codec Preset:", 2, default_preset, self.preset_map["software"])
ToolTip(self.preset_combobox, "A trade-off between encoding speed and quality/efficiency.\n- Faster presets use less CPU/GPU but result in lower quality.\n- Slower presets use more resources for better quality.\n'medium' or 'p4' is a good starting point.")
# Pixel Format
self.pix_fmt_options = ["yuv420p", "yuv422p", "yuv420p10le", "yuv422p10le"]
default_pix_fmt = "yuv420p"
_, self.pix_fmt_combobox, self.pix_fmt = self.create_combobox_input_widgets(video_opts_frame, "Pixel Format:", 3, default_pix_fmt, self.pix_fmt_options)
ToolTip(self.pix_fmt_combobox, "Defines the color information (chroma subsampling) and bit depth.\n- yuv420p: 8-bit color, 4:2:0 subsampling. The most common and compatible format.\n- yuv420p10le: 10-bit color. Used for HDR content with HEVC.")
video_opts_frame.grid_rowconfigure(0, pad=5) # cuda checkbox
video_opts_frame.grid_rowconfigure(1, pad=5) # codec
video_opts_frame.grid_rowconfigure(2, pad=5) # preset
video_opts_frame.grid_rowconfigure(3, pad=5) # pix_fmt
video_opts_frame.grid_rowconfigure(4, pad=5) # aspect
video_opts_frame.grid_rowconfigure(5, pad=5) # bframes
video_opts_frame.grid_rowconfigure(6, pad=5) # format
_, self.aspect_ratio_combobox, self.aspect_ratio = self.create_combobox_input_widgets(video_opts_frame, "Aspect Ratio:", 4, "16:9", ["16:9", "4:3"])
ToolTip(self.aspect_ratio_combobox, "The display aspect ratio for the video streams (e.g., 16:9 for widescreen).")
self.use_bframes_var = tk.BooleanVar(value=True)
bframes_checkbox = ttk.Checkbutton(video_opts_frame, text="Enable B-Frames", variable=self.use_bframes_var, command=self.update_command_preview)
bframes_checkbox.grid(row=5, column=0, columnspan=3, sticky='w')
ToolTip(bframes_checkbox, "Enable B-Frames for video encoding. Disabling this adds '-bf 0' to the command, which can improve compatibility but may reduce quality/efficiency.")
default_format = "720x576i @ 25 fps (PAL SD)"
_, self.video_format_combobox, self.video_format_display = self.create_combobox_input_widgets(video_opts_frame, "Video Format:", 6, default_format, list(self.video_format_map.keys()))
ToolTip(self.video_format_combobox, "Select a preset for the output resolution, scan type (i=interlaced, p=progressive), and frame rate.")
# -- Output Tab --
output_tab = self._create_tab(notebook, "DVB Broadcast")
output_tab.grid_columnconfigure(0, weight=1) # Allow content to expand horizontally
dektec_frame = ttk.Labelframe(output_tab, text="DVB-S/S2 Output", padding=(15, 10), style="Card.TLabelframe")
dektec_frame.grid(row=0, column=0, sticky='ew')
dektec_frame.grid_columnconfigure(1, weight=1)
dektec_frame.grid_rowconfigure(0, pad=5)
dektec_frame.grid_rowconfigure(1, pad=5)
dektec_frame.grid_rowconfigure(2, pad=5)
dektec_frame.grid_rowconfigure(3, pad=5)
dektec_frame.grid_rowconfigure(4, pad=5)
dektec_frame.grid_rowconfigure(5, pad=5)
dektec_frame.grid_rowconfigure(6, pad=5)
dektec_frame.grid_rowconfigure(7, pad=5)
video_opts_frame.grid_rowconfigure(6, pad=5) # format
_, dek_device_entry, self.dek_device = self.create_text_input_widgets(dektec_frame, "Device Index:", 0, "0", validation_type="numeric", columnspan=3)
ToolTip(dek_device_entry, "The index of the DekTec output device as seen by the system (usually 0 or 1).")
self.dvb_standard_options = ["DVB-S", "DVB-S2"]
_, dvb_standard_combobox, self.dvb_standard = self.create_combobox_input_widgets(dektec_frame, "Standard:", 1, "DVB-S", self.dvb_standard_options)
ToolTip(dvb_standard_combobox, "The DVB transmission standard.\n- DVB-S: Original standard, uses MPEG-2 video.\n- DVB-S2: More efficient, allows for HD channels using H.264.")
self.dvb_standard.trace_add("write", self.update_dvb_options)
self.mod_options = {
"DVB-S": ["DVB-S-QPSK"],
"DVB-S2": ["DVB-S2-QPSK", "DVB-S2-8PSK", "DVB-S2-16APSK", "DVB-S2-32APSK"]
}
_, self.dek_mod_combobox, self.dek_mod_var = self.create_combobox_input_widgets(dektec_frame, "Modulation:", 2, self.mod_options["DVB-S"][0], self.mod_options["DVB-S"])
ToolTip(self.dek_mod_combobox, "The modulation scheme. Higher-order modulations (e.g., 8PSK) are more efficient but require a stronger signal.\nOptions depend on the selected DVB standard.")
self.lnb_lo_options = ["10600", "9750"]
_, lnb_lo_freq_combobox, self.lnb_lo_freq = self.create_combobox_input_widgets(dektec_frame, "LNB LO (MHz):", 3, "10600", self.lnb_lo_options)
ToolTip(lnb_lo_freq_combobox, "The Local Oscillator frequency of your LNB.\nA Universal LNB uses 9750 MHz for the low band and 10600 MHz for the high band.")
self.lnb_lo_freq.trace_add("write", self._validate_frequency_range)
dek_freq_label, self.dek_freq_entry, self.dek_freq = self.create_text_input_widgets(dektec_frame, "Frequency (MHz):", 4, "11797", validation_type="numeric")
self.dek_freq_entry.grid(columnspan=1)
ToolTip(self.dek_freq_entry, "The target satellite frequency in MHz.\nThe GUI calculates the required hardware output frequency based on this and the LNB LO.")
self.dek_freq.trace_add("write", self._validate_frequency_range)
self.freq_warning_label = ttk.Label(dektec_frame, text="", foreground="red")
self.freq_warning_label.grid(row=4, column=2, columnspan=2, sticky="w", padx=(5,0))
_, dek_symrate_entry, self.dek_symrate = self.create_text_input_widgets(dektec_frame, "Symbol Rate (S/s):", 5, "27500000", validation_type="numeric", columnspan=3)
ToolTip(dek_symrate_entry, "The rate at which symbols are transmitted, in Symbols per second (e.g., 27500000).")
self.fec_options = {
"DVB-S": ["1/2", "2/3", "3/4", "5/6", "7/8"],
"DVB-S2": ["1/4", "1/3", "2/5", "1/2", "3/5", "2/3", "3/4", "4/5", "5/6", "8/9", "9/10"]
}
# Default to 3/4 which is valid for DVB-S
_, self.dek_fec_combobox, self.dek_fec_var = self.create_combobox_input_widgets(dektec_frame, "FEC:", 6, "3/4", self.fec_options["DVB-S"])
ToolTip(self.dek_fec_combobox, "Forward Error Correction rate. Higher rates (e.g., 7/8) are more efficient but offer less protection against signal errors.\nOptions depend on the selected DVB standard.")
# Mux Rate with Auto-Calculate
mux_rate_label = ttk.Label(dektec_frame, text="Mux Rate (bps):")
mux_rate_label.grid(row=7, column=0, sticky="w")
self.mux_rate_var = tk.StringVar(value="33790800")
mux_rate_entry = ttk.Entry(dektec_frame, textvariable=self.mux_rate_var, validate="key", validatecommand=(self.numeric_validate_cmd, '%P'))
ToolTip(mux_rate_entry, "The total bitrate of the final transport stream in bits per second (bps).\nThis must be high enough to accommodate all video, audio, and data streams.\nUse 'Auto-Calculate' for a good starting point.")
mux_rate_entry.grid(row=7, column=1, sticky="ew")
calc_button = ttk.Button(dektec_frame, text="Auto-Calculate", command=self.calculate_mux_rate)
ToolTip(calc_button, "Calculate the theoretical maximum mux rate based on the current DVB parameters.\nThis is a highly recommended starting point.")
calc_button.grid(row=7, column=2, sticky="w", padx=(5,0))
self.mux_rate_mbps_label = ttk.Label(dektec_frame, text="")
self.mux_rate_mbps_label.grid(row=7, column=3, sticky="w", padx=(5,0))
self.calculate_mux_rate() # Initial calculation
# --- Time Synchronization Frame ---
time_sync_frame = ttk.Labelframe(output_tab, text="Time Synchronization", padding=(15, 10), style="Card.TLabelframe")
time_sync_frame.grid(row=1, column=0, sticky='ew', pady=(10, 0))
time_sync_frame.grid_columnconfigure(1, weight=1)
tdt_ip_options = ["127.0.0.1", "localhost"]
_, tdt_ip_combobox, self.tdt_ip = self.create_combobox_input_widgets(time_sync_frame, "TDT IP Address:", 0, tdt_ip_options[0], tdt_ip_options)
ToolTip(tdt_ip_combobox, "The IP address for the TDT/TOT packet source.\nThis should match the address used by the tdt.exe utility.\nSelect either '127.0.0.1' or 'localhost'.")
_, tdt_port_entry, self.tdt_port = self.create_text_input_widgets(time_sync_frame, "TDT Port:", 1, "32000", validation_type="numeric")
ToolTip(tdt_port_entry, "The port for the TDT/TOT packet source. This can be any available port on your system.\nThis port will be used by both TSDuck and the TDT Injector utility to communicate.")
time_sync_frame.grid_rowconfigure(0, pad=5)
time_sync_frame.grid_rowconfigure(1, pad=5)
# -- Tools Tab (Moved to the end) --
self.tools_tab = self._create_tab(notebook, "Tools")
self.tools_tab.grid_columnconfigure(0, weight=1)
self.tools_tab.grid_rowconfigure(0, weight=1)
self._create_media_tools_ui(self.tools_tab)
# --- Bottom Pane for Command and Log ---
# This frame will be the bottom part of the main_paned_window
self.bottom_pane_container = ttk.Frame(self.main_paned_window, padding=(0, 10, 0, 5))
self.main_paned_window.add(self.bottom_pane_container, weight=1)
self.bottom_pane_container.grid_columnconfigure(0, weight=1)
self.bottom_pane_container.grid_rowconfigure(0, weight=1)
# This PanedWindow is now inside the bottom_pane_container
paned_window = ttk.PanedWindow(self.bottom_pane_container, orient=tk.VERTICAL)
paned_window.grid(row=0, column=0, sticky="nsew")
# --- Command Preview Pane ---
cmd_pane_frame = ttk.Frame(paned_window, padding=0)
paned_window.add(cmd_pane_frame, weight=1)
cmd_pane_frame.grid_rowconfigure(1, weight=1)
cmd_pane_frame.grid_columnconfigure(0, weight=1)
cmd_header_frame = self.create_section_header(cmd_pane_frame, "Generated Command")
self.preview_button = ttk.Button(cmd_header_frame, text="Preview Command", command=self.update_command_preview, style="Toolbutton")
ToolTip(self.preview_button, "Manually refresh the FFmpeg and TSDuck command preview below.")
self.export_command_button = ttk.Button(cmd_header_frame, text="Export...", command=self.export_command, style="Toolbutton")
ToolTip(self.export_command_button, "Save the generated command to a script file (.bat, .sh) for command-line use.")
self.export_command_button.pack(side=tk.RIGHT, padx=(5,0))
self.preview_button.pack(side=tk.RIGHT, padx=(10,0))
self.command_preview = tk.Text(cmd_pane_frame, height=6, wrap=tk.WORD, bg="black", fg="white", relief=tk.SUNKEN, borderwidth=1, insertbackground="white")
self.command_preview.grid(row=1, column=0, sticky="nsew")
make_readonly(self.command_preview)
TextContextMenu(self.command_preview)
# --- Log Output Pane ---
log_pane_frame = ttk.Frame(paned_window, padding=0)
paned_window.add(log_pane_frame, weight=3) # Give log more initial space
log_pane_frame.grid_rowconfigure(1, weight=1)
log_pane_frame.grid_columnconfigure(0, weight=1)
log_header_frame = self.create_section_header(log_pane_frame, "Live Log")
self.clear_log_button = ttk.Button(log_header_frame, text="Clear Log", command=self.clear_log, style="Toolbutton")
ToolTip(self.clear_log_button, "Clear the log output window.")
self.clear_log_button.pack(side=tk.RIGHT, padx=(0, 0))
self.save_log_button = ttk.Button(log_header_frame, text="Save Log", command=self.save_log, style="Toolbutton")
ToolTip(self.save_log_button, "Save the current log to a text file.")
self.save_log_button.pack(side=tk.RIGHT, padx=(10, 0))
self.log_output = ScrolledText(log_pane_frame, height=10, wrap=tk.WORD, bg="black", fg="white", relief=tk.SUNKEN, borderwidth=1, insertbackground="white")
self.log_output.grid(row=1, column=0, sticky="nsew")
make_readonly(self.log_output)
TextContextMenu(self.log_output)
# --- Action Buttons ---
button_frame = ttk.Frame(main_frame, padding=(10, 5), style="Action.TFrame")
button_frame.grid(row=1, column=0, sticky="ew", padx=0, pady=0)
button_frame.grid_columnconfigure(1, weight=1)
self.start_button = ttk.Button(button_frame, text="Start Broadcast", command=self.start_process, style="Success.TButton")
ToolTip(self.start_button, "Start the FFmpeg and TSDuck processes to begin the broadcast.")
self.start_button.pack(side=tk.LEFT, padx=(5,0))
self.stop_button = ttk.Button(button_frame, text="Stop Broadcast", command=self.stop_process, state=tk.DISABLED)
ToolTip(self.stop_button, "Stop all running broadcast and helper processes.")
self.stop_button.pack(side=tk.LEFT, padx=5)
self.status_label = ttk.Label(button_frame, text="Status: Idle", style="Action.TLabel")
self.status_label.pack(side=tk.RIGHT, padx=5) # This should be inside the button_frame
self.add_channel() # Add the first channel by default
self._validate_frequency_range() # Initial validation check
self.update_command_preview() # Initial preview
self.after(100, self.process_log_queue) # Start polling the log queue
# Add a handler to stop processes on window close
self.protocol("WM_DELETE_WINDOW", self.on_closing)
# Bind tab change event to hide/show the command/log pane
notebook.bind("<<NotebookTabChanged>>", self.on_tab_changed)
# Show the main window.
self.deiconify()
# Perform non-intrusive checks on startup.
self.after(100, self.update_hw_support_ui)
self.after(200, self.check_dependencies_on_startup_nonblocking)
def on_tab_changed(self, event):
"""Hides or shows the command/log pane based on the selected tab."""
notebook = event.widget
selected_tab_text = notebook.tab(notebook.select(), "text").strip() # .strip() to be safe
# Correctly check if the bottom pane is currently visible by comparing widget paths
is_visible = str(self.bottom_pane_container) in self.main_paned_window.panes()
if selected_tab_text == "Tools":
if is_visible:
self.main_paned_window.forget(self.bottom_pane_container)
else:
if not is_visible:
self.main_paned_window.add(self.bottom_pane_container, weight=1)
def _initialize_settings_path(self):
"""
Determines the path for the settings file.
1. Checks for a .path_config file in the app directory.
2. If it exists, uses the path from that file.
3. If not, defaults to .hackdvb_gui_settings.json in the app directory.
Finally, it loads the settings.
"""
# Determine the base path for resources, works for dev and for PyInstaller
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# Running in a PyInstaller bundle
self.app_dir = sys._MEIPASS
else:
# Running in a normal Python environment
self.app_dir = os.path.dirname(os.path.abspath(__file__))
self.path_config_file = os.path.join(self.app_dir, ".path_config")
if os.path.exists(self.path_config_file):
try:
with open(self.path_config_file, 'r') as f:
custom_path = f.read().strip()
if custom_path and os.path.isdir(os.path.dirname(custom_path)):
self.settings_file = custom_path
else: # The stored path is invalid, fall back to default
self.settings_file = os.path.join(self.app_dir, ".hackdvb_gui_settings.json")
except Exception:
self.settings_file = os.path.join(self.app_dir, ".hackdvb_gui_settings.json")
else:
self.settings_file = os.path.join(self.app_dir, ".hackdvb_gui_settings.json")
self._load_persistent_settings()
def _load_persistent_settings(self):
"""Loads executable paths from a persistent settings file in the user's home directory."""
if os.path.exists(self.settings_file):
try:
with open(self.settings_file, 'r') as f:
settings = json.load(f)
paths = settings.get("paths", {})
self.ffmpeg_path.set(paths.get("ffmpeg", self.ffmpeg_path.get()))
self.tsp_path.set(paths.get("tsp", self.tsp_path.get()))
self.tdt_path.set(paths.get("tdt", self.tdt_path.get()))
self.analysis_file_path.set(paths.get("analysis_file", self.analysis_file_path.get()))
except (json.JSONDecodeError, IOError) as e:
# Log to console, but don't bother the user with a popup on startup
print(f"Warning: Could not load persistent settings from {self.settings_file}: {e}")
def _save_persistent_settings(self):
"""Saves the current executable paths to the persistent settings file."""
settings = {
"paths": {
"ffmpeg": self.ffmpeg_path.get(),
"tsp": self.tsp_path.get(),
"tdt": self.tdt_path.get(),
"analysis_file": self.analysis_file_path.get()
}
}
with open(self.settings_file, 'w') as f:
json.dump(settings, f, indent=4)
def _on_mousewheel(self, event):
# Determine which canvas is under the mouse
try:
widget = self.winfo_containing(event.x_root, event.y_root)
except KeyError:
# This can happen if the mouse is over a combobox's dropdown list ('popdown')
return
if widget is None: return
# Check if the mouse is over the service canvas or one of its children
if str(widget).startswith(str(self.service_canvas)):
self.service_canvas.yview_scroll(int(-1*(event.delta/120)), "units")
elif str(widget).startswith(str(self.inputs_canvas)):
self.inputs_canvas.yview_scroll(int(-1*(event.delta/120)), "units")
def _validate_numeric_input(self, new_value):
"""Validates if the new_value is an integer or an empty string."""
if new_value == "" or new_value.isdigit():
return True
return False
def _validate_hex_input(self, new_value):
"""Validates if the new_value is a hexadecimal string (with or without 0x prefix) or an empty string."""
if new_value == "":
return True
# Regex to match optional "0x" prefix followed by one or more hex digits
# or just one or more hex digits.
if re.fullmatch(r"(0x)?[0-9a-fA-F]*", new_value):
return True
return False
def _validate_frequency_range(self, *args):
"""Validates that the satellite frequency is in the correct range for the LNB."""
is_valid = True
warning_message = ""
try:
lo_freq = int(self.lnb_lo_freq.get())
sat_freq_str = self.dek_freq.get()
if not sat_freq_str: # Don't validate if empty
is_valid = True
else:
sat_freq = int(sat_freq_str)
if lo_freq == 9750 and not (10700 <= sat_freq <= 11700):
is_valid = False
warning_message = "Range: 10700-11700 MHz"
elif lo_freq == 10600 and not (11700 <= sat_freq <= 12750):
is_valid = False
warning_message = "Range: 11700-12750 MHz"
except (ValueError, TclError):
is_valid = False # Invalid number format
warning_message = "Invalid number"
self.freq_warning_label.config(text=warning_message)
if is_valid:
self.dek_freq_entry.config(style="TEntry") # Reset to default style
# Only re-enable the start button if no process is currently running.
if self.process is None:
self.start_button.config(state=tk.NORMAL)
else:
self.dek_freq_entry.config(style="Error.TEntry") # Apply error style
self.start_button.config(state=tk.DISABLED)
def _is_executable(self, path):
"""Checks if a given path points to an executable file."""
if not path:
return False
# On Windows, os.access(path, os.X_OK) might not be sufficient or accurate.
# It's generally enough to check if it's a file and exists.
# The actual execution will fail if it's not a valid program.
if os.name == 'nt':
return os.path.isfile(path) and os.path.exists(path)
else:
return os.path.isfile(path) and os.access(path, os.X_OK)
def _check_and_update_executable_path(self, path_var, name, check_app_dir=False):
"""
Checks if the executable specified by path_var is valid.
If it's a simple command name, it tries to find it in PATH and updates path_var.
If check_app_dir is True, it also checks the application directory.
Returns True if a valid executable path is confirmed, False otherwise.
"""
current_path = path_var.get()
# 1. Check if the current path is an absolute path and is executable.
# This is the most reliable check and should be first.
if self._is_executable(current_path):
return True
# 2. If it's not a direct path, treat it as a command name and search for it in the system PATH.
# This covers both initial startup (e.g., "ffmpeg") and cases where a user might have
# manually entered a command name.
found_in_path = shutil.which(current_path)
if found_in_path:
path_var.set(found_in_path) # Update StringVar with full path
return True
# 3. If still not found, and check_app_dir is requested, check the app directory
if check_app_dir:
app_dir_path = os.path.join(self.app_dir, os.path.basename(current_path))
if self._is_executable(app_dir_path):
path_var.set(app_dir_path) # Update StringVar with full path
return True
return False
def create_section_header(self, parent, text):
row = parent.grid_size()[1]
header_frame = ttk.Frame(parent, padding=0)
header_frame.grid(row=0, column=0, columnspan=3, sticky="ew", pady=(0, 2))
label = ttk.Label(header_frame, text=text.upper(), style="Header.TLabel")
label.pack(side=tk.LEFT)
return header_frame
def _create_tab(self, notebook, text):
"""Creates a tab in the notebook."""
tab_frame = ttk.Frame(notebook, padding=(10, 15))
notebook.add(tab_frame, text=text)
return tab_frame
def create_file_input_widgets(self, parent, label_text, row, filetypes=None):
label = ttk.Label(parent, text=label_text)
label.grid(row=row, column=0, sticky="w")
entry_var = tk.StringVar()
entry = ttk.Entry(parent, textvariable=entry_var)
# The tooltip for the entry itself is usually set after this function is called.
TextContextMenu(entry)
entry.grid(row=row, column=1, sticky="ew")
TextContextMenu(entry)
button = ttk.Button(parent, text="Browse...", command=lambda: self.browse_file(entry_var, filetypes=filetypes))
button.grid(row=row, column=2, sticky="w", padx=(5, 0))
return label, entry, button, entry_var
def create_file_input(self, parent, label_text, row):
_, _, _, entry_var = self.create_file_input_widgets(parent, label_text, row)
return entry_var
def create_text_input_widgets(self, parent, label_text, row, default_value="", validation_type=None, columnspan=1, grid_column_offset=0):
label = ttk.Label(parent, text=label_text)
label.grid(row=row, column=0 + grid_column_offset, sticky="w")
entry_var = tk.StringVar(value=default_value)
if validation_type == "numeric":
entry = ttk.Entry(parent, textvariable=entry_var, validate="key", validatecommand=(self.numeric_validate_cmd, '%P'))
elif validation_type == "hex":
entry = ttk.Entry(parent, textvariable=entry_var, validate="key", validatecommand=(self.hex_validate_cmd, '%P'))
else:
entry = ttk.Entry(parent, textvariable=entry_var)
entry.grid(row=row, column=1 + grid_column_offset, columnspan=columnspan, sticky="ew")
TextContextMenu(entry)
return label, entry, entry_var
def create_text_input(self, parent, label_text, row, default_value="", validation_type=None, columnspan=1, grid_column_offset=0):
_, _, entry_var = self.create_text_input_widgets(parent, label_text, row, default_value, validation_type, columnspan, grid_column_offset)
return entry_var
def create_combobox_input(self, parent, label_text, row, default_value, options, grid_column_offset=0):
_, _, entry_var = self.create_combobox_input_widgets(parent, label_text, row, default_value, options, grid_column_offset)
return entry_var
def create_combobox_input_widgets(self, parent, label_text, row, default_value, options, grid_column_offset=0):
label = ttk.Label(parent, text=label_text)
label.grid(row=row, column=0 + grid_column_offset, sticky="w", padx=(0, 10))
entry_var = tk.StringVar(value=default_value)
combobox = ttk.Combobox(parent, textvariable=entry_var, values=options, state="readonly")
combobox.grid(row=row, column=1, columnspan=2, sticky="ew")