| 1 |
#!/usr/bin/env python |
| 2 |
# License: GPLv3 Copyright: 2009, Kovid Goyal <[email protected]> |
| 3 |
|
| 4 |
import re |
| 5 |
import time |
| 6 |
from functools import partial |
| 7 |
from typing import TYPE_CHECKING |
| 8 |
|
| 9 |
from qt.core import QAction, QApplication, QComboBox, QCompleter, QDialog, QEvent, QIcon, QKeyEvent, QKeySequence, QLineEdit, Qt, QTimer, pyqtSignal, pyqtSlot |
| 10 |
|
| 11 |
from calibre.gui2 import QT_HIDDEN_CLEAR_ACTION, config, gprefs, question_dialog |
| 12 |
from calibre.gui2.dialogs.saved_search_editor import SavedSearchEditor |
| 13 |
from calibre.gui2.dialogs.search import SearchDialog |
| 14 |
from calibre.gui2.widgets import stylesheet_for_lineedit |
| 15 |
from calibre.utils.icu import primary_sort_key |
| 16 |
from calibre.utils.localization import _, pgettext |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from calibre.gui2.ui import Main |
| 20 |
|
| 21 |
|
| 22 |
class AsYouType(str): |
| 23 |
as_you_type: bool |
| 24 |
|
| 25 |
def __new__(cls, text): |
| 26 |
self = str.__new__(cls, text) |
| 27 |
self.as_you_type = True |
| 28 |
return self |
| 29 |
|
| 30 |
|
| 31 |
class SearchLineEdit(QLineEdit): # {{{ |
| 32 |
key_pressed = pyqtSignal(object) |
| 33 |
clear_history = pyqtSignal() |
| 34 |
select_on_mouse_press = None |
| 35 |
as_url = None |
| 36 |
|
| 37 |
def keyPressEvent(self, a0): |
| 38 |
self.key_pressed.emit(a0) |
| 39 |
QLineEdit.keyPressEvent(self, a0) |
| 40 |
|
| 41 |
def dropEvent(self, a0): |
| 42 |
p = self.parent() |
| 43 |
assert p is not None |
| 44 |
assert isinstance(p, SearchBox2) |
| 45 |
p.normalize_state() |
| 46 |
return QLineEdit.dropEvent(self, a0) |
| 47 |
|
| 48 |
def contextMenuEvent(self, a0): |
| 49 |
p = self.parent() |
| 50 |
assert p is not None |
| 51 |
assert isinstance(p, SearchBox2) |
| 52 |
p.normalize_state() |
| 53 |
menu = self.createStandardContextMenu() |
| 54 |
assert menu is not None |
| 55 |
menu.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) |
| 56 |
ac = menu.addAction(_('Paste and &search')) |
| 57 |
assert ac is not None |
| 58 |
clipboard = QApplication.clipboard() |
| 59 |
assert clipboard is not None |
| 60 |
ac.setEnabled(bool(clipboard.text())) |
| 61 |
ac.setIcon(QIcon.ic('search.png')) |
| 62 |
ac.triggered.connect(self.paste_and_search) |
| 63 |
for action in menu.actions(): |
| 64 |
if action.text().startswith(_('&Paste') + '\t'): |
| 65 |
menu.insertAction(action, ac) |
| 66 |
break |
| 67 |
else: |
| 68 |
menu.addAction(ac) |
| 69 |
menu.addSeparator() |
| 70 |
ac = menu.addAction(_('Invert current search')) |
| 71 |
assert ac is not None |
| 72 |
ac.setEnabled(bool(self.text().strip())) |
| 73 |
ac.setIcon(QIcon.ic('search.png')) |
| 74 |
ac.triggered.connect(self.invert_search) |
| 75 |
menu.addAction(ac) |
| 76 |
menu.addSeparator() |
| 77 |
if self.as_url is not None: |
| 78 |
url = self.as_url(self.text()) |
| 79 |
if url: |
| 80 |
|
| 81 |
def copy_as_url(): |
| 82 |
cb = QApplication.clipboard() |
| 83 |
assert cb is not None |
| 84 |
cb.setText(url) |
| 85 |
|
| 86 |
menu.addAction(_('Copy search as URL'), copy_as_url) |
| 87 |
clear_ac = menu.addAction(_('&Clear search history')) |
| 88 |
assert clear_ac is not None |
| 89 |
clear_ac.triggered.connect(self.clear_history) |
| 90 |
menu.exec(a0.globalPos()) |
| 91 |
|
| 92 |
def invert_search(self): |
| 93 |
q = self.text().strip() |
| 94 |
if q: |
| 95 |
if q.startswith('NOT ( ') and q.endswith(' )'): |
| 96 |
q = q[6:-2] |
| 97 |
else: |
| 98 |
q = f'NOT ( {q} )' |
| 99 |
self.setText(q) |
| 100 |
ev = QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_Enter, Qt.KeyboardModifier.NoModifier) |
| 101 |
self.keyPressEvent(ev) |
| 102 |
|
| 103 |
def paste_and_search(self): |
| 104 |
self.paste() |
| 105 |
ev = QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_Enter, Qt.KeyboardModifier.NoModifier) |
| 106 |
self.keyPressEvent(ev) |
| 107 |
|
| 108 |
@pyqtSlot() |
| 109 |
def paste(self, *args): |
| 110 |
p = self.parent() |
| 111 |
assert p is not None |
| 112 |
assert isinstance(p, SearchBox2) |
| 113 |
p.normalize_state() |
| 114 |
return QLineEdit.paste(self) |
| 115 |
|
| 116 |
def focusInEvent(self, a0): |
| 117 |
self.select_on_mouse_press = time.time() |
| 118 |
return QLineEdit.focusInEvent(self, a0) |
| 119 |
|
| 120 |
def mousePressEvent(self, a0): |
| 121 |
QLineEdit.mousePressEvent(self, a0) |
| 122 |
if self.select_on_mouse_press is not None and abs(time.time() - self.select_on_mouse_press) < 0.2: |
| 123 |
self.selectAll() |
| 124 |
self.select_on_mouse_press = None |
| 125 |
|
| 126 |
|
| 127 |
# }}} |
| 128 |
|
| 129 |
|
| 130 |
class SearchBox2(QComboBox): # {{{ |
| 131 |
""" |
| 132 |
To use this class: |
| 133 |
|
| 134 |
* Call initialize() |
| 135 |
* Connect to the search() and cleared() signals from this widget. |
| 136 |
* Connect to the changed() signal to know when the box content changes |
| 137 |
* Connect to focus_to_library() signal to be told to manually change focus |
| 138 |
* Call search_done() after every search is complete |
| 139 |
* Call set_search_string() to perform a search programmatically |
| 140 |
* You can use the current_text property to get the current search text |
| 141 |
Be aware that if you are using it in a slot connected to the |
| 142 |
changed() signal, if the connection is not queued it will not be |
| 143 |
accurate. |
| 144 |
""" |
| 145 |
|
| 146 |
INTERVAL = 1500 #: Time to wait before emitting search signal |
| 147 |
MAX_COUNT = 25 |
| 148 |
|
| 149 |
search = pyqtSignal(object) |
| 150 |
cleared = pyqtSignal() |
| 151 |
changed = pyqtSignal() |
| 152 |
focus_to_library = pyqtSignal() |
| 153 |
|
| 154 |
def __init__(self, parent=None, add_clear_action=True, as_url=None): |
| 155 |
QComboBox.__init__(self, parent) |
| 156 |
self.line_edit = SearchLineEdit(self) |
| 157 |
self.line_edit.as_url = as_url |
| 158 |
self.setLineEdit(self.line_edit) |
| 159 |
self.line_edit.clear_history.connect(self.clear_history) |
| 160 |
if add_clear_action: |
| 161 |
le = self.lineEdit() |
| 162 |
assert le is not None |
| 163 |
le.setClearButtonEnabled(True) |
| 164 |
ac = self.findChild(QAction, QT_HIDDEN_CLEAR_ACTION) |
| 165 |
if ac is not None: |
| 166 |
ac.triggered.connect(self.clear_clicked) |
| 167 |
|
| 168 |
c = self.line_edit.completer() |
| 169 |
assert c is not None |
| 170 |
c.setCompletionMode(QCompleter.CompletionMode.PopupCompletion) |
| 171 |
c.highlighted[str].connect(self.completer_used) |
| 172 |
|
| 173 |
self.line_edit.key_pressed.connect(self.key_pressed, type=Qt.ConnectionType.DirectConnection) |
| 174 |
# QueuedConnection as workaround for https://bugreports.qt-project.org/browse/QTBUG-40807 |
| 175 |
self.textActivated.connect(self.history_selected, type=Qt.ConnectionType.QueuedConnection) |
| 176 |
self.setEditable(True) |
| 177 |
self.as_you_type = True |
| 178 |
self.timer = QTimer() |
| 179 |
self.timer.setSingleShot(True) |
| 180 |
self.timer.timeout.connect(self.timer_event, type=Qt.ConnectionType.QueuedConnection) |
| 181 |
self.setInsertPolicy(QComboBox.InsertPolicy.NoInsert) |
| 182 |
self.setMaxCount(self.MAX_COUNT) |
| 183 |
self.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) |
| 184 |
self.setMinimumContentsLength(25) |
| 185 |
self._in_a_search = False |
| 186 |
self.tool_tip_text = self.toolTip() |
| 187 |
self.parse_error_action = None |
| 188 |
|
| 189 |
def add_action(self, icon, position=QLineEdit.ActionPosition.TrailingPosition): |
| 190 |
if not isinstance(icon, QIcon): |
| 191 |
icon = QIcon.ic(icon) |
| 192 |
le = self.lineEdit() |
| 193 |
assert le is not None |
| 194 |
return le.addAction(icon, position) |
| 195 |
|
| 196 |
def initialize(self, opt_name, colorize=False, help_text=_('Search'), as_you_type=None): |
| 197 |
self.as_you_type = config['search_as_you_type'] if as_you_type is None else as_you_type |
| 198 |
self.opt_name = opt_name |
| 199 |
items = [] |
| 200 |
for item in config[opt_name]: |
| 201 |
if item not in items: |
| 202 |
items.append(item) |
| 203 |
self.addItems(items) |
| 204 |
self.line_edit.setPlaceholderText(help_text) |
| 205 |
self.clear() |
| 206 |
|
| 207 |
def clear_history(self): |
| 208 |
config[self.opt_name] = [] |
| 209 |
super().clear() |
| 210 |
self.clear() |
| 211 |
|
| 212 |
clear_search_history = clear_history |
| 213 |
|
| 214 |
def hide_completer_popup(self): |
| 215 |
try: |
| 216 |
le = self.lineEdit() |
| 217 |
assert le is not None |
| 218 |
comp = le.completer() |
| 219 |
assert comp is not None |
| 220 |
pop = comp.popup() |
| 221 |
assert pop is not None |
| 222 |
pop.setVisible(False) |
| 223 |
except Exception: |
| 224 |
pass |
| 225 |
|
| 226 |
def normalize_state(self): |
| 227 |
self.setToolTip(self.tool_tip_text) |
| 228 |
self.setStyleSheet('') |
| 229 |
self.show_parse_error_action(False) |
| 230 |
|
| 231 |
def text(self): |
| 232 |
return self.currentText() |
| 233 |
|
| 234 |
def clear(self, emit_search=True): |
| 235 |
self.show_parse_error_action(False) |
| 236 |
self.normalize_state() |
| 237 |
self.setEditText('') |
| 238 |
if emit_search: |
| 239 |
self.search.emit('') |
| 240 |
self._in_a_search = False |
| 241 |
self.cleared.emit() |
| 242 |
|
| 243 |
def clear_clicked(self, *args): |
| 244 |
self.clear() |
| 245 |
self.setFocus(Qt.FocusReason.OtherFocusReason) |
| 246 |
|
| 247 |
def show_parse_error_action(self, to_show, tooltip=''): |
| 248 |
if self.parse_error_action is not None: |
| 249 |
self.parse_error_action.setVisible(to_show) |
| 250 |
self.parse_error_action.setToolTip(tooltip) |
| 251 |
|
| 252 |
def search_done(self, ok): |
| 253 |
if isinstance(ok, (str, bytes)): |
| 254 |
self.setToolTip(ok) |
| 255 |
self.show_parse_error_action(True, tooltip=ok) |
| 256 |
ok = False |
| 257 |
if not str(self.currentText()).strip(): |
| 258 |
self.setStyleSheet('') |
| 259 |
self.clear(emit_search=False) |
| 260 |
return |
| 261 |
self._in_a_search = ok |
| 262 |
if self.parse_error_action is not None and not ok: |
| 263 |
self.setStyleSheet(stylesheet_for_lineedit(bool(ok), 'QComboBox')) |
| 264 |
else: |
| 265 |
self.setStyleSheet('') |
| 266 |
|
| 267 |
# Comes from the lineEdit control |
| 268 |
def key_pressed(self, event): |
| 269 |
k = event.key() |
| 270 |
if k in ( |
| 271 |
Qt.Key.Key_Left, |
| 272 |
Qt.Key.Key_Right, |
| 273 |
Qt.Key.Key_Up, |
| 274 |
Qt.Key.Key_Down, |
| 275 |
Qt.Key.Key_Home, |
| 276 |
Qt.Key.Key_End, |
| 277 |
Qt.Key.Key_PageUp, |
| 278 |
Qt.Key.Key_PageDown, |
| 279 |
Qt.Key.Key_unknown, |
| 280 |
): |
| 281 |
return |
| 282 |
self.normalize_state() |
| 283 |
if self._in_a_search: |
| 284 |
self.changed.emit() |
| 285 |
self._in_a_search = False |
| 286 |
if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter): |
| 287 |
self.do_search() |
| 288 |
self.focus_to_library.emit() |
| 289 |
elif self.as_you_type and str(event.text()): |
| 290 |
self.timer.start(1500) |
| 291 |
|
| 292 |
# Comes from the combobox itself |
| 293 |
def keyPressEvent(self, e): |
| 294 |
self.show_parse_error_action(False) |
| 295 |
k = e.key() |
| 296 |
if k in (Qt.Key.Key_Enter, Qt.Key.Key_Return): |
| 297 |
return self.do_search() |
| 298 |
if k not in (Qt.Key.Key_Up, Qt.Key.Key_Down): |
| 299 |
return QComboBox.keyPressEvent(self, e) |
| 300 |
self.blockSignals(True) |
| 301 |
self.normalize_state() |
| 302 |
le = self.lineEdit() |
| 303 |
assert le is not None |
| 304 |
if k == Qt.Key.Key_Down and self.currentIndex() == 0 and not le.text(): |
| 305 |
self.setCurrentIndex(1), self.setCurrentIndex(0) |
| 306 |
e.accept() |
| 307 |
else: |
| 308 |
QComboBox.keyPressEvent(self, e) |
| 309 |
self.blockSignals(False) |
| 310 |
|
| 311 |
def completer_used(self, text): |
| 312 |
self.timer.stop() |
| 313 |
self.normalize_state() |
| 314 |
|
| 315 |
def timer_event(self): |
| 316 |
self._do_search(as_you_type=True) |
| 317 |
# since this is an automatic search keep focus |
| 318 |
self.setFocus(Qt.FocusReason.OtherFocusReason) |
| 319 |
|
| 320 |
def history_selected(self, text): |
| 321 |
self.changed.emit() |
| 322 |
self.do_search() |
| 323 |
|
| 324 |
def _do_search(self, store_in_history=True, as_you_type=False): |
| 325 |
self.hide_completer_popup() |
| 326 |
text = str(self.currentText()).strip() |
| 327 |
if not text: |
| 328 |
return self.clear() |
| 329 |
if as_you_type: |
| 330 |
text = AsYouType(text) |
| 331 |
self.search.emit(text) |
| 332 |
|
| 333 |
if store_in_history: |
| 334 |
idx = self.findText(text, Qt.MatchFlag.MatchFixedString | Qt.MatchFlag.MatchCaseSensitive) |
| 335 |
self.block_signals(True) |
| 336 |
if idx < 0: |
| 337 |
self.insertItem(0, text) |
| 338 |
else: |
| 339 |
t = self.itemText(idx) |
| 340 |
self.removeItem(idx) |
| 341 |
self.insertItem(0, t) |
| 342 |
self.setCurrentIndex(0) |
| 343 |
self.block_signals(False) |
| 344 |
history = [str(self.itemText(i)) for i in range(self.count())] |
| 345 |
config[self.opt_name] = history |
| 346 |
|
| 347 |
def do_search(self, *args): |
| 348 |
self._do_search() |
| 349 |
self.timer.stop() |
| 350 |
|
| 351 |
def block_signals(self, yes): |
| 352 |
self.blockSignals(yes) |
| 353 |
self.line_edit.blockSignals(yes) |
| 354 |
|
| 355 |
def set_search_string(self, txt, store_in_history=False, emit_changed=True): |
| 356 |
if not store_in_history: |
| 357 |
self.textActivated.disconnect() |
| 358 |
try: |
| 359 |
self.setFocus(Qt.FocusReason.OtherFocusReason) |
| 360 |
if not txt: |
| 361 |
self.clear() |
| 362 |
else: |
| 363 |
self.normalize_state() |
| 364 |
# must turn on case sensitivity here so that tag browser strings |
| 365 |
# are not case-insensitively replaced from history |
| 366 |
line_edit_completer = self.line_edit.completer() |
| 367 |
assert line_edit_completer is not None |
| 368 |
line_edit_completer.setCaseSensitivity(Qt.CaseSensitivity.CaseSensitive) |
| 369 |
self.setEditText(txt) |
| 370 |
self.line_edit.end(False) |
| 371 |
if emit_changed: |
| 372 |
self.changed.emit() |
| 373 |
self._do_search(store_in_history=store_in_history) |
| 374 |
line_edit_completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive) |
| 375 |
self.focus_to_library.emit() |
| 376 |
finally: |
| 377 |
if not store_in_history: |
| 378 |
# QueuedConnection as workaround for https://bugreports.qt-project.org/browse/QTBUG-40807 |
| 379 |
self.textActivated.connect(self.history_selected, type=Qt.ConnectionType.QueuedConnection) |
| 380 |
|
| 381 |
def search_as_you_type(self, enabled): |
| 382 |
self.as_you_type = enabled |
| 383 |
|
| 384 |
def in_a_search(self): |
| 385 |
return self._in_a_search |
| 386 |
|
| 387 |
@property |
| 388 |
def current_text(self): |
| 389 |
le = self.lineEdit() |
| 390 |
assert le is not None |
| 391 |
return str(le.text()) |
| 392 |
|
| 393 |
# }}} |
| 394 |
|
| 395 |
|
| 396 |
class SearchBoxMixin: # {{{ |
| 397 |
def init_search_box_mixin(self: Main): |
| 398 |
self.search.initialize('main_search_history', help_text=_('Search (For advanced search click the gear icon to the left)')) |
| 399 |
self.search.cleared.connect(self.search_box_cleared) |
| 400 |
# Queued so that search.current_text will be correct |
| 401 |
self.search.changed.connect(self.search_box_changed, type=Qt.ConnectionType.QueuedConnection) |
| 402 |
self.search.focus_to_library.connect(self.focus_to_library) |
| 403 |
self.advanced_search_toggle_action.triggered.connect(self.do_advanced_search) |
| 404 |
|
| 405 |
self.search.clear() |
| 406 |
self.search.setMaximumWidth(self.width() - 150) |
| 407 |
self.action_focus_search = QAction(self) |
| 408 |
shortcuts = [str(x.toString(QKeySequence.SequenceFormat.PortableText)) for x in QKeySequence.keyBindings(QKeySequence.StandardKey.Find)] |
| 409 |
shortcuts += ['/', 'Alt+S'] |
| 410 |
self.keyboard.register_shortcut('start search', _('Start search'), default_keys=shortcuts, action=self.action_focus_search) |
| 411 |
self.action_focus_search.triggered.connect(self.focus_search_box) |
| 412 |
self.addAction(self.action_focus_search) |
| 413 |
self.search.setStatusTip(re.sub(r'<\w+>', ' ', str(self.search.toolTip()))) |
| 414 |
self.set_highlight_only_button_icon() |
| 415 |
self.highlight_only_button.clicked.connect(self.highlight_only_clicked) |
| 416 |
tt = _('Enable or disable search highlighting.') + '<br><br>' |
| 417 |
tt += config.help('highlight_search_matches') |
| 418 |
self.highlight_only_button.setToolTip(tt) |
| 419 |
self.highlight_only_action = ac = QAction(self) |
| 420 |
self.addAction(ac), ac.triggered.connect(self.highlight_only_clicked) |
| 421 |
self.keyboard.register_shortcut('highlight search results', _('Highlight search results'), action=self.highlight_only_action) |
| 422 |
self.refresh_search_bar_widgets() |
| 423 |
|
| 424 |
def refresh_search_bar_widgets(self: Main): |
| 425 |
self.set_highlight_only_button_icon() |
| 426 |
if gprefs['search_tool_bar_shows_text']: |
| 427 |
self.search_bar.search_button.setText(_('Search')) |
| 428 |
self.search_bar.search_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) |
| 429 |
else: |
| 430 |
self.search_bar.search_button.setText(None) |
| 431 |
self.search_bar.search_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) |
| 432 |
|
| 433 |
def highlight_only_clicked(self: Main, state): |
| 434 |
if not config['highlight_search_matches'] and not question_dialog( |
| 435 |
self, |
| 436 |
_('Are you sure?'), |
| 437 |
_( |
| 438 |
'This will change how searching works. When you search, instead of showing only the ' |
| 439 |
'matching books, all books will be shown with the matching books highlighted. ' |
| 440 |
'Are you sure this is what you want?' |
| 441 |
), |
| 442 |
skip_dialog_name='confirm_search_highlight_toggle', |
| 443 |
): |
| 444 |
return |
| 445 |
config['highlight_search_matches'] = not config['highlight_search_matches'] |
| 446 |
self.set_highlight_only_button_icon() |
| 447 |
self.search.do_search() |
| 448 |
self.focus_to_library() |
| 449 |
|
| 450 |
def set_highlight_only_button_icon(self: Main): |
| 451 |
b = self.highlight_only_button |
| 452 |
if config['highlight_search_matches']: |
| 453 |
b.setIcon(QIcon.ic('highlight_only_on.png')) |
| 454 |
if gprefs['search_tool_bar_shows_text']: |
| 455 |
b.setText(_('Filter')) |
| 456 |
b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) |
| 457 |
else: |
| 458 |
b.setText(None) |
| 459 |
b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) |
| 460 |
else: |
| 461 |
b.setIcon(QIcon.ic('highlight_only_off.png')) |
| 462 |
if gprefs['search_tool_bar_shows_text']: |
| 463 |
b.setText(pgettext('mark books matching search result instead of filtering them', 'Highlight')) |
| 464 |
b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) |
| 465 |
else: |
| 466 |
b.setText(None) |
| 467 |
b.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) |
| 468 |
self.highlight_only_button.setVisible(gprefs['show_highlight_toggle_button']) |
| 469 |
self.library_view._model.set_highlight_only(config['highlight_search_matches']) |
| 470 |
|
| 471 |
def focus_search_box(self: Main, *args): |
| 472 |
self.search.setFocus(Qt.FocusReason.OtherFocusReason) |
| 473 |
le = self.search.lineEdit() |
| 474 |
if le: |
| 475 |
le.selectAll() |
| 476 |
|
| 477 |
def search_box_cleared(self: Main): |
| 478 |
self.tags_view.clear() |
| 479 |
self.set_number_of_books_shown() |
| 480 |
|
| 481 |
def search_box_changed(self: Main): |
| 482 |
self.tags_view.conditional_clear(self.search.current_text) |
| 483 |
|
| 484 |
def do_advanced_search(self: Main, *args): |
| 485 |
d = SearchDialog(self, self.current_db) |
| 486 |
if d.exec() == QDialog.DialogCode.Accepted: |
| 487 |
self.search.set_search_string(d.search_string(), store_in_history=True) |
| 488 |
|
| 489 |
def do_search_button(self: Main): |
| 490 |
self.search.do_search() |
| 491 |
self.focus_to_library() |
| 492 |
|
| 493 |
def focus_to_library(self: Main): |
| 494 |
self.focus_current_view() |
| 495 |
|
| 496 |
# }}} |
| 497 |
|
| 498 |
|
| 499 |
class SavedSearchBoxMixin: # {{{ |
| 500 |
def init_saved_seach_box_mixin(self: Main): |
| 501 |
pass |
| 502 |
|
| 503 |
def add_saved_searches_to_menu(self: Main, menu, db, add_action_func=None): |
| 504 |
def add_action(current_menu, whole_name, last_component, func=None): |
| 505 |
if add_action_func is None: |
| 506 |
return current_menu.addAction(last_component, func) |
| 507 |
return add_action_func(current_menu, whole_name, last_component) |
| 508 |
|
| 509 |
folder_icon = QIcon.ic('folder_saved_search.png') |
| 510 |
search_icon = QIcon.ic('search.png') |
| 511 |
use_hierarchy = 'search' in db.new_api.pref('categories_using_hierarchy', []) |
| 512 |
submenus = {} |
| 513 |
for name in sorted(db.saved_search_names(), key=lambda x: primary_sort_key(x.strip())): |
| 514 |
display_name = name.replace('&', '&&') |
| 515 |
current_menu = menu |
| 516 |
if use_hierarchy: |
| 517 |
components = tuple(n.strip() for n in name.split('.')) |
| 518 |
hierarchy = components[:-1] |
| 519 |
last = components[-1] |
| 520 |
# Walk the hierarchy, creating submenus as needed |
| 521 |
for i, c in enumerate(hierarchy, start=1): |
| 522 |
hierarchical_prefix = '.'.join(hierarchy[:i]) |
| 523 |
if hierarchical_prefix not in submenus: |
| 524 |
current_menu = current_menu.addMenu(c.replace('&', '&&')) |
| 525 |
current_menu.setIcon(folder_icon) |
| 526 |
submenus[hierarchical_prefix] = current_menu |
| 527 |
else: |
| 528 |
current_menu = submenus[hierarchical_prefix] |
| 529 |
ac = add_action( |
| 530 |
current_menu, |
| 531 |
display_name, |
| 532 |
last.replace('&', '&&'), |
| 533 |
partial(self.search.set_search_string, 'search:"=' + name + '"'), |
| 534 |
) |
| 535 |
else: |
| 536 |
ac = add_action( |
| 537 |
current_menu, |
| 538 |
display_name, |
| 539 |
display_name, |
| 540 |
partial(self.search.set_search_string, 'search:"=' + name + '"'), |
| 541 |
) |
| 542 |
if ac.icon().isNull(): |
| 543 |
ac.setIcon(search_icon) |
| 544 |
|
| 545 |
def populate_add_saved_search_menu(self: Main, to_menu): |
| 546 |
m = to_menu |
| 547 |
m.clear() |
| 548 |
m.addAction(QIcon.ic('search_add_saved.png'), _('Add Saved search'), self.add_saved_search) |
| 549 |
m.addAction(QIcon.ic('search_copy_saved.png'), _('Get Saved search expression'), self.get_saved_search_text) |
| 550 |
m.addAction(QIcon.ic('folder_saved_search.png'), _('Manage Saved searches'), partial(self.do_saved_search_edit, None)) |
| 551 |
m.addSeparator() |
| 552 |
self.add_saved_searches_to_menu(m, self.current_db) |
| 553 |
|
| 554 |
def saved_searches_changed(self: Main, set_restriction=None, recount=True): |
| 555 |
self.build_search_restriction_list() |
| 556 |
if recount: |
| 557 |
self.tags_view.recount() |
| 558 |
if set_restriction: # redo the search restriction if there was one |
| 559 |
self.apply_named_search_restriction(set_restriction) |
| 560 |
|
| 561 |
def do_saved_search_edit(self: Main, search): |
| 562 |
d = SavedSearchEditor(self, search) |
| 563 |
d.exec() |
| 564 |
if d.result() == QDialog.DialogCode.Accepted: |
| 565 |
self.do_rebuild_saved_searches() |
| 566 |
|
| 567 |
def do_rebuild_saved_searches(self: Main): |
| 568 |
self.saved_searches_changed() |
| 569 |
|
| 570 |
def add_saved_search(self: Main): |
| 571 |
from calibre.gui2.dialogs.saved_search_editor import AddSavedSearch |
| 572 |
|
| 573 |
d = AddSavedSearch(parent=self, search=self.search.current_text) |
| 574 |
if d.exec() == QDialog.DialogCode.Accepted: |
| 575 |
self.current_db.new_api.ensure_has_search_category(fail_on_existing=False) |
| 576 |
self.do_rebuild_saved_searches() |
| 577 |
|
| 578 |
def get_saved_search_text(self: Main, search_name=None): |
| 579 |
db = self.current_db |
| 580 |
try: |
| 581 |
current_search = search_name or self.search.currentText() |
| 582 |
if not current_search.startswith('search:'): |
| 583 |
raise ValueError() |
| 584 |
# This strange expression accounts for the four ways a search can be written: |
| 585 |
# search:fff, search:"fff", search:"=fff". and search:="fff" |
| 586 |
current_search = current_search[7:].lstrip('=').strip('"').lstrip('=') |
| 587 |
current_search = db.saved_search_lookup(current_search) |
| 588 |
if not current_search: |
| 589 |
raise ValueError() |
| 590 |
self.search.set_search_string(current_search) |
| 591 |
except Exception: |
| 592 |
from calibre.gui2.ui import get_gui |
| 593 |
|
| 594 |
get_gui(fail_if_absent=True).status_bar.show_message(_('Current search is not a saved search'), 3000) |
| 595 |
|
| 596 |
# }}} |