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