Debian Codegraph @

src/pyj/viewer-main.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 import traceback
6 from elementmaker import E
7 from gettext import gettext as _, install
8
9 import initialize # noqa: unused-import
10 from ajax import absolute_path, ajax, workaround_qt_bug
11 from book_list.globals import get_session_data, set_session_data
12 from book_list.library_data import library_data
13 from book_list.theme import css_for_variables, get_color
14 from date import format_date
15 from dom import get_widget_css, set_css
16 from modals import create_modal_container
17 from qt import from_python, to_python
18 from read_book.db import new_book
19 from read_book.footnotes import main as footnotes_main
20 from read_book.globals import (
21 default_color_schemes, runtime, set_system_colors, ui_operations
22 )
23 from read_book.iframe import main as iframe_main
24 from read_book.open_book import remove_recently_opened
25 from read_book.prefs.head_foot import set_time_formatter
26 from read_book.view import View
27 from session import (
28 apply_reader_profile, default_interface_data, local_storage, session_defaults, settings_for_reader_profile
29 )
30 from utils import debounce, encode_query_with_path, parse_url_params
31 from viewer.constants import FAKE_HOST, FAKE_PROTOCOL
32
33 runtime.is_standalone_viewer = True
34 runtime.FAKE_HOST = FAKE_HOST
35 runtime.SANDBOX_HOST = FAKE_HOST.rpartition('.')[0] + '.sandbox'
36 runtime.FAKE_PROTOCOL = FAKE_PROTOCOL
37 book = None
38 view = None
39
40
41 def file_received(name, file_data, proceed, end_type, xhr, ev):
42 end_type = workaround_qt_bug(xhr, end_type)
43 if end_type is 'abort':
44 return
45 if end_type is not 'load':
46 show_error(_('Failed to load file from book'), _(
47 'Could not load the file: {} with error: {}').format(name, xhr.error_html))
48 return
49 if not xhr.responseType or xhr.responseType is 'text':
50 result = xhr.responseText
51 else if xhr.responseType is 'blob':
52 result = xhr.response
53 else:
54 show_error(_('Failed to load file from book'), _(
55 'Could not load the file: {} unknown response type: {}').format(name, xhr.responseType))
56 return
57
58 proceed(result, name, file_data.mimetype, book)
59
60
61 def get_url_for_book_file_name(name):
62 return absolute_path('book/' + name)
63
64
65 def get_file(book, name, proceed):
66 entry = book.manifest.files[name]
67 if not entry:
68 raise ValueError(f'No file named {name} in the book manifest')
69 xhr = ajax('book/' + name, file_received.bind(None, name, entry, proceed), ok_code=0)
70 if entry.is_html or entry.mimetype.startswith('text/') or entry.mimetype is 'application/javascript':
71 xhr.responseType = 'text'
72 else:
73 xhr.responseType = 'blob'
74 xhr.send()
75
76
77 profiles_callbacks = {'all': None, 'saved': None}
78
79
80 @from_python
81 @no_prune
82 def profile_response(which, x):
83 if which is 'all-profiles':
84 profiles_callbacks.all(x)
85 profiles_callbacks.all = None
86 elif which is 'save-profile':
87 profiles_callbacks.saved()
88 profiles_callbacks.saved = None
89 elif which is 'apply-profile':
90 sd = get_session_data()
91 apply_reader_profile(sd, x)
92 if view:
93 view.preferences_changed()
94 ui_operations.apply_profile(x)
95 elif which is 'request-save':
96 sd = get_session_data()
97 settings = settings_for_reader_profile(sd)
98 save_profile(x, settings, def (): pass;)
99
100
101 def get_all_profiles(proceed):
102 profiles_callbacks.all = proceed
103 to_python.profile_op('all-profiles', '', None)
104
105
106 def save_profile(name, settings, proceed):
107 profiles_callbacks.saved = proceed
108 to_python.profile_op('save-profile', name, settings)
109
110
111 def get_mathjax_files(proceed):
112 proceed({})
113
114
115 def update_url_state(replace):
116 if view and view.currently_showing:
117 bookpos = view.currently_showing.bookpos
118 if bookpos:
119 query = {'bookpos': bookpos}
120 query = encode_query_with_path(query)
121 if replace:
122 window.history.replaceState(None, '', query)
123 else:
124 window.history.pushState(None, '', query)
125
126
127 def on_pop_state():
128 if view and view.currently_showing:
129 data = parse_url_params()
130 if data.bookpos and data.bookpos.startswith('epubcfi(/'):
131 view.goto_cfi(data.bookpos)
132
133
134 def show_error(title, msg, details):
135 to_python.show_error(title, msg, details)
136
137
138 def manifest_received(key, initial_position, pathtoebook, highlights, book_url, reading_rates, book_in_library_url, end_type, xhr, ev):
139 nonlocal book
140 end_type = workaround_qt_bug(xhr, end_type)
141 if end_type is 'load':
142 book = new_book(key, {})
143 data = xhr.response
144 book.manifest = data[0]
145 book.metadata = book.manifest.metadata = data[1]
146 book.manifest.pathtoebook = pathtoebook
147 book.highlights = highlights
148 book.stored_files = {}
149 book.calibre_book_url = book_url
150 book.calibre_book_in_library_url = book_in_library_url
151 book.saved_reading_rates = reading_rates
152 book.is_complete = True
153 v'delete book.manifest["metadata"]'
154 v'delete book.manifest["last_read_positions"]'
155 view.display_book(book, initial_position)
156 else:
157 show_error(_('Could not open book'), _(
158 'Failed to load book manifest, click "Show details" for more info'),
159 xhr.error_html or None)
160
161
162 def clone(x):
163 if x:
164 x = window.structuredClone(x)
165 return x
166
167
168 class SessionData:
169 def __init__(self, prefs):
170 defaults = session_defaults()
171 self.data = {k: clone(defaults[k]) if prefs[k] is undefined else clone(prefs[k]) for k in defaults}
172
173 def get(self, key, defval):
174 ans = self.data[key]
175 if ans is undefined or ans is None:
176 if defval is undefined:
177 defval = None
178 return defval
179 return ans
180
181 def set(self, key, val):
182 if val is None:
183 self.data[key] = clone(session_defaults()[key])
184 else:
185 self.data[key] = val
186 to_python.set_session_data(key, val)
187
188 def set_bulk(self, changes):
189 defaults = session_defaults()
190 for key in Object.keys(changes):
191 val = changes[key]
192 if val is None:
193 self.data[key] = clone(defaults[key])
194 else:
195 self.data[key] = val
196 to_python.set_session_data(changes, None)
197
198 def clear(self):
199 defaults = session_defaults()
200 self.data = {k: clone(defaults[k]) for k in defaults}
201 to_python.set_session_data('*', None)
202
203
204 class LocalStorage:
205 def __init__(self, data):
206 self.data = data
207
208 def get(self, key, defval):
209 ans = self.data[key]
210 if ans is undefined or ans is None:
211 if defval is undefined:
212 defval = None
213 return defval
214 return ans
215
216 def set(self, key, val):
217 self.data[key] = val
218 to_python.set_local_storage(key, val)
219
220 def clear(self):
221 self.data = {}
222 to_python.set_local_storage('*', None)
223
224
225 def create_session_data(prefs, local_storage_data):
226 sd = SessionData(prefs)
227 set_session_data(sd)
228 local_storage.storage = LocalStorage(local_storage_data)
229
230
231 @from_python
232 @no_prune
233 def create_view(prefs, local_storage, field_metadata, ui_data):
234 nonlocal view
235 set_system_colors(ui_data.system_colors)
236 runtime.all_font_families = ui_data.all_font_families
237 library_data.field_metadata = field_metadata
238 document.documentElement.style.fontFamily = f'"{ui_data.ui_font_family}", sans-serif'
239 document.documentElement.style.fontSize = ui_data.ui_font_sz
240 runtime.QT_VERSION = ui_data.QT_VERSION
241 set_time_formatter(def (d):
242 return format_date(d, ui_data.short_time_fmt)
243 )
244 if view is None:
245 create_session_data(prefs, local_storage)
246 view = View(document.getElementById('view'))
247 window.addEventListener('resize', debounce(view.on_resize.bind(self), 250))
248 to_python.view_created({'default_color_schemes': default_color_schemes})
249 default_interface_data.use_roman_numerals_for_series_number = ui_data.use_roman_numerals_for_series_number
250 if ui_data.show_home_page_on_ready:
251 view.overlay.open_book(False)
252
253
254 @from_python
255 @no_prune
256 def set_system_palette(system_colors):
257 set_system_colors(system_colors)
258 if view:
259 view.update_color_scheme()
260
261
262 @from_python
263 @no_prune
264 def highlight_action(uuid, which):
265 if view:
266 view.highlight_action(uuid, which)
267
268
269 @from_python
270 @no_prune
271 def generic_action(which, data):
272 if which is 'set-notes-in-highlight':
273 view.set_notes_for_highlight(data.uuid, data.notes or '')
274 elif which is 'set-style-in-highlights':
275 view.set_style_for_highlights(data.updates)
276 elif which is 'show-status-message':
277 view.show_status_message(data.text)
278 elif which is 'remove-recently-opened':
279 remove_recently_opened(data.path)
280 elif which is 'add-notes-or-create-highlight':
281 view.add_notes_or_create_highlight(data.notes, data.style)
282
283
284 @from_python
285 @no_prune
286 def tts_event(which, data):
287 view.read_aloud.handle_tts_event(which, data)
288
289
290 @from_python
291 @no_prune
292 def show_home_page():
293 view.overlay.open_book(False)
294
295
296 @from_python
297 @no_prune
298 def redraw_tts_bar(pos):
299 sd = get_session_data()
300 sd.set('tts_bar_position', pos)
301 if view:
302 view.read_aloud.build_bar()
303
304
305 @from_python
306 @no_prune
307 def start_book_load(key, initial_position, pathtoebook, highlights, book_url, reading_rates, book_in_library_url):
308 xhr = ajax(
309 'manifest',
310 manifest_received.bind(None, key, initial_position, pathtoebook, highlights, book_url, reading_rates, book_in_library_url),
311 ok_code=0
312 )
313 xhr.responseType = 'json'
314 xhr.send()
315
316
317 @from_python
318 @no_prune
319 def goto_toc_node(node_id):
320 view.goto_toc_node(node_id)
321
322
323 @from_python
324 @no_prune
325 def goto_cfi(cfi, add_to_history):
326 return view.goto_cfi(cfi, v'!!add_to_history')
327
328
329 @from_python
330 @no_prune
331 def full_screen_state_changed(viewer_in_full_screen):
332 runtime.viewer_in_full_screen = viewer_in_full_screen
333
334
335 @from_python
336 @no_prune
337 def get_current_cfi(request_id):
338 view.get_current_cfi(request_id, ui_operations.report_cfi)
339
340
341 @from_python
342 @no_prune
343 def goto_frac(frac):
344 if view:
345 view.goto_frac(frac)
346
347
348 @from_python
349 @no_prune
350 def background_image_changed(img_id, url):
351 img = document.getElementById(img_id)
352 if img:
353 img.src = f'{url}?{Date().getTime()}'
354 img.dataset.url = url
355
356
357 @from_python
358 @no_prune
359 def trigger_shortcut(which):
360 if view:
361 view.on_handle_shortcut({'name': which})
362
363
364 @from_python
365 @no_prune
366 def show_search_result(sr):
367 if view:
368 if sr.on_discovery:
369 view.discover_search_result(sr)
370 else:
371 view.show_search_result(sr)
372
373
374 @from_python
375 @no_prune
376 def prepare_for_close():
377 if view:
378 view.prepare_for_close()
379 else:
380 ui_operations.close_prep_finished(None)
381
382
383 @from_python
384 @no_prune
385 def repair_after_fullscreen_switch():
386 if view:
387 view.show_status_message('...', 200)
388
389
390 @from_python
391 @no_prune
392 def viewer_font_size_changed():
393 if view:
394 view.viewer_font_size_changed()
395
396
397 @from_python
398 @no_prune
399 def native_gesture(gesture):
400 if view:
401 view.native_gesture(gesture)
402
403
404 source_map_set = False
405
406
407 def source_map_received(data, end_type, xhr, ev):
408 end_type = workaround_qt_bug(xhr, end_type)
409 if end_type is 'abort':
410 return
411 if end_type is 'load' and xhr.responseType is 'json':
412 traceback.set_source_map_data(xhr.response)
413 error_object = traceback.unserialize_error_for_formatting(data.error)
414 details = traceback.format_exception(error_object).join('')
415 show_error(data.title, data.msg, details)
416
417
418 def load_source_map(data):
419 nonlocal source_map_set
420 xhr = ajax('viewer.js.map', source_map_received.bind(None, data))
421 xhr.responseType = 'json'
422 xhr.send()
423 source_map_set = True
424
425
426 def onerror(msg, script_url, line_number, column_number, error_object):
427 if not error_object:
428 # cross domain error
429 return False
430 fname = script_url.rpartition('/')[-1] or script_url
431 msg += '<br><span style="font-size:smaller">' + 'Error at {}:{}:{}'.format(fname, line_number, column_number or '') + '</span>'
432 details = ''
433 console.log(error_object)
434 title = _('Unhandled error')
435 if source_map_set:
436 details = traceback.format_exception(error_object).join('')
437 show_error(title, msg, details)
438 else:
439 load_source_map({'title': title, 'msg': msg, 'error': traceback.serialize_error_for_formatting(error_object)})
440 return True
441
442
443 if window is window.top:
444 # main
445 if window.calibre_translations_data:
446 install(window.calibre_translations_data)
447 window.calibre_translations_data = None
448 ui_operations.get_all_profiles = get_all_profiles
449 ui_operations.save_profile = save_profile
450 ui_operations.apply_profile = def (profile):
451 to_python.profile_op('apply-profile-to-viewer-ui', '', profile)
452 ui_operations.get_file = get_file
453 ui_operations.get_url_for_book_file_name = get_url_for_book_file_name
454 ui_operations.get_mathjax_files = get_mathjax_files
455 ui_operations.update_url_state = update_url_state
456 ui_operations.show_error = show_error
457 ui_operations.redisplay_book = def ():
458 view.redisplay_book()
459 ui_operations.reload_book = def ():
460 to_python.reload_book()
461 ui_operations.forward_gesture = def (gesture):
462 view.forward_gesture(gesture)
463 ui_operations.update_color_scheme = def ():
464 view.update_color_scheme()
465 ui_operations.update_font_size = def ():
466 view.update_font_size()
467 ui_operations.focus_iframe = def ():
468 view.focus_iframe()
469 ui_operations.goto_cfi = def (cfi):
470 return view.goto_cfi(cfi)
471 ui_operations.goto_frac = def (frac):
472 return view.goto_frac(frac)
473 ui_operations.goto_book_position = def (bpos):
474 return view.goto_book_position(bpos)
475 ui_operations.goto_reference = def (ref):
476 return view.goto_reference(ref)
477 ui_operations.toggle_toc = def ():
478 to_python.toggle_toc()
479 ui_operations.toggle_bookmarks = def ():
480 to_python.toggle_bookmarks()
481 ui_operations.toggle_highlights = def ():
482 to_python.toggle_highlights()
483 ui_operations.new_bookmark = def (request_id, data):
484 if request_id is 'new-bookmark':
485 to_python.new_bookmark(data)
486 ui_operations.toggle_inspector = def ():
487 to_python.toggle_inspector()
488 ui_operations.content_file_changed = def (name):
489 to_python.content_file_changed(name)
490 ui_operations.update_last_read_position = def (cfi, pos_frac):
491 to_python.update_last_read_position(cfi, pos_frac)
492 ui_operations.show_search = def (text, trigger):
493 to_python.show_search(text, v'!!trigger')
494 ui_operations.find_next = def (previous):
495 to_python.find_next(previous)
496 ui_operations.reset_interface = def ():
497 sd = get_session_data()
498 defaults = session_defaults()
499 m = sd.get('standalone_misc_settings', {})
500 v'delete m.show_actions_toolbar'
501 sd.set('standalone_misc_settings', m)
502 sd.set('book_scrollbar', False)
503 view.book_scrollbar.apply_visibility()
504 sd.set('header', defaults.header)
505 sd.set('footer', defaults.footer)
506 view.update_header_footer()
507 to_python.reset_interface()
508 ui_operations.open_url = def (url):
509 to_python.open_url(url)
510 ui_operations.quit = def ():
511 to_python.quit()
512 ui_operations.toggle_lookup = def (force_show):
513 to_python.toggle_lookup(v'!!force_show')
514 ui_operations.selection_changed = def (selected_text, annot_id):
515 to_python.selection_changed(selected_text, annot_id or None)
516 ui_operations.update_current_toc_nodes = def (families):
517 to_python.update_current_toc_nodes(families)
518 ui_operations.toggle_full_screen = def ():
519 to_python.toggle_full_screen()
520 ui_operations.report_cfi = def (request_id, data):
521 to_python.report_cfi(request_id, data)
522 ui_operations.ask_for_open = def (path):
523 to_python.ask_for_open(path)
524 ui_operations.copy_selection = def (text, html):
525 to_python.copy_selection(text or None, html or None)
526 ui_operations.view_image = def (name):
527 to_python.view_image(name)
528 ui_operations.copy_image = def (name):
529 to_python.copy_image(name)
530 ui_operations.change_background_image = def (img_id):
531 to_python.change_background_image(img_id)
532 ui_operations.quit = def ():
533 to_python.quit()
534 ui_operations.overlay_visibility_changed = def (visible):
535 to_python.overlay_visibility_changed(visible)
536 ui_operations.reference_mode_changed = def (enabled):
537 to_python.reference_mode_changed(enabled)
538 ui_operations.show_loading_message = def (msg):
539 to_python.show_loading_message(msg)
540 ui_operations.export_shortcut_map = def (smap):
541 to_python.export_shortcut_map(smap)
542 ui_operations.print_book = def ():
543 to_python.print_book()
544 ui_operations.clear_history = def ():
545 to_python.clear_history()
546 ui_operations.customize_toolbar = def ():
547 to_python.customize_toolbar()
548 ui_operations.autoscroll_state_changed = def (active):
549 to_python.autoscroll_state_changed(active)
550 ui_operations.read_aloud_state_changed = def (active):
551 to_python.read_aloud_state_changed(active)
552 ui_operations.search_result_not_found = def (sr):
553 to_python.search_result_not_found(sr)
554 ui_operations.search_result_discovered = def (sr):
555 to_python.search_result_discovered(sr)
556 ui_operations.scrollbar_context_menu = def (x, y, frac):
557 to_python.scrollbar_context_menu(x, y, frac)
558 ui_operations.close_prep_finished = def (cfi):
559 to_python.close_prep_finished(cfi)
560 ui_operations.annots_changed = def (amap):
561 if amap.highlight:
562 to_python.highlights_changed(amap.highlight)
563 ui_operations.speak_simple_text = def (text):
564 to_python.speak_simple_text(text)
565 ui_operations.tts = def (action, data):
566 to_python.tts(action, data or v'{}')
567 ui_operations.edit_book = def (spine_name, frac, selected_text):
568 to_python.edit_book(spine_name, frac, selected_text or '')
569 ui_operations.show_book_folder = def ():
570 to_python.show_book_folder()
571 ui_operations.show_help = def (which):
572 to_python.show_help(which)
573 ui_operations.on_iframe_ready = def ():
574 to_python.on_iframe_ready()
575 ui_operations.update_reading_rates = def (rates):
576 to_python.update_reading_rates(rates)
577 ui_operations.reset_reading_rates = def ():
578 to_python.reset_reading_rates()
579 document.addEventListener('focusin', def (ev):
580 elem = ev.target
581 if elem and (elem.isContentEditable or (elem.nodeName is 'TEXTAREA' or elem.nodeName is 'INPUT')):
582 to_python.html_input_focusin()
583 , True)
584 document.body.appendChild(E.div(id='view'))
585 window.onerror = onerror
586 create_modal_container()
587 document.head.appendChild(E.style(css_for_variables() + '\n\n' + get_widget_css()))
588 set_css(document.body, background_color=get_color('window-background'), color=get_color('window-foreground'))
589 setTimeout(def ():
590 window.onpopstate = on_pop_state
591 , 0) # We do this after event loop ticks over to avoid catching popstate events that some browsers send on page load
592 else:
593 # iframe
594 if document.location.pathname.endsWith('/__index__'):
595 iframe_main()
596 elif document.location.pathname.endsWith('/__popup__'):
597 footnotes_main()