Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1955 lines (1726 loc) · 83.8 KB
/
Copy pathmain.py
File metadata and controls
1955 lines (1726 loc) · 83.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
main.py
-------
LoopClip - main application window.
Queue-based dark-themed UI (restyled to match the Video Downloader Pro
look: charcoal background, teal accent buttons, header + subtitle, and a
two-column options layout with a segmented quality selector):
1. Paste a YouTube URL (auto-filled from clipboard if one is copied).
2. Choose quality / audio / trim / output settings.
3. Click "Add to Queue" as many times as you like for different videos.
4. Click "Start Queue" - videos download and process one at a time.
5. "Cancel" stops the current video immediately and halts the queue.
"""
import os
import platform
import tempfile
import threading
import time
import webbrowser
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, messagebox
import customtkinter as ctk
# Must run before any import that pulls in yt_dlp (queue_manager ->
# downloader -> yt_dlp) - if a previously-downloaded yt-dlp update was
# applied on a prior run, this makes `import yt_dlp` resolve to it
# instead of whatever's frozen into the .exe / pip-installed. A no-op if
# no update has ever been applied.
import ytdlp_updater
ytdlp_updater.activate_pending_override()
import processor
import settings as settings_module
from queue_manager import QueueItem, QueueManager, QueueState
from tool_check import check_ffmpeg, check_nvenc, get_ffmpeg_version, missing_tools_message
from version import __version__
try:
import pyperclip
HAS_CLIPBOARD = True
except ImportError:
HAS_CLIPBOARD = False
# Importing downloader only for URL validation - queue_manager owns the
# actual download/process calls so UI code never talks to yt-dlp/FFmpeg
# directly.
import downloader
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("green")
# Same palette as Video Downloader Pro: lifted charcoal background with a
# teal accent, kept distinct from the "Cancel" and per-item state colors
# used in the queue list.
COLOR_BG = "#1c1c1e"
COLOR_PANEL = "#26262a"
COLOR_ACCENT = "#0f6e56"
COLOR_ACCENT_HOVER = "#0c5744"
COLOR_CANCEL = "#8B2C2C"
COLOR_CANCEL_HOVER = "#6E2323"
TEMP_ROOT = Path(tempfile.gettempdir()) / "LoopClip" / "Temp"
CLIPBOARD_POLL_MS = 150 # near-instant clipboard pickup
def _safe_float(text: str, default: float) -> float:
"""
Parses `text` as a float, falling back to `default` instead of raising
if it isn't a valid number.
Used for fields whose value only matters when a related option is
enabled (e.g. the similarity box when auto-loop detection is off) -
_validate_loop_settings() already blocks "Add to Queue" with a clear
message when that field's value *does* matter and is invalid, but
when it doesn't matter, silently falling back here (rather than still
hard-parsing it) avoids the field crashing item creation over a value
the user isn't even using.
"""
try:
return float(text)
except (TypeError, ValueError):
return default
STATE_COLORS = {
QueueState.QUEUED: "#9AA0A6",
QueueState.DOWNLOADING: "#3B8EEA",
QueueState.ANALYZING: "#3BB8EA",
QueueState.TRIMMING: "#E8A33D",
QueueState.LOOPING: "#B47EE8",
QueueState.FINISHED: "#3FB950",
QueueState.ERROR: "#F85149",
QueueState.CANCELLED: "#8B8F98",
}
# LoopyCut-style method options for automatic loop detection.
LOOP_METHOD_LABELS = [
("combined", "Combined (recommended)"),
("ssim", "SSIM (structural)"),
("histogram", "Histogram (color)"),
("hash", "Hash (fastest)"),
]
DOWNSAMPLE_LABELS = [
("1", "Every frame"),
("2", "Every 2nd frame"),
("4", "Every 4th frame"),
("8", "Every 8th frame"),
]
AUDIO_BITRATE_LABELS = [
("original", "Original"),
("128", "128 kbps"),
("192", "192 kbps"),
("256", "256 kbps"),
("320", "320 kbps"),
]
VIDEO_BITRATE_LABELS = [
("8", "8 Mbps"),
("15", "15 Mbps"),
("25", "25 Mbps"),
("40", "40 Mbps"),
]
CROSSFADE_LABELS = [
("1", "1 sec"),
("2", "2 sec"),
("3", "3 sec"),
]
QUALITY_LABELS = {
"best": "Best Available",
"4k_hdr": "4K HDR Preferred",
"1080p": "1080p Compatible",
}
class _TimeEntry(ctk.CTkFrame):
"""
A compact HH:MM:SS input made of three linked digit boxes instead of a
single free-text field. This removes the most common source of the
"invalid start time / duration" error dialog - wrong separators,
missing leading zeros, stray spaces - since each box only ever accepts
digits, auto-advances to the next box once two digits are typed, and
self-corrects out-of-range values (minutes/seconds above 59) when you
click away. get()/set() still work with plain "HH:MM:SS" strings so
the rest of the app doesn't need to change.
"""
def __init__(self, master, initial: str = "00:00:00", on_change=None, **kwargs):
super().__init__(master, fg_color="transparent", **kwargs)
self._on_change = on_change
vcmd = (self.register(self._validate_digits), "%P")
box_kwargs = dict(
width=40, justify="center", fg_color=COLOR_PANEL,
validate="key", validatecommand=vcmd,
)
caption_kwargs = dict(font=ctk.CTkFont(size=9), text_color="gray55")
def _box_with_caption(caption_text: str) -> ctk.CTkEntry:
col = ctk.CTkFrame(self, fg_color="transparent")
col.pack(side="left")
box = ctk.CTkEntry(col, **box_kwargs)
box.pack()
ctk.CTkLabel(col, text=caption_text, **caption_kwargs).pack()
return box
self.hh = _box_with_caption("H")
ctk.CTkLabel(self, text=":", width=6).pack(side="left", pady=(0, 14))
self.mm = _box_with_caption("M")
ctk.CTkLabel(self, text=":", width=6).pack(side="left", pady=(0, 14))
self.ss = _box_with_caption("S")
self.set(initial)
def _changed(e=None):
if self._on_change is not None:
self._on_change()
self.hh.bind("<KeyRelease>", lambda e: (self._maybe_advance(self.hh, self.mm), _changed()))
self.mm.bind("<KeyRelease>", lambda e: (self._maybe_advance(self.mm, self.ss), _changed()))
self.ss.bind("<KeyRelease>", _changed)
self.hh.bind("<FocusOut>", lambda e: (self._pad(self.hh), _changed()))
self.mm.bind("<FocusOut>", lambda e: (self._clamp(self.mm), _changed()))
self.ss.bind("<FocusOut>", lambda e: (self._clamp(self.ss), _changed()))
@staticmethod
def _validate_digits(proposed: str) -> bool:
"""Tk 'validate=key' callback - only allow up to 2 digits per box,
nothing else (no letters, colons, symbols)."""
return proposed == "" or (proposed.isdigit() and len(proposed) <= 2)
@staticmethod
def _maybe_advance(box: ctk.CTkEntry, next_box: ctk.CTkEntry):
if len(box.get()) >= 2:
next_box.focus_set()
next_box.select_range(0, "end")
@staticmethod
def _pad(box: ctk.CTkEntry):
value = box.get().strip()
box.delete(0, "end")
box.insert(0, value.zfill(2) if value else "00")
@staticmethod
def _clamp(box: ctk.CTkEntry):
"""Minutes/seconds are capped at 59 rather than left invalid."""
value = box.get().strip()
num = max(0, min(59, int(value) if value.isdigit() else 0))
box.delete(0, "end")
box.insert(0, f"{num:02d}")
def get(self) -> str:
h = self.hh.get().strip()
m = self.mm.get().strip()
s = self.ss.get().strip()
h_val = int(h) if h.isdigit() else 0
m_val = max(0, min(59, int(m) if m.isdigit() else 0))
s_val = max(0, min(59, int(s) if s.isdigit() else 0))
return f"{h_val:02d}:{m_val:02d}:{s_val:02d}"
def set(self, value: str):
try:
h, m, s = value.strip().split(":")
except (ValueError, AttributeError):
h, m, s = "0", "0", "0"
for box, v in ((self.hh, h), (self.mm, m), (self.ss, s)):
v = v.strip() if v.strip().isdigit() else "0"
box.delete(0, "end")
box.insert(0, v.zfill(2))
def configure_state(self, state: str):
for box in (self.hh, self.mm, self.ss):
box.configure(state=state)
class _ToolTip:
"""
A small hover tooltip for any widget - shows `text` in a borderless
popup near the cursor after a short delay, and hides it again on
mouse-leave or click. CustomTkinter has no built-in tooltip widget,
so this is a minimal one built directly on Tk's <Enter>/<Leave>
events rather than adding a third-party dependency for something
this small.
The delay (400ms) exists so tooltips don't flash into view while the
cursor just passes over a widget on its way somewhere else - only
genuinely hovering (pausing) triggers it, matching how tooltips
behave in most desktop apps.
"""
DELAY_MS = 400
def __init__(self, widget, text: str):
self.widget = widget
self.text = text
self._after_id = None
self._tip_window = None
widget.bind("<Enter>", self._schedule, add="+")
widget.bind("<Leave>", self._hide, add="+")
widget.bind("<Button-1>", self._hide, add="+")
def _schedule(self, _event=None):
self._cancel_pending()
self._after_id = self.widget.after(self.DELAY_MS, self._show)
def _cancel_pending(self):
if self._after_id is not None:
try:
self.widget.after_cancel(self._after_id)
except Exception:
pass
self._after_id = None
def _show(self):
if self._tip_window is not None or not self.widget.winfo_exists():
return
x = self.widget.winfo_rootx() + 12
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 6
tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True) # no title bar/borders - just the tip
tw.wm_geometry(f"+{x}+{y}")
tw.configure(bg=COLOR_ACCENT)
try:
tw.attributes("-topmost", True)
except Exception:
pass
label = ctk.CTkLabel(
tw, text=self.text, font=ctk.CTkFont(size=11),
fg_color=COLOR_PANEL, text_color="white",
corner_radius=6, justify="left", wraplength=280,
padx=10, pady=6,
)
label.pack()
self._tip_window = tw
def _hide(self, _event=None):
self._cancel_pending()
if self._tip_window is not None:
try:
self._tip_window.destroy()
except Exception:
pass
self._tip_window = None
def _add_tooltip(widget, text: str) -> _ToolTip:
"""Convenience wrapper - see _ToolTip for behavior."""
return _ToolTip(widget, text)
class LoopClipApp(ctk.CTk):
def __init__(self):
super().__init__()
self.configure(fg_color=COLOR_BG)
self.title(f"LoopClip {__version__}")
self.geometry("700x820")
self.minsize(640, 700)
self.resizable(True, True)
self._set_app_icon()
self.cfg = settings_module.load_settings()
self.queue_manager = QueueManager(on_update=self._on_queue_update, temp_root=TEMP_ROOT)
# Optimistic default (encode functions still fall back to CPU on
# failure either way) until the real probe below finishes - avoids
# blocking startup on the ~15s-worst-case NVENC test encode. Cached
# in tool_check itself, so this is the one real probe for the whole
# run; the About dialog's own check_nvenc() call reuses the result.
self.nvenc_available = True
threading.Thread(target=self._probe_nvenc, daemon=True).start()
self._build_ui()
self._last_seen_clip = None
self._poll_clipboard()
missing = missing_tools_message()
if missing:
self.after(300, lambda: messagebox.showwarning("Missing requirements", missing))
self.update_notice_frame = None # created lazily, only if an update is found
threading.Thread(target=self._check_yt_dlp_update, daemon=True).start()
def _probe_nvenc(self) -> None:
"""Background-thread target: runs the one real NVENC probe for this
run of the app (see check_nvenc's own caching) and updates
self.nvenc_available with the result. A plain attribute write is
safe to do off the main thread here since nothing reads it until
the next 'Add to Queue' click, well after this finishes in
practice."""
available, _ = check_nvenc()
self.nvenc_available = available
def _set_app_icon(self):
"""Sets the window/taskbar icon from icon.ico if it's present next
to main.py. Missing or unreadable icon files are non-fatal - the
app should still run fine with the default icon."""
icon_path = Path(__file__).resolve().parent / "icon.ico"
if icon_path.exists():
try:
self.iconbitmap(str(icon_path))
except tk.TclError:
pass
def _show_help_dialog(self):
"""
A single reference dialog explaining what each of the less
self-explanatory settings actually does, for anyone who wants
the full picture in one place rather than hovering over each
field's tooltip individually. Uses a CTkTextbox (scrollable,
read-only) rather than trying to fit everything in a fixed-size
dialog - long-form help content should always be expected to
need scrolling on some screen/font combination, so this doesn't
try to guess a height that fits everything (see
_show_about_dialog's history for why that guess is fragile
across different machines - here the answer is just "always
scrollable" instead of "measure and hope").
"""
dialog = ctk.CTkToplevel(self)
dialog.title("LoopClip Help")
dialog.geometry("480x560")
dialog.minsize(360, 300)
dialog.configure(fg_color=COLOR_BG)
dialog.transient(self)
dialog.grab_set()
ctk.CTkLabel(
dialog, text="What these settings do",
font=ctk.CTkFont(size=16, weight="bold"),
).pack(pady=(16, 10))
textbox = ctk.CTkTextbox(
dialog, fg_color=COLOR_PANEL, wrap="word",
font=ctk.CTkFont(size=12),
)
textbox.pack(fill="both", expand=True, padx=16, pady=(0, 10))
# Bold section headers via the underlying tkinter Text widget's
# tag system - CTkTextbox doesn't expose rich-text formatting
# directly, but wraps a real Text widget that does.
heading_font = ctk.CTkFont(size=12, weight="bold")
textbox._textbox.tag_configure("heading", font=heading_font, foreground=COLOR_ACCENT)
sections = [
("Download Quality", (
"Best Available picks whichever video+audio streams YouTube "
"offers at the highest quality, regardless of codec.\n"
"4K HDR Preferred favors an HDR-capable 4K stream when the "
"source has one.\n"
"1080p Compatible caps downloads at 1080p, for smaller files "
"and broader device compatibility."
)),
("Video Bitrate / Audio Bitrate", (
"Video Bitrate only applies to the H.265 re-encode fallback - "
"used when a clean stream-copy trim isn't possible for the "
"source. Higher means better quality and larger files.\n\n"
"Audio Bitrate's 'Original' keeps the source audio as-is "
"without re-encoding it; a specific value re-encodes the "
"audio track to that target instead."
)),
("Auto-detect seamless loop", (
"When enabled, LoopClip searches the video for a point where "
"it can loop cleanly, instead of you picking trim points "
"manually.\n\n"
"Method controls how frames get compared: Combined "
"(recommended) blends structural and color matching for the "
"most reliable results; SSIM checks structural similarity "
"only; Histogram checks color distribution only; Hash is "
"fastest but least precise.\n\n"
"Similarity % sets how closely the start and end of a "
"candidate loop need to match (0-100) - higher demands a "
"closer match; lower is more lenient.\n\n"
"Analyze controls how many frames get compared - 'Every "
"frame' is most thorough but slowest; skipping frames "
"analyzes faster at some cost to precision, useful for very "
"long videos."
)),
("Limit search window", (
"Restricts the loop search to a specific From/To portion of "
"the video instead of scanning the whole thing - useful for "
"skipping intros/outros, or speeding up analysis on long "
"videos."
)),
("Seamless loop crossfade", (
"Blends the end of the clip into the start over the chosen "
"duration, smoothing out any visible seam at the loop point. "
"Leave this off for a hard cut instead - it's optional, and "
"auto-detect can already find clean loop points without it."
)),
("After Download", (
"Delete original large file removes the full downloaded "
"source once the clip has been created, keeping only the "
"final output.\n\n"
"Open folder when finished opens the output folder in "
"Explorer automatically once a queued video is done."
)),
("Command line", (
"Everything here is also available without the GUI via "
"cli.py, for scripting or automation - run "
"'python cli.py --help' for the full list of options, or "
"see the README's Command-Line Usage section."
)),
]
for heading, body in sections:
textbox.insert("end", heading + "\n", "heading")
textbox.insert("end", body + "\n\n")
textbox.configure(state="disabled") # read-only after populating
ctk.CTkButton(
dialog, text="Close", width=100, fg_color=COLOR_ACCENT,
hover_color=COLOR_ACCENT_HOVER,
# Deferred by a tick rather than dialog.destroy directly:
# confirmed directly (isolated, reproducible minimal repro)
# that a CTkToplevel containing a CTkTextbox destroyed
# synchronously inside a button's own click handler can hit
# a genuine CustomTkinter-internal timing bug - some
# widget's deferred internal callback (most likely the
# textbox's scrollbar) is still pending when everything gets
# torn down, and fires afterward against an already-destroyed
# canvas ("invalid command name ...canvas"). A CTkButton
# alone, with no CTkTextbox present, does not trigger this -
# it's specific to that combination. Giving pending internal
# callbacks one more event-loop tick to complete before
# destroying reliably avoids it (verified across 5 repeated
# runs of the isolated repro with this fix applied).
command=lambda: dialog.after(50, dialog.destroy),
).pack(pady=(0, 16))
def _show_about_dialog(self):
"""
Shows version/environment diagnostics: LoopClip version, Python
runtime, FFmpeg availability, yt-dlp version, NVENC status, and a
link to the GitHub project. Meant to make troubleshooting
("what version are you on? Is FFmpeg actually found? Is NVENC
working?") a lot easier than asking the user to dig through logs
or run commands manually.
The NVENC check involves a real (tiny, ~0.1s) test encode, so
it's run on a background thread and the dialog fills in that one
row once it completes, rather than blocking the whole dialog from
opening.
"""
dialog = ctk.CTkToplevel(self)
dialog.title("About LoopClip")
dialog.resizable(False, False)
dialog.configure(fg_color=COLOR_BG)
dialog.transient(self)
dialog.grab_set()
# Deliberately NOT calling dialog.geometry("WIDTHxHEIGHT") with a
# hardcoded pixel size here: a fixed height picked against one
# machine's font rendering/DPI scaling can end up too short on a
# different one, clipping the bottom of the dialog (confirmed
# directly - this happened on a real Windows machine with the
# Close button cut off). Leaving geometry unset lets Tk size the
# window to whatever its packed content actually needs once
# rendered, which adapts correctly regardless of font metrics or
# display scaling.
dialog_width = 420
ctk.CTkLabel(
dialog, text=f"LoopClip {__version__}",
font=ctk.CTkFont(size=16, weight="bold"),
).pack(pady=(20, 4))
ctk.CTkLabel(
dialog, text="Seamless-loop 4K clips from YouTube videos.",
font=ctk.CTkFont(size=11), text_color="gray60",
).pack(pady=(0, 16))
info_frame = ctk.CTkFrame(dialog, fg_color=COLOR_PANEL)
info_frame.pack(fill="x", padx=20)
ffmpeg_version = get_ffmpeg_version()
ffmpeg_text = f"Found (v{ffmpeg_version})" if ffmpeg_version else \
("Found" if check_ffmpeg() else "Not found")
try:
ytdlp_version = downloader.get_installed_version()
except Exception:
ytdlp_version = "unknown"
rows = [
("Python", platform.python_version()),
("FFmpeg", ffmpeg_text),
("yt-dlp", ytdlp_version),
("NVENC (GPU encoding)", "Checking..."),
]
self._about_nvenc_label = None
for label, value in rows:
row = ctk.CTkFrame(info_frame, fg_color="transparent")
row.pack(fill="x", padx=12, pady=6)
# Label above value (not side-by-side) so a long value - the
# NVENC status in particular can be a full sentence, e.g.
# "Not available (no compatible NVIDIA GPU/driver detected) -
# using CPU encoding" - has room to wrap onto multiple lines
# instead of overlapping the label. Confirmed directly: the
# previous side-by-side layout visibly collided the label and
# value text together on a real machine once the value was
# longer than a couple of words.
ctk.CTkLabel(
row, text=label, anchor="w", text_color="gray70",
font=ctk.CTkFont(size=11),
).pack(fill="x")
value_label = ctk.CTkLabel(
row, text=value, anchor="w", justify="left",
wraplength=dialog_width - 64,
)
value_label.pack(fill="x")
if label.startswith("NVENC"):
self._about_nvenc_label = value_label
def _update_nvenc_status():
# Runs on a background thread (the NVENC check does a real,
# if tiny, subprocess encode) - Tkinter widgets can only be
# safely touched from the main thread, so the actual UI
# update is handed to self.after(0, ...) rather than calling
# .configure() here directly (which intermittently raises
# "main thread is not in main loop", confirmed by actually
# running this against a live Tk app rather than assuming
# the same pattern used elsewhere in this file would apply).
available, message = check_nvenc()
color = "#3FB950" if available else "gray70"
def _apply():
# Dialog may already be closed by the time this runs -
# guard against updating a destroyed widget.
try:
self._about_nvenc_label.configure(text=message, text_color=color)
# The real NVENC message can be noticeably longer
# than the "Checking..." placeholder the dialog was
# originally sized against, and wraplength may now
# push this row onto two lines instead of one -
# re-measure and re-apply the dialog's height so that
# doesn't get clipped at the bottom the same way the
# original fixed-size dialog did.
dialog.update_idletasks()
dialog.geometry(f"{dialog_width}x{dialog.winfo_reqheight()}")
except tk.TclError:
pass
self.after(0, _apply)
threading.Thread(target=_update_nvenc_status, daemon=True).start()
auto_update_var = tk.BooleanVar(value=self.cfg.get("auto_check_ytdlp_updates", True))
def _on_auto_update_toggle():
self.cfg["auto_check_ytdlp_updates"] = auto_update_var.get()
settings_module.save_settings(self.cfg)
ctk.CTkCheckBox(
dialog, text="Automatically check for yt-dlp updates",
variable=auto_update_var, command=_on_auto_update_toggle,
font=ctk.CTkFont(size=11), fg_color=COLOR_ACCENT, hover_color=COLOR_ACCENT_HOVER,
).pack(pady=(16, 0), padx=20, anchor="w")
link_label = ctk.CTkLabel(
dialog, text="github.com/quinnuk/LoopClip", text_color=COLOR_ACCENT,
cursor="hand2", font=ctk.CTkFont(size=12, underline=True),
)
link_label.pack(pady=(12, 4))
link_label.bind(
"<Button-1>",
lambda _e: webbrowser.open("https://github.com/quinnuk/LoopClip"),
)
ctk.CTkButton(
dialog, text="Close", width=100, fg_color=COLOR_ACCENT,
hover_color=COLOR_ACCENT_HOVER, command=dialog.destroy,
).pack(pady=(12, 20))
# Force layout now (rather than waiting for the next idle cycle)
# so the width constraint below applies to the dialog's actual
# first paint, not a stale/zero size.
dialog.update_idletasks()
dialog.geometry(f"{dialog_width}x{dialog.winfo_reqheight()}")
dialog.minsize(dialog_width, dialog.winfo_reqheight())
def _check_yt_dlp_update(self):
"""
Runs on a background thread at startup (never blocks the UI).
Checks whether a newer yt-dlp is available on PyPI - this matters
because YouTube changes things fairly often, and an outdated
yt-dlp is the single most common reason downloads suddenly start
failing. Never raises - any failure here (no internet, PyPI
unreachable, etc.) is silently ignored, since this is a
nice-to-have notice, not something that should ever interrupt
the app.
"""
if not self.cfg.get("auto_check_ytdlp_updates", True):
return
try:
installed = downloader.get_installed_version()
info = ytdlp_updater.check_for_update(installed)
if info is None:
return
if info.latest_version == self.cfg.get("skipped_ytdlp_version", ""):
return # user already explicitly declined this exact version
self.after(0, lambda: self._show_update_notice(info))
except Exception:
pass # Best-effort only - never surface this to the user as an error.
def _show_update_notice(self, info):
if self.update_notice_frame is not None:
return # already shown
self.update_notice_frame = ctk.CTkFrame(self, fg_color=COLOR_PANEL)
self.update_notice_frame.pack(fill="x", padx=20, pady=(0, 8))
self._update_notice_label = ctk.CTkLabel(
self.update_notice_frame,
text=f"A newer yt-dlp is available ({info.current_version} \u2192 {info.latest_version}).",
font=ctk.CTkFont(size=11), text_color="#E8A33D", anchor="w",
)
self._update_notice_label.pack(side="left", padx=(10, 6), pady=6)
button_row = ctk.CTkFrame(self.update_notice_frame, fg_color="transparent")
button_row.pack(side="right", padx=(6, 10), pady=4)
self._update_now_btn = ctk.CTkButton(
button_row, text="Update Now", width=90, height=24, font=ctk.CTkFont(size=11),
fg_color=COLOR_ACCENT, hover_color=COLOR_ACCENT_HOVER,
command=lambda: self._start_ytdlp_update(info),
)
self._update_now_btn.pack(side="left", padx=(0, 6))
self._update_skip_btn = ctk.CTkButton(
button_row, text="Skip", width=56, height=24, font=ctk.CTkFont(size=11),
fg_color="transparent", hover_color=COLOR_PANEL, text_color="gray60",
command=lambda: self._skip_ytdlp_update(info),
)
self._update_skip_btn.pack(side="left")
def _skip_ytdlp_update(self, info):
# Remembered so this exact version doesn't get offered again on
# every future launch - a newer version later still will be.
self.cfg["skipped_ytdlp_version"] = info.latest_version
settings_module.save_settings(self.cfg)
if self.update_notice_frame is not None:
self.update_notice_frame.destroy()
self.update_notice_frame = None
def _start_ytdlp_update(self, info):
"""
Downloads and applies the update on a background thread - never
blocks the UI, and the rest of the app keeps working normally
while it runs (queueing/processing videos, etc. are untouched;
this only affects which yt-dlp gets used on the *next* launch,
never the one already running in this process - see
ytdlp_updater.py's docstring for why an in-process hot-swap isn't
attempted).
"""
self._update_now_btn.configure(state="disabled", text="Updating...")
self._update_skip_btn.configure(state="disabled")
def do_update():
try:
wheel_path = ytdlp_updater.download_update(info)
ytdlp_updater.apply_update(wheel_path, info.latest_version)
self.after(0, lambda: self._on_ytdlp_update_success(info))
except ytdlp_updater.UpdateError as exc:
# Capture the message into a plain local NOW, not inside
# the lambda: Python implicitly deletes the "as exc" name
# at the end of an except block (to avoid a traceback
# reference cycle), but self.after(0, ...) only calls
# this lambda later, on the main thread - by then `exc`
# is already unbound, and referencing it would raise
# "cannot access free variable 'exc'" instead of showing
# the actual error to the user. Confirmed directly: this
# is exactly what happened before capturing the message
# as its own variable here.
message = str(exc)
self.after(0, lambda: self._on_ytdlp_update_failure(message))
except Exception as exc:
message = f"An unexpected error occurred: {exc}"
self.after(0, lambda: self._on_ytdlp_update_failure(message))
threading.Thread(target=do_update, daemon=True).start()
def _on_ytdlp_update_success(self, info):
if self.update_notice_frame is None:
return # dialog/window already gone
self._update_notice_label.configure(
text=(
f"yt-dlp {info.latest_version} downloaded and verified. "
"Restart LoopClip to start using it."
),
text_color="#3FB950",
)
self._update_now_btn.destroy()
self._update_skip_btn.configure(state="normal", text="Dismiss")
self._update_skip_btn.configure(
command=lambda: (self.update_notice_frame.destroy(), setattr(self, "update_notice_frame", None))
)
def _on_ytdlp_update_failure(self, message: str):
if self.update_notice_frame is not None:
self.update_notice_frame.destroy()
self.update_notice_frame = None
messagebox.showerror(
"yt-dlp update failed",
f"Could not update yt-dlp:\n\n{message}\n\n"
"LoopClip will keep working normally with the current version.",
)
def _manual_check_ytdlp_update(self):
"""
On-demand version of the startup check, triggered from the
"Check for Updates" header button. Unlike _check_yt_dlp_update()
(which stays completely silent unless there's actually something
new - see its docstring), this always shows a result: checking,
up to date, update available, or "couldn't reach PyPI" - since a
button the user explicitly clicked should never just do nothing.
Reuses the same download_update()/apply_update() functions and
success/failure handling as the automatic banner, just wired to
this dialog's own widgets instead of the main window's notice
frame.
"""
dialog = ctk.CTkToplevel(self)
dialog.title("yt-dlp Update Check")
dialog.resizable(False, False)
dialog.configure(fg_color=COLOR_BG)
dialog.transient(self)
dialog.grab_set()
dialog_width = 380
status_label = ctk.CTkLabel(
dialog, text="Checking for updates...", font=ctk.CTkFont(size=12),
wraplength=340, justify="left", anchor="w",
)
status_label.pack(fill="x", padx=20, pady=(20, 10))
button_row = ctk.CTkFrame(dialog, fg_color="transparent")
button_row.pack(fill="x", padx=20, pady=(0, 16), side="bottom")
ctk.CTkButton(
button_row, text="Close", width=90, fg_color=COLOR_ACCENT,
hover_color=COLOR_ACCENT_HOVER, command=dialog.destroy,
).pack(side="right")
def relayout():
if not dialog.winfo_exists():
return
dialog.update_idletasks()
dialog.geometry(f"{dialog_width}x{dialog.winfo_reqheight()}")
dialog.update_idletasks()
dialog.geometry(f"{dialog_width}x{dialog.winfo_reqheight()}")
def report(status: dict, current: str):
if not dialog.winfo_exists():
return
latest = status["latest"]
if latest is None:
status_label.configure(
text=f"Currently running yt-dlp {current}.\n"
"Could not reach PyPI to check for a newer version."
)
relayout()
return
if status["up_to_date"]:
status_label.configure(text=f"You're on the latest version of yt-dlp ({current}).")
relayout()
return
info = status["info"]
if info is None:
status_label.configure(
text=f"Update available: {current} \u2192 {latest}.\n"
"No downloadable release was found for it yet - please "
"check again later."
)
relayout()
return
status_label.configure(text=f"Update available: {current} \u2192 {latest}.")
install_btn = ctk.CTkButton(
button_row, text="Download & Install", width=140, fg_color=COLOR_ACCENT,
hover_color=COLOR_ACCENT_HOVER,
command=lambda: do_install(info, install_btn),
)
install_btn.pack(side="left")
relayout()
def do_install(info, install_btn):
install_btn.configure(state="disabled", text="Updating...")
def do_update():
try:
wheel_path = ytdlp_updater.download_update(info)
ytdlp_updater.apply_update(wheel_path, info.latest_version)
self.after(0, lambda: on_success(info))
except ytdlp_updater.UpdateError as exc:
message = str(exc) # captured now - see _start_ytdlp_update for why
self.after(0, lambda: on_failure(message))
except Exception as exc:
message = f"An unexpected error occurred: {exc}"
self.after(0, lambda: on_failure(message))
threading.Thread(target=do_update, daemon=True).start()
def on_success(info):
if not dialog.winfo_exists():
return
status_label.configure(
text=(
f"yt-dlp {info.latest_version} downloaded and verified. "
"Restart LoopClip to start using it."
),
)
for child in list(button_row.winfo_children()):
if isinstance(child, ctk.CTkButton) and child.cget("text") in ("Updating...", "Download & Install"):
child.destroy()
relayout()
def on_failure(message: str):
if dialog.winfo_exists():
dialog.destroy()
messagebox.showerror(
"yt-dlp update failed",
f"Could not update yt-dlp:\n\n{message}\n\n"
"LoopClip will keep working normally with the current version.",
)
def do_check():
try:
current = downloader.get_installed_version()
except Exception:
current = "unknown"
status = ytdlp_updater.check_status(current)
self.after(0, lambda: report(status, current))
threading.Thread(target=do_check, daemon=True).start()
# ------------------------------------------------------------------ UI
def _build_ui(self):
pad_x = 20
# Subtitle, with a small unobtrusive "About" link in the top-right
# corner - no full menu bar needed for a single dialog like this.
header_row = ctk.CTkFrame(self, fg_color="transparent")
header_row.pack(fill="x", padx=pad_x, pady=(10, 0))
ctk.CTkButton(
header_row, text="About", width=56, height=22, font=ctk.CTkFont(size=11),
fg_color="transparent", hover_color=COLOR_PANEL, text_color="gray60",
command=self._show_about_dialog,
).pack(side="right")
ctk.CTkButton(
header_row, text="Help", width=56, height=22, font=ctk.CTkFont(size=11),
fg_color="transparent", hover_color=COLOR_PANEL, text_color="gray60",
command=self._show_help_dialog,
).pack(side="right", padx=(0, 4))
ctk.CTkButton(
header_row, text="Check for Updates", width=130, height=22, font=ctk.CTkFont(size=11),
fg_color="transparent", hover_color=COLOR_PANEL, text_color="gray60",
command=self._manual_check_ytdlp_update,
).pack(side="right", padx=(0, 4))
ctk.CTkLabel(
self, text="Paste a YouTube link, set your options, then queue it up.",
font=ctk.CTkFont(size=11), text_color="gray60",
).pack(pady=(2, 12))
# URL
ctk.CTkLabel(self, text="YouTube Video URL", anchor="w").pack(fill="x", padx=pad_x)
url_row = ctk.CTkFrame(self, fg_color="transparent")
url_row.pack(fill="x", padx=pad_x, pady=(2, 0))
self.url_entry = ctk.CTkEntry(
url_row, placeholder_text="https://www.youtube.com/watch?v=...", fg_color=COLOR_PANEL
)
self.url_entry.pack(side="left", fill="x", expand=True)
self.url_entry.insert(0, self.cfg.get("last_url", ""))
self._add_context_menu(self.url_entry)
ctk.CTkButton(
url_row, text="Clear", width=62, fg_color=COLOR_ACCENT, hover_color=COLOR_ACCENT_HOVER,
command=self._clear_url,
).pack(side="left", padx=(8, 0))
# Options, two columns side by side to make better use of horizontal space
options = ctk.CTkFrame(self, fg_color="transparent")
options.pack(fill="x", padx=pad_x, pady=(12, 0))
left = ctk.CTkFrame(options, fg_color="transparent")
left.pack(side="left", fill="both", expand=True)
right = ctk.CTkFrame(options, fg_color="transparent")
right.pack(side="left", fill="both", expand=True, padx=(16, 0))
# Output folder (left column)
ctk.CTkLabel(left, text="Output Folder", anchor="w").pack(fill="x")
folder_row = ctk.CTkFrame(left, fg_color="transparent")
folder_row.pack(fill="x", pady=(2, 8))
self.folder_entry = ctk.CTkEntry(folder_row, fg_color=COLOR_PANEL)
self.folder_entry.pack(side="left", fill="x", expand=True)
self.folder_entry.insert(0, self.cfg.get("output_folder"))
self._add_context_menu(self.folder_entry)
ctk.CTkButton(
folder_row, text="Browse", width=68, fg_color=COLOR_ACCENT,
hover_color=COLOR_ACCENT_HOVER, command=self._browse_folder,
).pack(side="left", padx=(6, 0))
self.recent_folders_btn = ctk.CTkButton(
folder_row, text="Recent", width=68, fg_color=COLOR_ACCENT,
hover_color=COLOR_ACCENT_HOVER, command=self._show_recent_folders_menu,
)
self.recent_folders_btn.pack(side="left", padx=(6, 0))
# Download quality (left column) - segmented button, same control
# style as Video Downloader Pro's quality selector.
quality_label = ctk.CTkLabel(left, text="Download Quality", anchor="w")
quality_label.pack(fill="x")
_add_tooltip(
quality_label,
"Best Available picks whichever video+audio streams YouTube offers "
"at the highest quality, any codec. 4K HDR Preferred favors an "
"HDR-capable 4K stream when the source has one. 1080p Compatible "
"caps at 1080p for smaller files and broader compatibility.",
)
self.quality_var = ctk.StringVar(value=self.cfg.get("quality", "best"))
quality_values_by_label = {label: value for value, label in QUALITY_LABELS.items()}
self.quality_display_var = ctk.StringVar(
value=QUALITY_LABELS.get(self.quality_var.get(), "Best Available")
)
ctk.CTkSegmentedButton(
left,
values=list(QUALITY_LABELS.values()),
variable=self.quality_display_var,
selected_color=COLOR_ACCENT,
selected_hover_color=COLOR_ACCENT_HOVER,
command=lambda label: self.quality_var.set(quality_values_by_label[label]),