Debian Codegraph @

src/pyj/read_book/footnotes.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 from dom import clear
6 from iframe_comm import IframeClient
7 from read_book.globals import runtime, current_spine_item, set_current_spine_item
8 from read_book.resources import finalize_resources, unserialize_html
9 from read_book.settings import (
10 apply_settings, set_color_scheme_class, update_settings
11 )
12
13 block_names = dict.fromkeys(['p', 'div', 'li', 'td', 'h1', 'h2', 'h2', 'h3', 'h4', 'h5', 'h6', 'body'], True).as_object()
14 block_display_styles = dict.fromkeys(['block', 'list-item', 'table-cell', 'table'], True).as_object()
15
16
17 def elem_roles(elem):
18 return {k.toLowerCase(): True for k in (elem.getAttribute('role') or '').split(' ')}
19
20
21 def epub_type(elem):
22 for a in elem.attributes:
23 if a.nodeName.toLowerCase() == 'epub:type' and a.nodeValue:
24 return a.nodeValue
25
26
27 def get_containing_block(node):
28 while node and node.tagName and block_names[node.tagName.toLowerCase()] is not True:
29 node = node.parentNode
30 return node
31
32
33 def is_footnote_link(a, dest_name, dest_frag, src_name, link_to_map):
34 roles = elem_roles(a)
35 if roles['doc-noteref'] or roles['doc-biblioref'] or roles['doc-glossref']:
36 return True
37 if roles['doc-link']:
38 return False
39 if epub_type(a) is 'noteref':
40 return True
41
42 # Check if node or any of its first few parents have vertical-align set
43 x, num = a, 3
44 while x and num > 0:
45 style = window.getComputedStyle(x)
46 if not is_footnote_link.inline_displays[style.display]:
47 break
48 if is_footnote_link.vert_aligns[style.verticalAlign]:
49 return True
50 x = x.parentNode
51 num -= 1
52
53 # Check if node has a single child with the appropriate css
54 children = [x for x in a.childNodes if x.nodeType is Node.ELEMENT_NODE]
55 if children.length == 1:
56 style = window.getComputedStyle(children[0])
57 if is_footnote_link.inline_displays[style.display] and is_footnote_link.vert_aligns[style.verticalAlign]:
58 text_children = [x for x in a.childNodes if x.nodeType is Node.TEXT_NODE and x.nodeValue and /\S+/.test(x.nodeValue)]
59 if not text_children.length:
60 return True
61
62 eid = a.getAttribute('id') or a.getAttribute('name')
63 files_linking_to_self = link_to_map[src_name]
64 if eid and files_linking_to_self:
65 files_linking_to_anchor = files_linking_to_self[eid] or []
66 if files_linking_to_anchor.length > 1 or (files_linking_to_anchor.length == 1 and files_linking_to_anchor[0] is not src_name):
67 # An <a href="..." id="..."> link that is linked back from some other
68 # file in the spine, most likely an endnote. We exclude links that are
69 # the only content of their parent block tag, as these are not likely
70 # to be endnotes.
71 cb = get_containing_block(a)
72 if not cb or cb.tagName.toLowerCase() == 'body':
73 return False
74 ltext = a.textContent
75 if not ltext:
76 return False
77 ctext = cb.textContent
78 if not ctext:
79 return False
80 if ctext.strip() is ltext.strip():
81 return False
82 return True
83
84 return False
85
86
87 is_footnote_link.inline_displays = {'inline': True, 'inline-block': True}
88 is_footnote_link.vert_aligns = {'sub': True, 'super': True, 'top': True, 'bottom': True}
89
90
91 def is_epub_footnote(node):
92 et = epub_type(node)
93 if et:
94 et = et.toLowerCase()
95 if et is 'note' or et is 'footnote' or et is 'rearnote':
96 return True
97 roles = elem_roles(node)
98 if roles['doc-note'] or roles['doc-footnote'] or roles['doc-rearnote']:
99 return True
100 return False
101
102
103 def get_note_container(node):
104 while node and block_names[node.tagName.toLowerCase()] is not True and block_display_styles[window.getComputedStyle(node).display] is not True:
105 node = node.parentNode
106 return node
107
108
109 def get_parents_and_self(node):
110 ans = []
111 while node and node is not document.body:
112 ans.push(node)
113 node = node.parentNode
114 return ans
115
116
117 def get_page_break(node):
118 style = window.getComputedStyle(node)
119 return {
120 'before': get_page_break.on[style.getPropertyValue('page-break-before')] is True,
121 'after': get_page_break.on[style.getPropertyValue('page-break-after')] is True,
122 }
123 get_page_break.on = {'always': True, 'left': True, 'right': True}
124
125
126 def hide_children(node):
127 for child in node.childNodes:
128 if child.nodeType is Node.ELEMENT_NODE:
129 if child.do_not_hide:
130 hide_children(child)
131 v'delete child.do_not_hide'
132 else:
133 child.style.display = 'none'
134
135
136 def unhide_tree(elem):
137 elem.do_not_hide = True
138 for c in elem.getElementsByTagName('*'):
139 c.do_not_hide = True
140
141
142 ok_list_types = {'disc': True, 'circle': True, 'square': True}
143
144
145 def is_new_footnote_start(elem, start_elem):
146 c = get_note_container(elem)
147 return c is not start_elem and c is not start_elem.firstElementChild
148
149
150 def show_footnote(target, known_anchors):
151 if not target:
152 return
153 start_elem = document.getElementById(target)
154 if not start_elem:
155 return
156 start_elem = get_note_container(start_elem)
157 for elem in get_parents_and_self(start_elem):
158 elem.do_not_hide = True
159 style = window.getComputedStyle(elem)
160 if style.display is 'list-item' and ok_list_types[style.listStyleType] is not True:
161 # We cannot display list numbers since they will be
162 # incorrect as we are removing siblings of this element.
163 elem.style.listStyleType = 'none'
164 if is_epub_footnote(start_elem):
165 unhide_tree(start_elem)
166 else:
167 # Try to detect natural boundaries based on markup for this note
168 found_note_start = False
169 for elem in document.documentElement.getElementsByTagName('*'):
170 if found_note_start:
171 eid = elem.getAttribute('id')
172 if eid is not target and known_anchors[eid] and is_new_footnote_start(elem, start_elem):
173 # console.log('Breaking footnote on anchor: ' + elem.getAttribute('id'))
174 v'delete get_note_container(elem).do_not_hide'
175 break
176 pb = get_page_break(elem)
177 if pb.before:
178 # console.log('Breaking footnote on page break before')
179 break
180 if pb.after:
181 unhide_tree(elem)
182 # console.log('Breaking footnote on page break after')
183 break
184 elem.do_not_hide = True
185 else if elem is start_elem:
186 found_note_start = True
187
188 hide_children(document.body)
189 window.location.hash = '#' + target
190
191
192 class PopupIframeBoss:
193 def __init__(self):
194 handlers = {
195 'initialize': self.initialize,
196 'clear': self.on_clear,
197 'display': self.display,
198 }
199 self.comm = IframeClient(handlers, 'popup-iframe')
200 self.blob_url_map = {}
201 self.name = None
202 self.frag = None
203 self.link_attr = None
204
205 def initialize(self, data):
206 window.addEventListener('error', self.on_error)
207 window.addEventListener('keydown', self.on_keydown)
208 document.addEventListener('contextmenu', def (ev):
209 ev.preventDefault()
210 )
211
212 def on_keydown(self, ev):
213 if ev.key is 'Escape':
214 self.comm.send_message('close_requested', from_keypress=True)
215
216 def on_error(self, evt):
217 msg = evt.message
218 script_url = evt.filename
219 line_number = evt.lineno
220 column_number = evt.colno
221 error_object = evt.error
222 evt.stopPropagation(), evt.preventDefault()
223 if error_object is None:
224 # This happens for cross-domain errors (probably javascript injected
225 # into the browser via extensions/ userscripts and the like). It also
226 # happens all the time when using Chrome on Safari
227 console.log(f'Unhandled error from external javascript, ignoring: {msg} {script_url} {line_number}:{column_number}')
228 else:
229 console.log(error_object)
230
231 def display(self, data):
232 self.book = data.book
233 self.name = data.name
234 self.frag = data.frag
235 self.link_attr = 'data-' + self.book.manifest.link_uid
236 spine = self.book.manifest.spine
237 index = spine.indexOf(data.name)
238 set_current_spine_item({
239 'name': data.name,
240 'is_first': index is 0,
241 'is_last': index is spine.length - 1,
242 'index': index,
243 'initial_position': data.initial_position
244 })
245 update_settings(data.settings)
246 for name in self.blob_url_map:
247 window.URL.revokeObjectURL(self.blob_url_map[name])
248 document.body.style.removeProperty('font-family')
249 root_data, self.mathjax, self.blob_url_map = finalize_resources(self.book, data.name, data.resource_data)
250 self.resource_urls = unserialize_html(root_data, self.content_loaded, self.show_only_footnote, data.name)
251
252 def connect_links(self):
253 for a in document.body.querySelectorAll(f'a[{self.link_attr}]'):
254 a.addEventListener('click', self.link_activated)
255 if runtime.is_standalone_viewer:
256 # links with a target get turned into requests to open a new window by Qt
257 for a in document.body.querySelectorAll('a[target]'):
258 a.removeAttribute('target')
259
260 def link_activated(self, evt):
261 try:
262 data = JSON.parse(evt.currentTarget.getAttribute(self.link_attr))
263 except:
264 print('WARNING: Failed to parse link data {}, ignoring'.format(evt.currentTarget?.getAttribute?(self.link_attr)))
265 return
266 self.activate_link(data.name, data.frag, evt.currentTarget)
267
268 def activate_link(self, name, frag, target_elem):
269 if not name:
270 name = current_spine_item().name
271 try:
272 is_popup = is_footnote_link(target_elem, name, frag, current_spine_item().name, self.book.manifest.link_to_map or {})
273 title = target_elem.textContent
274 except:
275 import traceback
276 traceback.print_exc()
277 is_popup = False
278 title = ''
279 self.comm.send_message('link_activated', is_popup=is_popup, name=name, frag=frag, title=title)
280
281 def on_clear(self, data):
282 clear(document.head)
283 clear(document.body)
284 document.body.textContent = data.text
285 self.name = None
286 self.frag = None
287
288 def show_only_footnote(self):
289 known_anchors = {}
290 ltm = self.book.manifest.link_to_map?[self.name]
291 if ltm:
292 known_anchors = {k: True for k in Object.keys(ltm)}
293 show_footnote(self.frag, known_anchors)
294
295 def content_loaded(self):
296 if not self.comm.encrypted_communications:
297 window.setTimeout(self.content_loaded, 2)
298 return
299 self.connect_links()
300 # this is the loading styles used to suppress scrollbars during load
301 # added in unserialize_html
302 document.head.removeChild(document.head.firstChild)
303 document.body.classList.add('calibre-footnote-container')
304 set_color_scheme_class()
305 apply_settings(True)
306 self.comm.send_message('content_loaded', height=document.documentElement.scrollHeight + 25)
307
308
309 @no_prune
310 def main():
311 main.boss = PopupIframeBoss()