Debian Codegraph @

src/pyj/read_book/overlay.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2016, 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 _
7 from uuid import short_uuid
8
9 from book_list.book_details import CLASS_NAME as BD_CLASS_NAME, render_metadata
10 from book_list.globals import get_session_data
11 from book_list.library_data import (
12 current_library_id, set_book_metadata, sync_library_books
13 )
14 from book_list.router import home
15 from book_list.theme import get_color
16 from book_list.top_bar import create_top_bar
17 from book_list.ui import query_as_href, show_panel
18 from dom import clear, ensure_id, set_css, svgicon
19 from modals import error_dialog, question_dialog
20 from read_book.bookmarks import create_bookmarks_panel
21 from read_book.chrome import apply_viewer_chrome_colors, viewer_chrome_colors
22 from read_book.globals import is_dark_theme, runtime, ui_operations
23 from read_book.goto import create_goto_panel, create_location_overlay, create_page_list_overlay
24 from read_book.highlights import builtin_color, create_highlights_panel
25 from read_book.main_overlay_style import (
26 MAIN_OVERLAY_ACTION_CONTROL_CLASS, MAIN_OVERLAY_ACTION_ICON_CLASS,
27 MAIN_OVERLAY_ACTIONS_CLASS, MAIN_OVERLAY_FOOTER_ACTION_CLASS,
28 MAIN_OVERLAY_FOOTER_ACTIONS_CLASS, MAIN_OVERLAY_FOOTER_CLASS,
29 MAIN_OVERLAY_FOOTER_MIDDLE_SLOT_CLASS, MAIN_OVERLAY_FOOTER_RIGHT_SLOT_CLASS,
30 MAIN_OVERLAY_FOOTER_SLOT_CLASS, MAIN_OVERLAY_ICON_SIZE, MAIN_OVERLAY_TEXT_ICON_CLASS,
31 MAIN_OVERLAY_TIMER_CLASS, MAIN_OVERLAY_TITLE_CLASS, MAIN_OVERLAY_TOP_ROW_CLASS,
32 MAIN_OVERLAY_TS_CLASS, timer_id
33 )
34 from read_book.open_book import create_open_book
35 from read_book.prefs.font_size import create_font_size_panel
36 from read_book.prefs.head_foot import time_formatter, format_time_left
37 from read_book.prefs.main import create_prefs_panel
38 from read_book.profiles import create_profiles_panel
39 from read_book.toc import create_toc_panel
40 from read_book.word_actions import create_word_actions_panel
41 from session import session_defaults, get_device_uuid
42 from utils import (
43 default_context_menu_should_be_allowed, full_screen_element,
44 full_screen_supported, is_ios, safe_set_inner_html
45 )
46 from widgets import create_button, create_spinner
47
48
49 class LoadingMessage: # {{{
50 def __init__(self, msg, current_color_scheme):
51 self.msg = msg or ''
52 self.current_color_scheme = current_color_scheme
53 self.is_not_escapable = True # prevent Esc key from closing
54
55 def show(self, container):
56 self.container_id = container.getAttribute('id')
57 container.style.backgroundColor = self.current_color_scheme.background
58 container.style.color = self.current_color_scheme.foreground
59 container.appendChild(
60 E.div(
61 style='text-align:center',
62 E.div(create_spinner('100px', '100px')),
63 E.h2()
64 ))
65 safe_set_inner_html(container.firstChild.lastChild, self.msg)
66 set_css(container.firstChild, position='relative', top='50%', transform='translateY(-50%)')
67
68 def set_msg(self, msg):
69 self.msg = msg
70 container = document.getElementById(self.container_id)
71 safe_set_inner_html(container.firstChild.lastChild, self.msg)
72
73 def on_container_click(self, evt):
74 pass # Don't allow panel to be closed by a click
75 # }}}
76
77
78 class DeleteBook: # {{{
79 def __init__(self, overlay, question, ok_icon, ok_text, reload_book):
80 self.overlay = overlay
81 self.question = question or _(
82 'Are you sure you want to remove this book from local storage? You will have to re-download it from calibre if you want to read it again.')
83 self.ok_icon = ok_icon or 'trash'
84 self.ok_text = ok_text or _('Delete book')
85 self.reload_book = reload_book
86
87 def show(self, container):
88 self.container_id = container.getAttribute('id')
89 apply_viewer_chrome_colors(container)
90 container.appendChild(E.div(
91 style='display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%',
92 tabindex='0',
93 E.div(style='margin:1ex 1em; max-width: 80%',
94 E.h2(self.question),
95 E.div(style='display:flex; justify-content:flex-end; margin-top:1rem',
96 create_button(self.ok_text, self.ok_icon, action=self.delete_book, highlight=True),
97 E.span('\xa0'),
98 create_button(_('Cancel'), action=self.cancel),
99 )
100 ),
101 onkeyup=def (ev):
102 if ev.key is 'Escape':
103 ev.stopPropagation(), ev.preventDefault()
104 self.cancel()
105 elif ev.key is 'Enter' or ev.key is 'Return':
106 ev.stopPropagation(), ev.preventDefault()
107 self.delete_book()
108 ))
109 window.setTimeout(self.focus_me, 0)
110
111 def focus_me(self):
112 document.getElementById(self.container_id).lastChild.focus()
113
114 def show_working(self):
115 container = document.getElementById(self.container_id)
116 clear(container)
117 container.appendChild(
118 E.div(
119 style='text-align:center',
120 E.div(create_spinner('100px', '100px')),
121 E.h2()
122 ))
123 safe_set_inner_html(container.lastChild.lastChild, _('Deleting local book copy, please wait...'))
124
125 def on_container_click(self, evt):
126 pass # Don't allow panel to be closed by a click
127
128 def delete_book(self):
129 if runtime.is_standalone_viewer:
130 if self.reload_book:
131 self.overlay.view.reload_book()
132 return
133 self.show_working()
134 view = self.overlay.view
135 ui_operations.delete_book(view.book, def (book, errmsg):
136 self.overlay.hide_current_panel()
137 if errmsg:
138 view.ui.show_error(
139 _('Failed to delete book'),
140 _('Failed to delete book from local storage, click "Show details" for more information.'),
141 errmsg
142 )
143 else:
144 if self.reload_book:
145 self.overlay.view.reload_book()
146 else:
147 home()
148 )
149
150 def cancel(self):
151 self.overlay.hide_current_panel()
152 # }}}
153
154
155 class SyncBook: # {{{
156 def __init__(self, overlay):
157 self.overlay = overlay
158 self.canceled = False
159
160 def show(self, container):
161 self.container_id = container.getAttribute('id')
162 apply_viewer_chrome_colors(container)
163 book = self.overlay.view.book
164 to_sync = [[book.key, Date(0)]]
165 view = self.overlay.view
166
167 def start_download():
168 sync_library_books(book.key[0], to_sync, self.sync_data_received)
169
170 def after_position_upload(success):
171 start_download()
172
173 def after_annot_upload(success):
174 view.upload_current_position(after_position_upload)
175
176 if ui_operations.upload_pending_annotations:
177 ui_operations.upload_pending_annotations(after_annot_upload)
178 else:
179 after_annot_upload(True)
180 container.appendChild(E.div(
181 style='display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%',
182 E.div(style='margin:1ex 1em; max-width: 80vw',
183 E.h2(_('Syncing last read position and annotations')),
184 E.p(_('Downloading data from server, please wait...')),
185 E.div(style='display:flex; justify-content:flex-end',
186 create_button(_('Cancel'), action=self.cancel),
187 )
188 )
189 ))
190
191 def on_container_click(self, evt):
192 pass # Don't allow panel to be closed by a click
193
194 def cancel(self):
195 self.canceled = True
196 self.overlay.hide_current_panel()
197
198 def sync_data_received(self, library_id, lrmap, load_type, xhr, ev):
199 if self.canceled:
200 return
201 self.overlay.hide()
202 if load_type is not 'load':
203 if xhr.responseText is 'login required for sync':
204 error_dialog(_('Failed to fetch sync data'), _('You must setup user accounts and login to use the sync functionality'))
205 else:
206 error_dialog(
207 _('Failed to fetch sync data'),
208 _('Failed to download sync data from server, click "Show details" for more information.'),
209 xhr.error_html
210 )
211 return
212 data = JSON.parse(xhr.responseText)
213 book = self.overlay.view.book
214 dev = get_device_uuid()
215 epoch = 0
216 ans = None
217 new_annotations_map = None
218 for key in data:
219 book_id, fmt = key.partition(':')[::2]
220 if book_id is str(book.key[1]) and fmt.upper() is book.key[2].upper():
221 new_vals = data[key]
222 last_read_positions = new_vals.last_read_positions
223 new_annotations_map = new_vals.annotations_map
224 for d in last_read_positions:
225 if d.device is not dev and d.epoch > epoch:
226 epoch = d.epoch
227 ans = d
228 break
229 cfi = ans?.cfi
230 if new_annotations_map or cfi:
231 self.overlay.view.sync_data_received(cfi, new_annotations_map)
232
233
234 # }}}
235
236
237 def create_main_overlay_action_with_icon(text, tooltip, action, icon_elem, icon_color=None):
238 if icon_color:
239 icon_elem.style.color = icon_color
240 icon_elem.classList.add(MAIN_OVERLAY_ACTION_ICON_CLASS)
241 return E.li(E.button(
242 class_=MAIN_OVERLAY_ACTION_CONTROL_CLASS, title=tooltip, type='button', onclick=action,
243 icon_elem, text
244 ))
245
246
247 def create_main_overlay_action(text, tooltip, action, icon, icon_color=None):
248 return create_main_overlay_action_with_icon(text, tooltip, action, svgicon(icon, MAIN_OVERLAY_ICON_SIZE, MAIN_OVERLAY_ICON_SIZE), icon_color)
249
250
251 def create_main_overlay_text_action(text, tooltip, action, icon_text):
252 return create_main_overlay_action_with_icon(text, tooltip, action, E.span(icon_text, class_=MAIN_OVERLAY_TEXT_ICON_CLASS))
253
254
255 def create_main_overlay_footer_action(icon, text, tooltip, action):
256 return E.button(
257 class_=MAIN_OVERLAY_FOOTER_ACTION_CLASS, title=tooltip, type='button', onclick=action,
258 svgicon(icon, MAIN_OVERLAY_ICON_SIZE, MAIN_OVERLAY_ICON_SIZE), text
259 )
260
261
262 def create_main_overlay_footer(close_action, help_action):
263 middle = E.div(class_=' '.join([MAIN_OVERLAY_FOOTER_SLOT_CLASS, MAIN_OVERLAY_FOOTER_MIDDLE_SLOT_CLASS]), '\xa0')
264 right = E.div(class_=' '.join([MAIN_OVERLAY_FOOTER_SLOT_CLASS, MAIN_OVERLAY_FOOTER_RIGHT_SLOT_CLASS]), '\xa0')
265 footer = E.div(
266 class_=MAIN_OVERLAY_FOOTER_CLASS,
267 E.div(
268 class_=MAIN_OVERLAY_FOOTER_ACTIONS_CLASS,
269 create_main_overlay_footer_action('close', _('Close'), _('Close the viewer controls'), close_action),
270 create_main_overlay_footer_action('help', _('Help'), _('Show viewer help'), help_action)
271 ),
272 middle,
273 right,
274 )
275 return {'footer': footer, 'middle_slot': middle, 'right_slot': right}
276
277
278 def render_main_overlay_footer_templates(footer_parts, renderer):
279 if not renderer:
280 return
281 renderer(footer_parts.middle_slot, 'controls_footer', 'middle', '')
282 renderer(footer_parts.right_slot, 'controls_footer', 'right', '')
283
284
285 def simple_overlay_title(title, overlay, container, close_action):
286 apply_viewer_chrome_colors(container)
287
288 def action():
289 event = this
290 event.stopPropagation()
291 overlay.hide_current_panel(event)
292
293 create_top_bar(container, title=title, icon='close', action=close_action or action)
294
295
296 class MainOverlay: # {{{
297 def __init__(self, overlay, elements):
298 self.overlay = overlay
299 self.elements = elements or {}
300 self.timer = None
301 if window.Intl?.DateTimeFormat:
302 self.date_formatter = window.Intl.DateTimeFormat(undefined, {'hour': 'numeric', 'minute': 'numeric'})
303 else:
304 self.date_formatter = {'format': def (date):
305 return '{}:{}'.format(date.getHours(), date.getMinutes())
306 }
307
308 def create_actions(self, sd):
309 ac = create_main_overlay_action
310 text_ac = create_main_overlay_text_action
311
312 sync_icon_color = None
313 if ui_operations.has_unsynced_changes and ui_operations.has_unsynced_changes():
314 sync_icon_color = builtin_color('yellow', is_dark_theme())
315 sync_action = ac(_('Sync'), _('Get last read position and annotations from the server'), self.overlay.sync_book, 'cloud-download', sync_icon_color)
316 delete_action = ac(_('Delete'), _('Delete this book from local storage'), self.overlay.delete_book, 'trash')
317 reload_action = ac(
318 _('Reload'),
319 _('Reload this book from the {}').format(_('computer') if runtime.is_standalone_viewer else _('server')),
320 self.overlay.reload_book,
321 'refresh'
322 )
323 back_action = ac(_('Back'), _('Go back'), self.back, 'arrow-left')
324 forward_action = ac(_('Forward'), _('Go forward'), self.forward, 'arrow-right')
325 nav_actions = E.ul(back_action, forward_action)
326 if runtime.is_standalone_viewer:
327 reload_actions = E.ul(
328 ac(_('Open book'), _('Open a book'), self.overlay.open_book, 'book'),
329 reload_action
330 )
331 editable_formats = v'''__EDITABLE_FORMATS__'''
332 fmt = self.overlay.view?.book?.manifest.book_format or ''
333 if fmt.toUpperCase() in editable_formats:
334 reload_actions.appendChild(ac(_('Edit book'), _('Edit this book'), self.overlay.view.edit_book, 'edit'))
335 else:
336 reload_actions = E.ul(sync_action, delete_action, reload_action)
337
338 bookmarks_action = ac(_('Bookmarks'), _('Browse all bookmarks'), self.overlay.show_bookmarks, 'bookmark')
339 highlights_action = ac(
340 _('Highlights'), _('Browse all highlights'), def ():
341 self.overlay.show_highlights()
342 , 'image')
343 reading_stats_action = ac(_('Reading statistics'), _('Show reading statistics for this book'), def ():
344 self.overlay.show_reading_stats()
345 , 'hourglass')
346
347 toc_actions = E.ul(ac(_('Table of Contents'), _('Browse the Table of Contents'), self.overlay.show_toc, 'toc'))
348 toc_actions.appendChild(ac(_('Reference mode'), _('Toggle the Reference mode'), self.overlay.toggle_reference_mode, 'reference-mode'))
349
350 actions_div = E.div( # actions
351 nav_actions,
352 E.ul(
353 ac(_('Search'), _('Search for text in this book'), self.overlay.show_search, 'search'),
354 ac(_('Go to'), _('Go to a specific location in the book'), self.overlay.show_goto, 'chevron-right'),
355 ),
356 reload_actions,
357 toc_actions,
358 E.ul(highlights_action, bookmarks_action, reading_stats_action),
359 E.ul(
360 text_ac(_('Font size'), _('Change text size'), self.overlay.show_font_size_chooser, 'Aa'),
361 ac(_('Preferences'), _('Configure the E-book viewer'), self.overlay.show_prefs, 'cogs'),
362 ),
363 class_=MAIN_OVERLAY_ACTIONS_CLASS
364 )
365 if not runtime.is_standalone_viewer:
366 home_action = ac(_('Home'), _('Return to the home page'), def ():
367 home()
368 ui_operations.close_book()
369 , 'home')
370 library_action = ac(_('Library'), _('Return to the library page'), self.overlay.show_library, 'library')
371 book_action = ac(_('Book'), _('Return to the book\'s page'), self.overlay.show_book_page, 'book')
372 actions_div.insertBefore(E.ul(home_action, library_action, book_action), actions_div.firstChild)
373 full_screen_actions = []
374 if runtime.is_standalone_viewer:
375 text = _('Exit full screen') if runtime.viewer_in_full_screen else _('Enter full screen')
376 full_screen_actions.push(
377 ac(text, _('Toggle full screen mode'), def (): self.overlay.hide(), ui_operations.toggle_full_screen();, 'full-screen'))
378 full_screen_actions.push(
379 ac(_('Print'), _('Print book to PDF'), def (): self.overlay.hide(), ui_operations.print_book();, 'print'))
380 else:
381 if not is_ios and full_screen_supported():
382 text = _('Exit full screen') if full_screen_element() else _('Enter full screen')
383 # No fullscreen on iOS, see http://caniuse.com/#search=fullscreen
384 full_screen_actions.push(
385 ac(text, _('Toggle full screen mode'), def (): self.overlay.hide(), ui_operations.toggle_full_screen();, 'full-screen')
386 )
387 if sd.get('read_mode') is 'flow':
388 asa = self.overlay.view.autoscroll_active
389 full_screen_actions.append(ac(
390 _('Stop auto scroll') if asa else _('Auto scroll'), _('Toggle auto-scrolling'), def ():
391 self.overlay.hide()
392 window.setTimeout(self.overlay.view.toggle_autoscroll, 0)
393 , 'auto-scroll'))
394
395 actions_div.appendChild(E.ul(
396 ac(_('Read aloud'), _('Read the book aloud'), def ():
397 self.overlay.hide()
398 self.overlay.view.start_read_aloud()
399 , 'bullhorn'),
400 ac(_('Profiles'), _('Quickly switch between different settings'), def ():
401 self.overlay.show_profiles()
402 , 'convert')
403 ))
404
405 if full_screen_actions.length:
406 actions_div.appendChild(E.ul(*full_screen_actions))
407
408 no_selection_bar = not sd.get('show_selection_bar')
409 if runtime.is_standalone_viewer:
410 if no_selection_bar:
411 actions_div.appendChild(E.ul(
412 ac(_('Lookup/search word'), _('Lookup or search for the currently selected word'),
413 def (): self.overlay.hide(), ui_operations.toggle_lookup(True);, 'library')
414 ))
415 copy_actions = E.ul()
416 if self.elements.link:
417 copy_actions.appendChild(ac(_('Copy link'), _('Copy the current link'), def ():
418 self.overlay.hide(), ui_operations.copy_selection(self.elements.link)
419 , 'link'))
420 if self.elements.img:
421 copy_actions.appendChild(ac(_('View image'), _('View the current image'), def ():
422 self.overlay.hide(), ui_operations.view_image(self.elements.img)
423 , 'image'))
424 copy_actions.appendChild(ac(_('Copy image'), _('Copy the current image'), def ():
425 self.overlay.hide(), ui_operations.copy_image(self.elements.img)
426 , 'copy'))
427 if copy_actions.childNodes.length:
428 actions_div.appendChild(copy_actions)
429
430 actions_div.appendChild(E.ul(
431 ac(_('Inspector'), _('Show the content inspector'),
432 def (): self.overlay.hide(), ui_operations.toggle_inspector();, 'bug'),
433 ac(_('Reset interface'), _('Reset E-book viewer panels, toolbars and scrollbars to defaults'),
434 def ():
435 question_dialog(
436 _('Are you sure?'), _(
437 'Are you sure you want to reset the viewer interface'
438 ' to its default appearance?'
439 ),
440 def (yes):
441 if yes:
442 self.overlay.hide()
443 ui_operations.reset_interface()
444 sd = get_session_data()
445 sd.set('skipped_dialogs', session_defaults().skipped_dialogs)
446 )
447 , 'window-restore'),
448 ac(_('Quit'), _('Close the E-book viewer'),
449 def (): self.overlay.hide(), ui_operations.quit();, 'remove'),
450 ))
451 else:
452 copy_actions = E.ul()
453 if self.elements.link:
454 copy_actions.appendChild(ac(_('Copy link'), _('Copy the current link'), def ():
455 self.overlay.hide(), ui_operations.copy_selection(self.elements.link)
456 , 'link'))
457 if self.elements.img:
458 copy_actions.appendChild(ac(_('View image'), _('View the current image'), def ():
459 self.overlay.hide(), ui_operations.view_image(self.elements.img)
460 , 'image'))
461 if window.navigator.clipboard:
462 copy_actions.appendChild(ac(_('Copy image'), _('Copy the current image'), def ():
463 self.overlay.hide(), ui_operations.copy_image(self.elements.img)
464 , 'copy'))
465 if copy_actions.childNodes.length:
466 actions_div.appendChild(copy_actions)
467
468 return actions_div
469
470 def create_top_section(self, actions_div):
471 return E.div(class_=MAIN_OVERLAY_TS_CLASS,
472 onclick=def (evt): evt.stopPropagation();,
473 E.div(
474 E.div(self.overlay.view.book?.metadata?.title or _('Unknown'), class_=MAIN_OVERLAY_TITLE_CLASS),
475 E.div(time_formatter.format(Date()), id=timer_id(), class_=MAIN_OVERLAY_TIMER_CLASS),
476 class_=MAIN_OVERLAY_TOP_ROW_CLASS,
477 ),
478 actions_div,
479 )
480
481 def create_footer(self):
482 def close_viewer_controls(ev):
483 ev.stopPropagation()
484 self.overlay.hide_current_panel(ev)
485
486 def show_viewer_help(ev):
487 ev.stopPropagation()
488 ui_operations.show_help('viewer')
489 self.overlay.hide_current_panel(ev)
490
491 footer_parts = create_main_overlay_footer(close_viewer_controls, show_viewer_help)
492 render_main_overlay_footer_templates(footer_parts, self.overlay.view.create_template_renderer())
493 return footer_parts.footer
494
495 def show(self, container):
496 self.container_id = container.getAttribute('id')
497 sd = get_session_data()
498 container.appendChild(self.create_top_section(self.create_actions(sd)))
499 container.appendChild(self.create_footer())
500
501 self.on_hide()
502 self.timer = setInterval(self.update_time, 1000)
503
504 def update_time(self):
505 tm = document.getElementById(timer_id())
506 if tm:
507 tm.textContent = self.date_formatter.format(Date())
508
509 def on_hide(self):
510 if self.timer is not None:
511 clearInterval(self.timer)
512 self.timer = None
513
514 def back(self):
515 window.history.back()
516 self.overlay.hide()
517
518 def forward(self):
519 window.history.forward()
520 self.overlay.hide()
521
522 # }}}
523
524
525 class SimpleOverlay: # {{{
526 def __init__(self, overlay, create_func, title):
527 self.overlay = overlay
528 self.create_func = create_func
529 self.title = title
530
531 def on_container_click(self, evt):
532 pass # Don't allow panel to be closed by a click
533
534 def show(self, container):
535 simple_overlay_title(self.title, self.overlay, container)
536 self.create_func(self.overlay, container)
537 # }}}
538
539
540 class TOCOverlay(SimpleOverlay): # {{{
541 def __init__(self, overlay, create_func, title):
542 self.overlay = overlay
543 self.create_func = create_func or create_toc_panel
544 self.title = title or _('Table of Contents')
545
546 def show(self, container):
547 container.appendChild(E.div())
548 container = container.firstChild
549 simple_overlay_title(self.title, self.overlay, container)
550 self.create_func(self.overlay.view.book, container, self.handle_activate)
551
552 def handle_activate(self, dest, frag):
553 self.overlay.hide()
554 if jstype(dest) is 'function':
555 dest(self.overlay.view, frag)
556 else:
557 self.overlay.view.goto_named_destination(dest, frag)
558 # }}}
559
560
561 class GotoOverlay: # {{{
562 def __init__(self, overlay):
563 self.overlay = overlay
564
565 def on_container_click(self, evt):
566 pass # Don't allow panel to be closed by a click
567
568 def show(self, container):
569 container.appendChild(E.div())
570 inner = container.firstChild
571 simple_overlay_title(_('Go to\u2026'), self.overlay, inner)
572 create_goto_panel(self.overlay.view.current_position_data, self.overlay.view.book, inner, self.handle_navigate, self.show_sub_panel)
573
574 def handle_navigate(self, dest, frag):
575 self.overlay.hide()
576 if jstype(dest) is 'function':
577 dest(self.overlay.view, frag)
578 else:
579 self.overlay.view.goto_named_destination(dest, frag)
580
581 def show_sub_panel(self, name):
582 # Push the sub-panel on top of the goto panel (keep goto in stack so
583 # closing the sub-panel returns to goto rather than to reading).
584 if name is 'location':
585 self.overlay.panels.push(SimpleOverlay(
586 self.overlay,
587 create_location_overlay.bind(None, self.overlay.view.current_position_data, self.overlay.view.book),
588 _('Go to location, position or reference\u2026')))
589 elif name is 'metadata':
590 self.overlay.panels.push(self.overlay._build_metadata_panel())
591 elif name is 'page_list':
592 self.overlay.panels.push(SimpleOverlay(
593 self.overlay,
594 create_page_list_overlay.bind(None, self.overlay.view.book),
595 _('Go to page')))
596 self.overlay.show_current_panel()
597 # }}}
598
599
600 class WordActionsOverlay: # {{{
601 def __init__(self, word, overlay):
602 self.word = word
603 self.overlay = overlay
604
605 def on_container_click(self, evt):
606 pass # Don't allow panel to be closed by a click
607
608 def show(self, container):
609 simple_overlay_title(_('Lookup: {}').format(self.word), self.overlay, container)
610 create_word_actions_panel(container, self.word, self.overlay.hide)
611 # }}}
612
613
614 class PrefsOverlay: # {{{
615 def __init__(self, overlay):
616 self.overlay = overlay
617 self.changes_occurred = False
618
619 def on_container_click(self, evt):
620 pass # Don't allow panel to be closed by a click
621
622 def create_panel_impl(self, container):
623 return create_prefs_panel(container, self.overlay.hide_current_panel, self.on_change)
624
625 def show(self, container):
626 self.changes_occurred = False
627 apply_viewer_chrome_colors(container)
628 self.prefs = self.create_panel_impl(container)
629
630 def on_change(self):
631 self.changes_occurred = True
632
633 def handle_escape(self):
634 self.prefs.onclose()
635
636 def on_hide(self):
637 if self.changes_occurred:
638 self.changes_occurred = False
639 self.overlay.view.preferences_changed()
640
641
642 class ProfilesOverlay(PrefsOverlay):
643 def create_panel_impl(self, container):
644 return create_profiles_panel(container, self.overlay.hide_current_panel, self.on_change)
645
646 def handle_escape(self):
647 self.overlay.hide_current_panel()
648
649 # }}}
650
651
652 class FontSizeOverlay: # {{{
653 def __init__(self, overlay):
654 self.overlay = overlay
655
656 def show(self, container):
657 create_font_size_panel(container, self.overlay.hide_current_panel)
658 # }}}
659
660
661 class OpenBook: # {{{
662 def __init__(self, overlay, closeable):
663 self.overlay = overlay
664 self.closeable = closeable
665
666 def handle_escape(self):
667 if self.closeable:
668 self.overlay.hide_current_panel()
669 else:
670 if self.overlay.handling_context_menu_event is None:
671 ui_operations.quit()
672
673 def on_container_click(self, evt):
674 pass # Don't allow panel to be closed by a click
675
676 def show(self, container):
677 simple_overlay_title(_('Open a book'), self.overlay, container, def ():
678 ev = this
679 ev.stopPropagation(), ev.preventDefault()
680 if self.closeable:
681 self.overlay.hide_current_panel(ev)
682 else:
683 ui_operations.quit()
684 )
685 create_open_book(container, self.overlay.view?.book)
686 # }}}
687
688
689 class ReadingStatsOverlay: # {{{
690 def __init__(self, overlay):
691 self.overlay = overlay
692
693 def on_container_click(self, evt):
694 pass # Don't allow panel to be closed by a click
695
696 def reset_stats(self):
697 question_dialog(
698 _('Reset reading statistics'),
699 _('Are you sure you want to delete all reading statistics? This will remove all saved reading rate data.'),
700 def (yes):
701 if yes:
702 self.do_reset()
703 )
704
705 def do_reset(self):
706 view = self.overlay.view
707 if view.timers:
708 view.timers.rates = []
709 view.timers.chapter_times = v'{}'
710 view.timers.average = view.timers.stddev = 0
711 if ui_operations.reset_reading_rates:
712 ui_operations.reset_reading_rates()
713 self.overlay.hide_current_panel()
714
715 def show(self, container):
716 simple_overlay_title(_('Reading statistics'), self.overlay, container)
717 view = self.overlay.view
718 book = view.book
719 if not book or not book.manifest:
720 container.appendChild(E.div(_('No book open'), style='padding: 1ex 1em'))
721 return
722
723 spine = book.manifest.spine
724 current_name = view.currently_showing.name
725 current_idx = spine.indexOf(current_name)
726 file_progress = view.current_file_progress_frac
727 chapter_length = book.manifest.files[current_name]?.length or 0
728 remaining_chars = chapter_length * max(0, 1 - file_progress)
729 chapter_remaining_time = view.timers.time_for(remaining_chars)
730 chapter_done_pct = Math.round(file_progress * 100)
731 total_chapters = spine.length
732
733 next_idx = current_idx + 1
734 next_name = spine[next_idx] if next_idx < spine.length else None
735 next_chapter_time = None
736 if next_name:
737 next_length = book.manifest.files[next_name]?.length or 0
738 next_chapter_time = view.timers.time_for(next_length)
739
740 book_remaining_chars = remaining_chars
741 for spine_idx in range(next_idx, spine.length):
742 book_remaining_chars += book.manifest.files[spine[spine_idx]]?.length or 0
743 book_remaining_time = view.timers.time_for(book_remaining_chars)
744
745 content = E.div(style='padding: 1ex 1em')
746 if current_idx >= 0:
747 content.appendChild(E.p(
748 _('Chapter {current} of {total}: {pct}% complete').format(
749 current=current_idx + 1, total=total_chapters, pct=chapter_done_pct),
750 style='margin: 0.5ex 0; font-weight: bold'))
751
752 if chapter_remaining_time is not None:
753 content.appendChild(E.p(
754 _('Time remaining in chapter: {}').format(format_time_left(chapter_remaining_time)),
755 style='margin: 0.5ex 0'))
756 else:
757 content.appendChild(E.p(
758 _('Time remaining in chapter: {}').format(_('Calculating…')),
759 style='margin: 0.5ex 0'))
760
761 if book_remaining_time is not None:
762 content.appendChild(E.p(
763 _('Time remaining in book: {}').format(format_time_left(book_remaining_time)),
764 style='margin: 0.5ex 0'))
765 else:
766 content.appendChild(E.p(
767 _('Time remaining in book: {}').format(_('Calculating…')),
768 style='margin: 0.5ex 0'))
769
770 if next_name:
771 if next_chapter_time is not None:
772 content.appendChild(E.p(
773 _('Time to read next chapter: {}').format(format_time_left(next_chapter_time)),
774 style='margin: 0.5ex 0'))
775 else:
776 content.appendChild(E.p(
777 _('Time to read next chapter: {}').format(_('Calculating…')),
778 style='margin: 0.5ex 0'))
779 else:
780 content.appendChild(E.p(_('This is the last chapter'), style='margin: 0.5ex 0'))
781
782 container.appendChild(content)
783
784 # Build bar graph of chapter reading times
785 chapter_times = view.timers.chapter_times
786 bar_data = []
787 max_time = 0
788 for i in range(spine.length):
789 name = spine[i]
790 length = book.manifest.files[name]?.length or 0
791 is_current = i == current_idx
792 if is_current:
793 actual_t = chapter_times[name] or 0
794 rem = view.timers.time_for(remaining_chars)
795 t = actual_t + rem if rem is not None else view.timers.time_for(length)
796 is_actual = actual_t > 0
797 elif i < current_idx:
798 actual_t = chapter_times[name]
799 if actual_t and actual_t > 0:
800 t = actual_t
801 is_actual = True
802 else:
803 t = view.timers.time_for(length)
804 is_actual = False
805 else:
806 t = view.timers.time_for(length)
807 is_actual = False
808 if t is not None and t > 0:
809 max_time = Math.max(max_time, t)
810 bar_data.push({'t': t, 'is_actual': is_actual, 'is_current': is_current, 'past': i < current_idx})
811
812 BAR_H = 120
813 BAR_W = 22
814 BAR_GAP = 3
815 COLOR_ACTUAL = '#27ae60'
816 COLOR_CURRENT = '#e67e22'
817 COLOR_ESTIMATED = '#7fb3d3'
818 COLOR_PAST_EST = '#95a5a6'
819
820 graph_section = E.div(style='padding: 0 1em 1em 1em')
821 graph_section.appendChild(E.div(
822 _('Chapter reading times'),
823 style='font-size: smaller; font-weight: bold; margin-bottom: 0.5ex'))
824
825 if max_time > 0:
826 bars_row = E.div(
827 style='display: flex; align-items: flex-end; overflow-x: auto; '
828 + f'border-bottom: 1px solid currentColor; min-height: {BAR_H + 4}px; padding-top: 4px')
829 for i in range(bar_data.length):
830 bd = bar_data[i]
831 t = bd.t
832 if t is not None and t > 0:
833 h = max(2, Math.round(t / max_time * BAR_H))
834 else:
835 h = 2
836 if bd.is_current:
837 color = COLOR_CURRENT
838 elif bd.is_actual:
839 color = COLOR_ACTUAL
840 elif bd.past:
841 color = COLOR_PAST_EST
842 else:
843 color = COLOR_ESTIMATED
844 outline = 'outline: 2px solid currentColor; outline-offset: 1px; ' if bd.is_current else ''
845 label = str(i + 1)
846 tip = _('Chapter {}').format(i + 1)
847 if t and t > 0:
848 tip += ': ' + format_time_left(t)
849 elif bd.is_current or bd.past:
850 tip += ' (' + _('no data') + ')'
851 else:
852 tip += ' (' + _('Calculating…') + ')'
853 bar = E.div(
854 style='display: inline-flex; flex-direction: column; align-items: center; '
855 + f'width: {BAR_W}px; flex-shrink: 0; margin-right: {BAR_GAP}px; cursor: default',
856 title=tip,
857 E.div(style=f'width: {BAR_W}px; height: {h}px; background-color: {color}; {outline}'),
858 E.div(label, style=f'font-size: 9px; text-align: center; width: {BAR_W}px; margin-top: 2px; overflow: hidden')
859 )
860 bars_row.appendChild(bar)
861 graph_section.appendChild(bars_row)
862 if current_idx >= 0:
863 scroll_offset = max(0, current_idx * (BAR_W + BAR_GAP) - 80)
864 window.setTimeout(def (): bars_row.scrollLeft=scroll_offset;, 0)
865 else:
866 graph_section.appendChild(E.div(
867 _('Start reading to see chapter time statistics'),
868 style='color: {}; font-style: italic'.format(get_color('faded-text'))))
869
870 legend = E.div(
871 style='display: flex; gap: 1em; margin-top: 0.5ex; font-size: smaller; flex-wrap: wrap',
872 E.span(E.span('■ ', style=f'color: {COLOR_ACTUAL}'), _('Actual time')),
873 E.span(E.span('■ ', style=f'color: {COLOR_CURRENT}'), _('Current chapter')),
874 E.span(E.span('■ ', style=f'color: {COLOR_ESTIMATED}'), _('Estimated')),
875 E.span(E.span('■ ', style=f'color: {COLOR_PAST_EST}'), _('Previous (estimated)')),
876 )
877 graph_section.appendChild(legend)
878 container.appendChild(graph_section)
879 container.appendChild(E.div(_(
880 'For reading stats, a "chapter" is a single internal file inside the larger book. If you'
881 ' see very few "chapters" above, then try converting your book to EPUB in calibre, that'
882 ' will often automatically split up the book into per chapter files.'),
883 style='padding: 0 1em 1em 1em; font-size: smaller'))
884 container.appendChild(E.div(
885 style='padding: 0 1em 1em 1em; display: flex; justify-content: flex-end',
886 create_button(_('Reset statistics'), 'trash', action=self.reset_stats)
887 ))
888 # }}}
889
890
891 class Overlay:
892 def __init__(self, view):
893 self.view = view
894 self.handling_context_menu_event = None
895 c = self.clear_container()
896 c.addEventListener('click', self.container_clicked)
897 c.addEventListener('contextmenu', self.oncontextmenu, {'passive': False})
898 self.panels = []
899
900 def oncontextmenu(self, evt):
901 if default_context_menu_should_be_allowed(evt):
902 return
903 evt.preventDefault()
904 self.handling_context_menu_event = evt
905 self.handle_escape()
906 self.handling_context_menu_event = None
907
908 def clear_container(self):
909 c = self.container
910 colors = viewer_chrome_colors()
911 clear(c)
912 c.style.backgroundColor = 'transparent'
913 c.style.color = colors.foreground
914 if c.style.display is not 'block':
915 c.style.display = 'block'
916 return c
917
918 @property
919 def container(self):
920 return document.getElementById('book-overlay')
921
922 @property
923 def is_visible(self):
924 return self.container.style.display is not 'none'
925
926 def update_visibility(self):
927 if self.panels.length:
928 self.container.style.display = 'block'
929 self.view.overlay_visibility_changed(True)
930 elif self.container.style.display is 'block':
931 self.container.style.display = 'none'
932 self.view.focus_iframe()
933 self.view.overlay_visibility_changed(False)
934
935 def container_clicked(self, evt):
936 if self.panels.length and jstype(self.panels[-1].on_container_click) is 'function':
937 self.panels[-1].on_container_click(evt)
938 else:
939 self.hide_current_panel()
940
941 def show_loading_message(self, msg):
942 if ui_operations.show_loading_message:
943 ui_operations.show_loading_message(msg)
944 else:
945 lm = LoadingMessage(msg, self.view.current_color_scheme)
946 self.panels.push(lm)
947 self.show_current_panel()
948
949 def hide_loading_message(self):
950 if ui_operations.show_loading_message:
951 ui_operations.show_loading_message(None)
952 else:
953 self.panels = [p for p in self.panels if not isinstance(p, LoadingMessage)]
954 self.show_current_panel()
955
956 def hide_current_panel(self):
957 p = self.panels.pop()
958 if p and callable(p.on_hide):
959 p.on_hide()
960 self.show_current_panel()
961
962 def handle_escape(self):
963 if self.panels.length:
964 p = self.panels[-1]
965 if not p.is_not_escapable:
966 if p.handle_escape:
967 p.handle_escape()
968 else:
969 self.hide_current_panel()
970 return True
971 return False
972
973 def show_current_panel(self):
974 if self.panels.length:
975 c = self.clear_container()
976 self.panels[-1].show(c)
977 self.update_visibility()
978
979 def show(self, elements):
980 self.panels = [MainOverlay(self, elements)]
981 self.show_current_panel()
982
983 def hide(self):
984 while self.panels.length:
985 self.hide_current_panel()
986 self.update_visibility()
987
988 def delete_book(self):
989 self.hide_current_panel()
990 self.panels = [DeleteBook(self)]
991 self.show_current_panel()
992
993 def reload_book(self):
994 self.hide_current_panel()
995 self.panels = [DeleteBook(self, _('Are you sure you want to reload this book?'), 'refresh', _('Reload book'), True)]
996 self.show_current_panel()
997
998 def open_book(self, closeable):
999 self.hide_current_panel()
1000 if jstype(closeable) is not 'boolean':
1001 closeable = True
1002 self.panels = [OpenBook(self, closeable)]
1003 self.show_current_panel()
1004
1005 def sync_book(self):
1006 self.hide_current_panel()
1007 self.panels = [SyncBook(self)]
1008 self.show_current_panel()
1009
1010 def show_toc(self):
1011 self.hide_current_panel()
1012 if runtime.is_standalone_viewer:
1013 ui_operations.toggle_toc()
1014 return
1015 self.panels.push(TOCOverlay(self))
1016 self.show_current_panel()
1017
1018 def toggle_reference_mode(self):
1019 self.hide_current_panel()
1020 self.view.toggle_reference_mode()
1021
1022 def show_bookmarks(self):
1023 self.hide_current_panel()
1024 if runtime.is_standalone_viewer:
1025 ui_operations.toggle_bookmarks()
1026 return
1027
1028 def do_it(action, data):
1029 self.panels.push(TOCOverlay(self, create_bookmarks_panel.bind(None, self.view.annotations_manager, data), _('Bookmarks')))
1030 self.show_current_panel()
1031 self.view.get_current_cfi('show-bookmarks', do_it)
1032
1033 def show_highlights(self):
1034 self.hide_current_panel()
1035 if ui_operations.toggle_highlights:
1036 self.hide()
1037 ui_operations.toggle_highlights()
1038 return
1039 self.panels.push(TOCOverlay(self, create_highlights_panel.bind(None, self.view.annotations_manager, self.hide_current_panel), _('Highlights')))
1040 self.show_current_panel()
1041
1042 def show_profiles(self):
1043 self.hide_current_panel()
1044 self.panels.push(ProfilesOverlay(self))
1045 self.show_current_panel()
1046
1047 def show_goto(self):
1048 self.hide_current_panel()
1049 self.panels.push(GotoOverlay(self))
1050 self.show_current_panel()
1051
1052 def _build_metadata_panel(self):
1053 from_read_book = short_uuid()
1054
1055 def show_metadata_overlay(mi, pathtoebook, calibre_book_in_library_url, lname, book_id, overlay, container):
1056 container_id = ensure_id(container)
1057 container.appendChild(E.div(class_=BD_CLASS_NAME, style='padding: 1ex 1em'))
1058 table = E.table(class_='metadata')
1059
1060 def handle_message(msg):
1061 data = msg.data
1062 if data.from_read_book is not from_read_book:
1063 return
1064 if data.type is 'edit_metadata_closed':
1065 ui_operations.stop_waiting_for_messages_from(this)
1066 self.hide_current_panel()
1067 return
1068 if data.type is 'update_cached_book_metadata' and data.metadata:
1069 if current_library_id() is data.library_id:
1070 mi = data.metadata
1071 book_id = int(data.book_id)
1072 set_book_metadata(book_id, mi)
1073 book = self.view.book
1074 if book and book.key[0] is data.library_id and book.key[1] is book_id:
1075 ui_operations.update_metadata(book, mi)
1076
1077 if not runtime.is_standalone_viewer and lname:
1078 container.lastChild.appendChild(E.div(
1079 style='text-align: right',
1080 E.a(_('Edit the metadata for this book in the library'), class_='blue-link', onclick=def ():
1081 container = document.getElementById(container_id)
1082 clear(container)
1083 container.appendChild(E.iframe(
1084 style='position: absolute; left: 0; top: 0; width: 100vw; height: 100vh; border-width: 0',
1085 src=query_as_href({
1086 'from_read_book': from_read_book, 'library_id': lname, 'book_id': book_id + ''}, 'edit_metadata')
1087 ))
1088 w = container.lastChild.contentWindow
1089 ui_operations.wait_for_messages_from(w, handle_message.bind(w))
1090 )
1091 ))
1092 container.lastChild.appendChild(table)
1093 render_metadata(mi, table, None, f'html {{ font-size: {document.documentElement.style.fontSize} }}')
1094 for a in table.querySelectorAll('a[href]'):
1095 a.removeAttribute('href')
1096 a.removeAttribute('title')
1097 a.classList.remove('blue-link')
1098 a.style.color = 'currentColor'
1099 a.style.textDecorationLine = 'none'
1100 if pathtoebook:
1101 container.lastChild.appendChild(E.div(
1102 style='margin-top: 1ex; padding-top: 1ex; border-top: solid 1px',
1103 _('Path:'), ' ',
1104 E.a(
1105 href='javascript: void(0)',
1106 class_='blue-link', title=_('Click to open the folder the book is in'),
1107 onclick=def ():
1108 ui_operations.show_book_folder()
1109 ,
1110 pathtoebook)
1111 )
1112 )
1113 if calibre_book_in_library_url:
1114 container.lastChild.appendChild(E.div(
1115 style='margin-top: 1ex; padding-top: 1ex;',
1116 E.a(
1117 href=calibre_book_in_library_url,
1118 class_='blue-link', title=_('Click to see this book in the main calibre program book list'),
1119 _('Show book in the main calibre program'))
1120 )
1121 )
1122
1123 book = self.view.book
1124 key = book.key or [None, 0]
1125 lname, book_id = key
1126 book_id = int(book_id or 0)
1127 panel = SimpleOverlay(
1128 self,
1129 show_metadata_overlay.bind(None, book.metadata, book.manifest.pathtoebook, book.calibre_book_in_library_url, lname, book_id),
1130 self.view.book.metadata.title
1131 )
1132 panel.from_read_book = from_read_book
1133 return panel
1134
1135 def show_metadata(self):
1136 self.hide_current_panel()
1137 self.panels.push(self._build_metadata_panel())
1138 self.show_current_panel()
1139
1140 def show_ask_for_location(self):
1141 self.hide_current_panel()
1142 self.panels.push(SimpleOverlay(
1143 self, create_location_overlay.bind(None, self.view.current_position_data, self.view.book), _('Go to location, position or reference…')))
1144 self.show_current_panel()
1145
1146 def show_page_list(self):
1147 self.hide_current_panel()
1148 self.panels.push(SimpleOverlay(
1149 self, create_page_list_overlay.bind(None, self.view.book), _('Go to page')))
1150 self.show_current_panel()
1151
1152 def show_search(self):
1153 self.hide()
1154 self.view.show_search()
1155
1156 def show_reading_stats(self):
1157 self.hide_current_panel()
1158 self.panels.push(ReadingStatsOverlay(self))
1159 self.show_current_panel()
1160
1161 def show_prefs(self):
1162 self.hide_current_panel()
1163 self.panels.push(PrefsOverlay(self))
1164 self.show_current_panel()
1165
1166 def show_library(self):
1167 self.hide_current_panel()
1168 book = self.view.book
1169 show_panel('book_list', {'library_id': book.key[0], 'book_id': book.key[1] + ''}, replace=False)
1170 ui_operations.close_book()
1171
1172 def show_book_page(self):
1173 self.hide_current_panel()
1174 self.view.open_book_page()
1175 ui_operations.close_book()
1176
1177 def show_font_size_chooser(self):
1178 self.hide_current_panel()
1179 self.panels.push(FontSizeOverlay(self))
1180 self.show_current_panel()
1181
1182 def show_word_actions(self, word):
1183 self.hide_current_panel()
1184 self.panels.push(WordActionsOverlay(word, self))
1185 self.show_current_panel()