-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbottompanel.py
More file actions
222 lines (176 loc) · 7.56 KB
/
Copy pathbottompanel.py
File metadata and controls
222 lines (176 loc) · 7.56 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
"""Bottom panel containing rhyme search controls."""
from __future__ import annotations
import logging
from typing import Iterable, Optional, TYPE_CHECKING
from PyQt6.QtCore import QModelIndex, Qt, pyqtSignal, QTimer
from PyQt6.QtGui import QColor, QStandardItem, QStandardItemModel
from PyQt6.QtWidgets import (
QApplication,
QButtonGroup,
QCompleter,
QFrame,
QHBoxLayout,
QLabel,
QLineEdit,
QMessageBox,
QRadioButton,
QSizePolicy,
QWidget,
QVBoxLayout,
)
from constants import CENTER_MAX_WIDTH
from rhyme_backend import RhymeEngine
from styles import TOP_PANEL_SEPARATOR_STYLESHEET, build_top_panel_styles, color_for_level
if TYPE_CHECKING:
from i18n import I18N
LOGGER = logging.getLogger(__name__)
class BottomPanel(QFrame):
"""Panel providing automatic rhyme search."""
rhymeSelected = pyqtSignal(str)
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.setObjectName("BottomPanel")
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self._i18n: Optional["I18N"] = None
self.search_timer = QTimer(self)
self.search_timer.setSingleShot(True)
self.search_timer.setInterval(300)
self.search_timer.timeout.connect(self._perform_search)
root_layout = QVBoxLayout(self)
root_layout.setContentsMargins(0, 0, 0, 0)
root_layout.setSpacing(0)
root_layout.addWidget(self._make_separator())
self._body_widget = QWidget(self)
self._body_widget.setMaximumWidth(CENTER_MAX_WIDTH)
body_layout = QHBoxLayout(self._body_widget)
body_layout.setContentsMargins(24, 10, 24, 10)
body_layout.setSpacing(10)
body_layout.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
self._label = QLabel(self)
self._label.setObjectName("TopPanelLabel")
body_layout.addWidget(self._label)
self.rb_ru = QRadioButton("Ru", self)
self.rb_ua = QRadioButton("Ua", self)
self.rb_ru.setChecked(True)
self.lang_group = QButtonGroup(self)
self.lang_group.addButton(self.rb_ru)
self.lang_group.addButton(self.rb_ua)
body_layout.addWidget(self.rb_ru)
body_layout.addWidget(self.rb_ua)
self.search_input = QLineEdit(self)
self.search_input.setFixedWidth(300)
self.search_input.returnPressed.connect(self._perform_search)
self.search_input.textChanged.connect(lambda: self.search_timer.start())
body_layout.addWidget(self.search_input)
self._init_rhyme_completer()
center_container = QWidget(self)
center_layout = QHBoxLayout(center_container)
center_layout.setContentsMargins(0, 0, 0, 0)
center_layout.setSpacing(0)
center_layout.addStretch(1)
center_layout.addWidget(self._body_widget)
center_layout.addStretch(1)
root_layout.addWidget(center_container)
root_layout.addWidget(self._make_separator())
self._apply_styles()
@staticmethod
def _make_separator() -> QFrame:
separator = QFrame()
separator.setFixedHeight(1)
separator.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
separator.setStyleSheet(TOP_PANEL_SEPARATOR_STYLESHEET)
return separator
def _apply_styles(self) -> None:
self.setStyleSheet(build_top_panel_styles())
def retranslate(self, i18n: "I18N") -> None:
self._i18n = i18n
self._label.setText(i18n.t("RHYME_PICKER_LABEL"))
self._label.setToolTip(i18n.t("RHYME_PICKER_TIP"))
self.rb_ru.setToolTip(i18n.t("RHYME_LANG_RU_TIP"))
self.rb_ua.setToolTip(i18n.t("RHYME_LANG_UA_TIP"))
self.search_input.setPlaceholderText(i18n.t("RHYME_INPUT_PLACEHOLDER"))
self.search_input.setToolTip(i18n.t("RHYME_INPUT_TIP"))
def _perform_search(self) -> None:
word = self.search_input.text().strip()
if not word:
return
lang = "ru" if self.rb_ru.isChecked() else "ua"
try:
results = RhymeEngine.find_rhymes(word, lang)
except Exception: # noqa: BLE001
LOGGER.exception("Failed to load rhymes for word: %s", word)
title = self._i18n.t("RHYME_SEARCH_ERROR_TITLE") if self._i18n else self.tr("Error")
message = self._i18n.t("RHYME_SEARCH_ERROR_MESSAGE") if self._i18n else self.tr("Failed to load rhymes.")
QMessageBox.warning(
self,
title,
message,
)
return
self._populate_rhyme_results(results)
self._show_rhyme_popup()
def _init_rhyme_completer(self) -> None:
self._rhyme_model = QStandardItemModel(self)
self._rhyme_model.setColumnCount(1)
self._rhyme_completer = QCompleter(self._rhyme_model, self)
self._rhyme_completer.setCompletionMode(QCompleter.CompletionMode.UnfilteredPopupCompletion)
self._rhyme_completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self._rhyme_completer.setFilterMode(Qt.MatchFlag.MatchContains)
self._rhyme_completer.activated[QModelIndex].connect(self._on_rhyme_index_selected)
self._rhyme_completer.popup().setUniformItemSizes(True)
self.search_input.setCompleter(self._rhyme_completer)
@staticmethod
def _score_level(score: int) -> str:
if score >= 90:
return "good"
if score >= 70:
return "mid"
return "bad"
def _populate_rhyme_results(self, results: Iterable[object]) -> None:
self._rhyme_model.removeRows(0, self._rhyme_model.rowCount())
entries = list(results or [])
if not entries:
text = self._i18n.t("RHYME_NO_MATCHES") if self._i18n else self.tr("No matches")
self._append_placeholder_item(text)
return
for entry in entries:
if isinstance(entry, tuple) and entry:
text = str(entry[0])
score = entry[1] if len(entry) > 1 else None
else:
text = str(entry)
score = None
item = QStandardItem(text)
item.setEditable(False)
if score is not None:
try:
score_value = int(score)
except (TypeError, ValueError):
score_value = 0
item.setData(score_value, Qt.ItemDataRole.UserRole)
item.setData(
self.tr("Score: {value}").format(value=score_value),
Qt.ItemDataRole.ToolTipRole,
)
level = self._score_level(score_value)
item.setData(QColor(color_for_level(level)), Qt.ItemDataRole.ForegroundRole)
self._rhyme_model.appendRow(item)
def _append_placeholder_item(self, text: str) -> None:
item = QStandardItem(text)
item.setEditable(False)
item.setFlags(Qt.ItemFlag.NoItemFlags)
self._rhyme_model.appendRow(item)
def _show_rhyme_popup(self) -> None:
if self._rhyme_model.rowCount() == 0:
return
self._rhyme_completer.complete(self.search_input.rect())
def _on_rhyme_index_selected(self, index: QModelIndex) -> None:
if not index.isValid():
return
if not bool(index.flags() & Qt.ItemFlag.ItemIsEnabled):
return
text = index.data(Qt.ItemDataRole.DisplayRole)
if not isinstance(text, str):
return
QApplication.clipboard().setText(text)
self.rhymeSelected.emit(text)