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