Debian Codegraph @

src/pyj/read_book/ui.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3 # globals: __RENDER_VERSION__
4 from __python__ import hash_literals
5
6 import traceback
7 from elementmaker import E
8 from gettext import gettext as _
9
10 from ajax import ajax, ajax_send
11 from book_list.constants import read_book_container_id
12 from book_list.library_data import current_library_id, library_data
13 from book_list.router import home, push_state, read_book_mode, update_window_title
14 from book_list.ui import show_panel
15 from dom import clear
16 from image_popup import show_image
17 from modals import create_simple_dialog_markup, error_dialog
18 from read_book.db import get_db
19 from read_book.globals import ui_operations
20 from read_book.tts import Client
21 from read_book.view import View
22 from session import get_interface_data
23 from utils import debounce, full_screen_element, human_readable, request_full_screen
24 from widgets import create_button
25
26 RENDER_VERSION = __RENDER_VERSION__
27 MATHJAX_VERSION = '__MATHJAX_VERSION__'
28
29
30 class ReadUI:
31 def __init__(self):
32 self.base_url_data = {}
33 self.current_metadata = {'title': _('Unknown book')}
34 self.current_book_id = None
35 self.manifest_xhr = None
36 self.pending_load = None
37 self.downloads_in_progress = []
38 self.progress_id = 'book-load-progress'
39 self.display_id = 'book-iframe-container'
40 self.error_id = 'book-global-error-container'
41 self.stacked_widgets = [self.progress_id, self.display_id, self.error_id]
42 container = document.getElementById(read_book_container_id)
43
44 container.appendChild(E.div(
45 id=self.progress_id, style='display:none; text-align: center',
46 E.h3(style='margin-top:30vh; margin-bottom: 1ex;'),
47 E.progress(style='margin: 1ex'),
48 E.div(style='margin: 1ex')
49 ))
50
51 container.appendChild(E.div(
52 id=self.error_id, style='display:none;',
53 ))
54
55 container.appendChild(E.div(
56 id=self.display_id, style='display:none; overflow-x:hidden; width:100%; max-width:100%;',
57 ))
58 self.view = View(container.lastChild)
59 self.tts_client = Client()
60 self.windows_to_listen_for_messages_from = []
61 self.unsynced_amap = None
62 self.unsynced_indicator_active = False
63 self.unsynced_indicator_timer = None
64 window.addEventListener('resize', debounce(self.on_resize.bind(self), 250))
65 window.addEventListener('online', self._on_network_restored.bind(self))
66 window.addEventListener('message', self.message_from_other_window.bind(self))
67 self.db = get_db(self.db_initialized.bind(self), self.show_error.bind(self))
68 ui_operations.get_file = self.db.get_file
69 ui_operations.get_mathjax_files = self.db.get_mathjax_files
70 ui_operations.update_url_state = self.update_url_state.bind(self)
71 ui_operations.update_last_read_time = self.db.update_last_read_time
72 ui_operations.show_error = self.show_error.bind(self)
73 ui_operations.update_reading_rates = self.update_reading_rates.bind(self)
74 ui_operations.reset_reading_rates = self.reset_reading_rates.bind(self)
75 ui_operations.redisplay_book = self.redisplay_book.bind(self)
76 ui_operations.reload_book = self.reload_book.bind(self)
77 ui_operations.forward_gesture = self.forward_gesture.bind(self)
78 ui_operations.update_color_scheme = self.update_color_scheme.bind(self)
79 ui_operations.update_font_size = self.update_font_size.bind(self)
80 ui_operations.goto_cfi = self.goto_cfi.bind(self)
81 ui_operations.goto_frac = self.goto_frac.bind(self)
82 ui_operations.goto_book_position = self.goto_book_position.bind(self)
83 ui_operations.goto_reference = self.goto_reference.bind(self)
84 ui_operations.delete_book = self.delete_book.bind(self)
85 ui_operations.focus_iframe = self.focus_iframe.bind(self)
86 ui_operations.toggle_toc = self.toggle_toc.bind(self)
87 ui_operations.toggle_full_screen = self.toggle_full_screen.bind(self)
88 ui_operations.annots_changed = self.annots_changed.bind(self)
89 ui_operations.annotations_synced = self.annotations_synced.bind(self)
90 ui_operations.has_unsynced_changes = self.has_unsynced_changes.bind(self)
91 ui_operations.upload_pending_annotations = self.upload_pending_annotations.bind(self)
92 ui_operations.wait_for_messages_from = self.wait_for_messages_from.bind(self)
93 ui_operations.stop_waiting_for_messages_from = self.stop_waiting_for_messages_from.bind(self)
94 ui_operations.update_metadata = self.update_metadata.bind(self)
95 ui_operations.close_book = self.close_book.bind(self)
96 ui_operations.copy_image = self.copy_image.bind(self)
97 ui_operations.view_image = self.view_image.bind(self)
98 ui_operations.speak_simple_text = self.speak_simple_text.bind(self)
99 ui_operations.tts = self.tts.bind(self)
100 ui_operations.search_result_discovered = self.view.search_overlay.search_result_discovered
101 ui_operations.search_result_not_found = self.view.search_overlay.search_result_not_found
102 ui_operations.find_next = self.view.search_overlay.find_next
103 ui_operations.open_url = def (url):
104 window.open(url, '_blank')
105 ui_operations.show_help = def (which):
106 if which is 'viewer':
107 path = '/viewer.html'
108 else:
109 return
110 if get_interface_data().lang_code_for_user_manual:
111 path = f'/{get_interface_data().lang_code_for_user_manual}{path}'
112 url = 'https://manual.calibre-ebook.com' + path
113 window.open(url, '_blank')
114
115 ui_operations.copy_selection = def (text, html):
116 # try using document.execCommand which on chrome allows the
117 # copy on non-secure origin if this is close to a user
118 # interaction event
119 active_elem = document.activeElement
120 ta = document.createElement('textarea')
121 ta.value = text
122 ta.style.position = 'absolute'
123 ta.style.top = window.innerHeight + 'px'
124 ta.style.left = window.innerWidth + 'px'
125 document.body.appendChild(ta)
126 ta.focus()
127 ta.select()
128 ok = False
129 try:
130 ok = document.execCommand('copy')
131 except:
132 pass
133 document.body.removeChild(ta)
134 if active_elem:
135 active_elem.focus()
136 if ok:
137 return
138 if not window.navigator.clipboard:
139 return error_dialog(_('No clipboard access'), _(
140 'Your browser requires you to access the Content server over an HTTPS connection'
141 ' to be able to copy to clipboard.'))
142 window.navigator.clipboard.writeText(text or '').then(def (): pass;, def ():
143 error_dialog(_('Could not copy to clipboard'), _('No permission to write to clipboard'))
144 )
145
146 ui_operations.get_all_profiles = def (proceed):
147 ajax('reader-profiles/get-all', def (end_type, xhr, ev):
148 if end_type is not 'load':
149 if end_type is 'abort': return
150 return self.show_error(_('Failed to load profiles'), _(
151 'Could not load profiles: with error: {}').format(xhr.error_html))
152 try:
153 result = JSON.parse(xhr.responseText)
154 except Exception:
155 return self.show_error(_('Failed to parse profiles'), _('Unparsable data received for profiles'))
156 proceed(result)
157 ).send()
158
159 ui_operations.save_profile = def (profile_name, profile, proceed):
160 ajax_send('reader-profiles/save', {'name': profile_name, 'profile': profile}, def (end_type, xhr, ev):
161 if end_type is not 'load':
162 if end_type is 'abort': return
163 return self.show_error(_('Failed to load profiles'), _(
164 'Could not load profiles: with error: {}').format(xhr.error_html))
165 proceed()
166 )
167
168 def on_resize(self):
169 self.view.on_resize()
170
171 def show_stack(self, name):
172 ans = None
173 for w in self.stacked_widgets:
174 d = document.getElementById(w)
175 v = 'none'
176 if name is w:
177 ans = d
178 v = 'block'
179 d.style.display = v
180 return ans
181
182 def show_error(self, title, msg, details):
183 div = self.show_stack(self.error_id)
184 clear(div)
185 if self.current_metadata:
186 book = self.current_metadata.title
187 elif self.current_book_id:
188 book = _('Book id #{}').format(self.current_book_id)
189 else:
190 book = _('book')
191
192 div.appendChild(E.div(style='padding: 2ex 2rem; display:table; margin: auto'))
193 div = div.lastChild
194 dp = E.div()
195 create_simple_dialog_markup(title, _('Could not open {}. {}').format(book, msg), details, 'bug', '', 'red', dp)
196 div.appendChild(dp)
197 div.appendChild(E.div(
198 style='margin-top: 1ex; padding-top: 1ex; border-top: solid 1px currentColor',
199 _('Go back to:'), E.br(), E.br(),
200 create_button(_('Home'), 'home', def (): home(True);),
201 ))
202 q = {}
203 if self.current_book_id:
204 q.book_id = self.current_book_id + ''
205 q.close_action = 'home'
206 div.lastChild.appendChild(E.span(
207 '\xa0',
208 create_button(_('Book list'), 'library', def (): show_panel('book_list', q, True);),
209 ))
210 if self.current_book_id:
211 q.close_action = 'book_list'
212 div.lastChild.appendChild(E.span(
213 '\xa0',
214 create_button(_('Book details'), 'book', def (): show_panel('book_details', q, True);),
215 ))
216
217 def init_ui(self):
218 div = self.show_stack(self.progress_id)
219 if self.current_metadata:
220 div.firstChild.textContent = _(
221 'Downloading {0} for offline reading, please wait...').format(self.current_metadata.title)
222 else:
223 div.firstChild.textContent = ''
224 pr = div.firstChild.nextSibling
225 pr.removeAttribute('value'), pr.removeAttribute('max')
226 div.lastChild.textContent = _('Downloading book manifest...')
227
228 def show_progress_message(self, msg):
229 div = document.getElementById(self.progress_id)
230 div.lastChild.textContent = msg or ''
231
232 def close_book(self):
233 # Called when leaving reader mode: always stop any ongoing speech/audio.
234 try:
235 self.tts_client.stop()
236 except Exception:
237 pass
238 if self.view:
239 try:
240 self.view.read_aloud.hide()
241 except Exception:
242 pass
243 try:
244 self.view.read_audio_ebook.hide()
245 except Exception:
246 pass
247 self.base_url_data = {}
248
249 def copy_image(self, image_file_name):
250 if not self.view?.book:
251 return
252 ui_operations.get_file(
253 self.view.book, image_file_name, def (blob, name, mimetype):
254 try:
255 window.navigator.clipboard.write([new ClipboardItem({mimetype: blob})]) # noqa
256 except Exception as err:
257 error_dialog(_('Could not copy image'), str(err))
258 )
259
260 def view_image(self, image_file_name):
261 if not self.view?.book:
262 return
263 ui_operations.get_file(
264 self.view.book, image_file_name, def (blob, name, mimetype):
265 url = window.URL.createObjectURL(blob)
266 show_image(url)
267 )
268
269 def load_book(self, library_id, book_id, fmt, metadata, force_reload):
270 self.unsynced_amap = None
271 if self.unsynced_indicator_timer:
272 window.clearTimeout(self.unsynced_indicator_timer)
273 self.unsynced_indicator_timer = None
274 if self.unsynced_indicator_active:
275 self.unsynced_indicator_active = False
276 self.view.show_unsynced_indicator(False)
277 self.base_url_data = {'library_id': library_id, 'book_id': book_id, 'fmt': fmt}
278 if not self.db.initialized:
279 self.pending_load = [book_id, fmt, metadata, force_reload]
280 return
281 if not self.db.is_ok:
282 self.show_error(_('Cannot read books'), self.db.initialize_error_msg)
283 return
284 self.start_load(book_id, fmt, metadata, force_reload)
285
286 def reload_book(self):
287 library_id, book_id, fmt = self.base_url_data.library_id, self.base_url_data.book_id, self.base_url_data.fmt
288 metadata = self.metadata or library_data.metadata[book_id]
289 self.load_book(library_id, book_id, fmt, metadata, True)
290
291 def redisplay_book(self):
292 self.view.redisplay_book()
293
294 def forward_gesture(self, gesture):
295 self.view.forward_gesture(gesture)
296
297 def update_font_size(self):
298 self.view.update_font_size()
299
300 def goto_cfi(self, bookpos):
301 return self.view.goto_cfi(bookpos)
302
303 def goto_frac(self, frac):
304 return self.view.goto_frac(frac)
305
306 def goto_book_position(self, bpos):
307 return self.view.goto_book_position(bpos)
308
309 def goto_reference(self, ref):
310 return self.view.goto_reference(ref)
311
312 def delete_book(self, book, proceed):
313 self.db.delete_book(book, proceed)
314
315 def focus_iframe(self):
316 self.view.focus_iframe()
317
318 def toggle_toc(self):
319 self.view.overlay.show_toc()
320
321 def toggle_full_screen(self):
322 if full_screen_element():
323 document.exitFullscreen()
324 else:
325 request_full_screen(document.documentElement)
326
327 def update_color_scheme(self):
328 self.view.update_color_scheme()
329
330 def annots_changed(self, amap):
331 library_id = self.base_url_data.library_id
332 book_id = self.base_url_data.book_id
333 fmt = self.base_url_data.fmt
334 self.db.update_annotations_data_from_key(library_id, book_id, fmt, {'annotations_map': amap})
335 self.unsynced_amap = amap
336 self.db.set_pending_annot_upload(library_id, book_id, fmt, amap)
337 self._reschedule_unsynced_indicator()
338 ajax_send(f'book-update-annotations/{library_id}/{book_id}/{fmt}', amap,
339 self._make_annot_upload_done(library_id, book_id, fmt))
340
341 def _make_annot_upload_done(self, library_id, book_id, fmt):
342 def on_cleared():
343 if (self.unsynced_amap is not None and self.base_url_data
344 and self.base_url_data.library_id is library_id
345 and str(self.base_url_data.book_id) is str(book_id)
346 and self.base_url_data.fmt is fmt):
347 self.unsynced_amap = None
348 if self.unsynced_indicator_timer:
349 window.clearTimeout(self.unsynced_indicator_timer)
350 self.unsynced_indicator_timer = None
351 if self.unsynced_indicator_active:
352 self.unsynced_indicator_active = False
353 self.view.show_unsynced_indicator(False)
354 self._upload_next_from_idb()
355
356 def done(end_type, xhr, ev):
357 if end_type is 'load':
358 self.db.clear_pending_annot_upload(library_id, book_id, fmt, on_cleared)
359 return done
360
361 def _upload_next_from_idb(self):
362 self.db.get_all_pending_annot_uploads(def (entries):
363 if not entries.length:
364 return
365 e = entries[0]
366 if (self.base_url_data
367 and self.base_url_data.library_id is e.library_id
368 and str(self.base_url_data.book_id) is str(e.book_id)
369 and self.base_url_data.fmt is e.fmt):
370 self.unsynced_amap = e.amap
371 self._reschedule_unsynced_indicator()
372 ajax_send(f'book-update-annotations/{e.library_id}/{e.book_id}/{e.fmt}', e.amap,
373 self._make_annot_upload_done(e.library_id, e.book_id, e.fmt))
374 )
375
376 def has_unsynced_changes(self):
377 return self.unsynced_indicator_active
378
379 def _reschedule_unsynced_indicator(self):
380 if self.unsynced_indicator_timer:
381 window.clearTimeout(self.unsynced_indicator_timer)
382
383 def show_it():
384 self.unsynced_indicator_active = True
385 self.view.show_unsynced_indicator(True)
386 self.unsynced_indicator_timer = window.setTimeout(show_it, 60000)
387
388 def upload_pending_annotations(self, callback):
389 if self.unsynced_amap is not None:
390 library_id = self.base_url_data.library_id
391 book_id = self.base_url_data.book_id
392 fmt = self.base_url_data.fmt
393 amap = self.unsynced_amap
394 ajax_send(f'book-update-annotations/{library_id}/{book_id}/{fmt}', amap,
395 self._make_annot_upload_done(library_id, book_id, fmt))
396 callback(True)
397 return
398 # unsynced_amap is None — page may have been killed or this is another book
399 # check IDB for surviving entries
400 self.db.get_all_pending_annot_uploads(def (entries):
401 if not entries.length:
402 callback(True)
403 return
404 e = entries[0]
405 if (self.base_url_data
406 and self.base_url_data.library_id is e.library_id
407 and str(self.base_url_data.book_id) is str(e.book_id)
408 and self.base_url_data.fmt is e.fmt):
409 self.unsynced_amap = e.amap
410 self._reschedule_unsynced_indicator()
411 ajax_send(f'book-update-annotations/{e.library_id}/{e.book_id}/{e.fmt}', e.amap,
412 self._make_annot_upload_done(e.library_id, e.book_id, e.fmt))
413 callback(True)
414 )
415
416 def _on_network_restored(self):
417 self.upload_pending_annotations(def (ok): None;)
418
419 def annotations_synced(self, amap):
420 library_id = self.base_url_data.library_id
421 book_id = self.base_url_data.book_id
422 fmt = self.base_url_data.fmt
423 self.db.update_annotations_data_from_key(library_id, book_id, fmt, {'annotations_map': amap})
424
425 @property
426 def url_data(self):
427 ans = {'library_id': self.base_url_data.library_id, 'book_id': self.base_url_data.book_id, 'fmt': self.base_url_data.fmt}
428 bookpos = self.view.currently_showing.bookpos
429 if bookpos:
430 ans.bookpos = bookpos
431 return ans
432
433 def db_initialized(self):
434 if not self.db.is_ok:
435 error_dialog(_('Could not initialize database'), self.db.initialize_error_msg)
436 return
437 if self.pending_load is not None:
438 pl, self.pending_load = self.pending_load, None
439 if self.db.initialize_error_msg:
440 self.show_error(_('Failed to initialize IndexedDB'), self.db.initialize_error_msg)
441 else:
442 self.start_load(*pl)
443
444 def start_load(self, book_id, fmt, metadata, force_reload):
445 self.current_book_id = book_id
446 self.current_book_fmt = fmt
447 metadata = metadata or library_data.metadata[book_id]
448 self.current_metadata = metadata or {'title': _('Book id #') + book_id}
449 update_window_title('', self.current_metadata.title)
450 self.init_ui()
451 if jstype(self.db) is 'string':
452 self.show_error(_('Cannot read book'), self.db)
453 return
454 self.db.get_book(current_library_id(), book_id, fmt, metadata, self.got_book.bind(self, force_reload))
455
456 def got_book(self, force_reload, book):
457 if not book.manifest or book.manifest.version is not RENDER_VERSION or not book.is_complete:
458 # We re-download the manifest when the book is not complete to ensure we have the
459 # correct manifest, even though doing so is not strictly necessary
460 self.get_manifest(book, force_reload)
461 else:
462 self.display_book(book)
463
464 def get_manifest(self, book, force_reload):
465 library_id, book_id, fmt = book.key
466 if self.manifest_xhr:
467 self.manifest_xhr.abort()
468 query = {'library_id': library_id}
469 if force_reload:
470 query.force_reload = '1'
471 self.manifest_xhr = ajax(('book-manifest/' + encodeURIComponent(book_id) + '/' + encodeURIComponent(fmt)),
472 self.got_manifest.bind(self, book), query=query)
473 self.manifest_xhr.send()
474
475 def got_manifest(self, book, end_type, xhr, ev):
476 self.manifest_xhr = None
477 if end_type is 'abort':
478 return
479 if end_type is not 'load':
480 if xhr.status is 404:
481 fmt = (self.current_book_fmt or 'UNKNOWN').toUpperCase()
482 if 'cannot be viewed' in xhr.error_html:
483 return self.show_error(
484 _('Failed to view book'), _('Viewing of the {} format is not supported.').format(fmt), xhr.error_html)
485 return self.show_error(_('Failed to view book'), _('The {} format is not available.').format(fmt), xhr.error_html)
486 return self.show_error(_('Failed to load book manifest'),
487 _('The book manifest failed to load, click "Show details" for more information.').format(title=self.current_metadata.title),
488 xhr.error_html)
489 try:
490 manifest = JSON.parse(xhr.responseText)
491 except Exception:
492 return self.show_error(_('Failed to load book manifest'),
493 _('The manifest for {title} is not valid').format(title=self.current_metadata.title),
494 traceback.format_exc())
495 if manifest.version is not undefined:
496 if manifest.version is not RENDER_VERSION:
497 print('calibre upgraded: RENDER_VERSION={} manifest.version={}'.format(RENDER_VERSION, manifest.version))
498 return self.show_error(_('calibre upgraded!'), _(
499 'A newer version of calibre is available, please click the Reload button in your browser.'))
500 self.current_metadata = manifest.metadata
501 self.db.save_manifest(book, manifest, self.download_book.bind(self, book))
502 return
503 # Book is still being processed
504 msg = _('Downloading book manifest...')
505 if manifest.job_status is 'finished':
506 if manifest.aborted:
507 return self.show_error(_('Failed to prepare book for reading'), _('Preparation of book for reading was aborted because it took too long'))
508 if manifest.traceback:
509 return self.show_error(_('Failed to prepare book for reading'), _(
510 'There was an error processing the book, click "Show details" for more information'), manifest.traceback or '')
511 elif manifest.job_status is 'waiting':
512 msg = _('Book is queued for processing on the server...')
513 elif manifest.job_status is 'running':
514 msg = _('Book is being prepared for reading on the server...')
515 self.show_progress_message(msg)
516 setTimeout(self.get_manifest.bind(self, book), 100)
517
518 def download_book(self, book):
519 files = book.manifest.files
520 total = 0
521 cover_total_updated = False
522 for name in files:
523 total += files[name].size
524 files_left = set(book.manifest.files)
525 failed_files = []
526 for xhr in self.downloads_in_progress:
527 xhr.abort()
528 self.downloads_in_progress = []
529 progress = document.getElementById(self.progress_id)
530 pbar = progress.firstChild.nextSibling
531 library_id, book_id, fmt = book.key
532 base_path = 'book-file/{}/{}/{}/{}/'.format(encodeURIComponent(book_id), encodeURIComponent(fmt),
533 encodeURIComponent(book.manifest.book_hash.size), encodeURIComponent(book.manifest.book_hash.mtime))
534 query = {'library_id': library_id}
535 progress_track = {}
536 pbar.setAttribute('max', total + '')
537 raster_cover_name = book.manifest.raster_cover_name
538 if not raster_cover_name:
539 nnum = 1
540 base = 'raster-cover-image-{}.jpg'
541 inserted_name = base.format(nnum)
542 while inserted_name in files_left:
543 nnum += 1
544 inserted_name = base.format(nnum)
545 raster_cover_name = inserted_name
546 files_left.add(raster_cover_name)
547
548 raster_cover_size = 0
549
550 def update_progress():
551 x = 0
552 for name in progress_track:
553 x += progress_track[name]
554 pbar.setAttribute('value', x + '')
555 if x is total:
556 msg = _('Downloaded {}, saving to disk. This may take a few seconds...').format(human_readable(total))
557 else:
558 msg = _('Downloaded {0}, {1} left').format(human_readable(x), human_readable(total - x))
559 progress.lastChild.textContent = msg
560
561 def show_failure():
562 det = ['<h4>{}</h4><div>{}</div><hr>'.format(fname, err_html) for fname, err_html in failed_files].join('')
563 self.show_error(_('Could not download book'), _(
564 'Failed to download some book data, click "Show details" for more information'), det)
565
566 def on_stored(err):
567 files_left.discard(this)
568 if err:
569 failed_files.append([this, err])
570 if len(files_left):
571 return
572 if failed_files.length:
573 return show_failure()
574 self.db.finish_book(book, self.display_book.bind(self, book))
575
576 def on_complete(end_type, xhr, ev):
577 self.downloads_in_progress.remove(xhr)
578 progress_track[this] = raster_cover_size if this is raster_cover_name else files[this].size
579 update_progress()
580 if len(queued):
581 for fname in queued:
582 start_download(fname, base_path + encodeURIComponent(fname).replace(/%2[fF]/g, '/'))
583 queued.discard(fname)
584 break
585 if end_type is 'abort':
586 files_left.discard(this)
587 return
588 if end_type is 'load':
589 self.db.store_file(book, this, xhr, on_stored.bind(this), this is raster_cover_name)
590 else:
591 failed_files.append([this, xhr.error_html])
592 files_left.discard(this)
593 if not len(files_left):
594 show_failure()
595
596 def on_progress(loaded, ftotal):
597 nonlocal total, cover_total_updated, raster_cover_size
598 if this is raster_cover_name and not cover_total_updated:
599 raster_cover_size = ftotal
600 cover_total_updated = True
601 total = total - (files[raster_cover_name]?.size or 0) + raster_cover_size
602 pbar.setAttribute('max', total + '')
603 progress_track[this] = loaded
604 update_progress()
605
606 def start_download(fname, path):
607 xhr = ajax(path, on_complete.bind(fname), on_progress=on_progress.bind(fname), query=query, progress_totals_needed=fname is raster_cover_name)
608 xhr.responseType = 'text'
609 if not book.manifest.files[fname]?.is_virtualized:
610 xhr.responseType = 'blob' if self.db.supports_blobs else 'arraybuffer'
611 xhr.send()
612 self.downloads_in_progress.append(xhr)
613
614 if raster_cover_name:
615 start_download(raster_cover_name, 'get/cover/' + book_id + '/' + encodeURIComponent(library_id))
616
617 count = 0
618 queued = set()
619 for fname in files_left:
620 if fname is not raster_cover_name:
621 count += 1
622 # Chrome starts killing AJAX requests if there are too many in flight, unlike Firefox
623 # which is smart enough to queue them
624 if count < 20:
625 start_download(fname, base_path + encodeURIComponent(fname).replace(/%2[fF]/g, '/'))
626 else:
627 queued.add(fname)
628
629 def ensure_maths(self, proceed):
630 self.db.get_mathjax_info(def (mathjax_info):
631 if mathjax_info.version is MATHJAX_VERSION:
632 return proceed()
633 print('Upgrading MathJax, previous version:', mathjax_info.version)
634 self.db.clear_mathjax(def ():
635 self.get_mathjax_manifest(mathjax_info, proceed)
636 )
637 )
638
639 def get_mathjax_manifest(self, mathjax_info, proceed):
640 ajax('mathjax', def (end_type, xhr, event):
641 if end_type is 'abort':
642 return
643 if end_type is not 'load':
644 return self.show_error(_('Failed to load MathJax manifest'),
645 _('The MathJax manifest failed to load, click "Show details" for more information.').format(title=self.current_metadata.title),
646 xhr.error_html)
647 try:
648 manifest = JSON.parse(xhr.responseText)
649 except Exception:
650 return self.show_error(_('Failed to load MathJax manifest'),
651 _('The MathJax manifest is not valid'), traceback.format_exc())
652 if manifest.etag is not MATHJAX_VERSION:
653 print('calibre upgraded: MATHJAX_VERSION={} manifest.etag={}'.format(MATHJAX_VERSION, manifest.etag))
654 return self.show_error(_('calibre upgraded!'), _(
655 'A newer version of calibre is available, please click the Reload button in your browser.'))
656 mathjax_info.version = manifest.etag
657 mathjax_info.files = manifest.files
658 self.download_mathjax(mathjax_info, proceed)
659 ).send()
660
661 def download_mathjax(self, mathjax_info, proceed):
662 files = mathjax_info.files
663 total = 0
664 progress_track = {}
665 files_left = set()
666 failed_files = []
667 for key in files:
668 total += files[key]
669 progress_track[key] = 0
670 files_left.add(key)
671 progress = document.getElementById(self.progress_id)
672 progress.firstChild.textContent = _(
673 'Downloading MathJax to render mathematics in this book...')
674 pbar = progress.firstChild.nextSibling
675 pbar.setAttribute('max', total + '')
676 for xhr in self.downloads_in_progress:
677 xhr.abort()
678 self.downloads_in_progress = []
679
680 def update_progress():
681 x = 0
682 for name in progress_track:
683 x += progress_track[name]
684 pbar.setAttribute('value', x + '')
685 if x is total:
686 msg = _('Downloaded {}, saving to disk. This may take a few seconds...').format(human_readable(total))
687 else:
688 msg = _('Downloaded {0}, {1} left').format(human_readable(x), human_readable(total - x))
689 progress.lastChild.textContent = msg
690
691 def on_progress(loaded, ftotal):
692 progress_track[this] = loaded
693 update_progress()
694
695 def show_failure():
696 det = ['<h4>{}</h4><div>{}</div><hr>'.format(fname, err_html) for fname, err_html in failed_files].join('')
697 self.show_error(_('Could not download MathJax'), _(
698 'Failed to download some MathJax data, click "Show details" for more information'), det)
699
700 def on_complete(end_type, xhr, ev):
701 self.downloads_in_progress.remove(xhr)
702 progress_track[this] = files[this]
703 update_progress()
704 if end_type is 'abort':
705 files_left.discard(this)
706 return
707 if end_type is 'load':
708 self.db.store_mathjax_file(this, xhr, on_stored.bind(this))
709 else:
710 failed_files.append([this, xhr.error_html])
711 files_left.discard(this)
712 if not len(files_left):
713 show_failure()
714
715 def on_stored(err):
716 files_left.discard(this)
717 if err:
718 failed_files.append([this, err])
719 if len(files_left):
720 return
721 if failed_files.length:
722 return show_failure()
723 self.db.finish_mathjax(mathjax_info, proceed)
724
725 def start_download(name):
726 path = 'mathjax/' + name
727 xhr = ajax(path, on_complete.bind(name), on_progress=on_progress.bind(name), progress_totals_needed=False)
728 xhr.responseType = 'blob' if self.db.supports_blobs else 'arraybuffer'
729 xhr.send()
730 self.downloads_in_progress.push(xhr)
731
732 for fname in files_left:
733 start_download(fname)
734
735 def display_book(self, book):
736 if book.manifest.has_maths:
737 self.ensure_maths(self.display_book_stage2.bind(self, book))
738 else:
739 self.display_book_stage2(book)
740
741 def display_book_stage2(self, book):
742 self.current_metadata = book.metadata
743 update_window_title('', self.current_metadata.title)
744 self.show_stack(self.display_id)
745 self.view.display_book(book)
746 if window.navigator.onLine:
747 self.upload_pending_annotations(def (ok): None;)
748
749 def apply_url_state(self, current_query):
750 same = True
751 current_state = self.url_data
752 same = (current_query.library_id is current_state.library_id
753 and str(current_query.book_id) is str(current_state.book_id)
754 and current_query.fmt is current_state.fmt)
755 self.view.overlay.hide()
756 window.scrollTo(0, 0) # Ensure we are at the top of the window
757 if same:
758 if current_state.bookpos is not current_query.bookpos and current_query.bookpos:
759 self.view.goto_cfi(current_query.bookpos)
760 else:
761 self.load_book(current_query.library_id, int(current_query.book_id), current_query.fmt, library_data.metadata[current_query.book_id])
762
763 def update_url_state(self, replace):
764 push_state(self.url_data, replace=replace, mode=read_book_mode)
765
766 def update_metadata(self, book, metadata):
767 self.db.update_metadata(book, metadata)
768
769 def wait_for_messages_from(self, w, callback):
770 self.windows_to_listen_for_messages_from.push([w, callback])
771
772 def stop_waiting_for_messages_from(self, w):
773 self.windows_to_listen_for_messages_from = [x for x in self.windows_to_listen_for_messages_from if x[0] is not w]
774
775 def message_from_other_window(self, msg):
776 if not self.windows_to_listen_for_messages_from.length:
777 return
778 old = self.windows_to_listen_for_messages_from
779 for x in old:
780 w, callback = x
781 if w is msg.source:
782 callback(msg)
783
784 def check_for_speech_capability(self):
785 if not window.speechSynthesis:
786 error_dialog(_('No speech support'), _(
787 'Your browser does not have support for Text-to-Speech'))
788 return False
789 return True
790
791 def speak_simple_text(self, text):
792 if not self.check_for_speech_capability():
793 return
794 self.tts_client.speak_simple_text(text)
795
796 def tts(self, event, data):
797 if not self.check_for_speech_capability():
798 return
799 if event is 'play':
800 self.tts_client.speak_marked_text(data.marked_text, self.view.read_aloud.handle_tts_event)
801 else:
802 getattr(self.tts_client, event)()
803
804 def update_reading_rates(self, rates):
805 if not self.view?.book:
806 return
807 book = self.view.book
808 self.db.save_reading_rates(book, rates)
809
810 def reset_reading_rates(self):
811 if not self.view?.book:
812 return
813 book = self.view.book
814 self.db.save_reading_rates(book, v'{}')