-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
4757 lines (3883 loc) · 179 KB
/
main.py
File metadata and controls
4757 lines (3883 loc) · 179 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 json
import math
import subprocess
import shutil
import webbrowser
import re
import tempfile
import os
import time
from datetime import datetime
from dataclasses import dataclass, field, asdict
from typing import Optional, List, Tuple, Dict, Any
from pathlib import Path
from enum import Enum
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGridLayout, QTabWidget, QPushButton, QListWidget, QListWidgetItem,
QScrollArea, QLabel, QSpinBox, QDoubleSpinBox, QFormLayout, QFileDialog, QMenu,
QSplitter, QFrame, QMessageBox, QAbstractItemView, QSizePolicy,
QComboBox, QCheckBox, QGroupBox, QColorDialog, QProgressDialog, QDialog,
QProgressBar, QPlainTextEdit, QToolButton, QTextEdit
)
from PySide6.QtCore import (
Qt, Signal, QMimeData, QByteArray, QDataStream, QIODevice, QSize, QRectF, QPointF,
QThread, QObject, QTimer, QProcess, QElapsedTimer
)
from PySide6.QtGui import (
QAction, QDrag, QColor, QPalette, QPainter, QPen, QBrush, QFont, QDesktopServices,
QPixmap, QImage
)
# =============================================================================
# FFMPEG/FFPROBE DISCOVERY
# =============================================================================
def find_ffmpeg() -> Optional[str]:
"""
Find FFmpeg executable, checking bundled location first, then system PATH.
Search Order:
1. Bundled ffmpeg in app directory (ffmpeg.exe on Windows, ffmpeg on Unix)
2. System PATH (using shutil.which)
3. Direct test of common command (handles venv PATH issues)
Returns:
Path to ffmpeg executable, or None if not found
"""
# Get the application directory
app_dir = Path(__file__).parent.resolve()
# Check for bundled ffmpeg
if sys.platform == "win32":
bundled_path = app_dir / "ffmpeg.exe"
else:
bundled_path = app_dir / "ffmpeg"
if bundled_path.exists() and bundled_path.is_file():
return str(bundled_path)
# Try shutil.which first
which_result = shutil.which("ffmpeg")
if which_result:
return which_result
# Fallback: try to run ffmpeg directly to see if it's in PATH
# This handles cases where shutil.which fails in venvs
try:
result = subprocess.run(
["ffmpeg", "-version"],
capture_output=True,
timeout=3,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
if result.returncode == 0:
return "ffmpeg" # It's in PATH, command works
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
return None
def find_ffprobe() -> Optional[str]:
"""
Find ffprobe executable, checking bundled location first, then system PATH.
Returns:
Path to ffprobe executable, or None if not found
"""
app_dir = Path(__file__).parent.resolve()
if sys.platform == "win32":
bundled_path = app_dir / "ffprobe.exe"
else:
bundled_path = app_dir / "ffprobe"
if bundled_path.exists() and bundled_path.is_file():
return str(bundled_path)
# Try shutil.which first
which_result = shutil.which("ffprobe")
if which_result:
return which_result
# Fallback: try to run ffprobe directly
try:
result = subprocess.run(
["ffprobe", "-version"],
capture_output=True,
timeout=3,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
if result.returncode == 0:
return "ffprobe" # It's in PATH, command works
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
pass
return None
# =============================================================================
# ENUMS
# =============================================================================
class ScalingMode(Enum):
"""Video scaling modes for grid cells."""
LETTERBOX = "letterbox" # Fit, centered with bars
CROP = "crop" # Fill, centered with crop
STRETCH = "stretch" # Stretch to fill
class AnchorPosition(Enum):
"""Canvas anchor positions for grid placement."""
CENTER = "center"
TOP_LEFT = "top_left"
TOP_RIGHT = "top_right"
BOTTOM_LEFT = "bottom_left"
BOTTOM_RIGHT = "bottom_right"
class ResolutionPreset(Enum):
"""Output resolution presets."""
HD_1080P = "1080p"
QHD_1440P = "1440p"
UHD_4K = "4k"
CUSTOM = "custom"
class QualityPreset(Enum):
"""Export speed presets."""
BEST_QUALITY = "best" # slow preset, CRF 17
BALANCED = "balanced" # medium preset, CRF 19 (default)
FAST_EXPORT = "fast" # veryfast preset, CRF 25
class DurationMode(Enum):
"""Duration mode for export."""
SHORTEST_CLIP = "shortest"
CUSTOM = "custom"
class AudioSource(Enum):
"""Audio source for export."""
NONE = "none"
FIRST_CLIP = "first"
SELECTED_CLIP = "selected"
# =============================================================================
# FFPROBE UTILITY (must be defined before Clip class)
# =============================================================================
def probe_video(file_path: str) -> Optional[Dict[str, Any]]:
"""
Use ffprobe to extract video metadata in JSON format.
Extracts:
- duration: Video duration in seconds
- width: Video width in pixels
- height: Video height in pixels
- fps: Frame rate (as float)
- has_audio: Whether the file has an audio stream
Args:
file_path: Path to the video file
Returns:
Dictionary with metadata, or None if ffprobe fails
"""
# Check if ffprobe is available (bundled or system PATH)
ffprobe_path = find_ffprobe()
if not ffprobe_path:
return None
try:
# Run ffprobe with JSON output for streams and format
cmd = [
ffprobe_path,
"-v", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
file_path
]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=10, # Timeout after 10 seconds
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
if result.returncode != 0:
return None
data = json.loads(result.stdout)
# Extract format duration
duration = float(data.get("format", {}).get("duration", 0))
# Find video stream
width = 0
height = 0
fps = 0.0
has_audio = False
for stream in data.get("streams", []):
codec_type = stream.get("codec_type", "")
if codec_type == "video" and width == 0:
width = stream.get("width", 0)
height = stream.get("height", 0)
# Parse frame rate from avg_frame_rate or r_frame_rate
# Format is typically "30000/1001" or "30/1"
fps_str = stream.get("avg_frame_rate") or stream.get("r_frame_rate", "0/1")
if "/" in fps_str:
num, den = fps_str.split("/")
if int(den) > 0:
fps = float(num) / float(den)
else:
fps = float(fps_str) if fps_str else 0.0
elif codec_type == "audio":
has_audio = True
return {
"duration": duration,
"width": width,
"height": height,
"fps": round(fps, 3), # Round to 3 decimal places
"has_audio": has_audio
}
except (subprocess.TimeoutExpired, json.JSONDecodeError, ValueError, OSError):
return None
def generate_thumbnail(video_path: str, size: Tuple[int, int] = (320, 180)) -> str:
"""
Generate a thumbnail image from a video file using FFmpeg.
Extracts a frame from 1 second into the video (or first frame if shorter)
and saves it as a temporary JPEG file.
Args:
video_path: Path to the video file
size: Thumbnail size (width, height), default 320x180 (16:9)
Returns:
Path to the generated thumbnail, or empty string if failed
"""
ffmpeg_path = find_ffmpeg()
if not ffmpeg_path:
return ""
try:
# Create a temporary file for the thumbnail
# Use a persistent temp directory so thumbnails survive during session
thumb_dir = Path(tempfile.gettempdir()) / "ezgrid_thumbnails"
thumb_dir.mkdir(exist_ok=True)
# Create unique filename based on video path hash
video_hash = abs(hash(video_path)) % (10 ** 10)
thumb_path = thumb_dir / f"thumb_{video_hash}.jpg"
# If thumbnail already exists, return it
if thumb_path.exists():
return str(thumb_path)
# Generate thumbnail using FFmpeg
# -ss 1: seek to 1 second (fast for most videos)
# -vframes 1: extract only 1 frame
# -vf scale: scale to target size maintaining aspect ratio
cmd = [
ffmpeg_path,
"-y", # Overwrite
"-ss", "1", # Seek to 1 second
"-i", video_path,
"-vframes", "1",
"-vf", f"scale={size[0]}:{size[1]}:force_original_aspect_ratio=decrease,pad={size[0]}:{size[1]}:(ow-iw)/2:(oh-ih)/2:black",
"-q:v", "2", # High quality JPEG
str(thumb_path)
]
result = subprocess.run(
cmd,
capture_output=True,
timeout=10,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
if result.returncode == 0 and thumb_path.exists():
return str(thumb_path)
# If seeking to 1s failed (video too short), try first frame
cmd[3] = "0" # Change -ss to 0
result = subprocess.run(
cmd,
capture_output=True,
timeout=10,
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
)
if result.returncode == 0 and thumb_path.exists():
return str(thumb_path)
except (subprocess.TimeoutExpired, OSError):
pass
return ""
# Global thumbnail cache for QPixmap objects
_thumbnail_cache: Dict[str, QPixmap] = {}
def get_thumbnail_pixmap(thumbnail_path: str) -> Optional[QPixmap]:
"""
Get a QPixmap for a thumbnail, using cache for performance.
Args:
thumbnail_path: Path to thumbnail image file
Returns:
QPixmap or None if loading failed
"""
if not thumbnail_path or not Path(thumbnail_path).exists():
return None
if thumbnail_path not in _thumbnail_cache:
pixmap = QPixmap(thumbnail_path)
if not pixmap.isNull():
_thumbnail_cache[thumbnail_path] = pixmap
else:
return None
return _thumbnail_cache.get(thumbnail_path)
# =============================================================================
# DATA MODEL
# =============================================================================
@dataclass
class Clip:
"""Represents an imported video clip with metadata."""
path: str
display_name: str
duration: float = 0.0 # Duration in seconds
width: int = 0 # Video width in pixels
height: int = 0 # Video height in pixels
fps: float = 0.0 # Frame rate
has_audio: bool = False # Whether clip has audio stream
thumbnail_path: str = "" # Path to generated thumbnail image
@classmethod
def from_path(cls, file_path: str) -> "Clip":
"""Create a Clip from a file path with metadata from ffprobe."""
clip = cls(
path=file_path,
display_name=Path(file_path).name
)
# Try to probe metadata (non-blocking, fails gracefully)
metadata = probe_video(file_path)
if metadata:
clip.duration = metadata.get("duration", 0.0)
clip.width = metadata.get("width", 0)
clip.height = metadata.get("height", 0)
clip.fps = metadata.get("fps", 0.0)
clip.has_audio = metadata.get("has_audio", False)
# Generate thumbnail
clip.thumbnail_path = generate_thumbnail(file_path)
return clip
@dataclass
class GridSettings:
"""Grid configuration settings with full layout controls."""
rows: int = 2
columns: int = 2
tile_width: int = 320 # Uniform tile width in pixels
tile_height: int = 180 # Uniform tile height (16:9 = 320x180)
gap_horizontal: int = 4 # Horizontal gap between cells
gap_vertical: int = 4 # Vertical gap between cells
background_color: str = "#000000" # Background color (hex)
scaling_mode: str = "letterbox" # ScalingMode value
anchor: str = "center" # AnchorPosition value
center_last_row: bool = True # Center clips in last row if partial
canvas_width: int = 1920 # Output canvas width
canvas_height: int = 1080 # Output canvas height (16:9)
auto_tile_size: bool = True # Auto-compute tile size to fit canvas
@dataclass
class ExportSettings:
"""Export configuration settings."""
# Resolution
resolution_preset: str = "1080p" # ResolutionPreset value
custom_width: int = 1920
custom_height: int = 1080
# FPS
fps_auto: bool = True
fps_manual: float = 30.0
# Quality/Speed
quality_preset: str = "balanced" # QualityPreset value (best/balanced/fast)
# Performance
use_proxies: bool = True # Use proxy files for faster export
# Duration
duration_mode: str = "shortest" # DurationMode value
custom_duration: float = 10.0 # seconds
# Audio
audio_source: str = "none" # AudioSource value
audio_clip_index: int = 0 # For "selected" audio source
def get_resolution(self) -> Tuple[int, int]:
"""Get the actual output resolution."""
preset = ResolutionPreset(self.resolution_preset)
if preset == ResolutionPreset.HD_1080P:
return (1920, 1080)
elif preset == ResolutionPreset.QHD_1440P:
return (2560, 1440)
elif preset == ResolutionPreset.UHD_4K:
return (3840, 2160)
else: # CUSTOM
return (self.custom_width, self.custom_height)
@dataclass
class CellLayout:
"""Computed layout for a single grid cell."""
row: int
col: int
x: float # X position on canvas
y: float # Y position on canvas
width: float # Cell width
height: float # Cell height
clip_index: int # Index of clip in this cell (-1 if empty)
is_visible: bool # Whether this cell should be rendered
@dataclass
class GridLayout:
"""Computed layout for the entire grid."""
cells: List[CellLayout]
total_width: float # Total grid width (without offset)
total_height: float # Total grid height (without offset)
offset_x: float # X offset for centering/anchoring
offset_y: float # Y offset for centering/anchoring
scale: float # Scale factor for preview
# =============================================================================
# UNDO/REDO SYSTEM
# =============================================================================
class UndoCommand:
"""Base class for undoable commands."""
def __init__(self, description: str):
self.description = description
def undo(self):
"""Undo this command."""
raise NotImplementedError
def redo(self):
"""Redo this command."""
raise NotImplementedError
class ReorderClipsCommand(UndoCommand):
"""Command for reordering clips (move from_index to to_index)."""
def __init__(self, model: "DataModel", from_index: int, to_index: int):
super().__init__(f"Reorder clip {from_index} to {to_index}")
self.model = model
self.from_index = from_index
self.to_index = to_index
def undo(self):
"""Move back from to_index to from_index."""
clip = self.model.clips.pop(self.to_index)
self.model.clips.insert(self.from_index, clip)
def redo(self):
"""Move from from_index to to_index."""
clip = self.model.clips.pop(self.from_index)
self.model.clips.insert(self.to_index, clip)
class SwapClipsCommand(UndoCommand):
"""Command for swapping two clips."""
def __init__(self, model: "DataModel", index_a: int, index_b: int):
super().__init__(f"Swap clips {index_a} and {index_b}")
self.model = model
self.index_a = index_a
self.index_b = index_b
def undo(self):
"""Swap back."""
self.model.clips[self.index_a], self.model.clips[self.index_b] = \
self.model.clips[self.index_b], self.model.clips[self.index_a]
def redo(self):
"""Swap again."""
self.model.clips[self.index_a], self.model.clips[self.index_b] = \
self.model.clips[self.index_b], self.model.clips[self.index_a]
class RemoveClipCommand(UndoCommand):
"""Command for removing a clip."""
def __init__(self, model: "DataModel", clip_index: int, clip: "Clip"):
super().__init__(f"Remove clip {clip_index}")
self.model = model
self.clip_index = clip_index
self.clip = clip # Store the clip for undo
def undo(self):
"""Re-insert the clip."""
self.model.clips.insert(self.clip_index, self.clip)
def redo(self):
"""Remove the clip again."""
self.model.clips.pop(self.clip_index)
class UndoStack:
"""Manages undo/redo command stack."""
def __init__(self, max_size: int = 100):
self.undo_stack: List[UndoCommand] = []
self.redo_stack: List[UndoCommand] = []
self.max_size = max_size
def push(self, command: UndoCommand):
"""Push a command onto the undo stack and execute it."""
command.redo() # Execute the command
self.undo_stack.append(command)
self.redo_stack.clear() # Clear redo stack on new action
# Limit stack size
if len(self.undo_stack) > self.max_size:
self.undo_stack.pop(0)
def undo(self) -> bool:
"""Undo the last command. Returns True if successful."""
if not self.undo_stack:
return False
command = self.undo_stack.pop()
command.undo()
self.redo_stack.append(command)
return True
def redo(self) -> bool:
"""Redo the last undone command. Returns True if successful."""
if not self.redo_stack:
return False
command = self.redo_stack.pop()
command.redo()
self.undo_stack.append(command)
return True
def can_undo(self) -> bool:
"""Check if undo is available."""
return len(self.undo_stack) > 0
def can_redo(self) -> bool:
"""Check if redo is available."""
return len(self.redo_stack) > 0
def clear(self):
"""Clear all undo/redo history."""
self.undo_stack.clear()
self.redo_stack.clear()
# =============================================================================
# LOGGING AND DETAILS PANEL SYSTEM
# =============================================================================
@dataclass
class ErrorEntry:
"""Represents an error entry for the error history."""
timestamp: str
summary: str
details: str
exit_code: int = 0
output_path: str = ""
command: str = ""
class LogManager(QObject):
"""
Singleton manager for logging, progress tracking, and error history.
Signals:
log_added: Emitted when a log line is added (message)
progress_updated: Emitted when progress changes (task, current, total, item_name, elapsed_ms, eta_ms)
error_added: Emitted when an error is recorded (ErrorEntry)
ffmpeg_stats_updated: Emitted with parsed FFmpeg stats (time_str, fps_str, speed_str)
"""
log_added = Signal(str)
progress_updated = Signal(str, int, int, str, int, int) # task, current, total, item, elapsed_ms, eta_ms
error_added = Signal(object) # ErrorEntry
ffmpeg_stats_updated = Signal(str, str, str) # time, fps, speed
task_started = Signal(str) # task name
task_finished = Signal(str, bool) # task name, success
_instance = None
@classmethod
def instance(cls) -> 'LogManager':
"""Get the singleton LogManager instance."""
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialized = False
return cls._instance
def __init__(self):
if self._initialized:
return
super().__init__()
self._initialized = True
self.errors: List[ErrorEntry] = []
self._log_buffer: List[str] = []
self._flush_timer = QTimer()
self._flush_timer.timeout.connect(self._flush_logs)
self._flush_timer.setInterval(150) # Batch logs every 150ms
def log(self, message: str, timestamp: bool = True):
"""Add a log message (buffered for efficiency)."""
if timestamp:
ts = datetime.now().strftime("%H:%M:%S")
line = f"[{ts}] {message}"
else:
line = message
self._log_buffer.append(line)
if not self._flush_timer.isActive():
self._flush_timer.start()
def _flush_logs(self):
"""Flush buffered log messages to UI."""
if self._log_buffer:
combined = "\n".join(self._log_buffer)
self.log_added.emit(combined)
self._log_buffer.clear()
self._flush_timer.stop()
def flush_now(self):
"""Force immediate flush of log buffer."""
self._flush_logs()
def update_progress(self, task: str, current: int, total: int, item_name: str = "",
elapsed_ms: int = 0, eta_ms: int = 0):
"""Update progress for a task."""
self.progress_updated.emit(task, current, total, item_name, elapsed_ms, eta_ms)
def update_ffmpeg_stats(self, time_str: str, fps_str: str, speed_str: str):
"""Update FFmpeg-specific stats."""
self.ffmpeg_stats_updated.emit(time_str, fps_str, speed_str)
def start_task(self, task_name: str):
"""Signal that a task has started."""
self.log(f"Started: {task_name}")
self.task_started.emit(task_name)
def finish_task(self, task_name: str, success: bool = True):
"""Signal that a task has finished."""
status = "completed" if success else "failed"
self.log(f"Finished: {task_name} ({status})")
self.flush_now()
self.task_finished.emit(task_name, success)
def add_error(self, summary: str, details: str, exit_code: int = 0,
output_path: str = "", command: str = ""):
"""Add an error to the error history."""
entry = ErrorEntry(
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
summary=summary,
details=details,
exit_code=exit_code,
output_path=output_path,
command=command
)
self.errors.append(entry)
self.error_added.emit(entry)
self.log(f"ERROR: {summary}")
def clear_errors(self):
"""Clear error history."""
self.errors.clear()
# Global log manager instance
def get_log_manager() -> LogManager:
"""Get the global LogManager instance."""
return LogManager()
class DetailsPanel(QWidget):
"""
Collapsible details panel with Progress, Logs, and Errors tabs.
Shows detailed information about long-running tasks, live logs,
and error history.
"""
def __init__(self, parent=None):
super().__init__(parent)
self._collapsed = True
self._elapsed_timer = QElapsedTimer()
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
# Header with toggle button
header = QWidget()
header.setFixedHeight(28)
header.setStyleSheet("background-color: #2a2a2a; border-top: 1px solid #404040;")
header_layout = QHBoxLayout(header)
header_layout.setContentsMargins(8, 0, 8, 0)
self.toggle_btn = QToolButton()
self.toggle_btn.setArrowType(Qt.RightArrow)
self.toggle_btn.setCheckable(True)
self.toggle_btn.setStyleSheet("QToolButton { border: none; }")
self.toggle_btn.clicked.connect(self._toggle_collapsed)
header_layout.addWidget(self.toggle_btn)
self.header_label = QLabel("Details")
self.header_label.setStyleSheet("color: #aaaaaa; font-weight: bold;")
header_layout.addWidget(self.header_label)
header_layout.addStretch()
# Status indicator in header
self.status_label = QLabel("")
self.status_label.setStyleSheet("color: #808080; font-size: 11px;")
header_layout.addWidget(self.status_label)
layout.addWidget(header)
# Content area (collapsible)
self.content = QWidget()
self.content.setVisible(False)
content_layout = QVBoxLayout(self.content)
content_layout.setContentsMargins(0, 0, 0, 0)
# Tab widget
self.tabs = QTabWidget()
self.tabs.setFixedHeight(200)
# Progress tab
self._setup_progress_tab()
# Logs tab
self._setup_logs_tab()
# Errors tab
self._setup_errors_tab()
content_layout.addWidget(self.tabs)
layout.addWidget(self.content)
# Connect to log manager
log_mgr = get_log_manager()
log_mgr.log_added.connect(self._on_log_added)
log_mgr.progress_updated.connect(self._on_progress_updated)
log_mgr.error_added.connect(self._on_error_added)
log_mgr.ffmpeg_stats_updated.connect(self._on_ffmpeg_stats)
log_mgr.task_started.connect(self._on_task_started)
log_mgr.task_finished.connect(self._on_task_finished)
def _setup_progress_tab(self):
"""Setup the Progress tab."""
progress_widget = QWidget()
layout = QVBoxLayout(progress_widget)
layout.setContentsMargins(8, 8, 8, 8)
layout.setSpacing(6)
# Task name
self.task_label = QLabel("No active task")
self.task_label.setStyleSheet("font-weight: bold; font-size: 12px;")
layout.addWidget(self.task_label)
# Progress bar
self.detail_progress = QProgressBar()
self.detail_progress.setRange(0, 100)
self.detail_progress.setValue(0)
layout.addWidget(self.detail_progress)
# Current item
self.item_label = QLabel("")
self.item_label.setStyleSheet("color: #aaaaaa;")
layout.addWidget(self.item_label)
# Time info (elapsed / ETA)
time_layout = QHBoxLayout()
self.elapsed_label = QLabel("Elapsed: --")
self.elapsed_label.setStyleSheet("color: #808080;")
time_layout.addWidget(self.elapsed_label)
self.eta_label = QLabel("ETA: --")
self.eta_label.setStyleSheet("color: #808080;")
time_layout.addWidget(self.eta_label)
time_layout.addStretch()
layout.addLayout(time_layout)
# FFmpeg stats (only shown during export)
self.ffmpeg_stats_label = QLabel("")
self.ffmpeg_stats_label.setStyleSheet("color: #808080; font-family: monospace;")
self.ffmpeg_stats_label.setVisible(False)
layout.addWidget(self.ffmpeg_stats_label)
layout.addStretch()
self.tabs.addTab(progress_widget, "Progress")
def _setup_logs_tab(self):
"""Setup the Logs tab."""
self.logs_text = QPlainTextEdit()
self.logs_text.setReadOnly(True)
self.logs_text.setStyleSheet("""
QPlainTextEdit {
background-color: #1a1a1a;
color: #cccccc;
font-family: Consolas, monospace;
font-size: 11px;
border: none;
}
""")
self.logs_text.setMaximumBlockCount(1000) # Limit to 1000 lines
self.tabs.addTab(self.logs_text, "Logs")
def _setup_errors_tab(self):
"""Setup the Errors tab."""
errors_widget = QWidget()
layout = QVBoxLayout(errors_widget)
layout.setContentsMargins(4, 4, 4, 4)
layout.setSpacing(4)
# Error list
self.error_list = QListWidget()
self.error_list.setStyleSheet("""
QListWidget {
background-color: #1a1a1a;
color: #ff6666;
border: none;
}
QListWidget::item:selected {
background-color: #3a3a3a;
}
""")
self.error_list.itemClicked.connect(self._on_error_clicked)
layout.addWidget(self.error_list)
# Error details (expandable)
self.error_details = QTextEdit()
self.error_details.setReadOnly(True)
self.error_details.setVisible(False)
self.error_details.setMaximumHeight(100)
self.error_details.setStyleSheet("""
QTextEdit {
background-color: #1a1a1a;
color: #cccccc;
font-family: Consolas, monospace;
font-size: 10px;
border: 1px solid #404040;
}
""")
layout.addWidget(self.error_details)
# Buttons
btn_layout = QHBoxLayout()
self.copy_cmd_btn = QPushButton("Copy Command")
self.copy_cmd_btn.setVisible(False)
self.copy_cmd_btn.clicked.connect(self._copy_error_command)
btn_layout.addWidget(self.copy_cmd_btn)
clear_btn = QPushButton("Clear Errors")
clear_btn.clicked.connect(self._clear_errors)
btn_layout.addWidget(clear_btn)
btn_layout.addStretch()
layout.addLayout(btn_layout)
self.tabs.addTab(errors_widget, "Errors (0)")
def _toggle_collapsed(self):
"""Toggle the collapsed state."""
self._collapsed = not self._collapsed
self.content.setVisible(not self._collapsed)
self.toggle_btn.setArrowType(Qt.DownArrow if not self._collapsed else Qt.RightArrow)
def expand(self):
"""Expand the panel."""
if self._collapsed:
self._toggle_collapsed()
self.toggle_btn.setChecked(True)
def _on_log_added(self, message: str):
"""Handle new log message."""
self.logs_text.appendPlainText(message)
# Auto-scroll to bottom
scrollbar = self.logs_text.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
def _on_progress_updated(self, task: str, current: int, total: int, item: str,
elapsed_ms: int, eta_ms: int):
"""Handle progress update."""
self.task_label.setText(task)
if total > 0:
percent = int((current / total) * 100)
self.detail_progress.setValue(percent)
self.item_label.setText(f"Processing: {item}" if item else f"{current} / {total}")
else:
self.detail_progress.setValue(current)
self.item_label.setText(item)
# Format elapsed time
if elapsed_ms > 0:
elapsed_sec = elapsed_ms / 1000
self.elapsed_label.setText(f"Elapsed: {self._format_time(elapsed_sec)}")
# Format ETA
if eta_ms > 0:
eta_sec = eta_ms / 1000
self.eta_label.setText(f"ETA: {self._format_time(eta_sec)}")
else:
self.eta_label.setText("ETA: --")
# Update header status
if total > 0:
self.status_label.setText(f"{task}: {current}/{total}")
def _on_ffmpeg_stats(self, time_str: str, fps_str: str, speed_str: str):
"""Handle FFmpeg stats update."""
self.ffmpeg_stats_label.setVisible(True)
parts = []
if time_str:
parts.append(f"time={time_str}")
if fps_str:
parts.append(f"fps={fps_str}")
if speed_str:
parts.append(f"speed={speed_str}")
self.ffmpeg_stats_label.setText(" ".join(parts))
def _on_task_started(self, task: str):
"""Handle task start."""
self.task_label.setText(task)
self.detail_progress.setValue(0)
self.item_label.setText("")
self.elapsed_label.setText("Elapsed: 0s")
self.eta_label.setText("ETA: --")
self.ffmpeg_stats_label.setVisible(False)
self.status_label.setText(f"{task}...")
def _on_task_finished(self, task: str, success: bool):
"""Handle task finish."""
if success:
self.detail_progress.setValue(100)