-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2503 lines (2216 loc) · 120 KB
/
Copy pathmain.py
File metadata and controls
2503 lines (2216 loc) · 120 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 ctypes
import os
import json
import threading
import time
import queue
import subprocess
import shutil
import urllib.request
import webbrowser
import hashlib
import math
from datetime import datetime
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QPushButton, QStackedWidget,
QScrollArea, QFrame, QLineEdit, QProgressBar,
QSpacerItem, QSizePolicy, QComboBox, QGraphicsDropShadowEffect,
QSystemTrayIcon, QStyle, QGraphicsOpacityEffect, QMenu, QFileDialog,
QPlainTextEdit)
from PySide6.QtCore import (Qt, QThread, Signal, QSize, QObject,
QTimer, QUrl, QVariantAnimation, QPropertyAnimation, QEasingCurve,
QPoint, QParallelAnimationGroup, QSequentialAnimationGroup, QEvent,
QElapsedTimer, QRect, QRectF, QPointF)
from PySide6.QtGui import (QFont, QFontDatabase, QIcon, QPixmap, QImage, QColor,
QPainter, QPainterPath, QCursor, QDesktopServices, QAction,
QPen, QBrush, QLinearGradient, QRadialGradient, QFontMetrics)
try:
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('mycompany.myapp.1.0')
except Exception:
pass
try:
import yt_dlp
except Exception:
yt_dlp = None
repo_root = Path(__file__).resolve().parent
BASE_DIR = Path(__file__).resolve().parent
ICON_PATH = str(BASE_DIR / "icons/icon.ico")
src_dir = repo_root / "src"
cache_dir = repo_root / "cache"
thumb_dir = cache_dir / "thumbnails"
favicon_dir = cache_dir / "favicons"
thumb_dir.mkdir(parents=True, exist_ok=True)
favicon_dir.mkdir(parents=True, exist_ok=True)
if str(repo_root) not in sys.path: sys.path.insert(0, str(repo_root))
if src_dir.exists() and str(src_dir) not in sys.path: sys.path.insert(0, str(src_dir))
TEAL_ACCENT = "#00BFA5"
BG_DARK = "#121212"
SIDEBAR_DARK = "#181818"
CARD_BG = "#1E1E1E"
CARD_INNER_BG = "#282828"
INPUT_BG = "#333333"
TEXT_MAIN = "#FFFFFF"
TEXT_MUTED = "#8A8A8A"
ERROR_RED = "#FF5555"
ERROR_BG = "#2A1515"
_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(d in url.lower() for d in _AUDIO_ONLY_DOMAINS)
def _is_youtube_url(url):
return any(d in url.lower() for d in
("youtube.com","youtu.be","youtube-nocookie.com","music.youtube.com","m.youtube.com"))
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 "Web"
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":"Mozilla/5.0"})
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 fetch_formats(url):
try:
import importlib
module_name = "Fetcher" if _is_youtube_url(url) else "universal_scraper"
module = importlib.import_module(module_name)
for fn in ("fetch_formats","scrape_formats"):
if hasattr(module, fn): return getattr(module, fn)(url)
return {"ok": False, "error": f"{module_name} has no fetch function"}
except Exception as e:
return {"ok": False, "error": str(e)}
def fetcher_download(url, selected_fid=None, out_dir=None, is_audio=False, start_time=None, end_time=None):
import queue
import threading
import os
q = queue.Queue()
def format_size(b):
if not b: return "0 MB"
if b >= 1024 * 1024 * 1024: return f"{b / (1024**3):.2f} GB"
if b >= 1024 * 1024: return f"{b / (1024**2):.1f} MB"
return f"{b / 1024:.1f} KB"
def progress_hook(d):
if d.get('status') == 'downloading':
total = d.get('total_bytes') or d.get('total_bytes_estimate') or 0
downloaded = d.get('downloaded_bytes', 0)
percent = (downloaded / total) if total > 0 else 0.0
speed_bytes = d.get('speed') or 0
if speed_bytes > 1024 * 1024:
speed_str = f"{speed_bytes / (1024*1024):.1f} MB/s"
elif speed_bytes > 1024:
speed_str = f"{speed_bytes / 1024:.1f} KB/s"
else:
speed_str = f"{speed_bytes:.0f} B/s" if speed_bytes else "0 MB/s"
eta_sec = d.get('eta')
if eta_sec is not None:
m, s = divmod(int(eta_sec), 60)
h, m = divmod(m, 60)
eta_str = f"{h:02d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
else:
eta_str = "--:--"
q.put({
"type": "progress",
"percent": percent,
"speed": speed_str,
"eta": eta_str,
"downloaded": format_size(downloaded),
"size": format_size(total)
})
elif d.get('status') == 'finished':
q.put({
"type": "progress",
"percent": 1.0,
"speed": "Processing...",
"eta": "00:00",
"downloaded": "",
"size": ""
})
def run_dl():
try:
import glob
os.makedirs(out_dir, exist_ok=True)
ydl_opts = {
'outtmpl': os.path.join(out_dir, '%(title)s.%(ext)s'),
'quiet': True,
'no_warnings': True,
'progress_hooks': [progress_hook],
'concurrent_fragment_downloads': 8,
'merge_output_format': 'mp4',
'postprocessor_args': {
'ffmpeg': ['-avoid_negative_ts', 'make_zero']
}
}
if _is_youtube_url(url):
ydl_opts['extractor_args'] = {'youtube': ['player_client=tv,web_safari']}
ydl_opts['http_headers'] = {'Accept-Language': 'en-US,en;q=0.9'}
final_path_holder = {"path": None}
def _pp_hook(d):
if d.get('status') == 'finished':
info_d = d.get('info_dict') or {}
fp = info_d.get('filepath') or info_d.get('_filename')
if fp:
final_path_holder['path'] = fp
ydl_opts['postprocessor_hooks'] = [_pp_hook]
if is_audio:
ydl_opts['format'] = 'bestaudio/best'
ydl_opts['writethumbnail'] = True
ydl_opts['postprocessors'] = [
{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192'},
{'key': 'FFmpegMetadata'},
{'key': 'EmbedThumbnail'},
]
elif selected_fid:
ydl_opts['format'] = f"{selected_fid}+bestaudio/best"
else:
ydl_opts['format'] = 'bestvideo+bestaudio/best'
if start_time is not None and end_time is not None:
def range_func(info_dict, ydl):
return [{'start_time': start_time, 'end_time': end_time}]
ydl_opts['download_ranges'] = range_func
# force_keyframes_at_cuts already gets accurate cuts cheaply:
# yt-dlp re-encodes only the small slice right at each cut
# point and stream-copies everything else. Forcing a full
# '-c:v libx264' re-encode of the whole segment on top of
# that (as this used to) throws that efficiency away and
# makes ffmpeg software-encode the entire clip - that was
# the actual source of the high CPU usage during trimming.
ydl_opts['force_keyframes_at_cuts'] = True
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
if info is None:
raise Exception("Could not extract video information")
if info.get('_type') == 'playlist' and info.get('entries'):
info = next((e for e in info['entries'] if e), info)
try:
from yt_dlp.utils import sanitize_filename
except ImportError:
def sanitize_filename(s, **kwargs):
import re
return re.sub(r'(?u)[^-\w.]', '_', s)
base_title = info.get('title', 'Download')
current_title = base_title
sanitized = sanitize_filename(current_title, restricted=False)
counter = 1
while glob.glob(os.path.join(glob.escape(out_dir), f"{glob.escape(sanitized)}.*")):
current_title = f"{base_title} ({counter})"
sanitized = sanitize_filename(current_title, restricted=False)
counter += 1
info['title'] = current_title
ydl.process_ie_result(info, download=True)
resolved_path = final_path_holder["path"]
if not resolved_path:
try:
candidate = ydl.prepare_filename(info)
if candidate and os.path.exists(candidate):
resolved_path = candidate
except Exception:
pass
q.put({"type": "done", "filepath": resolved_path})
except Exception as e:
q.put({"type": "error", "message": str(e)})
t = threading.Thread(target=run_dl, daemon=True)
t.start()
while True:
try:
item = q.get(timeout=0.1)
yield item
if item.get("type") in ("done", "error"):
break
except queue.Empty:
if not t.is_alive():
yield {"type": "error", "message": "Download thread terminated unexpectedly"}
break
def get_rounded_pixmap(pixmap, radius):
if pixmap.isNull(): return pixmap
rounded = QPixmap(pixmap.size())
rounded.fill(Qt.GlobalColor.transparent)
painter = QPainter(rounded)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(0, 0, pixmap.width(), pixmap.height(), radius, radius)
painter.setClipPath(path)
painter.drawPixmap(0, 0, pixmap)
painter.end()
return rounded
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 [-12, 12, -8, 8, -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()
class ToastWidget(QFrame):
dismissed = Signal(object)
def __init__(self, message, parent=None, icon_pixmap=None, rich_text=False):
super().__init__(parent)
self.setWindowIcon(QIcon(ICON_PATH))
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: #EF4444; 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 ToastManager(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 = ToastWidget(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
def update_positions(self):
self._reposition_toasts(animate_last=False)
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()
class ModernScrollArea(QScrollArea):
def __init__(self, parent=None):
super().__init__(parent)
self.setWidgetResizable(True)
self.setFrameShape(QFrame.Shape.NoFrame)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setStyleSheet("""
QScrollArea { background-color: transparent; border: none; }
QScrollBar:vertical { width: 8px; background: transparent; margin: 0px; }
QScrollBar::handle:vertical { background-color: #444444; border-radius: 4px; min-height: 40px; }
QScrollBar::handle:vertical:hover { background-color: #666666; }
QScrollBar::handle:vertical:pressed { background-color: #00BFA5; }
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0px; border: none; background: none; }
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: none; }
""")
self._scroll_anim = QPropertyAnimation(self.verticalScrollBar(), b"value", self)
self._scroll_anim.setEasingCurve(QEasingCurve.Type.OutCubic)
self._scroll_anim.setDuration(180)
def wheelEvent(self, event):
delta = event.angleDelta().y()
if delta != 0:
vbar = self.verticalScrollBar()
current = self._scroll_anim.endValue() if self._scroll_anim.state() == QPropertyAnimation.State.Running else vbar.value()
step = -int(delta * 1.2)
target = max(vbar.minimum(), min(vbar.maximum(), current + step))
self._scroll_anim.stop()
self._scroll_anim.setStartValue(vbar.value())
self._scroll_anim.setEndValue(target)
self._scroll_anim.start()
event.accept()
else:
super().wheelEvent(event)
class SkeletonBox(QFrame):
def __init__(self, width=None, height=12, radius=6, parent=None):
super().__init__(parent)
self.setFixedHeight(height)
if width is not None:
self.setFixedWidth(width)
else:
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.setStyleSheet(f"background-color: {CARD_INNER_BG}; border-radius: {radius}px; border: none;")
effect = QGraphicsOpacityEffect(self)
self.setGraphicsEffect(effect)
anim = QPropertyAnimation(effect, b"opacity", self)
anim.setDuration(950)
anim.setStartValue(0.35)
anim.setKeyValueAt(0.5, 0.9)
anim.setEndValue(0.35)
anim.setEasingCurve(QEasingCurve.Type.InOutSine)
anim.setLoopCount(-1)
anim.start()
self._anim = anim
class ShimmerBox(QFrame):
"""A skeleton placeholder with a soft light band continuously sweeping
across it - the "flowing" shimmer look, rather than SkeletonBox's flat
pulse. Every instance shares one QTimer/clock (like the processing
overlay's racing line), so a whole card full of these costs one timer,
not one per block - and since they all read the same shared clock and
map it through their own width, the bands all sweep past together as
if gliding across one continuous surface."""
_instances = []
_timer = None
_clock = None
def __init__(self, width=None, height=12, radius=6, parent=None):
super().__init__(parent)
self.setFixedHeight(height)
if width is not None:
self.setFixedWidth(width)
else:
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self._radius = radius
self.setStyleSheet("background: transparent; border: none;")
ShimmerBox._instances.append(self)
if ShimmerBox._clock is None:
ShimmerBox._clock = QElapsedTimer()
ShimmerBox._clock.start()
if ShimmerBox._timer is None:
ShimmerBox._timer = QTimer()
ShimmerBox._timer.setInterval(33)
ShimmerBox._timer.timeout.connect(ShimmerBox._tick)
if not ShimmerBox._timer.isActive():
ShimmerBox._timer.start()
@classmethod
def _tick(cls):
# Belt-and-suspenders pruning for anything that got destroyed
# without going through unregister() - normal cleanup is
# deterministic (see unregister/_clear_home_slot), this is just
# a safety net so a missed case can't silently accumulate.
alive = []
for w in cls._instances:
try:
win = w.window()
if w.isVisible() and not (win is not None and win.isMinimized()):
w.update()
alive.append(w)
except RuntimeError:
pass
cls._instances = alive
if not cls._instances and cls._timer is not None:
cls._timer.stop()
@classmethod
def unregister(cls, box):
"""Explicit, immediate removal - called the moment a skeleton card
is discarded, rather than waiting on Qt's deferred deleteLater()
(which only runs once the event loop is idle) or on isVisible()
happening to already read False by then. Without this, a
ShimmerBox whose parent widget was queued for deletion but hadn't
actually been destroyed yet stayed in _instances - still visible,
still getting update()+repainted every tick - and every fresh
link pasted in the same session added more of these on top,
so the paint cost (and CPU/power draw) only ever grew across a
session instead of being released when a card was replaced."""
if box in cls._instances:
cls._instances.remove(box)
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(0, 0, self.width(), self.height(), self._radius, self._radius)
p.setClipPath(path)
p.fillRect(self.rect(), QColor(CARD_INNER_BG))
now = ShimmerBox._clock.elapsed()
period = 1400.0
t = (now % period) / period
w = float(self.width())
band_w = max(60.0, w * 0.5)
x = -band_w + (w + band_w) * t
g = QLinearGradient(x, 0, x + band_w, 0)
c0 = QColor(255, 255, 255, 0)
c1 = QColor(255, 255, 255, 26)
g.setColorAt(0.0, c0); g.setColorAt(0.5, c1); g.setColorAt(1.0, c0)
p.fillRect(self.rect(), QBrush(g))
p.end()
class FilterTab(QFrame):
clicked = Signal(str)
def __init__(self, name, count, is_active=False, parent=None):
super().__init__(parent)
self.name, self._is_active, self._count = name, is_active, count
self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.setFixedHeight(32)
self.layout = QHBoxLayout(self)
self.layout.setContentsMargins(16, 0, 16, 0)
self.layout.setSpacing(8)
self.text_lbl = QLabel(name)
self.text_lbl.setFont(QFont("Roboto", 10, QFont.Weight.Medium))
self.badge_lbl = QLabel(str(count if count < 100 else "99+"))
self.badge_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.badge_lbl.setFixedHeight(20)
self.badge_lbl.setMinimumWidth(16)
self.layout.addWidget(self.text_lbl)
self.layout.addWidget(self.badge_lbl)
self._anim = QVariantAnimation(self)
self._anim.setDuration(250)
self._anim.valueChanged.connect(self._on_anim_step)
self._current_text = QColor(TEAL_ACCENT) if is_active else QColor("#E0E0E0")
self._current_badge_bg = QColor("#1B3D37") if is_active else QColor("#3D3D3D")
self._current_bg = QColor("#142C28") if is_active else QColor("#2A2A2A")
self._update_stylesheet()
def update_count(self, count):
if self._count != count:
self._count = count
self.badge_lbl.setText(str(count if count < 100 else "99+"))
def set_active(self, active):
if self._is_active == active: return
self._is_active = active
self._animate_colors(QColor(TEAL_ACCENT) if active else QColor("#E0E0E0"),
QColor("#1B3D37") if active else QColor("#3D3D3D"),
QColor("#142C28") if active else QColor("#2A2A2A"), 250)
def _animate_colors(self, t_text, t_badge, t_bg, duration):
self._anim.stop()
self._anim.setDuration(duration)
self._start_text, self._start_badge_bg, self._start_bg = self._current_text, self._current_badge_bg, self._current_bg
self._target_text, self._target_badge_bg, self._target_bg = t_text, t_badge, t_bg
self._anim.setStartValue(0.0)
self._anim.setEndValue(1.0)
self._anim.start()
def _on_anim_step(self, progress):
self._current_text = self._interpolate_color(self._start_text, self._target_text, progress)
self._current_badge_bg = self._interpolate_color(self._start_badge_bg, self._target_badge_bg, progress)
self._current_bg = self._interpolate_color(self._start_bg, self._target_bg, progress)
self._update_stylesheet()
def _interpolate_color(self, c1, c2, factor):
return QColor(int(c1.red() + (c2.red() - c1.red()) * factor),
int(c1.green() + (c2.green() - c1.green()) * factor),
int(c1.blue() + (c2.blue() - c1.blue()) * factor))
def _update_stylesheet(self):
text, badge_bg, bg = self._current_text.name(), self._current_badge_bg.name(), self._current_bg.name()
self.setStyleSheet(f"FilterTab {{ background-color: {bg}; border-radius: 16px; border: none; }}")
self.text_lbl.setStyleSheet(f"color: {text}; border: none; background: transparent;")
self.badge_lbl.setStyleSheet(f'background-color: {badge_bg}; color: {text}; border-radius: 10px; min-width: 14px; font-size: 11px; font-weight: bold; padding: 0px 8px; border: none;')
def enterEvent(self, event):
if not self._is_active: self._animate_colors(QColor("#FFFFFF"), QColor("#555555"), QColor("#333333"), 150)
super().enterEvent(event)
def leaveEvent(self, event):
if not self._is_active: self._animate_colors(QColor("#E0E0E0"), QColor("#3D3D3D"), QColor("#2A2A2A"), 150)
super().leaveEvent(event)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton: self.clicked.emit(self.name)
class FilterTabBar(QFrame):
filter_changed = Signal(str)
def __init__(self, filters, parent=None):
super().__init__(parent)
self.setFixedHeight(44)
self.tabs = {}
self.active_tab = filters[0]
self.indicator = QFrame(self)
self.indicator.setStyleSheet("background-color: transparent; border: none; border-radius: 16px;")
self.anim = QPropertyAnimation(self.indicator, b"geometry")
self.anim.setDuration(350)
self.anim.setEasingCurve(QEasingCurve.Type.InOutCubic)
self.layout = QHBoxLayout(self)
self.layout.setContentsMargins(0, 6, 0, 6)
self.layout.setSpacing(10)
for f_name in filters:
tab = FilterTab(f_name, 0, is_active=(f_name == self.active_tab))
tab.clicked.connect(self._on_tab_clicked)
self.layout.addWidget(tab)
self.tabs[f_name] = tab
self.layout.addStretch()
def update_counts(self, counts):
for f_name, tab in self.tabs.items():
if f_name in counts: tab.update_count(counts[f_name])
if not self.anim.state() == QPropertyAnimation.State.Running and self.active_tab in self.tabs:
self.indicator.setGeometry(self.tabs[self.active_tab].geometry())
def _on_tab_clicked(self, f_name):
if f_name == self.active_tab: return
prev_tab = self.active_tab
self.active_tab = f_name
self.tabs[prev_tab].set_active(False)
self.tabs[f_name].set_active(True)
self.anim.stop()
self.anim.setStartValue(self.indicator.geometry())
self.anim.setEndValue(self.tabs[f_name].geometry())
self.anim.start()
self.filter_changed.emit(f_name)
def showEvent(self, event):
super().showEvent(event)
if self.active_tab in self.tabs: self.indicator.setGeometry(self.tabs[self.active_tab].geometry())
def resizeEvent(self, event):
super().resizeEvent(event)
if self.active_tab in self.tabs and self.anim.state() != QPropertyAnimation.State.Running:
self.indicator.setGeometry(self.tabs[self.active_tab].geometry())
class SidebarNavButton(QFrame):
clicked = Signal(int)
def __init__(self, name, icon, idx, is_active=False, parent=None):
super().__init__(parent)
self.idx = idx
self._is_active = is_active
self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
self.setFixedHeight(44)
self.setStyleSheet("SidebarNavButton { background: transparent; border: none; }")
layout = QHBoxLayout(self)
layout.setContentsMargins(11, 0, 11, 0)
layout.setSpacing(12)
self.icon_lbl = QLabel()
self.icon_lbl.setPixmap(icon.pixmap(22, 22))
self.icon_lbl.setFixedSize(22, 22)
self.icon_lbl.setStyleSheet("background: transparent; border: none;")
self.text_lbl = QLabel(name)
self.text_lbl.setFont(QFont("Roboto", 11, QFont.Weight.Medium))
self.text_lbl.setMinimumWidth(0)
layout.addWidget(self.icon_lbl)
layout.addWidget(self.text_lbl, 1)
self._color_anim = QVariantAnimation(self)
self._color_anim.setDuration(220)
self._color_anim.valueChanged.connect(self._on_color_step)
self._current_text = QColor(TEAL_ACCENT) if is_active else QColor(TEXT_MUTED)
self._current_bg = QColor(20, 44, 40, 255) if is_active else QColor(0, 0, 0, 0)
self._update_text_color()
self._ripple_pos = QPoint(0, 0)
self._ripple_radius = 0.0
self._ripple_opacity = 0.0
self._ripple_anim = QVariantAnimation(self)
self._ripple_anim.setDuration(400)
self._ripple_anim.valueChanged.connect(self._on_ripple_step)
self._ripple_anim.setEasingCurve(QEasingCurve.Type.OutQuad)
self._collapsed = False
self._text_fade_anim = None
self._text_opacity = QGraphicsOpacityEffect(self.text_lbl)
self.text_lbl.setGraphicsEffect(self._text_opacity)
self._text_opacity.setOpacity(1.0)
def _update_text_color(self):
text = self._current_text.name()
self.text_lbl.setStyleSheet(f"color: {text}; border: none; background: transparent;")
self.update()
def _on_color_step(self, progress):
self._current_text = self._lerp(self._start_text, self._target_text, progress)
self._current_bg = self._lerp(self._start_bg, self._target_bg, progress)
self._update_text_color()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
bg_path = QPainterPath()
bg_path.addRoundedRect(0, 0, self.width(), self.height(), 12, 12)
painter.fillPath(bg_path, self._current_bg)
if self._ripple_opacity > 0:
painter.setClipPath(bg_path)
ripple_color = QColor(TEAL_ACCENT)
ripple_color.setAlphaF(self._ripple_opacity)
painter.setBrush(ripple_color)
painter.setPen(Qt.PenStyle.NoPen)
painter.drawEllipse(self._ripple_pos, self._ripple_radius, self._ripple_radius)
def set_active(self, active, animate=True):
if self._is_active == active:
return
self._is_active = active
target_text = QColor(TEAL_ACCENT) if active else QColor(TEXT_MUTED)
target_bg = QColor(20, 44, 40, 255) if active else QColor(0, 0, 0, 0)
if animate:
self._animate_to(target_text, target_bg, 220)
else:
self._current_text, self._current_bg = target_text, target_bg
self._update_text_color()
def _animate_to(self, target_text, target_bg, duration):
self._color_anim.stop()
self._color_anim.setDuration(duration)
self._start_text, self._start_bg = self._current_text, self._current_bg
self._target_text, self._target_bg = target_text, target_bg
self._color_anim.setStartValue(0.0)
self._color_anim.setEndValue(1.0)
self._color_anim.start()
def _lerp(self, c1, c2, 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),
int(c1.alpha() + (c2.alpha() - c1.alpha()) * t),
)
def enterEvent(self, event):
if not self._is_active:
self._animate_to(QColor(TEXT_MUTED), QColor(255, 255, 255, 18), 150)
super().enterEvent(event)
def leaveEvent(self, event):
if not self._is_active:
self._animate_to(QColor(TEXT_MUTED), QColor(0, 0, 0, 0), 150)
super().leaveEvent(event)
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._ripple_pos = event.position().toPoint()
self._ripple_radius = 0.0
self._ripple_opacity = 0.35
self._ripple_anim.stop()
self._ripple_anim.setStartValue(0.0)
self._ripple_anim.setEndValue(1.0)
self._ripple_anim.start()
self.clicked.emit(self.idx)
super().mousePressEvent(event)
def _on_ripple_step(self, progress):
max_radius = self.width() * 1.5
self._ripple_radius = max_radius * progress
self._ripple_opacity = 0.35 * (1.0 - progress)
self.update()
def set_collapsed(self, collapsed, animate=True):
self._collapsed = collapsed
if collapsed:
self._text_opacity.setOpacity(0.0)
else:
self._text_opacity.setOpacity(1.0)
def begin_collapse_fade(self):
self._collapsed = True
if self._text_fade_anim and self._text_fade_anim.state() == QPropertyAnimation.State.Running:
self._text_fade_anim.stop()
anim = QPropertyAnimation(self._text_opacity, b"opacity", self)
anim.setDuration(160)
anim.setStartValue(self._text_opacity.opacity())
anim.setEndValue(0.0)
anim.setEasingCurve(QEasingCurve.Type.OutCubic)
self._text_fade_anim = anim
anim.start()
def begin_expand_layout(self):
self._collapsed = False
if self._text_fade_anim and self._text_fade_anim.state() == QPropertyAnimation.State.Running:
self._text_fade_anim.stop()
anim = QPropertyAnimation(self._text_opacity, b"opacity", self)
anim.setDuration(200)
anim.setStartValue(self._text_opacity.opacity())
anim.setEndValue(1.0)
anim.setEasingCurve(QEasingCurve.Type.InCubic)
self._text_fade_anim = anim
anim.start()
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):