-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1468 lines (1229 loc) · 56.4 KB
/
app.py
File metadata and controls
1468 lines (1229 loc) · 56.4 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 os
import random
import sys
from pathlib import Path
import time
import webbrowser
from PySide6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QFrame,
QPushButton,
QLabel,
QFileDialog,
QSizePolicy,
)
from PySide6.QtCore import Qt, QTimer, Signal, QSize
from PySide6.QtGui import QKeyEvent, QMouseEvent, QMoveEvent, QResizeEvent, QIcon, QShowEvent, QPalette
from app_types import DeleteSelectionAction, SeekAction, SegmentPlayMode, FilePlayMode, SelectionBeginAction, SelectionCompleteAction
from app_state import AppState
from buttons_dialog import ButtonsDialog, ButtonSpec
from clickable_label import ClickableLabel
from constants import *
from directory_operations_util import DirectoryOperationsUtil
from confirmable_dialog import ConfirmableDialog, ConfirmableButtonSpec
from silence_util import SilenceUtil
from sound_file_util import SoundFileUtil
from sound_files_util import SoundFilesUtil
from sound_loader import SoundLoader
from sound_util import SoundUtil
from timeline import Timeline, TimelineMouseAction
from settings import Settings
from segments import Segments
from stream import Stream
from sound import Sound
from sound_state import SoundState
from app_util import AppUtil
from util import *
class App(QMainWindow):
"""
PySide6 main window and app logic
"""
# Signal for cross-thread communication when sound loading completes
_load_complete_signal = Signal(object, str) # arguments: Sound | None, file path
def __init__(self):
super().__init__()
# Connect cross-thread signal for sound loading
self._load_complete_signal.connect(self._load_sound_continued)
# Load settings and related
self._settings = Settings.load()
self._override_settings_using_argv()
self._startup_info: dict | None = {
"last_position": self._settings.last_position,
"play_mode": self._settings.play_mode
}
self._stream = Stream()
self._stream.compressor_enabled = self._settings.compressor_enabled
self._state = SoundState(file_path="", sound=None)
self._loader = SoundLoader()
self._mouse_pos = (0, 0)
# Init UI
self._init_ui()
# Create AppState
self._app_state = AppState(self._settings, self._stream, self._timeline)
# Sync initial zoom
self._app_state.set_timeline_zoom(self._settings.timeline_zoom)
self._window_rect_timer = QTimer(self)
self._window_rect_timer.setSingleShot(True)
self._window_rect_timer.timeout.connect(self._on_window_rect_complete)
self._interval_timer = QTimer(self)
self._interval_timer.timeout.connect(self._on_interval)
self._interval_timer.start(16)
# Load initial sound (rem, async)
self._load_sound_using_current_state()
def _override_settings_using_argv(self) -> None:
if len(sys.argv) <= 1:
return
arg_path = sys.argv[1].strip()
if not arg_path:
return
if not os.path.exists(arg_path):
print(f"* Ignoring argument, path doesn't exist: [{arg_path}]")
return
if os.path.isdir(arg_path):
# Argument is a directory
if self._settings.dir_path == arg_path:
... # Do nothing
else:
self._settings.set_dir_and_print(arg_path)
return
# Is file - attempt to set its directory and file index
dir_path = str(Path(arg_path).parent)
temp_prefs = Settings()
temp_prefs.dir_path = dir_path
try:
index = temp_prefs._file_paths.index(arg_path)
except:
index = -1
if index == -1:
print(f"* Ignoring argument, unsupported file type: [{arg_path}]")
return
is_already_at_file = (self._settings.dir_path == dir_path and self._settings.file_name == Path(arg_path).name)
if is_already_at_file:
# Continue silently
return
self._settings.set_dir_and_print(dir_path)
self._settings.file_name = Path(arg_path).name
def _init_ui(self) -> None:
"""Create all UI elements mirroring app.py layout"""
self.setWindowTitle(WINDOW_TITLE)
self.setWindowFlags(self.windowFlags() & ~Qt.WindowType.WindowMaximizeButtonHint)
self.setMinimumWidth(500)
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
# Central widget and main layout
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(10, 10, 10, 10)
main_layout.setSpacing(10)
# === Header Frame ===
header_frame = QFrame()
header_frame.setObjectName("headerFrame")
header_layout = QHBoxLayout(header_frame)
header_layout.setContentsMargins(0, 0, 0, 0)
header_layout.setSpacing(5)
# Select dir button
self._dir_button = QPushButton("Select dir")
self._dir_button.setStyleSheet(f"padding: 8px;")
self._dir_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self._dir_button.clicked.connect(self._select_and_set_directory)
header_layout.addWidget(self._dir_button)
# File info frame (contains dir and file labels)
file_info_frame = QFrame()
file_info_frame.setObjectName("fileInfoFrame")
file_info_layout = QVBoxLayout(file_info_frame)
file_info_layout.setContentsMargins(5, 0, 5, 0)
file_info_layout.setSpacing(0)
# Directory label
self.dir_label = QLabel("")
self.dir_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
file_info_layout.addWidget(self.dir_label)
# File label
self.file_label = QLabel("")
self.file_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
file_info_layout.addWidget(self.file_label)
header_layout.addWidget(file_info_frame, 1) # Stretch factor 1
# Right-side labels frame (contains fast mode and start-end auto labels)
right_labels_frame = QFrame()
right_labels_frame.setObjectName("rightLabelsFrame")
right_labels_layout = QVBoxLayout(right_labels_frame)
right_labels_layout.setContentsMargins(0, 0, 0, 0)
right_labels_layout.setSpacing(0)
# Fast mode label (top-right)
self._fast_mode_label = ClickableLabel()
self._fast_mode_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
self._fast_mode_label.clicked.connect(self._on_fast_mode_label_click)
self._update_togglable_label(
self._fast_mode_label, "Fast mode", self._settings.fast_mode
)
right_labels_layout.addWidget(self._fast_mode_label)
# Auto-trim label (below fast mode label)
self._start_end_auto_label = ClickableLabel()
self._start_end_auto_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
self._start_end_auto_label.clicked.connect(self._on_start_end_auto_label_click)
self._update_togglable_label(
self._start_end_auto_label, "Start/end auto", self._settings.start_end_auto
)
right_labels_layout.addWidget(self._start_end_auto_label)
header_layout.addWidget(right_labels_frame, 0) # No stretch
# Help button
self._help_button = QPushButton("?")
self._help_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
# self._help_button.setFixedWidth(25)
self._help_button.setStyleSheet(f"padding: 8px;")
self._help_button.clicked.connect(self._on_help_button)
header_layout.addSpacing(5)
header_layout.addWidget(self._help_button)
# ...
main_layout.addWidget(header_frame)
# Timeline Widget
self._timeline = Timeline(self)
self._timeline.canvas_clicked.connect(self._on_timeline_click)
main_layout.addWidget(self._timeline)
# Play/pause button and sound info label container
info_container = QWidget()
info_layout = QHBoxLayout(info_container)
info_layout.setContentsMargins(0, 0, 0, 0)
info_layout.setSpacing(4)
# Play/pause button
self._play_pause_button = QPushButton()
self._play_pause_button.setIcon(QIcon("assets/play_icon.svg"))
self._play_pause_button.setIconSize(QSize(20, 20))
self._play_pause_button.setFixedSize(28, 28)
self._play_pause_button.clicked.connect(self._toggle_pause)
self._play_pause_button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
info_layout.addWidget(self._play_pause_button)
# Sound info label
self.sound_info_label = QLabel()
self.sound_info_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
info_layout.addWidget(self.sound_info_label)
# Right-aligned labels container
right_labels_container = QWidget()
right_labels_layout = QVBoxLayout(right_labels_container)
right_labels_layout.setContentsMargins(0, 0, 0, 0)
right_labels_layout.setSpacing(0)
self._mouse_prompt_label = QLabel("")
self._mouse_prompt_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
palette = self._mouse_prompt_label.palette()
palette.setColor(QPalette.ColorRole.WindowText, QCOLOR_MEDIUM_GRAY)
self._mouse_prompt_label.setPalette(palette)
self._mouse_prompt_label.setAutoFillBackground(True)
right_labels_layout.addWidget(self._mouse_prompt_label)
self._compressor_label = ClickableLabel("")
self._compressor_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
self._compressor_label.setContentsMargins(0, 3, 0, 0)
right_labels_layout.addWidget(self._compressor_label)
self._compressor_label.clicked.connect(self._on_compressor_label_click)
self._update_togglable_label(
self._compressor_label, "Compressor", self._settings.compressor_enabled
)
right_labels_container.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
info_layout.addWidget(right_labels_container)
main_layout.addWidget(info_container)
self._update_header()
self._restore_window_geometry()
def _restore_window_geometry(self) -> None:
"""Restore window position and size from preferences"""
w = self._settings.window_width
h = self.sizeHint().height()
x, y = self._settings.window_position
# Compensate for window frame (titlebar) on Linux
# frameGeometry() includes decorations, geometry() does not
frame_height = self.frameGeometry().height() - self.geometry().height()
y += frame_height # Add titlebar height to saved position
# Clamp position within screen
screen = QApplication.primaryScreen()
if screen:
screen_geometry = screen.availableGeometry()
x = max(0, min(x, screen_geometry.width() - w // 2))
y = max(0, min(y, screen_geometry.height() - h // 2))
self.setGeometry(x, y, w, h)
def _select_and_set_directory(self) -> None:
""" Show directory selection dialog """
initial_dir = self._settings.dir_path if self._settings.dir_path and Path(self._settings.dir_path).exists() else ""
path = QFileDialog.getExistingDirectory(
self,
"Select directory containing sound files",
initial_dir,
)
if not path:
return
self._settings.set_dir_and_print(path)
self._load_sound_using_current_state()
def _select_directory_and_file(self) -> None:
"""
Show file selection dialog, etc
"""
initial_dir = self._settings.dir_path if self._settings.dir_path and Path(self._settings.dir_path).exists() else ""
filter_string = "Supported media (" + " ".join(f"*{s}" for s in SoundFileUtil.MEDIA_FILE_SUFFIXES) + ")"
path, _ = QFileDialog.getOpenFileName(
self,
caption="Select sound file (and its parent directory)",
dir=initial_dir,
filter=filter_string
)
if not path:
return
dir_path = str(Path(path).parent)
temp_prefs = Settings()
temp_prefs.dir_path = dir_path
try:
index = temp_prefs._file_paths.index(path)
except:
index = -1
if index == -1:
print(f"Unsupported file type, ignoring: {path}")
return
is_already_at_file = (self._settings.dir_path == dir_path and self._settings.file_name == Path(path).name)
if is_already_at_file:
print(f"File already open, ignoring: {path}")
return
self._on_sound_blur()
self._settings.set_dir_and_print(dir_path)
self._settings.file_name = Path(path).name
self._load_sound_using_current_state()
def _toggle_pause(self) -> None:
if self._state.has_sound:
if self._stream.paused:
self._stream.unpause()
else:
self._stream.pause()
def _toggle_start_end_auto(self) -> None:
self._settings.start_end_auto = not self._settings.start_end_auto
self._update_togglable_label(
self._start_end_auto_label, "Start/end auto", self._settings.start_end_auto
)
if self._settings.start_end_auto:
self._set_start_end_using_silence()
def _cycle_file_play_mode(self) -> None:
# Cycles play mode between FilePlayMode types
if isinstance(self.play_mode, SegmentPlayMode):
self.play_mode = FilePlayMode.DEFAULT
else:
match self.play_mode:
case FilePlayMode.DEFAULT:
self.play_mode = FilePlayMode.REPEAT_SINGLE
case FilePlayMode.REPEAT_SINGLE:
self.play_mode = FilePlayMode.TO_END
case FilePlayMode.TO_END:
self.play_mode = FilePlayMode.TO_END_REPEAT
case FilePlayMode.TO_END_REPEAT:
self.play_mode = FilePlayMode.RANDOM_NEXT
case FilePlayMode.RANDOM_NEXT:
self.play_mode = FilePlayMode.DEFAULT
case _:
... # shouldn't happen
def _cycle_segment_play_mode(self) -> None:
""" Cycles play mode between SegmentPlayMode types """
if not self._state.has_sound and not self._state.has_segments:
# Ignore because no segments
return
if isinstance(self.play_mode, FilePlayMode):
# Transition from any FilePlayMode to first SegmentPlayMode
self.play_mode = SegmentPlayMode.TO_END
else:
match self.play_mode:
case SegmentPlayMode.TO_END:
self.play_mode = SegmentPlayMode.REPEAT_ALL
case SegmentPlayMode.REPEAT_ALL:
self.play_mode = SegmentPlayMode.REPEAT_SINGLE
case SegmentPlayMode.REPEAT_SINGLE:
# Transition from last SegmentPlayMode to default FilePlayMode
self.play_mode = FilePlayMode.DEFAULT
def _get_subtitle(self) -> str:
return self._state.get_subtitle_at(self._stream.position)
def _update_togglable_label(
self, label: QLabel, prefix: str, value: bool, true_string="On", false_string="Off"
) -> None:
prefix = f'<span style="color: #888888">{prefix}: </span>'
value_string = true_string if value else false_string
value_color = "#ffffff" if value else "#888888"
value_string = f'<span style="color: {value_color};">{value_string}</span>'
label.setText(f'{prefix} {value_string}')
def _save_sound(self) -> bool:
""" Returns True on success """
assert self._state.sound
err = SoundFileUtil.rewrite_flac(self._state.sound, self._state.file_path)
if err:
print(f"* {err}")
return False
self._state.sound_dirty = False
print(f"Saved {self._state.file_path}")
return True
# ------------------------------------------
# Event handlers and 'pseudo event' handlers
def _on_interval(self) -> None:
""" Runs on an interval. Is UI thread. """
# Check if stream is running
if self._stream._stream and not self._stream._stream.active:
print("* CRITICAL: sounddevice inactive")
# Check for stream completion events from audio thread (non-blocking)
if self._stream.get_completion_event():
self._on_stream_complete()
# Playhead
# TODO: this should be done in a separate callback
self._timeline.playhead_position = self._stream.position
# Update play/pause button icon
self._update_play_pause_button()
# Play info text
text, color = self._get_play_info_text()
if text != self.sound_info_label.text():
self.sound_info_label.setText(text)
self.sound_info_label.setStyleSheet(f"color: {color};")
# Subtitle text
subtitle = self._get_subtitle()
self._timeline.set_subtitle_text(subtitle)
# Mouse prompt
self._timeline.update_mouse_prompt()
if self._timeline.mouse_prompt != self._mouse_prompt_label.text():
self._mouse_prompt_label.setText(self._timeline.mouse_prompt)
# Draw
self._timeline.update()
def _update_play_pause_button(self) -> None:
"""Update play/pause button icon based on stream state"""
if self._stream.paused:
self._play_pause_button.setIcon(QIcon("assets/play_icon.svg"))
else:
self._play_pause_button.setIcon(QIcon("assets/pause_icon.svg"))
def keyPressEvent(self, event: QKeyEvent) -> None:
""" Handles keyboard input """
key = event.key()
modifiers = event.modifiers()
# Quit
if key == Qt.Key.Key_C and modifiers == Qt.KeyboardModifier.ControlModifier:
self._do_quit()
return
# Ignore input while loading
if self.ignore_user_input:
return
# ---
# Playback/seek related
if key == Qt.Key.Key_Space:
if self._state.sound and self._stream.is_at_end:
# If at end of playable area, restart
self._stream.position = 0.0
self._stream.unpause()
else:
# Default behavior
self._toggle_pause()
elif key == Qt.Key.Key_P:
if modifiers == Qt.KeyboardModifier.ShiftModifier:
# Seek near end and play
self._stream.position = self._timeline.max_position - 1.5
self._stream.unpause()
else:
# Seek to start and play
self._stream.position = 0.0
self._stream.unpause()
# Seek forward
elif key == Qt.Key.Key_Greater:
delta = 0.1
self._stream.position += delta
elif key == Qt.Key.Key_Period:
if modifiers == Qt.KeyboardModifier.NoModifier:
delta = 1
elif modifiers == Qt.KeyboardModifier.AltModifier:
delta = 10
elif modifiers == Qt.KeyboardModifier.ControlModifier:
delta = 60
elif modifiers == (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier):
delta = 60 * 15 # 15 minutes
else:
return
self._stream.position += delta
# Seek back
elif key == Qt.Key.Key_Less:
delta = 0.1
self._stream.position -= delta
elif key == Qt.Key.Key_Comma:
if modifiers == Qt.KeyboardModifier.NoModifier:
delta = 1
elif modifiers == Qt.KeyboardModifier.AltModifier:
delta = 10
elif modifiers == Qt.KeyboardModifier.ControlModifier:
delta = 60
elif modifiers == (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier):
delta = 60 * 15 # 15 minutes
else:
return
self._stream.position -= delta
# Seek start/end
elif key == Qt.Key.Key_Home:
self._stream.position = 0.0
elif key == Qt.Key.Key_End:
self._stream.position = (self._state.sound.duration if self._state.sound else 0)
# Seek to next/previous segment
elif key == Qt.Key.Key_Apostrophe:
self._seek_next_segment(True)
elif key == Qt.Key.Key_Semicolon:
self._seek_next_segment(False)
elif key == Qt.Key.Key_R:
# Cycle file play mode
if modifiers == Qt.KeyboardModifier.NoModifier:
self._cycle_file_play_mode()
# Reload (without saving)
elif modifiers == Qt.KeyboardModifier.ControlModifier:
self._load_sound_using_current_state()
# Set start/end position
elif key in [Qt.Key.Key_1, Qt.Key.Key_2]:
self._set_start_end_position_using_mouse(is_start=(key == Qt.Key.Key_1))
# Clear any segment start marker
elif key == Qt.Key.Key_Escape and modifiers == Qt.KeyboardModifier.NoModifier:
self._timeline.segment_start = -1
elif key == Qt.Key.Key_M:
# Turn off segment play mode
if modifiers == Qt.KeyboardModifier.ShiftModifier:
if isinstance(self.play_mode, SegmentPlayMode):
self.play_mode = FilePlayMode.DEFAULT
else:
# Cycle segment play mode
if (self._state.has_sound and self._state.has_segments):
self._cycle_segment_play_mode()
else:
print("Can't set segment mode, no segments defined")
# Invert segments
elif key == Qt.Key.Key_I:
did = self._state.invert_segments()
if did:
self._on_segments_changed()
print("Inverted segments" if did else "No segments to invert")
# Add silence segment at playhead
elif key == Qt.Key.Key_9:
if self._state.sound:
silence_segment = SilenceUtil.detect_silence_boundaries_from(self._state.sound, self._stream.position)
if silence_segment:
index = self._state.insert_segment(silence_segment[0], silence_segment[1], can_merge=False)
if index == -1:
print(f"Couldn't add segment {silence_segment}")
return
self._on_segments_changed()
else:
print(f"No silence at {self._stream.position}")
# Navigate between files
elif key == Qt.Key.Key_BracketLeft:
self._load_sound_by_increment(-1)
elif key == Qt.Key.Key_BracketRight:
self._load_sound_by_increment(1)
elif key == Qt.Key.Key_BraceLeft:
self._load_sound_by_increment(-10)
elif key == Qt.Key.Key_BraceRight:
self._load_sound_by_increment(10)
elif key == Qt.Key.Key_Home and Qt.KeyboardModifier.ControlModifier:
self._load_sound_by_index(0)
elif key == Qt.Key.Key_End and Qt.KeyboardModifier.ControlModifier:
index = len(self._settings.file_paths) - 1
self._load_sound_by_index(index)
# Zoom level
elif key == Qt.Key.Key_Equal or key == Qt.Key.Key_Plus:
self._increment_zoom(+0.1)
elif key == Qt.Key.Key_Minus:
self._increment_zoom(-0.1)
elif key == Qt.Key.Key_O:
# Select directory
if modifiers == Qt.KeyboardModifier.NoModifier:
self._select_and_set_directory()
# Select directory - next/previous
elif modifiers == Qt.KeyboardModifier.ShiftModifier:
self._select_adjacent_directory(previous=False)
elif modifiers == Qt.KeyboardModifier.AltModifier:
self._select_adjacent_directory(previous=True)
# Select directory and file
elif modifiers == Qt.KeyboardModifier.ControlModifier:
self._select_directory_and_file()
elif key == Qt.Key.Key_T:
if modifiers == Qt.KeyboardModifier.NoModifier:
# Set start-end using silence
self._set_start_end_using_silence()
elif modifiers == Qt.KeyboardModifier.ShiftModifier:
# Start-end auto toggle
self._toggle_start_end_auto()
elif modifiers == Qt.KeyboardModifier.ControlModifier:
# Trim sound using start/end
self._edit_sound_using_start_end()
elif key == Qt.Key.Key_X:
if modifiers == Qt.KeyboardModifier.ControlModifier:
# Cut segments
self._edit_sound_using_segments(is_inverse=True) # nb, True
elif modifiers == (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier):
# Cut segments inverse
self._edit_sound_using_segments(is_inverse=False)
elif key == Qt.Key.Key_N and modifiers == Qt.KeyboardModifier.ControlModifier:
if self._state.sound:
DB = -3.0
new_sound = SoundUtil.normalize(self._state.sound, DB)
self._update_state_using_sound(new_sound)
print(f"Peak normalized {DB}db")
# Compressor
elif key == Qt.Key.Key_C:
self._set_compressor_enabled(not self._settings.compressor_enabled)
# Delete sound
elif key == Qt.Key.Key_Delete:
self._do_delete_current_sound()
elif key == Qt.Key.Key_S:
if modifiers == Qt.KeyboardModifier.ControlModifier:
# Manual save
if self._state.sound and self._state.sound_dirty:
self._save_sound()
self._update_header()
else:
print("Nothing to save")
else:
# Split files dialog
self._split_dialog()
# Directory-wide save operations dialog
elif key == Qt.Key.Key_D:
self._dir_op_dialog()
else:
super().keyPressEvent(event)
def wheelEvent(self, event):
"""Handle mouse wheel for zooming."""
delta = event.angleDelta().y()
increment = 0.02 if delta > 0 else -0.02
self._increment_zoom(increment)
event.accept()
def mouseMoveEvent(self, event: QMouseEvent) -> None:
"""Track mouse position"""
self._mouse_pos = (event.position().x(), event.position().y())
super().mouseMoveEvent(event)
def moveEvent(self, event: QMoveEvent) -> None:
""" Handle window move """
self._window_rect_timer.start(500) # Debounce 500ms
super().moveEvent(event)
def resizeEvent(self, event: QResizeEvent) -> None:
""" Handle window resize """
self._window_rect_timer.start(500) # Debounce 500ms
super().resizeEvent(event)
def showEvent(self, event: QShowEvent) -> None:
"""Lock window height after initial display"""
super().showEvent(event)
self.setFixedHeight(self.height())
def closeEvent(self, event) -> None:
"""Handle window close, save some settings values"""
self._interval_timer.stop()
# Timeline zoom is already synced via AppState
self._settings.set_window_geometry(self.x(), self.y(), self.width())
event.accept()
def _on_window_rect_complete(self) -> None:
"""Save window geometry after debounce"""
self._settings.set_window_geometry(self.x(), self.y(), self.width())
def _on_timeline_click(self, mouse_action: TimelineMouseAction) -> None:
if self.ignore_user_input:
return
if not self._state.sound:
return
print(mouse_action)
match mouse_action:
case SeekAction(position):
self._stream.position = position
case DeleteSelectionAction(index):
assert self._state.segments
segment = self._state.segments.segments[index]
self._state.delete_segment_at(index)
print(f"Deleted selection {segment}")
self._on_segments_changed()
case SelectionBeginAction(begin_position, _):
# First click: set start point
self._timeline.segment_start = begin_position
case SelectionCompleteAction(complete_position, begin_position, _):
# Second click: complete the selection
# Normalize: ensure start < end
start = min(begin_position, complete_position)
end = max(begin_position, complete_position)
# Insert segment
index = self._state.insert_segment(start, end, can_merge=True)
if index == -1:
print(f"Couldn't add selection {make_position_range_string(start, end)}")
return
print(f"Added selection {make_position_range_string(start, end)}")
self._timeline.segment_start = -1 # Reset start marker
self._on_segments_changed()
case _:
...
# xxx assert_never(mouse_action)
# typ = mouse_action.typ
# value = mouse_action.value
# match typ:
# case TimelineMouseActionType.SELECTION_BEGIN_START | \
# TimelineMouseActionType.SELECTION_BEGIN_START_SILENCE | \
# TimelineMouseActionType.SELECTION_BEGIN_END | \
# TimelineMouseActionType.SELECTION_END_SILENCE:
# segment = None
# if typ in [TimelineMouseActionType.SELECTION_BEGIN_START, TimelineMouseActionType.SELECTION_BEGIN_START_SILENCE]:
# end = self._timeline.segment_end
# if typ == TimelineMouseActionType.SELECTION_BEGIN_START_SILENCE:
# silence_segment = SilenceUtil.detect_silence_boundaries_from(self._state.sound, value)
# if not silence_segment:
# print(f"Ignoring, no silence detected at {value:2f}")
# return
# else:
# start = silence_segment[1] # TODO crossed boundary
# else:
# start = value
# if end >= 0:
# if start >= end:
# # Overwrite end marker with start marker
# self._timeline.segment_start = start
# self._timeline.segment_end = -1
# else:
# segment = (start, end)
# else:
# # Set start marker
# self._timeline.segment_start = start
# else: # SELECTION_END or SELECTION_END_SILENCE_DETECT:
# start = self._timeline.segment_start
# if typ == TimelineMouseActionType.SELECTION_END_SILENCE:
# silence_segment = SilenceUtil.detect_silence_boundaries_from(self._state.sound, value)
# if not silence_segment:
# print(f"Ignoring, no silence detected at {value:2f}")
# return
# else:
# end = silence_segment[0] # TODO crossed boundary
# else:
# end = value
# if start >= 0:
# if end <= start:
# # Overwrite start marker with end marker
# self._timeline.segment_end = end
# self._timeline.segment_start = -1
# else:
# segment = (start, end)
# else:
# # Set end marker
# self._timeline.segment_end = end
# if segment:
# index = self._state.insert_segment(segment[0], segment[1], can_merge=True)
# if index == -1:
# # Couldn't insert segment
# print(f"Couldn't add selection {make_position_range_string(segment[0], segment[1])}")
# return
# print(f"Added selection {make_position_range_string(segment[0], segment[1])}")
# self._timeline.segment_start = -1
# self._timeline.segment_end = -1
# self._on_segments_changed()
def _on_fast_mode_label_click(self) -> None:
self._settings.fast_mode = not self._settings.fast_mode
self._update_togglable_label(
self._fast_mode_label, "Fast mode", self._settings.fast_mode
)
def _on_start_end_auto_label_click(self) -> None:
self._toggle_start_end_auto()
def _on_compressor_label_click(self) -> None:
self._set_compressor_enabled(not self._settings.compressor_enabled)
def _on_help_button(self) -> None:
webbrowser.open(HELP_URL)
def _on_stream_complete(self) -> None:
if self._loader.is_loading:
return
match self.play_mode:
case FilePlayMode.REPEAT_SINGLE:
self._stream.clear_completion_event() # nb
self._stream.position = self._stream.min_position
case FilePlayMode.TO_END:
if self._settings.index < len(self._settings.file_paths) - 1:
self._load_sound_by_increment(1)
case FilePlayMode.TO_END_REPEAT:
if self._settings.index < len(self._settings.file_paths) - 1:
self._load_sound_by_increment(1)
else:
self._load_sound_by_index(0)
case FilePlayMode.RANDOM_NEXT:
i = random.randrange(0, len(self._settings.file_paths))
self._load_sound_by_index(i)
case _:
... # do nothing
def _on_segments_changed(self) -> None:
"""
Sets a copy of sound_state segments on the Stream instance.
Should be called on any segment update.
"""
assert self._state.segments is not None
self._stream.segments = self._state.segments.segments.copy()
if not self._state.segments.segments and isinstance(self.play_mode, SegmentPlayMode):
self.play_mode = FilePlayMode.DEFAULT
def _on_sound_blur(self) -> None:
""" Should be called before current sound is navigated away from, on quit, etc """
if not self._state.sound:
return
if self._state.sound_dirty:
# Save sound
ok = self._save_sound()
if not ok:
return
# Delete existing segments json
assert self._state.segments
self._state.segments.segments.clear()
self._state.segments.delete_json()
else:
# Sound is not dirty; save segments json if necessary
assert self._state.segments
self._state.segments.save_json()
# === Internal methods ===
@property
def ignore_user_input(self) -> bool:
return self._loader.is_loading
@property
def play_mode(self) -> SegmentPlayMode | FilePlayMode:
"""Delegates to AppState for coordinated state access."""
return self._app_state.play_mode
@play_mode.setter
def play_mode(self, value: SegmentPlayMode | FilePlayMode) -> None:
"""Delegates to AppState for coordinated state update."""
self._app_state.set_play_mode(value)
def _get_play_info_text(self) -> tuple[str, str]:
if not self._state.has_sound:
string = "No sound"
color = "#888888"
else:
index = self._stream.get_segment_index()
if not self._state.has_segments:
index_string = "None"
else:
index_string = str(index+1) if index > -1 else "-"
index_string += f" / {self._state.num_segments}"
string = "Play mode: "
match self.play_mode:
case FilePlayMode.DEFAULT:
string += "Normal"
color = "#888888"
case FilePlayMode.REPEAT_SINGLE:
string += "Repeat single"
color = "#ffffff"
case FilePlayMode.TO_END:
string += "Auto-advance"
color = "#ffffff"
case FilePlayMode.TO_END_REPEAT:
string += "Auto-advance and repeat"
color = "#ffffff"
case FilePlayMode.RANDOM_NEXT:
string += "Random next"
color = "#ffffff"
case SegmentPlayMode.TO_END:
string += "Segments"
color = "red"
case SegmentPlayMode.REPEAT_ALL:
string += "Segments (repeat)"
color = "red"
case SegmentPlayMode.REPEAT_SINGLE:
string += "Segments (repeat single)"
color = "red"
case None: # shouldnt happen
color = "#888888"
return string, color
def _load_sound_using_current_state(self) -> None:
self._load_sound(self._settings.current_file_path)
def _load_sound(self, path: str) -> None:
"""
Main initialization routine
"""
def on_load_complete(result: Sound | str) -> None:
# Rem, is not on UI thread
if isinstance(result, str):
# Error
print("\n\n*", result[:100], "\n")
sound = None
else:
# Loaded
ms = int((time.time() - start_time) * 1000)
print(f"{ms}ms")
num_channels = result.data.shape[0]
if num_channels > 2:
print(f"* Sound file with more than two channels ({num_channels}) is unsupported")
sound = None
else:
# Success
sound = result
# Continue on UI thread using signal (thread-safe)
self._load_complete_signal.emit(sound, path)