-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock.py
More file actions
1034 lines (890 loc) · 42.1 KB
/
Copy pathblock.py
File metadata and controls
1034 lines (890 loc) · 42.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
"""Reusable editor widgets for RapNote blocks."""
from __future__ import annotations
from typing import List, Optional
from PyQt6.QtCore import QEvent, QSize, QSignalBlocker, Qt, pyqtSignal
from PyQt6.QtGui import QColor, QFont, QFontMetrics, QIcon, QKeyEvent, QTextCharFormat, QTextCursor
from PyQt6.QtWidgets import (
QComboBox,
QDialog,
QHBoxLayout,
QLabel,
QMessageBox,
QPlainTextEdit,
QSizePolicy,
QSpacerItem,
QTextEdit,
QToolButton,
QVBoxLayout,
QWidget,
)
from constants import (
BLOCK_META_GAP,
BLOCK_NUMBER_GAP,
INSTRUMENTAL_TEXT_KEYS,
LINE_NUMBER_WIDTH,
LINE_WIDTH,
META_WIDTH,
SECTION_TEXT_KEYS,
)
from i18n import I18N
from logic import classify_value
from model import INSTRUMENTAL_SECTIONS, SECTION_CHOICES, Block, Project
from block_controller import BlockController
from combo_popup import SquarePopupComboBox
from instructions import InstructionDialog
from block_events import AnalysisResultEvent, RhymeSyllableResult
from readmode import configure_plain_text_edit, display_text_for_mode
from rhyme import rhyme_marks_for_block
from styles import C_SEPARATOR, color_for_level
from syllables import count_syllables
__all__ = ["SyllableEdit", "BlockWidget", "clear_layout"]
class SyllableEdit(QPlainTextEdit):
"""Plain text editor with navigation helpers and separator highlighting."""
returnPressed = pyqtSignal()
movedUpFromTop = pyqtSignal()
movedDownFromBottom = pyqtSignal()
textEdited = pyqtSignal(str)
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.setFont(QFont("Segoe UI", 11))
self.setFixedWidth(LINE_WIDTH)
self.setFixedHeight(34)
self.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.setTabChangesFocus(True)
self.document().setDocumentMargin(2)
self._reading_mode: bool = False
self._model_text: str = ""
self._updating: bool = False
self.textChanged.connect(self._on_text_changed)
def model_text(self) -> str:
return self._model_text
def set_model_text(self, text: str) -> None:
normalized = text or ""
if self._model_text == normalized:
return
self._model_text = normalized
self._sync_display()
def set_reading_mode(self, on: bool) -> None:
self._reading_mode = bool(on)
configure_plain_text_edit(self, reading_mode=self._reading_mode)
self._sync_display()
def ensure_cursor_at_end(self) -> None:
cursor = self.textCursor()
cursor.movePosition(QTextCursor.MoveOperation.End)
self.setTextCursor(cursor)
def keyPressEvent(self, event: QKeyEvent) -> None:
key = event.key()
modifiers = event.modifiers()
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
if modifiers in (Qt.KeyboardModifier.NoModifier, Qt.KeyboardModifier.KeypadModifier):
self.returnPressed.emit()
return
if key == Qt.Key.Key_Up and modifiers == Qt.KeyboardModifier.NoModifier:
if self.textCursor().position() == 0:
self.movedUpFromTop.emit()
return
if key == Qt.Key.Key_Down and modifiers == Qt.KeyboardModifier.NoModifier:
if self.textCursor().position() == len(self.toPlainText()):
self.movedDownFromBottom.emit()
return
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
return
super().keyPressEvent(event)
def focusOutEvent(self, event) -> None:
# Обновляем подсветку при потере фокуса
super().focusOutEvent(event)
self._apply_highlight()
def focusInEvent(self, event) -> None:
# При получении фокуса можно сбросить extraSelections, чтобы не мешать пользователю
super().focusInEvent(event)
self.setExtraSelections([])
def _sync_display(self) -> None:
display_text = display_text_for_mode(self._model_text, reading_mode=self._reading_mode)
current_text = self.toPlainText()
if self._reading_mode or current_text != display_text:
cursor = self.textCursor()
saved_position = cursor.position()
saved_anchor = cursor.anchor()
saved_has_selection = cursor.hasSelection()
with QSignalBlocker(self):
# Always use cursor operations to preserve the undo stack.
# setPlainText() clears the undo history.
if current_text != display_text:
cursor.beginEditBlock()
cursor.select(QTextCursor.SelectionType.Document)
cursor.removeSelectedText()
cursor.insertText(display_text)
cursor.endEditBlock()
cursor = self.textCursor()
max_pos = len(display_text)
saved_position = max(0, min(saved_position, max_pos))
saved_anchor = max(0, min(saved_anchor, max_pos))
# Restore selection correctly!
if saved_has_selection:
# Set anchor first, then set position with KeepAnchor!
cursor.setPosition(saved_anchor, QTextCursor.MoveMode.MoveAnchor)
cursor.setPosition(saved_position, QTextCursor.MoveMode.KeepAnchor)
else:
cursor.setPosition(saved_position, QTextCursor.MoveMode.MoveAnchor)
self.setTextCursor(cursor)
if self._reading_mode:
self.setExtraSelections([])
else:
self._apply_highlight()
if not self.hasFocus():
self.ensure_cursor_at_end()
def _on_text_changed(self) -> None:
if self._reading_mode or self._updating:
return
self._updating = True
try:
text = self.toPlainText()
if "\n" in text:
cursor = self.textCursor()
cursor_pos = cursor.position()
sanitized = text.replace("\n", " ")
with QSignalBlocker(self):
cursor.beginEditBlock()
cursor.select(QTextCursor.SelectionType.Document)
cursor.removeSelectedText()
cursor.insertText(sanitized)
cursor.endEditBlock()
cursor = self.textCursor()
cursor.setPosition(min(cursor_pos, len(sanitized)))
self.setTextCursor(cursor)
text = sanitized
if text == self._model_text:
self._apply_highlight()
return
self._model_text = text
self._apply_highlight()
self.textEdited.emit(self._model_text)
finally:
self._updating = False
def _apply_highlight(self) -> None:
# Если виджет в фокусе, не обновляем extraSelections, чтобы не сбрасывать пользовательское выделение
if self.hasFocus():
return
if self._reading_mode:
self.setExtraSelections([])
return
text = self.toPlainText()
selections: List[QTextEdit.ExtraSelection] = []
if not text:
self.setExtraSelections(selections)
return
fmt = QTextCharFormat()
fmt.setForeground(QColor(C_SEPARATOR))
highlight_bg = QColor(C_SEPARATOR)
highlight_bg.setAlpha(60)
fmt.setBackground(highlight_bg)
for idx, ch in enumerate(text):
if ch != "|":
continue
cursor = QTextCursor(self.document())
cursor.setPosition(idx)
cursor.setPosition(idx + 1, QTextCursor.MoveMode.KeepAnchor)
selection = QTextEdit.ExtraSelection()
selection.cursor = cursor
selection.format = fmt
selections.append(selection)
self.setExtraSelections(selections)
class BlockWidget(QWidget):
requestInsertLyricsAfter = pyqtSignal(str, int)
requestInsertInstrumentalAfter = pyqtSignal(str)
requestDelete = pyqtSignal(str)
requestMoveUp = pyqtSignal(str)
requestMoveDown = pyqtSignal(str)
instructionChanged = pyqtSignal(str)
activeChanged = pyqtSignal(str)
requestEnterNext = pyqtSignal(str, int)
sectionChanged = pyqtSignal(str, object)
contentChanged = pyqtSignal(str)
requestMoveFocusUp = pyqtSignal(str, int)
requestMoveFocusDown = pyqtSignal(str, int)
def __init__(
self,
block: Block,
index: int,
i18n: I18N,
project: Project,
controller: BlockController,
parent: Optional[QWidget] = None,
) -> None:
super().__init__(parent)
self.block: Block = block
self.index: int = index
self.i18n: I18N = i18n
self.project: Project = project
self.controller: BlockController = controller
self._is_instrumental: bool = self.block.kind == "instrumental"
self._target: int = 16
self._tol: int = 0
self._reading_mode: bool = False
self._base_meta_width: int = self._compute_meta_sample_width()
self._max_meta_width: int = self._base_meta_width
self._line_number_width: int = LINE_NUMBER_WIDTH
self._number_gap: int = BLOCK_NUMBER_GAP
self._meta_gap: int = BLOCK_META_GAP
self.root_layout = QVBoxLayout(self)
self.root_layout.setContentsMargins(0, 0, 0, 0)
self.root_layout.setSpacing(10)
# Контейнер для режима редактирования
self.edit_container = QWidget(self)
self._build_edit_ui(self.edit_container)
# Контейнер для режима чтения
self.reading_container = QWidget(self)
self.reading_layout = QVBoxLayout(self.reading_container)
self.reading_layout.setContentsMargins(0, 0, 0, 0)
self.reading_layout.setSpacing(8) # Комфортный отступ между заголовком и текстом
self.section_title_label = QLabel("", self.reading_container)
self.section_title_label.setContentsMargins(0, 0, 0, 4)
self.reading_layout.addWidget(self.section_title_label)
self.reading_text = QLabel("", self.reading_container)
self.reading_text.setWordWrap(True)
self.reading_text.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
# Ограничим ширину текста для комфортного чтения (60-80 символов)
self.reading_text.setMaximumWidth(650)
self.reading_layout.addWidget(self.reading_text)
self.root_layout.addWidget(self.edit_container)
self.root_layout.addWidget(self.reading_container)
self.reading_container.setVisible(False)
self._sync_section_combo()
self.set_index(index)
self.recompute_all()
self._refresh_instruction_display()
self._apply_reading_mode(False)
def _build_edit_ui(self, container: QWidget) -> None:
layout = QVBoxLayout(container)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0) # Убираем автоматические отступы, чтобы контролировать все вручную
title_layout = QHBoxLayout()
title_layout.setContentsMargins(0, 0, 0, 0)
title_layout.setSpacing(6)
self.hdr_label: QLabel = QLabel("", self)
self.hdr_label.setObjectName("SmallMuted")
self.section_caption: QLabel = QLabel("", self)
self.section_caption.setObjectName("SmallMuted")
title_layout.addWidget(self.hdr_label)
title_layout.addWidget(self.section_caption)
title_layout.addStretch(1)
layout.addLayout(title_layout)
layout.addSpacing(10) # Отступ между заголовком и панелью инструментов
self.Hdr = QHBoxLayout()
self.Hdr.setContentsMargins(0, 0, 0, 0)
self.Hdr.setSpacing(10)
self.section_combo: QComboBox = SquarePopupComboBox(self)
self.section_combo.setToolTip(self.i18n.t("SELECT_SECTION_TIP"))
self.section_combo.currentIndexChanged.connect(self._on_section_combo)
self.btn_instructions: QToolButton = QToolButton(self)
self.btn_instructions.setObjectName("BlockIconButton")
self.btn_instructions.setIcon(QIcon("img/tune.svg"))
self.btn_instructions.setIconSize(QSize(24, 24))
self.btn_instructions.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_instructions.setToolTip(self.i18n.t("INSTRUCTIONS_BTN_TIP"))
self.btn_instructions.clicked.connect(self._on_instructions)
self.section_label: QLabel = QLabel("", self)
self.section_label.setObjectName("SmallMuted")
self.btn_add: QToolButton = QToolButton(self)
self.btn_add.setObjectName("BlockAddButton")
self.btn_add.setText(self.i18n.t("ADD_BLOCK"))
self.btn_add.setToolTip(self.i18n.t("ADD_BLOCK_TIP"))
self.btn_add.clicked.connect(lambda: self.requestInsertLyricsAfter.emit(self.block.id, 4))
self.btn_add_block_2: QToolButton = QToolButton(self)
self.btn_add_block_2.setObjectName("BlockAddButton")
self.btn_add_block_2.setText(self.i18n.t("ADD_BLOCK_2"))
self.btn_add_block_2.setToolTip(self.i18n.t("ADD_BLOCK_2_TIP"))
self.btn_add_block_2.clicked.connect(lambda: self.requestInsertLyricsAfter.emit(self.block.id, 2))
self.btn_add_block_8: QToolButton = QToolButton(self)
self.btn_add_block_8.setObjectName("BlockAddButton")
self.btn_add_block_8.setText(self.i18n.t("ADD_BLOCK_8"))
self.btn_add_block_8.setToolTip(self.i18n.t("ADD_BLOCK_8_TIP"))
self.btn_add_block_8.clicked.connect(lambda: self.requestInsertLyricsAfter.emit(self.block.id, 8))
self.btn_add_block_12: QToolButton = QToolButton(self)
self.btn_add_block_12.setObjectName("BlockAddButton")
self.btn_add_block_12.setText(self.i18n.t("ADD_BLOCK_12"))
self.btn_add_block_12.setToolTip(self.i18n.t("ADD_BLOCK_12_TIP"))
self.btn_add_block_12.clicked.connect(lambda: self.requestInsertLyricsAfter.emit(self.block.id, 12))
self.btn_add_block_16: QToolButton = QToolButton(self)
self.btn_add_block_16.setObjectName("BlockAddButton")
self.btn_add_block_16.setText(self.i18n.t("ADD_BLOCK_16"))
self.btn_add_block_16.setToolTip(self.i18n.t("ADD_BLOCK_16_TIP"))
self.btn_add_block_16.clicked.connect(lambda: self.requestInsertLyricsAfter.emit(self.block.id, 16))
self.btn_add_instr: QToolButton = QToolButton(self)
self.btn_add_instr.setObjectName("BlockAddButton")
self.btn_add_instr.setText(self.i18n.t("ADD_INSTR_BLOCK"))
self.btn_add_instr.setToolTip(self.i18n.t("ADD_INSTR_BLOCK_TIP"))
self.btn_add_instr.clicked.connect(lambda: self.requestInsertInstrumentalAfter.emit(self.block.id))
self.btn_add_line: QToolButton = QToolButton(self)
self.btn_add_line.setObjectName("BlockAddButton")
self.btn_add_line.setText(self.i18n.t("ADD_LINE"))
self.btn_add_line.setToolTip(self.i18n.t("ADD_LINE_TIP"))
self.btn_add_line.clicked.connect(self._on_add_line)
self.btn_add_line.setVisible(not self._is_instrumental)
self.btn_remove_line: QToolButton = QToolButton(self)
self.btn_remove_line.setObjectName("BlockAddButton")
self.btn_remove_line.setText(self.i18n.t("REMOVE_LINE"))
self.btn_remove_line.setToolTip(self.i18n.t("REMOVE_LINE_TIP"))
self.btn_remove_line.clicked.connect(self._on_remove_line)
self.btn_remove_line.setVisible(not self._is_instrumental)
self.btn_up: QToolButton = QToolButton(self)
self.btn_up.setObjectName("BlockIconButton")
self.btn_up.setIcon(QIcon("img/up.svg"))
self.btn_up.setIconSize(QSize(24, 24))
self.btn_up.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_up.setToolTip(self.i18n.t("MOVE_UP_TIP"))
self.btn_up.setAutoRepeat(True)
self.btn_up.setAutoRepeatDelay(250)
self.btn_up.setAutoRepeatInterval(120)
self.btn_up.clicked.connect(lambda: self.requestMoveUp.emit(self.block.id))
self.btn_dn: QToolButton = QToolButton(self)
self.btn_dn.setObjectName("BlockIconButton")
self.btn_dn.setIcon(QIcon("img/down.svg"))
self.btn_dn.setIconSize(QSize(24, 24))
self.btn_dn.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_dn.setToolTip(self.i18n.t("MOVE_DOWN_TIP"))
self.btn_dn.setAutoRepeat(True)
self.btn_dn.setAutoRepeatDelay(250)
self.btn_dn.setAutoRepeatInterval(120)
self.btn_dn.clicked.connect(lambda: self.requestMoveDown.emit(self.block.id))
self.btn_del: QToolButton = QToolButton(self)
self.btn_del.setObjectName("BlockIconButton")
self.btn_del.setIcon(QIcon("img/delete.svg"))
self.btn_del.setIconSize(QSize(24, 24))
self.btn_del.setCursor(Qt.CursorShape.PointingHandCursor)
self.btn_del.setToolTip(self.i18n.t("DELETE_BLOCK_TIP"))
self.btn_del.clicked.connect(lambda: self.requestDelete.emit(self.block.id))
self.Hdr.addWidget(self.section_combo)
self.Hdr.addWidget(self.btn_instructions)
if not self._is_instrumental:
self.Hdr.addWidget(self.btn_add_line)
self.Hdr.addWidget(self.btn_remove_line)
self.Hdr.addStretch(1)
self.Hdr.addWidget(self.btn_up)
self.Hdr.addWidget(self.btn_dn)
self.Hdr.addWidget(self.btn_del)
self.toolbar_spacer: QSpacerItem = QSpacerItem(
self._meta_gap + self._max_meta_width,
0,
QSizePolicy.Policy.Fixed,
QSizePolicy.Policy.Minimum,
)
self.Hdr.addItem(self.toolbar_spacer)
layout.addLayout(self.Hdr)
layout.addSpacing(12) # Одинаковый отступ над первой строкой
self.line_edits: List[SyllableEdit] = []
self.meta_labels: List[QLabel] = []
self.num_labels: List[QLabel] = []
self.lines_layout: QVBoxLayout = QVBoxLayout()
self.lines_layout.setContentsMargins(0, 0, 0, 0)
self.lines_layout.setSpacing(8)
self._line_rows: List[QHBoxLayout] = []
self.instrument_instruction_label: Optional[QLabel] = None
if self._is_instrumental:
self.instrument_instruction_label = QLabel("", self)
self.instrument_instruction_label.setObjectName("SmallMuted")
self.instrument_instruction_label.setWordWrap(True)
self.instrument_instruction_label.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
self.lines_layout.addWidget(self.instrument_instruction_label)
else:
for idx, text in enumerate(self.block.lines):
self._add_line_row(idx, text)
layout.addLayout(self.lines_layout)
layout.addSpacing(12) # Одинаковый отступ под последней строкой
self.action_bar = QHBoxLayout()
self.action_bar.setContentsMargins(0, 0, 0, 0)
self.action_bar.setSpacing(10)
self.action_bar.addWidget(self.btn_add)
self.action_bar.addWidget(self.btn_add_block_8)
self.action_bar.addWidget(self.btn_add_block_12)
self.action_bar.addWidget(self.btn_add_block_16)
self.action_bar.addWidget(self.btn_add_block_2)
self.action_bar.addWidget(self.btn_add_instr)
self.action_bar.addStretch(1)
layout.addLayout(self.action_bar)
def customEvent(self, event: QEvent) -> None:
"""Handle custom events, like analysis results."""
if event.type() == AnalysisResultEvent.EVENT_TYPE and isinstance(event, AnalysisResultEvent):
if event.block_id == self.block.id:
self._apply_analysis_result(event.result)
super().customEvent(event)
def eventFilter(self, obj, event):
if obj in self.line_edits and event.type() == event.Type.FocusIn:
self.activeChanged.emit(self.block.id)
return super().eventFilter(obj, event)
def set_index(self, idx: int) -> None:
self.index = idx
self._update_header()
def _sync_section_combo(self) -> None:
if self._is_instrumental:
key = self.block.instrumental_type or INSTRUMENTAL_SECTIONS[0]
if key not in INSTRUMENTAL_SECTIONS:
key = INSTRUMENTAL_SECTIONS[0]
index = INSTRUMENTAL_SECTIONS.index(key)
else:
sec = self.block.section or "None"
if sec not in SECTION_CHOICES:
sec = "None"
index = SECTION_CHOICES.index(sec)
self.section_combo.blockSignals(True)
self._update_section_combo_items()
self.section_combo.setCurrentIndex(index)
self.section_combo.blockSignals(False)
self.set_index(self.index)
def _on_section_combo(self, _index: int) -> None:
data = self.section_combo.currentData(Qt.ItemDataRole.UserRole)
key = str(data) if data is not None else "None"
if self._is_instrumental:
if key in INSTRUMENTAL_SECTIONS and key != self.block.instrumental_type:
self.block.instrumental_type = key
self._update_header()
self.sectionChanged.emit(self.block.id, key)
# Обновляем вид режима чтения при изменении секции
if self._reading_mode:
self.update_reading_view()
else:
sec = None if key == "None" else key
if sec != self.block.section:
previous_section = self.block.section
self.block.section = sec
if previous_section != self.block.section:
if self.block.instruction_command or self.block.instruction_description:
self.block.instruction_command = ""
self.block.instruction_description = ""
self.instructionChanged.emit(self.block.id)
self._sync_section_combo()
self._update_header()
self.sectionChanged.emit(self.block.id, sec)
# Обновляем вид режима чтения при изменении секции
if self._reading_mode:
self.update_reading_view()
def _display_name_for_section(self, key: str) -> str:
return key
def _tooltip_for_section(self, key: str) -> str:
if self._is_instrumental:
_, hint_key = INSTRUMENTAL_TEXT_KEYS.get(key, (None, None))
return self.i18n.t(hint_key) if hint_key else ""
_, hint_key = SECTION_TEXT_KEYS.get(key, (None, None))
return self.i18n.t(hint_key) if hint_key else ""
def _combo_text_for_section(self, key: str) -> str:
return f"[{key}]"
def _update_section_combo_items(self) -> None:
self.section_combo.clear()
keys = INSTRUMENTAL_SECTIONS if self._is_instrumental else SECTION_CHOICES
for key in keys:
self.section_combo.addItem(self._combo_text_for_section(key))
idx = self.section_combo.count() - 1
self.section_combo.setItemData(idx, key, Qt.ItemDataRole.UserRole)
tooltip = self._tooltip_for_section(key)
if tooltip:
self.section_combo.setItemData(idx, tooltip, Qt.ItemDataRole.ToolTipRole)
def set_state(
self,
target: int,
tol: int,
reading_mode: bool,
) -> None:
self._target = int(target)
self._tol = int(tol)
self._reading_mode = bool(reading_mode)
self._apply_reading_mode(self._reading_mode)
self.recompute_all()
def update_reading_view(self) -> None:
# Обновляем текст для режима чтения
if self._is_instrumental:
# Для инструментальных блоков показываем тип секции
section_key = self.block.instrumental_type or INSTRUMENTAL_SECTIONS[0]
section_name = self._display_name_for_section(section_key)
self.section_title_label.setText(f"[{section_name}]")
self.reading_text.setText("")
else:
# Для текстовых блоков
section_key = self.block.section or "None"
if section_key != "None":
section_name = self._display_name_for_section(section_key)
# Если это Verse, добавляем номер
if section_key == "Verse":
verse_index = self.controller.get_verse_number(self.block)
self.section_title_label.setText(f"[{section_name} {verse_index}]")
else:
self.section_title_label.setText(f"[{section_name}]")
self.section_title_label.setVisible(True)
else:
self.section_title_label.setVisible(False)
# Собираем текст, убирая разделители |
lines = []
for line in self.block.lines:
clean_line = line.replace("|", "").strip()
if clean_line:
lines.append(clean_line)
self.reading_text.setText("\n".join(lines))
def _apply_reading_mode(self, on: bool) -> None:
self._reading_mode = on
self.edit_container.setVisible(not on)
self.reading_container.setVisible(on)
if on:
self.update_reading_view()
self.root_layout.setSpacing(20) # Комфортный отступ между блоками
self.reading_container.setContentsMargins(0, 0, 0, 12) # Keep first block aligned with edit mode
# Идеальная типографика для чтения с экрана
self.section_title_label.setStyleSheet("""
font-family: 'Segoe UI', Roboto, Inter, sans-serif;
font-weight: 600;
font-size: 16px;
color: #A0A0A0;
letter-spacing: 0.3px;
""")
self.reading_text.setStyleSheet("""
font-family: 'Segoe UI', Roboto, Inter, sans-serif;
font-size: 17px;
color: #FFFFFF;
line-height: 1.55;
letter-spacing: 0.2px;
""")
else:
# В режиме редактирования восстанавливаем старые настройки
self.section_combo.setVisible(not on)
self.btn_instructions.setVisible(not on)
self.section_label.setVisible(not on)
self.hdr_label.setVisible(not on)
self.btn_add.setVisible(not on)
self.btn_add_instr.setVisible(not on)
self.btn_add_block_2.setVisible(not on)
self.btn_add_block_8.setVisible(not on)
self.btn_add_block_12.setVisible(not on)
self.btn_add_block_16.setVisible(not on)
if self._is_instrumental:
self.btn_add_line.setVisible(False)
self.btn_remove_line.setVisible(False)
else:
self.btn_add_line.setVisible(not on)
self.btn_remove_line.setVisible(not on)
self.btn_up.setVisible(not on)
self.btn_dn.setVisible(not on)
self.btn_del.setVisible(not on)
for ln in self.num_labels:
ln.setVisible(not on)
for edit in self.line_edits:
edit.set_reading_mode(on)
for meta in self.meta_labels:
meta.setVisible(not on)
self.root_layout.setSpacing(10)
def _current_target(self) -> int:
return self._target
def _on_text_changed(self) -> None:
self.block.lines = [edit.model_text() for edit in self.line_edits]
if self._is_instrumental and self.block.lines:
self.block.lines = [self.block.lines[0]]
self.contentChanged.emit(self.block.id)
self.recompute_all()
# Обновляем вид режима чтения при изменении текста
if self._reading_mode:
self.update_reading_view()
def focus_line(self, line_index: int, cursor_end: bool = True) -> None:
if not self.line_edits:
return
line_index = max(0, min(len(self.line_edits) - 1, line_index))
edit = self.line_edits[line_index]
edit.setFocus()
if cursor_end:
edit.ensure_cursor_at_end()
else:
cursor = edit.textCursor()
cursor.setPosition(0)
edit.setTextCursor(cursor)
def recompute_all(self) -> None:
if self._reading_mode or self._is_instrumental:
# Clear meta labels if they are not applicable
for label in self.meta_labels:
label.setText("")
return
self.controller.request_analysis(self.block, self)
def _apply_analysis_result(self, result: RhymeSyllableResult) -> None:
"""Update UI with the analysis result."""
if self._reading_mode or self._is_instrumental:
return
target = self._current_target()
tol = max(0, self._tol)
syllable_counts = result.syllable_counts
rhyme_marks = result.rhyme_marks
for i, line in enumerate(self.block.lines):
if i >= len(self.meta_labels):
continue
syl = syllable_counts[i] if i < len(syllable_counts) else 0
syl_level = classify_value(syl, target, tol)
syl_color = color_for_level(syl_level)
mark = rhyme_marks[i] if i < len(rhyme_marks) else None
rk = mark.kind if mark else "bad"
r_color = color_for_level(rk)
r_dot = "●"
parts: List[str] = []
parts.append(f"{self.i18n.t('SYLLABLES')}: <span style='color:{syl_color};'><b>{syl:02d}</b></span>")
parts.append(f"{self.i18n.t('RHYMES')}: <span style='color:{r_color};'><b>{r_dot}</b></span>")
self.meta_labels[i].setText((" " * 4).join(parts))
self.meta_labels[i].setTextFormat(Qt.TextFormat.RichText)
self.meta_labels[i].adjustSize()
hint_width = self.meta_labels[i].sizeHint().width()
if hint_width > self._max_meta_width:
self._max_meta_width = hint_width
self._update_minimum_width(self._max_meta_width)
def _add_line_row(self, index: int, text: str) -> None:
row = QHBoxLayout()
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(0)
ln = QLabel(str(index + 1), self)
ln.setFixedWidth(self._line_number_width)
ln.setObjectName("LineNumber")
self.num_labels.insert(index, ln)
edit = SyllableEdit(self)
edit.set_model_text(text)
edit.textEdited.connect(lambda _t: self._on_text_changed())
edit.installEventFilter(self)
meta = QLabel("", self)
meta.setObjectName("SmallMuted")
meta.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
meta.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
meta.setFixedWidth(self._max_meta_width)
row.addWidget(ln)
row.addSpacing(self._number_gap)
row.addWidget(edit)
row.addSpacing(self._meta_gap)
row.addWidget(meta)
self.line_edits.insert(index, edit)
self.meta_labels.insert(index, meta)
self._line_rows.insert(index, row)
self.lines_layout.insertLayout(index, row)
self._refresh_navigation_handlers()
meta.adjustSize()
hint_width = meta.sizeHint().width()
self._apply_meta_width(hint_width)
def _update_minimum_width(self, meta_width: int) -> None:
spacing = max(self._number_gap, 2)
normalized_meta = max(self._base_meta_width, meta_width)
total_width = self._line_number_width + spacing + LINE_WIDTH + self._meta_gap + normalized_meta
self.setFixedWidth(total_width)
container = self.parent()
if container is not None and hasattr(container, "setMinimumWidth"):
try:
container.setFixedWidth(total_width)
except Exception: # noqa: BLE001
container.setMinimumWidth(total_width)
def _apply_meta_width(self, width: int) -> None:
normalized = max(self._base_meta_width, width)
self._max_meta_width = normalized
for label in self.meta_labels:
label.setFixedWidth(normalized)
self.toolbar_spacer.changeSize(
self._meta_gap + self._max_meta_width,
0,
QSizePolicy.Policy.Fixed,
QSizePolicy.Policy.Minimum,
)
if self.Hdr is not None:
self.Hdr.invalidate()
self._update_minimum_width(self._max_meta_width)
def _compute_meta_sample_width(self) -> int:
sample = f"{self.i18n.t('SYLLABLES')}: 00 {self.i18n.t('RHYMES')}: ●"
metrics = QFontMetrics(self.font())
return metrics.horizontalAdvance(sample) + 12
def _on_remove_line(self) -> None:
if self._is_instrumental or len(self.line_edits) <= 1:
return
answer = QMessageBox.question(
self,
self.i18n.t("DELETE_LINE_TITLE"),
self.i18n.t("DELETE_LINE_Q"),
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
if answer != QMessageBox.StandardButton.Yes:
return
remove_index = len(self.line_edits) - 1
self.block.lines.pop()
layout_item = self.lines_layout.takeAt(remove_index)
row_layout = layout_item.layout() if layout_item is not None else None
stored_layout = self._line_rows.pop() if self._line_rows else None
target_layout = row_layout or stored_layout
if target_layout is not None:
while target_layout.count():
item = target_layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
inner_layout = item.layout()
if inner_layout is not None:
inner_layout.deleteLater()
target_layout.setParent(None)
edit = self.line_edits.pop()
edit.deleteLater()
meta_label = self.meta_labels.pop()
meta_label.deleteLater()
num_label = self.num_labels.pop()
num_label.deleteLater()
self._reindex_rows()
self._on_text_changed()
self.focus_line(remove_index - 1 if remove_index > 0 else 0)
def _on_add_line(self) -> None:
if self._is_instrumental:
return
insert_index = len(self.line_edits)
self.block.lines.append("")
self._add_line_row(insert_index, "")
self._reindex_rows()
self._on_text_changed()
self.focus_line(insert_index)
def _reindex_rows(self) -> None:
for idx, label in enumerate(self.num_labels):
label.setText(str(idx + 1))
def _refresh_navigation_handlers(self) -> None:
for idx, edit in enumerate(self.line_edits):
try:
edit.returnPressed.disconnect()
except TypeError:
pass
try:
edit.movedUpFromTop.disconnect()
except TypeError:
pass
try:
edit.movedDownFromBottom.disconnect()
except TypeError:
pass
edit.returnPressed.connect(lambda idx=idx: self.requestEnterNext.emit(self.block.id, idx))
edit.movedUpFromTop.connect(lambda idx=idx: self.requestMoveFocusUp.emit(self.block.id, idx))
edit.movedDownFromBottom.connect(lambda idx=idx: self.requestMoveFocusDown.emit(self.block.id, idx))
def _update_header(self) -> None:
base_title = f"{self.i18n.t('BLOCK')} {self.index + 1}"
instruction_display = self._instruction_label()
if self._is_instrumental:
key = self.block.instrumental_type or INSTRUMENTAL_SECTIONS[0]
if key not in INSTRUMENTAL_SECTIONS:
key = INSTRUMENTAL_SECTIONS[0]
section_display = self._display_name_for_section(key)
verse_index: Optional[int] = None
else:
section_key = self.block.section or "None"
if section_key not in SECTION_CHOICES:
section_key = "None"
if section_key != "None" and section_key == "Verse":
verse_index = self.controller.get_verse_number(self.block)
section_display = f"Verse {verse_index}"
else:
verse_index = None
section_display = (
self._display_name_for_section(section_key)
if section_key != "None"
else self.i18n.t("SECTION_NONE")
)
pieces: List[str] = []
if section_display:
pieces.append(section_display)
if instruction_display:
pieces.append(instruction_display)
caption = f"[{': '.join(pieces)}]" if pieces else ""
self.hdr_label.setText(base_title)
self.section_caption.setText(caption)
self.section_label.setText("")
def retranslate(self) -> None:
self.section_combo.setToolTip(self.i18n.t("SELECT_SECTION_TIP"))
self.btn_instructions.setToolTip(self.i18n.t("INSTRUCTIONS_BTN_TIP"))
self.btn_add.setText(self.i18n.t("ADD_BLOCK"))
self.btn_add.setToolTip(self.i18n.t("ADD_BLOCK_TIP"))
self.btn_add_block_2.setText(self.i18n.t("ADD_BLOCK_2"))
self.btn_add_block_2.setToolTip(self.i18n.t("ADD_BLOCK_2_TIP"))
self.btn_add_block_8.setText(self.i18n.t("ADD_BLOCK_8"))
self.btn_add_block_8.setToolTip(self.i18n.t("ADD_BLOCK_8_TIP"))
self.btn_add_block_12.setText(self.i18n.t("ADD_BLOCK_12"))
self.btn_add_block_12.setToolTip(self.i18n.t("ADD_BLOCK_12_TIP"))
self.btn_add_block_16.setText(self.i18n.t("ADD_BLOCK_16"))
self.btn_add_block_16.setToolTip(self.i18n.t("ADD_BLOCK_16_TIP"))
self.btn_add_instr.setText(self.i18n.t("ADD_INSTR_BLOCK"))
self.btn_add_instr.setToolTip(self.i18n.t("ADD_INSTR_BLOCK_TIP"))
self.btn_add_line.setText(self.i18n.t("ADD_LINE"))
self.btn_add_line.setToolTip(self.i18n.t("ADD_LINE_TIP"))
self.btn_remove_line.setText(self.i18n.t("REMOVE_LINE"))
self.btn_remove_line.setToolTip(self.i18n.t("REMOVE_LINE_TIP"))
self.btn_up.setToolTip(self.i18n.t("MOVE_UP_TIP"))
self.btn_dn.setToolTip(self.i18n.t("MOVE_DOWN_TIP"))
self.btn_del.setToolTip(self.i18n.t("DELETE_BLOCK_TIP"))
self._update_header()
self._refresh_instruction_display()
self.recompute_all()
def _instruction_label(self) -> str:
command = (self.block.instruction_command or "").strip()
description = (self.block.instruction_description or "").strip()
if command and description:
return f"{command} — {description}"
if command:
return command
return description
def _refresh_instruction_display(self) -> None:
if not self._is_instrumental or self.instrument_instruction_label is None:
return
text = self._instruction_label()
if text:
self.instrument_instruction_label.setText(text)
else:
self.instrument_instruction_label.setText(self.i18n.t("INSTRUMENTAL_NO_INSTRUCTION"))
def _on_instructions(self) -> None:
if self._is_instrumental:
section_key = self.block.instrumental_type or INSTRUMENTAL_SECTIONS[0]
else:
section_key = self.block.section or "None"
section_label = self._display_name_for_section(section_key)
dialog = InstructionDialog(
section_label=section_label,
section_key=section_key,
initial_command=self.block.instruction_command,
initial_description=self.block.instruction_description,
i18n=self.i18n,
parent=self,
)
result = dialog.exec()
if result != QDialog.DialogCode.Accepted:
return
changed = False
if dialog.clear_requested:
if self.block.instruction_command or self.block.instruction_description:
changed = True
self.block.instruction_command = ""
self.block.instruction_description = ""
else:
new_command = dialog.command_value
new_description = dialog.description_value
if (
new_command != self.block.instruction_command