-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrimLoad.py
More file actions
2002 lines (1680 loc) · 84.5 KB
/
Copy pathTrimLoad.py
File metadata and controls
2002 lines (1680 loc) · 84.5 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 sys
import os
import math
import threading
import urllib.request
import webbrowser
import hashlib
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QLineEdit, QComboBox,
QProgressBar, QFrame, QGraphicsDropShadowEffect,
QGridLayout, QSpacerItem, QSizePolicy,
QGraphicsOpacityEffect, QPlainTextEdit)
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput
from PySide6.QtMultimediaWidgets import QVideoWidget
from PySide6.QtCore import (Qt, QUrl, Signal, QPointF, QRectF, QLineF, QObject, QTimer,
QPropertyAnimation, QSequentialAnimationGroup, QParallelAnimationGroup,
QPoint, QEasingCurve, QEvent, QRect, QElapsedTimer, QVariantAnimation)
from PySide6.QtGui import (QFont, QPainter, QColor, QPen, QCursor, QPixmap, QIcon, QDesktopServices,
QPainterPath, QBrush, QLinearGradient, QRadialGradient, QFontMetrics)
try:
from PySide6.QtSvgWidgets import QSvgWidget
from PySide6.QtSvg import QSvgRenderer
HAS_SVG = True
except ImportError:
HAS_SVG = False
try:
import yt_dlp
import builtins
# Inject yt_dlp globally so the DownloadWorker in main.py can access it for range functions
builtins.yt_dlp = yt_dlp
except ImportError:
yt_dlp = None
# Cache Directories
repo_root = Path(__file__).resolve().parent
cache_dir = repo_root / "cache"
favicon_dir = cache_dir / "favicons"
thumb_dir = cache_dir / "thumbnails"
favicon_dir.mkdir(parents=True, exist_ok=True)
thumb_dir.mkdir(parents=True, exist_ok=True)
# UI Theme Constants
TEAL_ACCENT = "#00BFA5"
BG_DARK = "#121212"
CARD_BG = "#1E1E1E"
INPUT_BG = "#333333"
TEXT_MAIN = "#FFFFFF"
TEXT_MUTED = "#8A8A8A"
ERROR_RED = "#FF5555"
# Global Headers
DEFAULT_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
_AUDIO_ONLY_DOMAINS = (
"music.youtube.com", "soundcloud.com", "spotify.com",
"tidal.com", "deezer.com", "music.apple.com", "apple.com",
"bandcamp.com", "audiomack.com", "reverbnation.com",
"mixcloud.com",
)
def _is_audio_only_url(url):
return any(domain in url.lower() for domain in _AUDIO_ONLY_DOMAINS)
class AnimatedComboBox(QComboBox):
def __init__(self, parent=None):
super().__init__(parent)
self._popup = None
self._anim_group = None
def showPopup(self):
super().showPopup()
popup = self.view().window()
if popup and popup is not self._popup:
self._popup = popup
popup.installEventFilter(self)
if popup:
popup.setWindowOpacity(0.0)
QTimer.singleShot(0, self._animate_popup)
def eventFilter(self, obj, event):
if obj is self._popup and event.type() == QEvent.Type.Show:
obj.setWindowOpacity(0.0)
return super().eventFilter(obj, event)
def _animate_popup(self):
popup = self._popup
if not popup:
return
if self._anim_group and self._anim_group.state() == QParallelAnimationGroup.State.Running:
self._anim_group.stop()
self._anim_group = QParallelAnimationGroup(self)
fade_anim = QPropertyAnimation(popup, b"windowOpacity")
fade_anim.setDuration(200)
fade_anim.setStartValue(0.0)
fade_anim.setEndValue(1.0)
fade_anim.setEasingCurve(QEasingCurve.Type.OutCubic)
slide_anim = QPropertyAnimation(popup, b"pos")
slide_anim.setDuration(200)
target_pos = popup.pos()
global_pos = self.mapToGlobal(QPoint(0, self.height()))
if target_pos.y() < global_pos.y() - 10:
slide_anim.setStartValue(target_pos + QPoint(0, 8))
else:
slide_anim.setStartValue(target_pos + QPoint(0, -8))
slide_anim.setEndValue(target_pos)
slide_anim.setEasingCurve(QEasingCurve.Type.OutCubic)
self._anim_group.addAnimation(fade_anim)
self._anim_group.addAnimation(slide_anim)
self._anim_group.start()
def _site_name(url):
try:
host = urlparse(url).netloc.lower()
if "music.youtube.com" in host: return "YouTube Music"
if "music.apple.com" in host or "apple.com" in host: return "Apple Music"
if "spotify.com" in host: return "Spotify"
if "soundcloud.com" in host: return "SoundCloud"
if "deezer.com" in host: return "Deezer"
if "tidal.com" in host: return "Tidal"
if "bandcamp.com" in host: return "Bandcamp"
if "audiomack.com" in host: return "Audiomack"
if "youtu.be" in host or "youtube.com" in host: return "YouTube"
host = host.replace("www.", "").replace("m.", "").replace("music.", "")
return host.split(".")[0].title()
except Exception:
return "YouTube"
def _fetch_favicon_sync(url):
try:
parsed = urlparse(url)
host = parsed.netloc or "unknown"
filepath = favicon_dir / f"{host}.png"
if filepath.exists():
return str(filepath)
furl = f"https://icons.duckduckgo.com/ip3/{parsed.netloc}.ico"
req = urllib.request.Request(furl, headers={"User-Agent": DEFAULT_UA})
with urllib.request.urlopen(req, timeout=3) as r:
data = r.read()
with open(filepath, 'wb') as f:
f.write(data)
return str(filepath)
except Exception:
return None
def format_time_str(seconds):
seconds = max(0, float(seconds))
m, s = divmod(int(seconds), 60)
h, m = divmod(m, 60)
return f"{h:02d}:{m:02d}:{s:02d}"
def parse_time_str(time_str):
try:
parts = [float(p) for p in time_str.split(":")]
if len(parts) == 3:
return parts[0] * 3600 + parts[1] * 60 + parts[2]
elif len(parts) == 2:
return parts[0] * 60 + parts[1]
elif len(parts) == 1:
return parts[0]
except Exception:
pass
return -1.0
def jiggle_widget(widget):
if hasattr(widget, "_jiggle_anim") and widget._jiggle_anim.state() == QSequentialAnimationGroup.State.Running:
return
orig_pos = widget.pos()
group = QSequentialAnimationGroup(widget)
for offset in [-10, 10, -7, 7, -4, 4, -2, 2, 0]:
anim = QPropertyAnimation(widget, b"pos", widget)
anim.setDuration(35)
anim.setStartValue(widget.pos())
anim.setEndValue(orig_pos + QPoint(offset, 0))
group.addAnimation(anim)
widget._jiggle_anim = group
group.start()
def select_preview_stream(info, url):
if not isinstance(info, dict):
return None, None, False
formats = info.get('formats') or []
is_audio_platform = _is_audio_only_url(url)
if not formats:
stream_url = info.get('url')
if stream_url:
vcodec = info.get('vcodec')
is_audio = is_audio_platform or (vcodec == 'none')
return stream_url, 0, is_audio
return None, None, False
valid = [f for f in formats if f.get('url') and str(f.get('url')).startswith('http')]
vids = [f for f in valid if f.get('vcodec') not in ('none', None)]
all_audio_only = bool(valid) and all(f.get('vcodec') == 'none' for f in valid)
is_pure_audio = is_audio_platform or all_audio_only
if is_pure_audio:
auds = [f for f in valid if f.get('acodec') not in ('none', None)]
if auds:
best_aud = sorted(auds, key=lambda x: x.get('abr') or 0, reverse=True)[0]
return best_aud.get('url'), 0, True
fallback = [f for f in valid]
if fallback:
return fallback[0].get('url'), 0, True
return None, None, True
def vid_score(f):
s = 0
h = f.get('height') or 9999
vcodec = (f.get('vcodec') or '').lower()
ext = (f.get('ext') or '').lower()
if 'av1' in vcodec or 'av01' in vcodec:
s -= 100000
if 'vp9' in vcodec or 'vp09' in vcodec:
s -= 20000
if 'avc' in vcodec or 'h264' in vcodec:
s += 50000
if ext == 'mp4':
s += 20000
if 0 < h <= 720:
s += (10000 - h)
return s
if vids:
best_vid = max(vids, key=vid_score)
elif valid:
best_vid = valid[0]
else:
return None, None, False
return best_vid.get('url'), best_vid.get('height') or 0, False
class SvgSpinnerWidget(QWidget):
def __init__(self, svg_path, parent=None):
super().__init__(parent)
self.setFixedSize(48, 48)
self.renderer = QSvgRenderer(svg_path) if HAS_SVG and os.path.exists(svg_path) else None
self.angle = 0
self.timer = QTimer(self)
self.timer.timeout.connect(self.rotate)
self.timer.start(16)
def rotate(self):
self.angle = (self.angle + 8) % 360
self.update()
def paintEvent(self, event):
if not self.renderer:
return
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.translate(self.width() / 2, self.height() / 2)
painter.rotate(self.angle)
painter.translate(-self.width() / 2, -self.height() / 2)
self.renderer.render(painter, QRectF(0, 0, self.width(), self.height()))
class LoadingOverlay(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True)
self.setStyleSheet("background-color: rgba(0, 0, 0, 160); border-radius: 12px")
layout = QVBoxLayout(self)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
icon_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
svg_path = os.path.join(icon_dir, "line-md--loading-loop.svg")
if not os.path.exists(svg_path):
svg_path = os.path.join(icon_dir, "line-md--loading-loop")
if HAS_SVG and os.path.exists(svg_path):
self.spinner = SvgSpinnerWidget(svg_path, self)
layout.addWidget(self.spinner, alignment=Qt.AlignmentFlag.AlignCenter)
else:
self.spinner = None
lbl = QLabel("Loading...")
lbl.setStyleSheet(f"color: {TEAL_ACCENT}; font-size: 16px; font-weight: bold;")
layout.addWidget(lbl, alignment=Qt.AlignmentFlag.AlignCenter)
self.hide()
def resizeEvent(self, event):
super().resizeEvent(event)
if self.parent():
self.setGeometry(0, 0, self.parent().width(), self.parent().height())
def start(self):
if self.parent():
self.setGeometry(0, 0, self.parent().width(), self.parent().height())
self.show()
self.raise_()
def stop(self):
self.hide()
class StandaloneToastWidget(QFrame):
dismissed = Signal(object)
def __init__(self, message, parent=None, icon_pixmap=None, rich_text=False):
super().__init__(parent)
self.setFixedSize(290, 48)
self.setStyleSheet("QFrame { background-color: #242424; border: 1px solid #333333; border-radius: 12px; }")
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(16)
shadow.setColor(QColor(0, 0, 0, 160))
shadow.setOffset(0, 4)
self.setGraphicsEffect(shadow)
layout = QHBoxLayout(self)
layout.setContentsMargins(14, 0, 10, 0)
layout.setSpacing(10)
if icon_pixmap is not None and not icon_pixmap.isNull():
icon_lbl = QLabel()
icon_lbl.setFixedSize(22, 22)
icon_lbl.setPixmap(icon_pixmap)
icon_lbl.setStyleSheet("background: transparent; border: none;")
else:
icon_lbl = QLabel("✕")
icon_lbl.setStyleSheet("color: #FF5555; font-size: 15px; font-weight: bold; border: none; background: transparent;")
layout.addWidget(icon_lbl)
msg_lbl = QLabel(message)
if rich_text:
msg_lbl.setTextFormat(Qt.TextFormat.RichText)
msg_lbl.setStyleSheet("color: #FFFFFF; font-size: 13px; font-weight: 500; border: none; background: transparent;")
layout.addWidget(msg_lbl, 1)
close_btn = QPushButton("✕")
close_btn.setFixedSize(22, 22)
close_btn.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
close_btn.setStyleSheet("QPushButton { color: #888888; font-size: 13px; font-weight: bold; border: none; background: transparent; } QPushButton:hover { color: #FFFFFF; }")
close_btn.clicked.connect(self.close_toast)
layout.addWidget(close_btn)
self.timer = QTimer(self)
self.timer.setSingleShot(True)
self.timer.timeout.connect(self.close_toast)
self.timer.start(4000)
self._is_closing = False
def close_toast(self):
if self._is_closing: return
self._is_closing = True
self.timer.stop()
self.dismissed.emit(self)
class LocalToastManager(QObject):
def __init__(self, parent_window):
super().__init__(parent_window)
self.win = parent_window
self.toasts = []
def show_toast(self, message, icon_pixmap=None, rich_text=False):
toast = StandaloneToastWidget(message, parent=self.win, icon_pixmap=icon_pixmap, rich_text=rich_text)
toast.dismissed.connect(self._remove_toast)
self.toasts.append(toast)
toast.show()
toast.raise_()
self._reposition_toasts(animate_last=True)
def _reposition_toasts(self, animate_last=False):
if not self.win: return
w_width, w_height = self.win.width(), self.win.height()
for i, toast in enumerate(self.toasts):
target_x = w_width - 24 - 290
target_y = w_height - 24 - (i + 1) * 48 - i * 10
if animate_last and i == len(self.toasts) - 1:
toast.move(target_x, w_height + 20)
anim = QPropertyAnimation(toast, b"pos", toast)
anim.setDuration(250)
anim.setStartValue(QPoint(target_x, w_height + 20))
anim.setEndValue(QPoint(target_x, target_y))
anim.setEasingCurve(QEasingCurve.Type.OutCubic)
anim.start()
toast._pos_anim = anim
else:
anim = QPropertyAnimation(toast, b"pos", toast)
anim.setDuration(200)
anim.setStartValue(toast.pos())
anim.setEndValue(QPoint(target_x, target_y))
anim.setEasingCurve(QEasingCurve.Type.OutCubic)
anim.start()
toast._pos_anim = anim
def _remove_toast(self, toast):
if toast in self.toasts:
self.toasts.remove(toast)
anim_group = QParallelAnimationGroup(toast)
slide_anim = QPropertyAnimation(toast, b"pos", toast)
slide_anim.setDuration(200)
slide_anim.setStartValue(toast.pos())
slide_anim.setEndValue(toast.pos() + QPoint(40, 0))
slide_anim.setEasingCurve(QEasingCurve.Type.InCubic)
anim_group.addAnimation(slide_anim)
def _on_finish():
toast.deleteLater()
self._reposition_toasts(animate_last=False)
anim_group.finished.connect(_on_finish)
anim_group.start()
toast._close_anim = anim_group
class AspectRatioLabel(QLabel):
def __init__(self, parent=None):
super().__init__(parent)
self.pix = None
self.setStyleSheet("background-color: #000000;")
def setPixmap(self, p):
self.pix = p
super().setPixmap(self.scaled_pixmap())
def resizeEvent(self, event):
if self.pix:
super().setPixmap(self.scaled_pixmap())
super().resizeEvent(event)
def scaled_pixmap(self):
if not self.pix:
return QPixmap()
return self.pix.scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
class TrimRangeSlider(QWidget):
positionChanged = Signal(float)
seekRequested = Signal(float)
trimRangeChanged = Signal(float, float)
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedHeight(44)
self.duration = 1.0
self.start_time = 0.0
self.end_time = 1.0
self.current_time = 0.0
self._dragging = None
self.setMouseTracking(True)
def set_duration(self, dur):
self.duration = max(dur, 1.0)
self.start_time = 0.0
self.end_time = self.duration
self.current_time = 0.0
self.update()
def set_position(self, pos):
self.current_time = max(0.0, min(pos, self.duration))
self.update()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
w, h = self.width(), self.height()
cy = h - 12
margin = 14
usable_w = w - (margin * 2)
if usable_w <= 0 or self.duration <= 0:
return
painter.setPen(QPen(QColor("#3A3A3A"), 4))
painter.drawLine(QLineF(margin, cy, w - margin, cy))
start_x = margin + (self.start_time / self.duration) * usable_w
end_x = margin + (self.end_time / self.duration) * usable_w
painter.setPen(QPen(QColor(TEAL_ACCENT), 4))
painter.drawLine(QLineF(start_x, cy, end_x, cy))
handle_w = 12
handle_h = 22
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(TEAL_ACCENT))
start_rect = QRectF(start_x - handle_w / 2, cy - handle_h / 2, handle_w, handle_h)
painter.drawRoundedRect(start_rect, handle_w / 2, handle_w / 2)
painter.setPen(QPen(QColor("#121212"), 2))
painter.drawLine(QLineF(start_x, cy - 4, start_x, cy + 4))
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor(TEAL_ACCENT))
end_rect = QRectF(end_x - handle_w / 2, cy - handle_h / 2, handle_w, handle_h)
painter.drawRoundedRect(end_rect, handle_w / 2, handle_w / 2)
painter.setPen(QPen(QColor("#121212"), 2))
painter.drawLine(QLineF(end_x, cy - 4, end_x, cy + 4))
pos_x = margin + (self.current_time / self.duration) * usable_w
top_y = cy - 22
painter.setPen(QPen(QColor(TEAL_ACCENT), 2))
painter.drawLine(QLineF(pos_x, cy, pos_x, top_y))
glow_color = QColor(TEAL_ACCENT)
glow_color.setAlpha(70)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(glow_color)
painter.drawEllipse(QPointF(pos_x, top_y), 8, 8)
painter.setBrush(QColor(TEAL_ACCENT))
painter.drawEllipse(QPointF(pos_x, top_y), 4.5, 4.5)
def mousePressEvent(self, event):
x = event.position().x()
margin = 14
usable_w = self.width() - (margin * 2)
if usable_w <= 0: return
click_time = max(0.0, min(((x - margin) / usable_w) * self.duration, self.duration))
start_x = margin + (self.start_time / self.duration) * usable_w
end_x = margin + (self.end_time / self.duration) * usable_w
pos_x = margin + (self.current_time / self.duration) * usable_w
if abs(x - start_x) <= 12:
self._dragging = 'start'
elif abs(x - end_x) <= 12:
self._dragging = 'end'
elif abs(x - pos_x) <= 12:
self._dragging = 'position'
else:
self._dragging = 'position'
self.current_time = click_time
self.positionChanged.emit(self.current_time)
self.update()
def mouseMoveEvent(self, event):
margin = 14
usable_w = self.width() - (margin * 2)
if usable_w <= 0: return
x = event.position().x()
start_x = margin + (self.start_time / self.duration) * usable_w
end_x = margin + (self.end_time / self.duration) * usable_w
pos_x = margin + (self.current_time / self.duration) * usable_w
if self._dragging:
t = max(0.0, min(((x - margin) / usable_w) * self.duration, self.duration))
if self._dragging == 'start':
self.start_time = min(t, self.end_time - 0.5)
self.current_time = self.start_time
self.positionChanged.emit(self.current_time)
self.trimRangeChanged.emit(self.start_time, self.end_time)
elif self._dragging == 'end':
self.end_time = max(t, self.start_time + 0.5)
self.current_time = self.end_time
self.positionChanged.emit(self.current_time)
self.trimRangeChanged.emit(self.start_time, self.end_time)
elif self._dragging == 'position':
self.current_time = t
self.positionChanged.emit(self.current_time)
self.update()
else:
if abs(x - start_x) <= 12 or abs(x - end_x) <= 12 or abs(x - pos_x) <= 12:
self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
else:
self.setCursor(QCursor(Qt.CursorShape.ArrowCursor))
def mouseReleaseEvent(self, event):
if self._dragging:
self.seekRequested.emit(self.current_time)
self._dragging = None
class ProcessingOverlay(QWidget):
"""The "processing" screen shown while a pasted link is being parsed.
Everything (background, headline, step tracker, racing line, cancel
button) is painted by this one widget instead of being built from a
pile of child widgets + QGraphicsEffects. That keeps it cheap (no
offscreen buffers, no per-widget effect compositing) and lets the
whole thing fade/slide as a single unit.
The screen mirrors what the worker thread is *actually* doing: the
app calls set_phase() as each real stage begins. Each stage is held
on screen for at least MIN_DWELL_MS so quick stages stay readable,
and the queued stages are shown in order."""
# key, headline, tracker label, detail line
STEPS = [
("start", "Starting", "Start", "Getting things ready"),
("fetch", "Fetching URL streams", "Streams", "Contacting {host} and reading the available streams"),
("process", "Processing", "Process", "Reading the title, duration and available qualities"),
("preview", "Loading preview", "Preview", "Grabbing the thumbnail and site info"),
("done", "Done", "Done", "All set"),
]
MIN_DWELL_MS = 260 # shortest time a stage stays on screen
DONE_DWELL_MS = 550 # how long "Done" is shown before the card appears
FAIL_COLOR_MS = 480 # how long the ambient glow/accent takes to turn red
LINE_PERIOD_MS = 1500 # one lap of the racing line
FADE_IN_MS = 240
FADE_OUT_MS = 280
LOG_PANEL_H = 134
cancel_requested = Signal()
retry_requested = Signal()
def __init__(self, parent):
super().__init__(parent)
self._keys = [s[0] for s in self.STEPS]
self._host = ""
self._active, self._prev = 0, 0
self._queue = []
self._done_at = [None] * len(self.STEPS)
self._change_at, self._active_since = -10000, 0
self._failed, self._fail_at = False, 0
self._error_text = ""
self._log_open = False
self._finish_cb, self._finish_armed = None, False
self._alpha, self._opaque = 0.0, False
self._ease = QEasingCurve(QEasingCurve.Type.OutCubic)
self._line_ease = QEasingCurve(QEasingCurve.Type.InOutCubic)
self._clock = QElapsedTimer(); self._clock.start()
# 30fps rather than 60fps - this is slow ambient motion (gradient
# sweeps, a pulsing dot), not fast action; halving the repaint
# rate is not visually distinguishable here but meaningfully cuts
# sustained CPU/power draw for however long a fetch takes.
self._tick = QTimer(self); self._tick.setInterval(33)
self._tick.timeout.connect(self._on_tick)
self._fade = QVariantAnimation(self)
self._fade.valueChanged.connect(self._on_fade_step)
self._fade.finished.connect(self._on_fade_finished)
# Smoothly carries the ambient glow/accent color from teal to red
# on failure, instead of snapping instantly.
self._fail_color_t = 0.0
self._fail_color_anim = QVariantAnimation(self)
self._fail_color_anim.valueChanged.connect(self._on_fail_color_step)
self._build_buttons()
self._build_log_panel()
parent.installEventFilter(self)
self.hide()
# ---------- buttons / log panel (real child widgets, not painted) ----------
def _pill_style(self, filled=False):
if filled:
return (f"QPushButton {{ background-color: {TEAL_ACCENT}; border: none; border-radius: 17px; "
f"color: #0B0B0B; font-size: 13px; font-weight: bold; }} "
f"QPushButton:hover {{ background-color: #1ED6B8; }}")
return (f"QPushButton {{ background: transparent; border: 1.2px solid #3A3A3A; border-radius: 17px; "
f"color: {TEXT_MUTED}; font-size: 13px; }} "
f"QPushButton:hover {{ border-color: {TEAL_ACCENT}; color: {TEXT_MAIN}; background-color: rgba(0, 191, 165, 22); }}")
def _fade_with_overlay(self, widget):
"""Gives a child widget its own opacity effect so it fades in/out
together with the hand-painted content instead of popping in/out
at full opacity (child widgets aren't touched by this widget's own
paintEvent-level p.setOpacity() calls)."""
eff = QGraphicsOpacityEffect(widget)
eff.setOpacity(0.0)
widget.setGraphicsEffect(eff)
return eff
def _build_buttons(self):
self._btn_cancel = QPushButton("Cancel", self)
self._btn_cancel.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self._btn_cancel.setStyleSheet(self._pill_style(filled=False))
self._btn_cancel.clicked.connect(self.cancel_requested.emit)
self._cancel_fx = self._fade_with_overlay(self._btn_cancel)
self._btn_retry = QPushButton("Try Again", self)
self._btn_retry.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self._btn_retry.setStyleSheet(self._pill_style(filled=True))
self._btn_retry.clicked.connect(self.retry_requested.emit)
self._retry_fx = self._fade_with_overlay(self._btn_retry)
self._btn_log = QPushButton("Error Log", self)
self._btn_log.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self._btn_log.setStyleSheet(self._pill_style(filled=False))
self._btn_log.clicked.connect(self._toggle_log)
self._log_btn_fx = self._fade_with_overlay(self._btn_log)
for b in (self._btn_cancel, self._btn_retry, self._btn_log):
b.setFixedSize(120, 34); b.hide()
def _build_log_panel(self):
self._log_panel = QFrame(self)
self._log_panel.setStyleSheet("QFrame { background-color: #161616; border: 1px solid #2E2E2E; border-radius: 10px; }")
lay = QVBoxLayout(self._log_panel)
lay.setContentsMargins(14, 10, 14, 10)
lay.setSpacing(8)
header = QHBoxLayout()
title = QLabel("Error details")
title.setStyleSheet(f"color: {TEXT_MUTED}; font-size: 11px; font-weight: bold; border: none; background: transparent;")
header.addWidget(title)
header.addStretch()
self._btn_copy = QPushButton("Copy")
self._btn_copy.setFixedSize(64, 24)
self._btn_copy.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self._copy_style_normal = (f"QPushButton {{ background: transparent; border: 1px solid #3A3A3A; border-radius: 12px; "
f"color: {TEXT_MUTED}; font-size: 11px; }} "
f"QPushButton:hover {{ border-color: {TEAL_ACCENT}; color: {TEXT_MAIN}; }}")
self._copy_style_done = (f"QPushButton {{ background: transparent; border: 1px solid {TEAL_ACCENT}; border-radius: 12px; "
f"color: {TEAL_ACCENT}; font-size: 11px; font-weight: bold; }}")
self._btn_copy.setStyleSheet(self._copy_style_normal)
self._btn_copy.clicked.connect(self._copy_error_text)
header.addWidget(self._btn_copy)
lay.addLayout(header)
self._log_text = QPlainTextEdit()
self._log_text.setReadOnly(True)
self._log_text.setStyleSheet(f"QPlainTextEdit {{ background: transparent; border: none; color: {ERROR_RED}; "
f"font-family: Consolas, monospace; font-size: 11px; }}")
lay.addWidget(self._log_text, 1)
self._log_panel.hide()
self._log_fx = self._fade_with_overlay(self._log_panel)
self._log_anim = QPropertyAnimation(self._log_panel, b"geometry", self)
self._log_anim.setEasingCurve(QEasingCurve.Type.InOutCubic)
self._log_anim.setDuration(240)
self._log_anim.finished.connect(self._on_log_anim_finished)
def _copy_error_text(self):
QApplication.clipboard().setText(self._error_text)
self._btn_copy.setText("Copied")
self._btn_copy.setStyleSheet(self._copy_style_done)
QTimer.singleShot(1500, self._reset_copy_button)
def _reset_copy_button(self):
self._btn_copy.setText("Copy")
self._btn_copy.setStyleSheet(self._copy_style_normal)
def _toggle_log(self):
self._log_open = not self._log_open
self._btn_log.setText("Hide Log" if self._log_open else "Error Log")
rect = self._log_panel_geometry()
collapsed = QRect(rect.x(), rect.y(), rect.width(), 0)
expanded = QRect(rect.x(), rect.y(), rect.width(), self.LOG_PANEL_H)
self._log_anim.stop()
if self._log_open:
self._log_panel.setGeometry(collapsed)
self._log_panel.show()
self._log_fx.setOpacity(1.0)
self._log_anim.setStartValue(collapsed)
self._log_anim.setEndValue(expanded)
else:
self._log_anim.setStartValue(self._log_panel.geometry())
self._log_anim.setEndValue(collapsed)
self._log_anim.start()
def _on_log_anim_finished(self):
if not self._log_open:
self._log_panel.hide()
# ---------- public API ----------
def begin(self, host):
n = len(self.STEPS)
self._host = host or "the link"
self._active, self._prev = 0, 0
self._queue = []
self._done_at = [None] * n
self._change_at, self._active_since = -10000, 0
self._failed = False
self._error_text = ""
self._log_open = False
self._log_panel.hide()
self._btn_log.setText("Error Log")
self._reset_copy_button()
self._finish_cb, self._finish_armed = None, False
self._fail_color_anim.stop(); self._fail_color_t = 0.0
self._clock.restart()
self.setGeometry(self.parentWidget().rect())
self._reposition_buttons()
self.raise_()
self.show()
self._fade_to(1.0, self.FADE_IN_MS)
def set_phase(self, key):
if self._failed or key not in self._keys: return
idx = self._keys.index(key)
last = self._queue[-1] if self._queue else self._active
if idx > last: self._queue.append(idx)
def finish(self, callback):
"""Queue up "Done"; callback fires once it has been shown."""
last = self._queue[-1] if self._queue else self._active
for i in range(last + 1, len(self.STEPS)): self._queue.append(i)
self._finish_cb, self._finish_armed = callback, True
self._reposition_buttons()
def fail(self, message):
now = self._clock.elapsed()
self._failed, self._fail_at = True, now
self._prev, self._change_at = self._active, now
self._queue = []
self._error_text = message or "Unknown error"
self._log_text.setPlainText(self._error_text)
self._log_open = False
self._log_panel.hide()
self._btn_log.setText("Error Log")
self._finish_cb, self._finish_armed = None, False
self._fail_color_anim.stop()
self._fail_color_anim.setStartValue(self._fail_color_t)
self._fail_color_anim.setEndValue(1.0)
self._fail_color_anim.setDuration(self.FAIL_COLOR_MS)
self._fail_color_anim.start()
self._reposition_buttons()
def dismiss(self):
self._finish_cb, self._finish_armed = None, False
if self._log_open:
self._log_open = False
self._log_anim.stop()
self._log_panel.hide()
self._fade_to(0.0, self.FADE_OUT_MS)
# ---------- internals ----------
def _fade_to(self, target, ms):
self._fade.stop()
self._fade.setStartValue(self._alpha)
self._fade.setEndValue(float(target))
self._fade.setDuration(ms)
self._fade.setEasingCurve(QEasingCurve.Type.InOutSine)
self._fade.start()
def _on_fade_step(self, v):
self._alpha = float(v)
opaque = self._alpha >= 0.999
if opaque != self._opaque:
self._opaque = opaque
self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, opaque)
# Child widgets (real buttons/panel) don't fade on their own just
# because the parent's paintEvent sets an opacity - drive each
# one's own opacity effect off the same alpha so everything fades
# together as one unit.
self._cancel_fx.setOpacity(self._alpha if self._btn_cancel.isVisible() else 0.0)
self._retry_fx.setOpacity(self._alpha if self._btn_retry.isVisible() else 0.0)
self._log_btn_fx.setOpacity(self._alpha if self._btn_log.isVisible() else 0.0)
self._log_fx.setOpacity(self._alpha if self._log_panel.isVisible() else 0.0)
self.update()
def _on_fade_finished(self):
if self._alpha <= 0.001: self.hide()
def _on_fail_color_step(self, v):
self._fail_color_t = float(v)
self.update()
def showEvent(self, e):
self._tick.start()
self._refresh_button_effects()
super().showEvent(e)
def hideEvent(self, e):
self._tick.stop(); super().hideEvent(e)
def _refresh_button_effects(self):
"""Re-creates each button's/the log panel's QGraphicsOpacityEffect
from scratch instead of reusing the existing instance. This
guards against a real Qt quirk: when this overlay's ancestor
chain is hidden and shown again (e.g. switching away from the
Home tab and back while a failure is still on screen), a widget
under a QGraphicsOpacityEffect can keep showing its last cached
render - invisible or faded - even though it's fully visible and
clickable again as far as Qt's hit-testing is concerned. That's
exactly "buttons gone but still clickable". A brand new effect
instance has no stale cache to carry over."""
self._cancel_fx = self._fade_with_overlay(self._btn_cancel)
self._retry_fx = self._fade_with_overlay(self._btn_retry)
self._log_btn_fx = self._fade_with_overlay(self._btn_log)
self._log_fx = self._fade_with_overlay(self._log_panel)
self._cancel_fx.setOpacity(self._alpha if self._btn_cancel.isVisible() else 0.0)
self._retry_fx.setOpacity(self._alpha if self._btn_retry.isVisible() else 0.0)
self._log_btn_fx.setOpacity(self._alpha if self._btn_log.isVisible() else 0.0)
self._log_fx.setOpacity(self._alpha if self._log_panel.isVisible() else 0.0)
def eventFilter(self, obj, event):
if obj is self.parentWidget() and event.type() == QEvent.Type.Resize:
self.setGeometry(self.parentWidget().rect())
self._reposition_buttons()
if self._log_open:
self._log_anim.stop()
self._log_panel.setGeometry(self._log_panel_geometry())
return False
def _activate(self, idx, now):
for i in range(self._active, idx):
if self._done_at[i] is None: self._done_at[i] = now
self._prev, self._active = self._active, idx
self._change_at = self._active_since = now
if idx == len(self.STEPS) - 1: self._done_at[idx] = now
self._reposition_buttons()
def _on_tick(self):
now = self._clock.elapsed()
if self._queue and not self._failed and now - self._active_since >= self.MIN_DWELL_MS:
self._activate(self._queue.pop(0), now)
if self._finish_armed and not self._failed and self._active == len(self.STEPS) - 1 and not self._queue:
if now - self._active_since >= self.DONE_DWELL_MS:
cb, self._finish_cb, self._finish_armed = self._finish_cb, None, False
if cb: QTimer.singleShot(0, cb)
# Stage progression/dwell timing above always keeps running (so
# things don't stall while minimized), but repainting a window
# nobody can see is wasted power for zero benefit - skip it.
win = self.window()
if win is not None and win.isMinimized():
return
# Full repaint every tick: the ambient glow is large (a ~380px
# soft radial gradient) and its color is continuously animating
# between teal and red, so constraining updates to the small
# content/line rects (as a pure power optimization) left stale,
# hard-edged glow outside those rects - exactly the "rectangle"
# artifact. A plain gradient fill is cheap regardless of area, so
# the earlier partial-update split wasn't saving much that
# mattered - correctness wins here.
self.update()
def _center(self): return QPointF(self.width() / 2, self.height() * 0.46)
def _content_rect(self):
c = self._center(); return QRect(int(c.x()) - 390, int(c.y()) - 150, 780, 350)
def _line_rect(self): return QRect(0, self.height() - 16, self.width(), 16)
def _button_row_rect(self):
c = self._center()
return QRect(int(c.x() - 56), int(c.y() + 132), 112, 34)
def _log_panel_geometry(self):
c = self._center()
w = 460
return QRect(int(c.x() - w / 2), int(c.y() + 132 + 34 + 14), w, self.LOG_PANEL_H)
def _reposition_buttons(self):
cancel_visible = (not self._failed) and (not self._finish_armed) and self._active < len(self.STEPS) - 1
c = self._center()
if self._failed:
self._btn_retry.setGeometry(int(c.x() - 127), int(c.y() + 132), 120, 34)
self._btn_log.setGeometry(int(c.x() + 7), int(c.y() + 132), 120, 34)
# Visibility is purely state-driven (not gated on the current
# alpha) - the fade itself is handled by each button's own
# opacity effect in _on_fade_step, which reads this visibility to
# decide whether to fade to 0 or to the current alpha. Gating
# setVisible on alpha here would freeze a button hidden forever
# once _reposition_buttons happened to run at alpha==0 (e.g. the
# very start of begin()), since nothing re-shows it as alpha
# rises during the fade-in.
self._btn_cancel.setVisible(cancel_visible)
self._btn_retry.setVisible(self._failed)
self._btn_log.setVisible(self._failed)
if cancel_visible:
r = self._button_row_rect()
self._btn_cancel.setGeometry(r)
self._cancel_fx.setOpacity(self._alpha if self._btn_cancel.isVisible() else 0.0)
self._retry_fx.setOpacity(self._alpha if self._btn_retry.isVisible() else 0.0)
self._log_btn_fx.setOpacity(self._alpha if self._btn_log.isVisible() else 0.0)
if not self._failed:
self._log_panel.hide()
# ---------- painting ----------
def _lerp_color(self, c1, c2, t):
t = max(0.0, min(1.0, t))
return QColor(
int(c1.red() + (c2.red() - c1.red()) * t),
int(c1.green() + (c2.green() - c1.green()) * t),
int(c1.blue() + (c2.blue() - c1.blue()) * t),
)
def _font(self, px, weight=None, spacing=None):
f = QFont(self.font()); f.setPixelSize(px)
if weight is not None: f.setWeight(weight)
if spacing: f.setLetterSpacing(QFont.SpacingType.AbsoluteSpacing, spacing)
return f
def _draw_phase_text(self, p, idx, failed, opacity, dy, now, cx, cy):
base = p.opacity()
p.setOpacity(base * opacity)