]> git.gir.st - VimFx.git/blob - extension/lib/utils.coffee
Correctly determine viewport size
[VimFx.git] / extension / lib / utils.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
4 # Copyright Wang Zhuochun 2013.
5 #
6 # This file is part of VimFx.
7 #
8 # VimFx is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # VimFx is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
20 ###
21
22 notation = require('vim-like-key-notation')
23 { getPref
24 , setPref
25 } = require('./prefs')
26
27 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
28
29 { classes: Cc, interfaces: Ci, utils: Cu } = Components
30
31 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
32 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
33 HTMLInputElement = Ci.nsIDOMHTMLInputElement
34 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
35 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
36 XULMenuListElement = Ci.nsIDOMXULMenuListElement
37 XULDocument = Ci.nsIDOMXULDocument
38 XULElement = Ci.nsIDOMXULElement
39 XPathResult = Ci.nsIDOMXPathResult
40 HTMLDocument = Ci.nsIDOMHTMLDocument
41 HTMLElement = Ci.nsIDOMHTMLElement
42 Window = Ci.nsIDOMWindow
43 ChromeWindow = Ci.nsIDOMChromeWindow
44
45 class Bucket
46 constructor: (@newFunc) ->
47 @bucket = new WeakMap()
48
49 get: (obj) ->
50 if @bucket.has(obj)
51 return @bucket.get(obj)
52 else
53 value = @newFunc(obj)
54 @bucket.set(obj, value)
55 return value
56
57 forget: (obj) ->
58 @bucket.delete(obj)
59
60 getEventWindow = (event) ->
61 if event.originalTarget instanceof Window
62 return event.originalTarget
63 else
64 doc = event.originalTarget.ownerDocument or event.originalTarget
65 if doc instanceof HTMLDocument or doc instanceof XULDocument
66 return doc.defaultView
67
68 getEventRootWindow = (event) ->
69 return unless window = getEventWindow(event)
70 return getRootWindow(window)
71
72 getEventCurrentTabWindow = (event) ->
73 return unless rootWindow = getEventRootWindow(event)
74 return getCurrentTabWindow(rootWindow)
75
76 getRootWindow = (window) ->
77 return window
78 .QueryInterface(Ci.nsIInterfaceRequestor)
79 .getInterface(Ci.nsIWebNavigation)
80 .QueryInterface(Ci.nsIDocShellTreeItem)
81 .rootTreeItem
82 .QueryInterface(Ci.nsIInterfaceRequestor)
83 .getInterface(Window)
84
85 getCurrentTabWindow = (window) ->
86 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
87
88 blurActiveElement = (window) ->
89 # Only blur editable elements, in order to interfere with the browser as
90 # little as possible.
91 { activeElement } = window.document
92 if activeElement and isElementEditable(activeElement)
93 activeElement.blur()
94
95 isTextInputElement = (element) ->
96 return element instanceof HTMLInputElement or
97 element instanceof HTMLTextAreaElement
98
99 isElementEditable = (element) ->
100 return element instanceof HTMLInputElement or
101 element instanceof HTMLTextAreaElement or
102 element instanceof HTMLSelectElement or
103 element instanceof XULMenuListElement or
104 element.isContentEditable or
105 isElementGoogleEditable(element)
106
107 isElementGoogleEditable = (element) ->
108 # `g_editable` is a non-standard attribute commonly used by Google.
109 return element.getAttribute?('g_editable') == 'true' or
110 (element instanceof HTMLElement and
111 element.ownerDocument.body?.getAttribute('g_editable') == 'true')
112
113 isElementClickable = (element) ->
114 return element instanceof HTMLAnchorElement or
115 element instanceof HTMLButtonElement or
116 isElementEditable(element)
117
118 isElementVisible = (element) ->
119 document = element.ownerDocument
120 window = document.defaultView
121 # `.getComputedStyle()` may return `null` if the computed style isn’t
122 # availble yet. If so, consider the element not visible.
123 return false unless computedStyle = window.getComputedStyle(element, null)
124 return computedStyle.getPropertyValue('visibility') == 'visible' and
125 computedStyle.getPropertyValue('display') != 'none' and
126 computedStyle.getPropertyValue('opacity') != '0'
127
128 getSessionStore = ->
129 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
130
131 loadCss = do ->
132 sss = Cc['@mozilla.org/content/style-sheet-service;1']
133 .getService(Ci.nsIStyleSheetService)
134 return (name) ->
135 uri = getResourceURI("resources/#{ name }.css")
136 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
137 # website themes installed by users often make the hint markers unreadable,
138 # for example. Just using `!important` in the CSS is not enough.
139 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
140 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
141
142 module.onShutdown(->
143 sss.unregisterSheet(uri, sss.AGENT_SHEET)
144 )
145
146 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
147 # memory. This approach is better than for example setting `event.simulated =
148 # true`, since that tells the sites that the click was simulated, and allows
149 # sites to spoof it.
150 simulated_events = new WeakMap()
151
152 # Simulate mouse click with a full chain of events. Copied from Vimium
153 # codebase.
154 simulateClick = (element, modifiers = {}) ->
155 document = element.ownerDocument
156 window = document.defaultView
157
158 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
159 for event in eventSequence
160 mouseEvent = document.createEvent('MouseEvents')
161 mouseEvent.initMouseEvent(
162 event, true, true, window, 1, 0, 0, 0, 0,
163 modifiers.ctrlKey, false, false, modifiers.metaKey,
164 0, null
165 )
166 simulated_events.set(mouseEvent, true)
167 # Debugging note: Firefox will not execute the element's default action if
168 # we dispatch this click event, but Webkit will. Dispatching a click on an
169 # input box does not seem to focus it; we do that separately.
170 element.dispatchEvent(mouseEvent)
171
172 isEventSimulated = (event) ->
173 return simulated_events.has(event)
174
175 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
176 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
177 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
178
179 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
180 # specified position.
181 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
182 windowUtils = window
183 .QueryInterface(Ci.nsIInterfaceRequestor)
184 .getInterface(Ci.nsIDOMWindowUtils)
185
186 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
187 windowUtils.sendWheelEvent(
188 pX, pY, # Window offset (x, y) in pixels.
189 deltaX, deltaY, 0, # Deltas (x, y, z).
190 mode, # Mode (pixel, line, page).
191 0, # Key Modifiers.
192 0, 0, # Line or Page deltas (x, y).
193 0 # Options.
194 )
195
196 # Write a string to the system clipboard.
197 writeToClipboard = (text) ->
198 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
199 .getService(Ci.nsIClipboardHelper)
200 clipboardHelper.copyString(text)
201
202 # Executes function `func` and mearues how much time it took.
203 timeIt = (func, name) ->
204 console.time(name)
205 result = func()
206 console.timeEnd(name)
207 return result
208
209 isBlacklisted = (str) ->
210 matchingRules = getMatchingBlacklistRules(str)
211 return (matchingRules.length != 0)
212
213 # Returns all blacklisted keys in matching rules.
214 getBlacklistedKeys = (str) ->
215 matchingRules = getMatchingBlacklistRules(str)
216 blacklistedKeys = []
217 for rule in matchingRules when /##/.test(rule)
218 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
219 return blacklistedKeys
220
221 # Returns all rules in the blacklist that match the provided string.
222 getMatchingBlacklistRules = (str) ->
223 return getBlacklist().filter((rule) ->
224 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
225 )
226
227 getBlacklist = ->
228 return splitListString(getPref('black_list'))
229
230 setBlacklist = (blacklist) ->
231 setPref('black_list', blacklist.join(','))
232
233 updateBlacklist = ({ add, remove } = {}) ->
234 blacklist = getBlacklist()
235
236 if add
237 blacklist.push(splitListString(add)...)
238
239 blacklist = blacklist.filter((rule) -> rule != '')
240 blacklist = removeDuplicates(blacklist)
241
242 if remove
243 for rule in splitListString(remove) when rule in blacklist
244 blacklist.splice(blacklist.indexOf(rule), 1)
245
246 setBlacklist(blacklist)
247
248 # Splits a comma/space separated list into an array.
249 splitListString = (str) ->
250 return str.split(/\s*,[\s,]*/)
251
252 # Prepares a string to be used in a regexp, where "*" matches zero or more
253 # characters and "!" matches one character.
254 simpleWildcards = (string) ->
255 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
256
257 # Returns the first element that matches a pattern, favoring earlier patterns.
258 # The patterns are case insensitive `simpleWildcards`s and must match either in
259 # the beginning or at the end of a string. Moreover, a pattern does not match
260 # in the middle of words, so "previous" does not match "previously". If that is
261 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
262 # use `\b` word boundaries, because they don’t work well with non-English
263 # characters. Instead we match a space as word boundary. Therefore we normalize
264 # the whitespace and add spaces at the edges of the element text.
265 getBestPatternMatch = (patterns, attrs, elements) ->
266 regexps = []
267 for pattern in patterns
268 wildcarded = simpleWildcards(pattern)
269 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
270
271 # Helper function that matches a string against all the patterns.
272 matches = (text) ->
273 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
274 for re in regexps
275 if re.test(normalizedText)
276 return true
277 return false
278
279 # First search in attributes (favoring earlier attributes) as it's likely
280 # that they are more specific than text contexts.
281 for attr in attrs
282 for element in elements
283 if matches(element.getAttribute(attr))
284 return element
285
286 # Then search in element contents.
287 for element in elements
288 if matches(element.textContent)
289 return element
290
291 return null
292
293 # Get VimFx verion. AddonManager only provides async API to access addon data,
294 # so it's a bit tricky...
295 getVersion = do ->
296 version = null
297
298 scope = {}
299 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
300 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
301
302 return ->
303 return version
304
305 parseHTML = (document, html) ->
306 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
307 flags = parser.SanitizerAllowStyle
308 return parser.parseFragment(html, flags, false, null,
309 document.documentElement)
310
311 escapeHTML = (s) ->
312 return s
313 .replace(/&/g, '&amp;')
314 .replace(/</g, '&lt;')
315 .replace(/>/g, '&gt;')
316 .replace(/"/g, '&quot;')
317 .replace(/'/g, '&apos;')
318
319 createElement = (document, type, attributes = {}) ->
320 element = document.createElement(type)
321
322 for attribute, value of attributes
323 element.setAttribute(attribute, value)
324
325 if document instanceof HTMLDocument
326 element.classList.add('VimFxReset')
327
328 return element
329
330 isURL = (str) ->
331 try
332 url = Cc['@mozilla.org/network/io-service;1']
333 .getService(Ci.nsIIOService)
334 .newURI(str, null, null)
335 .QueryInterface(Ci.nsIURL)
336 return true
337 catch err
338 return false
339
340 # Use Firefox services to search for a given string.
341 browserSearchSubmission = (str) ->
342 ss = Cc['@mozilla.org/browser/search-service;1']
343 .getService(Ci.nsIBrowserSearchService)
344
345 engine = ss.currentEngine or ss.defaultEngine
346 return engine.getSubmission(str, null)
347
348 normalizedKey = (key) -> key.map(notation.normalize).join('')
349
350 # Get hint characters, convert them to lower case, and filter duplicates.
351 getHintChars = ->
352 hintChars = getPref('hint_chars')
353 # Make sure that hint chars contain at least two characters.
354 if not hintChars or hintChars.length < 2
355 hintChars = 'fj'
356
357 return removeDuplicateCharacters(hintChars)
358
359 # Remove duplicate characters from string (case insensitive).
360 removeDuplicateCharacters = (str) ->
361 return removeDuplicates( str.toLowerCase().split('') ).join('')
362
363 # Return URI to some file in the extension packaged as resource.
364 getResourceURI = do ->
365 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
366 return (path) -> return Services.io.newURI(path, null, baseURI)
367
368 # Escape a string to render it usable in regular expressions.
369 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
370
371 removeDuplicates = (array) ->
372 # coffeelint: disable=no_backticks
373 return `[...new Set(array)]`
374 # coffeelint: enable=no_backticks
375
376 # Why isn’t `a[@href]` used, when `area[@href]` is? Some sites (such as
377 # StackExchange sites) leave out the `href` property and use the anchor as a
378 # JavaScript-powered button (instead of just using the `button` element).
379 ACTION_ELEMENT_TAGS = [
380 'a'
381 'area[@href]'
382 'button'
383 # When viewing an image directly, and it is larger than the viewport,
384 # clicking it toggles zoom.
385 'img[contains(@class, "decoded") and
386 (contains(@class, "overflowing") or
387 contains(@class, "shrinkToFit"))]'
388 ]
389
390 ACTION_ELEMENT_PROPERTIES = [
391 '@onclick'
392 '@onmousedown'
393 '@onmouseup'
394 '@oncommand'
395 '@role="link"'
396 '@role="button"'
397 'contains(@class, "button")'
398 'contains(@class, "js-new-tweets-bar")'
399 ]
400
401 EDITABLE_ELEMENT_TAGS = [
402 'textarea'
403 'select'
404 'input[not(@type="hidden" or @disabled)]'
405 ]
406
407 EDITABLE_ELEMENT_PROPERTIES = [
408 '@contenteditable=""'
409 'translate(@contenteditable, "TRUE", "true")="true"'
410 ]
411
412 FOCUSABLE_ELEMENT_TAGS = [
413 'frame'
414 'iframe'
415 'embed'
416 'object'
417 ]
418
419 FOCUSABLE_ELEMENT_PROPERTIES = [
420 '@tabindex!=-1'
421 ]
422
423 getMarkableElements = do ->
424 xpathify = (tags, properties) ->
425 return tags
426 .concat("*[#{ properties.join(' or ') }]")
427 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
428 .join(' | ')
429
430 xpaths =
431 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
432 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
433 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
434 all: xpathify(
435 # coffeelint: disable=max_line_length
436 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
437 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
438 # coffeelint: enable=max_line_length
439 )
440
441 # The actual function that will return the desired elements.
442 return (document, { type }) ->
443 return xpathQueryAll(document, xpaths[type])
444
445 xpathHelper = (node, query, resultType) ->
446 document = node.ownerDocument ? node
447 namespaceResolver = (namespace) ->
448 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
449 return document.evaluate(query, node, namespaceResolver, resultType, null)
450
451 xpathQuery = (node, query) ->
452 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
453 return result.singleNodeValue
454
455 xpathQueryAll = (node, query) ->
456 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
457 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
458
459
460 exports.Bucket = Bucket
461 exports.getEventWindow = getEventWindow
462 exports.getEventRootWindow = getEventRootWindow
463 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
464 exports.getRootWindow = getRootWindow
465 exports.getCurrentTabWindow = getCurrentTabWindow
466
467 exports.blurActiveElement = blurActiveElement
468 exports.isTextInputElement = isTextInputElement
469 exports.isElementEditable = isElementEditable
470 exports.isElementClickable = isElementClickable
471 exports.isElementVisible = isElementVisible
472 exports.getSessionStore = getSessionStore
473
474 exports.loadCss = loadCss
475
476 exports.simulateClick = simulateClick
477 exports.isEventSimulated = isEventSimulated
478 exports.simulateWheel = simulateWheel
479 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
480 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
481 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
482 exports.writeToClipboard = writeToClipboard
483 exports.timeIt = timeIt
484
485 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
486 exports.isBlacklisted = isBlacklisted
487 exports.getBlacklistedKeys = getBlacklistedKeys
488 exports.updateBlacklist = updateBlacklist
489 exports.splitListString = splitListString
490 exports.getBestPatternMatch = getBestPatternMatch
491
492 exports.getVersion = getVersion
493 exports.parseHTML = parseHTML
494 exports.escapeHTML = escapeHTML
495 exports.createElement = createElement
496 exports.isURL = isURL
497 exports.browserSearchSubmission = browserSearchSubmission
498 exports.normalizedKey = normalizedKey
499 exports.getHintChars = getHintChars
500 exports.removeDuplicates = removeDuplicates
501 exports.removeDuplicateCharacters = removeDuplicateCharacters
502 exports.getResourceURI = getResourceURI
503 exports.getMarkableElements = getMarkableElements
504 exports.xpathQuery = xpathQuery
505 exports.xpathQueryAll = xpathQueryAll
506 exports.ADDON_ID = ADDON_ID
Imprint / Impressum