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