Debian Codegraph @

src/pyj/editor.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 from elementmaker import E
6
7 from fs_images import fix_fullscreen_svg_images
8 from live_css import get_matched_css, get_sourceline_address
9 from qt import from_python, to_python
10
11
12 FAKE_HOST = '__FAKE_HOST__'
13 FAKE_PROTOCOL = '__FAKE_PROTOCOL__'
14
15
16 def is_hidden(elem):
17 while elem:
18 if (elem.style and (elem.style.visibility is 'hidden' or elem.style.display is 'none')):
19 return True
20 elem = elem.parentNode
21 return False
22
23
24 def is_block(elem):
25 style = window.getComputedStyle(elem)
26 return style.display is 'block' or style.display is 'flex-box' or style.display is 'box'
27
28
29 def in_table(elem):
30 while elem:
31 tn = elem.tagName.toLowerCase() if elem.tagName else ''
32 if tn is 'table':
33 return True
34 elem = elem.parentNode
35 return False
36
37
38 def find_containing_block(elem):
39 while elem and elem.dataset.isBlock is not '1':
40 elem = elem.parentNode
41 return elem
42
43
44 def line_height():
45 ans = line_height.ans
46 if not ans:
47 ds = window.getComputedStyle(document.body)
48 try:
49 # will fail if line-height = "normal"
50 lh = float(ds.lineHeight)
51 except:
52 try:
53 lh = 1.2 * float(ds.fontSize)
54 except:
55 lh = 15
56 ans = line_height.ans = max(5, lh)
57 return ans
58
59
60 def scroll_to_node(node, sync_context):
61 if node is document.body:
62 window.scrollTo(0, 0)
63 else:
64 node.scrollIntoView()
65 if sync_context:
66 window.scrollBy(0, -sync_context * line_height())
67
68
69 state = {'blocks_found': False, 'in_split_mode': False}
70
71
72 def go_to_line(lnum, sync_context):
73 for node in document.querySelectorAll(f'[data-lnum="{lnum}"]'):
74 if is_hidden(node):
75 continue
76 scroll_to_node(node, sync_context)
77 break
78
79
80 @from_python
81 @no_prune
82 def go_to_sourceline_address(sourceline, tags, sync_context):
83 nodes = document.querySelectorAll(f'[data-lnum="{sourceline}"]')
84 for index in range(nodes.length):
85 node = nodes[index]
86 if index >= tags.length or node.tagName.toLowerCase() is not tags[index]:
87 break
88 if index == tags.length - 1 and not is_hidden(node):
89 return scroll_to_node(node, sync_context)
90 go_to_line(sourceline, sync_context)
91
92
93 def line_numbers():
94 found_body = False
95 ans = []
96 for node in document.getElementsByTagName('*'):
97 if not found_body and node.tagName.toLowerCase() is 'body':
98 found_body = True
99 if found_body:
100 ans.push(node.dataset.lnum)
101 return ans
102
103
104 def find_blocks():
105 if state.blocks_found:
106 return
107 for elem in document.body.getElementsByTagName('*'):
108 if is_block(elem) and not in_table(elem):
109 elem.setAttribute('data-is-block', '1')
110 state.blocks_found = True
111
112
113 @from_python
114 @no_prune
115 def set_split_mode(enabled):
116 state.in_split_mode = enabled
117 document.body.dataset.inSplitMode = '1' if enabled else '0'
118 if enabled:
119 find_blocks()
120
121
122 def report_split(node):
123 loc = []
124 totals = []
125 parent = find_containing_block(node)
126 while parent and parent.tagName.toLowerCase() is not 'body':
127 totals.push(parent.parentNode.children.length)
128 num = 0
129 sibling = parent.previousElementSibling
130 while sibling:
131 num += 1
132 sibling = sibling.previousElementSibling
133 loc.push(num)
134 parent = parent.parentNode
135 loc.reverse()
136 totals.reverse()
137 to_python.request_split(loc, totals)
138
139
140 def onclick(event):
141 event.preventDefault()
142 if state.in_split_mode:
143 report_split(event.target)
144 else:
145 e = event.target
146 address = get_sourceline_address(e)
147 # Find the closest containing link, if any
148 href = tn = ''
149 while e and e is not document.body and e is not document and e is not document.documentElement and (tn is not 'a' or not href):
150 tn = e.tagName.toLowerCase() if e.tagName else ''
151 href = e.getAttribute('href')
152 e = e.parentNode
153 if to_python.request_sync:
154 to_python.request_sync(tn, href, address)
155 return False
156
157
158 @from_python
159 @no_prune
160 def go_to_anchor(anchor):
161 elem = document.getElementById(anchor)
162 if not elem:
163 elem = document.querySelector(f'[name="{anchor}"]')
164 if elem:
165 elem.scrollIntoView()
166 address = get_sourceline_address(elem)
167 if to_python.request_sync:
168 to_python.request_sync('', '', address)
169
170
171 @from_python
172 @no_prune
173 def live_css(editor_name, sourceline, tags):
174 all_properties = {}
175 ans = {'nodes': [], 'computed_css': all_properties, 'editor_name': editor_name, 'sourceline': sourceline, 'tags': tags}
176 target = None
177 i = 0
178 for node in document.querySelectorAll(f'[data-lnum="{sourceline}"]'):
179 tn = node.tagName.toLowerCase() if node.tagName else ''
180 if tn is not tags[i]:
181 if to_python.live_css_data:
182 to_python.live_css_data(ans)
183 return
184 i += 1
185 target = node
186 if i >= tags.length:
187 break
188 ancestor_specificity = 0
189 while target and target.ownerDocument:
190 css = get_matched_css(target, ancestor_specificity is not 0, all_properties)
191 # We want to show the Matched CSS rules header even if no rules matched
192 if css.length > 0 or ancestor_specificity is 0:
193 tn = target.tagName.toLowerCase() if target.tagName else ''
194 ans.nodes.push({
195 'name': tn,
196 'css': css, 'ancestor_specificity': -ancestor_specificity,
197 'sourceline': target.getAttribute('data-lnum')
198 })
199 target = target.parentNode
200 ancestor_specificity += 1
201 if to_python.live_css_data:
202 to_python.live_css_data(ans)
203
204
205 def check_for_maths():
206 if document.body.getElementsByTagNameNS('http://www.w3.org/1998/Math/MathML', 'math').length > 0:
207 return True
208 for s in document.scripts:
209 if s.type is 'text/x-mathjax-config':
210 return True
211 return False
212
213
214 def load_mathjax():
215 script = E.script(type='text/javascript')
216 script.async = True
217 script.src = f'{FAKE_PROTOCOL}://{FAKE_HOST}/calibre_internal-mathjax/startup.js'
218 document.head.appendChild(script)
219
220
221 if document.body:
222 settings = JSON.parse(window.navigator.userAgent.split('|')[1])
223 css = '[data-in-split-mode="1"] [data-is-block="1"]:hover { cursor: pointer !important; border-top: solid 5px green !important }'
224 if settings.os is 'macos':
225 # See settings.pyj for reason for webkit-hyphenate-character
226 css += '\n* { -webkit-hyphenate-character: "-" !important }\n'
227 document.body.addEventListener('click', onclick, True)
228 document.documentElement.appendChild(E.style(type='text/css', css))
229
230 fix_fullscreen_svg_images()
231 if check_for_maths():
232 load_mathjax()