Repository navigation
Expand file tree
/
Copy pathdialogs.py
More file actions
2951 lines (2507 loc) · 119 KB
/
Copy pathdialogs.py
File metadata and controls
2951 lines (2507 loc) · 119 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
"""Dialog windows for CapsQual."""
import html
import os
import json
import re
import shutil
from pathlib import Path
from PyQt5.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QLabel, QTextEdit, QDialogButtonBox,
QPushButton, QLineEdit, QWidget, QMessageBox, QComboBox, QStackedWidget,
QScrollArea, QFrame, QSizePolicy, QGridLayout, QFileDialog, QCheckBox,
QRadioButton, QGroupBox, QSpinBox, QDoubleSpinBox, QPlainTextEdit, QShortcut, QFontDialog, QFormLayout, QApplication,
QTreeWidget, QTreeWidgetItem
)
from PyQt5.QtCore import Qt, QTimer, QRect
from PyQt5.QtGui import QFont, QKeySequence
from widgets import ThemeToggle
from utils import logger, app_data_dir
from highlighting import FormattingMarkerHighlighter
from generators import (
generate_srt_text, generate_transcript_text, strip_markup
)
from export import build_html_content
def _is_dark_theme(widget):
"""Check whether *widget* is using the dark palette via its QPalette."""
return widget.palette().window().color().lightness() < 128
class TextSelectionDialog(QDialog):
def __init__(self, block_text, parent=None):
super().__init__(parent)
self.block_text = block_text
self.start_pos = 0
self.end_pos = 0
self.dark = _is_dark_theme(self)
self.init_ui()
def init_ui(self):
self.setWindowTitle("Select Text")
self.setGeometry(300, 300, 700, 300)
layout = QVBoxLayout(self)
instructions = QLabel("Use ← → arrows to adjust selection, Shift+arrows to extend, then press Enter:")
instructions.setStyleSheet("font-weight: bold;")
layout.addWidget(instructions)
self.text_display = QTextEdit()
self.text_display.setReadOnly(True)
self.text_display.setMaximumHeight(100)
self.text_display.setStyleSheet("font-family: monospace; font-size: 14px;")
self.highlighter = FormattingMarkerHighlighter(self.text_display.document())
layout.addWidget(self.text_display)
self.selection_label = QLabel("Selection: (none)")
layout.addWidget(self.selection_label)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
for button in button_box.buttons():
button.setFocusPolicy(Qt.NoFocus)
layout.addWidget(button_box)
self.update_display()
self.setFocusPolicy(Qt.StrongFocus)
self.setFocus()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Left and not event.modifiers() & Qt.ShiftModifier:
if self.start_pos > 0:
self.start_pos -= 1
self.end_pos = self.start_pos
self.update_display()
event.accept()
elif event.key() == Qt.Key_Right and not event.modifiers() & Qt.ShiftModifier:
if self.end_pos < len(self.block_text):
self.start_pos += 1
self.end_pos = self.start_pos
self.update_display()
event.accept()
elif event.key() == Qt.Key_Left and event.modifiers() & Qt.ShiftModifier:
if self.start_pos > 0:
self.start_pos -= 1
self.update_display()
event.accept()
elif event.key() == Qt.Key_Right and event.modifiers() & Qt.ShiftModifier:
if self.end_pos < len(self.block_text):
self.end_pos += 1
self.update_display()
event.accept()
elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
self.accept()
event.accept()
else:
super().keyPressEvent(event)
def update_display(self):
before_text = self.block_text[:self.start_pos]
selected_text = self.block_text[self.start_pos:self.end_pos]
after_text = self.block_text[self.end_pos:]
if self.dark:
text_bg = "#3a3a3a"
sel_bg = "#5a4a20"
else:
text_bg = "#e0e0e0"
sel_bg = "#ffcc00"
html_content = f"""
<div style="font-family: monospace; font-size: 14px; padding: 10px;">
<span style="background-color: {text_bg}; padding: 5px; border-radius: 3px;">{html.escape(before_text)}</span>
<span style="background-color: {sel_bg}; padding: 5px; border-radius: 3px;">{html.escape(selected_text)}</span>
<span style="background-color: {text_bg}; padding: 5px; border-radius: 3px;">{html.escape(after_text)}</span>
</div>
"""
self.text_display.setHtml(html_content)
if self.start_pos == self.end_pos:
self.selection_label.setText(f"Selection: (none) - Position: {self.start_pos}")
else:
self.selection_label.setText(f"Selection: '{html.escape(selected_text)}' (positions {self.start_pos}-{self.end_pos})")
def get_selection(self):
return self.start_pos, self.end_pos, self.block_text[self.start_pos:self.end_pos]
class BlockSplitDialog(QDialog):
def __init__(self, block_text, parent=None):
super().__init__(parent)
self.block_text = block_text
self.split_position = 0
self.dark = _is_dark_theme(self)
self.init_ui()
def init_ui(self):
self.setWindowTitle("Split Block")
self.setGeometry(300, 300, 700, 250)
layout = QVBoxLayout(self)
instructions = QLabel("Use ← → arrows to position split, then press Enter to confirm:")
instructions.setStyleSheet("font-weight: bold;")
layout.addWidget(instructions)
self.text_display = QTextEdit()
self.text_display.setReadOnly(True)
self.text_display.setMaximumHeight(100)
self.text_display.setStyleSheet("font-family: monospace; font-size: 14px;")
layout.addWidget(self.text_display)
self.cursor_label = QLabel("Split position: 0")
layout.addWidget(self.cursor_label)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
for button in button_box.buttons():
button.setFocusPolicy(Qt.NoFocus)
layout.addWidget(button_box)
self.update_display()
self.setFocusPolicy(Qt.StrongFocus)
self.setFocus()
def keyPressEvent(self, event):
if event.key() == Qt.Key_Left:
self.split_position = max(0, self.split_position - 1)
self.update_display()
event.accept()
elif event.key() == Qt.Key_Right:
self.split_position = min(len(self.block_text), self.split_position + 1)
self.update_display()
event.accept()
elif event.key() in (Qt.Key_Return, Qt.Key_Enter, Qt.Key_Space):
self.accept()
event.accept()
else:
super().keyPressEvent(event)
def update_display(self):
before_text = self.block_text[:self.split_position]
after_text = self.block_text[self.split_position:]
if self.dark:
before_bg = "#3a5a3a"
after_bg = "#5a3a3a"
else:
before_bg = "#c8f7c8"
after_bg = "#f7c8c8"
html_content = f"""
<div style="font-family: monospace; font-size: 14px; padding: 10px;">
<span style="background-color: {before_bg}; padding: 5px; border-radius: 3px;">{html.escape(before_text)}</span>
<span style="background-color: {after_bg}; padding: 5px; border-radius: 3px;">{html.escape(after_text)}</span>
</div>
"""
self.text_display.setHtml(html_content)
self.cursor_label.setText(f"Split position: {self.split_position} (text will be split after character {self.split_position})")
class EditTimestampsDialog(QDialog):
def __init__(self, start_time="", end_time="", parent=None):
super().__init__(parent)
self.start_time = start_time
self.end_time = end_time
self.init_ui()
def init_ui(self):
self.setWindowTitle("Edit Segment Timestamps")
self.setGeometry(300, 300, 350, 200)
layout = QVBoxLayout(self)
# Checkbox to enable/disable timestamps
self.enable_check = QCheckBox("Set timestamps for this segment")
self.enable_check.setChecked(bool(self.start_time or self.end_time))
self.enable_check.toggled.connect(self.on_enable_toggled)
layout.addWidget(self.enable_check)
# Create spin boxes for start time with labels above
start_group = QGroupBox("Start Time")
start_layout = QVBoxLayout()
# Labels row – each label has fixed width matching its spin box
labels_layout = QHBoxLayout()
lbl_h = QLabel("HH")
lbl_h.setFixedWidth(80)
lbl_h.setAlignment(Qt.AlignCenter)
labels_layout.addWidget(lbl_h)
lbl_m = QLabel("mm")
lbl_m.setFixedWidth(80)
lbl_m.setAlignment(Qt.AlignCenter)
labels_layout.addWidget(lbl_m)
lbl_s = QLabel("ss")
lbl_s.setFixedWidth(80)
lbl_s.setAlignment(Qt.AlignCenter)
labels_layout.addWidget(lbl_s)
lbl_ms = QLabel("SSS")
lbl_ms.setFixedWidth(90)
lbl_ms.setAlignment(Qt.AlignCenter)
labels_layout.addWidget(lbl_ms)
labels_layout.addStretch()
start_layout.addLayout(labels_layout)
# Spin boxes row
spins_layout = QHBoxLayout()
self.start_h = QSpinBox()
self.start_h.setRange(0, 99)
self.start_h.setFixedWidth(80)
self.start_h.setAlignment(Qt.AlignCenter)
self.start_m = QSpinBox()
self.start_m.setRange(0, 59)
self.start_m.setFixedWidth(80)
self.start_m.setAlignment(Qt.AlignCenter)
self.start_s = QSpinBox()
self.start_s.setRange(0, 59)
self.start_s.setFixedWidth(80)
self.start_s.setAlignment(Qt.AlignCenter)
self.start_ms = QSpinBox()
self.start_ms.setRange(0, 999)
self.start_ms.setFixedWidth(90)
self.start_ms.setAlignment(Qt.AlignCenter)
spins_layout.addWidget(self.start_h)
spins_layout.addWidget(self.start_m)
spins_layout.addWidget(self.start_s)
spins_layout.addWidget(self.start_ms)
spins_layout.addStretch()
start_layout.addLayout(spins_layout)
start_group.setLayout(start_layout)
layout.addWidget(start_group)
# End time group (identical structure)
end_group = QGroupBox("End Time")
end_layout = QVBoxLayout()
# Labels row for end time
labels_layout_end = QHBoxLayout()
lbl_h_end = QLabel("HH")
lbl_h_end.setFixedWidth(80)
lbl_h_end.setAlignment(Qt.AlignCenter)
labels_layout_end.addWidget(lbl_h_end)
lbl_m_end = QLabel("mm")
lbl_m_end.setFixedWidth(80)
lbl_m_end.setAlignment(Qt.AlignCenter)
labels_layout_end.addWidget(lbl_m_end)
lbl_s_end = QLabel("ss")
lbl_s_end.setFixedWidth(80)
lbl_s_end.setAlignment(Qt.AlignCenter)
labels_layout_end.addWidget(lbl_s_end)
lbl_ms_end = QLabel("SSS")
lbl_ms_end.setFixedWidth(90)
lbl_ms_end.setAlignment(Qt.AlignCenter)
labels_layout_end.addWidget(lbl_ms_end)
labels_layout_end.addStretch()
end_layout.addLayout(labels_layout_end)
# Spin boxes row for end time
spins_layout_end = QHBoxLayout()
self.end_h = QSpinBox()
self.end_h.setRange(0, 99)
self.end_h.setFixedWidth(80)
self.end_h.setAlignment(Qt.AlignCenter)
self.end_m = QSpinBox()
self.end_m.setRange(0, 59)
self.end_m.setFixedWidth(80)
self.end_m.setAlignment(Qt.AlignCenter)
self.end_s = QSpinBox()
self.end_s.setRange(0, 59)
self.end_s.setFixedWidth(80)
self.end_s.setAlignment(Qt.AlignCenter)
self.end_ms = QSpinBox()
self.end_ms.setRange(0, 999)
self.end_ms.setFixedWidth(90)
self.end_ms.setAlignment(Qt.AlignCenter)
spins_layout_end.addWidget(self.end_h)
spins_layout_end.addWidget(self.end_m)
spins_layout_end.addWidget(self.end_s)
spins_layout_end.addWidget(self.end_ms)
spins_layout_end.addStretch()
end_layout.addLayout(spins_layout_end)
end_group.setLayout(end_layout)
layout.addWidget(end_group)
# Parse existing times to populate spin boxes
self.parse_time(self.start_time, self.start_h, self.start_m, self.start_s, self.start_ms)
self.parse_time(self.end_time, self.end_h, self.end_m, self.end_s, self.end_ms)
# Buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
# Initial enable state
self.on_enable_toggled(self.enable_check.isChecked())
def parse_time(self, time_str, h_spin, m_spin, s_spin, ms_spin):
"""Parse a time string like HH:MM:SS,mmm and set spin boxes."""
if not time_str:
return
match = re.match(r'(\d{2}):(\d{2}):(\d{2}),(\d{3})', time_str)
if match:
h_spin.setValue(int(match.group(1)))
m_spin.setValue(int(match.group(2)))
s_spin.setValue(int(match.group(3)))
ms_spin.setValue(int(match.group(4)))
def on_enable_toggled(self, checked):
"""Enable/disable all spin boxes based on checkbox."""
for spin in [self.start_h, self.start_m, self.start_s, self.start_ms,
self.end_h, self.end_m, self.end_s, self.end_ms]:
spin.setEnabled(checked)
def get_times(self):
"""Return formatted start and end time strings, or empty strings if disabled."""
if not self.enable_check.isChecked():
return "", ""
start = f"{self.start_h.value():02d}:{self.start_m.value():02d}:{self.start_s.value():02d},{self.start_ms.value():03d}"
end = f"{self.end_h.value():02d}:{self.end_m.value():02d}:{self.end_s.value():02d},{self.end_ms.value():03d}"
return start, end
class InsertPausesDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.init_ui()
def init_ui(self):
self.setWindowTitle("Insert Pause Symbols for Gaps")
self.setGeometry(300, 300, 500, 300)
layout = QVBoxLayout(self)
# Convention
form_layout = QFormLayout()
self.convention_combo = QComboBox()
self.convention_combo.addItems(["GAT2", "Dresing & Pehl", "TiQ"])
form_layout.addRow("Transcription convention:", self.convention_combo)
# Measured pauses
self.measured_check = QCheckBox("Use measured pauses for gaps longer than")
self.measured_spin = QSpinBox()
self.measured_spin.setRange(1, 60)
self.measured_spin.setValue(2)
self.measured_spin.setSuffix(" seconds")
self.measured_check.toggled.connect(self.measured_spin.setEnabled)
self.measured_spin.setEnabled(False)
measured_layout = QHBoxLayout()
measured_layout.addWidget(self.measured_check)
measured_layout.addWidget(self.measured_spin)
measured_layout.addStretch()
form_layout.addRow(measured_layout)
# Minimum gap
self.min_gap_spin = QDoubleSpinBox()
self.min_gap_spin.setRange(0.0, 10.0)
self.min_gap_spin.setSingleStep(0.1)
self.min_gap_spin.setValue(0.1)
self.min_gap_spin.setSuffix(" seconds")
form_layout.addRow("Minimum gap to consider:", self.min_gap_spin)
# Insert mode
mode_group = QGroupBox("Insert pauses")
mode_layout = QVBoxLayout()
self.separate_radio = QRadioButton("On separate lines")
self.attach_radio = QRadioButton("At the beginning of the following segment")
self.threshold_radio = QRadioButton("Separately if gap ≥")
self.threshold_spin = QDoubleSpinBox()
self.threshold_spin.setRange(0.1, 60.0)
self.threshold_spin.setValue(4.0)
self.threshold_spin.setSuffix(" seconds")
self.threshold_radio.toggled.connect(self.threshold_spin.setEnabled)
self.threshold_spin.setEnabled(False)
self.separate_radio.setChecked(True)
mode_layout.addWidget(self.separate_radio)
mode_layout.addWidget(self.attach_radio)
threshold_row = QHBoxLayout()
threshold_row.addWidget(self.threshold_radio)
threshold_row.addWidget(self.threshold_spin)
threshold_row.addStretch()
mode_layout.addLayout(threshold_row)
mode_group.setLayout(mode_layout)
form_layout.addRow(mode_group)
layout.addLayout(form_layout)
# Info label
info = QLabel("Pauses will be inserted between existing segments based on gaps in timestamps.")
info.setWordWrap(True)
info.setStyleSheet("color: #555; font-size: 11px;")
layout.addWidget(info)
# Buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
def get_settings(self):
if self.separate_radio.isChecked():
mode = "separate"
threshold = 0
elif self.attach_radio.isChecked():
mode = "attach"
threshold = 0
else:
mode = "threshold"
threshold = self.threshold_spin.value()
return {
'convention': self.convention_combo.currentText().lower().replace(' & ', '_'),
'use_measured': self.measured_check.isChecked(),
'measured_threshold': self.measured_spin.value(),
'min_gap': self.min_gap_spin.value(),
'mode': mode,
'threshold': threshold
}
class SymbolCategory:
def __init__(self, name, symbols, descriptions=None):
self.name = name
self.symbols = symbols
self.descriptions = descriptions or [""] * len(symbols)
self.selected_index = 0
class AddCustomSymbolDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Add Custom Symbol")
self.setGeometry(300, 300, 500, 250)
# Detect dark theme through parent chain
dark = False
try:
if parent and hasattr(parent, '_is_dark') and parent._is_dark():
dark = True
elif parent and hasattr(parent, 'parent'):
gp = parent.parent()
if gp and hasattr(gp, 'current_theme') and gp.current_theme == "dark":
dark = True
except AttributeError:
pass
if dark:
self.setStyleSheet("""
QDialog {
background-color: #2d2d2d;
}
QLabel {
color: #cccccc;
}
QLineEdit {
background-color: #3a3a3a;
color: #cccccc;
border: 1px solid #555;
}
QComboBox {
background-color: #3a3a3a;
color: #cccccc;
border: 1px solid #555;
}
""")
layout = QVBoxLayout(self)
# Symbol type selector
type_layout = QHBoxLayout()
type_layout.addWidget(QLabel("Symbol type:"))
self.type_combo = QComboBox()
self.type_combo.addItems(["Simple", "Segment Wrapper", "Comment Wrapper", "Comment with Scope"])
self.type_combo.currentTextChanged.connect(self.update_fields)
type_layout.addWidget(self.type_combo)
layout.addLayout(type_layout)
# Stacked widget for different input fields
self.stacked = QStackedWidget()
layout.addWidget(self.stacked)
# ---- Page 0: Simple ----
simple_page = QWidget()
simple_layout = QVBoxLayout(simple_page)
self.simple_symbol_edit = QLineEdit()
self.simple_symbol_edit.setPlaceholderText("Enter symbol text")
simple_layout.addWidget(QLabel("Symbol:"))
simple_layout.addWidget(self.simple_symbol_edit)
self.simple_desc_edit = QLineEdit()
self.simple_desc_edit.setPlaceholderText("Optional description")
simple_layout.addWidget(QLabel("Description (optional):"))
simple_layout.addWidget(self.simple_desc_edit)
self.stacked.addWidget(simple_page)
# ---- Page 1: Segment Wrapper ----
wrapper_page = QWidget()
wrapper_layout = QVBoxLayout(wrapper_page)
self.wrapper_left_edit = QLineEdit()
self.wrapper_left_edit.setPlaceholderText("e.g., <<")
wrapper_layout.addWidget(QLabel("Left side:"))
wrapper_layout.addWidget(self.wrapper_left_edit)
self.wrapper_right_edit = QLineEdit()
self.wrapper_right_edit.setPlaceholderText("e.g., >>")
wrapper_layout.addWidget(QLabel("Right side:"))
wrapper_layout.addWidget(self.wrapper_right_edit)
self.wrapper_desc_edit = QLineEdit()
self.wrapper_desc_edit.setPlaceholderText("Optional description")
wrapper_layout.addWidget(QLabel("Description (optional):"))
wrapper_layout.addWidget(self.wrapper_desc_edit)
self.stacked.addWidget(wrapper_page)
# ---- Page 2: Comment Wrapper ----
comment_page = QWidget()
comment_layout = QVBoxLayout(comment_page)
self.comment_left_edit = QLineEdit()
self.comment_left_edit.setPlaceholderText("e.g., ((")
comment_layout.addWidget(QLabel("Left side:"))
comment_layout.addWidget(self.comment_left_edit)
self.comment_right_edit = QLineEdit()
self.comment_right_edit.setPlaceholderText("e.g., ))")
comment_layout.addWidget(QLabel("Right side:"))
comment_layout.addWidget(self.comment_right_edit)
self.comment_desc_edit = QLineEdit()
self.comment_desc_edit.setPlaceholderText("Optional description")
comment_layout.addWidget(QLabel("Description (optional):"))
comment_layout.addWidget(self.comment_desc_edit)
self.stacked.addWidget(comment_page)
# ---- Page 3: Comment with Scope ----
reach_page = QWidget()
reach_layout = QVBoxLayout(reach_page)
self.reach_left_edit = QLineEdit()
self.reach_left_edit.setPlaceholderText("e.g., <<")
reach_layout.addWidget(QLabel("Action/comment left side:"))
reach_layout.addWidget(self.reach_left_edit)
self.reach_right_action_edit = QLineEdit()
self.reach_right_action_edit.setPlaceholderText("e.g., >")
reach_layout.addWidget(QLabel("Action/comment right side:"))
reach_layout.addWidget(self.reach_right_action_edit)
self.reach_right_segment_edit = QLineEdit()
self.reach_right_segment_edit.setPlaceholderText("e.g., >")
reach_layout.addWidget(QLabel("Segment right side:"))
reach_layout.addWidget(self.reach_right_segment_edit)
self.reach_desc_edit = QLineEdit()
self.reach_desc_edit.setPlaceholderText("Optional description")
reach_layout.addWidget(QLabel("Description (optional):"))
reach_layout.addWidget(self.reach_desc_edit)
self.stacked.addWidget(reach_page)
# OK / Cancel buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.update_fields()
def update_fields(self):
"""Switch stacked page based on selected type"""
index = self.type_combo.currentIndex()
self.stacked.setCurrentIndex(index)
def get_symbol_data(self):
"""Return dictionary with symbol info, or None if validation fails"""
data = {}
index = self.type_combo.currentIndex()
if index == 0: # Simple
symbol = self.simple_symbol_edit.text().strip()
if not symbol:
QMessageBox.warning(self, "Missing Data", "Symbol text cannot be empty.")
return None
data = {
'type': 'simple',
'display': symbol,
'value': symbol,
'description': self.simple_desc_edit.text().strip() or symbol
}
elif index == 1: # Segment Wrapper
left = self.wrapper_left_edit.text().strip()
right = self.wrapper_right_edit.text().strip()
if not left or not right:
QMessageBox.warning(self, "Missing Data", "Both left and right sides are required.")
return None
display = f"{left}text{right}"
data = {
'type': 'wrapper',
'display': display,
'left': left,
'right': right,
'description': self.wrapper_desc_edit.text().strip() or display
}
elif index == 2: # Comment Wrapper
left = self.comment_left_edit.text().strip()
right = self.comment_right_edit.text().strip()
if not left or not right:
QMessageBox.warning(self, "Missing Data", "Both left and right sides are required.")
return None
display = f"{left}comment{right}"
data = {
'type': 'comment',
'display': display,
'left': left,
'right': right,
'description': self.comment_desc_edit.text().strip() or display
}
else: # Comment with Scope
left = self.reach_left_edit.text().strip()
right_action = self.reach_right_action_edit.text().strip()
right_segment = self.reach_right_segment_edit.text().strip()
if not left or not right_action or not right_segment:
QMessageBox.warning(self, "Missing Data", "All three sides are required.")
return None
display = f"{left}comment{right_action}text{right_segment}"
data = {
'type': 'comment_reach',
'display': display,
'left': left,
'right': right_action,
'segment_right': right_segment,
'description': self.reach_desc_edit.text().strip() or display
}
return data
class EnhancedSymbolDialog(QDialog):
# Custom symbols live in the per-user data directory (standard convention),
# NOT next to the executable — the install dir may be read-only.
custom_symbols_file = os.path.join(app_data_dir(), "custom_symbols.json")
# Builds before the app-data change saved next to the source/install dir;
# load_custom_symbols() migrates it on first run of the new version.
_legacy_custom_symbols_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "custom_symbols.json")
custom_symbols = []
def __init__(self, parent=None, initial_category=None):
super().__init__(parent)
# NOTE: do NOT store the editor as `self.parent` — that shadows
# QWidget.parent() and crashes callers like AddCustomSymbolDialog
# (TypeError: '<Editor>' object is not callable).
self.editor = parent
self.initial_category = initial_category
self.categories = []
self.current_category_index = 0
self.selected_option = 0
self.load_custom_symbols()
self.init_categories()
self.init_ui()
def _is_dark(self):
"""Detect if the parent editor is in dark theme."""
try:
return self.editor.current_theme == "dark"
except AttributeError:
return False
def init_categories(self):
# GAT2
self.categories.append(SymbolCategory(
"GAT2",
["(.)", "(-)", "(--)", "(---)", "(_._)", "(())", "<<>>", "[ ]",
"°h", "°hh", "°hhh", "h°", "hh°", "hhh°"],
["micropause", "short estimated pause", "medium estimated pause", "long estimated pause",
"measured pause", "comment", "action/comment with scope", "overlap",
"short inhale", "medium inhale", "long inhale",
"short exhale", "medium exhale", "long exhale"]
))
# Dresing & Pehl
self.categories.append(SymbolCategory(
"Dresing && Pehl",
["(.)", "(..)", "(...)", "(_)", "//", "( )", "⏱️"],
["short estimated pause", "medium estimated pause", "long estimated pause",
"measured pause", "overlap", "comment", "insert timestamp"]
))
# TiQ
self.categories.append(SymbolCategory(
"TiQ",
["(.)", "(_)", "(())", "└", "@(.)@", "@(_)@", "@( )@", "° °", "// //"],
["short pause", "measured pause", "comment",
"overlap marker", "short laughter", "laughing seconds",
"laughing speech", "quiet speech", "listener's signal"]
))
# Custom
custom_symbols_list = [s['display'] for s in self.custom_symbols]
custom_descriptions = [s.get('description', s['type']) for s in self.custom_symbols]
self.categories.append(SymbolCategory(
"Custom",
custom_symbols_list,
custom_descriptions
))
def load_custom_symbols(self):
try:
path = EnhancedSymbolDialog.custom_symbols_file
if not os.path.exists(path):
self._migrate_custom_symbols_if_needed(path)
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as f:
self.custom_symbols = json.load(f)
else:
self.custom_symbols = []
except Exception as e:
logger.error(f"Failed to load custom symbols: {e}")
self.custom_symbols = []
def _migrate_custom_symbols_if_needed(self, new_path):
"""One-time migration from the old install-dir location, if present."""
legacy = EnhancedSymbolDialog._legacy_custom_symbols_file
if legacy == new_path or not os.path.exists(legacy):
return
try:
os.makedirs(os.path.dirname(new_path), exist_ok=True)
shutil.copy2(legacy, new_path)
logger.info("Migrated custom symbols from %s to %s", legacy, new_path)
except Exception as e:
logger.warning("Could not migrate custom symbols from %s: %s", legacy, e)
def save_custom_symbols(self):
try:
path = EnhancedSymbolDialog.custom_symbols_file
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
json.dump(self.custom_symbols, f, indent=2)
except Exception as e:
logger.error(f"Failed to save custom symbols: {e}")
QMessageBox.warning(self, "Error", f"Could not save custom symbols: {e}")
def init_ui(self):
self.setWindowTitle("Insert Symbol")
self.setGeometry(300, 300, 650, 500)
if self._is_dark():
self.setStyleSheet("""
QDialog {
background-color: #2d2d2d;
}
QLabel {
color: #cccccc;
}
""")
layout = QVBoxLayout(self)
# Category tabs
tab_layout = QHBoxLayout()
self.category_buttons = []
for i, category in enumerate(self.categories):
btn = QPushButton(category.name)
btn.setCheckable(True)
btn.setChecked(i == 0)
btn.setFocusPolicy(Qt.TabFocus)
if self._is_dark():
btn.setStyleSheet("""
QPushButton {
padding: 8px 15px;
font-weight: bold;
border: 2px solid #555;
border-radius: 5px 5px 0 0;
background-color: #3a3a3a;
color: #cccccc;
}
QPushButton:checked {
background-color: #4a90e2;
color: white;
border-bottom-color: #4a90e2;
}
QPushButton:hover:!checked {
background-color: #4a4a4a;
}
""")
else:
btn.setStyleSheet("""
QPushButton {
padding: 8px 15px;
font-weight: bold;
border: 2px solid #ccc;
border-radius: 5px 5px 0 0;
background-color: #f0f0f0;
}
QPushButton:checked {
background-color: #4a90e2;
color: white;
border-bottom-color: #4a90e2;
}
QPushButton:hover:!checked {
background-color: #e0e0e0;
}
""")
btn.clicked.connect(lambda checked, idx=i: self.switch_category(idx))
tab_layout.addWidget(btn)
self.category_buttons.append(btn)
tab_instruction = QLabel("<i>(Tab to switch)</i>")
tab_instruction.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
if self._is_dark():
tab_instruction.setStyleSheet("color: #888; font-size: 11px;")
else:
tab_instruction.setStyleSheet("color: #555; font-size: 11px;")
tab_layout.addWidget(tab_instruction)
tab_layout.addSpacing(23)
layout.addLayout(tab_layout)
# Management buttons for custom category
self.management_layout = QHBoxLayout()
self.btn_add_symbol = QPushButton("Add New Symbol")
self.btn_add_symbol.clicked.connect(self.add_new_symbol)
self.btn_add_symbol.setVisible(False)
self.btn_delete_custom = QPushButton("Delete Selected")
self.btn_delete_custom.clicked.connect(self.delete_selected_symbol)
self.btn_delete_custom.setVisible(False)
self.btn_delete_custom.setStyleSheet("""
QPushButton:hover {
background-color: #fdd2d2;
border: 1px solid #cc0000;
border-radius: 3px;
}
QPushButton:disabled {
background-color: #cccccc;
border-color: #999999;
color: #666666;
}
""")
self.btn_export_custom = QPushButton("Export")
self.btn_export_custom.clicked.connect(self.export_custom_symbols)
self.btn_export_custom.setVisible(False)
self.btn_import_custom = QPushButton("Import")
self.btn_import_custom.clicked.connect(self.import_custom_symbols)
self.btn_import_custom.setVisible(False)
self.management_layout.addWidget(self.btn_add_symbol)
self.management_layout.addWidget(self.btn_delete_custom)
self.management_layout.addStretch()
self.management_layout.addWidget(self.btn_export_custom)
self.management_layout.addWidget(self.btn_import_custom)
layout.addLayout(self.management_layout)
# Scrollable grid area
self.scroll_area = QScrollArea()
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setFrameShape(QFrame.NoFrame)
self.category_widget = QWidget()
self.category_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.category_layout = QGridLayout(self.category_widget)
self.category_layout.setSpacing(10)
self.category_layout.setAlignment(Qt.AlignCenter)
self.scroll_area.setWidget(self.category_widget)
layout.addWidget(self.scroll_area)
# Selected description label
self.selected_label = QLabel("")
self.selected_label.setAlignment(Qt.AlignCenter)
if self._is_dark():
self.selected_label.setStyleSheet("""
QLabel {
background-color: #3a3a3a;
border: 1px solid #555;
border-radius: 4px;
padding: 6px;
font-size: 12px;
color: #cccccc;
margin-top: 5px;
margin-bottom: 5px;
}
""")
else:
self.selected_label.setStyleSheet("""
QLabel {
background-color: #f0f0f0;
border: 1px solid #ccc;
border-radius: 4px;
padding: 6px;
font-size: 12px;
color: #333;
margin-top: 5px;
margin-bottom: 5px;
}
""")
layout.addWidget(self.selected_label)
# OK / Cancel buttons
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.button_box = button_box
self._update_ok_button_state()
# Shortcuts for Tab / Shift+Tab to switch categories
self.tab_shortcut = QShortcut(QKeySequence(Qt.Key_Tab), self)
self.tab_shortcut.activated.connect(self.next_category)
self.shift_tab_shortcut = QShortcut(QKeySequence(Qt.Key_Backtab), self)
self.shift_tab_shortcut.activated.connect(self.prev_category)
self.tab_shortcut.setContext(Qt.WidgetWithChildrenShortcut)
self.shift_tab_shortcut.setContext(Qt.WidgetWithChildrenShortcut)
self.update_category_display()
if self.initial_category is not None:
self.switch_category(self.initial_category)
self.setFocusPolicy(Qt.StrongFocus)
self.setFocus()
def next_category(self):
new_index = (self.current_category_index + 1) % len(self.categories)
self.switch_category(new_index)
def prev_category(self):
new_index = (self.current_category_index - 1) % len(self.categories)
self.switch_category(new_index)
def switch_category(self, index):
if 0 <= index < len(self.categories):
for i, btn in enumerate(self.category_buttons):
btn.setChecked(i == index)
self.current_category_index = index
self.selected_option = 0
self.categories[index].selected_index = 0
self.update_category_display()
self.setFocus()
# Show/hide custom management buttons
is_custom = (index == len(self.categories) - 1)