| 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 |
import traceback |
| 6 |
|
| 7 |
from fs_images import fix_fullscreen_svg_images |
| 8 |
from iframe_comm import IframeClient |
| 9 |
from range_utils import ( |
| 10 |
all_annots_in_selection, |
| 11 |
highlight_associated_with_selection, |
| 12 |
last_span_for_crw, |
| 13 |
reset_highlight_counter, |
| 14 |
select_crw, |
| 15 |
set_title_for_crw, |
| 16 |
unwrap_all_crw, |
| 17 |
unwrap_crw, |
| 18 |
wrap_text_in_range |
| 19 |
) |
| 20 |
from read_book.anchor_visibility import ensure_page_list_target_is_displayed, invalidate_anchor_position_cache |
| 21 |
from read_book.cfi import cfi_for_selection, range_from_cfi |
| 22 |
from read_book.extract import get_elements |
| 23 |
from read_book.find import first_tts_word_after_viewport_start, reset_find_caches, select_search_result, select_tts_mark, tts_data |
| 24 |
from read_book.flow_mode import anchor_funcs as flow_anchor_funcs |
| 25 |
from read_book.flow_mode import auto_scroll_action as flow_auto_scroll_action |
| 26 |
from read_book.flow_mode import cancel_drag_scroll as cancel_drag_scroll_flow |
| 27 |
from read_book.flow_mode import ensure_selection_boundary_visible as ensure_selection_boundary_visible_flow |
| 28 |
from read_book.flow_mode import ensure_selection_visible, flow_onwheel, flow_to_scroll_fraction |
| 29 |
from read_book.flow_mode import handle_gesture as flow_handle_gesture |
| 30 |
from read_book.flow_mode import handle_shortcut as flow_handle_shortcut |
| 31 |
from read_book.flow_mode import jump_to_cfi as flow_jump_to_cfi |
| 32 |
from read_book.flow_mode import layout as flow_layout |
| 33 |
from read_book.flow_mode import scroll_by_page as flow_scroll_by_page |
| 34 |
from read_book.flow_mode import scroll_to_extend_annotation as flow_annotation_scroll |
| 35 |
from read_book.flow_mode import start_drag_scroll as start_drag_scroll_flow |
| 36 |
from read_book.footnotes import is_footnote_link |
| 37 |
from read_book.gestures import action_for_gesture |
| 38 |
from read_book.globals import ( |
| 39 |
annot_id_uuid_map, |
| 40 |
clear_annot_id_uuid_map, |
| 41 |
current_book, |
| 42 |
current_layout_mode, |
| 43 |
current_spine_item, |
| 44 |
runtime, |
| 45 |
set_boss, |
| 46 |
set_current_spine_item, |
| 47 |
set_layout_mode, |
| 48 |
set_toc_anchor_map |
| 49 |
) |
| 50 |
from read_book.highlights import highlight_style_as_css |
| 51 |
from read_book.hints import apply_prefix_to_hints, hint_visible_links, unhint_links |
| 52 |
from read_book.mathjax import apply_mathjax |
| 53 |
from read_book.paged_mode import anchor_funcs as paged_anchor_funcs |
| 54 |
from read_book.paged_mode import auto_scroll_action as paged_auto_scroll_action |
| 55 |
from read_book.paged_mode import ( |
| 56 |
calc_columns_per_screen, |
| 57 |
current_cfi, |
| 58 |
get_columns_per_screen_data, |
| 59 |
page_counts, |
| 60 |
progress_frac, |
| 61 |
reset_paged_mode_globals, |
| 62 |
scroll_to_elem, |
| 63 |
snap_to_selection, |
| 64 |
will_columns_per_screen_change |
| 65 |
) |
| 66 |
from read_book.paged_mode import cancel_drag_scroll as cancel_drag_scroll_paged |
| 67 |
from read_book.paged_mode import ensure_selection_boundary_visible as ensure_selection_boundary_visible_paged |
| 68 |
from read_book.paged_mode import handle_gesture as paged_handle_gesture |
| 69 |
from read_book.paged_mode import handle_shortcut as paged_handle_shortcut |
| 70 |
from read_book.paged_mode import jump_to_cfi as paged_jump_to_cfi |
| 71 |
from read_book.paged_mode import layout as paged_layout |
| 72 |
from read_book.paged_mode import onwheel as paged_onwheel |
| 73 |
from read_book.paged_mode import prepare_for_resize as paged_prepare_for_resize |
| 74 |
from read_book.paged_mode import resize_done as paged_resize_done |
| 75 |
from read_book.paged_mode import scroll_by_page as paged_scroll_by_page |
| 76 |
from read_book.paged_mode import scroll_to_extend_annotation as paged_annotation_scroll |
| 77 |
from read_book.paged_mode import scroll_to_fraction as paged_scroll_to_fraction |
| 78 |
from read_book.paged_mode import start_drag_scroll as start_drag_scroll_paged |
| 79 |
from read_book.referencing import elem_for_ref, end_reference_mode, start_reference_mode |
| 80 |
from read_book.resources import finalize_resources, unserialize_html |
| 81 |
from read_book.settings import ( |
| 82 |
apply_colors, |
| 83 |
apply_font_size, |
| 84 |
apply_settings, |
| 85 |
apply_stylesheet, |
| 86 |
opts, |
| 87 |
set_color_scheme_class, |
| 88 |
set_selection_style, |
| 89 |
update_settings |
| 90 |
) |
| 91 |
from read_book.shortcuts import create_shortcut_map, keyevent_as_shortcut, shortcut_for_key_event |
| 92 |
from read_book.smil import flatten_smil_map, mark_smil_element, smil_element_at |
| 93 |
from read_book.toc import find_anchor_before_range, update_visible_toc_anchors |
| 94 |
from read_book.touch import create_handlers as create_touch_handlers |
| 95 |
from read_book.touch import reset_handlers as reset_touch_handlers |
| 96 |
from read_book.viewport import scroll_viewport |
| 97 |
from select import first_visible_word, is_start_closer_to_point, move_end_of_selection, selection_extents, word_at_point |
| 98 |
from utils import debounce, is_ios |
| 99 |
|
| 100 |
FORCE_FLOW_MODE = False |
| 101 |
CALIBRE_VERSION = '__CALIBRE_VERSION__' |
| 102 |
ONSCROLL_DEBOUNCE_TIME = 1000 |
| 103 |
ERS_SUPPORTED_FEATURES = {'dom-manipulation', 'layout-changes', 'touch-events', 'mouse-events', 'keyboard-events', 'spine-scripting'} |
| 104 |
|
| 105 |
|
| 106 |
def layout_style(): |
| 107 |
return 'scrolling' if current_layout_mode() is 'flow' else 'paginated' |
| 108 |
|
| 109 |
|
| 110 |
drag_mouse_position = {'x': None, 'y': None} |
| 111 |
|
| 112 |
|
| 113 |
def cancel_drag_scroll(): |
| 114 |
cancel_drag_scroll_flow() |
| 115 |
cancel_drag_scroll_paged() |
| 116 |
|
| 117 |
|
| 118 |
class EPUBReadingSystem: |
| 119 |
@property |
| 120 |
def name(self): |
| 121 |
return 'calibre' |
| 122 |
|
| 123 |
@property |
| 124 |
def version(self): |
| 125 |
return CALIBRE_VERSION |
| 126 |
|
| 127 |
@property |
| 128 |
def layoutStyle(self): |
| 129 |
return layout_style() |
| 130 |
|
| 131 |
def hasFeature(self, feature, version): |
| 132 |
return feature in ERS_SUPPORTED_FEATURES |
| 133 |
|
| 134 |
def __repr__(self): |
| 135 |
return f'{{name:{self.name}, version:{self.version}, layoutStyle:{self.layoutStyle}}}' |
| 136 |
|
| 137 |
def __str__(self): |
| 138 |
return self.__repr__() |
| 139 |
|
| 140 |
|
| 141 |
class FullBookSearch: |
| 142 |
def __init__(self): |
| 143 |
start_spine_index = current_spine_item()?.index |
| 144 |
if not start_spine_index?: |
| 145 |
start_spine_index = -1 |
| 146 |
self.start_spine_index = start_spine_index |
| 147 |
self.progress_frac_at_start = progress_frac() |
| 148 |
self.first_result_shown = False |
| 149 |
|
| 150 |
|
| 151 |
class IframeBoss: |
| 152 |
def __init__(self): |
| 153 |
window.navigator.epubReadingSystem = EPUBReadingSystem() |
| 154 |
self.last_cfi = None |
| 155 |
self.last_search_at = -1001 |
| 156 |
self.reference_mode_enabled = False |
| 157 |
self.replace_history_on_next_cfi_update = True |
| 158 |
self.blob_url_map = {} |
| 159 |
self.content_ready = False |
| 160 |
self.last_window_width = self.last_window_height = -1 |
| 161 |
self.forward_keypresses = False |
| 162 |
self.full_book_search_in_progress = None |
| 163 |
set_boss(self) |
| 164 |
handlers = { |
| 165 |
'change_color_scheme': self.change_color_scheme, |
| 166 |
'change_font_size': self.change_font_size, |
| 167 |
'viewer_font_size_changed': self.viewer_font_size_changed, |
| 168 |
'change_number_of_columns': self.change_number_of_columns, |
| 169 |
'number_of_columns_changed': self.number_of_columns_changed, |
| 170 |
'change_scroll_speed': self.change_scroll_speed, |
| 171 |
'display': self.display, |
| 172 |
'gesture_from_margin': self.gesture_from_margin, |
| 173 |
'native_gesture': self.native_gesture, |
| 174 |
'get_current_cfi': self.get_current_cfi, |
| 175 |
'initialize': self.initialize, |
| 176 |
'modify_selection': self.modify_selection, |
| 177 |
'next_screen': self.on_next_screen, |
| 178 |
'scroll_to_anchor': self.on_scroll_to_anchor, |
| 179 |
'scroll_to_frac': self.on_scroll_to_frac, |
| 180 |
'scroll_to_ref': self.on_scroll_to_ref, |
| 181 |
'fake_popup_activation': self.on_fake_popup_activation, |
| 182 |
'set_reference_mode': self.set_reference_mode, |
| 183 |
'toggle_autoscroll': self.toggle_autoscroll, |
| 184 |
'fake_wheel_event': self.fake_wheel_event, |
| 185 |
'window_size': self.received_window_size, |
| 186 |
'overlay_visibility_changed': self.on_overlay_visibility_changed, |
| 187 |
'show_search_result': self.show_search_result, |
| 188 |
'handle_navigation_shortcut': self.on_handle_navigation_shortcut, |
| 189 |
'annotations': self.annotations_msg_received, |
| 190 |
'tts': self.tts_msg_received, |
| 191 |
'audio-ebook': self.audio_ebook_msg_received, |
| 192 |
'hints': self.hints_msg_received, |
| 193 |
'copy_selection': self.copy_selection, |
| 194 |
'replace_highlights': self.replace_highlights, |
| 195 |
'clear_selection': def (): window.getSelection().removeAllRanges();, |
| 196 |
} |
| 197 |
self.comm = IframeClient(handlers, 'main-iframe') |
| 198 |
self.last_window_ypos = 0 |
| 199 |
self.length_before = None |
| 200 |
|
| 201 |
def on_overlay_visibility_changed(self, data): |
| 202 |
cancel_drag_scroll() |
| 203 |
if data.visible: |
| 204 |
self.forward_keypresses = True |
| 205 |
if self.auto_scroll_action: |
| 206 |
self.auto_scroll_active_before_overlay = self.auto_scroll_action('is_active') |
| 207 |
self.auto_scroll_action('stop') |
| 208 |
else: |
| 209 |
self.forward_keypresses = False |
| 210 |
if self.auto_scroll_active_before_overlay: |
| 211 |
self.auto_scroll_active_before_overlay = undefined |
| 212 |
self.auto_scroll_action('start') |
| 213 |
|
| 214 |
def modify_selection(self, data): |
| 215 |
sel = window.getSelection() |
| 216 |
use_end = False |
| 217 |
if data.granularity is 'all': |
| 218 |
r = document.createRange() |
| 219 |
r.selectNode(document.body) |
| 220 |
sel.removeAllRanges() |
| 221 |
sel.addRange(r) |
| 222 |
else: |
| 223 |
use_end = data.direction is 'forward' or data.direction is 'right' |
| 224 |
try: |
| 225 |
sel.modify('extend', data.direction, data.granularity) |
| 226 |
except: |
| 227 |
if data.granularity is 'paragraph': |
| 228 |
sel.modify('extend', data.direction, 'line') |
| 229 |
self.ensure_selection_boundary_visible(use_end) |
| 230 |
|
| 231 |
def initialize(self, data): |
| 232 |
scroll_viewport.update_window_size(data.width, data.height) |
| 233 |
window.addEventListener('error', self.onerror) |
| 234 |
window.addEventListener('scroll', debounce(self.onscroll, ONSCROLL_DEBOUNCE_TIME)) |
| 235 |
window.addEventListener('scroll', self.no_latency_onscroll) |
| 236 |
window.addEventListener('resize', debounce(self.onresize, 500)) |
| 237 |
window.addEventListener('wheel', self.onwheel, {'passive': False}) |
| 238 |
window.addEventListener('keydown', self.onkeydown, {'passive': False}) |
| 239 |
window.addEventListener('mousemove', self.onmousemove, {'passive': True}) |
| 240 |
window.addEventListener('mouseup', self.onmouseup, {'passive': True}) |
| 241 |
window.addEventListener('dblclick', self.ondoubleclick, {'passive': True}) |
| 242 |
document.documentElement.addEventListener('contextmenu', self.oncontextmenu, {'passive': False}) |
| 243 |
document.addEventListener('selectionchange', self.onselectionchange) |
| 244 |
self.color_scheme = data.color_scheme |
| 245 |
create_touch_handlers() |
| 246 |
|
| 247 |
def onerror(self, evt): |
| 248 |
msg = evt.message |
| 249 |
script_url = evt.filename |
| 250 |
line_number = evt.lineno |
| 251 |
column_number = evt.colno |
| 252 |
error_object = evt.error |
| 253 |
evt.stopPropagation(), evt.preventDefault() |
| 254 |
if error_object is None: |
| 255 |
# This happens for cross-domain errors (probably javascript injected |
| 256 |
# into the browser via extensions/ userscripts and the like). It also |
| 257 |
# happens all the time when using Chrome on Safari, so ignore this |
| 258 |
# type of error |
| 259 |
console.log(f'Unhandled error from external javascript, ignoring: {msg} {script_url} {line_number}') |
| 260 |
return |
| 261 |
is_internal_error = script_url in ('about:srcdoc', 'userscript:viewer.js') |
| 262 |
if is_internal_error: # don't report errors from scripts in the book itself |
| 263 |
try: |
| 264 |
(console.error or console.log)(error_object) |
| 265 |
self.send_message('error', errkey='unhandled-error', msg=msg, |
| 266 |
script_url=script_url, line_number=line_number, column_number=column_number, |
| 267 |
error_object=traceback.serialize_error_for_formatting(error_object)) |
| 268 |
except: |
| 269 |
console.log('There was an error in the iframe unhandled exception handler') |
| 270 |
else: |
| 271 |
(console.error or console.log)('There was an error in the JavaScript from within the book') |
| 272 |
(console.error or console.log)(error_object) |
| 273 |
|
| 274 |
def display(self, data): |
| 275 |
cancel_drag_scroll() |
| 276 |
drag_mouse_position.x = drag_mouse_position.y = None |
| 277 |
self.length_before = None |
| 278 |
self.content_ready = False |
| 279 |
clear_annot_id_uuid_map() |
| 280 |
reset_highlight_counter() |
| 281 |
set_toc_anchor_map() |
| 282 |
self.replace_history_on_next_cfi_update = True |
| 283 |
self.book = current_book.book = data.book |
| 284 |
self.smil_map = data.smil_map |
| 285 |
self.smil_anchor_map, self.smil_par_list = flatten_smil_map(self.smil_map) |
| 286 |
self.link_attr = 'data-' + self.book.manifest.link_uid |
| 287 |
self.reference_mode_enabled = data.reference_mode_enabled |
| 288 |
self.is_titlepage = data.is_titlepage |
| 289 |
spine = self.book.manifest.spine |
| 290 |
index = spine.indexOf(data.name) |
| 291 |
reset_paged_mode_globals() |
| 292 |
set_layout_mode('flow' if FORCE_FLOW_MODE else data.settings.read_mode) |
| 293 |
if current_layout_mode() is 'flow': |
| 294 |
self.do_layout = flow_layout |
| 295 |
self.handle_wheel = flow_onwheel |
| 296 |
self.handle_navigation_shortcut = flow_handle_shortcut |
| 297 |
self._handle_gesture = flow_handle_gesture |
| 298 |
self.to_scroll_fraction = flow_to_scroll_fraction |
| 299 |
self.jump_to_cfi = flow_jump_to_cfi |
| 300 |
self.anchor_funcs = flow_anchor_funcs |
| 301 |
self.auto_scroll_action = flow_auto_scroll_action |
| 302 |
self.scroll_to_extend_annotation = flow_annotation_scroll |
| 303 |
self.ensure_selection_visible = ensure_selection_visible |
| 304 |
self.ensure_selection_boundary_visible = ensure_selection_boundary_visible_flow |
| 305 |
self.start_drag_scroll = start_drag_scroll_flow |
| 306 |
paged_auto_scroll_action('stop') |
| 307 |
else: |
| 308 |
self.do_layout = paged_layout |
| 309 |
self.handle_wheel = paged_onwheel |
| 310 |
self.handle_navigation_shortcut = paged_handle_shortcut |
| 311 |
self.to_scroll_fraction = paged_scroll_to_fraction |
| 312 |
self.jump_to_cfi = paged_jump_to_cfi |
| 313 |
self._handle_gesture = paged_handle_gesture |
| 314 |
self.anchor_funcs = paged_anchor_funcs |
| 315 |
self.auto_scroll_action = paged_auto_scroll_action |
| 316 |
self.scroll_to_extend_annotation = paged_annotation_scroll |
| 317 |
self.ensure_selection_visible = snap_to_selection |
| 318 |
self.ensure_selection_boundary_visible = ensure_selection_boundary_visible_paged |
| 319 |
self.start_drag_scroll = start_drag_scroll_paged |
| 320 |
flow_auto_scroll_action('stop') |
| 321 |
update_settings(data.settings) |
| 322 |
self.keyboard_shortcut_map = create_shortcut_map(data.settings.keyboard_shortcuts) |
| 323 |
set_current_spine_item({ |
| 324 |
'name': data.name, |
| 325 |
'is_first': index is 0, |
| 326 |
'is_last': index is spine.length - 1, |
| 327 |
'index': index, |
| 328 |
'initial_position': data.initial_position |
| 329 |
}) |
| 330 |
self.last_cfi = None |
| 331 |
for name in self.blob_url_map: |
| 332 |
window.URL.revokeObjectURL(self.blob_url_map[name]) |
| 333 |
document.body.style.removeProperty('font-family') |
| 334 |
root_data, self.mathjax, self.blob_url_map = finalize_resources(self.book, data.name, data.resource_data) |
| 335 |
self.highlights_to_apply = data.highlights |
| 336 |
unserialize_html(root_data, self.content_loaded, None, data.name) |
| 337 |
|
| 338 |
def on_scroll_to_frac(self, data): |
| 339 |
self.to_scroll_fraction(data.frac, False) |
| 340 |
|
| 341 |
def toggle_autoscroll(self): |
| 342 |
self.auto_scroll_action('toggle') |
| 343 |
|
| 344 |
def handle_gesture(self, gesture): |
| 345 |
gesture.resolved_action = action_for_gesture(gesture, current_layout_mode() is 'flow') |
| 346 |
if gesture.resolved_action is 'show_chrome': |
| 347 |
self.send_message('show_chrome') |
| 348 |
elif gesture.resolved_action is 'decrease_font_size': |
| 349 |
self.send_message('bump_font_size', increase=False) |
| 350 |
elif gesture.resolved_action is 'increase_font_size': |
| 351 |
self.send_message('bump_font_size', increase=True) |
| 352 |
elif gesture.resolved_action is 'highlight_or_inspect': |
| 353 |
self.handle_long_tap(gesture) |
| 354 |
else: |
| 355 |
self._handle_gesture(gesture) |
| 356 |
|
| 357 |
def handle_long_tap(self, gesture): |
| 358 |
elements = get_elements(gesture.viewport_x, gesture.viewport_y) |
| 359 |
if elements.img: |
| 360 |
self.send_message('view_image', calibre_src=elements.img) |
| 361 |
return |
| 362 |
if elements.highlight: |
| 363 |
select_crw(elements.crw) |
| 364 |
return |
| 365 |
r = word_at_point(gesture.viewport_x, gesture.viewport_y) |
| 366 |
if r: |
| 367 |
s = document.getSelection() |
| 368 |
s.removeAllRanges() |
| 369 |
s.addRange(r) |
| 370 |
|
| 371 |
def gesture_from_margin(self, data): |
| 372 |
self.handle_gesture(data.gesture) |
| 373 |
|
| 374 |
def native_gesture(self, data): |
| 375 |
self.handle_gesture(data.gesture) |
| 376 |
|
| 377 |
def fake_wheel_event(self, data): |
| 378 |
# these are wheel events from margin or selection mode |
| 379 |
self.onwheel(data.evt) |
| 380 |
|
| 381 |
def report_human_scroll(self, scrolled_by_frac): |
| 382 |
self.send_message('human_scroll', scrolled_by_frac=scrolled_by_frac or None) |
| 383 |
|
| 384 |
def on_scroll_to_anchor(self, data): |
| 385 |
frag = data.frag |
| 386 |
if frag: |
| 387 |
self.replace_history_on_next_cfi_update = False |
| 388 |
self.scroll_to_anchor(frag) |
| 389 |
else: |
| 390 |
self.to_scroll_fraction(0.0, False) |
| 391 |
|
| 392 |
def on_next_screen(self, data): |
| 393 |
backwards = data.backwards |
| 394 |
if current_layout_mode() is 'flow': |
| 395 |
flow_scroll_by_page(-1 if backwards else 1, data.flip_if_rtl_page_progression) |
| 396 |
else: |
| 397 |
paged_scroll_by_page(backwards, data.all_pages_on_screen, data.flip_if_rtl_page_progression) |
| 398 |
|
| 399 |
def change_font_size(self, data): |
| 400 |
if data.base_font_size? and data.base_font_size != opts.base_font_size: |
| 401 |
opts.base_font_size = data.base_font_size |
| 402 |
apply_font_size() |
| 403 |
if not runtime.is_standalone_viewer: |
| 404 |
# in the standalone viewer this is a separate event as |
| 405 |
# apply_font_size() is a no-op |
| 406 |
self.relayout_on_font_size_change() |
| 407 |
|
| 408 |
def viewer_font_size_changed(self, data): |
| 409 |
self.relayout_on_font_size_change() |
| 410 |
|
| 411 |
def change_number_of_columns(self, data): |
| 412 |
if current_layout_mode() is 'flow': |
| 413 |
self.send_message('error', errkey='changing-columns-in-flow-mode') |
| 414 |
return |
| 415 |
cdata = get_columns_per_screen_data() |
| 416 |
delta = int(data.delta) |
| 417 |
if delta is 0: |
| 418 |
new_val = 0 |
| 419 |
else: |
| 420 |
new_val = max(1, cdata.cps + delta) |
| 421 |
opts.columns_per_screen[cdata.which] = new_val |
| 422 |
self.relayout_on_font_size_change() |
| 423 |
self.send_message('columns_per_screen_changed', which=cdata.which, cps=new_val) |
| 424 |
|
| 425 |
def relayout_on_font_size_change(self): |
| 426 |
if current_layout_mode() is not 'flow' and will_columns_per_screen_change(): |
| 427 |
self.do_layout(self.is_titlepage) |
| 428 |
if self.last_cfi: |
| 429 |
cfi = self.last_cfi[len('epubcfi(/'):-1].partition('/')[2] |
| 430 |
if cfi: |
| 431 |
self.jump_to_cfi('/' + cfi) |
| 432 |
self.update_cfi() |
| 433 |
invalidate_anchor_position_cache() |
| 434 |
self.update_toc_position(True) |
| 435 |
|
| 436 |
def number_of_columns_changed(self, data): |
| 437 |
opts.columns_per_screen = data.columns_per_screen |
| 438 |
self.relayout_on_font_size_change() |
| 439 |
|
| 440 |
def change_scroll_speed(self, data): |
| 441 |
if data.lines_per_sec_auto?: |
| 442 |
opts.lines_per_sec_auto = data.lines_per_sec_auto |
| 443 |
|
| 444 |
def change_stylesheet(self, data): |
| 445 |
opts.user_stylesheet = data.sheet or '' |
| 446 |
apply_stylesheet() |
| 447 |
|
| 448 |
def change_color_scheme(self, data): |
| 449 |
if data.color_scheme and data.color_scheme.foreground and data.color_scheme.background: |
| 450 |
opts.color_scheme = data.color_scheme |
| 451 |
opts.is_dark_theme = v'!!data.color_scheme.is_dark_theme' |
| 452 |
apply_colors() |
| 453 |
set_color_scheme_class() |
| 454 |
|
| 455 |
def content_loaded(self): |
| 456 |
document.documentElement.style.overflow = 'hidden' |
| 457 |
if self.is_titlepage and not opts.cover_preserve_aspect_ratio: |
| 458 |
document.body.classList.add('cover-fill') |
| 459 |
document.body.classList.add(f'calibre-viewer-{layout_style()}') |
| 460 |
set_color_scheme_class() |
| 461 |
if self.reference_mode_enabled: |
| 462 |
start_reference_mode() |
| 463 |
self.last_window_width, self.last_window_height = scroll_viewport.width(), scroll_viewport.height() |
| 464 |
if self.highlights_to_apply: |
| 465 |
self.apply_highlights_on_load(self.highlights_to_apply) |
| 466 |
self.highlights_to_apply = None |
| 467 |
apply_settings() |
| 468 |
invalidate_anchor_position_cache() |
| 469 |
fix_fullscreen_svg_images() |
| 470 |
self.do_layout(self.is_titlepage) |
| 471 |
if self.mathjax: |
| 472 |
return apply_mathjax(self.mathjax, self.book.manifest.link_uid, self.content_loaded_stage2) |
| 473 |
# window.setTimeout(self.content_loaded_stage2, 1000) |
| 474 |
self.content_loaded_stage2() |
| 475 |
|
| 476 |
def content_loaded_stage2(self): |
| 477 |
reset_find_caches() |
| 478 |
self.connect_links() |
| 479 |
if runtime.is_standalone_viewer: |
| 480 |
self.listen_for_image_double_clicks() |
| 481 |
self.content_ready = True |
| 482 |
if document.head?.firstChild: |
| 483 |
# this is the loading styles used to suppress scrollbars during load |
| 484 |
# added in unserialize_html |
| 485 |
document.head.removeChild(document.head.firstChild) |
| 486 |
|
| 487 |
csi = current_spine_item() |
| 488 |
if csi.initial_position: |
| 489 |
ipos = csi.initial_position |
| 490 |
self.replace_history_on_next_cfi_update = ipos.replace_history or False |
| 491 |
if ipos.type is 'frac': |
| 492 |
self.to_scroll_fraction(ipos.frac, True) |
| 493 |
elif ipos.type is 'anchor': |
| 494 |
self.scroll_to_anchor(ipos.anchor) |
| 495 |
elif ipos.type is 'ref': |
| 496 |
self.scroll_to_ref(ipos.refnum) |
| 497 |
elif ipos.type is 'cfi': |
| 498 |
self.jump_to_cfi(ipos.cfi) |
| 499 |
elif ipos.type is 'search_result': |
| 500 |
self.show_search_result(ipos, True) |
| 501 |
elif ipos.type is 'edit_annotation': |
| 502 |
window.setTimeout(def (): |
| 503 |
self.annotations_msg_received({'type': 'edit-highlight', 'uuid': ipos.uuid}) |
| 504 |
, 5) |
| 505 |
elif ipos.type is 'smil_id': |
| 506 |
self.audio_ebook_msg_received({'type': 'play', 'anchor': ipos.anchor}) |
| 507 |
elif ipos.type is 'pagelist_ref': |
| 508 |
self.scroll_to_pagelist_ref(ipos.anchor) |
| 509 |
spine = self.book.manifest.spine |
| 510 |
files = self.book.manifest.files |
| 511 |
spine_index = csi.index |
| 512 |
self.length_before = 0 |
| 513 |
if spine_index > -1: |
| 514 |
for i in range(spine_index): |
| 515 |
si = spine[i] |
| 516 |
if si: |
| 517 |
self.length_before += files[si]?.length or 0 |
| 518 |
self.send_message( |
| 519 |
'content_loaded', progress_frac=self.calculate_progress_frac(), |
| 520 |
file_progress_frac=progress_frac(), page_counts=page_counts() |
| 521 |
) |
| 522 |
self.last_cfi = None |
| 523 |
self.auto_scroll_action('resume') |
| 524 |
reset_touch_handlers() # Needed to mitigate issue https://bugs.chromium.org/p/chromium/issues/detail?id=464579 |
| 525 |
|
| 526 |
window.setTimeout(self.update_cfi, ONSCROLL_DEBOUNCE_TIME) |
| 527 |
window.setTimeout(self.update_toc_position, 0) |
| 528 |
load_event = document.createEvent('Event') |
| 529 |
load_event.initEvent('load', False, False) |
| 530 |
window.dispatchEvent(load_event) |
| 531 |
|
| 532 |
def calculate_progress_frac(self): |
| 533 |
current_name = current_spine_item().name |
| 534 |
files = self.book.manifest.files |
| 535 |
file_length = files[current_name]?.length or 0 |
| 536 |
if self.length_before is None: |
| 537 |
return 0 |
| 538 |
frac = progress_frac() |
| 539 |
ans = (self.length_before + (file_length * frac)) / self.book.manifest.spine_length |
| 540 |
return ans |
| 541 |
|
| 542 |
def get_current_cfi(self, data): |
| 543 |
cfi = current_cfi() |
| 544 |
csi = current_spine_item() |
| 545 |
|
| 546 |
def epubcfi(cfi): |
| 547 |
return 'epubcfi(/{}{})'.format(2 * (index + 1), cfi) if cfi else None |
| 548 |
|
| 549 |
if cfi and csi: |
| 550 |
index = csi.index |
| 551 |
if index > -1: |
| 552 |
selection = window.getSelection() |
| 553 |
selcfi = seltext = None |
| 554 |
if selection and not selection.isCollapsed: |
| 555 |
seltext = selection.toString() |
| 556 |
selcfi = cfi_for_selection() |
| 557 |
selcfi.start = epubcfi(selcfi.start) |
| 558 |
selcfi.end = epubcfi(selcfi.end) |
| 559 |
cfi = epubcfi(cfi) |
| 560 |
self.send_message( |
| 561 |
'report_cfi', cfi=cfi, progress_frac=self.calculate_progress_frac(), |
| 562 |
file_progress_frac=progress_frac(), request_id=data.request_id, |
| 563 |
selected_text=seltext, selection_bounds=selcfi, page_counts=page_counts()) |
| 564 |
return |
| 565 |
self.send_message( |
| 566 |
'report_cfi', cfi=None, progress_frac=0, file_progress_frac=0, page_counts=page_counts(), request_id=data.request_id) |
| 567 |
|
| 568 |
def update_cfi(self, force_update): |
| 569 |
cfi = current_cfi() |
| 570 |
if cfi: |
| 571 |
index = current_spine_item().index |
| 572 |
if index > -1: |
| 573 |
cfi = 'epubcfi(/{}{})'.format(2 * (index + 1), cfi) |
| 574 |
pf = self.calculate_progress_frac() |
| 575 |
fpf = progress_frac() |
| 576 |
if cfi is not self.last_cfi or force_update: |
| 577 |
self.last_cfi = cfi |
| 578 |
self.send_message( |
| 579 |
'update_cfi', cfi=cfi, replace_history=self.replace_history_on_next_cfi_update, |
| 580 |
progress_frac=pf, file_progress_frac=fpf, page_counts=page_counts()) |
| 581 |
self.replace_history_on_next_cfi_update = True |
| 582 |
else: |
| 583 |
self.send_message( |
| 584 |
'update_progress_frac', progress_frac=pf, file_progress_frac=fpf, page_counts=page_counts()) |
| 585 |
|
| 586 |
def update_toc_position(self, recalculate_toc_anchor_positions): |
| 587 |
visible_anchors = update_visible_toc_anchors( |
| 588 |
self.book.manifest.toc_anchor_map, |
| 589 |
self.book.manifest.page_list_anchor_map, |
| 590 |
bool(recalculate_toc_anchor_positions) |
| 591 |
) |
| 592 |
self.send_message('update_toc_position', visible_anchors=visible_anchors) |
| 593 |
|
| 594 |
def onscroll(self): |
| 595 |
if self.content_ready: |
| 596 |
self.update_cfi() |
| 597 |
self.update_toc_position() |
| 598 |
|
| 599 |
def no_latency_onscroll(self): |
| 600 |
pf = self.calculate_progress_frac() |
| 601 |
fpf = progress_frac() |
| 602 |
self.send_message( |
| 603 |
'update_progress_frac', progress_frac=pf, file_progress_frac=fpf, page_counts=page_counts()) |
| 604 |
sel = window.getSelection() |
| 605 |
if sel and not sel.isCollapsed: |
| 606 |
self.send_message('update_selection_position', selection_extents=selection_extents(current_layout_mode() is 'flow', True)) |
| 607 |
|
| 608 |
def onresize(self): |
| 609 |
self.send_message('request_size') |
| 610 |
if self.content_ready: |
| 611 |
if is_ios: |
| 612 |
# On iOS window.innerWidth/Height are wrong inside the iframe, |
| 613 |
# so we wait for the reply from request_size |
| 614 |
return |
| 615 |
self.onresize_stage2() |
| 616 |
|
| 617 |
def onselectionchange(self): |
| 618 |
if not self.content_ready: |
| 619 |
return |
| 620 |
sel = window.getSelection() |
| 621 |
text = '' |
| 622 |
annot_id = None |
| 623 |
collapsed = not sel or sel.isCollapsed |
| 624 |
start_is_anchor = True |
| 625 |
if not collapsed: |
| 626 |
text = sel.toString() |
| 627 |
annot_id = highlight_associated_with_selection(sel, annot_id_uuid_map) |
| 628 |
r = sel.getRangeAt(0) |
| 629 |
start_is_anchor = r.startContainer is sel.anchorNode and r.startOffset is sel.anchorOffset |
| 630 |
now = window.performance.now() |
| 631 |
by_search = now - self.last_search_at < 1000 |
| 632 |
self.send_message( |
| 633 |
'selectionchange', text=text, empty=v'!!collapsed', annot_id=annot_id, |
| 634 |
drag_mouse_position=drag_mouse_position, selection_change_caused_by_search=by_search, |
| 635 |
selection_extents=selection_extents(current_layout_mode() is 'flow'), |
| 636 |
rtl=scroll_viewport.rtl, vertical=scroll_viewport.vertical_writing_mode, |
| 637 |
start_is_anchor=start_is_anchor |
| 638 |
) |
| 639 |
|
| 640 |
def onresize_stage2(self): |
| 641 |
if scroll_viewport.width() is self.last_window_width and scroll_viewport.height() is self.last_window_height: |
| 642 |
# Safari at least, generates lots of spurious resize events |
| 643 |
return |
| 644 |
if current_layout_mode() is not 'flow': |
| 645 |
paged_prepare_for_resize(self.last_window_width, self.last_window_height) |
| 646 |
self.do_layout(self.is_titlepage) |
| 647 |
self.last_window_width, self.last_window_height = scroll_viewport.width(), scroll_viewport.height() |
| 648 |
if self.last_cfi: |
| 649 |
cfi = self.last_cfi[len('epubcfi(/'):-1].partition('/')[2] |
| 650 |
if cfi: |
| 651 |
self.jump_to_cfi('/' + cfi) |
| 652 |
if current_layout_mode() is not 'flow': |
| 653 |
paged_resize_done() |
| 654 |
self.update_cfi() |
| 655 |
self.update_toc_position() |
| 656 |
sel = window.getSelection() |
| 657 |
if sel and not sel.isCollapsed: |
| 658 |
# update_selection_position has probably already been called by |
| 659 |
# no_latency_onscroll but make sure |
| 660 |
self.send_message('update_selection_position', selection_extents=selection_extents(current_layout_mode() is 'flow')) |
| 661 |
|
| 662 |
def received_window_size(self, data): |
| 663 |
scroll_viewport.update_window_size(data.width, data.height) |
| 664 |
if self.content_ready: |
| 665 |
self.onresize_stage2() |
| 666 |
|
| 667 |
def onwheel(self, evt): |
| 668 |
if self.content_ready: |
| 669 |
if evt.preventDefault: |
| 670 |
evt.preventDefault() |
| 671 |
if evt.deltaY and evt.ctrlKey and not evt.shiftKey and not evt.altKey and not evt.metaKey: |
| 672 |
self.send_message('handle_shortcut', name='increase_font_size' if evt.deltaY < 0 else 'decrease_font_size') |
| 673 |
else: |
| 674 |
self.handle_wheel(evt) |
| 675 |
|
| 676 |
def onmousemove(self, evt): |
| 677 |
if evt.buttons is not 1: |
| 678 |
return |
| 679 |
drag_mouse_position.x = evt.clientX |
| 680 |
drag_mouse_position.y = evt.clientY |
| 681 |
if 0 <= evt.clientY <= window.innerHeight: |
| 682 |
cancel_drag_scroll() |
| 683 |
return |
| 684 |
sel = window.getSelection() |
| 685 |
if not sel: |
| 686 |
cancel_drag_scroll() |
| 687 |
return |
| 688 |
delta = evt.clientY if evt.clientY < 0 else (evt.clientY - window.innerHeight) |
| 689 |
self.start_drag_scroll(delta) |
| 690 |
|
| 691 |
def onmouseup(self, evt): |
| 692 |
cancel_drag_scroll() |
| 693 |
drag_mouse_position.x = drag_mouse_position.y = None |
| 694 |
# ensure selection bar is updated |
| 695 |
self.onselectionchange() |
| 696 |
if evt.button is 3 or evt.button is 4: |
| 697 |
self.send_message('handle_shortcut', name='back' if evt.button is 3 else 'forward') |
| 698 |
|
| 699 |
def ondoubleclick(self, evt): |
| 700 |
self.send_message('annotations', type='double-click') |
| 701 |
|
| 702 |
def onkeydown(self, evt): |
| 703 |
if current_layout_mode() is not 'flow' and evt.key is 'Tab': |
| 704 |
# Prevent the TAB key from shifting focus as it causes partial scrolling |
| 705 |
evt.preventDefault() |
| 706 |
if self.forward_keypresses: |
| 707 |
self.send_message('handle_keypress', evt=keyevent_as_shortcut(evt)) |
| 708 |
evt.preventDefault(), evt.stopPropagation() |
| 709 |
return |
| 710 |
if self.content_ready: |
| 711 |
sc_name = shortcut_for_key_event(evt, self.keyboard_shortcut_map) |
| 712 |
if sc_name: |
| 713 |
evt.preventDefault() |
| 714 |
if not self.handle_navigation_shortcut(sc_name, evt): |
| 715 |
self.send_message('handle_shortcut', name=sc_name) |
| 716 |
|
| 717 |
def on_handle_navigation_shortcut(self, data): |
| 718 |
self.handle_navigation_shortcut(data.name, data.key or { |
| 719 |
'key': '', 'altKey': False, 'ctrlKey': False, 'shiftKey': False, 'metaKey': False}) |
| 720 |
|
| 721 |
def oncontextmenu(self, evt): |
| 722 |
if self.content_ready: |
| 723 |
evt.preventDefault() |
| 724 |
self.send_message('show_chrome', elements=get_elements(evt.clientX, evt.clientY)) |
| 725 |
|
| 726 |
def send_message(self, action, **data): |
| 727 |
self.comm.send_message(action, data) |
| 728 |
|
| 729 |
def connect_links(self): |
| 730 |
for a in document.body.querySelectorAll(f'a[{self.link_attr}],area[{self.link_attr}]'): |
| 731 |
a.addEventListener('click', self.link_activated) |
| 732 |
if runtime.is_standalone_viewer: |
| 733 |
# links with a target get turned into requests to open a new window by Qt |
| 734 |
for a in document.body.querySelectorAll('a[target]'): |
| 735 |
a.removeAttribute('target') |
| 736 |
|
| 737 |
def listen_for_image_double_clicks(self): |
| 738 |
for img in document.querySelectorAll('img, image'): |
| 739 |
img.addEventListener('dblclick', self.image_double_clicked, {'passive': True}) |
| 740 |
|
| 741 |
def image_double_clicked(self, ev): |
| 742 |
img = ev.currentTarget |
| 743 |
if img.dataset.calibreSrc: |
| 744 |
self.send_message('view_image', calibre_src=img.dataset.calibreSrc) |
| 745 |
|
| 746 |
def link_activated(self, evt): |
| 747 |
try: |
| 748 |
data = JSON.parse(evt.currentTarget.getAttribute(self.link_attr)) |
| 749 |
except: |
| 750 |
print('WARNING: Failed to parse link data {}, ignoring'.format(evt.currentTarget?.getAttribute?(self.link_attr))) |
| 751 |
return |
| 752 |
if data.missing: |
| 753 |
self.send_message('link_to_missing_activated', name=data.name) |
| 754 |
else: |
| 755 |
self.activate_link(data.name, data.frag, evt.currentTarget) |
| 756 |
|
| 757 |
def activate_link(self, name, frag, target_elem): |
| 758 |
if not name: |
| 759 |
name = current_spine_item().name |
| 760 |
try: |
| 761 |
is_popup = is_footnote_link(target_elem, name, frag, current_spine_item().name, self.book.manifest.link_to_map or {}) |
| 762 |
except: |
| 763 |
import traceback |
| 764 |
traceback.print_exc() |
| 765 |
is_popup = False |
| 766 |
if is_popup: |
| 767 |
self.on_fake_popup_activation({'name': name, 'frag': frag, 'title': target_elem.textContent}) |
| 768 |
return |
| 769 |
if name is current_spine_item().name: |
| 770 |
self.replace_history_on_next_cfi_update = False |
| 771 |
self.scroll_to_anchor(frag) |
| 772 |
else: |
| 773 |
self.send_message('scroll_to_anchor', name=name, frag=frag) |
| 774 |
|
| 775 |
def on_fake_popup_activation(self, data): |
| 776 |
self.send_message( |
| 777 |
'show_footnote', name=data.name, frag=data.frag, title=data.title, |
| 778 |
cols_per_screen=calc_columns_per_screen(), rtl=scroll_viewport.rtl, |
| 779 |
vertical_writing_mode=scroll_viewport.vertical_writing_mode |
| 780 |
) |
| 781 |
|
| 782 |
def scroll_to_anchor(self, frag): |
| 783 |
if frag: |
| 784 |
elem = document.getElementById(frag) |
| 785 |
if not elem: |
| 786 |
c = document.getElementsByName(frag) |
| 787 |
if c and c.length: |
| 788 |
elem = c[0] |
| 789 |
if elem: |
| 790 |
scroll_to_elem(elem) |
| 791 |
else: |
| 792 |
scroll_viewport.scroll_to(0, 0) |
| 793 |
|
| 794 |
def scroll_to_pagelist_ref(self, frag): |
| 795 |
elem = document.getElementById(frag) |
| 796 |
if not elem: |
| 797 |
c = document.getElementsByName(frag) |
| 798 |
if c and c.length: |
| 799 |
elem = c[0] |
| 800 |
if elem: |
| 801 |
ensure_page_list_target_is_displayed(elem) |
| 802 |
scroll_to_elem(elem) |
| 803 |
|
| 804 |
def scroll_to_ref(self, refnum): |
| 805 |
refnum = int(refnum) |
| 806 |
elem = elem_for_ref(refnum) |
| 807 |
if elem: |
| 808 |
scroll_to_elem(elem) |
| 809 |
|
| 810 |
def on_scroll_to_ref(self, data): |
| 811 |
refnum = data.refnum |
| 812 |
if refnum?: |
| 813 |
self.scroll_to_ref(refnum) |
| 814 |
|
| 815 |
def show_search_result(self, data, from_load): |
| 816 |
if self.load_search_result_timer: |
| 817 |
window.clearTimeout(self.load_search_result_timer) |
| 818 |
self.load_search_result_timer = None |
| 819 |
sr = data.search_result |
| 820 |
if sr.on_discovery: |
| 821 |
if sr.result_num is 1: |
| 822 |
self.full_book_search_in_progress = FullBookSearch() |
| 823 |
elif self.full_book_search_in_progress?.first_result_shown: |
| 824 |
return |
| 825 |
self.last_search_at = window.performance.now() |
| 826 |
before_select_pos = {'x': scroll_viewport.x(), 'y': scroll_viewport.y()} |
| 827 |
if select_search_result(sr): |
| 828 |
self.ensure_selection_boundary_visible() |
| 829 |
need_workaround = from_load and current_layout_mode() is 'paged' |
| 830 |
if need_workaround: |
| 831 |
# workaround bug in chrome where sizes are incorrect in paged |
| 832 |
# mode on initial load for some books |
| 833 |
self.load_search_result_timer = window.setTimeout( |
| 834 |
self.ensure_search_result_visible.bind(None, before_select_pos), |
| 835 |
int(3 * ONSCROLL_DEBOUNCE_TIME / 4) |
| 836 |
) |
| 837 |
if self.full_book_search_in_progress and not self.full_book_search_in_progress.first_result_shown and sr.on_discovery: |
| 838 |
discovered = False |
| 839 |
if (sr.force_jump_to |
| 840 |
or progress_frac() >= self.full_book_search_in_progress.progress_frac_at_start |
| 841 |
or current_spine_item().index is not self.full_book_search_in_progress.start_spine_index): |
| 842 |
self.full_book_search_in_progress.first_result_shown = True |
| 843 |
discovered = True |
| 844 |
else: |
| 845 |
scroll_viewport.scroll_to(before_select_pos.x, before_select_pos.y) |
| 846 |
self.send_message('search_result_discovered', search_result=data.search_result, discovered=discovered) |
| 847 |
if not need_workaround: |
| 848 |
self.add_search_result_to_history_stack(before_select_pos) |
| 849 |
else: |
| 850 |
self.send_message('search_result_not_found', search_result=data.search_result) |
| 851 |
|
| 852 |
def add_search_result_to_history_stack(self, before_select_pos): |
| 853 |
self.replace_history_on_next_cfi_update = False |
| 854 |
self.update_cfi(True) |
| 855 |
|
| 856 |
def ensure_search_result_visible(self, before_select_pos): |
| 857 |
self.load_search_result_timer = None |
| 858 |
sel = window.getSelection() |
| 859 |
if sel.isCollapsed or sel.rangeCount is 0: |
| 860 |
return |
| 861 |
self.ensure_selection_boundary_visible() |
| 862 |
self.add_search_result_to_history_stack(before_select_pos) |
| 863 |
|
| 864 |
def set_reference_mode(self, data): |
| 865 |
self.reference_mode_enabled = data.enabled |
| 866 |
if data.enabled: |
| 867 |
start_reference_mode() |
| 868 |
else: |
| 869 |
end_reference_mode() |
| 870 |
|
| 871 |
def apply_highlight(self, uuid, existing, has_notes, style_defn, notes): |
| 872 |
sel = window.getSelection() |
| 873 |
if not sel.rangeCount: |
| 874 |
return |
| 875 |
anchor_before = find_anchor_before_range(sel.getRangeAt(0), self.book.manifest.toc_anchor_map, self.book.manifest.page_list_anchor_map) |
| 876 |
text = sel.toString() |
| 877 |
bounds = cfi_for_selection() |
| 878 |
style = highlight_style_as_css(style_defn, opts.is_dark_theme, opts.color_scheme.foreground) |
| 879 |
cls = 'crw-has-dot' if has_notes else None |
| 880 |
title = None if opts.hide_tooltips else notes |
| 881 |
annot_id, intersecting_wrappers = wrap_text_in_range(style, None, cls, self.add_highlight_listeners, title) |
| 882 |
removed_highlights = [] |
| 883 |
if annot_id is not None: |
| 884 |
intersecting_uuids = {annot_id_uuid_map[x]: True for x in intersecting_wrappers} |
| 885 |
if existing and intersecting_uuids[existing]: |
| 886 |
uuid = existing |
| 887 |
elif intersecting_wrappers.length is 1 and annot_id_uuid_map[intersecting_wrappers[0]]: |
| 888 |
uuid = annot_id_uuid_map[intersecting_wrappers[0]] |
| 889 |
intersecting_wrappers = [] |
| 890 |
removed_highlights = {} |
| 891 |
for crw in intersecting_wrappers: |
| 892 |
unwrap_crw(crw) |
| 893 |
if annot_id_uuid_map[crw]: |
| 894 |
if annot_id_uuid_map[crw] is not uuid: |
| 895 |
removed_highlights[annot_id_uuid_map[crw]] = True |
| 896 |
v'delete annot_id_uuid_map[crw]' |
| 897 |
removed_highlights = Object.keys(removed_highlights) |
| 898 |
sel.removeAllRanges() |
| 899 |
annot_id_uuid_map[annot_id] = uuid |
| 900 |
self.send_message( |
| 901 |
'annotations', |
| 902 |
type='highlight-applied', |
| 903 |
uuid=uuid, ok=annot_id is not None, |
| 904 |
bounds=bounds, style=style_defn, |
| 905 |
removed_highlights=removed_highlights, |
| 906 |
highlighted_text=text, |
| 907 |
anchor_before=anchor_before |
| 908 |
) |
| 909 |
reset_find_caches() |
| 910 |
|
| 911 |
def annotations_msg_received(self, data): |
| 912 |
dtype = data?.type |
| 913 |
if dtype is 'move-end-of-selection': |
| 914 |
move_end_of_selection(data.pos, data.start) |
| 915 |
elif dtype is 'set-highlight-style': |
| 916 |
set_selection_style(data.style) |
| 917 |
elif dtype is 'trigger-shortcut': |
| 918 |
self.on_handle_navigation_shortcut(data) |
| 919 |
elif dtype is 'extend-to-paragraph': |
| 920 |
sel = window.getSelection() |
| 921 |
try: |
| 922 |
try: |
| 923 |
sel.modify('extend', 'forward', 'paragraphboundary') |
| 924 |
except: |
| 925 |
sel.modify('extend', 'forward', 'lineboundary') |
| 926 |
end_node, end_offset = sel.focusNode, sel.focusOffset |
| 927 |
try: |
| 928 |
sel.modify('extend', 'backward', 'paragraphboundary') |
| 929 |
except: |
| 930 |
sel.modify('extend', 'backward', 'lineboundary') |
| 931 |
sel.setBaseAndExtent(sel.focusNode, sel.focusOffset, end_node, end_offset) |
| 932 |
except: |
| 933 |
(console.error or console.log)('Failed to extend selection to paragraph') |
| 934 |
elif dtype is 'extend-to-point': |
| 935 |
move_end_of_selection(data.pos, is_start_closer_to_point(data.pos)) |
| 936 |
elif dtype is 'drag-scroll': |
| 937 |
self.scroll_to_extend_annotation(data.backwards) |
| 938 |
elif dtype is 'edit-highlight': |
| 939 |
found_highlight_to_edit = False |
| 940 |
for qcrw, quuid in Object.entries(annot_id_uuid_map): |
| 941 |
if quuid is data.uuid and select_crw(qcrw): |
| 942 |
found_highlight_to_edit = True |
| 943 |
break |
| 944 |
if found_highlight_to_edit: |
| 945 |
self.ensure_selection_visible() |
| 946 |
window.setTimeout(def (): |
| 947 |
self.send_message('annotations', type='edit-highlight') |
| 948 |
, 50) |
| 949 |
else: |
| 950 |
self.send_message('annotations', type='edit-highlight-failed', uuid=data.uuid) |
| 951 |
elif dtype is 'notes-edited': |
| 952 |
cls = 'crw-has-dot' |
| 953 |
for qcrw, quuid in Object.entries(annot_id_uuid_map): |
| 954 |
if quuid is data.uuid: |
| 955 |
node = last_span_for_crw(qcrw) |
| 956 |
if node: |
| 957 |
if data.has_notes: |
| 958 |
node.classList.add(cls) |
| 959 |
else: |
| 960 |
node.classList.remove(cls) |
| 961 |
set_title_for_crw(qcrw, None if opts.hide_tooltips else data.notes) |
| 962 |
elif dtype is 'remove-highlight': |
| 963 |
found_highlight_to_remove = False |
| 964 |
for qcrw, quuid in Object.entries(annot_id_uuid_map): |
| 965 |
if quuid is data.uuid: |
| 966 |
found_highlight_to_remove = True |
| 967 |
unwrap_crw(qcrw) |
| 968 |
v'delete annot_id_uuid_map[qcrw]' |
| 969 |
if found_highlight_to_remove: |
| 970 |
# have to remove selection otherwise selection bar does |
| 971 |
# not hide itself on multiline selections |
| 972 |
window.getSelection().removeAllRanges() |
| 973 |
elif dtype is 'apply-highlight': |
| 974 |
existing = all_annots_in_selection(window.getSelection(), annot_id_uuid_map) |
| 975 |
if existing.length is 0 or (existing.length is 1 and existing[0] is data.existing): |
| 976 |
self.apply_highlight(data.uuid, data.existing, data.has_notes, data.style, data.notes) |
| 977 |
else: |
| 978 |
self.send_message( |
| 979 |
'annotations', type='highlight-overlapped', |
| 980 |
uuid=data.uuid, existing=data.existing, has_notes=data.has_notes, style=data.style, notes=data.notes) |
| 981 |
elif dtype is 'apply-highlight-overwrite': |
| 982 |
self.apply_highlight(data.uuid, data.existing, data.has_notes, data.style, data.notes) |
| 983 |
elif dtype is 'cite-current-selection': |
| 984 |
sel = window.getSelection() |
| 985 |
if not sel.rangeCount: |
| 986 |
return |
| 987 |
bounds = cfi_for_selection() |
| 988 |
text = sel.toString() |
| 989 |
self.send_message('annotations', type='cite-data', bounds=bounds, highlighted_text=text) |
| 990 |
else: |
| 991 |
console.log('Ignoring annotations message to iframe with unknown type: ' + dtype) |
| 992 |
|
| 993 |
def apply_highlights_on_load(self, highlights): |
| 994 |
clear_annot_id_uuid_map() |
| 995 |
reset_highlight_counter() |
| 996 |
strcmp = v'new Intl.Collator().compare' |
| 997 |
highlights.sort(def (a, b): return strcmp(a.timestamp, b.timestamp);) |
| 998 |
for h in highlights: |
| 999 |
r = range_from_cfi(h.start_cfi, h.end_cfi) |
| 1000 |
if not r: |
| 1001 |
continue |
| 1002 |
style = highlight_style_as_css(h.style, opts.is_dark_theme, opts.color_scheme.foreground) |
| 1003 |
cls = 'crw-has-dot' if h.notes else None |
| 1004 |
title = None if opts.hide_tooltips else h.notes |
| 1005 |
annot_id, intersecting_wrappers = wrap_text_in_range(style, r, cls, self.add_highlight_listeners, title) |
| 1006 |
if annot_id is not None: |
| 1007 |
annot_id_uuid_map[annot_id] = h.uuid |
| 1008 |
for crw in intersecting_wrappers: |
| 1009 |
unwrap_crw(crw) |
| 1010 |
v'delete annot_id_uuid_map[crw]' |
| 1011 |
|
| 1012 |
def replace_highlights(self, data): |
| 1013 |
highlights = data.highlights |
| 1014 |
unwrap_all_crw() |
| 1015 |
self.apply_highlights_on_load(highlights or []) |
| 1016 |
|
| 1017 |
def add_highlight_listeners(self, wrapper): |
| 1018 |
wrapper.addEventListener('dblclick', self.highlight_wrapper_dblclicked) |
| 1019 |
|
| 1020 |
def highlight_wrapper_dblclicked(self, ev): |
| 1021 |
crw = ev.currentTarget.dataset.calibreRangeWrapper |
| 1022 |
if crw: |
| 1023 |
ev.preventDefault(), ev.stopPropagation() |
| 1024 |
select_crw(crw) |
| 1025 |
|
| 1026 |
def copy_selection(self): |
| 1027 |
try: |
| 1028 |
if document.execCommand('copy'): |
| 1029 |
return |
| 1030 |
except: |
| 1031 |
pass |
| 1032 |
|
| 1033 |
s = window.getSelection() |
| 1034 |
text = s.toString() |
| 1035 |
if text: |
| 1036 |
container = document.createElement('div') |
| 1037 |
for i in range(s.rangeCount): |
| 1038 |
container.appendChild(s.getRangeAt(i).cloneContents()) |
| 1039 |
self.send_message('copy_text_to_clipboard', text=text, html=container.innerHTML) |
| 1040 |
|
| 1041 |
def tts_msg_received(self, data): |
| 1042 |
if data.type is 'mark': |
| 1043 |
self.mark_word_being_spoken(data.num) |
| 1044 |
elif data.type is 'play': |
| 1045 |
if data.pos: |
| 1046 |
r = word_at_point(data.pos.x, data.pos.y) |
| 1047 |
if not r: |
| 1048 |
return |
| 1049 |
else: |
| 1050 |
r = first_visible_word() |
| 1051 |
if r and r.startContainer?.nodeType is Node.TEXT_NODE: |
| 1052 |
marked_text = tts_data(r.startContainer, r.startOffset) |
| 1053 |
else: |
| 1054 |
# no text visible in the viewport (e.g. a full page image). |
| 1055 |
# Start from the first word after the viewport start rather |
| 1056 |
# than from the start of the file, see https://bugs.launchpad.net/bugs/2165923 |
| 1057 |
entry = first_tts_word_after_viewport_start() |
| 1058 |
marked_text = tts_data(entry.node, 0) if entry else v'[]' |
| 1059 |
sel = window.getSelection() |
| 1060 |
sel.removeAllRanges() |
| 1061 |
self.send_message('tts', type='text-extracted', marked_text=marked_text, pos=data.pos) |
| 1062 |
|
| 1063 |
def mark_word_being_spoken(self, x): |
| 1064 |
if jstype(x) is 'number': |
| 1065 |
x = {'first': x, 'last': x} |
| 1066 |
self.last_search_at = window.performance.now() |
| 1067 |
if select_tts_mark(x.first, x.last): |
| 1068 |
self.ensure_selection_boundary_visible() |
| 1069 |
|
| 1070 |
def audio_ebook_msg_received(self, data): |
| 1071 |
if data.type is 'mark': |
| 1072 |
if data.anchor: |
| 1073 |
self.last_search_at = window.performance.now() |
| 1074 |
if mark_smil_element(data.anchor): |
| 1075 |
self.ensure_selection_boundary_visible() |
| 1076 |
self.send_message('audio_ebook_message', type='marked', anchor=data.anchor, idx=data.idx) |
| 1077 |
else: |
| 1078 |
self.send_message('audio_ebook_message', type='marked') |
| 1079 |
else: |
| 1080 |
window.getSelection().removeAllRanges() |
| 1081 |
self.send_message('audio_ebook_message', type='marked') |
| 1082 |
elif data.type is 'play': |
| 1083 |
if data.anchor: |
| 1084 |
pos = self.smil_anchor_map[data.anchor] |
| 1085 |
if pos?: |
| 1086 |
par = self.smil_par_list[pos] |
| 1087 |
else: |
| 1088 |
par = None |
| 1089 |
else: |
| 1090 |
par = smil_element_at(data.pos, self.smil_anchor_map, self.smil_par_list) |
| 1091 |
self.send_message('audio_ebook_message', type='start_play_at', par=par or None, anchor=data.anchor or None, pos=data.pos or None) |
| 1092 |
else: |
| 1093 |
console.error(f'Unknown audio ebook message type from main: {data.type}') |
| 1094 |
|
| 1095 |
def hints_msg_received(self, data): |
| 1096 |
if data.type is 'show': |
| 1097 |
# clear selection so that it does not confuse with the hints which use the same colors |
| 1098 |
window.getSelection().removeAllRanges() |
| 1099 |
hints_map = hint_visible_links() |
| 1100 |
self.send_message('hints', type='shown', hints_map=hints_map) |
| 1101 |
elif data.type is 'hide': |
| 1102 |
unhint_links() |
| 1103 |
elif data.type is 'activate': |
| 1104 |
hint = data.hint |
| 1105 |
if hint.type is 'link': |
| 1106 |
a = document.body.querySelector(f'[data-calibre-hint-value="{hint.value}"]') |
| 1107 |
a.removeEventListener('animationend', self.hint_animation_ended) |
| 1108 |
a.addEventListener('animationend', self.hint_animation_ended, False) |
| 1109 |
a.classList.add('calibre-animated-hint') |
| 1110 |
elif data.type is 'apply_prefix': |
| 1111 |
apply_prefix_to_hints(data.prefix) |
| 1112 |
|
| 1113 |
def hint_animation_ended(self, ev): |
| 1114 |
a = ev.currentTarget |
| 1115 |
a.classList.remove('calibre-animated-hint') |
| 1116 |
a.click() |
| 1117 |
|
| 1118 |
|
| 1119 |
@no_prune |
| 1120 |
def main(): |
| 1121 |
if not main.boss: |
| 1122 |
main.boss = IframeBoss() |