]> git.gir.st - VimFx.git/blob - extension/lib/hints.coffee
Merge pull request #461 from lydell/scroll
[VimFx.git] / extension / lib / hints.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013.
3 # Copyright Simon Lydell 2013, 2014.
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 utils = require('./utils')
22 huffman = require('n-ary-huffman')
23
24 { interfaces: Ci } = Components
25
26 Element = Ci.nsIDOMElement
27 HTMLDocument = Ci.nsIDOMHTMLDocument
28 XULDocument = Ci.nsIDOMXULDocument
29
30 injectHints = (rootWindow, window, filter) ->
31 {
32 clientWidth, clientHeight # Viewport size excluding scrollbars, usually.
33 scrollWidth, scrollHeight
34 } = window.document.documentElement
35 { innerWidth, innerHeight } = window # Viewport size including scrollbars.
36 # We don’t want markers to cover the scrollbars, so we should use
37 # `clientWidth` and `clientHeight`. However, when there are no scrollbars
38 # those might be too small. Then we use `innerWidth` and `innerHeight`.
39 width = if scrollWidth > innerWidth then clientWidth else innerWidth
40 height = if scrollHeight > innerHeight then clientHeight else innerHeight
41 viewport = {
42 left: 0
43 top: 0
44 right: width
45 bottom: height
46 width
47 height
48 zoom: rootWindow.gBrowser.selectedBrowser.markupDocumentViewer.fullZoom
49 }
50
51 groups = {semantic: [], unsemantic: [], combined: []}
52 createMarkers(window, viewport, groups, filter)
53 { semantic, unsemantic, combined } = groups
54 markers = semantic.concat(unsemantic)
55
56 return [[], null] if markers.length == 0
57
58 # Each marker gets a unique `z-index`, so that it can be determined if a
59 # marker overlaps another. Put more important markers (higher weight) at the
60 # end, so that they get higher `z-index`, in order not to be overlapped.
61 zIndex = 0
62 setZIndexes = (markers) ->
63 markers.sort((a, b) -> a.weight - b.weight)
64 for marker in markers when marker not instanceof huffman.BranchPoint
65 marker.markerElement.style.zIndex = zIndex++
66 # Add `z-index` space for all the children of the marker (usually 0).
67 zIndex += marker.numChildren
68
69 # The `markers` passed to this function have been sorted by `setZIndexes` in
70 # advance, so we can skip sorting in the `huffman.createTree` function.
71 hintChars = utils.getHintChars()
72 createHuffmanTree = (markers) ->
73 return huffman.createTree(markers, hintChars.length, {sorted: true})
74
75 # Semantic elements should always get better hints and higher `z-index`:es
76 # than unsemantic ones, even if they are smaller. The latter is achieved by
77 # putting the unsemantic elements in their own branch of the huffman tree.
78 if unsemantic.length > 0
79 if markers.length > hintChars.length
80 setZIndexes(unsemantic)
81 subTree = createHuffmanTree(unsemantic)
82 semantic.push(subTree)
83 else
84 semantic.push(unsemantic...)
85
86 setZIndexes(semantic)
87
88 tree = createHuffmanTree(semantic)
89 tree.assignCodeWords(hintChars, (marker, hint) -> marker.setHint(hint))
90
91 # Markers for links with the same href can be combined to use the same hint.
92 # They should all have the same `z-index` (because they all have the same
93 # combined weight), but in case any of them cover another they still get a
94 # unique `z-index` (space for this was added in `setZIndexes`).
95 for marker in combined
96 { parent } = marker
97 marker.markerElement.style.zIndex = parent.markerElement.style.zIndex++
98 marker.setHint(parent.hint)
99 markers.push(combined...)
100
101 container = rootWindow.document.createElement('box')
102 container.classList.add('VimFxMarkersContainer')
103 rootWindow.gBrowser.mCurrentBrowser.parentNode.appendChild(container)
104
105 for marker in markers
106 container.appendChild(marker.markerElement)
107 # Must be done after the hints have been inserted into the DOM (see
108 # marker.coffee).
109 marker.setPosition(viewport)
110
111 return [markers, container]
112
113 # `filter` is a function that is given every element in every frame of the page.
114 # It should return new `Marker`s for markable elements and a falsy value for all
115 # other elements. All returned `Marker`s are added to `groups`. `groups` is
116 # modified instead of using return values to avoid array concatenation for each
117 # frame. It might sound expensive to go through _every_ element, but that’s
118 # actually what other methods like using XPath or CSS selectors would need to do
119 # anyway behind the scenes.
120 createMarkers = (window, viewport, groups, filter, parents = []) ->
121 { document } = window
122
123 localGetElementShape = getElementShape.bind(null, window, viewport, parents)
124 for element in getElements(document, viewport) when element instanceof Element
125 continue unless marker = filter(element, localGetElementShape)
126 if marker.parent
127 groups.combined.push(marker)
128 else if marker.semantic
129 groups.semantic.push(marker)
130 else
131 groups.unsemantic.push(marker)
132
133 for frame in window.frames
134 rect = frame.frameElement.getBoundingClientRect() # Frames only have one.
135 continue unless isInsideViewport(rect, viewport)
136
137 # Calculate the visible part of the frame, according to the parent.
138 { clientWidth, clientHeight } = frame.document.documentElement
139 frameViewport =
140 left: Math.max(viewport.left - rect.left, 0)
141 top: Math.max(viewport.top - rect.top, 0)
142 right: clientWidth + Math.min(viewport.right - rect.right, 0)
143 bottom: clientHeight + Math.min(viewport.bottom - rect.bottom, 0)
144
145 # `.getComputedStyle()` may return `null` if the computed style isn’t
146 # availble yet. If so, consider the element not visible.
147 continue unless computedStyle = window.getComputedStyle(frame.frameElement)
148 offset =
149 left: rect.left +
150 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
151 parseFloat(computedStyle.getPropertyValue('padding-left'))
152 top: rect.top +
153 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
154 parseFloat(computedStyle.getPropertyValue('padding-top'))
155
156 createMarkers(frame, frameViewport, groups, filter,
157 parents.concat({ window, offset }))
158
159 return
160
161 # Returns a suitable set of elements in `document` that could possibly get
162 # markers.
163 getElements = (document, viewport) -> switch
164 # In HTML documents we can use a super-fast Firefox API to get all elements in
165 # the viewport.
166 when document instanceof HTMLDocument
167 windowUtils = document.defaultView
168 .QueryInterface(Ci.nsIInterfaceRequestor)
169 .getInterface(Ci.nsIDOMWindowUtils)
170 return windowUtils.nodesFromRect(
171 viewport.left, viewport.top, # Rect coordinates, relative to the viewport.
172 # Distances to expand in all directions: top, right, bottom, left.
173 0, viewport.right, viewport.bottom, 0,
174 true, # Unsure what this does. Toggling it seems to make no difference.
175 true # Ensure that the list of matching elements is fully up to date.
176 )
177 # In XUL documents we have to resort to get every single element in the entire
178 # document, because there are lots of complicated “anonymous” elements, which
179 # `windowUtils.nodesFromRect()` does not catch.
180 when document instanceof XULDocument
181 elements = []
182 getAllRegular = (element) ->
183 for child in element.getElementsByTagName('*')
184 elements.push(child)
185 getAllAnonymous(child)
186 return
187 getAllAnonymous = (element) ->
188 for child in document.getAnonymousNodes(element) or []
189 continue unless child instanceof Element
190 elements.push(child)
191 getAllRegular(child)
192 return
193 getAllRegular(document.documentElement)
194 return elements
195
196 # Returns the “shape” of `element`:
197 #
198 # - `rects`: Its `.getClientRects()` rectangles.
199 # - `visibleRects`: The parts of rectangles out of the above that are inside
200 # `viewport`.
201 # - `nonCoveredPoint`: The coordinates of the first point of `element` that
202 # isn’t covered by another element (except children of `element`). It also
203 # contains the offset needed to make those coordinates relative to the top
204 # frame, as well as the rectangle that the coordinates occur in.
205 # - `area`: The area of the part of `element` that is inside `viewport`.
206 #
207 # Returns `null` if `element` is outside `viewport` or entirely covered by other
208 # elements.
209 getElementShape = (window, viewport, parents, element) ->
210 # `element.getClientRects()` returns a list of rectangles, usually just one,
211 # which is identical to the one returned by `element.getBoundingClientRect()`.
212 # However, if `element` is inline and line-wrapped, then it returns one
213 # rectangle for each line, since each line may be of different length, for
214 # example. That allows us to properly add hints to line-wrapped links.
215 rects = element.getClientRects()
216 totalArea = 0
217 visibleRects = []
218 # The `isInsideViewport` check is not needed in HTML documents, but in XUL
219 # documents (see `getElements()`). However, there seems to be no performance
220 # gain in not running the check in HTML documents, so let’s keep it simple.
221 for rect in rects when isInsideViewport(rect, viewport)
222 visibleRect = adjustRectToViewport(rect, viewport)
223 continue if visibleRect.area == 0
224 totalArea += visibleRect.area
225 visibleRects.push(visibleRect)
226
227 if visibleRects.length == 0
228 if rects.length == 1 and totalArea == 0
229 [ rect ] = rects
230 if rect.width > 0 or rect.height > 0
231 # If we get here, it means that everything inside `element` is floated
232 # and/or absolutely positioned (and that `element` hasn’t been made to
233 # “contain” the floats). For example, a link in a menu could contain a
234 # span of text floated to the left and an icon floated to the right.
235 # Those are still clickable. Therefore we return the shape of the first
236 # visible child instead. At least in that example, that’s the best bet.
237 for child in element.children
238 shape = getElementShape(window, viewport, parents, child)
239 return shape if shape
240 return null
241
242 # Even if `element` has a visible rect, it might be covered by other elements.
243 for visibleRect in visibleRects
244 nonCoveredPoint = getFirstNonCoveredPoint(window, viewport, element,
245 visibleRect, parents)
246 if nonCoveredPoint
247 nonCoveredPoint.rect = visibleRect
248 break
249
250 return null unless nonCoveredPoint
251
252 return {
253 rects, visibleRects, nonCoveredPoint, area: totalArea
254 }
255
256
257 MINIMUM_EDGE_DISTANCE = 4
258 isInsideViewport = (rect, viewport) ->
259 return \
260 rect.left <= viewport.right - MINIMUM_EDGE_DISTANCE and
261 rect.top <= viewport.bottom + MINIMUM_EDGE_DISTANCE and
262 rect.right >= viewport.left + MINIMUM_EDGE_DISTANCE and
263 rect.bottom >= viewport.top - MINIMUM_EDGE_DISTANCE
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
290 getFirstNonCoveredPoint = (window, viewport, element, elementRect, parents) ->
291 # Tries a point `(x + dx, y + dy)`. Returns `(x, y)` (and the frame offset)
292 # if it passes the tests. Otherwise it tries to the right of whatever is at
293 # `(x, y)`, `tryRight` times . If nothing succeeds, `false` is returned. `dx`
294 # and `dy` are used to offset the wanted point `(x, y)` while trying (see the
295 # invocations of `tryPoint` below).
296 tryPoint = (x, dx, y, dy, tryRight = 0) ->
297 elementAtPoint = window.document.elementFromPoint(x + dx, y + dy)
298 offset = {left: 0, top: 0}
299 found = false
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.
307 if element.contains(elementAtPoint) or # Note that `a.contains(a) == true`!
308 (window.document instanceof XULDocument and
309 getClosestNonAnonymousParent(element) == elementAtPoint)
310 found = true
311 # If we’re currently in a frame, there might be something on top of the
312 # frame that covers `element`. Therefore we ensure that the frame really
313 # is present at the point for each parent in `parents`.
314 currentWindow = window
315 for parent in parents by -1
316 offset.left += parent.offset.left
317 offset.top += parent.offset.top
318 elementAtPoint = parent.window.document.elementFromPoint(
319 offset.left + x + dx, offset.top + y + dy
320 )
321 unless elementAtPoint == currentWindow.frameElement
322 found = false
323 break
324 currentWindow = parent.window
325
326 if found
327 return {x, y, offset}
328 else
329 return false if elementAtPoint == null or tryRight == 0
330 rect = elementAtPoint.getBoundingClientRect()
331 x = rect.right - offset.left + 1
332 return false if x > viewport.right
333 return tryPoint(x, 0, y, 0, tryRight - 1)
334
335
336 # Try the left-middle point, or immediately to the right of a covering element
337 # at that point. If both of those are covered the whole element is considered
338 # to be covered. The reasoning is:
339 #
340 # - A marker should show up as near the left edge of its visible area as
341 # possible. Having it appear to the far right (for example) is confusing.
342 # - We can’t try too many times because of performance.
343 # - We used to try left-top first, but if `element` has `border-radius`, the
344 # corners won’t really belong to `element`, so `document.elementFromPoint()`
345 # will return whatever is behind. This will result in missing or
346 # out-of-place markers. The solution is to temporarily add a CSS class that
347 # removes `border-radius`, but that turned out to be rather slow, making it
348 # not worth it. Usually you don’t see the difference between left-top and
349 # left-middle, because links are usually not that high.
350 # - We used to try left-bottom as well, but that is so rare that it’s not
351 # worth it.
352 #
353 # It is safer to try points at least one pixel into the element from the
354 # edges, hence the `+1`.
355 { left, top, bottom, height } = elementRect
356 nonCoveredPoint = tryPoint(left, +1, Math.floor(top + height / 2), 0, 1)
357
358 return nonCoveredPoint
359
360 # In XUL documents there are “anonymous” elements, whose node names start with
361 # `xul:` or `html:`. These are not never returned by `document.elementFromPoint`
362 # but their closest non-anonymous parents are.
363 getClosestNonAnonymousParent = (element) ->
364 element = element.parentNode while element.prefix?
365 return element
366
367 exports.injectHints = injectHints
Imprint / Impressum