]> 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.
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 # Each marker gets a unique `z-index`, so that it can be determined if a
62 # marker overlaps another. Put more important markers (higher weight) at the
63 # end, so that they get higher `z-index`, in order not to be overlapped.
64 zIndex = 0
65 setZIndexes = (markers) ->
66 markers.sort((a, b) -> a.weight - b.weight)
67 for marker in markers when marker not instanceof huffman.BranchPoint
68 marker.markerElement.style.zIndex = zIndex++
69 # Add `z-index` space for all the children of the marker.
70 zIndex += marker.wrapper.numChildren if marker.wrapper.numChildren?
71 return
72
73 # The `markers` passed to this function have been sorted by `setZIndexes` in
74 # advance, so we can skip sorting in the `huffman.createTree` function.
75 hintChars = options.hint_chars
76 createHuffmanTree = (markers) ->
77 return huffman.createTree(markers, hintChars.length, {sorted: true})
78
79 # Semantic elements should always get better hints and higher `z-index`:es
80 # than unsemantic ones, even if they are smaller. The former is achieved by
81 # putting the unsemantic elements in their own branch of the huffman tree.
82 if unsemantic.length > 0
83 if markers.length > hintChars.length
84 setZIndexes(unsemantic)
85 subTree = createHuffmanTree(unsemantic)
86 semantic.push(subTree)
87 else
88 semantic.push(unsemantic...)
89
90 setZIndexes(semantic)
91
92 tree = createHuffmanTree(semantic)
93 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
94
95 # Markers for links with the same href can be combined to use the same hint.
96 # They should all have the same `z-index` (because they all have the same
97 # combined weight), but in case any of them cover another they still get a
98 # unique `z-index` (space for this was added in `setZIndexes`).
99 for marker in combined
100 parent = markerMap[marker.wrapper.parentIndex]
101 marker.markerElement.style.zIndex = parent.markerElement.style.zIndex++
102 marker.setHint(parent.hint)
103 markers.push(combined...)
104
105 removeHints(window) # Better safe than sorry.
106 container = window.document.createElement('box')
107 container.id = CONTAINER_ID
108
109 zoom = 1
110
111 if options.ui
112 container.classList.add('ui')
113 window.document.getElementById('browser-panel').appendChild(container)
114 else
115 window.gBrowser.mCurrentBrowser.parentNode.appendChild(container)
116 # If “full zoom” is not used, it means that “Zoom text only” is enabled.
117 # If so, that “zoom” does not need to be taken into account.
118 if window.ZoomManager.useFullZoom
119 zoom =
120 window.ZoomManager.getZoomForBrowser(window.gBrowser.selectedBrowser)
121
122 for marker in markers
123 container.appendChild(marker.markerElement)
124 # Must be done after the hints have been inserted into the DOM (see
125 # marker.coffee).
126 marker.setPosition(viewport, zoom)
127
128 return {markers, markerMap}
129
130
131 getMarkableElementsAndViewport = (window, filter) ->
132 {
133 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
134 scrollWidth, scrollHeight
135 } = window.document.documentElement
136 {innerWidth, innerHeight} = window # Viewport size including scrollbars.
137 # We don’t want markers to cover the scrollbars, so we should use
138 # `clientWidth` and `clientHeight`. However, when there are no scrollbars
139 # those might be too small. Then we use `innerWidth` and `innerHeight`.
140 width = if scrollWidth > innerWidth then clientWidth else innerWidth
141 height = if scrollHeight > innerHeight then clientHeight else innerHeight
142 viewport = {
143 left: 0
144 top: 0
145 right: width
146 bottom: height
147 width
148 height
149 }
150
151 wrappers = []
152 getMarkableElements(window, viewport, wrappers, filter)
153 return {wrappers, viewport}
154
155 # `filter` is a function that is given every element in every frame of the page.
156 # It should return wrapper objects for markable elements and a falsy value for
157 # all other elements. All returned wrappers are added to `wrappers`. `wrappers`
158 # is modified instead of using return values to avoid array concatenation for
159 # each frame. It might sound expensive to go through _every_ element, but that’s
160 # actually what other methods like using XPath or CSS selectors would need to do
161 # anyway behind the scenes.
162 getMarkableElements = (window, viewport, wrappers, filter, parents = []) ->
163 {document} = window
164
165 for element in getAllElements(document) when element instanceof Element
166 # `getRects` is fast and filters out most elements, so run it first of all.
167 rects = getRects(element, viewport)
168 continue unless rects.length > 0
169 continue unless wrapper = filter(
170 element, (elementArg) ->
171 return getElementShape(window, viewport, parents, elementArg,
172 if elementArg == element then rects else null)
173 )
174 wrappers.push(wrapper)
175
176 for frame in window.frames when frame.frameElement
177 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
178 continue unless isInsideViewport(rect, viewport)
179
180 # Calculate the visible part of the frame, according to the parent.
181 {clientWidth, clientHeight} = frame.document.documentElement
182 frameViewport =
183 left: Math.max(viewport.left - rect.left, 0)
184 top: Math.max(viewport.top - rect.top, 0)
185 right: clientWidth + Math.min(viewport.right - rect.right, 0)
186 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
187
188 # `.getComputedStyle()` may return `null` if the computed style isn’t
189 # availble yet. If so, consider the element not visible.
190 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
191 offset =
192 left: rect.left +
193 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
194 parseFloat(computedStyle.getPropertyValue('padding-left'))
195 top: rect.top +
196 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
197 parseFloat(computedStyle.getPropertyValue('padding-top'))
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 if nonCoveredPoint
277 nonCoveredPoint.rect = visibleRect
278 break
279
280 return null unless nonCoveredPoint
281
282 return {
283 nonCoveredPoint, area: totalArea
284 }
285
286
287 MINIMUM_EDGE_DISTANCE = 4
288 isInsideViewport = (rect, viewport) ->
289 return \
290 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
291 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
292 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
293 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
294
295
296 adjustRectToViewport = (rect, viewport) ->
297 # The right and bottom values are subtracted by 1 because
298 # `document.elementFromPoint(right, bottom)` does not return the element
299 # otherwise.
300 left = Math.max(rect.left, viewport.left)
301 right = Math.min(rect.right - 1, viewport.right)
302 top = Math.max(rect.top, viewport.top)
303 bottom = Math.min(rect.bottom - 1, viewport.bottom)
304
305 # Make sure that `right >= left and bottom >= top`, since we subtracted by 1
306 # above.
307 right = Math.max(right, left)
308 bottom = Math.max(bottom, top)
309
310 width = right - left
311 height = bottom - top
312 area = Math.floor(width * height)
313
314 return {
315 left, right, top, bottom
316 height, width, area
317 }
318
319
320 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
321 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
322 # if it passes the tests. Otherwise it tries to the right of whatever is at
323 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
324 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
325 # invocations of `tryPoint` below).
326 tryPoint = (x, dx, y, dy, tryRight = 0) ->
327 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
328 offset = {left: 0, top: 0}
329 found = false
330
331 # Ensure that `element`, or a child of `element` (anything inside an `<a>`
332 # is clickable too), really is present at (x,y). Note that this is not 100%
333 # bullet proof: Combinations of CSS can cause this check to fail, even
334 # though `element` isn’t covered. We don’t try to temporarily reset such CSS
335 # because of performance. Instead we rely on that some of the attempts below
336 # will work.
337 if contains(element, elementAtPoint)
338 found = true
339 # If we’re currently in a frame, there might be something on top of the
340 # frame that covers `element`. Therefore we ensure that the frame really
341 # is present at the point for each parent in `parents`.
342 currentWindow = window
343 for parent in parents by -1
344 offset.left += parent.offset.left
345 offset.top += parent.offset.top
346 elementAtPoint = parent.window.document.elementFromPoint(
347 offset.left + x + dx, offset.top + y + dy
348 )
349 unless contains(currentWindow.frameElement, elementAtPoint)
350 found = false
351 break
352 currentWindow = parent.window
353
354 if found
355 return {x, y, offset}
356 else
357 return false if elementAtPoint == null or tryRight == 0
358 rect = elementAtPoint.getBoundingClientRect()
359 x = rect.right - offset.left + 1
360 return false if x > viewport.right
361 return tryPoint(x, 0, y, 0, tryRight - 1)
362
363
364 # Try the left-middle point, or immediately to the right of a covering element
365 # at that point. If both of those are covered the whole element is considered
366 # to be covered. The reasoning is:
367 #
368 # - A marker should show up as near the left edge of its visible area as
369 # possible. Having it appear to the far right (for example) is confusing.
370 # - We can’t try too many times because of performance.
371 # - We used to try left-top first, but if `element` has `border-radius`, the
372 # corners won’t really belong to `element`, so `document.elementFromPoint()`
373 # will return whatever is behind. This will result in missing or
374 # out-of-place markers. The solution is to temporarily add a CSS class that
375 # removes `border-radius`, but that turned out to be rather slow, making it
376 # not worth it. Usually you don’t see the difference between left-top and
377 # left-middle, because links are usually not that high.
378 # - We used to try left-bottom as well, but that is so rare that it’s not
379 # worth it.
380 #
381 # It is safer to try points at least one pixel into the element from the
382 # edges, hence the `+1`.
383 {left, top, bottom, height} = elementRect
384 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
385
386 return nonCoveredPoint
387
388 # In XUL documents there are “anonymous” elements. These are never returned by
389 # `document.elementFromPoint` but their closest non-anonymous parents are.
390 normalize = (element) ->
391 normalized = element.ownerDocument.getBindingParent(element) or element
392 normalized = normalized.parentNode while normalized.prefix?
393 return normalized
394
395 # Returns whether `element` corresponds to `elementAtPoint`. This is only
396 # complicated for browser elements in the web page content area.
397 # `.elementAtPoint()` always returns `<tabbrowser#content>` then. The element
398 # might be in another tab and thus invisible, but `<tabbrowser#content>` is the
399 # same and visible in _all_ tabs, so we have to check that the element really
400 # belongs to the current tab.
401 contains = (element, elementAtPoint) ->
402 container = normalize(element)
403 if elementAtPoint.nodeName == 'tabbrowser' and elementAtPoint.id == 'content'
404 {gBrowser} = element.ownerGlobal.top
405 tabpanel = gBrowser.getNotificationBox(gBrowser.selectedBrowser)
406 return tabpanel.contains(element)
407 else
408 # Note that `a.contains(a)` is supposed to be true, but strangely aren’t for
409 # `<menulist>`s in the Add-ons Manager, so do a direct comparison as well.
410 return container == elementAtPoint or container.contains(elementAtPoint)
411
412 module.exports = {
413 removeHints
414 injectHints
415 getMarkableElementsAndViewport
416 }
Imprint / Impressum