Repository navigation
Expand file tree
/
Copy pathmp4trim_app.py
More file actions
1643 lines (1451 loc) · 65.1 KB
/
Copy pathmp4trim_app.py
File metadata and controls
1643 lines (1451 loc) · 65.1 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
"""Main window (Trimmer), app entry point, and --selftest."""
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from PySide6.QtCore import (Property, QEvent, QObject, QSettings, QSizeF,
Qt, QThread, QTimer, QUrl, Signal)
from PySide6.QtGui import (QAction, QColor, QFont, QIcon, QImage,
QKeySequence, QPixmap)
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
from PySide6.QtMultimediaWidgets import QGraphicsVideoItem
from PySide6.QtWidgets import (QApplication, QComboBox, QFileDialog,
QGraphicsScene, QGraphicsView,
QMenuBar, QStatusBar,
QHBoxLayout, QLabel, QMainWindow, QMenu,
QMessageBox, QProgressBar, QPushButton,
QSizePolicy, QSlider, QStackedWidget,
QVBoxLayout, QWidget)
import mp4trim_updater as upd
from mp4trim_core import * # noqa: F401,F403
from mp4trim_updater import UpdateChecker
from mp4trim_workers import (Analyzer, FrameGrabber, Job, ProbeWorker,
ScrubEngine, SnapGrabber)
from mp4trim_widgets import (SHORTCUTS_HELP, STYLE, SnapshotDialog,
SnapshotView, Timeline)
# GlassPanel / AutoHider land in mp4trim_widgets; until then, develop against
# minimal local stand-ins that implement the same contract (no animation).
try:
from mp4trim_widgets import AutoHider, GlassPanel
GLASS_IS_STUB = False
except ImportError:
GLASS_IS_STUB = True
class GlassPanel(QWidget):
"""Fallback stand-in for mp4trim_widgets.GlassPanel (no fade)."""
visibility_changed = Signal(bool)
def __init__(self, parent=None):
super().__init__(parent)
self._pinned = False
lay = QVBoxLayout(self)
lay.setContentsMargins(14, 10, 14, 10)
lay.setSpacing(6)
self.setAutoFillBackground(True)
def fade_in(self, ms: int = 160):
if not self.isVisible():
self.show()
self.visibility_changed.emit(True)
def fade_out(self, ms: int = 260):
if self._pinned:
return
if self.isVisible():
self.hide()
self.visibility_changed.emit(False)
def _get_pinned(self) -> bool:
return self._pinned
def _set_pinned(self, v: bool):
self._pinned = bool(v)
pinned = Property(bool, _get_pinned, _set_pinned)
class AutoHider(QObject):
"""Fallback stand-in for mp4trim_widgets.AutoHider (never hides)."""
def __init__(self, window, panels, idle_ms=2000, cursor_target=None):
super().__init__(window)
self.panels = list(panels)
self.idle_ms = idle_ms
self.cursor_target = cursor_target
self.hide_cursor_when_idle = True
self._enabled = False
def set_enabled(self, on: bool):
self._enabled = bool(on)
if not on:
self.poke()
def poke(self):
for p in self.panels:
p.fade_in()
class _EdgeResizer(QObject):
"""Frameless windows lose their resize border; give it back: within
BORDER px of an edge show the resize cursor and hand the drag to the
OS (startSystemResize keeps Aero snap etc.)."""
BORDER = 6
def __init__(self, win):
super().__init__(win)
self.win = win
self._cursor_set = False
def _edges(self, gp):
w = self.win
if w.isMaximized() or w.isFullScreen():
return Qt.Edges()
g = w.frameGeometry()
b = self.BORDER
x, y = gp.x(), gp.y()
if not (g.left() - 1 <= x <= g.right() + 1
and g.top() - 1 <= y <= g.bottom() + 1):
return Qt.Edges()
e = Qt.Edges()
if x <= g.left() + b:
e |= Qt.LeftEdge
elif x >= g.right() - b:
e |= Qt.RightEdge
if y <= g.top() + b:
e |= Qt.TopEdge
elif y >= g.bottom() - b:
e |= Qt.BottomEdge
return e
@staticmethod
def _cursor(e):
if e in (Qt.LeftEdge | Qt.TopEdge, Qt.RightEdge | Qt.BottomEdge):
return Qt.SizeFDiagCursor
if e in (Qt.RightEdge | Qt.TopEdge, Qt.LeftEdge | Qt.BottomEdge):
return Qt.SizeBDiagCursor
if e & (Qt.LeftEdge | Qt.RightEdge):
return Qt.SizeHorCursor
return Qt.SizeVerCursor
def eventFilter(self, obj, ev):
t = ev.type()
if t not in (QEvent.MouseMove, QEvent.MouseButtonPress):
return False
if not isinstance(obj, QWidget) or obj.window() is not self.win:
return False
e = self._edges(ev.globalPosition().toPoint())
if t == QEvent.MouseMove:
if e and not ev.buttons():
if not self._cursor_set:
QApplication.setOverrideCursor(self._cursor(e))
self._cursor_set = True
else:
QApplication.changeOverrideCursor(self._cursor(e))
elif self._cursor_set:
QApplication.restoreOverrideCursor()
self._cursor_set = False
return False
if e and ev.button() == Qt.LeftButton:
h = self.win.windowHandle()
if h is not None:
h.startSystemResize(e)
return True
return False
class _VideoView(QGraphicsView):
"""Borderless graphics view that keeps the video item filling it.
QVideoWidget is a native win32 child window that Windows composites
over sibling Qt widgets, hiding the glass panels. QGraphicsVideoItem
renders through Qt's scene graph instead, so normal stacking works.
"""
def __init__(self, scene, item):
super().__init__(scene)
self._item = item
self.setFrameShape(QGraphicsView.NoFrame)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QColor(0, 0, 0))
self.setRenderHints(self.renderHints())
item.nativeSizeChanged.connect(lambda *_: self._fit())
def _fit(self):
vp = self.viewport().size()
self._item.setSize(QSizeF(vp.width(), vp.height()))
self.setSceneRect(0, 0, vp.width(), vp.height())
def resizeEvent(self, e):
super().resizeEvent(e)
self._fit()
class _TierCombo(QComboBox):
"""QComboBox that reports when its popup is open (used to pin panels)."""
popup_open = Signal(bool)
def showPopup(self):
self.popup_open.emit(True)
super().showPopup()
def hidePopup(self):
super().hidePopup()
self.popup_open.emit(False)
class _FlexWidget(QWidget):
"""Container whose sizeHint().width() is always 0.
Placed in an HBoxLayout with stretch > 0 so it expands to fill
remaining space without inflating the parent layout's sizeHint.
"""
def sizeHint(self):
sh = super().sizeHint()
sh.setWidth(0)
return sh
def minimumSizeHint(self):
sh = super().minimumSizeHint()
sh.setWidth(0)
return sh
# ------------------------------------------------------------- main window
class Trimmer(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("mp4trim")
# no native title bar: window controls live in the top glass panel
self.setWindowFlag(Qt.FramelessWindowHint, True)
self.setMinimumSize(640, 360)
# menu + status bar are overlay widgets inside the glass panels so
# the video owns the whole client area (no bars, no letterbox)
self._menu_bar = QMenuBar()
self._menu_bar.setNativeMenuBar(False)
self._status_bar = QStatusBar()
self._status_bar.setSizeGripEnabled(False)
self.settings = QSettings("mp4trim", "mp4trim")
geo = self.settings.value("geometry")
if geo is None or not self.restoreGeometry(geo):
self.resize(1240, 820)
self.info: MediaInfo | None = None
self.position = 0
self.keyframes: list[int] = []
self.job: Job | None = None
self.last_output: str | None = None
self.fallback = False
self._prime = False
self._gen = 0
self._analyzer: Analyzer | None = None
self._load_gen = 0
self._prober: ProbeWorker | None = None
self._snapper: SnapGrabber | None = None
self._threads: list[QThread] = [] # keep stopped threads alive
# --- playback ---
self.player = QMediaPlayer(self)
self.audio = QAudioOutput(self)
self.player.setAudioOutput(self.audio)
self._scene = QGraphicsScene(self)
self._video_item = QGraphicsVideoItem()
self._scene.addItem(self._video_item)
self.video = _VideoView(self._scene, self._video_item)
self.video.setFocusPolicy(Qt.NoFocus)
self.player.setVideoOutput(self._video_item)
self.player.positionChanged.connect(self.on_player_pos)
self.player.playbackStateChanged.connect(self.on_play_state)
self.player.errorOccurred.connect(self.on_player_error)
self.frame_label = QLabel("Drop a video here · or press Ctrl+O")
self.frame_label.setObjectName("drop")
self.frame_label.setAlignment(Qt.AlignCenter)
self.stack = QStackedWidget()
self.stack.addWidget(self.video) # 0 = live playback
self.stack.addWidget(self.frame_label) # 1 = ffmpeg preview / empty
self.stack.setCurrentIndex(1)
self.grabber = FrameGrabber()
self.grabber.ready.connect(self._show_frame)
self.grabber.start()
self._frame_timer = QTimer(self, singleShot=True, interval=60)
self._frame_timer.timeout.connect(self.update_frame)
# frame-exact scrubbing (GOP cache). During a drag the preview stack
# switches to frame_label and shows engine frames; the media player
# is only seeked once, on release.
self.scrub = ScrubEngine()
self.scrub.frame_ready.connect(self._on_scrub_frame)
self.scrub.start()
self._scrubbing = False
# --- timeline ---
self.timeline = Timeline()
self.timeline.seeked.connect(self.seek)
self.timeline.range_changed.connect(self.refresh_range)
self.timeline.drag_state.connect(self._on_drag_state)
# --- transport row ---
def btn(text, tip, slot, name=None):
b = QPushButton(text)
b.setToolTip(tip)
b.clicked.connect(slot)
b.setFocusPolicy(Qt.NoFocus)
if name:
b.setObjectName(name)
return b
self.btn_go_in = btn("⇤", "Go to in-point (Home)", self.go_in, "tp")
self.btn_prev_vid = btn("«", "Previous video in this folder (PgUp)",
lambda: self.step_video(-1), "nav")
self.btn_next_vid = btn("»", "Next video in this folder (PgDn)",
lambda: self.step_video(1), "nav")
self.btn_prev = btn("◂", "Previous frame ( , )",
lambda: self.step_frames(-1), "tp")
self.btn_play = btn("▶", "Play / pause (Space)", self.play_pause, "play")
self.btn_next = btn("▸", "Next frame ( . )",
lambda: self.step_frames(1), "tp")
self.btn_go_out = btn("⇥", "Go to out-point (End)", self.go_out, "tp")
self.btn_set_in = btn("[ In", "Set in-point at playhead (I)",
self.set_in, "mark")
self.btn_set_out = btn("Out ]", "Set out-point at playhead (O)",
self.set_out, "mark")
self.lbl_time = QLabel("0:00:00.000")
self.lbl_time.setObjectName("time")
self.lbl_dur = QLabel("/ 0:00:00.000")
self.lbl_dur.setObjectName("dur")
self.lbl_range = QLabel("")
self.lbl_range.setObjectName("range")
self.lbl_range.setTextFormat(Qt.RichText)
self.lbl_range.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lbl_est = QLabel("")
self.lbl_est.setObjectName("est")
self.lbl_est.setTextFormat(Qt.RichText)
self.lbl_est.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
# --- volume ---
self.btn_mute = btn("🔊", "Mute / unmute (M)", self.toggle_mute, "glass")
self.vol = QSlider(Qt.Horizontal)
self.vol.setObjectName("vol")
self.vol.setRange(0, 100)
self.vol.setFixedWidth(110)
self.vol.setFocusPolicy(Qt.NoFocus)
self.vol.setToolTip("Volume")
self.vol.valueChanged.connect(self._on_volume)
self.vol_slider = self.vol # contract alias (tests, future UI work)
vol0 = int(self.settings.value("volume", 100))
muted0 = self.settings.value("muted", False, bool)
self.vol.setValue(min(max(vol0, 0), 100))
self.audio.setVolume(self.vol.value() / 100)
self.audio.setMuted(muted0)
self._sync_mute_icon()
# --- export controls ---
self.btn_open = btn("📂 Open", "Open a video (Ctrl+O)", self.open_dialog)
self.combo_tier = _TierCombo()
self.combo_tier.setFocusPolicy(Qt.NoFocus)
for name, mb in DISCORD_TIERS:
self.combo_tier.addItem(name, mb)
self.combo_tier.setToolTip("Target size for Discord MP4 and GIF exports")
self.combo_tier.currentIndexChanged.connect(
lambda i: self.set_discord_limit(self.combo_tier.itemData(i)))
self._combo_open = False
self._menu_open = False
self.combo_tier.popup_open.connect(self._on_combo_popup)
self.btn_snap = btn("📷 Snap", "Grab + crop the current frame (S)",
self.snapshot)
self.btn_gif = btn("🎞 GIF", "Animated GIF sized for your Discord "
"limit (G)", self.export_gif)
self.btn_discord = btn("💬 Discord",
"Discord MP4: re-encode to fit your limit (D)",
self.export_discord, "discord")
self.btn_trim = btn("✂ Trim",
"Lossless trim: stream copy, original quality (Enter)",
self.trim, "accent")
# --- edge-to-edge video with floating glass panels on top ---
root = QVBoxLayout()
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
root.addWidget(self.stack, stretch=1)
host = QWidget()
host.setLayout(root)
self.setCentralWidget(host)
self.setAcceptDrops(True)
# bottom panel: timeline on its own line, then transport | export row
self.bottom_panel = GlassPanel(host)
bl = QVBoxLayout()
bl.setSpacing(6)
if hasattr(self.bottom_panel, "set_content_layout"):
self.bottom_panel.set_content_layout(bl)
else: # stub fallback
old = self.bottom_panel.layout()
if old is not None:
QWidget().setLayout(old)
bl.setContentsMargins(14, 10, 14, 10)
self.bottom_panel.setLayout(bl)
bl.addWidget(self.timeline)
# row 1: transport · marks · volume · time ········ range/estimate
row = QHBoxLayout()
row.setSpacing(6)
for w in (self.btn_go_in, self.btn_prev, self.btn_play, self.btn_next,
self.btn_go_out):
row.addWidget(w)
row.addSpacing(8)
row.addWidget(self.btn_set_in)
row.addWidget(self.btn_set_out)
row.addSpacing(10)
row.addWidget(self.btn_mute)
row.addWidget(self.vol)
row.addSpacing(10)
row.addWidget(self.lbl_time)
row.addWidget(self.lbl_dur)
# wrap range/est labels in a _FlexWidget so their preferred width
# doesn't inflate the bottom panel's sizeHint (they clip naturally)
self._info_flex = _FlexWidget()
info_col = QVBoxLayout(self._info_flex)
info_col.setContentsMargins(0, 0, 0, 0)
info_col.setSpacing(2)
info_col.addWidget(self.lbl_range)
info_col.addWidget(self.lbl_est)
row.addWidget(self._info_flex, 1) # stretch = 1
bl.addLayout(row)
# row 2: exports, right-aligned ····· tier · snap · gif · discord · trim
row2 = QHBoxLayout()
row2.setSpacing(6)
row2.addStretch()
row2.addWidget(self.combo_tier)
row2.addSpacing(6)
for w in (self.btn_snap, self.btn_gif, self.btn_discord, self.btn_trim):
row2.addWidget(w)
bl.addLayout(row2)
bl.addWidget(self._status_bar)
# top panel: open / folder nav / clip name / update
self.top_panel = GlassPanel(host)
self.lbl_clip = QLabel("")
self.lbl_clip.setObjectName("muted")
self.lbl_clip.setMinimumWidth(0)
self.lbl_clip.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred)
self._lbl_clip_full = "" # unelided text; elided version set via _elide_clip()
top_row = QHBoxLayout()
top_row.setSpacing(6)
top_row.addWidget(self._menu_bar)
top_row.addSpacing(6)
top_row.addWidget(self.btn_open)
top_row.addSpacing(8)
top_row.addWidget(self.btn_prev_vid)
top_row.addWidget(self.btn_next_vid)
top_row.addSpacing(10)
top_row.addWidget(self.lbl_clip)
top_row.addStretch()
if hasattr(self.top_panel, "set_content_layout"):
self.top_panel.set_content_layout(top_row)
else: # stub fallback
old = self.top_panel.layout()
if old is not None:
QWidget().setLayout(old)
top_row.setContentsMargins(14, 8, 14, 8)
self.top_panel.setLayout(top_row)
self._top_row = top_row
# real-mouse support: without tracking, Qt emits no MouseMove
# while no button is held, so the AutoHider would never see
# activity; hover events need WA_Hover.
for w in (self, host, self.stack, self.video, self.frame_label,
self.timeline):
w.setMouseTracking(True)
w.setAttribute(Qt.WA_Hover, True)
# single/double click on the video toggles playback
for w in (self.stack, self.video, self.video.viewport(),
self.frame_label):
w.installEventFilter(self)
host.installEventFilter(self) # relayout panels when host resizes
# --- status bar: progress, cancel, show-in-folder ---
self.progress = QProgressBar()
self.progress.setRange(0, 1000)
self.progress.setTextVisible(False)
self.progress.hide()
self.btn_cancel = btn("Cancel", "Stop the running export",
self.cancel_job, "cancel")
self.btn_cancel.hide()
self.btn_reveal = btn("Show in folder", "Open the export's folder",
self.reveal_last, "link")
self.btn_reveal.hide()
sb = self.statusBar()
sb.addPermanentWidget(self.btn_reveal)
sb.addPermanentWidget(self.progress)
sb.addPermanentWidget(self.btn_cancel)
self._build_menu()
self._menu_bar.setMinimumWidth(self._menu_bar.sizeHint().width())
saved = float(self.settings.value("discord_limit", 20.0))
saved = {10.0: 20.0, 500.0: 1000.0}.get(saved, saved) # Aug 2026 bump
self.set_discord_limit(saved if saved in [m for _, m in DISCORD_TIERS]
else 20.0)
self.update_controls()
if have_ffmpeg():
sb.showMessage("Ready · drop a video to start")
else:
sb.showMessage("ffmpeg not found · install it: winget install Gyan.FFmpeg")
QTimer.singleShot(0, self._warn_no_ffmpeg)
# auto-update: quiet startup check 3 s after launch
self._updater: UpdateChecker | None = None
self._update_msi: str | None = None
self.btn_update = btn("", "Install the downloaded update and restart "
"mp4trim", self.apply_update, "accent")
self.btn_update.hide()
self._top_row.addWidget(self.btn_update)
self._top_row.addSpacing(8)
self.btn_min = btn("–", "Minimize", self.showMinimized, "winbtn")
self.btn_max = btn("□", "Maximize / restore (double-click the bar)",
self.toggle_maximize, "winbtn")
self.btn_close = btn("✕", "Close", self.close, "winclose")
for b_ in (self.btn_min, self.btn_max, self.btn_close):
self._top_row.addWidget(b_)
# drag the top panel to move; edges resize
self.top_panel.installEventFilter(self)
self._menu_bar.installEventFilter(self)
self.lbl_clip.installEventFilter(self)
self._edges = _EdgeResizer(self)
QApplication.instance().installEventFilter(self._edges)
QTimer.singleShot(3000, lambda: self.check_updates(manual=False))
self._update_timer = QTimer(self)
self._update_timer.setInterval(24 * 60 * 60 * 1000)
self._update_timer.timeout.connect(
lambda: self.check_updates(manual=False))
self._update_timer.start()
# --- auto-hide chrome (panels + menu bar + status bar) ---
self.hider = AutoHider(self, [self.top_panel, self.bottom_panel],
idle_ms=2000, cursor_target=self.video)
self.hider.hide_cursor_when_idle = True
self.auto_hider = self.hider # alias used by tests
self.hider.set_enabled(False) # nothing loaded: keep chrome visible
self.bottom_panel.visibility_changed.connect(self._on_chrome_visible)
self._wire_menu_pins()
# fullscreen + mute shortcuts
self.addAction(self._act("Fullscreen", self.toggle_fullscreen, "F11"))
self.addAction(self._act("Exit fullscreen", self._esc_pressed, "Esc"))
self.addAction(self._act("Mute", self.toggle_mute, "M"))
QTimer.singleShot(0, self._relayout_panels)
# ------------------------------------------- glass panels / auto-hide
def _wire_menu_pins(self):
"""Pin panels + keep chrome up while any menu is open."""
for m in self.menuBar().findChildren(QMenu):
m.aboutToShow.connect(lambda: self._set_menu_open(True))
m.aboutToHide.connect(lambda: self._set_menu_open(False))
def _set_menu_open(self, on: bool):
self._menu_open = on
self._update_pins()
def _on_combo_popup(self, on: bool):
self._combo_open = on
self._update_pins()
def _update_pins(self):
busy = self.job is not None
pin_bottom = busy or self._combo_open or self._menu_open
self.bottom_panel.pinned = pin_bottom
self.top_panel.pinned = self._menu_open
if pin_bottom or self._menu_open:
self.hider.poke()
def _on_chrome_visible(self, visible: bool):
"""Menu + status bar follow the bottom panel's visibility."""
pinned_sb = (self.job is not None or self._update_msi is not None
or self._menu_open)
self._menu_bar.setVisible(True)
self._status_bar.setVisible(True)
def _place_panel(self, panel, x: int, y: int, w: int, h: int):
# The real GlassPanel slides via a QPropertyAnimation on 'pos' whose
# end value was captured before this relayout; stop it and resync the
# base position or the animation drags the panel back to (0, 0).
slide = getattr(panel, "_slide", None)
if slide is not None:
slide.stop()
panel.setGeometry(x, y, w, h)
if getattr(panel, "_base_pos", None) is not None:
panel._base_pos = panel.pos()
def _elide_clip(self, avail_px: int):
"""Set lbl_clip text, elided to avail_px with Qt.ElideMiddle."""
if not self._lbl_clip_full:
self.lbl_clip.setText("")
return
fm = self.lbl_clip.fontMetrics()
elided = fm.elidedText(self._lbl_clip_full, Qt.ElideMiddle,
max(avail_px, 20))
self.lbl_clip.setText(elided)
def _apply_tier(self, host_width: int):
"""Switch between full / compact / minimal layout tiers based on host_width.
Tiers
-----
full >= 1100 px all labels visible, vol_slider 110 px
compact 820-1099 shorten mark buttons, hide lbl_dur,
narrow vol_slider to 70 px
minimal < 820 hide vol_slider (keep btn_mute), hide lbl_range,
shorten export buttons to emoji only
"""
if host_width >= 1100:
tier = "full"
elif host_width >= 820:
tier = "compact"
else:
tier = "minimal"
if getattr(self, "_current_tier", None) == tier:
return # nothing to do
self._current_tier = tier
# Reset max-width constraints (previous tiers may have set them)
self.lbl_range.setMaximumWidth(16777215)
self.lbl_est.setMaximumWidth(16777215)
if tier == "full":
self.btn_set_in.setText("[ In")
self.btn_set_out.setText("Out ]")
self.lbl_dur.show()
self.vol.setFixedWidth(110)
self.vol.show()
self.btn_mute.show()
self.lbl_range.show()
self.lbl_est.show()
# max widths will be set by _relayout_panels based on bw
self.btn_snap.setText("📷 Snap")
self.btn_gif.setText("🎞 GIF")
self.btn_discord.setText("💬 Discord")
self.btn_trim.setText("✂ Trim")
self.btn_open.setText("📂 Open")
elif tier == "compact":
self.btn_set_in.setText("[")
self.btn_set_out.setText("]")
self.lbl_dur.hide()
self.vol.setFixedWidth(70)
self.vol.show()
self.btn_mute.show()
self.lbl_range.show()
self.lbl_est.show()
# max widths will be set by _relayout_panels based on bw
self.btn_snap.setText("📷 Snap")
self.btn_gif.setText("🎞 GIF")
self.btn_discord.setText("💬 Discord")
self.btn_trim.setText("✂ Trim")
self.btn_open.setText("📂 Open")
else: # minimal
self.btn_set_in.setText("[")
self.btn_set_out.setText("]")
self.lbl_dur.hide()
self.vol.hide()
self.btn_mute.show()
self.lbl_range.hide()
self.lbl_est.show()
self.btn_snap.setText("📷")
self.btn_gif.setText("🎞")
self.btn_discord.setText("💬")
self.btn_trim.setText("✂")
self.btn_open.setText("📂")
def _relayout_panels(self):
host = self.centralWidget()
if host is None or not hasattr(self, "bottom_panel"):
return
hw, hh = host.width(), host.height()
m = 16
bw = min(1240, hw - 2 * m)
# apply responsive tier FIRST (changes widget visibility / sizes)
self._apply_tier(hw)
# _FlexWidget (info_flex) reports sizeHint().width() == 0, so
# lbl_range / lbl_est never inflate the bottom panel's sizeHint.
# No manual max-width caps needed; the layout stretch gives them
# exactly the leftover space.
# activate layouts so sizeHints reflect the new tier
for pan in (self.top_panel, self.bottom_panel):
lay = pan.layout()
if lay is not None:
lay.activate()
bh = self.bottom_panel.sizeHint().height()
self._place_panel(self.bottom_panel, (hw - bw) // 2, hh - bh - m, bw, bh)
# top panel: lbl_clip gets whatever space is left after fixed widgets
# estimate fixed widget widths to compute clip label budget
_menu_w = self._menu_bar.sizeHint().width()
_open_w = self.btn_open.sizeHint().width()
_nav_w = (self.btn_prev_vid.sizeHint().width()
+ self.btn_next_vid.sizeHint().width())
_wctl_w = (self.btn_min.sizeHint().width()
+ self.btn_max.sizeHint().width()
+ self.btn_close.sizeHint().width())
_upd_w = (self.btn_update.sizeHint().width()
if self.btn_update.isVisible() else 0)
# spacings: 6+6+8+10+8 (from top_row layout, approximate)
_spacing = 6 + 6 + 8 + 10 + 8 + 6 * 3 + 14 * 2 # margins + spacings
_clip_budget = (hw - 2 * m
- _menu_w - _open_w - _nav_w - _wctl_w
- _upd_w - _spacing - 20)
self._elide_clip(max(_clip_budget, 20))
# re-activate after elision may change sizeHint
lay = self.top_panel.layout()
if lay is not None:
lay.activate()
tw = min(max(self.top_panel.sizeHint().width(),
self.top_panel.minimumSizeHint().width(), 520),
hw - 2 * m) # top panel capped at host_width - 32
th = self.top_panel.sizeHint().height()
self._place_panel(self.top_panel, (hw - tw) // 2, m, tw, th)
self.bottom_panel.raise_()
self.top_panel.raise_()
# ------------------------------------------------------------- volume
def _on_volume(self, v: int):
self.audio.setVolume(v / 100)
self.settings.setValue("volume", int(v))
def toggle_mute(self):
self.audio.setMuted(not self.audio.isMuted())
self.settings.setValue("muted", self.audio.isMuted())
self._sync_mute_icon()
def _sync_mute_icon(self):
self.btn_mute.setText("🔇" if self.audio.isMuted() else "🔊")
# --------------------------------------------------------- fullscreen
def toggle_fullscreen(self):
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
def toggle_maximize(self):
if self.isMaximized():
self.showNormal()
else:
self.showMaximized()
def fit_to_video(self):
"""Resize the window to the clip's aspect ratio (no black bars),
as big as fits in 90% of the screen, centred on its current spot."""
if not self.info or self.isFullScreen() or self.isMaximized():
return
vw, vh = self.info.width, self.info.height
if not vw or not vh:
return
scr = (self.screen() or QApplication.primaryScreen()).availableGeometry()
s = min(scr.width() * 0.9 / vw, scr.height() * 0.9 / vh, 1.0)
w, h = round(vw * s), round(vh * s)
if w < 640 or h < 360: # tiny/odd clips: grow to the minimum
s = max(640 / vw, 360 / vh)
w, h = round(vw * s), round(vh * s)
c = self.geometry().center()
x = min(max(c.x() - w // 2, scr.left()), scr.right() - w)
y = min(max(c.y() - h // 2, scr.top()), scr.bottom() - h)
self.setGeometry(x, y, w, h)
def _esc_pressed(self):
if self.isFullScreen():
self.showNormal()
def keyPressEvent(self, e):
# Menu bar hides with the chrome, and Qt disables shortcuts of
# actions in hidden menus; match keys against menu shortcuts
# manually so D/G/S/I/O etc. keep working while the UI is
# faded out. Unconditional: if this handler receives the key at
# all, Qt's native shortcut resolution already declined it.
if True:
seq = QKeySequence(int(e.modifiers().value) | e.key())
for top in self._menu_bar.actions():
menu = top.menu()
if menu is None:
continue
for act in menu.actions():
if act.isEnabled() and any(
s.matches(seq) == QKeySequence.ExactMatch
for s in act.shortcuts()):
act.trigger()
e.accept()
return
super().keyPressEvent(e)
def eventFilter(self, obj, ev):
host = self.centralWidget()
if obj is host and ev.type() == QEvent.Resize:
self._relayout_panels()
elif obj in (self.top_panel, self.lbl_clip) or (
obj is self._menu_bar and ev.type() in (
QEvent.MouseButtonPress, QEvent.MouseButtonDblClick)
and self._menu_bar.actionAt(ev.position().toPoint()) is None):
if ev.type() == QEvent.MouseButtonDblClick \
and ev.button() == Qt.LeftButton:
self.toggle_maximize()
return True
if ev.type() == QEvent.MouseButtonPress \
and ev.button() == Qt.LeftButton:
h = self.windowHandle()
if h is not None and not self.isFullScreen():
h.startSystemMove()
return True
elif obj in (self.stack, self.video, self.video.viewport(),
self.frame_label):
# single AND double click both play/pause; the second click of a
# double arrives as DblClick, which we swallow so the pair counts
# as one toggle, not two.
if ev.type() == QEvent.MouseButtonPress \
and ev.button() == Qt.LeftButton:
self.hider.poke()
self.play_pause()
return True
if ev.type() == QEvent.MouseButtonDblClick \
and ev.button() == Qt.LeftButton:
return True
return super().eventFilter(obj, ev)
# ------------------------------------------------------------ updates
def check_updates(self, manual: bool = True):
if self._updater and self._updater.isRunning():
return
u = UpdateChecker(manual=manual)
u.update_ready.connect(self._on_update_ready)
if manual:
u.no_update.connect(self.statusBar().showMessage)
u.finished.connect(lambda: None)
self._updater = u
if manual:
self.statusBar().showMessage("Checking for updates…")
u.start()
def _on_update_ready(self, version: str, msi: str):
self._update_msi = msi
self.btn_update.setText(f"⬆ Update to {version}")
self.btn_update.show()
self.statusBar().show()
self._relayout_panels()
self.statusBar().showMessage(
f"mp4trim {version} is ready to install (you have {APP_VERSION})")
def apply_update(self):
if not self._update_msi or not Path(self._update_msi).exists():
return
if self.job:
QMessageBox.information(
self, "mp4trim", "An export is running. The update will "
"install after you finish or cancel it.")
return
upd.launch_update(self._update_msi)
self.close()
# ---------------------------------------------------------------- menu
def menuBar(self):
return self._menu_bar
def statusBar(self):
return self._status_bar
def _act(self, text, slot, shortcut=None, checkable=False):
a = QAction(text, self, checkable=checkable)
if shortcut:
a.setShortcut(QKeySequence(shortcut))
if checkable:
a.toggled.connect(slot)
else:
a.triggered.connect(slot)
return a
def _build_menu(self):
mb = self.menuBar()
m_file = mb.addMenu("&File")
m_file.addAction(self._act("&Open…", self.open_dialog, QKeySequence.Open))
self.m_recent = m_file.addMenu("Open &Recent")
self._rebuild_recent()
m_file.addSeparator()
self.act_trim = self._act("&Trim (lossless)", self.trim, "Return")
self.act_trim.setShortcuts([QKeySequence("Return"), QKeySequence("Enter"),
QKeySequence("Ctrl+E")])
m_file.addAction(self.act_trim)
m_file.addAction(self._act("Export &Discord MP4", self.export_discord, "D"))
m_file.addAction(self._act("Export &GIF", self.export_gif, "G"))
m_file.addAction(self._act("&Snapshot / Crop…", self.snapshot, "S"))
m_file.addSeparator()
m_file.addAction(self._act("Show last export in folder", self.reveal_last))
m_file.addSeparator()
m_file.addAction(self._act("E&xit", self.close, QKeySequence.Quit))
m_edit = mb.addMenu("&Marks")
m_edit.addAction(self._act("Set &in-point at playhead", self.set_in, "I"))
m_edit.addAction(self._act("Set &out-point at playhead", self.set_out, "O"))
m_edit.addAction(self._act("Snap in-point to &keyframe", self.snap_in, "K"))
m_edit.addSeparator()
m_edit.addAction(self._act("Go to in-point", self.go_in, "Home"))
m_edit.addAction(self._act("Go to out-point", self.go_out, "End"))
m_edit.addAction(self._act("Previous frame", lambda: self.step_frames(-1), ","))
m_edit.addAction(self._act("Next frame", lambda: self.step_frames(1), "."))
m_edit.addSeparator()
m_edit.addAction(self._act("Reset timeline &zoom", self.timeline.reset_zoom, "Z"))
m_edit.addAction(self._act("Reset in/out to whole file", self.reset_marks, "Ctrl+R"))
m_edit.addSeparator()
m_edit.addAction(self._act("&Previous video in folder",
lambda: self.step_video(-1), "PgUp"))
m_edit.addAction(self._act("&Next video in folder",
lambda: self.step_video(1), "PgDown"))
# playback keys that live on the window, not in a menu
for text, slot, key in [
("Play/pause", self.play_pause, "Space"),
("Back 1s", lambda: self.seek(self.position - 1000), "Left"),
("Forward 1s", lambda: self.seek(self.position + 1000), "Right"),
("Back 10s", lambda: self.seek(self.position - 10_000), "Shift+Left"),
("Forward 10s", lambda: self.seek(self.position + 10_000), "Shift+Right"),
]:
self.addAction(self._act(text, slot, key))
m_opts = mb.addMenu("&Options")
self.act_reencode = self._act(
"Frame-accurate trim (re-encode, drops Dolby Vision)",
lambda _: self.refresh_range(), checkable=True)
self.act_mix = self._act(
"Mix all audio tracks in Discord MP4", self._save_mix, checkable=True)
self.act_mix.setChecked(self.settings.value("mix_audio", False, bool))
self.act_ffpreview = self._act(
"Force ffmpeg preview (no playback)", self.on_force_fallback,
checkable=True)
m_opts.addActions([self.act_reencode, self.act_mix, self.act_ffpreview])
m_opts.addSeparator()
m_tier = m_opts.addMenu("Discord upload limit")
self.tier_actions = []
for name, mbytes in DISCORD_TIERS:
act = QAction(name, self, checkable=True)
act.triggered.connect(lambda _=False, v=mbytes: self.set_discord_limit(v))
m_tier.addAction(act)
self.tier_actions.append((act, mbytes))
m_help = mb.addMenu("&Help")
m_help.addAction(self._act("&Keyboard shortcuts", self.show_shortcuts, "F1"))
m_help.addAction(self._act("Check for &updates", self.check_updates))
m_help.addAction(self._act("&About", self.show_about))
def _rebuild_recent(self):
self.m_recent.clear()
recent = [p for p in self._recent() if Path(p).exists()]
for p in recent:
self.m_recent.addAction(
self._act(Path(p).name, lambda _=False, x=p: self.load(x)))
if not recent:
a = self.m_recent.addAction("(none)")
a.setEnabled(False)
else:
self.m_recent.addSeparator()
self.m_recent.addAction(self._act("Clear list", self._clear_recent))
def _recent(self) -> list[str]:
v = self.settings.value("recent", [])
return [v] if isinstance(v, str) else list(v or [])
def _push_recent(self, path: str):
rec = [p for p in self._recent() if os.path.normcase(p) != os.path.normcase(path)]
self.settings.setValue("recent", [path, *rec][:10])
self._rebuild_recent()
def _clear_recent(self):
self.settings.setValue("recent", [])
self._rebuild_recent()
def _save_mix(self, on: bool):
self.settings.setValue("mix_audio", on)
def show_shortcuts(self):
QMessageBox.information(self, "Keyboard shortcuts", SHORTCUTS_HELP)
def show_about(self):
QMessageBox.about(
self, "mp4trim",
f"<b>mp4trim {APP_VERSION}</b><br><br>"
"Drag the green/red handles to pick the kept range.<br>"
"<b>Trim</b> is lossless (stream copy, Dolby Vision / HDR safe).<br>"
"<b>Discord MP4</b> re-encodes to fit your upload limit.<br><br>"