-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickFFSync.py
More file actions
7206 lines (6255 loc) · 265 KB
/
QuickFFSync.py
File metadata and controls
7206 lines (6255 loc) · 265 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
# IMPORTS
# Standard library
import ctypes.wintypes
import os
import subprocess
import sys
import tempfile
import tkinter as tk
from collections import OrderedDict
from datetime import datetime
from io import BytesIO
from json import dump, load
from re import sub, search
from shlex import split
from threading import Event, Thread, Timer
from tkinter import filedialog, messagebox, simpledialog
from winsound import MB_ICONASTERISK, MessageBeep
# Third-party
import customtkinter as ctk
from CTkToolTip import CTkToolTip
from PIL import Image
# Win32 constants
GWL_WNDPROC = -4
WM_DROPFILES = 0x0233
CF_UNICODETEXT = 13
GMEM_MOVEABLE = 0x0002
# Tray icon Win32 constants
WM_USER_TRAY = 0x8000
NIF_MESSAGE = 0x01
NIF_ICON = 0x02
NIF_TIP = 0x04
NIM_ADD = 0x00
NIM_DELETE = 0x02
MF_STRING = 0x00
MF_SEPARATOR = 0x800
TPM_RIGHTBUTTON = 0x02
TPM_RETURNCMD = 0x0100
IDM_STOP_RECORDING = 1001
# Process snapshot constants for killing only our ffmpeg.exe
TH32CS_SNAPPROCESS = 0x00000002
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
PROCESS_TERMINATE = 0x0001
class PROCESSENTRY32W(ctypes.Structure):
_fields_ = [
("dwSize", ctypes.wintypes.DWORD),
("cntUsage", ctypes.wintypes.DWORD),
("th32ProcessID", ctypes.wintypes.DWORD),
("th32DefaultHeapID", ctypes.c_size_t),
("th32ModuleID", ctypes.wintypes.DWORD),
("cntThreads", ctypes.wintypes.DWORD),
("th32ParentProcessID", ctypes.wintypes.DWORD),
("pcPriClassBase", ctypes.c_long),
("dwFlags", ctypes.wintypes.DWORD),
("szExeFile", ctypes.c_wchar * 260),
]
# Hotkey Win32 constants
WM_HOTKEY = 0x0312
MOD_ALT = 0x0001
VK_F9 = 0x78
HOTKEY_ID = 1002
# Win32 callback type for window procedures
WNDPROC = ctypes.WINFUNCTYPE(
ctypes.c_long,
ctypes.wintypes.HWND,
ctypes.wintypes.UINT,
ctypes.wintypes.WPARAM,
ctypes.wintypes.LPARAM,
)
# Shell32 — Drag-and-Drop
_shell32 = ctypes.windll.shell32
_shell32.DragAcceptFiles.argtypes = [ctypes.wintypes.HWND, ctypes.wintypes.BOOL]
_shell32.DragAcceptFiles.restype = None
_shell32.DragFinish.argtypes = [ctypes.wintypes.HANDLE]
_shell32.DragFinish.restype = None
_shell32.DragQueryFileW.argtypes = [
ctypes.wintypes.HANDLE,
ctypes.wintypes.UINT,
ctypes.wintypes.LPWSTR,
ctypes.wintypes.UINT,
]
_shell32.DragQueryFileW.restype = ctypes.wintypes.UINT
# User32 — Window Proc & Clipboard
_user32 = ctypes.windll.user32
_user32.SetWindowLongPtrW.argtypes = [
ctypes.wintypes.HWND,
ctypes.c_int,
ctypes.c_void_p,
]
_user32.SetWindowLongPtrW.restype = ctypes.c_void_p
_user32.CallWindowProcW.argtypes = [
ctypes.c_void_p,
ctypes.wintypes.HWND,
ctypes.wintypes.UINT,
ctypes.wintypes.WPARAM,
ctypes.wintypes.LPARAM,
]
_user32.CallWindowProcW.restype = ctypes.c_long
_user32.OpenClipboard.argtypes = [ctypes.wintypes.HWND]
_user32.OpenClipboard.restype = ctypes.wintypes.BOOL
_user32.CloseClipboard.argtypes = []
_user32.CloseClipboard.restype = ctypes.wintypes.BOOL
_user32.EmptyClipboard.argtypes = []
_user32.EmptyClipboard.restype = ctypes.wintypes.BOOL
_user32.SetClipboardData.argtypes = [ctypes.wintypes.UINT, ctypes.wintypes.HANDLE]
_user32.SetClipboardData.restype = ctypes.wintypes.HANDLE
# Kernel32 — GlobalAlloc for clipboard
_kernel32 = ctypes.windll.kernel32
_kernel32.GlobalAlloc.argtypes = [ctypes.wintypes.UINT, ctypes.c_size_t]
_kernel32.GlobalAlloc.restype = ctypes.wintypes.HANDLE
_kernel32.GlobalLock.argtypes = [ctypes.wintypes.HANDLE]
_kernel32.GlobalLock.restype = ctypes.c_void_p
_kernel32.GlobalUnlock.argtypes = [ctypes.wintypes.HANDLE]
_kernel32.GlobalUnlock.restype = ctypes.wintypes.BOOL
_kernel32.GlobalFree.argtypes = [ctypes.wintypes.HANDLE]
_kernel32.GlobalFree.restype = ctypes.wintypes.HANDLE
def _set_clipboard_text(text: str) -> bool:
"""Copy Unicode text to the Windows clipboard using ctypes."""
encoded = text.encode("utf-16-le") + b"\x00\x00"
# Allocate global movable memory
h_mem = _kernel32.GlobalAlloc(GMEM_MOVEABLE, len(encoded))
if not h_mem:
return False
ptr = _kernel32.GlobalLock(h_mem)
if not ptr:
_kernel32.GlobalFree(h_mem)
return False
try:
ctypes.memmove(ptr, encoded, len(encoded))
finally:
_kernel32.GlobalUnlock(h_mem)
if not _user32.OpenClipboard(None):
_kernel32.GlobalFree(h_mem)
return False
try:
_user32.EmptyClipboard()
# If SetClipboardData succeeds, ownership of h_mem
# transfers to the system. We must NOT free it.
if not _user32.SetClipboardData(CF_UNICODETEXT, h_mem):
_kernel32.GlobalFree(h_mem)
return False
finally:
_user32.CloseClipboard()
return True
def get_icon_path():
if getattr(sys, "frozen", False):
base_path = os.path.dirname(sys.executable)
else:
base_path = os.path.dirname(__file__)
return os.path.join(base_path, "qff.ico")
def get_real_dpi():
"""Get the actual DPI taking system scaling into account"""
user32 = ctypes.windll.user32
shcore = ctypes.windll.shcore
try:
awareness = ctypes.c_int(2)
user32.SetProcessDpiAwarenessContext(awareness)
except Exception:
try:
shcore.SetProcessDpiAwareness(2)
except Exception:
user32.SetProcessDPIAware()
try:
hwnd = user32.GetForegroundWindow()
dpi = user32.GetDpiForWindow(hwnd)
if dpi == 0:
dpi = user32.GetDpiForSystem()
except Exception:
gdi32 = ctypes.windll.gdi32
hdc = user32.GetDC(0)
dpi = gdi32.GetDeviceCaps(hdc, 88)
user32.ReleaseDC(0, hdc)
return dpi
def is_us_english_layout():
"""Return True if the current keyboard layout is US English (0x0409)."""
try:
user32 = ctypes.windll.user32
# Get keyboard layout for the current thread
hkl = user32.GetKeyboardLayout(0)
# Language ID is the low 16 bits
lang_id = hkl & 0xFFFF
return lang_id == 0x0409 # 0x0409 = US English
except Exception:
return False # On error, assume not English (or fall back to default)
# UI THEME
# ctk.ThemeManager.theme["CTkFont"].update({"family": "Segoe UI", "size": 12})
# ctk.set_window_scaling(2.0)
# ctk.set_widget_scaling(2.0)
ctk.set_appearance_mode("dark")
PRIMARY_BG = "#151f43"
SECONDARY_BG = "#202e5d"
ACCENT_BLUE = "#0d9fea"
HOVER_BLUE = "#096cad"
ACCENT_DEEPBLUE = "#070d2d"
HOVER_DEEPBLUE = "#172e9f"
ACCENT_RED = "#FF5555"
HOVER_RED = "#d83636"
TEXT_COLOR_W = "#FFFFFF"
TEXT_COLOR_B = "#000000"
PLACEHOLDER_COLOR = "#A0A0A0"
# Supported video extensions (used for drag-and-drop and file dialog filters)
VIDEO_EXTENSIONS = (
".mp4",
".mkv",
".avi",
".mov",
".flv",
".wmv",
".webm",
".ts",
".m4v",
".mpg",
".mpeg",
".m2ts",
".mts",
".3gp",
".ogv",
".ogm",
".vob",
".f4v",
".asf",
".divx",
)
VIDEO_EXTENSIONS_FILTER = (
"Video Files",
"*.mp4 *.mkv *.avi *.mov *.flv *.wmv *.webm *.ts *.m4v"
" *.mpg *.mpeg *.m2ts *.mts *.3gp *.ogv *.ogm *.vob *.f4v *.asf *.divx",
)
class TextCheckbox(ctk.CTkFrame):
def __init__(self, master=None, text="", variable=None, command=None, **kwargs):
super().__init__(master, **kwargs)
self.configure(fg_color="transparent")
self.var = variable if variable is not None else ctk.BooleanVar()
self.command = command
self.unchecked_char = "▼"
self.checked_char = "▲"
# Main container for checkbox and text
self.container = ctk.CTkFrame(self, fg_color="transparent")
self.container.pack(anchor="w", fill="x")
# Checkbox as a label
self.checkbox_label = ctk.CTkLabel(
self.container,
text=self.unchecked_char,
width=24,
height=24,
corner_radius=6,
fg_color=ACCENT_BLUE,
text_color=TEXT_COLOR_W,
cursor="hand2",
)
self.checkbox_label.pack(side="left", padx=(0, 8))
# Text label
self.text_label = ctk.CTkLabel(
self.container,
text=text,
cursor="hand2",
)
self.text_label.pack(side="left", fill="x", expand=True)
# Bind click events to both labels
self.checkbox_label.bind("<Button-1>", self.toggle)
self.text_label.bind("<Button-1>", self.toggle)
# Add hover effects
self.checkbox_label.bind("<Enter>", self._on_hover)
self.checkbox_label.bind("<Leave>", self._on_leave)
self.text_label.bind("<Enter>", self._on_hover)
self.text_label.bind("<Leave>", self._on_leave)
self.var.trace_add("write", self.update_display)
def _on_hover(self, event):
self.checkbox_label.configure(fg_color=HOVER_BLUE)
def _on_leave(self, event):
self.checkbox_label.configure(fg_color=ACCENT_BLUE)
def toggle(self, event=None):
self.var.set(not self.var.get())
if self.command:
self.command()
def update_display(self, *args):
if self.var.get():
self.checkbox_label.configure(text=self.checked_char)
else:
self.checkbox_label.configure(text=self.unchecked_char)
class CTkContextMenu(ctk.CTkToplevel):
def __init__(self, master, target_widget, app_instance, **kwargs):
super().__init__(master, **kwargs)
self.target_widget = target_widget
self.app_instance = app_instance
self.withdraw() # Hide right away while configuring
# Hide from taskbar securely on Windows
self.transient(master)
self.overrideredirect(True)
if sys.platform == "win32":
self.attributes("-toolwindow", True)
self.attributes("-topmost", True)
# Create a true transparent color for the surrounding corners
transparent_color = "#000001" if sys.platform == "win32" else PRIMARY_BG
self.configure(fg_color=transparent_color)
# Apply transparency to the corners (Win32)
if sys.platform == "win32":
self.attributes("-transparentcolor", transparent_color)
# Frame to hold buttons, with corner_radius=10
self.frame = ctk.CTkFrame(
self,
fg_color=ACCENT_DEEPBLUE,
bg_color=transparent_color,
corner_radius=10,
border_width=0,
)
self.frame.pack(fill="both", expand=True)
self._add_button("Cut", self._cut)
self._add_button("Copy", self._copy)
self._add_button("Paste", self._paste)
self._add_button("Delete", self._delete)
self._add_button("Select All", self._select_all)
self.bind("<FocusOut>", self._on_focus_out)
def _on_focus_out(self, event=None):
self.withdraw()
def _add_button(self, text, command):
btn = ctk.CTkButton(
self.frame,
text=text,
fg_color="transparent",
hover_color=HOVER_DEEPBLUE,
text_color=TEXT_COLOR_W,
anchor="w",
corner_radius=6,
height=28,
width=120,
command=command,
)
# Extra padding to ensure buttons don't clip the corners
btn.pack(fill="x", padx=3, pady=3)
def _execute_action(self, action_func):
if not self.target_widget or not self.target_widget.winfo_exists():
self.withdraw()
return
self.target_widget.focus_set()
# Delay the action to allow FocusIn events to clear the placeholder text
self.target_widget.after(50, action_func)
self.withdraw()
def _select_all(self):
self._execute_action(self.app_instance._select_all)
def _copy(self):
self._execute_action(self.app_instance._copy_text)
def _cut(self):
self._execute_action(self.app_instance._cut_text)
def _paste(self):
self._execute_action(self.app_instance._paste_text)
def _delete(self):
self._execute_action(self.app_instance._delete_text)
def destroy(self):
self.target_widget = None
self.app_instance = None
self.frame = None
super().destroy()
# DRAG N DROP FILES
class DropTarget:
def __init__(self, hwnd, callback):
self.hwnd = hwnd
self.callback = callback
_shell32.DragAcceptFiles(self.hwnd, True)
# Wrap _wnd_proc in WNDPROC and keep a reference to prevent GC
self._wndproc_func = WNDPROC(self._wnd_proc)
self.old_wnd_proc = _user32.SetWindowLongPtrW(
self.hwnd,
GWL_WNDPROC,
ctypes.cast(self._wndproc_func, ctypes.c_void_p).value,
)
self._self_ref = self # important
def _wnd_proc(self, hwnd, msg, wparam, lparam):
if msg == WM_DROPFILES:
try:
hdrop = wparam
# Get number of files dropped
file_count = _shell32.DragQueryFileW(hdrop, 0xFFFFFFFF, None, 0)
for i in range(file_count):
# Get required length
length = _shell32.DragQueryFileW(hdrop, i, None, 0)
# Allocate buffer dynamically
buffer = ctypes.create_unicode_buffer(length + 1)
_shell32.DragQueryFileW(hdrop, i, buffer, length + 1)
file_path = buffer.value
if self.callback:
self.callback(file_path)
_shell32.DragFinish(hdrop)
except Exception as e:
print(f"Error handling drop: {e}")
return 0
return _user32.CallWindowProcW(self.old_wnd_proc, hwnd, msg, wparam, lparam)
def cleanup(self):
"""Clean up the drop target - call this before destroying the window"""
try:
if hasattr(self, "old_wnd_proc") and self.old_wnd_proc:
_user32.SetWindowLongPtrW(self.hwnd, GWL_WNDPROC, self.old_wnd_proc)
except Exception:
# Silently ignore cleanup errors — not critical
pass
class TrayIcon:
"""System tray icon with a right-click context menu for screen recording control."""
class _NOTIFYICONDATA(ctypes.Structure):
_fields_ = [
("cbSize", ctypes.wintypes.DWORD),
("hWnd", ctypes.wintypes.HWND),
("uID", ctypes.wintypes.UINT),
("uFlags", ctypes.wintypes.UINT),
("uCallbackMessage", ctypes.wintypes.UINT),
("hIcon", ctypes.wintypes.HANDLE),
("szTip", ctypes.c_wchar * 128),
]
def __init__(self, hwnd, icon_path, on_stop_callback):
self.hwnd = hwnd
self.on_stop = on_stop_callback
self._active = False
_user32.LoadImageW.restype = ctypes.wintypes.HANDLE
_user32.LoadImageW.argtypes = [
ctypes.wintypes.HINSTANCE,
ctypes.wintypes.LPCWSTR,
ctypes.wintypes.UINT,
ctypes.c_int,
ctypes.c_int,
ctypes.wintypes.UINT,
]
LR_LOADFROMFILE = 0x0010
IMAGE_ICON = 1
self._hicon = _user32.LoadImageW(
None, icon_path, IMAGE_ICON, 16, 16, LR_LOADFROMFILE
)
if not self._hicon:
self._hicon = _user32.LoadIconW(None, ctypes.wintypes.LPCWSTR(32512))
self._prev_wndproc = None
self._wndproc_ref = WNDPROC(self._wnd_proc)
self._prev_wndproc = _user32.SetWindowLongPtrW(
self.hwnd,
GWL_WNDPROC,
ctypes.cast(self._wndproc_ref, ctypes.c_void_p).value,
)
# Register global hotkey (Alt + F9)
_user32.RegisterHotKey(self.hwnd, HOTKEY_ID, MOD_ALT, VK_F9)
def _nid(self):
nid = self._NOTIFYICONDATA()
nid.cbSize = ctypes.sizeof(self._NOTIFYICONDATA)
nid.hWnd = self.hwnd
nid.uID = 1
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP
nid.uCallbackMessage = WM_USER_TRAY
nid.hIcon = self._hicon
nid.szTip = "QuickFFSync 1.2.2"
return nid
def show(self):
if self._active:
return
nid = self._nid()
_shell32.Shell_NotifyIconW(NIM_ADD, ctypes.byref(nid))
self._active = True
def hide(self):
if not self._active:
return
nid = self._nid()
_shell32.Shell_NotifyIconW(NIM_DELETE, ctypes.byref(nid))
self._active = False
def _show_context_menu(self):
hmenu = _user32.CreatePopupMenu()
_user32.AppendMenuW(
hmenu, MF_STRING, IDM_STOP_RECORDING, "Stop Recording (Alt + F9)"
)
_user32.SetForegroundWindow(self.hwnd)
pt = ctypes.wintypes.POINT()
_user32.GetCursorPos(ctypes.byref(pt))
cmd = _user32.TrackPopupMenu(
hmenu, TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, self.hwnd, None
)
_user32.DestroyMenu(hmenu)
if cmd == IDM_STOP_RECORDING:
self.on_stop()
def _wnd_proc(self, hwnd, msg, wparam, lparam):
if msg == WM_HOTKEY and wparam == HOTKEY_ID:
# Safely escape the CTypes Windows hook before interacting with Tkinter
# by spawning a temporary thread to queue the UI event.
from threading import Thread
Thread(target=self.on_stop, daemon=True).start()
return 0
if msg == WM_USER_TRAY:
if lparam in (0x0205, 0x007B):
self._show_context_menu()
return 0
if self._prev_wndproc:
return _user32.CallWindowProcW(
self._prev_wndproc, hwnd, msg, wparam, lparam
)
return _user32.DefWindowProcW(hwnd, msg, wparam, lparam)
def destroy(self):
_user32.UnregisterHotKey(self.hwnd, HOTKEY_ID)
self.hide()
if self._prev_wndproc:
_user32.SetWindowLongPtrW(self.hwnd, GWL_WNDPROC, self._prev_wndproc)
self._prev_wndproc = None
class BatchConverterWindow:
def __init__(self, master, main_app):
self.master = master
self.main_app = main_app
self.is_converting = False
self.current_file_index = 0
self.files = main_app.batch_files.copy()
self._saved_input_file = ""
self._saved_output_file = ""
# Create window
self.window = ctk.CTkToplevel(master)
self.window.title("Batch Converter")
self.window.geometry("600x400")
self.window.minsize(600, 400)
self.window.configure(fg_color=SECONDARY_BG)
# Center window
master.update_idletasks()
master_x = master.winfo_x()
master_y = master.winfo_y()
master_width = master.winfo_width()
master_height = master.winfo_height()
window_width = 600
window_height = 400
x = master_x + (master_width - window_width) // 2
y = master_y + (master_height - window_height) // 2
self.window.geometry(f"{window_width}x{window_height}+{x}+{y}")
self.window.after(100, self.window.focus_force)
# Set icon
if os.path.exists(icon_path):
self.window.after(201, lambda: self.window.iconbitmap(icon_path))
# Create UI
self._create_widgets()
self._setup_drag_drop()
self._update_files_display()
# Update main window convert button
self._update_main_convert_button()
self.window.protocol("WM_DELETE_WINDOW", self._on_close)
def _create_widgets(self):
# Main container
main_frame = ctk.CTkFrame(self.window, fg_color=SECONDARY_BG)
main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Files list frame
list_frame = ctk.CTkFrame(main_frame, fg_color=SECONDARY_BG)
list_frame.pack(fill="both", expand=True, pady=(0, 10))
# Scrollable frame for files
self.scrollable_frame = ctk.CTkScrollableFrame(
list_frame,
fg_color=PRIMARY_BG,
scrollbar_button_color=HOVER_BLUE,
scrollbar_button_hover_color=ACCENT_BLUE,
)
self.scrollable_frame.pack(
fill="both",
expand=True,
padx=5,
pady=5,
)
# Buttons frame
buttons_frame = ctk.CTkFrame(main_frame, fg_color=SECONDARY_BG)
buttons_frame.pack(fill="x", pady=5)
# Buttons
self.add_btn = ctk.CTkButton(
buttons_frame,
text="Add Files",
command=self._add_files,
fg_color=ACCENT_BLUE,
hover_color=HOVER_BLUE,
text_color=TEXT_COLOR_B,
)
self.add_btn.pack(side="left", expand=True, fill="x", padx=(0, 5))
self.close_btn = ctk.CTkButton(
buttons_frame,
text="Close",
command=self._on_close,
fg_color=ACCENT_DEEPBLUE,
hover_color=HOVER_DEEPBLUE,
text_color=TEXT_COLOR_W,
)
self.close_btn.pack(side="left", expand=True, fill="x", padx=(0, 5))
self.remove_all_btn = ctk.CTkButton(
buttons_frame,
text="Remove All",
command=self._remove_all_files,
fg_color=ACCENT_RED,
hover_color=HOVER_RED,
text_color=TEXT_COLOR_B,
)
self.remove_all_btn.pack(side="left", expand=True, fill="x")
def _setup_drag_drop(self):
# Enable drag and drop for the window
self.drop_target = DropTarget(
self.window.winfo_id(), self._handle_dropped_files
)
def _handle_dropped_files(self, file_path):
"""Handle files dropped into the batch converter window"""
# Process in separate thread like main window
Thread(
target=self._process_dropped_file, args=(file_path,), daemon=True
).start()
def _process_dropped_file(self, file_path):
"""Process dropped file in separate thread"""
if file_path.lower().endswith(VIDEO_EXTENSIONS):
normalized_path = os.path.normpath(file_path)
# Update GUI from main thread
self.window.after(0, lambda: self._add_file_to_list(normalized_path))
else:
# Show warning in main thread
self.window.after(
0,
lambda: messagebox.showwarning(
"Unsupported File",
"Please drop a video file (.mp4, .mkv, .avi, etc.)",
),
)
def _add_files(self):
initial_dir = (
self.main_app.last_input_dir.get()
if self.main_app.last_input_dir.get()
else os.getcwd()
)
filenames = filedialog.askopenfilenames(
title="Select Video Files",
initialdir=initial_dir,
filetypes=(
VIDEO_EXTENSIONS_FILTER,
("All Files", "*.*"),
),
)
self.window.lift()
self.window.focus_force()
if not filenames:
return
for filename in filenames:
normalized_path = os.path.normpath(filename)
self._add_file_to_list(normalized_path)
def _add_file_to_list(self, file_path):
# Check if file already exists in list
for existing_file in self.files:
if existing_file["path"] == file_path:
return
# Add to list
file_info = {
"path": file_path,
"status": "Ready", # Ready, Converting, Done, Failed
"widgets": None,
}
self.files.append(file_info)
self._update_files_display()
self._update_main_convert_button()
self.main_app.batch_files = self.files.copy()
self.window.lift()
# Remove from list
def _remove_file(self, index):
if 0 <= index < len(self.files):
self.files.pop(index)
self._update_files_display()
self._update_main_convert_button()
self.main_app.batch_files = self.files.copy()
def _remove_all_files(self):
if self.files:
self.files.clear()
self._update_files_display()
self._update_main_convert_button()
self.main_app.batch_files = self.files.copy()
# Clear current display
def _update_files_display(self):
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
# Recreate file entries
for i, file_info in enumerate(self.files):
self._create_file_entry(i, file_info)
def _create_file_entry(self, index, file_info):
file_frame = ctk.CTkFrame(self.scrollable_frame, fg_color=PRIMARY_BG)
file_frame.pack(fill="x", pady=2)
# Number
num_label = ctk.CTkLabel(file_frame, text=f"{index + 1}.", width=30)
num_label.pack(side="left", padx=(5, 0))
# Filename (truncated if too long)
filename = os.path.basename(file_info["path"])
if len(filename) > 40:
filename = filename[:37] + "..."
name_label = ctk.CTkLabel(file_frame, text=filename, width=300, anchor="w")
name_label.pack(side="left", padx=5, fill="x", expand=True)
# Status
status_label = ctk.CTkLabel(file_frame, text=file_info["status"], width=80)
status_label.pack(side="left", padx=5)
# Remove button
remove_btn = ctk.CTkButton(
file_frame,
text="×",
width=20,
height=20,
command=lambda idx=index: self._remove_file(idx),
fg_color=ACCENT_RED,
hover_color=HOVER_RED,
text_color=TEXT_COLOR_B,
# font=("", 24, "bold"),
)
remove_btn.pack(side="right", padx=(0, 5))
# Store widgets for later updates
file_info["widgets"] = {"status_label": status_label}
def _update_file_status(self, index, status):
if not self.window.winfo_exists():
return
if 0 <= index < len(self.files):
self.files[index]["status"] = status
if self.files[index]["widgets"]:
try:
self.files[index]["widgets"]["status_label"].configure(text=status)
except Exception:
pass
def _update_main_convert_button(self):
if hasattr(self.main_app, "convert_button"):
if self.is_converting:
self.main_app.convert_button.configure(
text="Cancel", fg_color=ACCENT_RED, hover_color=HOVER_DEEPBLUE
)
elif self.files:
self.main_app.convert_button.configure(
text="Batch Convert", fg_color=ACCENT_BLUE, hover_color=HOVER_BLUE
)
else:
self.main_app.convert_button.configure(
text="Convert", fg_color=ACCENT_BLUE, hover_color=HOVER_BLUE
)
def start_batch_conversion(self):
if not self.files or self.is_converting:
return
self.is_converting = True
self.current_file_index = 0
# Save original input/output so we can restore after batch
self._saved_input_file = self.main_app.input_file.get()
self._saved_output_file = self.main_app.output_file.get()
self.main_app.progress_frame.grid()
self.main_app.progress_value.set(0.0)
self.main_app.progress_label.configure(text="0%")
self.main_app.status_text.set("Conversion in progress...")
self.main_app.convert_button.configure(
text="Cancel", fg_color=ACCENT_RED, hover_color=HOVER_RED
)
self._convert_next_file()
def _convert_next_file(self):
if not self.window.winfo_exists():
self.is_converting = False
self._restore_input_output()
return
if self.current_file_index >= len(self.files) or not self.is_converting:
self.is_converting = False
self.main_app.progress_frame.grid_remove()
self.main_app.ffmpeg_output.set("")
self.main_app.status_text.set("Batch conversion completed!")
self._update_main_convert_button()
self._restore_input_output()
return
current_file = self.files[self.current_file_index]
self._update_file_status(self.current_file_index, "Converting")
# Set up conversion for current file
input_path = current_file["path"]
# Generate output filename based on main app settings
base_name = os.path.splitext(os.path.basename(input_path))[0]
codec_suffix = (
"_hevc"
if self.main_app.video_codec.get() == "hevc"
else "_h264"
if self.main_app.video_codec.get() == "h264"
else "_av1"
if self.main_app.video_codec.get() == "av1"
else "_vp9"
)
# Get output directory from main app or use input file directory
if self.main_app.last_output_dir.get() and os.path.exists(
self.main_app.last_output_dir.get()
):
output_dir = self.main_app.last_output_dir.get()
else:
output_dir = os.path.dirname(input_path)
# Use the same extension logic as main app
current_output = self.main_app.output_file.get()
if current_output:
original_extension = os.path.splitext(current_output)[1]
if not original_extension:
original_extension = ".mp4"
else:
original_extension = ".mp4"
output_path = os.path.normpath(
os.path.join(
output_dir, f"{base_name}{codec_suffix}_custom{original_extension}"
)
)
try:
# Set current file for conversion
self.main_app.input_file.set(input_path)
self.main_app.output_file.set(output_path)
self.main_app._get_video_duration()
# Build and execute command
command = self.main_app._build_ffmpeg_command()
# Run conversion in thread
conversion_thread = Thread(
target=self._run_single_conversion,
args=(command, self.current_file_index),
daemon=True,
)
conversion_thread.start()
except Exception as e:
self._update_file_status(self.current_file_index, f"Failed: {str(e)}")
self.current_file_index += 1
self.master.after(100, self._convert_next_file)
def _run_single_conversion(self, command, file_index):
startupinfo = None
creationflags = 0
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
creationflags = subprocess.CREATE_NO_WINDOW
try:
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
startupinfo=startupinfo,
creationflags=creationflags,
encoding="utf-8",
errors="replace",
)
for line in process.stdout:
if not self.is_converting:
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
break
if line:
self.master.after(
0,
lambda line_text=line: self.main_app.ffmpeg_output.set(
line_text
),
)
self.master.after(
0,
lambda line_text=line: self.main_app._update_progress(
line_text