Debian Codegraph @

src/pyj/read_book/cfi.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import hash_literals
4
5 from read_book.viewport import scroll_viewport, rem_size
6
7 # CFI escaping {{{
8 escape_pat = /[\[\],^();~@!]/g
9 unescape_pat = /[\^](.)/g
10
11
12 def escape_for_cfi(raw):
13 return (raw or '').replace(escape_pat, '^$&')
14
15
16 def unescape_from_cfi(raw):
17 return (raw or '').replace(unescape_pat, '$1')
18 # }}}
19
20
21 def fstr(d): # {{{
22 # Convert a timestamp floating point number to a string
23 ans = ''
24 if d < 0:
25 ans = '-'
26 d = -d
27 n = Math.floor(d)
28 ans += n
29 n = Math.round((d - n) * 100)
30 if n is not 0:
31 ans += '.' + (n / 10 if (n % 10 is 0) else n)
32 return ans
33 # }}}
34
35
36 def get_current_time(target): # {{{
37 return fstr(target.currentTime or 0)
38 # }}}
39
40
41 def id_is_unique(idval): # {{{
42 try:
43 multiples = document.querySelectorAll('[id=' + window.CSS.escape(idval) + ']')
44 except:
45 return False
46 if multiples and multiples.length < 2:
47 return True
48 return False
49 # }}}
50
51
52 # Convert point to character offset {{{
53 def range_has_point(range_, x, y):
54 rects = range_.getClientRects()
55 for v'var i = 0; i < rects.length; i++':
56 rect = rects[i]
57 if (rect.left <= x <= rect.right) and (rect.top <= y <= rect.bottom):
58 return True
59 return False
60
61
62 def offset_in_text_node(node, range_, x, y):
63 limits = [0, node.nodeValue.length]
64 while limits[0] is not limits[1]:
65 pivot = Math.floor((limits[0] + limits[1]) / 2)
66 lr = [limits[0], pivot]
67 rr = [pivot + 1, limits[1]]
68 range_.setStart(node, pivot)
69 range_.setEnd(node, pivot + 1)
70 if range_has_point(range_, x, y):
71 return pivot
72 range_.setStart(node, rr[0])
73 range_.setEnd(node, rr[1])
74 if range_has_point(range_, x, y):
75 limits = rr
76 continue
77 range_.setStart(node, lr[0])
78 range_.setEnd(node, lr[1])
79 if range_has_point(range_, x, y):
80 limits = lr
81 continue
82 break
83 return limits[0]
84
85
86 def find_offset_for_point(x, y, node, cdoc):
87 range_ = cdoc.createRange()
88 child = node.firstChild
89 while child:
90 if Node.TEXT_NODE <= child.nodeType <= Node.ENTITY_NODE and child.nodeValue and child.nodeValue.length:
91 range_.setStart(child, 0)
92 range_.setEnd(child, child.nodeValue.length)
93 if range_has_point(range_, x, y):
94 return [child, offset_in_text_node(child, range_, x, y)]
95 child = child.nextSibling
96
97 # The point must be after the last bit of text/in the padding/border, we don't know
98 # how to get a good point in this case
99 return None, None
100
101 # }}}
102
103
104 def set_current_time(target, val): # {{{
105 if target.currentTime is undefined:
106 return
107 if target.readyState is 4 or target.readyState is 'complete':
108 target.currentTime = val + 0
109 else:
110 target.addEventListener('canplay', def (): target.currentTime=val;, False)
111 # }}}
112
113 # def encode(doc, node, offset, tail): {{{
114
115
116 def is_text_node(node):
117 return node.nodeType is Node.TEXT_NODE or node.nodeType is Node.CDATA_SECTION_NODE
118
119
120 def text_length_in_range_wrapper(node):
121 p = node.firstChild
122 ans = 0
123 while p:
124 if is_text_node(p):
125 ans += p.nodeValue.length
126 elif p.nodeType is Node.ELEMENT_NODE and p.dataset?.calibreRangeWrapper:
127 ans += text_length_in_range_wrapper(p)
128 p = p.nextSibling
129 return ans
130
131
132 def adjust_node_for_text_offset(node):
133 if node.parentNode and node.parentNode.dataset?.calibreRangeWrapper:
134 node = node.parentNode
135 offset = 0
136 adjusted = False
137 while True:
138 p = node.previousSibling
139 if not p or p.nodeType > Node.COMMENT_NODE:
140 break
141 if is_text_node(p):
142 offset += p.nodeValue.length
143 elif p.nodeType is Node.ELEMENT_NODE and p.dataset?.calibreRangeWrapper:
144 offset += text_length_in_range_wrapper(p)
145 node = p
146 adjusted = True
147 if adjusted and node.nodeType is Node.ELEMENT_NODE and node.dataset?.calibreRangeWrapper:
148 if not node.firstChild or node.firstChild.nodeType is not Node.TEXT_NODE:
149 node.insertBefore(document.createTextNode(''), node.firstChild or None)
150 node = node.firstChild
151 return node, offset, adjusted
152
153
154 def unwrapped_nodes(range_wrapper):
155 ans = []
156 for child in range_wrapper.childNodes:
157 if child.nodeType is Node.ELEMENT_NODE and child.dataset?.calibreRangeWrapper:
158 ans = ans.concat(unwrapped_nodes(child))
159 else:
160 ans.push(child)
161 return ans
162
163
164 def increment_index_for_child(child, index, sentinel):
165 is_element = child.nodeType is Node.ELEMENT_NODE
166 if is_element and child.dataset?.calibreRangeWrapper:
167 nodes = unwrapped_nodes(child)
168 index = increment_index_for_children(nodes, index, sentinel)
169 else:
170 index |= 1 # increment if even
171 if is_element:
172 index += 1
173 return index
174
175
176 def increment_index_for_children(children, index, sentinel):
177 for i in range(children.length):
178 child = children[i]
179 index = increment_index_for_child(child, index, sentinel)
180 if child is sentinel:
181 break
182 return index
183
184
185 def non_range_wrapper_parent(node):
186 p = node.parentNode
187 child = node
188 while p.dataset?.calibreRangeWrapper:
189 child = p
190 p = p.parentNode
191 return p, child
192
193
194 def encode(doc, node, offset, tail):
195 cfi = tail or ''
196 # Handle the offset, if any
197 if node.nodeType is Node.ELEMENT_NODE:
198 if jstype(offset) is 'number':
199 q = node.childNodes.item(offset)
200 if q:
201 if q.nodeType is Node.ELEMENT_NODE:
202 node = q
203 if node.dataset?.calibreRangeWrapper:
204 if not node.firstChild:
205 node.appendChild(document.createTextNode(''))
206 node = node.firstChild
207 elif node.dataset?.calibreRangeWrapper:
208 if not node.firstChild:
209 node.appendChild(document.createTextNode(''))
210 node = node.firstChild
211 if is_text_node(node):
212 offset = offset or 0
213 adjusted_node, additional_offset, adjusted = adjust_node_for_text_offset(node)
214 if adjusted:
215 node = adjusted_node
216 offset += additional_offset
217 cfi = ':' + offset + cfi
218 elif node.nodeType is not Node.ELEMENT_NODE: # Not handled
219 print(f"Offsets for nodes of type {node.nodeType} are not handled")
220
221 # Construct the path to node from root
222 is_first = True
223 while node is not doc:
224 p, sentinel = non_range_wrapper_parent(node)
225 if not p:
226 if node.nodeType == Node.DOCUMENT_NODE: # Document node (iframe)
227 win = node.defaultView
228 if win.frameElement:
229 node = win.frameElement
230 cfi = '!' + cfi
231 continue
232 break
233
234 # Find position of node in parent
235 index = increment_index_for_children(p.childNodes, 0, sentinel)
236 if is_first:
237 is_first = False
238 if node.nodeType is Node.ELEMENT_NODE and node.dataset?.calibreRangeWrapper:
239 index -= 1
240 # Add id assertions for robustness where possible
241 id = node.id
242 idspec = ''
243 if id and id_is_unique(id):
244 idspec = ('[' + escape_for_cfi(id) + ']')
245 cfi = '/' + index + idspec + cfi
246 node = p
247
248 return cfi
249 # }}}
250
251 # def decode(cfi, doc): {{{
252
253
254 def node_at_index(nodes, target, index, iter_text_nodes):
255 for i in range(nodes.length):
256 node = nodes[i]
257 is_element = node.nodeType is Node.ELEMENT_NODE
258 if is_element and node.dataset?.calibreRangeWrapper:
259 q, index = node_at_index(unwrapped_nodes(node), target, index, iter_text_nodes)
260 if q:
261 return q, index
262 continue
263 if (iter_text_nodes and not is_text_node(node)) or (not iter_text_nodes and not is_element):
264 continue
265 if index is target:
266 return node, index
267 index += 1
268 return None, index
269
270
271 def node_for_path_step(parent, target, assertion):
272 if assertion:
273 q = document.getElementById(assertion)
274 if q and id_is_unique(assertion):
275 return q
276 is_element = target % 2 == 0
277 target //= 2
278 if is_element and target > 0:
279 target -= 1
280 return node_at_index(parent.childNodes, target, 0, not is_element)[0]
281
282
283 def node_for_text_offset(nodes, offset, first_node):
284 last_text_node = None
285 seen_first = False
286 for i in range(nodes.length):
287 node = nodes[i]
288 if not seen_first:
289 if not first_node or node.isSameNode(first_node):
290 seen_first = True
291 else:
292 continue
293 if is_text_node(node):
294 l = node.nodeValue.length
295 if offset <= l:
296 return node, offset, True
297 last_text_node = node
298 offset -= l
299 # mathml nodes don't have dataset
300 elif node.nodeType is Node.ELEMENT_NODE and node.dataset?.calibreRangeWrapper:
301 qn, offset, ok = node_for_text_offset(unwrapped_nodes(node), offset)
302 if ok:
303 return qn, offset, True
304 return last_text_node, offset, False
305
306
307 # Based on a CFI string, returns a decoded CFI, with members:
308 #
309 # node: The node to which the CFI refers.
310 # time: If the CFI refers to a video or sound, this is the time within such to which it refers.
311 # x, y: If the CFI defines a spatial offset (technically only valid for images and videos),
312 # these are the X and Y percentages from the top-left of the image or video.
313 # Note that Calibre has a fallback to set CFIs with spatial offset on the HTML document,
314 # and interprets them as a position within the Calibre-rendered document.
315 # forward: This is set to True if the CFI had a side bias of 'a' (meaning 'after').
316 # offset: When the CFI refers to a text node, this is the offset (zero-based index) of the character
317 # the CFI refers to. The position is defined as being before the specified character,
318 # i.e. an offset of 0 is before the first character and an offset equal to number of characters
319 # in the text is after the last character.
320 # error: If there was a problem decoding the CFI, this is set to a string describing the error.
321 def decode(cfi, doc):
322 doc = doc or window.document
323 simple_node_regex = ///
324 ^/(\d+) # The node count
325 (\[[^\]]*\])? # The optional id assertion
326 ///
327 error = None
328 node = doc
329
330 orig_cfi = cfi
331 while cfi.length > 0 and not error:
332 r = cfi.match(simple_node_regex)
333 if r: # Path step
334 target = parseInt(r[1])
335 assertion = r[2]
336 if assertion:
337 assertion = unescape_from_cfi(assertion.slice(1, assertion.length - 1))
338 q = node_for_path_step(node, target, assertion)
339 if q:
340 node = q
341 cfi = cfi.substr(r[0].length)
342 else:
343 if target:
344 error = f"No matching child found for CFI: {orig_cfi} leftover: {cfi}"
345 break
346 else:
347 cfi = cfi.substr(r[0].length)
348 else if cfi[0] is '!': # Indirection
349 if node.contentDocument:
350 node = node.contentDocument
351 cfi = cfi.substr(1)
352 else:
353 error = 'Cannot reference ' + node.nodeName + "'s content: " + cfi
354 else:
355 break
356
357 if error:
358 print(error)
359 return None
360
361 decoded = {}
362 error = None
363 offset = None
364
365 r = cfi.match(/^:(\d+)/)
366 if r:
367 # Character offset
368 offset = parseInt(r[1])
369 cfi = cfi.substr(r[0].length)
370
371 r = cfi.match(/^~(-?\d+(\.\d+)?)/)
372 if r:
373 # Temporal offset
374 decoded.time = r[1] - 0 # Coerce to number
375 cfi = cfi.substr(r[0].length)
376
377 r = cfi.match(/^@(-?\d+(\.\d+)?):(-?\d+(\.\d+)?)/)
378 if r:
379 # Spatial offset
380 decoded.x = r[1] - 0 # Coerce to number
381 decoded.y = r[3] - 0 # Coerce to number
382 cfi = cfi.substr(r[0].length)
383
384 r = cfi.match(/^\[([^\]]+)\]/)
385 if r:
386 assertion = r[1]
387 cfi = cfi.substr(r[0].length)
388 r = assertion.match(/;s=([ab])$/)
389 if r:
390 if r.index > 0 and assertion[r.index - 1] is not '^':
391 assertion = assertion.substr(0, r.index)
392 decoded.forward = (r[1] is 'a')
393 assertion = unescape_from_cfi(assertion)
394 # TODO: Handle text assertion
395
396 # Find the text node that contains the offset
397 if offset is not None:
398 orig_offset = offset
399 if node.parentNode?.nodeType is Node.ELEMENT_NODE and node.parentNode.dataset?.calibreRangeWrapper:
400 node = node.parentNode
401 qnode, offset, ok = node_for_text_offset(node.parentNode.childNodes, offset, node)
402 if not ok:
403 error = 'Offset out of range: ' + orig_offset
404 if qnode:
405 node = qnode
406 decoded.offset = offset
407
408 decoded.node = node
409 if error:
410 decoded.error = error
411 else if cfi.length > 0:
412 decoded.error = 'Undecoded CFI: ' + cfi
413
414 if decoded.error:
415 print(decoded.error)
416
417 return decoded
418 # }}}
419
420
421 def cfi_sort_key(cfi): # {{{
422 simple_node_regex = ///
423 ^/(\d+) # The node count
424 (\[[^\]]*\])? # The optional id assertion
425 ///
426 steps = []
427
428 while cfi.length > 0:
429 r = cfi.match(simple_node_regex)
430 if r: # Path step
431 target = parseInt(r[1])
432 cfi = cfi.substr(r[0].length)
433 steps.push(target)
434 else if cfi[0] is '!': # Indirection
435 cfi = cfi.substr(1)
436 else:
437 break
438
439 ans = {'steps': steps, 'text_offset': 0, 'temporal_offset': 0, 'spatial_offset': [0, 0]}
440
441 r = cfi.match(/^:(\d+)/)
442 if r:
443 # Character offset
444 offset = parseInt(r[1])
445 ans['text_offset'] = offset
446 cfi = cfi.substr(r[0].length)
447
448 r = cfi.match(/^~(-?\d+(\.\d+)?)/)
449 if r:
450 # Temporal offset
451 ans['temporal_offset'] = r[1] - 0 # Coerce to number
452 cfi = cfi.substr(r[0].length)
453
454 r = cfi.match(/^@(-?\d+(\.\d+)?):(-?\d+(\.\d+)?)/)
455 if r:
456 # Spatial offset
457 ans['spatial_offset'] = [r[1] - 0, r[3] - 0]
458 cfi = cfi.substr(r[0].length)
459 return ans
460
461
462 def create_cfi_cmp(key_map):
463 if not key_map:
464 key_map = {}
465
466 def cfi_cmp(a_cfi, b_cfi):
467 a = key_map[a_cfi]
468 if not a:
469 a = key_map[a_cfi] = cfi_sort_key(a_cfi)
470 b = key_map[b_cfi]
471 if not b:
472 b = key_map[b_cfi] = cfi_sort_key(b_cfi)
473 for i in range(min(a.steps.length, b.steps.length)):
474 diff = a.steps[i] - b.steps[i]
475 if diff is not 0:
476 return diff
477 diff = a.steps.length - b.steps.length
478 if diff is not 0:
479 return diff
480
481 if a.temporal_offset is not b.temporal_offset:
482 return a.temporal_offset - b.temporal_offset
483
484 if a.spatial_offset[0] is not b.spatial_offset[0]:
485 return a.spatial_offset[0] - b.spatial_offset[0]
486 if a.spatial_offset[1] is not b.spatial_offset[1]:
487 return a.spatial_offset[1] - b.spatial_offset[1]
488
489 if a.text_offset is not b.text_offset:
490 return a.text_offset - b.text_offset
491
492 return 0
493
494 return cfi_cmp
495
496
497 def sort_cfis(array_of_cfis):
498 key_map = {cfi: cfi_sort_key(cfi) for cfi in array_of_cfis}
499 Array.prototype.sort.call(array_of_cfis, create_cfi_cmp(key_map))
500 # }}}
501
502
503 def at(x, y, doc): # {{{
504 # x, y are in viewport coordinates
505 doc = doc or window.document
506 cdoc = doc
507 target = None
508 tail = ''
509 offset = None
510 name = None
511
512 # Drill down into iframes, etc.
513 while True:
514 target = cdoc.elementFromPoint(x, y)
515 if not target or target is cdoc.documentElement or target is cdoc.body:
516 # We ignore both html and body even though body could
517 # have text nodes under it as performance is very poor if body
518 # has large margins/padding (e.g. in fullscreen mode)
519 # A possible solution for this is to wrap all text node
520 # children of body in <span> but that is seriously ugly and
521 # might have side effects. Lets do this only if there are lots of
522 # books in the wild that actually have text children of body,
523 # and even in this case it might be better to change the input
524 # plugin to prevent this from happening.
525 # log("No element at (#{ x }, #{ y })")
526 return None
527
528 name = target.localName
529 if name not in {'iframe', 'embed', 'object'}:
530 break
531
532 cd = target.contentDocument
533 if not cd:
534 break
535
536 # We have an embedded document, transforms x, y into the co-prd
537 # system of the embedded document's viewport
538 rect = target.getBoundingClientRect()
539 x -= rect.left
540 y -= rect.top
541 cdoc = cd
542
543 (target.parentNode or target).normalize()
544
545 if name in {'audio', 'video'}:
546 tail = '~' + get_current_time(target)
547
548 if name in {'img', 'video'}:
549 rect = target.getBoundingClientRect()
550 px = ((x - rect.left) * 100) / target.offsetWidth
551 py = ((y - rect.top) * 100) / target.offsetHeight
552 tail = str.format('{}@{}:{}', tail, fstr(px), fstr(py))
553 else if name is not 'audio':
554 # Get the text offset
555 # We use a custom function instead of caretRangeFromPoint as
556 # caretRangeFromPoint does weird things when the point falls in the
557 # padding of the element
558 target, offset = find_offset_for_point(x, y, target, cdoc)
559 if target is None:
560 return None
561
562 return encode(doc, target, offset, tail)
563 # }}}
564
565
566 # Wrapper for decode(), tries to construct a range from the CFI's
567 # character offset and include it in the return value.
568 #
569 # If the CFI defines a character offset, there are three cases:
570 # Case 1. If the offset is 0 and the text node's length is zero,
571 # the range is set to None. This is a failure case, but
572 # later code will try to use the node's bounding box.
573 # Case 2. Otherwise, if the offset is >= the length of the range,
574 # then a range from the previous to the last character is created,
575 # and use_range_end_pos is set. This is the special case.
576 # Case 3. Otherwise, the range is set start at the offset and end at one character past the offset.
577 #
578 # In cases 2 and 3, the range is then checked to verify that bounding information can be obtained.
579 # If not, no range is returned.
580 #
581 # If the CFI does not define a character offset, then the spatial offset is set in the return value.
582 #
583 # Includes everything that the decode() function does, in addition to:
584 # range: A text range, as described above.
585 # use_range_end_pos: If this is True, a position calculated from the range should
586 # use the position after the last character in the range.
587 # (This is set if the offset is equal to the length of the text in the node.)
588 def decode_with_range(cfi, doc): # {{{
589 doc = doc or window.document
590 decoded = decode(cfi, doc)
591 if not decoded or not decoded.node:
592 return None
593 node = decoded.node
594 ndoc = node.ownerDocument
595 if not ndoc:
596 print(str.format('CFI node has no owner document: {} {}', cfi, node))
597 return None
598
599 range_ = None
600 position_at_end_of_range = None
601
602 if jstype(decoded.offset) is 'number':
603 # We can only create a meaningful range if the node length is
604 # positive and nonzero.
605 node_len = node.nodeValue.length if node.nodeValue else 0
606 if not node_len and node.nextSibling?.dataset?.calibreRangeWrapper and node.nextSibling.firstChild?.nodeType is Node.TEXT_NODE:
607 node = node.nextSibling.firstChild
608 node_len = node.nodeValue.length if node.nodeValue else 0
609 if node_len:
610 range_ = ndoc.createRange()
611
612 # Check for special case: End of range offset, after the last character
613 offset = decoded.offset
614 position_at_end_of_range = False
615 if offset >= node_len:
616 offset = node_len - 1
617 position_at_end_of_range = True
618
619 range_.setStart(node, offset)
620 range_.setEnd(node, offset + 1)
621 rect = range_.getBoundingClientRect()
622
623 if not rect:
624 print(str.format('Could not find caret position for {} (offset: {})', cfi, decoded.offset))
625 range_ = None
626 else:
627 print(f'Caret offset pointed to an empty text node or a non-text node for {cfi}, (offset: {decoded.offset})')
628 range_ = None
629
630 # Augment decoded with range, if found
631 decoded.range = range_
632 decoded.use_range_end_pos = position_at_end_of_range
633
634 return decoded
635
636 # }}}
637
638
639 # It's only valid to call this if you have a decoded CFI with a range included.
640 # Call decoded_to_document_position if you're not sure.
641 def decoded_range_to_document_position(decoded):
642 # Character offset
643 # Get the bounding rect of the range, in (real) viewport space
644 rect = decoded.range.getBoundingClientRect()
645 inserted_node = None
646 if not rect.width and not rect.height and not rect.left and not rect.right:
647 # this happens is range is a text node containing a newline after a
648 # <br> https://bugs.launchpad.net/bugs/1944433
649 inserted_node = document.createTextNode('\xa0')
650 decoded.range.insertNode(inserted_node)
651 rect = decoded.range.getBoundingClientRect()
652
653 # Now, get the viewport-space position (vs_pos) we want to scroll to
654 # This is a little complicated.
655 # The box we are using is a character's bounding box.
656 # First, the inline direction.
657 # We want to use the beginning of the box per the ePub CFI spec,
658 # which states character offset CFIs refer to the beginning of the
659 # character, which would be in the inline direction.
660 # Unless the flag is set to use the end of the range:
661 # (because ranges indices may not exceed the range,
662 # but CFI offsets are allowed to be one past the end.)
663 if decoded.use_range_end_pos:
664 inline_vs_pos = scroll_viewport.rect_inline_end(rect)
665 else:
666 inline_vs_pos = scroll_viewport.rect_inline_start(rect)
667
668 # Next, the block direction.
669 # If the CFI specifies a side bias, we should respect that.
670 # Otherwise, we want to use the block start.
671 if decoded.forward:
672 block_vs_pos = scroll_viewport.rect_block_end(rect)
673 else:
674 block_vs_pos = scroll_viewport.rect_block_start(rect)
675
676 if inserted_node:
677 inserted_node.parentNode.removeChild(inserted_node)
678 # Now, we need to convert these to document X and Y coordinates.
679 return scroll_viewport.viewport_to_document_inline_block(inline_vs_pos, block_vs_pos, decoded.node.ownerDocument)
680
681
682 # This will work on a decoded CFI that refers to a node or node with spatial offset.
683 # It will ignore any ranges, so call decoded_to_document_position unless you're sure the decoded CFI has no range.
684 def decoded_node_or_spatial_offset_to_document_position(decoded):
685 node = decoded.node
686 rect = node.getBoundingClientRect()
687 percentx, percenty = decoded.x, decoded.y
688 # If we have a spatial offset, base the CFI position on the offset into the object
689 if jstype(percentx) is 'number' and node.offsetWidth and jstype(percenty) is 'number' and node.offsetHeight:
690 viewx = rect.left + (percentx * node.offsetWidth) / 100
691 viewy = rect.top + (percenty * node.offsetHeight) / 100
692 doc_left, doc_top = scroll_viewport.viewport_to_document(viewx, viewy, node.ownerDocument)
693 return doc_left, doc_top
694 # Otherwise, base it on the inline and block start and end, along with side bias:
695 else:
696 if decoded.forward:
697 block_vs_pos = scroll_viewport.rect_block_end(rect)
698 else:
699 block_vs_pos = scroll_viewport.rect_block_start(rect)
700
701 inline_vs_pos = scroll_viewport.rect_inline_start(rect)
702 return scroll_viewport.viewport_to_document_inline_block(inline_vs_pos, block_vs_pos, node.ownerDocument)
703
704
705 # This will take a decoded CFI and return a document position.
706 #
707 def decoded_to_document_position(decoded):
708 node = decoded.node
709 if decoded.range is not None:
710 return decoded_range_to_document_position(decoded)
711 else if node is not None and node.getBoundingClientRect:
712 return decoded_node_or_spatial_offset_to_document_position(decoded)
713 # No range, so we can't use that, and no node, so any spatial offset is meaningless
714 return None, None
715
716
717 def scroll_to(cfi, callback, doc): # {{{
718 decoded = decode_with_range(cfi, doc)
719 if not decoded:
720 print('No location information found for cfi: ' + cfi)
721 return
722 if jstype(decoded.time) is 'number':
723 set_current_time(decoded.node, decoded.time)
724
725 def handle_text_node():
726 # Character offset
727 r = decoded.range
728 so, eo = r.startOffset, r.endOffset
729 original_node = r.startContainer
730
731 # Save the node index and its parent so we can get the node back
732 # after removing the span and normalizing the parent.
733 node_parent = original_node.parentNode
734 original_node_index = 0
735 for v'var i = 0; i < node_parent.childNodes.length; i++':
736 if node_parent.childNodes[i].isSameNode(original_node):
737 original_node_index = i
738 break
739
740 ndoc = original_node.ownerDocument or document
741 span = ndoc.createElement('span')
742 span.setAttribute('style', 'border-width: 0; padding: 0; margin: 0')
743 r.surroundContents(span)
744 scroll_viewport.scroll_into_view(span)
745 return def ():
746 nonlocal original_node, r
747 # Remove the span and get the new position now that scrolling
748 # has (hopefully) completed
749 p = span.parentNode
750 for node in span.childNodes:
751 span.removeChild(node)
752 p.insertBefore(node, span)
753 p.removeChild(span)
754 p.normalize()
755 original_node = node_parent.childNodes[original_node_index]
756 if not original_node:
757 # something bad happened, give up
758 return
759
760 # Reset the range to what it was before the span was added
761 offset = so
762 while offset > -1:
763 try:
764 r.setStart(original_node, offset)
765 break
766 except:
767 offset -= 1
768
769 offset = eo
770 while offset > -1:
771 try:
772 r.setEnd(original_node, offset)
773 break
774 except:
775 offset -= 1
776
777 doc_x, doc_y = decoded_range_to_document_position(decoded)
778
779 # Abort if CFI position is invalid
780 if doc_x is None or doc_y is None:
781 return
782
783 # Since this position will be used for the upper-left of the viewport,
784 # in RTL mode, we need to offset it by the viewport width so the
785 # position will be on the right side of the viewport,
786 # from where we start reading.
787 # (Note that adding moves left in RTL mode because of the viewport X
788 # coordinate reversal in RTL mode.)
789 if scroll_viewport.rtl:
790 doc_x += scroll_viewport.width()
791
792 if callback:
793 callback(doc_x, doc_y)
794
795 def handle_element_node():
796 node = decoded.node
797 if node.nodeType is Node.TEXT_NODE:
798 node = decoded.node = node.parentNode
799 if not node.scrollIntoView:
800 return
801 scroll_viewport.scroll_into_view(node)
802
803 return def ():
804 doc_x, doc_y = decoded_node_or_spatial_offset_to_document_position(decoded)
805
806 # Abort if CFI position is invalid
807 if doc_x is None or doc_y is None:
808 return
809
810 # Since this position will be used for the upper-left of the viewport,
811 # in RTL mode, we need to offset it by the viewport width so the
812 # position will be on the right side of the viewport,
813 # from where we start reading.
814 # (Note that adding moves left in RTL mode because of the viewport X
815 # coordinate reversal in RTL mode.)
816 if scroll_viewport.rtl:
817 doc_x += scroll_viewport.width()
818 if callback:
819 callback(doc_x, doc_y)
820
821 if decoded.range is not None:
822 fn = handle_text_node()
823 else:
824 fn = handle_element_node()
825
826 setTimeout(fn, 10)
827
828 # }}}
829
830
831 def at_point(x, y): # {{{
832 # The CFI at the specified point. Different to at() in that this method
833 # returns null if there is an error, and also calculates a point from
834 # the CFI and returns null if the calculated point is far from the
835 # original point.
836
837 def dist(p1, p2):
838 Math.sqrt(Math.pow(p1[0] - p2[0], 2), Math.pow(p1[1] - p2[1], 2))
839
840 try:
841 cfi = at(x, y)
842 except:
843 cfi = None
844 if cfi is None:
845 return None
846
847 try:
848 decoded = decode_with_range(cfi)
849 except:
850 decoded = None
851 if not decoded:
852 return None
853
854 if cfi:
855 try:
856 cfix, cfiy = decoded_to_document_position(decoded)
857 except:
858 cfix = cfiy = None
859 if cfix is None or cfiy is None or dist(scroll_viewport.viewport_to_document(x, y), [cfix, cfiy]) > 50:
860 cfi = None
861
862 return cfi
863 # }}}
864
865
866 def at_current(): # {{{
867 # We subtract one because the actual position query for CFI elements is relative to the
868 # viewport, and the viewport coordinates actually go from 0 to the size - 1.
869 # If we don't do this, the first line of queries will always fail in those cases where we
870 # start at the right of the viewport because they'll be outside the viewport
871 wini, winb = scroll_viewport.inline_size() - 1, scroll_viewport.block_size() - 1
872
873 # Don't let the deltas go too small or too large, to prevent perverse cases where
874 # we don't loop at all, loop too many times, or skip elements because we're
875 # looping too fast.
876 deltai = deltab = max(8, min(Math.ceil(rem_size() / 2), 32))
877
878 # i.e. English, Hebrew:
879 if scroll_viewport.horizontal_writing_mode:
880 # Horizontal languages always start at the top
881 startb = 0
882 endb = winb
883 if scroll_viewport.ltr:
884 # i.e. English: we scan from the left margin to the right margin
885 starti = 0
886 endi = wini
887 else:
888 # i.e. Hebrew: we scan from the right margin to the left margin
889 starti = wini
890 endi = 0
891 deltai = -deltai
892 # i.e. Japanese, Mongolian script, traditional Chinese
893 else:
894 # These languages are only top-to-bottom
895 starti = 0
896 endi = winb
897 # i.e. Japanese: To the next line is from the right margin to the left margin
898 if scroll_viewport.rtl:
899 startb = winb
900 endb = 0
901 deltab = -deltab
902 # i.e. Mongolian: To the next line is from the left margin to the right margin
903 else:
904 startb = 0
905 endb = winb
906
907 # print(f'{starti} {deltai} {endi} {startb} {deltab} {endb}')
908 # Find the bounds
909 up_boundb = max(startb, endb)
910 up_boundi = max(starti, endi)
911 low_boundb = min(startb, endb)
912 low_boundi = min(starti, endi)
913
914 # In horizontal mode, X is the inline and Y is the block,
915 # but it's reversed for vertical modes, so reverse the lookup.
916 def at_point_vertical_mode(i, b):
917 return at_point(b, i)
918
919 at_point_conditional = at_point_vertical_mode if scroll_viewport.vertical_writing_mode else at_point
920
921 def i_loop(curb):
922 curi = starti
923 # The value will be either heading toward the lower or the upper bound,
924 # so just check for exceeding either bound
925 while low_boundi <= curi <= up_boundi:
926 cfi = at_point_conditional(curi, curb)
927 if cfi:
928 # print(f'found CFI at {curi}, {curb} {cfi}\n\t{starti} {deltai} {endi} {startb} {deltab} {endb}')
929 return cfi
930 curi += deltai
931
932 curb = startb
933 cfi = None
934 while low_boundb <= curb <= up_boundb and not cfi:
935 cfi = i_loop(curb)
936 curb += deltab
937
938 if cfi:
939 return cfi
940
941 # Use a spatial offset on the html element, since we could not find a
942 # normal CFI
943 x, y = scroll_viewport.x() + (0 if scroll_viewport.ltr else scroll_viewport.width()), scroll_viewport.y()
944 de = document.documentElement
945 rect = de.getBoundingClientRect()
946 px = (x * 100) / rect.width
947 py = (y * 100) / rect.height
948 cfi = str.format('/2@{}:{}', fstr(px), fstr(py))
949
950 return cfi
951
952 # }}}
953
954
955 def cfi_for_selection(r): # {{{
956 if not r:
957 r = window.getSelection().getRangeAt(0)
958
959 def pos(container, offset):
960 nt = container.nodeType
961 if nt is Node.TEXT_NODE or nt is Node.CDATA_SECTION_NODE or nt is Node.COMMENT_NODE:
962 return container, offset
963 if nt is Node.ELEMENT_NODE and offset and container.childNodes.length > offset:
964 return container.childNodes[offset], 0
965 return container, offset
966
967 return {
968 'start': encode(r.startContainer.ownerDocument, *pos(r.startContainer, r.startOffset)),
969 'end': encode(r.endContainer.ownerDocument, *pos(r.endContainer, r.endOffset)),
970 }
971
972 # }}}
973
974
975 def range_from_cfi(start, end): # {{{
976 start = decode(start)
977 end = decode(end)
978 if not start or start.error or not end or end.error:
979 return
980 r = document.createRange()
981 r.setStart(start.node, start.offset)
982 r.setEnd(end.node, end.offset)
983 return r
984 # }}}