Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
4068 lines (3767 loc) · 182 KB
/
Copy pathmain.py
File metadata and controls
4068 lines (3767 loc) · 182 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# SortView (سورتویو) — fast thumbnail browsing and safe file sorting.
# Copyright (c) 2026 Mohammad Jafari
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# SPDX-License-Identifier: GPL-3.0-or-later
# ----------------------------------------------------------------------------
"""
SortView — Qt6 edition
یک ابزار دسکتاپ برای مرور سریع فایلها و انتقال امن آنها به پوشههای دستهبندی.
نسخهی فعلی ابتدا PyQt6 را استفاده میکند؛ اگر نصب نبود، برای سازگاری PySide6 و
در نهایت PyQt5 را هم میپذیرد. پخش ویدیو و صدا با موتور چندرسانهای Qt انجام
میشود (بکاند FFmpeg داخل خود PyQt6) — بدون VLC و بدون ffplay. ظاهر و کارتهای
نوع فایل اختصاصی همین پروژه است و همهی آیکونهای
پوشهی assets نیز اثر اصلی و تازهساختهی همین پروژه هستند (بدون لوگوی برندها).
Bilingual UI (English / Persian) lives in app_i18n.py: the first run follows
the OS display language, the header combo switches instantly (with RTL for
Persian) and the choice is persisted in user_data/config.json.
"""
from __future__ import annotations
import hashlib
import io
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import threading
import time
import traceback
import zipfile
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from pathlib import Path
from shutil import which
from typing import Iterable, List, Optional, Tuple
import app_i18n
from app_i18n import t
# -----------------------------------------------------------------------------
# Qt binding: prefer PyQt6, then PySide6, then PyQt5 as a compatibility fallback.
# NOTE: only PyQt6 is tested, shipped and supported. The PySide6/PyQt5 branches
# exist so the source still starts on other machines, but bugs reported against
# them are out of scope (see README — PyQt6 >= 6.9 is the supported binding).
# -----------------------------------------------------------------------------
try: # Preferred
from PyQt6 import QtCore, QtGui, QtWidgets
Signal = QtCore.pyqtSignal
QT_API = "PyQt6"
QT6 = True
except Exception:
try: # Also Qt6 and API-wise very close
from PySide6 import QtCore, QtGui, QtWidgets
Signal = QtCore.Signal
QT_API = "PySide6"
QT6 = True
except Exception: # Untested last-resort fallback — not supported, see README.
from PyQt5 import QtCore, QtGui, QtWidgets
Signal = QtCore.pyqtSignal
QT_API = "PyQt5"
QT6 = False
Qt = QtCore.Qt
QTimer = QtCore.QTimer
QSize = QtCore.QSize
QUrl = QtCore.QUrl
QPixmap = QtGui.QPixmap
QImageReader = QtGui.QImageReader
QMovie = QtGui.QMovie
QIcon = QtGui.QIcon
QKeySequence = QtGui.QKeySequence
QDesktopServices = QtGui.QDesktopServices
QShortcut = getattr(QtGui, "QShortcut", getattr(QtWidgets, "QShortcut", None))
# Video and audio playback, the one bundled engine: Qt Multimedia. It ships
# inside the PyQt6/PySide6 wheels (FFmpeg backend included), so media plays
# in-app with NO VLC, no ffplay and no other external runtime. The dormant
# libVLC/ffplay branches below only wake up on dev machines that happen to
# have python-vlc or ffplay installed; the portable build ships none of them.
if QT_API == "PyQt5":
HAS_QTMEDIA = False
QTMEDIA_IMPORT_ERROR = "Qt Multimedia is not available on PyQt5"
else:
try:
if QT_API == "PyQt6":
from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer
from PyQt6.QtMultimediaWidgets import QVideoWidget
else:
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
HAS_QTMEDIA = True
QTMEDIA_IMPORT_ERROR = ""
except Exception as _qtmedia_exc:
HAS_QTMEDIA = False
QTMEDIA_IMPORT_ERROR = f"{type(_qtmedia_exc).__name__}: {_qtmedia_exc}"
def _qt_value(owner, enum_name: str, member_name: str, legacy_name: Optional[str] = None, default=None):
"""Return Qt6 enum member if present, otherwise the Qt5 legacy attribute."""
enum_obj = getattr(owner, enum_name, None)
if enum_obj is not None and hasattr(enum_obj, member_name):
return getattr(enum_obj, member_name)
if legacy_name is None:
legacy_name = member_name
return getattr(owner, legacy_name, default)
ALIGN_CENTER = _qt_value(Qt, "AlignmentFlag", "AlignCenter", default=0)
# Media status/error members used by QtVideoWidget's health check.
MEDIA_NOMEDIA = _qt_value(QMediaPlayer, "MediaStatus", "NoMedia", default=None) if HAS_QTMEDIA else None
MEDIA_INVALID = _qt_value(QMediaPlayer, "MediaStatus", "InvalidMedia", default=None) if HAS_QTMEDIA else None
MEDIA_NOERROR = _qt_value(QMediaPlayer, "Error", "NoError", default=None) if HAS_QTMEDIA else None
MEDIA_END = _qt_value(QMediaPlayer, "MediaStatus", "EndOfMedia", default=None) if HAS_QTMEDIA else None
MEDIA_STOPPED = _qt_value(QMediaPlayer, "PlaybackState", "StoppedState", default=None) if HAS_QTMEDIA else None
MEDIA_PLAYING = _qt_value(QMediaPlayer, "PlaybackState", "PlayingState", default=None) if HAS_QTMEDIA else None
ALIGN_LEFT = _qt_value(Qt, "AlignmentFlag", "AlignLeft", default=0)
ALIGN_TOP = _qt_value(Qt, "AlignmentFlag", "AlignTop", default=0)
KEEP_ASPECT = _qt_value(Qt, "AspectRatioMode", "KeepAspectRatio", default=1)
SMOOTH = _qt_value(Qt, "TransformationMode", "SmoothTransformation", default=1)
HORIZONTAL = _qt_value(Qt, "Orientation", "Horizontal", default=1)
USER_ROLE = _qt_value(Qt, "ItemDataRole", "UserRole", default=32)
WA_NATIVE_WINDOW = _qt_value(Qt, "WidgetAttribute", "WA_NativeWindow", default=100)
TEXT_SELECTABLE = _qt_value(Qt, "TextInteractionFlag", "TextSelectableByMouse", default=1)
LTR = _qt_value(Qt, "LayoutDirection", "LeftToRight", default=0)
RTL = _qt_value(Qt, "LayoutDirection", "RightToLeft", default=1)
POINTING_HAND = _qt_value(Qt, "CursorShape", "PointingHandCursor", default=None)
ViewMode_Icon = _qt_value(QtWidgets.QListView, "ViewMode", "IconMode")
Movement_Static = _qt_value(QtWidgets.QListView, "Movement", "Static")
Resize_Adjust = _qt_value(QtWidgets.QListView, "ResizeMode", "Adjust")
Selection_Extended = _qt_value(QtWidgets.QAbstractItemView, "SelectionMode", "ExtendedSelection")
Dialog_Accepted = _qt_value(QtWidgets.QDialog, "DialogCode", "Accepted")
OkButton = _qt_value(QtWidgets.QDialogButtonBox, "StandardButton", "Ok")
CancelButton = _qt_value(QtWidgets.QDialogButtonBox, "StandardButton", "Cancel")
ActionRole = _qt_value(QtWidgets.QDialogButtonBox, "ButtonRole", "ActionRole")
AcceptRole = _qt_value(QtWidgets.QMessageBox, "ButtonRole", "AcceptRole")
YesRole = _qt_value(QtWidgets.QMessageBox, "ButtonRole", "YesRole")
RejectRole = _qt_value(QtWidgets.QMessageBox, "ButtonRole", "RejectRole")
MsgBox_Yes = _qt_value(QtWidgets.QMessageBox, "StandardButton", "Yes")
MsgBox_No = _qt_value(QtWidgets.QMessageBox, "StandardButton", "No")
def _enum_int(value) -> int:
try:
return int(value)
except Exception:
return int(getattr(value, "value", value))
def _is_dialog_accepted(result) -> bool:
return _enum_int(result) == _enum_int(Dialog_Accepted)
# ---------------- early portable resource paths ----------------
SOURCE_DIR = Path(__file__).resolve().parent
RESOURCE_DIR = Path(getattr(sys, "_MEIPASS", SOURCE_DIR))
RUNTIME_DIR = Path(sys.executable).resolve().parent if getattr(sys, "frozen", False) else SOURCE_DIR
def _prepend_env_path(path: Path) -> None:
try:
if path.exists():
os.environ["PATH"] = str(path) + os.pathsep + os.environ.get("PATH", "")
if sys.platform == "win32" and hasattr(os, "add_dll_directory"):
try:
os.add_dll_directory(str(path))
except Exception:
pass
except Exception:
pass
def configure_portable_runtime() -> None:
"""Expose bundled command-line tools and VLC runtime before optional imports."""
for base in (RESOURCE_DIR / "bin", RUNTIME_DIR / "bin"):
_prepend_env_path(base)
vlc_dir = base / "vlc"
_prepend_env_path(vlc_dir)
libvlc = vlc_dir / "libvlc.dll"
if libvlc.exists():
os.environ.setdefault("PYTHON_VLC_LIB_PATH", str(libvlc))
os.environ.setdefault("PYTHON_VLC_MODULE_PATH", str(vlc_dir))
plugins = vlc_dir / "plugins"
if plugins.exists():
os.environ.setdefault("VLC_PLUGIN_PATH", str(plugins))
configure_portable_runtime()
# ---------------- optional non-Qt dependencies ----------------
try:
from PIL import Image, ImageDraw, ImageFont
HAS_PIL = True
except Exception:
HAS_PIL = False
# Decompression-bomb guard: refuse absurdly large images (DoS protection).
if HAS_PIL:
try:
Image.MAX_IMAGE_PIXELS = min(int(Image.MAX_IMAGE_PIXELS or 89_478_485), 64_000_000)
except Exception:
Image.MAX_IMAGE_PIXELS = 64_000_000
try:
import pymupdf # PyMuPDF (new import name; "import fitz" is deprecated)
HAS_FITZ = True
except Exception:
try:
import fitz as pymupdf # very old PyMuPDF
HAS_FITZ = True
except Exception:
HAS_FITZ = False
try:
import rarfile
HAS_RAR = True
except Exception:
HAS_RAR = False
try:
import py7zr
HAS_7Z = True
except Exception:
HAS_7Z = False
try:
import vlc
VLC_AVAILABLE = True
except Exception:
VLC_AVAILABLE = False
# ---------------- paths & constants ----------------
ASSETS_DIR = RESOURCE_DIR / "assets"
ICONS_DIR = ASSETS_DIR / "icons"
APP_ICON = ASSETS_DIR / "icon.png"
APP_FONT = ASSETS_DIR / "Vazirmatn-Regular.ttf"
# Portable layout: config/cache/category sets are written next to the source file
# during development and next to the executable after PyInstaller build.
APP_DIR = RUNTIME_DIR / "user_data"
try:
APP_DIR.mkdir(parents=True, exist_ok=True)
except OSError:
# Read-only install location (e.g. Program Files): instead of crashing,
# keep the portable data in a writable per-user folder.
_fb_base = Path(os.environ.get("LOCALAPPDATA") or (Path.home() / ".filesorterviewer"))
APP_DIR = _fb_base / "SortView" / "user_data"
APP_DIR.mkdir(parents=True, exist_ok=True)
LOG_FILE = APP_DIR / "app.log"
THUMB_CACHE = APP_DIR / "thumbs"
THUMB_CACHE.mkdir(parents=True, exist_ok=True)
CONFIG_FILE = APP_DIR / "config.json"
CATEGORY_SETS_DIR = APP_DIR / "category_sets"
CATEGORY_SETS_DIR.mkdir(parents=True, exist_ok=True)
# Startup language: the saved user choice (config.json "language") wins,
# otherwise the OS display language is auto-detected. Switchable in the header.
app_i18n.load_saved_language(CONFIG_FILE)
def log_exception(context: str, exc: Optional[BaseException] = None) -> None:
try:
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] {context}\n")
if exc is not None:
f.write(f"{type(exc).__name__}: {exc}\n")
f.write(traceback.format_exc())
except Exception:
pass
def _global_excepthook(exc_type, exc, tb):
try:
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] UNHANDLED EXCEPTION\n")
traceback.print_exception(exc_type, exc, tb, file=f)
except Exception:
pass
try:
sys.__excepthook__(exc_type, exc, tb)
except Exception:
pass
sys.excepthook = _global_excepthook
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tiff", ".tif", ".jxl"}
ANIM_EXTS = {".gif"}
VIDEO_EXTS = {".mp4", ".mkv", ".avi", ".mov", ".webm", ".wmv", ".flv", ".mpeg", ".mpg", ".m4v", ".ts"}
AUDIO_EXTS = {".mp3", ".wav", ".flac", ".aac", ".ogg", ".opus", ".m4a", ".wma"}
DOC_EXTS = {".pdf", ".txt", ".md", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".epub"}
ARCHIVE_EXTS = {".zip", ".rar", ".7z", ".tar", ".gz"}
SUBTITLE_EXTS = {".srt", ".ass", ".ssa", ".vtt", ".sub", ".idx"}
CODE_EXTS = {".py", ".js", ".ts", ".html", ".css", ".json", ".xml", ".yaml", ".yml", ".cpp", ".c", ".h", ".go", ".php", ".rb", ".java", ".rs"}
DEFAULT_THUMB = 168
HIGH_PREVIEW_MULT = 3
SAFE_MAX_IMAGE_DIM = 2400
# Archive-bomb guard: never read more than this from a single archive entry
# while hunting for a preview image.
MAX_ARCHIVE_IMAGE_BYTES = 64 * 1024 * 1024
CPU_COUNT = os.cpu_count() or 4
THUMB_BATCH_SIZE = max(8, min(32, CPU_COUNT * 2))
THUMB_MAX_WORKERS = max(4, min(16, CPU_COUNT))
THUMB_MAX_INFLIGHT = THUMB_MAX_WORKERS * 3
VIDEO_THUMB_PARALLEL = max(2, min(8, max(2, CPU_COUNT // 2)))
VIDEO_THUMB_SEMAPHORE = threading.BoundedSemaphore(VIDEO_THUMB_PARALLEL)
TYPE_CARD_MEM = {}
TRANSFER_CHUNK_SIZE = 2 * 1024 * 1024
EXT_ICON = {
".mp4": "video", ".mkv": "video", ".avi": "video", ".mov": "video", ".webm": "video", ".wmv": "video", ".flv": "video", ".mpeg": "video", ".mpg": "video", ".m4v": "video",
".mp3": "audio", ".wav": "audio", ".flac": "audio", ".aac": "audio", ".ogg": "audio", ".opus": "audio", ".m4a": "audio",
".png": "image", ".jpg": "image", ".jpeg": "image", ".bmp": "image", ".webp": "image", ".tiff": "image", ".gif": "image",
".zip": "zip", ".rar": "zip", ".7z": "zip", ".tar": "zip", ".gz": "zip",
".pdf": "pdf", ".txt": "document", ".md": "markdown", ".doc": "word", ".docx": "word", ".xls": "table", ".xlsx": "table", ".csv": "table", ".ppt": "powerpoint", ".pptx": "powerpoint", ".epub": "epub",
".py": "python", ".js": "javascript", ".jsx": "javascript", ".ts": "typescript", ".tsx": "typescript", ".html": "html", ".htm": "html", ".css": "css", ".json": "json", ".xml": "xml", ".yaml": "yaml", ".yml": "yaml", ".cpp": "cpp", ".c": "c", ".h": "c", ".go": "go", ".php": "php", ".rb": "ruby", ".java": "java", ".rs": "rust", ".log": "log",
".exe": "exe", ".msi": "exe", ".bat": "console", ".cmd": "console", ".ps1": "console", ".sh": "console",
".srt": "subtitles", ".ass": "subtitles", ".ssa": "subtitles", ".vtt": "subtitles", ".sub": "subtitles", ".idx": "subtitles",
}
GROUP_STYLE = {
"video": ("#5b7cf5", "#33247e", "VIDEO"),
"audio": ("#2dd4bf", "#0f766e", "AUDIO"),
"image": ("#38bdf8", "#1e3a8a", "IMAGE"),
"archive": ("#fbbf24", "#92400e", "ARCHIVE"),
"doc": ("#fb7185", "#9f1239", "DOC"),
"sub": ("#e879a9", "#9d2457", "SUB"),
"code": ("#a3e635", "#3f6212", "CODE"),
"exe": ("#94a3b8", "#334155", "APP"),
"other": ("#8b98ad", "#25334a", "FILE"),
}
# Six visually distinct themes, ordered light -> dark for the picker dropdown.
# "dim" was removed in 1.7.0: its colours were nearly identical to Dark
# (ΔE < 10 on background and panel) and it only differed by its blue accent.
# danger_bg is the solid fill used on DangerBtn:hover — it must stay dark
# enough for WHITE text (>= 4.5:1), which the text-colour "danger" token
# alone can never guarantee on its own.
THEMES = {
"light": {
"label": "Light", "bg": "#f3f5f9", "panel": "#ffffff", "panel2": "#f6f8fb", "card": "#ffffff",
"border": "#c6cfdb", "hover": "#e8edf4", "sel": "#d3deee", "text": "#1c2430", "muted": "#4f5965",
"accent": "#3d5af1", "accent2": "#6a5cff", "danger": "#dc2626", "danger_bg": "#b91c1c", "preview_bg": "#e7ebf2",
},
"paper": {
"label": "Paper", "bg": "#f2ebdc", "panel": "#fbf7ec", "panel2": "#f6f0e1", "card": "#fffdf6",
"border": "#cdbf9f", "hover": "#ebe2cc", "sel": "#e2d3b0", "text": "#2f2819", "muted": "#5a503c",
"accent": "#b4530a", "accent2": "#8f4108", "danger": "#b91c1c", "danger_bg": "#991b1b", "preview_bg": "#e8dfc9",
},
"graphite": {
"label": "Graphite", "bg": "#24272d", "panel": "#2d3138", "panel2": "#343941", "card": "#353a42",
"border": "#4b515c", "hover": "#3a4049", "sel": "#34494e", "text": "#eceef1", "muted": "#aab0ba",
"accent": "#0b7f81", "accent2": "#096669", "danger": "#ff6b66", "danger_bg": "#dc2626", "preview_bg": "#1b1d22",
},
"dark": {
"label": "Dark", "bg": "#0c111a", "panel": "#111927", "panel2": "#131b29", "card": "#141d2c",
"border": "#34455f", "hover": "#182338", "sel": "#22344f", "text": "#e7edf6", "muted": "#93a1b5",
"accent": "#3d5af1", "accent2": "#6a5cff", "danger": "#ef4444", "danger_bg": "#dc2626", "preview_bg": "#070a10",
},
"forest": {
"label": "Forest", "bg": "#0e1612", "panel": "#142019", "panel2": "#192720", "card": "#1a2921",
"border": "#2f4538", "hover": "#1e3027", "sel": "#244235", "text": "#e6efe9", "muted": "#95ab9f",
"accent": "#19804f", "accent2": "#13683f", "danger": "#ff7468", "danger_bg": "#dc2626", "preview_bg": "#09100c",
},
"amoled": {
"label": "AMOLED", "bg": "#000000", "panel": "#0d0d12", "panel2": "#111117", "card": "#13131a",
"border": "#2b2b38", "hover": "#1a1a24", "sel": "#23233a", "text": "#f2f2f5", "muted": "#9a9aa8",
"accent": "#6a5af0", "accent2": "#5a49e0", "danger": "#ff5c7a", "danger_bg": "#e11d48", "preview_bg": "#000000",
},
}
def theme_color_icon(theme_key: str, size: int = 18) -> "QtGui.QIcon":
"""Two-colour circle for the theme picker dropdown.
Left half = theme background, right half = accent colour, with a thin
border ring, so the user sees the palette before choosing it.
Rendered at 2x device pixels for crisp edges on scaled displays.
"""
c = THEMES.get(theme_key, {})
try:
# Qt6 (PyQt6) scopes every enum, PyQt5/PySide6 legacy access differs —
# resolve through the same _qt_value helper the rest of the file uses.
TRANSPARENT = _qt_value(Qt, "GlobalColor", "transparent")
NO_PEN = _qt_value(Qt, "PenStyle", "NoPen")
NO_BRUSH = _qt_value(Qt, "BrushStyle", "NoBrush")
d = size * 2
pm = QPixmap(d, d)
pm.fill(TRANSPARENT)
p = QtGui.QPainter(pm)
hint = getattr(QtGui.QPainter, "RenderHint", None)
aa = hint.Antialiasing if hint is not None else getattr(QtGui.QPainter, "Antialiasing", None)
if aa is not None:
p.setRenderHint(aa)
rect = QtCore.QRectF(2.0, 2.0, d - 4.0, d - 4.0)
p.setPen(NO_PEN)
p.setClipRect(QtCore.QRectF(rect.left(), rect.top(), rect.width() / 2.0, rect.height()))
p.setBrush(QtGui.QColor(c.get("bg", "#222222")))
p.drawEllipse(rect)
p.setClipRect(QtCore.QRectF(rect.left() + rect.width() / 2.0, rect.top(), rect.width() / 2.0, rect.height()))
p.setBrush(QtGui.QColor(c.get("accent", "#888888")))
p.drawEllipse(rect)
p.setClipping(False)
p.setPen(QtGui.QPen(QtGui.QColor(c.get("border", "#666666")), 2.0))
p.setBrush(NO_BRUSH)
p.drawEllipse(rect.adjusted(1.0, 1.0, -1.0, -1.0))
p.end()
pm.setDevicePixelRatio(2.0)
return QIcon(pm)
except Exception:
return QIcon()
class HeaderCombo(QtWidgets.QComboBox):
"""QComboBox that always paints a theme-coloured drop arrow.
With `QComboBox::drop-down { border: none }` Qt stops painting the arrow
entirely (the combo looked like a plain text field). Stylesheets cannot
render a triangle for ::down-arrow either — the CSS border-trick paints
a solid rectangle because Qt draws borders per side, and image files
would not survive the frozen exe without qrc resources. So the arrow is
painted here directly, in the theme's muted colour (set via the
`arrow_color` property from apply_theme).
"""
def __init__(self, parent=None):
super().__init__(parent)
self.arrow_color = "#93a1b5"
def paintEvent(self, event):
super().paintEvent(event)
try:
try:
no_pen = Qt.PenStyle.NoPen
except AttributeError:
no_pen = Qt.NoPen
try:
rtl = QtCore.Qt.LayoutDirection.RightToLeft
except AttributeError:
rtl = QtCore.Qt.RightToLeft
p = QtGui.QPainter(self)
hint = getattr(QtGui.QPainter, "RenderHint", None)
aa = hint.Antialiasing if hint is not None else getattr(QtGui.QPainter, "Antialiasing", None)
if aa is not None:
p.setRenderHint(aa)
r = self.rect()
drop_w = 24 # keep in sync with QComboBox::drop-down width in build_qss
x = r.width() - drop_w / 2.0 if self.layoutDirection() != rtl else drop_w / 2.0
y = r.height() / 2.0
p.setPen(no_pen)
p.setBrush(QtGui.QColor(getattr(self, "arrow_color", "#93a1b5")))
p.drawPolygon(QtCore.QPointF(x - 5.0, y - 3.0),
QtCore.QPointF(x + 5.0, y - 3.0),
QtCore.QPointF(x, y + 3.5))
p.end()
except Exception:
pass
def build_qss(theme_name: str) -> str:
c = THEMES.get(theme_name, THEMES["dark"])
return f"""
* {{ outline: none; }}
QWidget {{ background: {c['bg']}; color: {c['text']}; font-size: 13px; }}
QMainWindow {{ background: {c['bg']}; }}
QDialog {{ background: {c['panel']}; }}
QFrame#Panel {{ background: {c['panel']}; border: 1px solid {c['border']}; border-radius: 14px; }}
QFrame#PreviewPanel {{ background: {c['panel']}; border: 1px solid {c['border']}; border-radius: 16px; }}
QLabel#Title {{ font-size: 18px; font-weight: 800; background: transparent; }}
QLabel#Muted {{ color: {c['muted']}; background: transparent; }}
QLabel#FieldLabel {{ color: {c['muted']}; background: transparent; font-weight: 700; }}
QLabel#HeaderIcon {{ background: transparent; }}
QFrame#ChipSeparator {{ background: {c['border']}; border: none; }}
QLabel#StatusLabel {{ color: {c['muted']}; background: transparent; padding: 4px; }}
QLabel#Preview {{ background: {c['preview_bg']}; color: {c['muted']}; border: 1px solid {c['border']}; border-radius: 14px; }}
QPushButton {{ background: {c['panel2']}; border: 1px solid {c['border']}; border-radius: 10px; padding: 8px 12px; }}
QPushButton:hover {{ background: {c['hover']}; border-color: {c['accent']}; }}
QPushButton:pressed {{ background: {c['sel']}; }}
QPushButton#PrimaryBtn {{ background: {c['accent']}; color: white; border: none; font-weight: 700; }}
QPushButton#PrimaryBtn:hover {{ background: {c['accent2']}; }}
QPushButton#DangerBtn {{ background: transparent; color: {c['danger']}; border-color: {c['danger']}; }}
QPushButton#DangerBtn:hover {{ background: {c['danger_bg']}; color: white; border-color: {c['danger_bg']}; }}
QPushButton#SegBtn {{ background: transparent; border: 1px solid transparent; border-radius: 8px; padding: 5px 12px; color: {c['muted']}; font-weight: 600; }}
QPushButton#SegBtn:hover {{ background: {c['hover']}; color: {c['text']}; border-color: transparent; }}
QPushButton#SegBtn:checked {{ background: {c['accent']}; color: #ffffff; border-color: {c['accent']}; }}
/* Keyboard focus must be visible: outline:none kills the system ring, so
buttons get an accent border instead; accent-filled buttons get a text-
coloured one (an accent border on an accent fill would be invisible). */
QPushButton:focus {{ border-color: {c['accent']}; }}
QPushButton#PrimaryBtn:focus, QPushButton:checked:focus {{ border-color: {c['text']}; }}
QPushButton#PrimaryBtn:disabled {{ background: {c['hover']}; color: {c['muted']}; border: 1px solid {c['border']}; }}
QPushButton#DangerBtn:disabled {{ background: transparent; color: {c['muted']}; border-color: {c['border']}; }}
QPushButton:disabled {{ background: {c['panel']}; color: {c['muted']}; border-color: {c['border']}; }}
QLineEdit, QComboBox {{ background: {c['panel2']}; border: 1px solid {c['border']}; border-radius: 10px; padding: 7px 9px; selection-background-color: {c['accent']}; }}
QLineEdit:focus, QComboBox:focus {{ border-color: {c['accent']}; }}
QLineEdit:disabled, QComboBox:disabled {{ background: {c['hover']}; color: {c['muted']}; border-color: {c['border']}; }}
QListWidget {{ background: {c['panel']}; border: 1px solid {c['border']}; border-radius: 14px; padding: 6px; }}
QListWidget::item {{ border-radius: 10px; padding: 5px; margin: 3px; }}
QListWidget::item:hover {{ background: {c['hover']}; }}
QListWidget::item:selected {{ background: {c['sel']}; color: {c['text']}; border: 1px solid {c['accent']}; }}
QScrollArea {{ border: none; background: transparent; }}
QScrollArea > QWidget > QWidget {{ background: transparent; }}
QProgressBar {{ background: {c['panel2']}; border: 1px solid {c['border']}; border-radius: 8px; text-align: center; height: 12px; }}
QProgressBar::chunk {{ background: {c['accent']}; border-radius: 7px; }}
QSlider::groove:horizontal {{ height: 6px; background: {c['panel2']}; border: 1px solid {c['border']}; border-radius: 3px; }}
QSlider::handle:horizontal {{ background: {c['accent']}; border: none; width: 16px; margin: -5px 0; border-radius: 8px; }}
QSlider::handle:horizontal:hover {{ background: {c['accent2']}; }}
/* Slim themed scrollbars — the system ones stayed bright/light inside dark
panels and clashed with every theme. */
QScrollBar:vertical {{ background: transparent; width: 10px; margin: 2px; }}
QScrollBar::handle:vertical {{ background: {c['border']}; border-radius: 4px; min-height: 32px; }}
QScrollBar::handle:vertical:hover {{ background: {c['muted']}; }}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; }}
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{ background: transparent; }}
QScrollBar:horizontal {{ background: transparent; height: 10px; margin: 2px; }}
QScrollBar::handle:horizontal {{ background: {c['border']}; border-radius: 4px; min-width: 32px; }}
QScrollBar::handle:horizontal:hover {{ background: {c['muted']}; }}
QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {{ width: 0; }}
QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {{ background: transparent; }}
QStatusBar {{ background: {c['panel']}; border-top: 1px solid {c['border']}; }}
QStatusBar QLabel {{ background: transparent; color: {c['muted']}; }}
QSplitter::handle {{ background: {c['bg']}; }}
QToolTip {{ background: {c['panel2']}; color: {c['text']}; border: 1px solid {c['border']}; padding: 5px; border-radius: 6px; }}
QFrame#HeaderTools {{ background: {c['panel2']}; border: 1px solid {c['border']}; border-radius: 12px; }}
QFrame#HeaderTools QLabel {{ background: transparent; color: {c['muted']}; font-weight: 700; }}
QComboBox QAbstractItemView {{ background: {c['panel2']}; color: {c['text']}; border: 1px solid {c['border']}; border-radius: 10px; padding: 4px; outline: none; selection-background-color: {c['sel']}; selection-color: {c['text']}; }}
QComboBox QAbstractItemView::item {{ padding: 6px 16px; margin: 2px 4px; }}
QComboBox QAbstractItemView::item:selected {{ background: {c['sel']}; color: {c['text']}; }}
QComboBox::drop-down {{ border: none; width: 24px; }}
/* The arrow itself is painted by HeaderCombo.paintEvent (see class docstring):
Qt draws no arrow when drop-down has no border, and no stylesheet trick
produces a real triangle. */
QCheckBox {{ background: transparent; spacing: 8px; }}
QFrame#CheckCard {{ background: {c['panel2']}; border: 1px solid {c['accent']}; border-radius: 12px; }}
QFrame#CheckCard QLabel {{ background: transparent; border: none; }}
QLabel#CheckHint {{ color: {c['muted']}; }}
QCheckBox#BigCheck {{ background: transparent; spacing: 10px; font-weight: 700; color: {c['text']}; }}
QCheckBox#BigCheck::indicator {{ width: 20px; height: 20px; border: 2px solid {c['accent']}; border-radius: 6px; background: {c['bg']}; }}
QCheckBox#BigCheck::indicator:hover {{ background: {c['hover']}; }}
QCheckBox#BigCheck::indicator:checked {{ background: {c['accent']}; border-color: {c['accent2']}; }}
QMenu {{ background: {c['panel2']}; color: {c['text']}; border: 1px solid {c['border']}; border-radius: 10px; padding: 6px; }}
QMenu::item {{ padding: 6px 20px; border-radius: 6px; }}
QMenu::item:selected {{ background: {c['sel']}; }}
QMessageBox {{ background: {c['panel']}; }}
QMessageBox QLabel {{ background: transparent; }}
QMessageBox QPushButton {{ min-width: 76px; }}
/* Dialogs, message boxes and input dialogs must not paint light label boxes:
the generic QWidget rule gives every QLabel an opaque bg-coloured rectangle
that stands out against the panel colour of the dialog itself. */
QLabel {{ background: transparent; }}
QDialog QLabel {{ background: transparent; }}
QInputDialog {{ background: {c['panel']}; }}
QInputDialog QLabel {{ background: transparent; }}
/* QSpinBox (used by the swap-categories dialog) otherwise falls back to the
light system palette on Windows — a white field inside a dark dialog. */
QSpinBox {{ background: {c['panel2']}; color: {c['text']}; border: 1px solid {c['border']}; border-radius: 10px; padding: 5px 7px; selection-background-color: {c['accent']}; }}
QSpinBox::up-button, QSpinBox::down-button {{ background: {c['hover']}; border: none; width: 18px; }}
QSpinBox::up-button:hover, QSpinBox::down-button:hover {{ background: {c['sel']}; }}
/* QInputDialog's chooser list is a plain QListView, not a QListWidget. */
QListView {{ background: {c['panel2']}; color: {c['text']}; border: 1px solid {c['border']}; border-radius: 10px; padding: 4px; outline: none; }}
QListView::item {{ border-radius: 8px; padding: 5px; margin: 2px; }}
QListView::item:hover {{ background: {c['hover']}; }}
QListView::item:selected {{ background: {c['sel']}; color: {c['text']}; border: 1px solid {c['accent']}; }}
/* Small check indicators follow the theme instead of the system palette. */
QCheckBox::indicator {{ width: 16px; height: 16px; border: 1px solid {c['border']}; border-radius: 4px; background: {c['bg']}; }}
QCheckBox::indicator:hover {{ border-color: {c['accent']}; }}
QCheckBox::indicator:checked {{ background: {c['accent']}; border-color: {c['accent2']}; }}
"""
def build_palette(theme_name: str) -> QtGui.QPalette:
"""A QPalette that matches the theme.
A stylesheet never changes the QPalette, so with Fusion on Windows every
widget/subcontrol the QSS does not explicitly cover (QSpinBox fields,
disabled text, native popups, message-box details) still drew with the
LIGHT system palette — white patches inside dark dialogs. Seeding the
palette with the theme colours removes those mismatched areas app-wide.
"""
c = THEMES.get(theme_name, THEMES["dark"])
pal = QtGui.QPalette()
text = QtGui.QColor(c["text"])
muted = QtGui.QColor(c["muted"])
disabled = QtGui.QColor(c["muted"])
disabled.setAlpha(150)
R = QtGui.QPalette.ColorRole
G = QtGui.QPalette.ColorGroup
pal.setColor(R.Window, QtGui.QColor(c["bg"]))
pal.setColor(R.WindowText, text)
pal.setColor(R.Base, QtGui.QColor(c["panel"]))
pal.setColor(R.AlternateBase, QtGui.QColor(c["panel2"]))
pal.setColor(R.ToolTipBase, QtGui.QColor(c["panel2"]))
pal.setColor(R.ToolTipText, text)
pal.setColor(R.Text, text)
pal.setColor(R.Button, QtGui.QColor(c["panel2"]))
pal.setColor(R.ButtonText, text)
pal.setColor(R.PlaceholderText, muted)
pal.setColor(R.Highlight, QtGui.QColor(c["accent"]))
pal.setColor(R.HighlightedText, QtGui.QColor("#ffffff"))
pal.setColor(R.Link, QtGui.QColor(c["accent2"]))
for role in (R.WindowText, R.Text, R.ButtonText):
pal.setColor(G.Disabled, role, disabled)
pal.setColor(G.Disabled, R.Base, QtGui.QColor(c["panel2"]))
return pal
def _apply_windows_titlebar(widget: QtWidgets.QWidget, dark: bool):
"""Colour the native Windows title bar to match the app theme.
Windows decides title-bar colour from the SYSTEM theme, never from the Qt
palette — so a dark-themed app got white title bars on every dialog.
DWMWA_USE_IMMERSIVE_DARK_MODE (20; 19 on older builds) fixes that.
"""
if sys.platform != "win32" or widget is None:
return
try:
import ctypes
import ctypes.wintypes
hwnd = int(widget.winId())
for attr in (20, 19):
val = ctypes.c_int(1 if dark else 0)
res = ctypes.windll.dwmapi.DwmSetWindowAttribute(
ctypes.wintypes.HWND(hwnd), ctypes.c_uint(attr),
ctypes.byref(val), ctypes.sizeof(val))
if res == 0:
break
except Exception:
pass
def _apply_app_color_scheme(dark: bool):
"""Tell the platform theme that this app is dark/light (Qt >= 6.8).
On Windows 10/11 the native title bar of EVERY window — including dialogs
and message boxes created later — follows the application colour scheme,
so a dark-themed app no longer gets white dialog title bars. Older Qt
builds skip this gracefully (cosmetic-only degradation). Unlike an
app-wide event filter, this has no teardown-time risk and needs no
per-window bookkeeping.
"""
try:
sh = QtWidgets.QApplication.styleHints()
cs = getattr(QtCore.Qt, "ColorScheme", None)
if sh is not None and cs is not None and hasattr(sh, "setColorScheme"):
sh.setColorScheme(cs.Dark if dark else cs.Light)
except Exception:
pass
# ---------------- utility helpers ----------------
def bundled_tool(name: str) -> Optional[str]:
"""Find a tool from bundled bin/, app folder bin/, or system PATH."""
names = [name]
if sys.platform == "win32" and not name.lower().endswith(".exe"):
names.insert(0, name + ".exe")
for base in (RESOURCE_DIR / "bin", RUNTIME_DIR / "bin"):
for nm in names:
fp = base / nm
if fp.exists():
return str(fp)
return which(name) or (which(name + ".exe") if sys.platform == "win32" and not name.lower().endswith(".exe") else None)
def portable_vlc_dir() -> Optional[Path]:
for base in (RESOURCE_DIR / "bin", RUNTIME_DIR / "bin"):
d = base / "vlc"
if (d / "libvlc.dll").exists():
return d
return None
def run_hidden_subprocess(cmd, **kwargs):
"""Run console tools without flashing terminal windows on Windows."""
if sys.platform == "win32":
try:
flags = subprocess.CREATE_NO_WINDOW
flags |= getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)
kwargs.setdefault("creationflags", flags)
except Exception:
pass
try:
startupinfo = kwargs.get("startupinfo") or subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0
kwargs["startupinfo"] = startupinfo
except Exception:
pass
return subprocess.run(cmd, **kwargs)
def popen_hidden_subprocess(cmd, **kwargs):
"""Start console tools without a flashing console window on Windows."""
if sys.platform == "win32":
try:
kwargs.setdefault("creationflags", subprocess.CREATE_NO_WINDOW)
except Exception:
pass
try:
startupinfo = kwargs.get("startupinfo") or subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0
kwargs["startupinfo"] = startupinfo
except Exception:
pass
return subprocess.Popen(cmd, **kwargs)
def ffmpeg_available() -> bool:
return bundled_tool("ffmpeg") is not None
def extract_frame_with_ffmpeg(path: str, fraction=0.5, out_png: Optional[str] = None, timeout: int = 8) -> Optional[str]:
"""Extract one video frame quickly and silently.
Thumbnail generation deliberately uses a single ffmpeg call and no
separate ffprobe/duration pass — a second external process per file made
folders full of videos feel very slow. A frame around 1 second is
fast and good enough for sorting — but clips SHORTER than the seek point
produce no frame at all, so on an empty result we retry with earlier seek
positions (0.4s, then the very first frame). That is how very short clips
(< 1 s) still get a real thumbnail.
"""
if out_png is None:
out_png = str(THUMB_CACHE / f"ffthumb_{int(time.time() * 1000)}.png")
result = None
attempt_files: List[str] = []
try:
ffmpeg = bundled_tool("ffmpeg")
if ffmpeg is None:
return None
base_fp = Path(out_png)
for idx, seek in enumerate(("1", "0.4", "0")):
# A unique file per attempt: a failed attempt must never be
# mistaken for a successfully written frame.
attempt_out = str(base_fp.with_name(f"{base_fp.stem}_a{idx}{base_fp.suffix}"))
attempt_files.append(attempt_out)
# -ss before -i is much faster. scale keeps generated PNG small.
cmd = [
ffmpeg, "-hide_banner", "-loglevel", "error", "-y",
"-threads", "1", "-ss", seek, "-noaccurate_seek", "-i", str(path),
"-an", "-sn", "-dn", "-frames:v", "1", "-vf", "scale=360:-2", "-q:v", "5", attempt_out,
]
try:
with open(os.devnull, "wb") as dn:
run_hidden_subprocess(cmd, stdout=dn, stderr=dn, timeout=timeout)
except Exception:
pass
fp = Path(attempt_out)
if fp.exists() and fp.stat().st_size > 0:
result = attempt_out
break
except Exception as e:
log_exception("ffmpeg thumbnail extraction failed", e)
finally:
# Temp-file hygiene: every attempt file that is NOT the returned frame
# is deleted here. Without this, failed attempts pile up in the system
# TEMP folder next to the returned frame (found by the v1.9.2 review).
for stale in attempt_files:
if stale == result:
continue
try:
if Path(stale).exists():
Path(stale).unlink()
except Exception:
pass
return result
def thumb_cache_key(path: str, size: int) -> str:
try:
st = Path(path).stat()
key_src = f"{Path(path).resolve()}|{st.st_mtime_ns}|{st.st_size}|{size}|qt6-v4"
except Exception:
key_src = f"{path}|{size}|qt6-v4"
# usedforsecurity=False: the SHA1 is only a cache key for thumbnails,
# never a security primitive (also silences static analyzers like bandit).
return hashlib.sha1(key_src.encode("utf-8"), usedforsecurity=False).hexdigest()
def cached_thumbnail_bytes(path: str, size: int) -> Optional[bytes]:
try:
fp = THUMB_CACHE / (thumb_cache_key(path, size) + ".png")
if fp.exists():
data = fp.read_bytes()
return data if data else None
except Exception:
pass
return None
def _write_cache_safely(cache_fp: Path, data: bytes) -> None:
try:
tmp = cache_fp.with_suffix(cache_fp.suffix + f".tmp{os.getpid()}{threading.get_ident()}")
tmp.write_bytes(data)
os.replace(str(tmp), str(cache_fp))
except Exception:
try:
if "tmp" in locals() and tmp.exists():
tmp.unlink()
except Exception:
pass
def _png_from_pil_image(im, max_size: int) -> bytes:
if im.mode not in ("RGBA", "RGB"):
im = im.convert("RGBA")
im.thumbnail((max_size * 2, max_size * 2), Image.LANCZOS)
bio = io.BytesIO()
im.save(bio, format="PNG")
return bio.getvalue()
def group_for_extension(ext: str) -> str:
ext = ext.lower()
if ext in VIDEO_EXTS:
return "video"
if ext in AUDIO_EXTS:
return "audio"
if ext in IMAGE_EXTS or ext in ANIM_EXTS:
return "image"
if ext in ARCHIVE_EXTS:
return "archive"
if ext in SUBTITLE_EXTS:
return "sub"
if ext in CODE_EXTS:
return "code"
if ext in {".exe", ".msi", ".bat", ".cmd", ".ps1", ".sh"}:
return "exe"
if ext in DOC_EXTS:
return "doc"
return "other"
def _is_mpeg_ts_file(p) -> bool:
"""True if a `.ts` file really is an MPEG Transport Stream.
The `.ts` extension is ambiguous: it is both the MPEG-TS video container
and TypeScript source code, and it sits in VIDEO_EXTS *and* CODE_EXTS.
Every MPEG-TS packet starts with the sync byte 0x47 and packets are
188 bytes, so the first byte plus the sync byte of the second packet
(offset 188) is a strong signal. Anything else — including text that
merely happens to start with the letter 'G' (0x47) — is treated as code.
"""
try:
with open(p, "rb") as fh:
head = fh.read(189)
except OSError:
return False
if len(head) == 0 or head[0] != 0x47:
return False
if len(head) >= 189 and head[188] != 0x47:
return False
return True
def _plays_as_video(path) -> bool:
"""Extension says video AND, for the ambiguous .ts, content agrees."""
p = Path(path)
ext = p.suffix.lower()
if ext not in VIDEO_EXTS:
return False
if ext == ".ts":
return _is_mpeg_ts_file(p)
return True
def _asset_icon_pil(ext: str, side: int):
if not HAS_PIL:
return None
icon_name = EXT_ICON.get(ext.lower())
if not icon_name:
icon_name = {"video": "video", "audio": "audio", "image": "image", "archive": "zip", "doc": "document", "sub": "subtitles", "code": "console", "exe": "exe", "other": "document"}.get(group_for_extension(ext), "document")
fp = ICONS_DIR / f"{icon_name}.png"
if not fp.exists():
return None
try:
im = Image.open(str(fp)).convert("RGBA")
im.thumbnail((side, side), Image.LANCZOS)
return im
except Exception:
return None
def _font(size: int, bold: bool = False):
if not HAS_PIL:
return None
candidates = []
if APP_FONT.exists():
candidates.append(str(APP_FONT))
candidates += ["arial.ttf", "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf"]
for c in candidates:
try:
return ImageFont.truetype(c, size=size)
except Exception:
continue
return ImageFont.load_default()
def generate_type_card_bytes(path: str, size: int) -> Optional[bytes]:
"""File-type artwork: self-contained document-style icon, gradient card fallback.
Known extensions map to a real document-style icon from assets/icons/
(white page + colored label, original AI-generated artwork). Anything
unmapped falls back to the gradient card that spells out the extension.
"""
if not HAS_PIL:
return None
try:
p = Path(path)
ext = p.suffix.lower()
if ext in EXT_ICON:
icon = _asset_icon_pil(ext, max(128, int(size * 2)))
if icon is not None:
bio = io.BytesIO()
icon.save(bio, format="PNG")
return bio.getvalue()
group = group_for_extension(ext)
c1, c2, label = GROUP_STYLE.get(group, GROUP_STYLE["other"])
w = h = max(128, int(size * 2))
img = Image.new("RGBA", (w, h), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
r = max(16, w // 10)
# vertical gradient
def hexrgb(x):
x = x.lstrip("#")
return tuple(int(x[i:i+2], 16) for i in (0, 2, 4))
a = hexrgb(c1); b = hexrgb(c2)
for y in range(h):
t = y / max(1, h - 1)
col = tuple(int(a[i] * (1 - t) + b[i] * t) for i in range(3)) + (255,)
draw.line([(0, y), (w, y)], fill=col)
# soft overlay and border
draw.rounded_rectangle([2, 2, w - 3, h - 3], radius=r, outline=(255, 255, 255, 68), width=max(2, w // 80))
draw.rounded_rectangle([w * 0.08, h * 0.08, w * 0.92, h * 0.92], radius=r, fill=(255, 255, 255, 18))
icon = _asset_icon_pil(ext, int(w * 0.43))
if icon:
x = (w - icon.width) // 2
y = int(h * 0.19)
img.alpha_composite(icon, (x, y))
ext_text = (ext[1:] if ext else label).upper()[:8]
font_big = _font(max(18, w // 8), bold=True)
font_small = _font(max(12, w // 15))
bbox = draw.textbbox((0, 0), ext_text, font=font_big)
tx = (w - (bbox[2] - bbox[0])) // 2
ty = int(h * 0.64)
draw.text((tx + 2, ty + 2), ext_text, fill=(0, 0, 0, 90), font=font_big)
draw.text((tx, ty), ext_text, fill=(255, 255, 255, 245), font=font_big)
bbox2 = draw.textbbox((0, 0), label, font=font_small)
draw.text(((w - (bbox2[2] - bbox2[0])) // 2, int(h * 0.82)), label, fill=(255, 255, 255, 180), font=font_small)
bio = io.BytesIO()
img.save(bio, format="PNG")
return bio.getvalue()
except Exception:
return None
def _first_image_from_zip(path: Path, size: int) -> Optional[bytes]:
with zipfile.ZipFile(str(path), "r") as z:
for info in z.infolist():
if Path(info.filename).suffix.lower() in IMAGE_EXTS:
if info.file_size > MAX_ARCHIVE_IMAGE_BYTES:
continue # archive-bomb guard: skip absurdly large entries
try:
with z.open(info) as fh:
with Image.open(fh) as im:
return _png_from_pil_image(im, size)
except Exception:
continue
return None
def _first_image_from_rar(path: Path, size: int) -> Optional[bytes]:
if not HAS_RAR:
return None
with rarfile.RarFile(str(path)) as rf:
for info in rf.infolist():
if Path(info.filename).suffix.lower() in IMAGE_EXTS:
if int(getattr(info, "file_size", 0) or 0) > MAX_ARCHIVE_IMAGE_BYTES: