]> git.gir.st - VimFx.git/blob - extension/lib/hints.coffee
Support the "Default FullZoom Level" extension
[VimFx.git] / extension / lib / hints.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014, 2015.
4 #
5 # This file is part of VimFx.
6 #
7 # VimFx is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # VimFx is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
19 ###
20
21 # This file contains functions for getting markable elements, and related data,
22 # as well as for creating and inserting markers for markable elements.
23
24 huffman = require('n-ary-huffman')
25 {Marker} = require('./marker')
26 utils = require('./utils')
27
28 CONTAINER_ID = 'VimFxMarkersContainer'
29
30 Element = Ci.nsIDOMElement
31 XULDocument = Ci.nsIDOMXULDocument
32
33 # For some time we used to return the hints container from `injectHints`, and
34 # use that reference to remove the hints when needed. That’s fine in theory, but
35 # in case anything breaks we might loose that reference and end up with
36 # unremovable hints on the screen. Explicitly looking for an element with the
37 # container ID is more fail-safe.
38 removeHints = (window) ->
39 window.document.getElementById(CONTAINER_ID)?.remove()
40
41 # Create `Marker`s for every element (represented by a regular object of data
42 # about the element—a “wrapper,” a stand-in for the real element, which is only
43 # accessible in frame scripts) in `wrappers`, and insert them into `window`.
44 injectHints = (window, wrappers, viewport, options) ->
45 semantic = []
46 unsemantic = []
47 combined = []
48 markerMap = {}
49
50 for wrapper in wrappers
51 marker = new Marker(wrapper, window.document)
52 group = switch
53 when wrapper.parentIndex? then combined
54 when wrapper.semantic then semantic
55 else unsemantic
56 group.push(marker)
57 markerMap[wrapper.elementIndex] = marker
58
59 markers = semantic.concat(unsemantic)
60
61 return null if markers.length == 0
62
63 # Each marker gets a unique `z-index`, so that it can be determined if a
64 # marker overlaps another. Put more important markers (higher weight) at the
65 # end, so that they get higher `z-index`, in order not to be overlapped.
66 zIndex = 0
67 setZIndexes = (markers) ->
68 markers.sort((a, b) -> a.weight - b.weight)
69 for marker in markers when marker not instanceof huffman.BranchPoint
70 marker.markerElement.style.zIndex = zIndex++
71 # Add `z-index` space for all the children of the marker.
72 zIndex += marker.wrapper.numChildren if marker.wrapper.numChildren?
73 return
74
75 # The `markers` passed to this function have been sorted by `setZIndexes` in
76 # advance, so we can skip sorting in the `huffman.createTree` function.
77 hintChars = options.hint_chars
78 createHuffmanTree = (markers) ->
79 return huffman.createTree(markers, hintChars.length, {sorted: true})
80
81 # Semantic elements should always get better hints and higher `z-index`:es
82 # than unsemantic ones, even if they are smaller. The former is achieved by
83 # putting the unsemantic elements in their own branch of the huffman tree.
84 if unsemantic.length > 0
85 if markers.length > hintChars.length
86 setZIndexes(unsemantic)
87 subTree = createHuffmanTree(unsemantic)
88 semantic.push(subTree)
89 else
90 semantic.push(unsemantic...)
91
92 setZIndexes(semantic)
93
94 tree = createHuffmanTree(semantic)
95 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
96
97 # Markers for links with the same href can be combined to use the same hint.
98 # They should all have the same `z-index` (because they all have the same
99 # combined weight), but in case any of them cover another they still get a
100 # unique `z-index` (space for this was added in `setZIndexes`).
101 for marker in combined
102 parent = markerMap[marker.wrapper.parentIndex]
103 marker.markerElement.style.zIndex = parent.markerElement.style.zIndex++
104 marker.setHint(parent.hint)
105 markers.push(combined...)
106
107 removeHints(window) # Better safe than sorry.
108 container = window.document.createElement('box')
109 container.id = CONTAINER_ID
110
111 zoom = 1
112
113 if options.ui
114 container.classList.add('ui')
115 window.document.getElementById('browser-panel').appendChild(container)
116 else
117 {ZoomManager, gBrowser: {selectedBrowser: browser}} = window
118 browser.parentNode.appendChild(container)
119 # If “full zoom” is not used, it means that “Zoom text only” is enabled.
120 # If so, that “zoom” does not need to be taken into account.
121 # `.getCurrentMode()` is added by the “Default FullZoom Level” extension.
122 if ZoomManager.getCurrentMode?(browser) ? ZoomManager.useFullZoom
123 zoom = ZoomManager.getZoomForBrowser(browser)
124
125 for marker in markers
126 container.appendChild(marker.markerElement)
127 # Must be done after the hints have been inserted into the DOM (see
128 # marker.coffee).
129 marker.setPosition(viewport, zoom)
130
131 return markers
132
133
134 getMarkableElementsAndViewport = (window, filter) ->
135 {
136 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
137 scrollWidth, scrollHeight
138 } = window.document.documentElement
139 {innerWidth, innerHeight} = window # Viewport size including scrollbars.
140 # We don’t want markers to cover the scrollbars, so we should use
141 # `clientWidth` and `clientHeight`. However, when there are no scrollbars
142 # those might be too small. Then we use `innerWidth` and `innerHeight`.
143 width = if scrollWidth > innerWidth then clientWidth else innerWidth
144 height = if scrollHeight > innerHeight then clientHeight else innerHeight
145 viewport = {
146 left: 0
147 top: 0
148 right: width
149 bottom: height
150 width
151 height
152 }
153
154 wrappers = []
155 getMarkableElements(window, viewport, wrappers, filter)
156 return {wrappers, viewport}
157
158 # `filter` is a function that is given every element in every frame of the page.
159 # It should return wrapper objects for markable elements and a falsy value for
160 # all other elements. All returned wrappers are added to `wrappers`. `wrappers`
161 # is modified instead of using return values to avoid array concatenation for
162 # each frame. It might sound expensive to go through _every_ element, but that’s
163 # actually what other methods like using XPath or CSS selectors would need to do
164 # anyway behind the scenes.
165 getMarkableElements = (window, viewport, wrappers, filter, parents = []) ->
166 {document} = window
167
168 for element in getAllElements(document) when element instanceof Element
169 # `getRects` is fast and filters out most elements, so run it first of all.
170 rects = getRects(element, viewport)
171 continue unless rects.length > 0
172 continue unless wrapper = filter(
173 element, (elementArg) ->
174 return getElementShape(window, viewport, parents, elementArg,
175 if elementArg == element then rects else null)
176 )
177 wrappers.push(wrapper)
178
179 for frame in window.frames when frame.frameElement
180 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
181 continue unless isInsideViewport(rect, viewport)
182
183 # Calculate the visible part of the frame, according to the parent.
184 {clientWidth, clientHeight} = frame.document.documentElement
185 frameViewport =
186 left: Math.max(viewport.left - rect.left, 0)
187 top: Math.max(viewport.top - rect.top, 0)
188 right: clientWidth + Math.min(viewport.right - rect.right, 0)
189 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
190
191 # `.getComputedStyle()` may return `null` if the computed style isn’t
192 # availble yet. If so, consider the element not visible.
193 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
194 offset =
195 left: rect.left +
196 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
197 parseFloat(computedStyle.getPropertyValue('padding-left'))
198 top: rect.top +
199 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
200 parseFloat(computedStyle.getPropertyValue('padding-top'))
201
202 getMarkableElements(frame, frameViewport, wrappers, filter,
203 parents.concat({window, offset}))
204
205 return
206
207 getAllElements = (document) ->
208 unless document instanceof XULDocument
209 return document.getElementsByTagName('*')
210
211 # Use a `Set` since this algorithm may find the same element more than once.
212 # Ideally we should find a way to find all elements without duplicates.
213 elements = new Set()
214 getAllRegular = (element) ->
215 # The first time `zF` is run `.getElementsByTagName('*')` may oddly include
216 # `undefined` in its result! Filter those out.
217 for child in element.getElementsByTagName('*') when child
218 elements.add(child)
219 getAllAnonymous(child)
220 return
221 getAllAnonymous = (element) ->
222 for child in document.getAnonymousNodes(element) or []
223 continue unless child instanceof Element
224 elements.add(child)
225 getAllRegular(child)
226 return
227 getAllRegular(document.documentElement)
228 return Array.from(elements)
229
230 getRects = (element, viewport) ->
231 # `element.getClientRects()` returns a list of rectangles, usually just one,
232 # which is identical to the one returned by `element.getBoundingClientRect()`.
233 # However, if `element` is inline and line-wrapped, then it returns one
234 # rectangle for each line, since each line may be of different length, for
235 # example. That allows us to properly add hints to line-wrapped links.
236 return Array.filter(
237 element.getClientRects(), (rect) -> isInsideViewport(viewport, rect)
238 )
239
240 # Returns the “shape” of `element`:
241 #
242 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
243 # isn’t covered by another element (except children of `element`). It also
244 # contains the offset needed to make those coordinates relative to the top
245 # frame, as well as the rectangle that the coordinates occur in.
246 # - `area`: The area of the part of `element` that is inside `viewport`.
247 #
248 # Returns `null` if `element` is outside `viewport` or entirely covered by other
249 # elements.
250 getElementShape = (window, viewport, parents, element, rects = null) ->
251 rects ?= getRects(element, viewport)
252 totalArea = 0
253 visibleRects = []
254 for rect in rects
255 visibleRect = adjustRectToViewport(rect, viewport)
256 continue if visibleRect.area == 0
257 totalArea += visibleRect.area
258 visibleRects.push(visibleRect)
259
260 if visibleRects.length == 0
261 if rects.length == 1 and totalArea == 0
262 [rect] = rects
263 if rect.width > 0 or rect.height > 0
264 # If we get here, it means that everything inside `element` is floated
265 # and/or absolutely positioned (and that `element` hasn’t been made to
266 # “contain” the floats). For example, a link in a menu could contain a
267 # span of text floated to the left and an icon floated to the right.
268 # Those are still clickable. Therefore we return the shape of the first
269 # visible child instead. At least in that example, that’s the best bet.
270 for child in element.children
271 shape = getElementShape(window, viewport, parents, child)
272 return shape if shape
273 return null
274
275 # Even if `element` has a visible rect, it might be covered by other elements.
276 for visibleRect in visibleRects
277 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
278 visibleRect, parents)
279 if nonCoveredPoint
280 nonCoveredPoint.rect = visibleRect
281 break
282
283 return null unless nonCoveredPoint
284
285 return {
286 nonCoveredPoint, area: totalArea
287 }
288
289
290 MINIMUM_EDGE_DISTANCE = 4
291 isInsideViewport = (rect, viewport) ->
292 return \
293 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
294 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
295 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
296 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
297
298
299 adjustRectToViewport = (rect, viewport) ->
300 # The right and bottom values are subtracted by 1 because
301 # `document.elementFromPoint(right, bottom)` does not return the element
302 # otherwise.
303 left = Math.max(rect.left, viewport.left)
304 right = Math.min(rect.right - 1, viewport.right)
305 top = Math.max(rect.top, viewport.top)
306 bottom = Math.min(rect.bottom - 1, viewport.bottom)
307
308 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
309 # above.
310 right = Math.max(right, left)
311 bottom = Math.max(bottom, top)
312
313 width = right - left
314 height = bottom - top
315 area = Math.floor(width * height)
316
317 return {
318 left, right, top, bottom
319 height, width, area
320 }
321
322
323 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
324 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
325 # if it passes the tests. Otherwise it tries to the right of whatever is at
326 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
327 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
328 # invocations of `tryPoint` below).
329 tryPoint = (x, dx, y, dy, tryRight = 0) ->
330 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
331 offset = {left: 0, top: 0}
332 found = false
333
334 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
335 # is clickable too), really is present at (x,y). Note that this is not 100%
336 # bullet proof: Combinations of CSS can cause this check to fail, even
337 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
338 # because of performance. Instead we rely on that some of the attempts below
339 # will work.
340 if contains(element, elementAtPoint)
341 found = true
342 # If we’re currently in a frame, there might be something on top of the
343 # frame that covers `element`. Therefore we ensure that the frame really
344 # is present at the point for each parent in `parents`.
345 currentWindow = window
346 for parent in parents by -1
347 offset.left += parent.offset.left
348 offset.top += parent.offset.top
349 elementAtPoint = parent.window.document.elementFromPoint(
350 offset.left + x + dx, offset.top + y + dy
351 )
352 unless contains(currentWindow.frameElement, elementAtPoint)
353 found = false
354 break
355 currentWindow = parent.window
356
357 if found
358 return {x, y, offset}
359 else
360 return false if elementAtPoint == null or tryRight == 0
361 rect = elementAtPoint.getBoundingClientRect()
362 x = rect.right - offset.left + 1
363 return false if x > viewport.right
364 return tryPoint(x, 0, y, 0, tryRight - 1)
365
366
367 # Try the left-middle point, or immediately to the right of a covering element
368 # at that point. If both of those are covered the whole element is considered
369 # to be covered. The reasoning is:
370 #
371 # - A marker should show up as near the left edge of its visible area as
372 # possible. Having it appear to the far right (for example) is confusing.
373 # - We can’t try too many times because of performance.
374 # - We used to try left-top first, but if `element` has `border-radius`, the
375 # corners won’t really belong to `element`, so `document.elementFromPoint()`
376 # will return whatever is behind. This will result in missing or
377 # out-of-place markers. The solution is to temporarily add a CSS class that
378 # removes `border-radius`, but that turned out to be rather slow, making it
379 # not worth it. Usually you don’t see the difference between left-top and
380 # left-middle, because links are usually not that high.
381 # - We used to try left-bottom as well, but that is so rare that it’s not
382 # worth it.
383 #
384 # It is safer to try points at least one pixel into the element from the
385 # edges, hence the `+1`.
386 {left, top, bottom, height} = elementRect
387 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
388
389 return nonCoveredPoint
390
391 # In XUL documents there are “anonymous” elements. These are never returned by
392 # `document.elementFromPoint` but their closest non-anonymous parents are.
393 normalize = (element) ->
394 normalized = element.ownerDocument.getBindingParent(element) or element
395 normalized = normalized.parentNode while normalized.prefix?
396 return normalized
397
398 # Returns whether `element` corresponds to `elementAtPoint`. This is only
399 # complicated for browser elements in the web page content area.
400 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
401 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
402 # same and visible in _all_ tabs, so we have to check that the element really
403 # belongs to the current tab.
404 contains = (element, elementAtPoint) ->
405 return false unless elementAtPoint
406 container = normalize(element)
407 if elementAtPoint.nodeName == 'tabbrowser' and elementAtPoint.id == 'content'
408 {gBrowser} = element.ownerGlobal.top
409 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
410 return tabpanel.contains(element)
411 else
412 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
413 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
414 return container == elementAtPoint or container.contains(elementAtPoint)
415
416 module.exports = {
417 removeHints
418 injectHints
419 getMarkableElementsAndViewport
420 }
Imprint / Impressum