| 1 |
# vim:fileencoding=utf-8 |
| 2 |
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
from __python__ import bound_methods, hash_literals |
| 4 |
|
| 5 |
from elementmaker import E |
| 6 |
from gettext import gettext as _, ngettext |
| 7 |
|
| 8 |
from book_list.globals import get_session_data |
| 9 |
from book_list.theme import get_color |
| 10 |
from book_list.top_bar import create_top_bar |
| 11 |
from complete import create_search_bar |
| 12 |
from dom import clear, add_extra_css, build_rule |
| 13 |
from modals import error_dialog |
| 14 |
from read_book.globals import current_book, ui_operations |
| 15 |
from read_book.search_worker import ( |
| 16 |
CONNECT_FAILED, DB_ERROR, GET_SPINE_FAILED, UNHANDLED_ERROR, worker_main |
| 17 |
) |
| 18 |
from read_book.shortcuts import shortcut_for_key_event |
| 19 |
from widgets import create_button, create_spinner, create_select |
| 20 |
from worker import start_worker |
| 21 |
|
| 22 |
|
| 23 |
def parse_error_msg(msg): |
| 24 |
details = msg.msg |
| 25 |
emsg = _('Unknown error') |
| 26 |
if msg.code is GET_SPINE_FAILED: |
| 27 |
emsg = _('Loading text from the book failed.') |
| 28 |
elif msg.code is CONNECT_FAILED: |
| 29 |
emsg = _('Connecting to database storing the local copy of the book failed in the worker thread.') |
| 30 |
elif msg.code is UNHANDLED_ERROR: |
| 31 |
emsg = _('There was an unhandled error while searching.') |
| 32 |
elif msg.code is DB_ERROR: |
| 33 |
emsg = msg.error.msg |
| 34 |
details = msg.error.details |
| 35 |
return emsg, details |
| 36 |
|
| 37 |
|
| 38 |
def get_toc_data(book): |
| 39 |
spine = book.manifest.spine |
| 40 |
spine_toc_map = {name: [] for name in spine} |
| 41 |
parent_map = {} |
| 42 |
toc_id_map = {} |
| 43 |
|
| 44 |
def process_node(node): |
| 45 |
toc_id_map[node.id] = node |
| 46 |
items = spine_toc_map[node.dest] |
| 47 |
if items: |
| 48 |
items.push(node) |
| 49 |
children = node.children |
| 50 |
if children: |
| 51 |
for child in children: |
| 52 |
parent_map[child.id] = node |
| 53 |
process_node(child) |
| 54 |
|
| 55 |
toc = book.manifest.toc |
| 56 |
if toc: |
| 57 |
process_node(toc) |
| 58 |
return { |
| 59 |
'spine': spine, 'spine_toc_map': spine_toc_map, |
| 60 |
'spine_idx_map': {name: idx for idx, name in enumerate(spine)}, |
| 61 |
'parent_map': parent_map, 'toc_id_map': toc_id_map |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
class SearchOverlay: |
| 66 |
display_type = 'flex' |
| 67 |
CONTAINER_ID = 'book-search-overlay' |
| 68 |
|
| 69 |
def __init__(self, view): |
| 70 |
self.view = view |
| 71 |
self.search_in_flight = {'id': None, 'mode': 'contains', 'case_sensitive': False} |
| 72 |
self._worker = None |
| 73 |
self.request_counter = 0 |
| 74 |
self.result_map = {} |
| 75 |
c = self.container |
| 76 |
c.style.backgroundColor = get_color('window-background') |
| 77 |
c.style.maxHeight = '100vh' |
| 78 |
c.style.minHeight = '100vh' |
| 79 |
c.style.flexDirection = 'column' |
| 80 |
c.style.alignItems = 'stretch' |
| 81 |
c.style.overflow = 'hidden' |
| 82 |
c.style.userSelect = 'none' |
| 83 |
c.addEventListener('keydown', self.onkeydown) |
| 84 |
c.addEventListener('keyup', self.onkeyup) |
| 85 |
self.result_handler = None |
| 86 |
|
| 87 |
create_top_bar(c, title=_('Search in book'), action=self.hide, icon='close') |
| 88 |
|
| 89 |
search_button = create_button(_('Search'), 'search') |
| 90 |
c.appendChild(E.div( |
| 91 |
style='display: flex; padding: 1rem; padding-bottom: 0.5rem; overflow: hidden', |
| 92 |
create_search_bar(self.run_search, 'search-in-book', button=search_button), |
| 93 |
E.div('\xa0\xa0'), search_button, |
| 94 |
)) |
| 95 |
c.lastChild.firstChild.style.flexGrow = '100' |
| 96 |
sd = get_session_data() |
| 97 |
mode = sd.get('book_search_mode') |
| 98 |
ssc, ss = create_select(_('''Type of search: |
| 99 |
|
| 100 |
Contains: Search for the entered text anywhere |
| 101 |
|
| 102 |
Whole words: Search for whole words that equal the entered text |
| 103 |
|
| 104 |
Regex: Interpret the entered text as a regular expression'''), |
| 105 |
mode, contains=_('Contains'), word=_('Whole words'), regex=_('Regex')) |
| 106 |
ss.setAttribute('name', 'mode') |
| 107 |
ss.addEventListener('change', def (ev): |
| 108 |
get_session_data().set('book_search_mode', ev.target.value) |
| 109 |
) |
| 110 |
|
| 111 |
c.appendChild(E.div( |
| 112 |
style='display: flex; padding: 1rem; padding-top: 0.5rem; padding-bottom: 0; align-items: center; overflow: hidden', |
| 113 |
E.label(_('Search type:') + '\xa0', ssc), |
| 114 |
E.div('\xa0\xa0'), |
| 115 |
E.label(E.input( |
| 116 |
type='checkbox', name='case_sensitive', checked=bool(sd.get('book_search_case_sensitive'))), |
| 117 |
onchange=def (event): |
| 118 |
get_session_data().set('book_search_case_sensitive', event.target.checked) |
| 119 |
, _('Case sensitive'), |
| 120 |
), |
| 121 |
E.div('\xa0\xa0'), |
| 122 |
create_button(_('Return'), 'chevron-left', action=self.return_to_original_position, tooltip=_('Go back to where you were before searching')) |
| 123 |
)) |
| 124 |
|
| 125 |
c.appendChild(E.hr()) |
| 126 |
c.appendChild(E.div( |
| 127 |
style='display: none; overflow: auto', tabindex='0', |
| 128 |
E.div( |
| 129 |
style='text-align: center', |
| 130 |
E.div(create_spinner('4em', '4em')), |
| 131 |
E.div(_('Searching, please wait…'), style='margin-top: 1ex'), |
| 132 |
), |
| 133 |
E.div(), |
| 134 |
)) |
| 135 |
for child in c.childNodes: |
| 136 |
if child is not c.lastChild: |
| 137 |
child.style.flexShrink = '0' |
| 138 |
|
| 139 |
@property |
| 140 |
def current_query(self): |
| 141 |
c = self.container |
| 142 |
return { |
| 143 |
'mode': c.querySelector('select[name=mode]').value, |
| 144 |
'case_sensitive': c.querySelector('input[name=case_sensitive]').checked, |
| 145 |
'text': c.querySelector('input[type=search]').value |
| 146 |
} |
| 147 |
|
| 148 |
@current_query.setter |
| 149 |
def current_query(self, q): |
| 150 |
c = self.container |
| 151 |
c.querySelector('select[name=mode]').value = q.mode or 'contains' |
| 152 |
c.querySelector('input[name=case_sensitive]').checked = bool(q.case_sensitive) |
| 153 |
c.querySelector('input[type=search]').value = q.text or '' |
| 154 |
|
| 155 |
@property |
| 156 |
def bottom_container(self): |
| 157 |
return self.container.lastChild |
| 158 |
|
| 159 |
@property |
| 160 |
def results_container(self): |
| 161 |
return self.bottom_container.lastChild |
| 162 |
|
| 163 |
def show_wait(self): |
| 164 |
c = self.bottom_container |
| 165 |
c.style.display = 'block' |
| 166 |
c.firstChild.style.display = 'block' |
| 167 |
c.lastChild.style.display = 'none' |
| 168 |
|
| 169 |
def show_results(self): |
| 170 |
c = self.bottom_container |
| 171 |
c.style.display = 'block' |
| 172 |
c.firstChild.style.display = 'none' |
| 173 |
c.lastChild.style.display = 'block' |
| 174 |
c.focus() |
| 175 |
|
| 176 |
def clear_results(self): |
| 177 |
clear(self.results_container) |
| 178 |
self.result_map = {} |
| 179 |
|
| 180 |
@property |
| 181 |
def worker(self): |
| 182 |
if not self._worker: |
| 183 |
self._worker = start_worker('read_book.search') |
| 184 |
self._worker.onmessage = self.on_worker_message |
| 185 |
self.clear_caches() |
| 186 |
return self._worker |
| 187 |
|
| 188 |
def do_initial_search(self, text, query): |
| 189 |
q = {'mode': 'contains', 'case_sensitive': True, 'text': text, 'only_first_match': True} |
| 190 |
self.request_counter += 1 |
| 191 |
self.initial_search_result_counter = 0 |
| 192 |
self.initial_search_human_readable_query = query |
| 193 |
self.search_in_flight.id = self.request_counter |
| 194 |
self.result_handler = self.handle_initial_search_result |
| 195 |
self.worker.postMessage({ |
| 196 |
'type': 'search', 'current_name': '', 'id': self.request_counter, 'query': q |
| 197 |
}) |
| 198 |
|
| 199 |
def handle_initial_search_result(self, msg): |
| 200 |
if msg.type is 'error': |
| 201 |
emsg, details = parse_error_msg(msg) |
| 202 |
self.view.hide_loading() |
| 203 |
window.setTimeout(def (): |
| 204 |
error_dialog(_('Could not search'), emsg, details) |
| 205 |
, 1000) |
| 206 |
self.result_handler = None |
| 207 |
self.initial_search_result_counter = 0 |
| 208 |
elif msg.id is self.search_in_flight.id: |
| 209 |
if msg.type is 'search_complete': |
| 210 |
self.search_in_flight.id = None |
| 211 |
self.result_handler = None |
| 212 |
if self.initial_search_result_counter is 0: |
| 213 |
self.view.hide_loading() |
| 214 |
window.alert( |
| 215 |
_('The full text search query {} was not found in the book, try a manual search.') |
| 216 |
.format(self.initial_search_human_readable_query) |
| 217 |
) |
| 218 |
self.initial_search_result_counter = 0 |
| 219 |
elif msg.type is 'search_result': |
| 220 |
self.initial_search_result_counter += 1 |
| 221 |
if self.initial_search_result_counter is 1: |
| 222 |
self.view.discover_search_result(msg.result) |
| 223 |
self.view.hide_loading() |
| 224 |
|
| 225 |
def queue_search(self, query, book, current_name): |
| 226 |
self.request_counter += 1 |
| 227 |
self.original_position = self.view.currently_showing.bookpos |
| 228 |
self.view.get_current_cfi('search-original-pos', self.set_original_pos) |
| 229 |
self.search_in_flight.id = self.request_counter |
| 230 |
self.worker.postMessage({ |
| 231 |
'type': 'search', 'current_name': current_name, 'id': self.request_counter, 'query': query |
| 232 |
}) |
| 233 |
self.clear_results() |
| 234 |
self.show_wait() |
| 235 |
|
| 236 |
def set_original_pos(self, request_id, data): |
| 237 |
self.original_position = data.cfi |
| 238 |
|
| 239 |
def return_to_original_position(self): |
| 240 |
if self.original_position: |
| 241 |
self.view.goto_cfi(self.original_position) |
| 242 |
self.hide() |
| 243 |
|
| 244 |
def on_worker_message(self, evt): |
| 245 |
msg = evt.data |
| 246 |
if self.result_handler: |
| 247 |
return self.result_handler(msg) |
| 248 |
if msg.type is 'error': |
| 249 |
emsg, details = parse_error_msg(msg) |
| 250 |
error_dialog(_('Could not search'), emsg, details) |
| 251 |
elif msg.id is self.search_in_flight.id: |
| 252 |
if msg.type is 'search_complete': |
| 253 |
self.search_in_flight.id = None |
| 254 |
if Object.keys(self.result_map).length is 0: |
| 255 |
self.no_result_received() |
| 256 |
elif msg.type is 'search_result': |
| 257 |
self.result_received(msg.result) |
| 258 |
|
| 259 |
def no_result_received(self): |
| 260 |
self.show_results() |
| 261 |
self.results_container.appendChild(E.div( |
| 262 |
style='margin: 1rem', |
| 263 |
_('No matching results found'))) |
| 264 |
|
| 265 |
def result_received(self, result): |
| 266 |
self.show_results() |
| 267 |
self.result_map[result.result_num] = result |
| 268 |
sr = Object.assign({}, result) |
| 269 |
self.view.discover_search_result(sr) |
| 270 |
toc_node_id = result.toc_nodes[0] if result.toc_nodes.length else -1 |
| 271 |
toc_node = self.toc_data.toc_id_map[toc_node_id] |
| 272 |
c = self.results_container |
| 273 |
group = c.querySelector(f'[data-toc-node-id="{toc_node_id}"]') |
| 274 |
if not group: |
| 275 |
group = E.div( |
| 276 |
data_toc_node_id=toc_node_id + '', |
| 277 |
data_spine_index=result.spine_idx + '', |
| 278 |
E.div( |
| 279 |
E.span('+\xa0', style='display: none'), |
| 280 |
E.span(toc_node?.title or _('Unknown')), |
| 281 |
title=_('Click to show/hide the results in this chapter'), |
| 282 |
onclick=def (ev): |
| 283 |
ev.target.closest('[data-toc-node-id]').classList.toggle('collapsed') |
| 284 |
), |
| 285 |
E.ul() |
| 286 |
) |
| 287 |
appended = False |
| 288 |
for child in c.querySelectorAll('[data-spine-index]'): |
| 289 |
csi = parseInt(child.dataset.spineIndex) |
| 290 |
if csi > result.spine_idx: |
| 291 |
appended = True |
| 292 |
c.insertBefore(group, child) |
| 293 |
break |
| 294 |
if not appended: |
| 295 |
c.appendChild(group) |
| 296 |
ul = group.getElementsByTagName('ul')[0] |
| 297 |
tt = '' |
| 298 |
if result.toc_nodes.length: |
| 299 |
lines = [] |
| 300 |
for i, node_id in enumerate(result.toc_nodes): |
| 301 |
lines.push('\xa0\xa0' * i + '➤ ' + (self.toc_data.toc_id_map[node_id]?.title or _('Unknown'))) |
| 302 |
tt = ngettext('Table of Contents section:', 'Table of Contents sections:', lines.length) |
| 303 |
tt += '\n' + lines.join('\n') |
| 304 |
rnum = result.result_num |
| 305 |
entry = E.li(title=tt, data_result_num=rnum + '', onclick=self.result_clicked.bind(None, rnum)) |
| 306 |
|
| 307 |
if result.before: |
| 308 |
entry.appendChild(E.span('…' + result.before)) |
| 309 |
entry.appendChild(E.strong(result.text)) |
| 310 |
if result.after: |
| 311 |
entry.appendChild(E.span(result.after + '…')) |
| 312 |
ul.appendChild(entry) |
| 313 |
|
| 314 |
@property |
| 315 |
def current_result_container(self): |
| 316 |
return self.container.querySelector('.current') |
| 317 |
|
| 318 |
def make_result_current(self, result_num): |
| 319 |
q = result_num + '' |
| 320 |
for li in self.container.querySelectorAll('[data-result-num]'): |
| 321 |
if li.dataset.resultNum is q: |
| 322 |
li.classList.add('current') |
| 323 |
li.scrollIntoView() |
| 324 |
else: |
| 325 |
li.classList.remove('current') |
| 326 |
|
| 327 |
def search_result_discovered(self, sr): |
| 328 |
self.make_result_current(sr.result_num) |
| 329 |
|
| 330 |
def search_result_not_found(self, sr): |
| 331 |
if sr.on_discovery: |
| 332 |
return |
| 333 |
error_dialog( |
| 334 |
_('Search result not found'), _( |
| 335 |
'This search result matches text that is hidden in the book and cannot be displayed')) |
| 336 |
self.show() |
| 337 |
|
| 338 |
def select_search_result_in_book(self, result_num): |
| 339 |
sr = Object.assign({}, self.result_map[result_num]) |
| 340 |
sr.on_discovery = 0 |
| 341 |
self.view.show_search_result(sr) |
| 342 |
|
| 343 |
def result_clicked(self, rnum): |
| 344 |
self.make_result_current(rnum) |
| 345 |
self.select_search_result_in_book(rnum) |
| 346 |
self.hide() |
| 347 |
|
| 348 |
def clear_caches(self, book): |
| 349 |
self.clear_results() |
| 350 |
self.bottom_container.style.display = 'none' |
| 351 |
if self._worker: |
| 352 |
book = book or current_book() |
| 353 |
self.toc_data = get_toc_data(book) |
| 354 |
data = { |
| 355 |
'book_hash': book.book_hash, 'stored_files': book.stored_files, 'spine': book.manifest.spine, |
| 356 |
'toc_data': self.toc_data |
| 357 |
} |
| 358 |
self.worker.postMessage({'type': 'clear_caches', 'book': data}) |
| 359 |
|
| 360 |
def next_match(self, delta): |
| 361 |
delta = delta or 1 |
| 362 |
num_of_results = Object.keys(self.result_map).length |
| 363 |
c = self.current_result_container |
| 364 |
if c: |
| 365 |
rnum = parseInt(c.dataset.resultNum) - 1 |
| 366 |
rnum = (rnum + delta + num_of_results) % num_of_results |
| 367 |
rnum += 1 |
| 368 |
else: |
| 369 |
rnum = 1 |
| 370 |
self.make_result_current(rnum) |
| 371 |
self.results_container.focus() |
| 372 |
cr = self.current_result_container |
| 373 |
if cr: |
| 374 |
self.select_search_result_in_book(cr.dataset.resultNum) |
| 375 |
|
| 376 |
def onkeyup(self, event): |
| 377 |
if event.key is 'Escape' or event.key is 'Esc': |
| 378 |
self.hide() |
| 379 |
event.stopPropagation(), event.preventDefault() |
| 380 |
|
| 381 |
def onkeydown(self, event): |
| 382 |
sc_name = shortcut_for_key_event(event, self.view.keyboard_shortcut_map) |
| 383 |
if sc_name is 'next_match': |
| 384 |
self.next_match(1) |
| 385 |
event.stopPropagation(), event.preventDefault() |
| 386 |
return |
| 387 |
if sc_name is 'previous_match': |
| 388 |
self.next_match(-1) |
| 389 |
event.stopPropagation(), event.preventDefault() |
| 390 |
return |
| 391 |
|
| 392 |
def find_next(self, backwards): |
| 393 |
self.next_match(-1 if backwards else 1) |
| 394 |
|
| 395 |
@property |
| 396 |
def container(self): |
| 397 |
return document.getElementById(self.CONTAINER_ID) |
| 398 |
|
| 399 |
@property |
| 400 |
def is_visible(self): |
| 401 |
return self.container.style.display is not 'none' |
| 402 |
|
| 403 |
def set_text(self, text): |
| 404 |
self.container.querySelector('input[type=search]').value = text or '' |
| 405 |
|
| 406 |
def hide(self): |
| 407 |
self.container.style.display = 'none' |
| 408 |
ui_operations.focus_iframe() |
| 409 |
|
| 410 |
def show(self): |
| 411 |
c = self.container |
| 412 |
c.style.display = self.display_type |
| 413 |
inp = c.querySelector('input') |
| 414 |
inp.focus(), inp.select() |
| 415 |
|
| 416 |
def run_search(self): |
| 417 |
q = self.current_query |
| 418 |
if not q.text: |
| 419 |
self.clear_results() |
| 420 |
self.show_results() |
| 421 |
else: |
| 422 |
self.queue_search(q, current_book(), self.view.currently_showing.name) |
| 423 |
|
| 424 |
|
| 425 |
add_extra_css(def (): |
| 426 |
css = '' |
| 427 |
sel = f'#{SearchOverlay.CONTAINER_ID} ' |
| 428 |
sel += ' div[data-toc-node-id]' |
| 429 |
css += build_rule(sel, margin='1rem') |
| 430 |
css += sel + '.collapsed > div > span { display: inline !important; }' |
| 431 |
css += build_rule(sel + '.collapsed > ul', display='none') |
| 432 |
css += build_rule(sel + ' > div', font_style='italic', font_weight='bold', cursor='pointer') |
| 433 |
css += build_rule(sel + ' li', list_style_type='none', margin='1rem', margin_right='0', cursor='pointer') |
| 434 |
css += build_rule(sel + ' li.current', border_left='solid 2px var(--calibre-color-primary)', padding_left='2px') |
| 435 |
css += build_rule(sel + ' li strong', color='var(--calibre-color-primary)', font_style='italic') |
| 436 |
return css |
| 437 |
) |
| 438 |
|
| 439 |
|
| 440 |
main = worker_main |