Debian Codegraph @

src/pyj/read_book/paged_mode.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3
4 # Notes of paged mode scrolling:
5 # All the math in paged mode is based on the block and inline directions.
6 # Inline is "the direction lines of text go."
7 # In horizontal scripts such as English and Hebrew, the inline is horizontal
8 # and the block is vertical.
9 # In vertical languages such as Japanese and Mongolian, the inline is vertical
10 # and block is horizontal.
11 # Regardless of language, paged mode scrolls by column in the inline direction,
12 # because by the CSS spec, columns are laid out in the inline direction.
13 #
14 # In horizontal RTL books, such as Hebrew, the inline direction goes right to left.
15 # |<------|
16 # This means that the column positions become negative as you scroll.
17 # This is hidden from paged mode by the viewport, which transparently
18 # negates any inline coordinates sent in to the viewport_to_document* functions
19 # and the various scroll_to/scroll_by functions, as well as the reported X position.
20 #
21 # The result of all this is that paged mode's math can safely pretend that
22 # things scroll in the positive inline direction.
23
24 from __python__ import hash_literals, bound_methods
25
26 import traceback
27 from elementmaker import E
28
29 from dom import set_important_css
30 from read_book.cfi import (
31 at_current as cfi_at_current, at_point as cfi_at_point,
32 scroll_to as cfi_scroll_to
33 )
34 from read_book.globals import current_spine_item, get_boss, rtl_page_progression
35 from read_book.settings import opts
36 from read_book.viewport import scroll_viewport, line_height, rem_size, get_unit_size_in_pixels
37 from utils import (
38 get_elem_data, set_elem_data
39 )
40
41
42 def first_child(parent):
43 c = parent.firstChild
44 count = 0
45 while c?.nodeType is not Node.ELEMENT_NODE and count < 20:
46 c = c?.nextSibling
47 count += 1
48 if c?.nodeType is Node.ELEMENT_NODE:
49 return c
50
51
52 def has_start_text(elem):
53 # Returns true if elem has some non-whitespace text before its first child
54 # element
55 for c in elem.childNodes:
56 if c.nodeType is not Node.TEXT_NODE:
57 break
58 if c.nodeType is Node.TEXT_NODE and c.nodeValue and /\S/.test(c.nodeValue):
59 return True
60 return False
61
62
63 def handle_rtl_body(body_style):
64 if body_style.direction is 'rtl':
65 # If this in not set, Chrome scrolling breaks for some RTL and vertical content.
66 document.documentElement.style.overflow = 'visible'
67
68
69 def create_page_div(elem):
70 div = E('blank-page-div', ' \n ')
71 document.body.appendChild(div)
72 # the min-height is needed to get firefox to always insert a column break before this div
73 set_important_css(div, break_before='column', break_inside='avoid', display='block', white_space='pre', background_color='transparent',
74 background_image='none', border_width='0', float='none', position='static', min_height='100vh')
75
76 _in_paged_mode = False
77
78
79 def in_paged_mode():
80 return _in_paged_mode
81
82
83 col_size = screen_inline = screen_block = cols_per_screen = gap = col_and_gap = last_scrolled_to_column = 0
84 is_full_screen_layout = False
85
86
87 def get_number_of_cols(dont_return_integer):
88 # we don't store this because of the chrome resize bug where the document width
89 # sometimes changes a few milliseconds after layout in paged mode
90 if is_full_screen_layout:
91 return 1
92 ans = (scroll_viewport.paged_content_inline_size() + gap) / col_and_gap
93 if not dont_return_integer:
94 ans = Math.floor(ans)
95 return ans
96
97
98 def reset_paged_mode_globals():
99 nonlocal _in_paged_mode, col_size, col_and_gap, screen_block, gap, screen_inline, is_full_screen_layout, cols_per_screen, last_scrolled_to_column
100 scroll_viewport.reset_globals()
101 col_size = screen_inline = screen_block = cols_per_screen = gap = col_and_gap = last_scrolled_to_column = 0
102 is_full_screen_layout = _in_paged_mode = False
103 resize_manager.reset()
104
105
106 def column_at(pos):
107 # Return the (zero-based) number of the column that contains pos
108 si = scroll_viewport.paged_content_inline_size()
109 if pos >= si - col_and_gap:
110 pos = si - col_size + 10
111 # we subtract 1 here so that a point at the absolute trailing (right in
112 # horz-LTR) edge of a column remains in the column and not at the next column
113 return max(0, (pos + gap - 1)) // col_and_gap
114
115
116 def fit_images():
117 # Ensure no images are wider than the available size of a column. Note
118 # that this method use getBoundingClientRect() which means it will
119 # force a relayout if the render tree is dirty.
120 inline_limited_images = []
121 block_limited_images = []
122 img_tags = document.getElementsByTagName('img')
123 bounding_rects = []
124 for img_tag in img_tags:
125 bounding_rects.push(get_bounding_client_rect(img_tag))
126 maxb = screen_block
127 for i in range(img_tags.length):
128 img = img_tags[i]
129 br = bounding_rects[i]
130 previously_limited = get_elem_data(img, 'inline-limited', False)
131 data = get_elem_data(img, 'img-data', None)
132 if data is None:
133 data = {'left': br.left, 'right': br.right, 'height': br.height, 'display': img.style.display}
134 set_elem_data(img, 'img-data', data)
135
136 # Get start of image bounding box in the column direction (inline)
137 image_start = scroll_viewport.viewport_to_document_inline(scroll_viewport.rect_inline_start(br), img.ownerDocument)
138 col_start = column_at(image_start) * col_and_gap
139 # Get inline distance from the start of the column to the start of the image bounding box
140 column_start_to_image_start = image_start - col_start
141 image_block_size = scroll_viewport.rect_block_size(br)
142 image_inline_size = scroll_viewport.rect_inline_size(br)
143 # Get the inline distance from the start of the column to the end of the image
144 image_inline_end = column_start_to_image_start + image_inline_size
145 # If the end of the image goes past the column, add it to the list of inline_limited_images
146 if previously_limited or image_inline_end > col_size:
147 inline_limited_images.push([img, col_size - column_start_to_image_start])
148 previously_limited = get_elem_data(img, 'block-limited', False)
149 if previously_limited or image_block_size > maxb or (image_block_size is maxb and image_inline_size > col_size):
150 block_limited_images.push(img)
151 if previously_limited:
152 set_important_css(img, break_before='auto', display=data.display)
153 set_important_css(img, break_inside='avoid')
154
155 for img_tag, max_inline_size in inline_limited_images:
156 if scroll_viewport.vertical_writing_mode:
157 img_tag.style.setProperty('max-height', max_inline_size + 'px')
158 else:
159 img_tag.style.setProperty('max-width', max_inline_size + 'px')
160 set_elem_data(img_tag, 'inline-limited', True)
161
162 for img_tag in block_limited_images:
163 if scroll_viewport.vertical_writing_mode:
164 set_important_css(img_tag, break_before='always', max_width='100vw')
165 else:
166 set_important_css(img_tag, break_before='always', max_height='100vh')
167 set_elem_data(img_tag, 'block-limited', True)
168
169
170 def cps_by_em_size():
171 ans = cps_by_em_size.ans
172 fs = window.getComputedStyle(document.body).fontSize
173 if not ans or cps_by_em_size.at_font_size is not fs:
174 if fs is 0:
175 ans = cps_by_em_size.ans = 16
176 else:
177 ans = cps_by_em_size.ans = max(2, get_unit_size_in_pixels('rem'))
178 cps_by_em_size.at_font_size = fs
179 return ans
180
181
182 def calc_columns_per_screen():
183 cps = opts.columns_per_screen or {}
184 cps = cps.landscape if scroll_viewport.width() > scroll_viewport.height() else cps.portrait
185 try:
186 cps = int(cps)
187 except:
188 cps = 0
189 if not cps:
190 cps = int(Math.floor(scroll_viewport.inline_size() / (35 * cps_by_em_size())))
191 cps = max(1, min(cps or 1, 20))
192 return cps
193
194
195 def get_columns_per_screen_data():
196 which = 'landscape' if scroll_viewport.width() > scroll_viewport.height() else 'portrait'
197 return {'which': which, 'cps': calc_columns_per_screen()}
198
199
200 def will_columns_per_screen_change():
201 return calc_columns_per_screen() != cols_per_screen
202
203
204 class ScrollResizeBugWatcher:
205 # In Chrome sometimes after layout the scrollWidth of body increases after a
206 # few milliseconds, this can cause scrolling to the end to not work
207 # immediately after layout. This happens without a resize event, and
208 # without triggering the ResizeObserver and only in paged mode.
209
210 def __init__(self):
211 self.max_time = 750
212 self.last_layout_at = 0
213 self.last_command = None
214 self.doc_size = 0
215 self.timer = None
216
217 def layout_done(self):
218 self.last_layout_at = window.performance.now()
219 self.last_command = None
220 self.cancel_timer()
221
222 def scrolled(self, pos, limit):
223 self.cancel_timer()
224 now = window.performance.now()
225 if now - self.last_layout_at < self.max_time and self.last_command is not None:
226 self.doc_size = scroll_viewport.paged_content_inline_size()
227 self.check_for_resize_bug()
228
229 def cancel_timer(self):
230 if self.timer is not None:
231 window.clearTimeout(self.timer)
232 self.timer = None
233
234 def check_for_resize_bug(self):
235 sz = scroll_viewport.paged_content_inline_size()
236 if sz != self.doc_size:
237 return self.redo_scroll()
238 now = window.performance.now()
239 if now - self.last_layout_at < self.max_time:
240 window.setTimeout(self.check_for_resize_bug, 10)
241 else:
242 self.timer = None
243
244 def redo_scroll(self):
245 if self.last_command:
246 self.last_command()
247 self.last_command = None
248 self.timer = None
249 self.doc_size = 0
250
251
252 scroll_resize_bug_watcher = ScrollResizeBugWatcher()
253
254
255 def layout(is_single_page, on_resize):
256 nonlocal _in_paged_mode, col_size, col_and_gap, screen_block, gap, screen_inline, is_full_screen_layout, cols_per_screen
257 line_height(True)
258 rem_size(True)
259 body_style = window.getComputedStyle(document.body)
260 scroll_viewport.initialize_on_layout(body_style)
261 first_layout = not _in_paged_mode
262 cps = calc_columns_per_screen()
263 if first_layout:
264 handle_rtl_body(body_style)
265 # Check if the current document is a full screen layout like
266 # cover, if so we treat it specially.
267 single_screen = scroll_viewport.document_block_size() < (scroll_viewport.block_size() + 75)
268 first_layout = True
269 svgs = document.getElementsByTagName('svg')
270 has_svg = svgs.length > 0
271 imgs = document.getElementsByTagName('img')
272 only_img = imgs.length is 1 and document.getElementsByTagName('div').length < 3 and document.getElementsByTagName('p').length < 2
273 if only_img and window.getComputedStyle(imgs[0]).zIndex < 0:
274 # Needed for some stupidly coded fixed layout EPUB comics, see for
275 # instance: https://bugs.launchpad.net/calibre/+bug/1667357
276 imgs[0].style.zIndex = '0'
277 if not single_screen and cps > 1:
278 num = cps - 1
279 elems = document.querySelectorAll('body > *')
280 if elems.length is 1:
281 # Workaround for the case when the content is wrapped in a
282 # 100% height <div>. This causes the generated page divs to
283 # not be in the correct location, at least in WebKit. See
284 # https://bugs.launchpad.net/bugs/1594657 for an example.
285 elems[0].style.height = 'auto'
286 while num > 0:
287 num -= 1
288 create_page_div()
289
290 n = cols_per_screen = cps
291 # Calculate the column size so that cols_per_screen columns fit exactly in
292 # the window inline dimension, with their separator margins
293 col_size = screen_inline = scroll_viewport.inline_size()
294 margin_size = (opts.margin_left + opts.margin_right) if scroll_viewport.horizontal_writing_mode else (opts.margin_top + opts.margin_bottom)
295 # a zero margin causes scrolling issues, see https://bugs.launchpad.net/calibre/+bug/1918437
296 margin_size = max(1, margin_size)
297 gap = margin_size
298 if n > 1:
299 # Adjust the margin so that the window inline dimension satisfies
300 # col_size * n + (n-1) * 2 * margin = window_inline
301 overhang = (screen_inline + gap) % n
302 if overhang is not 0:
303 gap += n - overhang # now (screen_inline + gap) is a multiple of n
304 col_size = ((screen_inline + gap) // n) - gap
305
306 screen_block = scroll_viewport.block_size()
307 col_and_gap = col_size + gap
308
309 set_important_css(document.body, column_gap=gap + 'px', column_width=col_size + 'px', column_rule='0px inset blue',
310 min_width='0', max_width='none', min_height='0', max_height='100vh', column_fill='auto',
311 margin='0', border_width='0', padding='0', box_sizing='content-box',
312 width=scroll_viewport.width() + 'px', height=scroll_viewport.height() + 'px', overflow_wrap='break-word'
313 )
314 # Without this, webkit bleeds the margin of the first block(s) of body
315 # above the columns, which causes them to effectively be added to the
316 # page margins (the margin collapse algorithm)
317 document.body.style.setProperty('-webkit-margin-collapse', 'separate')
318 c = first_child(document.body)
319 if c:
320 # Remove page breaks on the first few elements to prevent blank pages
321 # at the start of a chapter
322 set_important_css(c, break_before='avoid')
323 if c.tagName.toLowerCase() is 'div':
324 c2 = first_child(c)
325 if c2 and not has_start_text(c):
326 # Common pattern of all content being enclosed in a wrapper
327 # <div>, see for example: https://bugs.launchpad.net/bugs/1366074
328 # In this case, we also modify the first child of the div
329 # as long as there was no text before it.
330 set_important_css(c2, break_before='avoid')
331
332 if first_layout:
333 # Because of a bug in webkit column mode, svg elements defined with
334 # width 100% are wider than body and lead to a blank page after the
335 # current page (when cols_per_screen == 1). Similarly img elements
336 # with height=100% overflow the first column
337 is_full_screen_layout = is_single_page
338 if not is_full_screen_layout:
339 has_no_more_than_two_columns = (scroll_viewport.paged_content_inline_size() < 2 * screen_inline + 10)
340 if has_no_more_than_two_columns and single_screen:
341 if only_img and imgs.length and get_bounding_client_rect(imgs[0]).left < screen_inline:
342 is_full_screen_layout = True
343 if has_svg and svgs.length == 1 and get_bounding_client_rect(svgs[0]).left < screen_inline:
344 is_full_screen_layout = True
345 if is_full_screen_layout and only_img and cols_per_screen > 1:
346 cols_per_screen = 1
347 col_size = screen_inline
348 col_and_gap = col_size + gap
349 document.body.style.columnWidth = f'100vw'
350
351 def check_column_sizes():
352 nc = get_number_of_cols(True)
353 if Math.floor(nc) is not nc:
354 data = {
355 'col_size': col_size, 'gap': gap, 'scrollWidth': scroll_viewport.paged_content_inline_size(),
356 'ncols': nc, 'screen_inline': screen_inline
357 }
358 print(
359 'WARNING: column layout broken, probably because there is some non-reflowable'
360 ' content in the book whose inline size is greater than the column size',
361 data
362 )
363
364 check_column_sizes()
365 _in_paged_mode = True
366 fit_images()
367 scroll_resize_bug_watcher.layout_done()
368 return gap
369
370
371 def current_scroll_offset():
372 return scroll_viewport.inline_pos()
373
374
375 def scroll_to_offset(offset):
376 scroll_viewport.scroll_to_in_inline_direction(offset)
377
378
379 def scroll_to_column(number, notify=False, duration=1000):
380 nonlocal last_scrolled_to_column
381 last_scrolled_to_column = number
382 pos = number * col_and_gap
383 limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size()
384 pos = min(pos, limit)
385 scroll_to_offset(pos)
386 scroll_resize_bug_watcher.scrolled(pos, limit)
387
388
389 def scroll_to_pos(pos, notify=False, duration=1000):
390 nonlocal last_scrolled_to_column
391 # Scroll to the column containing pos
392 if jstype(pos) is not 'number':
393 print(pos, 'is not a number, cannot scroll to it!')
394 return
395 if is_full_screen_layout:
396 scroll_to_offset(0)
397 last_scrolled_to_column = 0
398 return
399 scroll_to_column(column_at(pos), notify=notify, duration=duration)
400
401
402 def scroll_to_previous_position(fsd):
403 fsd = fsd or next_spine_item.forward_scroll_data
404 next_spine_item.forward_scroll_data = None
405 if 0 < fsd.cols_left < cols_per_screen and cols_per_screen < get_number_of_cols():
406 scroll_resize_bug_watcher.last_command = scroll_to_previous_position.bind(None, fsd)
407 scroll_to_column(fsd.current_col)
408 return True
409
410
411 def scroll_to_fraction(frac, on_initial_load):
412 # Scroll to the position represented by frac (number between 0 and 1)
413 if on_initial_load and frac is 1 and is_return() and scroll_to_previous_position():
414 return
415 scroll_resize_bug_watcher.last_command = scroll_to_fraction.bind(None, frac, False)
416 pos = Math.floor(scroll_viewport.paged_content_inline_size() * frac)
417 scroll_to_pos(pos)
418
419
420 def column_boundaries():
421 # Return the column numbers at the left edge and after the right edge
422 # of the viewport
423 l = column_at(current_scroll_offset() + 10)
424 return l, l + cols_per_screen
425
426
427 def column_at_current_scroll_offset():
428 return column_at(current_scroll_offset() + 10)
429
430
431 def current_column_location():
432 # The location of the starting edge of the first column currently
433 # visible in the viewport
434 if is_full_screen_layout:
435 return 0
436 return column_at_current_scroll_offset() * col_and_gap
437
438
439 def number_of_cols_left():
440 current_col = column_at(current_scroll_offset() + 10)
441 cols_left = get_number_of_cols() - (current_col + cols_per_screen)
442 return Math.max(0, cols_left)
443
444
445 def next_screen_location():
446 # The position to scroll to for the next screen (which could contain
447 # more than one pages). Returns -1 if no further scrolling is possible.
448 if is_full_screen_layout:
449 return -1
450 cc = current_column_location()
451 ans = cc + screen_inline + 1
452 if cols_per_screen > 1 and 0 < number_of_cols_left() < cols_per_screen:
453 return -1 # Only blank, dummy pages left
454 limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size()
455 if limit < col_and_gap:
456 return -1
457 if ans > limit:
458 current_pos = Math.ceil(current_scroll_offset())
459 ans = limit if current_pos < limit else -1
460 if cols_per_screen is 1 and ans is not -1 and ans - current_pos < col_size:
461 ans = -1 # can't scroll partial columns
462 return ans
463
464
465 def previous_screen_location():
466 # The position to scroll to for the previous screen (which could contain
467 # more than one pages). Returns -1 if no further scrolling is possible.
468 if is_full_screen_layout:
469 return -1
470 cc = current_column_location()
471 ans = cc - cols_per_screen * col_and_gap
472 if ans < 0:
473 # We ignore small scrolls (less than 15px) when going to previous
474 # screen
475 ans = 0 if current_scroll_offset() > 15 else -1
476 return ans
477
478
479 def next_col_location():
480 # The position to scroll to for the next column (same as
481 # next_screen_location() if columns per screen == 1). Returns -1 if no
482 # further scrolling is possible.
483 if is_full_screen_layout:
484 return -1
485 cc = current_column_location()
486 ans = cc + col_and_gap
487 limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size()
488 # print(f'cc={cc} col_and_gap={col_and_gap} ans={ans} limit={limit}'
489 # f' content_inline_size={scroll_viewport.paged_content_inline_size()}'
490 # f' inline={scroll_viewport.inline_size()} current_scroll_offset={current_scroll_offset()}')
491 if ans > limit:
492 if Math.ceil(current_scroll_offset()) < limit and column_at(limit) > column_at_current_scroll_offset():
493 ans = limit
494 else:
495 ans = -1
496 return ans
497
498
499 def previous_col_location():
500 # The position to scroll to for the previous column (same as
501 # previous_screen_location() if columns per screen == 1). Returns -1 if
502 # no further scrolling is possible.
503 if is_full_screen_layout:
504 return -1
505 cc = current_column_location()
506 ans = cc - col_and_gap
507 if ans < 0:
508 if Math.floor(current_scroll_offset()) > 0 and column_at(0) < column_at_current_scroll_offset():
509 ans = 0
510 else:
511 ans = -1
512 return ans
513
514
515 def jump_to_anchor(name):
516 # Jump to the element identified by anchor name.
517 elem = document.getElementById(name)
518 if not elem:
519 elems = document.getElementsByName(name)
520 if elems:
521 elem = elems[0]
522 if not elem:
523 return
524 scroll_to_elem(elem)
525
526
527 def scrollable_element(elem):
528 # bounding rect calculation for an inline element containing a block
529 # element that spans multiple columns is incorrect. Detect the common case
530 # of this and avoid it. See https://bugs.launchpad.net/calibre/+bug/1918437
531 # for a test case.
532 if not in_paged_mode() or window.getComputedStyle(elem).display.indexOf('inline') < 0 or not elem.firstElementChild:
533 return elem
534 if window.getComputedStyle(elem.firstElementChild).display.indexOf('block') > -1 and elem.getBoundingClientRect().top < -100:
535 return elem.firstElementChild
536 return elem
537
538
539 def scroll_to_elem(elem):
540 elem = scrollable_element(elem)
541 scroll_viewport.scroll_into_view(elem)
542
543 if in_paged_mode():
544 # Ensure we are scrolled to the column containing elem
545
546 # Because of a bug in WebKit's getBoundingClientRect() in column
547 # mode, this position can be inaccurate, see
548 # https://bugs.launchpad.net/calibre/+bug/1132641 for a test case.
549 # The usual symptom of the inaccuracy is br.top is highly negative.
550 br = get_bounding_client_rect(elem)
551 if br.top < -100:
552 # This only works because of the preceding call to
553 # elem.scrollIntoView(). However, in some cases it gives
554 # inaccurate results, so we prefer the bounding client rect,
555 # when possible.
556
557 # In horizontal writing, the inline start position depends on the direction
558 if scroll_viewport.horizontal_writing_mode:
559 inline_start = elem.scrollLeft if scroll_viewport.ltr else elem.scrollRight
560 # In vertical writing, the inline start position is always the top since
561 # vertical text only flows top-to-bottom
562 else:
563 inline_start = elem.scrollTop
564 else:
565 # If we can use the rect, just use the simpler viewport helper function
566 inline_start = scroll_viewport.rect_inline_start(br)
567
568 scroll_to_pos(scroll_viewport.viewport_to_document_inline(inline_start + 2, elem.ownerDocument))
569
570
571 def snap_to_selection():
572 # Ensure that the viewport is positioned at the start of the column
573 # containing the start of the current selection
574 if in_paged_mode():
575 sel = window.getSelection()
576 r = sel.getRangeAt(0).getBoundingClientRect()
577 node = sel.anchorNode
578 # Columns are in the inline direction, so get the beginning of the element in the inline
579 pos = scroll_viewport.viewport_to_document_inline(
580 scroll_viewport.rect_inline_start(r), doc=node.ownerDocument)
581
582 # Ensure we are scrolled to the column containing the start of the
583 # selection
584 scroll_to_pos(pos + 5)
585
586
587 def ensure_selection_boundary_visible(use_end):
588 sel = window.getSelection()
589 try:
590 rr = sel.getRangeAt(0)
591 except:
592 rr = None
593 if rr:
594 r = rr.getBoundingClientRect()
595 if r:
596 cnum = column_at_current_scroll_offset()
597 scroll_to_column(cnum)
598 node = sel.focusNode if use_end else sel.anchorNode
599 # Columns are in the inline direction, so get the beginning of the element in the inline
600 x = scroll_viewport.rect_inline_end(r) if use_end else scroll_viewport.rect_inline_start(r)
601 if x < 0 or x >= scroll_viewport.inline_size():
602 pos = scroll_viewport.viewport_to_document_inline(x, doc=node.ownerDocument)
603 scroll_to_pos(pos + 5)
604
605
606 def jump_to_cfi(cfi):
607 # Jump to the position indicated by the specified conformal fragment
608 # indicator.
609 scroll_resize_bug_watcher.last_command = jump_to_cfi.bind(None, cfi)
610 cfi_scroll_to(cfi, def (x, y):
611 if scroll_viewport.horizontal_writing_mode:
612 scroll_to_pos(x)
613 else:
614 scroll_to_pos(y)
615 )
616
617
618 def current_cfi():
619 # The Conformal Fragment Identifier at the current position, returns
620 # null if it could not be calculated.
621 ans = None
622 if in_paged_mode():
623 for cnum in range(cols_per_screen):
624 left = cnum * (col_and_gap + gap)
625 right = left + col_size
626 top, bottom = 0, scroll_viewport.height()
627 midx = (right - left) // 2
628 deltax = (right - left) // 24
629 deltay = (bottom - top) // 24
630 midy = (bottom - top) // 2
631 yidx = 0
632 while True:
633 yb, ya = midy - yidx * deltay, midy + yidx * deltay
634 if yb <= top or ya >= bottom:
635 break
636 yidx += 1
637 ys = [ya] if ya is yb else [yb, ya]
638 for cury in ys:
639 xidx = 0
640 while True:
641 xb, xa = midx - xidx * deltax, midx + xidx * deltax
642 if xb <= left or xa >= right:
643 break
644 xidx += 1
645 xs = [xa] if xa is xb else [xb, xa]
646 for curx in xs:
647 cfi = cfi_at_point(curx, cury)
648 if cfi:
649 # print('Viewport cfi:', cfi)
650 return cfi
651 else:
652 try:
653 ans = cfi_at_current() or None
654 except:
655 traceback.print_exc()
656 # if ans:
657 # print('Viewport cfi:', ans)
658 return ans
659
660
661 def progress_frac(frac):
662 # The current scroll position as a fraction between 0 and 1
663 if in_paged_mode():
664 limit = scroll_viewport.paged_content_inline_size() - scroll_viewport.inline_size()
665 if limit <= 0:
666 return 1 # ensures that if the book ends with a single page file the last shown percentage is 100%
667 return current_scroll_offset() / limit
668 # In flow mode, we scroll in the block direction, so use that
669 limit = scroll_viewport.document_block_size() - scroll_viewport.block_size()
670 if limit <= 0:
671 return 1
672 return Math.max(0, Math.min(scroll_viewport.block_pos() / limit, 1))
673
674
675 def page_counts():
676 if in_paged_mode():
677 return {'current': column_at_current_scroll_offset(), 'total': get_number_of_cols(), 'pages_per_screen': cols_per_screen}
678 doc_size = scroll_viewport.document_block_size()
679 screen_size = scroll_viewport.block_size()
680 pos = scroll_viewport.block_pos()
681 return {
682 'current': (pos + 10) // screen_size,
683 'total': doc_size // screen_size,
684 'pages_per_screen': 1
685 }
686
687
688 def next_spine_item(backward):
689 if not backward:
690 csi = current_spine_item()
691 next_spine_item.forward_scroll_data = {
692 'cols_per_screen': cols_per_screen, 'cols_left': number_of_cols_left(),
693 'spine_index': csi.index, 'spine_name': csi.name, 'current_col': column_at(current_scroll_offset() + 10)
694 }
695 get_boss().send_message('next_spine_item', previous=backward)
696
697
698 def is_return():
699 fsd = next_spine_item.forward_scroll_data
700 csi = current_spine_item()
701 return fsd and fsd.cols_per_screen is cols_per_screen and fsd.spine_index is csi.index and fsd.spine_name is csi.name
702
703
704 class WheelState:
705 last_event_mode = 'page'
706 last_event_at = -10000
707 last_event_backwards = False
708 accumulated_scroll = 0
709
710 def reset(self):
711 self.last_event_mode = WheelState.last_event_mode
712 self.last_event_at = WheelState.last_event_at
713 self.last_event_backwards = WheelState.last_event_backwards
714 self.accumulated_scroll = WheelState.accumulated_scroll
715
716 def add_pixel_scroll(self, backward, delta, scroll_func):
717 now = window.performance.now()
718 if now - self.last_event_at > 1000 or self.last_event_backwards is not backward or self.last_event_mode is not 'pixel':
719 self.accumulated_scroll = 0
720 self.last_event_mode = 'pixel'
721 self.last_event_at = now
722 self.last_event_backwards = backward
723 self.accumulated_scroll += delta
724 if self.accumulated_scroll > opts.paged_pixel_scroll_threshold:
725 self.reset()
726 scroll_func(backward)
727
728
729 class HandleWheel:
730 def __init__(self):
731 self.vertical_state = WheelState()
732 self.horizontal_state = WheelState()
733
734 def onwheel(self, evt):
735 if not (evt.deltaY or evt.deltaX):
736 return
737 major_axis_vertical = True
738 if evt.deltaY:
739 if evt.deltaX:
740 major_axis_vertical = Math.abs(evt.deltaY) >= Math.abs(evt.deltaX)
741 else:
742 major_axis_vertical = False
743 if major_axis_vertical:
744 backward = evt.deltaY < 0
745 if evt.deltaMode is window.WheelEvent.DOM_DELTA_PIXEL:
746 self.vertical_state.add_pixel_scroll(backward, Math.abs(evt.deltaY), self.do_scroll)
747 else:
748 self.vertical_state.reset()
749 self.do_scroll(backward)
750 else:
751 if opts.paged_wheel_section_jumps:
752 backward = evt.deltaX < 0
753 if evt.deltaMode is window.WheelEvent.DOM_DELTA_PIXEL:
754 self.horizontal_state.add_pixel_scroll(backward, Math.abs(evt.deltaX), self.do_section_jump)
755 else:
756 self.horizontal_state.reset()
757 self.do_section_jump(backward)
758
759 def do_scroll(self, backward):
760 if opts.paged_wheel_scrolls_by_screen:
761 pos = previous_screen_location() if backward else next_screen_location()
762 else:
763 pos = previous_col_location() if backward else next_col_location()
764 if pos is -1:
765 next_spine_item(backward)
766 else:
767 scroll_to_pos(pos)
768
769 def do_section_jump(self, backward):
770 get_boss().send_message('next_section', forward=not backward)
771
772 wheel_handler = HandleWheel()
773 onwheel = wheel_handler.onwheel
774
775
776 def scroll_by_page(backward, by_screen, flip_if_rtl_page_progression):
777 if flip_if_rtl_page_progression and rtl_page_progression():
778 backward = not backward
779
780 if by_screen:
781 pos = previous_screen_location() if backward else next_screen_location()
782 pages = cols_per_screen
783 else:
784 pos = previous_col_location() if backward else next_col_location()
785 pages = 1
786 if pos is -1:
787 # don't report human scroll since we don't know if a full page was
788 # scrolled or not
789 next_spine_item(backward)
790 else:
791 if not backward:
792 nc = get_number_of_cols()
793 scrolled_frac = (pages / nc) if nc > 0 else 0
794 get_boss().report_human_scroll(scrolled_frac)
795 else:
796 get_boss().report_human_scroll()
797 scroll_to_pos(pos)
798
799
800 def scroll_to_extend_annotation(backward):
801 pos = previous_col_location() if backward else next_col_location()
802 if pos is -1:
803 return False
804 scroll_to_pos(pos)
805 return True
806
807
808 def handle_shortcut(sc_name, evt):
809 if sc_name is 'up':
810 scroll_by_page(backward=True, by_screen=True, flip_if_rtl_page_progression=False)
811 return True
812 if sc_name is 'down':
813 scroll_by_page(backward=False, by_screen=True, flip_if_rtl_page_progression=False)
814 return True
815 if sc_name is 'start_of_file':
816 get_boss().report_human_scroll()
817 scroll_to_offset(0)
818 return True
819 if sc_name is 'end_of_file':
820 get_boss().report_human_scroll()
821 scroll_to_offset(scroll_viewport.document_inline_size())
822 return True
823 if sc_name is 'left':
824 scroll_by_page(backward=True, by_screen=False, flip_if_rtl_page_progression=True)
825 return True
826 if sc_name is 'right':
827 scroll_by_page(backward=False, by_screen=False, flip_if_rtl_page_progression=True)
828 return True
829 if sc_name is 'start_of_book':
830 get_boss().report_human_scroll()
831 get_boss().send_message('goto_doc_boundary', start=True)
832 return True
833 if sc_name is 'end_of_book':
834 get_boss().report_human_scroll()
835 get_boss().send_message('goto_doc_boundary', start=False)
836 return True
837 if sc_name is 'pageup':
838 scroll_by_page(backward=True, by_screen=True, flip_if_rtl_page_progression=False)
839 return True
840 if sc_name is 'pagedown':
841 scroll_by_page(backward=False, by_screen=True, flip_if_rtl_page_progression=False)
842 return True
843 if sc_name is 'toggle_autoscroll':
844 auto_scroll_action('toggle')
845 return True
846 return False
847
848
849 def handle_gesture(gesture):
850 # Gesture progression direction is determined in the gesture code,
851 # don't set flip_if_rtl_page_progression=True here.
852 if gesture.resolved_action is 'next_section':
853 get_boss().send_message('next_section', forward=True)
854 elif gesture.resolved_action is 'prev_section':
855 get_boss().send_message('next_section', forward=False)
856 elif gesture.resolved_action is 'next_screen':
857 scroll_by_page(False, True)
858 elif gesture.resolved_action is 'prev_screen':
859 scroll_by_page(True, True)
860 elif gesture.resolved_action is 'prev_page':
861 scroll_by_page(True, False)
862 elif gesture.resolved_action is 'next_page':
863 scroll_by_page(False, False)
864
865
866 def get_bounding_client_rect(elem):
867 br = elem.getBoundingClientRect()
868 if br.width is 0 and br.height is 0 and br.x is 0 and br.y is 0:
869 # getBoundingClientRect() fails sometimes, see https://bugs.launchpad.net/calibre/+bug/2037543
870 r = document.createRange()
871 r.selectNodeContents(elem)
872 br = r.getBoundingClientRect()
873 return br
874
875
876 anchor_funcs = {
877 'pos_for_elem': def pos_for_elem(elem):
878 if not elem:
879 return 0
880 elem = scrollable_element(elem)
881 br = get_bounding_client_rect(elem)
882 pos = scroll_viewport.viewport_to_document_inline(
883 scroll_viewport.rect_inline_start(br))
884 return column_at(pos)
885 ,
886 'visibility': def visibility(pos):
887 first = column_at(current_scroll_offset() + 10)
888 if pos < first:
889 return -1
890 if pos < first + cols_per_screen:
891 return 0
892 return 1
893 ,
894 'cmp': def cmp(a, b):
895 return a - b
896 ,
897 'get_bounding_client_rect': get_bounding_client_rect,
898 }
899
900
901 class ResizeManager:
902 def __init__(self):
903 self.reset()
904
905 def reset(self):
906 self.resize_in_progress = None
907 self.last_transition = None
908
909 def start_resize(self, width, height):
910 self.resize_in_progress = {'width': width, 'height': height, 'column': last_scrolled_to_column}
911
912 def end_resize(self):
913 if not self.resize_in_progress:
914 return
915 rp, self.resize_in_progress = self.resize_in_progress, None
916 transition = {'before': rp, 'after': {
917 'width': scroll_viewport.width(), 'height': scroll_viewport.height(), 'column': last_scrolled_to_column}}
918 if self.is_inverse_transition(transition):
919 if transition.after.column is not self.last_transition.before.column:
920 scroll_to_column(transition.after.column)
921 transition.after.column = last_scrolled_to_column
922 self.last_transition = transition
923
924 def is_inverse_transition(self, transition):
925 p = self.last_transition
926 if not p:
927 return False
928 p = p.after
929 n = transition.before
930 return p.column is n.column and p.width is n.width and p.height is n.height
931
932
933 resize_manager = ResizeManager()
934
935
936 def prepare_for_resize(width, height):
937 resize_manager.start_resize(width, height)
938
939
940 def resize_done():
941 resize_manager.end_resize()
942
943
944 def auto_scroll_action(action):
945 if action is 'toggle':
946 get_boss().send_message('error', errkey='no-auto-scroll-in-paged-mode', is_non_critical=True)
947 return False
948
949
950 class DragScroller:
951 INTERVAL = 500
952
953 def __init__(self):
954 self.backward = False
955 self.timer_id = None
956
957 def is_running(self):
958 return self.timer_id is not None
959
960 def start(self, backward):
961 if not self.is_running() or backward is not self.backward:
962 self.stop()
963 self.backward = backward
964 self.timer_id = window.setTimeout(self.do_one_page_turn, self.INTERVAL)
965
966 def do_one_page_turn(self):
967 pos = previous_col_location() if self.backward else next_col_location()
968 if pos >= 0:
969 scroll_to_pos(pos)
970 self.timer_id = window.setTimeout(self.do_one_page_turn, self.INTERVAL * 2)
971 else:
972 self.stop()
973
974 def stop(self):
975 if self.timer_id is not None:
976 window.clearTimeout(self.timer_id)
977 self.timer_id = None
978
979
980 drag_scroller = DragScroller()
981
982
983 def cancel_drag_scroll():
984 drag_scroller.stop()
985
986
987 def start_drag_scroll(delta):
988 drag_scroller.start(delta < 0)