-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·2673 lines (2279 loc) · 103 KB
/
app.py
File metadata and controls
executable file
·2673 lines (2279 loc) · 103 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
"""
VoxPlayer - A modern multimedia player built with PyQt6
Clean implementation without signal issues
"""
import sys
import os
import tempfile
import shutil
import requests
import webbrowser
import json
import re
import time
import uuid
from dataclasses import dataclass
from typing import List, Optional, Dict, Any
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QPushButton, QSlider, QLabel,
QFileDialog, QDockWidget, QListWidget, QListWidgetItem,
QMenuBar, QMenu, QStatusBar, QMessageBox, QInputDialog,
QLineEdit)
from PyQt6.QtCore import Qt, QTimer, QSettings, QUrl, QThread, pyqtSignal
from PyQt6.QtMultimediaWidgets import QVideoWidget
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
from PyQt6.QtGui import QKeySequence, QShortcut, QAction
# Data classes for state management
@dataclass
class AppState:
window_geometry: Optional[bytes] = None
theme: str = "dark"
volume: int = 50
last_file: str = ""
resume_positions: Dict[str, int] = None
auto_update_enabled: bool = True
update_channel: str = "stable"
audio_output_mode: str = "default" # "default" or "manual"
selected_audio_device: str = "" # Device ID for manual mode
def __post_init__(self):
if self.resume_positions is None:
self.resume_positions = {}
@dataclass
class SubtitleTrack:
index: int
language: str
name: str
enabled: bool = True
@dataclass
class SubtitleStyle:
font_family: str = "Arial"
font_size: int = 16
text_color: str = "#FFFFFF"
outline_color: str = "#000000"
background_color: str = "transparent"
bold: bool = False
italic: bool = False
# Torrent streaming classes
class TorrentStreamer(QThread):
"""Thread for handling torrent streaming using qBittorrent API"""
progress_updated = pyqtSignal(int, str) # progress, status
file_ready = pyqtSignal(str) # file_path
error_occurred = pyqtSignal(str) # error_message
def __init__(self, magnet_link: str = None, torrent_file: str = None):
super().__init__()
self.magnet_link = magnet_link
self.torrent_file = torrent_file
self.temp_dir = None
self.is_running = False
self.qb_client = None
self.torrent_hash = None
self.stream_file_path = None
self.stream_file_index = None
self.stream_file_size = 0
self._file_ready_emitted = False
self.stream_category = f"voxplayer_stream_{uuid.uuid4().hex[:10]}"
def run(self):
"""Start torrent streaming"""
try:
self.is_running = True
self.progress_updated.emit(0, "Initializing torrent client...")
# Create temporary directory for torrent files
self.temp_dir = tempfile.mkdtemp(prefix="voxplayer_torrent_")
# Initialize qBittorrent client
self._init_qbittorrent()
# Add torrent
if self.magnet_link:
self._add_magnet_link()
elif self.torrent_file:
self._add_torrent_file()
else:
self.error_occurred.emit("No magnet link or torrent file provided")
return
except Exception as e:
self.error_occurred.emit(f"Torrent streaming error: {str(e)}")
finally:
self.is_running = False
def _init_qbittorrent(self):
"""Initialize qBittorrent client"""
try:
from qbittorrentapi import Client
qb_host = os.getenv("QB_HOST", "localhost:8080")
qb_username = os.getenv("QB_USERNAME", "")
qb_password = os.getenv("QB_PASSWORD", "")
client_kwargs = {"host": qb_host}
if qb_username and qb_password:
client_kwargs["username"] = qb_username
client_kwargs["password"] = qb_password
# Connect to qBittorrent Web UI and verify availability.
self.qb_client = Client(**client_kwargs)
app_version_attr = self.qb_client.app.version
version = app_version_attr() if callable(app_version_attr) else app_version_attr
if not version:
raise RuntimeError("qBittorrent is not running. Please start qBittorrent first.")
self.progress_updated.emit(10, f"Connected to qBittorrent v{version}")
except ImportError as exc:
raise RuntimeError(
"qBittorrent API not available. Please install: pip install qbittorrent-api"
) from exc
except Exception as exc:
raise RuntimeError(
f"Failed to connect to qBittorrent at '{os.getenv('QB_HOST', 'localhost:8080')}'. "
"Please ensure qBittorrent is running, Web UI is enabled, and QB_USERNAME/QB_PASSWORD are set if auth is required."
) from exc
def _add_magnet_link(self):
"""Add magnet link to qBittorrent"""
try:
if not self.qb_client:
raise RuntimeError("qBittorrent client is not initialized.")
self.progress_updated.emit(20, "Adding magnet link...")
add_kwargs = {
"urls": self.magnet_link,
"save_path": self.temp_dir,
"category": self.stream_category,
"is_paused": False,
"use_auto_torrent_management": False,
"is_sequential_download": True,
"is_first_last_piece_prio": True,
}
try:
torrent_info = self.qb_client.torrents_add(**add_kwargs)
except TypeError:
# Older qBittorrent Web API versions do not support these add-time flags.
add_kwargs.pop("is_sequential_download", None)
add_kwargs.pop("is_first_last_piece_prio", None)
torrent_info = self.qb_client.torrents_add(**add_kwargs)
if isinstance(torrent_info, str) and torrent_info.startswith("Ok"):
self.progress_updated.emit(30, "Magnet link added successfully")
self._monitor_torrent()
else:
self.error_occurred.emit(f"Failed to add magnet link: {torrent_info}")
except Exception as e:
self.error_occurred.emit(f"Error adding magnet link: {str(e)}")
def _add_torrent_file(self):
"""Add torrent file to qBittorrent"""
try:
if not self.qb_client:
raise RuntimeError("qBittorrent client is not initialized.")
self.progress_updated.emit(20, "Adding torrent file...")
# Read torrent file
with open(self.torrent_file, 'rb') as f:
torrent_data = f.read()
add_kwargs = {
"torrent_files": torrent_data,
"save_path": self.temp_dir,
"category": self.stream_category,
"is_paused": False,
"use_auto_torrent_management": False,
"is_sequential_download": True,
"is_first_last_piece_prio": True,
}
try:
torrent_info = self.qb_client.torrents_add(**add_kwargs)
except TypeError:
add_kwargs.pop("is_sequential_download", None)
add_kwargs.pop("is_first_last_piece_prio", None)
torrent_info = self.qb_client.torrents_add(**add_kwargs)
if isinstance(torrent_info, str) and torrent_info.startswith("Ok"):
self.progress_updated.emit(30, "Torrent file added successfully")
self._monitor_torrent()
else:
self.error_occurred.emit(f"Failed to add torrent file: {torrent_info}")
except Exception as e:
self.error_occurred.emit(f"Error adding torrent file: {str(e)}")
def _monitor_torrent(self):
"""Monitor torrent progress and emit media file once buffer is ready."""
try:
self.torrent_hash = self._wait_for_torrent_hash()
if not self.torrent_hash:
self.error_occurred.emit("Unable to locate added torrent in qBittorrent.")
return
self._configure_streaming_mode()
while self.is_running:
torrent_items = self.qb_client.torrents_info(torrent_hashes=self.torrent_hash)
if not torrent_items:
self.error_occurred.emit("Torrent disappeared from qBittorrent.")
break
torrent_info = torrent_items[0]
progress = int(float(getattr(torrent_info, "progress", 0.0)) * 100)
state = str(getattr(torrent_info, "state", "unknown"))
dlspeed = int(getattr(torrent_info, "dlspeed", 0) or 0)
speed_mbps = dlspeed / (1024 * 1024)
self.progress_updated.emit(
40 + progress // 2,
f"{state} | {progress}% | {speed_mbps:.2f} MiB/s",
)
if not self._file_ready_emitted:
ready, downloaded, required = self._is_buffer_ready()
if ready and self.stream_file_path:
self._file_ready_emitted = True
self.progress_updated.emit(
90,
f"Buffer ready ({downloaded // (1024 * 1024)} / {required // (1024 * 1024)} MiB), starting playback",
)
self.file_ready.emit(self.stream_file_path)
elif required > 0:
self.progress_updated.emit(
55,
f"Buffering {downloaded // (1024 * 1024)} / {required // (1024 * 1024)} MiB",
)
if dlspeed <= 128 * 1024:
self.progress_updated.emit(
56,
"Low download speed detected, playback may stutter",
)
if state in {"error", "missingFiles"}:
self.error_occurred.emit(f"Torrent error: {state}")
break
time.sleep(1.5)
except Exception as e:
self.error_occurred.emit(f"Error monitoring torrent: {str(e)}")
def _wait_for_torrent_hash(self, timeout_seconds: int = 60) -> Optional[str]:
"""Wait until qBittorrent registers the newly added torrent."""
deadline = time.time() + timeout_seconds
while self.is_running and time.time() < deadline:
try:
torrents = self.qb_client.torrents_info(category=self.stream_category)
except Exception:
torrents = []
if torrents:
torrents = sorted(
torrents,
key=lambda t: int(getattr(t, "added_on", 0) or 0),
reverse=True,
)
selected = torrents[0]
self.progress_updated.emit(35, f"Metadata acquired: {selected.name}")
return selected.hash
self.progress_updated.emit(34, "Waiting for metadata and peers...")
time.sleep(1.0)
return None
def _configure_streaming_mode(self):
"""Enable sequential streaming mode and pick one playable media file."""
self._set_sequential_download()
self._set_first_last_piece_priority()
stream_file = self._pick_stream_file()
if not stream_file:
raise RuntimeError("No supported media file found in torrent contents.")
file_name = str(getattr(stream_file, "name", ""))
file_index = self._file_index(stream_file)
file_size = int(getattr(stream_file, "size", 0) or 0)
if file_index is None:
raise RuntimeError("Unable to identify media file index for streaming priority.")
self.stream_file_index = file_index
self.stream_file_size = file_size
self.stream_file_path = os.path.join(self.temp_dir, file_name)
self._prioritize_selected_file(file_index)
self.progress_updated.emit(
45,
f"Sequential mode enabled for {os.path.basename(file_name)}",
)
def _set_sequential_download(self):
"""Attempt to force sequential piece ordering."""
try:
self.qb_client.torrents_set_sequential_download(
torrent_hashes=self.torrent_hash, value=True
)
return
except Exception:
pass
try:
self.qb_client.torrents_toggle_sequential_download(
torrent_hashes=self.torrent_hash
)
except Exception:
pass
def _set_first_last_piece_priority(self):
"""Boost first/last piece priority to speed container header access."""
try:
self.qb_client.torrents_set_first_last_piece_priority(
torrent_hashes=self.torrent_hash, value=True
)
return
except Exception:
pass
try:
self.qb_client.torrents_toggle_first_last_piece_priority(
torrent_hashes=self.torrent_hash
)
except Exception:
pass
def _torrent_files(self) -> List[Any]:
"""Return file entries for the active torrent."""
try:
return self.qb_client.torrents_files(torrent_hash=self.torrent_hash)
except Exception:
return self.qb_client.torrents_files(torrent_hashes=self.torrent_hash)
def _file_index(self, file_item: Any) -> Optional[int]:
idx = getattr(file_item, "index", None)
if idx is None:
idx = getattr(file_item, "id", None)
return int(idx) if idx is not None else None
def _pick_stream_file(self) -> Optional[Any]:
"""Select best candidate for immediate playback (prefer MP4, then largest)."""
files = self._torrent_files()
if not files:
return None
media_rank = {
".mp4": 0,
".webm": 1,
".mov": 2,
".m4v": 3,
".avi": 4,
".mkv": 5,
".wmv": 6,
".flv": 7,
".mp3": 8,
".m4a": 9,
".aac": 10,
".flac": 11,
".wav": 12,
".ogg": 13,
}
candidates = []
for item in files:
name = str(getattr(item, "name", "")).lower()
_, ext = os.path.splitext(name)
if ext in media_rank:
size = int(getattr(item, "size", 0) or 0)
candidates.append((media_rank[ext], -size, item))
if not candidates:
return None
candidates.sort(key=lambda entry: (entry[0], entry[1]))
return candidates[0][2]
def _prioritize_selected_file(self, selected_index: int):
"""Download selected media file first to reduce startup delay."""
file_items = self._torrent_files()
selected_ids = []
other_ids = []
for item in file_items:
idx = self._file_index(item)
if idx is None:
continue
if idx == selected_index:
selected_ids.append(idx)
else:
other_ids.append(idx)
if selected_ids:
try:
self.qb_client.torrents_file_priority(
torrent_hash=self.torrent_hash, file_ids=selected_ids, priority=7
)
except Exception:
pass
if other_ids:
try:
self.qb_client.torrents_file_priority(
torrent_hash=self.torrent_hash, file_ids=other_ids, priority=0
)
except Exception:
pass
def _buffer_target_bytes(self) -> int:
"""Compute startup buffer based on file size/container."""
if self.stream_file_size <= 0 or not self.stream_file_path:
return 0
_, ext = os.path.splitext(self.stream_file_path.lower())
base = 64 * 1024 * 1024 if ext == ".mkv" else 32 * 1024 * 1024
pct_target = int(self.stream_file_size * 0.02)
return min(max(base, pct_target), 256 * 1024 * 1024)
def _is_buffer_ready(self):
"""Return whether selected file has enough sequentially downloaded data."""
if self.stream_file_index is None:
return False, 0, 0
required = self._buffer_target_bytes()
for item in self._torrent_files():
idx = self._file_index(item)
if idx == self.stream_file_index:
size = int(getattr(item, "size", 0) or 0)
progress = float(getattr(item, "progress", 0.0) or 0.0)
downloaded = int(size * progress)
return downloaded >= required, downloaded, required
return False, 0, required
def stop(self):
"""Stop torrent streaming"""
self.is_running = False
if self.qb_client:
try:
if self.torrent_hash:
self.qb_client.torrents_delete(
torrent_hashes=self.torrent_hash, delete_files=True
)
except Exception:
pass
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir, ignore_errors=True)
class UpdateChecker(QThread):
"""Thread for checking updates"""
update_available = pyqtSignal(dict) # update_info
check_completed = pyqtSignal(bool) # has_update
def __init__(self, current_version: str = "1.0.0"):
super().__init__()
self.current_version = current_version
self.github_repo = "voxhash/voxplayer"
self.github_api = f"https://api.github.com/repos/{self.github_repo}/releases/latest"
def run(self):
"""Check for updates"""
try:
response = requests.get(
self.github_api,
timeout=10,
headers={
"Accept": "application/vnd.github+json",
"User-Agent": "VoxPlayer-UpdateChecker",
},
)
if response.status_code == 200:
release_data = response.json()
latest_version = release_data.get("tag_name", "").lstrip("v")
if latest_version and self._is_newer_version(latest_version, self.current_version):
update_info = {
"version": latest_version,
"download_url": release_data.get("html_url", ""),
"release_notes": release_data.get("body", ""),
"published_at": release_data.get("published_at", "")
}
self.update_available.emit(update_info)
self.check_completed.emit(True)
else:
self.check_completed.emit(False)
else:
self.check_completed.emit(False)
except Exception as e:
print(f"Update check failed: {e}")
self.check_completed.emit(False)
def _is_newer_version(self, latest: str, current: str) -> bool:
"""Compare version strings"""
try:
latest_parts = [int(x) for x in latest.split('.')]
current_parts = [int(x) for x in current.split('.')]
# Pad with zeros if needed
max_len = max(len(latest_parts), len(current_parts))
latest_parts.extend([0] * (max_len - len(latest_parts)))
current_parts.extend([0] * (max_len - len(current_parts)))
return latest_parts > current_parts
except:
return False
class Settings:
def __init__(self, org: str, app: str):
self.settings = QSettings(org, app)
def save_state(self, state: AppState):
"""Save application state"""
self.settings.setValue("window_geometry", state.window_geometry)
self.settings.setValue("theme", state.theme)
self.settings.setValue("volume", state.volume)
self.settings.setValue("last_file", state.last_file)
self.settings.setValue("resume_positions", json.dumps(state.resume_positions))
self.settings.setValue("audio_output_mode", state.audio_output_mode)
self.settings.setValue("selected_audio_device", state.selected_audio_device)
def load_state(self) -> AppState:
"""Load application state"""
return AppState(
window_geometry=self.settings.value("window_geometry"),
theme=self.settings.value("theme", "dark"),
volume=int(self.settings.value("volume", 50)),
last_file=self.settings.value("last_file", ""),
resume_positions=json.loads(self.settings.value("resume_positions", "{}")),
audio_output_mode=self.settings.value("audio_output_mode", "default"),
selected_audio_device=self.settings.value("selected_audio_device", "")
)
class PlayerControls(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.parent_window = parent
self.setup_ui()
def setup_ui(self):
layout = QHBoxLayout(self)
layout.setContentsMargins(4, 2, 4, 2) # Even more compact
layout.setSpacing(4) # Reduced spacing
# Control buttons (micro-compact design)
self.btn_play = QPushButton("▶")
self.btn_play.setObjectName("playButton")
self.btn_play.setFixedSize(18, 18) # Much smaller
self.btn_play.setStyleSheet("""
QPushButton#playButton {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #00BFFF, stop: 1 #0099CC);
border: 1px solid #00BFFF;
border-radius: 9px;
color: white;
font-size: 8px;
font-weight: bold;
}
QPushButton#playButton:hover {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #00CCFF, stop: 1 #00BFFF);
border-color: #00CCFF;
}
QPushButton#playButton:pressed {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #0088BB, stop: 1 #006699);
}
""")
self.btn_stop = QPushButton("⏹")
self.btn_stop.setFixedSize(16, 16) # Much smaller
self.btn_stop.setStyleSheet("""
QPushButton {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
color: white;
font-size: 6px;
}
QPushButton:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.25);
}
""")
self.btn_mute = QPushButton("🔊")
self.btn_mute.setFixedSize(16, 16) # Much smaller
self.btn_mute.setStyleSheet("""
QPushButton {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
color: white;
font-size: 6px;
}
QPushButton:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.25);
}
""")
# Seek bar (micro-compact design) with timeline preview
self.seek_slider = QSlider(Qt.Orientation.Horizontal)
self.seek_slider.setRange(0, 1000)
self.seek_slider.setValue(0)
self.seek_slider.setStyleSheet("""
QSlider::groove:horizontal {
border: none;
height: 1px;
background: rgba(255, 255, 255, 0.15);
border-radius: 1px;
}
QSlider::handle:horizontal {
background: #00BFFF;
border: 1px solid #FFFFFF;
width: 8px;
margin: -3px 0;
border-radius: 4px;
}
QSlider::handle:horizontal:hover {
background: #00CCFF;
width: 10px;
margin: -4px 0;
}
""")
# Enable mouse tracking for timeline preview
self.seek_slider.setMouseTracking(True)
self.seek_slider.enterEvent = self.on_seek_hover
self.seek_slider.leaveEvent = self.on_seek_leave
self.seek_slider.mouseMoveEvent = self.on_seek_mouse_move
# Time labels (micro-compact)
self.time_label = QLabel("00:00")
self.time_label.setObjectName("timeLabel")
self.time_label.setStyleSheet("""
QLabel#timeLabel {
color: white;
font-family: "Consolas", "Monaco", monospace;
font-size: 7px;
font-weight: bold;
background: transparent;
border: none;
padding: 0px 2px;
min-width: 35px;
}
""")
# Volume control (micro-compact)
self.volume_slider = QSlider(Qt.Orientation.Horizontal)
self.volume_slider.setRange(0, 200)
self.volume_slider.setValue(100)
self.volume_slider.setMaximumWidth(40) # Much smaller
self.volume_slider.setStyleSheet("""
QSlider::groove:horizontal {
border: none;
height: 1px;
background: rgba(255, 255, 255, 0.15);
border-radius: 1px;
}
QSlider::handle:horizontal {
background: #00BFFF;
border: 1px solid #FFFFFF;
width: 6px;
margin: -2px 0;
border-radius: 3px;
}
""")
self.volume_label = QLabel("100%")
self.volume_label.setObjectName("volumeLabel")
self.volume_label.setStyleSheet("""
QLabel#volumeLabel {
color: white;
font-family: "Consolas", "Monaco", monospace;
font-size: 6px;
background: transparent;
border: none;
padding: 0px 2px;
min-width: 22px;
}
""")
# Previous/Next buttons
self.btn_prev = QPushButton("⏮")
self.btn_prev.setFixedSize(16, 16)
self.btn_prev.setStyleSheet("""
QPushButton {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
color: white;
font-size: 6px;
}
QPushButton:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.25);
}
""")
self.btn_next = QPushButton("⏭")
self.btn_next.setFixedSize(16, 16)
self.btn_next.setStyleSheet("""
QPushButton {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 8px;
color: white;
font-size: 6px;
}
QPushButton:hover {
background: rgba(255, 255, 255, 0.15);
border-color: rgba(255, 255, 255, 0.25);
}
""")
# Add widgets to layout (micro-compact arrangement)
layout.addWidget(self.btn_prev)
layout.addWidget(self.btn_play)
layout.addWidget(self.btn_stop)
layout.addWidget(self.btn_next)
layout.addWidget(QLabel("")) # Spacer
layout.addWidget(self.time_label)
layout.addWidget(self.seek_slider)
layout.addWidget(QLabel("")) # Spacer
layout.addWidget(self.btn_mute)
layout.addWidget(self.volume_slider)
layout.addWidget(self.volume_label)
# Connect signals
self.btn_play.clicked.connect(self.toggle_play)
self.btn_stop.clicked.connect(self.stop)
self.btn_mute.clicked.connect(self.toggle_mute)
self.btn_prev.clicked.connect(self.previous_media)
self.btn_next.clicked.connect(self.next_media)
self.seek_slider.valueChanged.connect(self.seek_changed)
self.volume_slider.valueChanged.connect(self.volume_changed)
def toggle_play(self):
if hasattr(self.parent_window, 'toggle_playback'):
self.parent_window.toggle_playback()
def stop(self):
if hasattr(self.parent_window, 'stop_playback'):
self.parent_window.stop_playback()
def toggle_mute(self):
if hasattr(self.parent_window, 'toggle_mute'):
self.parent_window.toggle_mute()
def previous_media(self):
if hasattr(self.parent_window, 'previous_media'):
self.parent_window.previous_media()
def next_media(self):
if hasattr(self.parent_window, 'next_media'):
self.parent_window.next_media()
def take_snapshot(self):
if hasattr(self.parent_window, 'take_snapshot'):
self.parent_window.take_snapshot()
def seek_changed(self, value):
if hasattr(self.parent_window, 'seek_to_position'):
self.parent_window.seek_to_position(value / 1000.0)
def volume_changed(self, value):
if hasattr(self.parent_window, 'set_volume'):
self.parent_window.set_volume(value)
self.volume_label.setText(f"{value}%")
def on_seek_hover(self, event):
"""Show timeline preview on hover"""
if hasattr(self.parent_window, 'show_timeline_preview'):
self.parent_window.show_timeline_preview(True)
def on_seek_leave(self, event):
"""Hide timeline preview on leave"""
if hasattr(self.parent_window, 'show_timeline_preview'):
self.parent_window.show_timeline_preview(False)
def on_seek_mouse_move(self, event):
"""Update timeline preview on mouse move"""
if hasattr(self.parent_window, 'update_timeline_preview'):
# Calculate position based on mouse position
pos = event.position().x()
width = self.seek_slider.width()
if width > 0:
position = pos / width
self.parent_window.update_timeline_preview(position)
def update_time(self, current, total):
"""Update time display"""
def format_time(ms):
seconds = ms // 1000
minutes = seconds // 60
seconds = seconds % 60
return f"{minutes:02d}:{seconds:02d}"
self.time_label.setText(f"{format_time(current)} / {format_time(total)}")
def update_seek_position(self, position):
"""Update seek slider position"""
self.seek_slider.blockSignals(True)
self.seek_slider.setValue(int(position * 1000))
self.seek_slider.blockSignals(False)
class PlaylistWidget(QListWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.parent_window = parent
self.setup_ui()
def setup_ui(self):
self.setSelectionMode(self.SelectionMode.SingleSelection)
self.setAcceptDrops(True)
self.setDragDropMode(self.DragDropMode.DropOnly) # Allow external drops
self.itemDoubleClicked.connect(self.item_double_clicked)
def item_double_clicked(self, item):
if hasattr(self.parent_window, 'play_selected_item'):
self.parent_window.play_selected_item()
def add_media_file(self, file_path):
"""Add a media file to the playlist"""
filename = os.path.basename(file_path) if file_path and "://" not in file_path else file_path
# Create custom widget for playlist item
item_widget = QWidget()
item_layout = QHBoxLayout(item_widget)
item_layout.setContentsMargins(4, 2, 4, 2)
item_layout.setSpacing(4)
# Remove button
remove_btn = QPushButton("✕")
remove_btn.setFixedSize(12, 12)
remove_btn.setStyleSheet("""
QPushButton {
background: rgba(255, 100, 100, 0.8);
border: 1px solid rgba(255, 100, 100, 1.0);
border-radius: 6px;
color: white;
font-size: 6px;
font-weight: bold;
}
QPushButton:hover {
background: rgba(255, 100, 100, 1.0);
border-color: #FF6666;
}
""")
remove_btn.clicked.connect(lambda: self.remove_item_by_file(file_path))
# File name label
name_label = QLabel(filename)
name_label.setStyleSheet("""
QLabel {
color: white;
font-size: 9px;
background: transparent;
border: none;
}
""")
name_label.setWordWrap(True)
# Add to layout
item_layout.addWidget(remove_btn)
item_layout.addWidget(name_label)
item_layout.addStretch()
# Create list item
item = QListWidgetItem()
item.setData(Qt.ItemDataRole.UserRole, file_path)
item.setSizeHint(item_widget.sizeHint())
# Add to list
self.addItem(item)
self.setItemWidget(item, item_widget)
def remove_item_by_file(self, file_path):
"""Remove an item from the playlist by file path"""
for i in range(self.count()):
item = self.item(i)
if item and item.data(Qt.ItemDataRole.UserRole) == file_path:
# If this is the currently playing file, stop playback
if hasattr(self.parent_window, 'app_state') and self.parent_window.app_state.last_file == file_path:
if hasattr(self.parent_window, 'stop_playback'):
self.parent_window.stop_playback()
# Remove the item
self.takeItem(i)
break
def get_current_file(self):
"""Get the currently selected file path"""
current_item = self.currentItem()
if current_item:
return current_item.data(Qt.ItemDataRole.UserRole)
return None
def find_file_index(self, file_path):
"""Find the index of a file in the playlist"""
for i in range(self.count()):
item = self.item(i)
if item and item.data(Qt.ItemDataRole.UserRole) == file_path:
return i
return None
def get_file_at_index(self, index):
"""Get the file path at a specific index"""
if 0 <= index < self.count():
item = self.item(index)
if item:
return item.data(Qt.ItemDataRole.UserRole)
return None
def dragEnterEvent(self, event):
"""Handle drag enter event"""
if event.mimeData().hasUrls():
# Check if any of the URLs are supported media files or directories
urls = event.mimeData().urls()
for url in urls:
file_path = url.toLocalFile()
if (self.parent_window.is_supported_media_file(file_path) or
os.path.isdir(file_path)):
event.acceptProposedAction()
return
event.ignore()
def dropEvent(self, event):
"""Handle drop event with enhanced support for multiple files/folders"""
if event.mimeData().hasUrls():
urls = event.mimeData().urls()
media_files = []
folders_processed = 0
files_processed = 0
# Process all dropped items
for url in urls:
file_path = url.toLocalFile()
if os.path.isdir(file_path):
# Handle folder - find all media files recursively
folder_files = self.parent_window.find_media_files_in_folder(file_path)
media_files.extend(folder_files)
folders_processed += 1
if folder_files:
self.parent_window.status_bar.showMessage(f"Scanning folder: {os.path.basename(file_path)} ({len(folder_files)} files found)", 2000)
elif self.parent_window.is_supported_media_file(file_path):
# Handle individual media file
media_files.append(file_path)
files_processed += 1
if media_files:
# Remove duplicates while preserving order
seen = set()
unique_media_files = []
for file_path in media_files:
if file_path not in seen:
seen.add(file_path)
unique_media_files.append(file_path)
# Sort files naturally for better organization
unique_media_files.sort()
# Clear current playlist and add all files
self.clear()
for file_path in unique_media_files:
self.add_media_file(file_path)
# Load and auto-play the first file
if unique_media_files:
self.parent_window.load_media(unique_media_files[0])
self.setCurrentRow(0)
# Auto-start playback
QTimer.singleShot(100, self.parent_window.media_player.play)
# Show comprehensive status message
status_parts = []
if files_processed > 0:
status_parts.append(f"{files_processed} file{'s' if files_processed != 1 else ''}")
if folders_processed > 0:
status_parts.append(f"{folders_processed} folder{'s' if folders_processed != 1 else ''}")
status_msg = f"Loaded {len(unique_media_files)} media files from {', '.join(status_parts)}"
self.parent_window.status_bar.showMessage(status_msg, 5000)
event.acceptProposedAction()
return