]> git.gir.st - VimFx.git/blob - extension/lib/hints.coffee
Merge branch 'master' into develop
[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 getMarkableElementsAndViewport = (window, filter) ->
146 viewport = utils.getWindowViewport(window)
147 wrappers = []
148 getMarkableElements(window, viewport, wrappers, filter)
149 return {wrappers, viewport}
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(window, viewport, parents, elementArg,
168 if elementArg == element then rects else null)
169 )
170 wrappers.push(wrapper)
171
172 for frame in window.frames when frame.frameElement
173 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
174 continue unless isInsideViewport(rect, viewport)
175
176 # Calculate the visible part of the frame, according to the parent.
177 # coffeelint: disable=colon_assignment_spacing
178 {clientWidth, clientHeight} = frame.document.documentElement
179 frameViewport = {
180 left: Math.max(viewport.left - rect.left, 0)
181 top: Math.max(viewport.top - rect.top, 0)
182 right: clientWidth + Math.min(viewport.right - rect.right, 0)
183 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
184 }
185 # coffeelint: enable=colon_assignment_spacing
186
187 # `.getComputedStyle()` may return `null` if the computed style isn’t
188 # availble yet. If so, consider the element not visible.
189 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
190 offset = {
191 left: rect.left +
192 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
193 parseFloat(computedStyle.getPropertyValue('padding-left'))
194 top: rect.top +
195 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
196 parseFloat(computedStyle.getPropertyValue('padding-top'))
197 }
198
199 getMarkableElements(frame, frameViewport, wrappers, filter,
200 parents.concat({window, offset}))
201
202 return
203
204 getAllElements = (document) ->
205 unless document instanceof XULDocument
206 return document.getElementsByTagName('*')
207
208 # Use a `Set` since this algorithm may find the same element more than once.
209 # Ideally we should find a way to find all elements without duplicates.
210 elements = new Set()
211 getAllRegular = (element) ->
212 # The first time `zF` is run `.getElementsByTagName('*')` may oddly include
213 # `undefined` in its result! Filter those out.
214 for child in element.getElementsByTagName('*') when child
215 elements.add(child)
216 getAllAnonymous(child)
217 return
218 getAllAnonymous = (element) ->
219 for child in document.getAnonymousNodes(element) or []
220 continue unless child instanceof Element
221 elements.add(child)
222 getAllRegular(child)
223 return
224 getAllRegular(document.documentElement)
225 return Array.from(elements)
226
227 getRects = (element, viewport) ->
228 # `element.getClientRects()` returns a list of rectangles, usually just one,
229 # which is identical to the one returned by `element.getBoundingClientRect()`.
230 # However, if `element` is inline and line-wrapped, then it returns one
231 # rectangle for each line, since each line may be of different length, for
232 # example. That allows us to properly add hints to line-wrapped links.
233 return Array.filter(
234 element.getClientRects(), (rect) -> isInsideViewport(viewport, rect)
235 )
236
237 # Returns the “shape” of `element`:
238 #
239 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
240 # isn’t covered by another element (except children of `element`). It also
241 # contains the offset needed to make those coordinates relative to the top
242 # frame, as well as the rectangle that the coordinates occur in.
243 # - `area`: The area of the part of `element` that is inside `viewport`.
244 #
245 # Returns `null` if `element` is outside `viewport` or entirely covered by other
246 # elements.
247 getElementShape = (window, viewport, parents, element, rects = null) ->
248 rects ?= getRects(element, viewport)
249 totalArea = 0
250 visibleRects = []
251 for rect in rects
252 visibleRect = adjustRectToViewport(rect, viewport)
253 continue if visibleRect.area == 0
254 totalArea += visibleRect.area
255 visibleRects.push(visibleRect)
256
257 if visibleRects.length == 0
258 if rects.length == 1 and totalArea == 0
259 [rect] = rects
260 if rect.width > 0 or rect.height > 0
261 # If we get here, it means that everything inside `element` is floated
262 # and/or absolutely positioned (and that `element` hasn’t been made to
263 # “contain” the floats). For example, a link in a menu could contain a
264 # span of text floated to the left and an icon floated to the right.
265 # Those are still clickable. Therefore we return the shape of the first
266 # visible child instead. At least in that example, that’s the best bet.
267 for child in element.children
268 shape = getElementShape(window, viewport, parents, child)
269 return shape if shape
270 return null
271
272 # Even if `element` has a visible rect, it might be covered by other elements.
273 for visibleRect in visibleRects
274 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
275 visibleRect, parents)
276 break if nonCoveredPoint
277
278 return null unless nonCoveredPoint
279
280 return {
281 nonCoveredPoint, area: totalArea
282 }
283
284 MINIMUM_EDGE_DISTANCE = 4
285 isInsideViewport = (rect, viewport) ->
286 return \
287 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
288 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
289 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
290 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
291
292 adjustRectToViewport = (rect, viewport) ->
293 # The right and bottom values are subtracted by 1 because
294 # `document.elementFromPoint(right, bottom)` does not return the element
295 # otherwise.
296 left = Math.max(rect.left, viewport.left)
297 right = Math.min(rect.right - 1, viewport.right)
298 top = Math.max(rect.top, viewport.top)
299 bottom = Math.min(rect.bottom - 1, viewport.bottom)
300
301 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
302 # above.
303 right = Math.max(right, left)
304 bottom = Math.max(bottom, top)
305
306 width = right - left
307 height = bottom - top
308 area = Math.floor(width * height)
309
310 return {
311 left, right, top, bottom
312 height, width, area
313 }
314
315 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
316 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
317 # if it passes the tests. Otherwise it tries to the right of whatever is at
318 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
319 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
320 # invocations of `tryPoint` below).
321 tryPoint = (x, dx, y, dy, tryRight = 0) ->
322 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
323 offset = {left: 0, top: 0}
324 found = false
325 firstLevel = true
326
327 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
328 # is clickable too), really is present at (x,y). Note that this is not 100%
329 # bullet proof: Combinations of CSS can cause this check to fail, even
330 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
331 # because of performance. Instead we rely on that some of the attempts below
332 # will work. (See further down for the special value `-1` of `tryRight`.)
333 if contains(element, elementAtPoint) or tryRight == -1
334 found = true
335 # If we’re currently in a frame, there might be something on top of the
336 # frame that covers `element`. Therefore we ensure that the frame really
337 # is present at the point for each parent in `parents`.
338 currentWindow = window
339 for parent in parents by -1
340 # If leaving the devtools container take the devtools zoom into account.
341 if currentWindow.DevTools and not parent.window.DevTools
342 toolbox = window.gDevTools.getToolbox(
343 devtools.TargetFactory.forTab(window.top.gBrowser.selectedTab)
344 )
345 if toolbox
346 devtoolsZoom = toolbox.zoomValue
347 offset.left *= devtoolsZoom
348 offset.top *= devtoolsZoom
349 x *= devtoolsZoom
350 y *= devtoolsZoom
351 dx *= devtoolsZoom
352 dy *= devtoolsZoom
353
354 offset.left += parent.offset.left
355 offset.top += parent.offset.top
356 elementAtPoint = parent.window.document.elementFromPoint(
357 offset.left + x + dx, offset.top + y + dy
358 )
359 firstLevel = false
360 unless contains(currentWindow.frameElement, elementAtPoint)
361 found = false
362 break
363 currentWindow = parent.window
364
365 return {x, y, offset} if found
366
367 return false if elementAtPoint == null or tryRight <= 0
368 rect = elementAtPoint.getBoundingClientRect()
369
370 # `.getBoundingClientRect()` does not include pseudo-elements that are
371 # absolutely positioned so that they go outside of the element (which is
372 # common for `/###\`-looking tabs), but calling `.elementAtPoint()` on the
373 # pseudo-element _does_ return the element. This means that the covering
374 # element’s _rect_ won’t cover the element we’re looking for. If so, it’s
375 # better to try again, forcing the element to be considered located at this
376 # point. That’s what `-1` for the `tryRight` argument means.
377 if firstLevel and rect.right <= x + offset.left
378 return tryPoint(x, dx, y, dy, -1)
379
380 x = rect.right - offset.left + 1
381 return false if x > viewport.right
382 return tryPoint(x, 0, y, 0, tryRight - 1)
383
384
385 # Try the left-middle point, or immediately to the right of a covering element
386 # at that point. If both of those are covered the whole element is considered
387 # to be covered. The reasoning is:
388 #
389 # - A marker should show up as near the left edge of its visible area as
390 # possible. Having it appear to the far right (for example) is confusing.
391 # - We can’t try too many times because of performance.
392 # - We used to try left-top first, but if `element` has `border-radius`, the
393 # corners won’t really belong to `element`, so `document.elementFromPoint()`
394 # will return whatever is behind. This will result in missing or
395 # out-of-place markers. The solution is to temporarily add a CSS class that
396 # removes `border-radius`, but that turned out to be rather slow, making it
397 # not worth it. Usually you don’t see the difference between left-top and
398 # left-middle, because links are usually not that high.
399 # - We used to try left-bottom as well, but that is so rare that it’s not
400 # worth it.
401 #
402 # It is safer to try points at least one pixel into the element from the
403 # edges, hence the `+1`.
404 {left, top, bottom, height} = elementRect
405 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
406
407 return nonCoveredPoint
408
409 # In XUL documents there are “anonymous” elements. These are never returned by
410 # `document.elementFromPoint` but their closest non-anonymous parents are.
411 normalize = (element) ->
412 normalized = element.ownerDocument.getBindingParent(element) or element
413 normalized = normalized.parentNode while normalized.prefix?
414 return normalized
415
416 # Returns whether `element` corresponds to `elementAtPoint`. This is only
417 # complicated for browser elements in the web page content area.
418 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
419 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
420 # same and visible in _all_ tabs, so we have to check that the element really
421 # belongs to the current tab.
422 contains = (element, elementAtPoint) ->
423 return false unless elementAtPoint
424 container = normalize(element)
425 if elementAtPoint.localName == 'tabbrowser' and elementAtPoint.id == 'content'
426 {gBrowser} = element.ownerGlobal.top
427 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
428 return tabpanel.contains(element)
429 else
430 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
431 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
432 return container == elementAtPoint or container.contains(elementAtPoint)
433
434 module.exports = {
435 removeHints
436 injectHints
437 getMarkableElementsAndViewport
438 }
Imprint / Impressum