]> git.gir.st - VimFx.git/blob - extension/lib/utils.coffee
Let simulated clicks bubble
[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 Window = Ci.nsIDOMWindow
32 ChromeWindow = Ci.nsIDOMChromeWindow
33 Element = Ci.nsIDOMElement
34 HTMLDocument = Ci.nsIDOMHTMLDocument
35 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
36 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
37 HTMLInputElement = Ci.nsIDOMHTMLInputElement
38 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
39 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
40 XULDocument = Ci.nsIDOMXULDocument
41 XULButtonElement = Ci.nsIDOMXULButtonElement
42 XULControlElement = Ci.nsIDOMXULControlElement
43 XULMenuListElement = Ci.nsIDOMXULMenuListElement
44 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
45
46 class Bucket
47 constructor: (@newFunc) ->
48 @bucket = new WeakMap()
49
50 get: (obj) ->
51 if @bucket.has(obj)
52 return @bucket.get(obj)
53 else
54 value = @newFunc(obj)
55 @bucket.set(obj, value)
56 return value
57
58 forget: (obj) ->
59 @bucket.delete(obj)
60
61 getEventWindow = (event) ->
62 if event.originalTarget instanceof Window
63 return event.originalTarget
64 else
65 doc = event.originalTarget.ownerDocument or event.originalTarget
66 if doc instanceof HTMLDocument or doc instanceof XULDocument
67 return doc.defaultView
68
69 getEventRootWindow = (event) ->
70 return unless window = getEventWindow(event)
71 return getRootWindow(window)
72
73 getEventCurrentTabWindow = (event) ->
74 return unless rootWindow = getEventRootWindow(event)
75 return getCurrentTabWindow(rootWindow)
76
77 getRootWindow = (window) ->
78 return window
79 .QueryInterface(Ci.nsIInterfaceRequestor)
80 .getInterface(Ci.nsIWebNavigation)
81 .QueryInterface(Ci.nsIDocShellTreeItem)
82 .rootTreeItem
83 .QueryInterface(Ci.nsIInterfaceRequestor)
84 .getInterface(Window)
85
86 getCurrentTabWindow = (window) ->
87 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
88
89 blurActiveElement = (window) ->
90 # Only blur focusable elements, in order to interfere with the browser as
91 # little as possible.
92 { activeElement } = window.document
93 if activeElement and activeElement.tabIndex > -1
94 activeElement.blur()
95
96 isProperLink = (element) ->
97 return (element instanceof HTMLAnchorElement or
98 (element.ownerDocument instanceof XULDocument and
99 element.hasAttribute('href'))) and
100 not element.href.endsWith('#') and
101 not element.href.startsWith('javascript:')
102
103 isTextInputElement = (element) ->
104 return (element instanceof HTMLInputElement and element.type in [
105 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
106 ]) or
107 element instanceof HTMLTextAreaElement or
108 # `<select>` elements can also receive text input: You may type the
109 # text of an item to select it.
110 element instanceof HTMLSelectElement or
111 element instanceof XULMenuListElement or
112 element instanceof XULTextBoxElement
113
114 isContentEditable = (element) ->
115 return element.isContentEditable or
116 isGoogleEditable(element)
117
118 isGoogleEditable = (element) ->
119 # `g_editable` is a non-standard attribute commonly used by Google.
120 return element.getAttribute?('g_editable') == 'true' or
121 element.ownerDocument.body?.getAttribute('g_editable') == 'true'
122
123 isActivatable = (element) ->
124 return element instanceof HTMLAnchorElement or
125 element instanceof HTMLButtonElement or
126 (element instanceof HTMLInputElement and element.type in [
127 'button', 'submit', 'reset', 'image'
128 ]) or
129 element instanceof XULButtonElement
130
131 isAdjustable = (element) ->
132 return element instanceof HTMLInputElement and element.type in [
133 'checkbox', 'radio', 'file', 'color'
134 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
135 ] or
136 element instanceof XULControlElement
137
138 area = (element) ->
139 return element.clientWidth * element.clientHeight
140
141 getSessionStore = ->
142 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
143
144 loadCss = do ->
145 sss = Cc['@mozilla.org/content/style-sheet-service;1']
146 .getService(Ci.nsIStyleSheetService)
147 return (name) ->
148 uri = getResourceURI("resources/#{ name }.css")
149 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
150 # website themes installed by users often make the hint markers unreadable,
151 # for example. Just using `!important` in the CSS is not enough.
152 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
153 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
154
155 module.onShutdown(->
156 sss.unregisterSheet(uri, sss.AGENT_SHEET)
157 )
158
159 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
160 # memory. This approach is better than for example setting `event.simulated =
161 # true`, since that tells the sites that the click was simulated, and allows
162 # sites to spoof it.
163 simulated_events = new WeakMap()
164
165 # Simulate mouse click with a full chain of events. ('command' is for XUL
166 # elements.)
167 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click', 'command']
168 simulateClick = (element) ->
169 window = element.ownerDocument.defaultView
170 for type in eventSequence
171 mouseEvent = new window.MouseEvent(type, {
172 # Let the event bubble in order to trigger delegated event listeners.
173 bubbles: true
174 })
175 element.dispatchEvent(mouseEvent)
176
177 isEventSimulated = (event) ->
178 return simulated_events.has(event)
179
180 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
181 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
182 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
183
184 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
185 # specified position.
186 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
187 windowUtils = window
188 .QueryInterface(Ci.nsIInterfaceRequestor)
189 .getInterface(Ci.nsIDOMWindowUtils)
190
191 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
192 windowUtils.sendWheelEvent(
193 pX, pY, # Window offset (x, y) in pixels.
194 deltaX, deltaY, 0, # Deltas (x, y, z).
195 mode, # Mode (pixel, line, page).
196 0, # Key Modifiers.
197 0, 0, # Line or Page deltas (x, y).
198 0 # Options.
199 )
200
201 # Write a string to the system clipboard.
202 writeToClipboard = (text) ->
203 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
204 .getService(Ci.nsIClipboardHelper)
205 clipboardHelper.copyString(text)
206
207 # Executes function `func` and mearues how much time it took.
208 timeIt = (func, name) ->
209 console.time(name)
210 result = func()
211 console.timeEnd(name)
212 return result
213
214 isBlacklisted = (str) ->
215 matchingRules = getMatchingBlacklistRules(str)
216 return (matchingRules.length != 0)
217
218 # Returns all blacklisted keys in matching rules.
219 getBlacklistedKeys = (str) ->
220 matchingRules = getMatchingBlacklistRules(str)
221 blacklistedKeys = []
222 for rule in matchingRules when /##/.test(rule)
223 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
224 return blacklistedKeys
225
226 # Returns all rules in the blacklist that match the provided string.
227 getMatchingBlacklistRules = (str) ->
228 return getBlacklist().filter((rule) ->
229 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
230 )
231
232 getBlacklist = ->
233 return splitListString(getPref('black_list'))
234
235 setBlacklist = (blacklist) ->
236 setPref('black_list', blacklist.join(','))
237
238 updateBlacklist = ({ add, remove } = {}) ->
239 blacklist = getBlacklist()
240
241 if add
242 blacklist.push(splitListString(add)...)
243
244 blacklist = blacklist.filter((rule) -> rule != '')
245 blacklist = removeDuplicates(blacklist)
246
247 if remove
248 for rule in splitListString(remove) when rule in blacklist
249 blacklist.splice(blacklist.indexOf(rule), 1)
250
251 setBlacklist(blacklist)
252
253 # Splits a comma/space separated list into an array.
254 splitListString = (str) ->
255 return str.split(/\s*,[\s,]*/)
256
257 # Prepares a string to be used in a regexp, where "*" matches zero or more
258 # characters and "!" matches one character.
259 simpleWildcards = (string) ->
260 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
261
262 # Returns the first element that matches a pattern, favoring earlier patterns.
263 # The patterns are case insensitive `simpleWildcards`s and must match either in
264 # the beginning or at the end of a string. Moreover, a pattern does not match
265 # in the middle of words, so "previous" does not match "previously". If that is
266 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
267 # use `\b` word boundaries, because they don’t work well with non-English
268 # characters. Instead we match a space as word boundary. Therefore we normalize
269 # the whitespace and add spaces at the edges of the element text.
270 getBestPatternMatch = (patterns, attrs, elements) ->
271 regexps = []
272 for pattern in patterns
273 wildcarded = simpleWildcards(pattern)
274 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
275
276 # Helper function that matches a string against all the patterns.
277 matches = (text) ->
278 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
279 for re in regexps
280 if re.test(normalizedText)
281 return true
282 return false
283
284 # First search in attributes (favoring earlier attributes) as it's likely
285 # that they are more specific than text contexts.
286 for attr in attrs
287 for element in elements
288 if matches(element.getAttribute(attr))
289 return element
290
291 # Then search in element contents.
292 for element in elements
293 if matches(element.textContent)
294 return element
295
296 return null
297
298 # Get VimFx verion. AddonManager only provides async API to access addon data,
299 # so it's a bit tricky...
300 getVersion = do ->
301 version = null
302
303 scope = {}
304 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
305 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
306
307 return ->
308 return version
309
310 parseHTML = (document, html) ->
311 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
312 flags = parser.SanitizerAllowStyle
313 return parser.parseFragment(html, flags, false, null,
314 document.documentElement)
315
316 escapeHTML = (s) ->
317 return s
318 .replace(/&/g, '&amp;')
319 .replace(/</g, '&lt;')
320 .replace(/>/g, '&gt;')
321 .replace(/"/g, '&quot;')
322 .replace(/'/g, '&apos;')
323
324 createElement = (document, type, attributes = {}) ->
325 element = document.createElement(type)
326
327 for attribute, value of attributes
328 element.setAttribute(attribute, value)
329
330 if document instanceof HTMLDocument
331 element.classList.add('VimFxReset')
332
333 return element
334
335 getAllElements = (document) -> switch
336 when document instanceof HTMLDocument
337 return document.getElementsByTagName('*')
338 when document instanceof XULDocument
339 elements = []
340 getAllRegular = (element) ->
341 for child in element.getElementsByTagName('*')
342 elements.push(child)
343 getAllAnonymous(child)
344 return
345 getAllAnonymous = (element) ->
346 for child in document.getAnonymousNodes(element) or []
347 continue unless child instanceof Element
348 elements.push(child)
349 getAllRegular(child)
350 return
351 getAllRegular(document.documentElement)
352 return elements
353
354 isURL = (str) ->
355 try
356 url = Cc['@mozilla.org/network/io-service;1']
357 .getService(Ci.nsIIOService)
358 .newURI(str, null, null)
359 .QueryInterface(Ci.nsIURL)
360 return true
361 catch err
362 return false
363
364 # Use Firefox services to search for a given string.
365 browserSearchSubmission = (str) ->
366 ss = Cc['@mozilla.org/browser/search-service;1']
367 .getService(Ci.nsIBrowserSearchService)
368
369 engine = ss.currentEngine or ss.defaultEngine
370 return engine.getSubmission(str, null)
371
372 openTab = (rootWindow, url, options) ->
373 { gBrowser } = rootWindow
374 rootWindow.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
375 gBrowser.loadOneTab(url, options)
376
377 normalizedKey = (key) -> key.map(notation.normalize).join('')
378
379 # Get hint characters, convert them to lower case, and filter duplicates.
380 getHintChars = ->
381 hintChars = getPref('hint_chars')
382 # Make sure that hint chars contain at least two characters.
383 if not hintChars or hintChars.length < 2
384 hintChars = 'fj'
385
386 return removeDuplicateCharacters(hintChars)
387
388 # Remove duplicate characters from string (case insensitive).
389 removeDuplicateCharacters = (str) ->
390 return removeDuplicates( str.toLowerCase().split('') ).join('')
391
392 # Return URI to some file in the extension packaged as resource.
393 getResourceURI = do ->
394 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
395 return (path) -> return Services.io.newURI(path, null, baseURI)
396
397 # Escape a string to render it usable in regular expressions.
398 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
399
400 removeDuplicates = (array) ->
401 # coffeelint: disable=no_backticks
402 return `[...new Set(array)]`
403 # coffeelint: enable=no_backticks
404
405 exports.Bucket = Bucket
406 exports.getEventWindow = getEventWindow
407 exports.getEventRootWindow = getEventRootWindow
408 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
409 exports.getRootWindow = getRootWindow
410 exports.getCurrentTabWindow = getCurrentTabWindow
411
412 exports.blurActiveElement = blurActiveElement
413 exports.isProperLink = isProperLink
414 exports.isTextInputElement = isTextInputElement
415 exports.isContentEditable = isContentEditable
416 exports.isActivatable = isActivatable
417 exports.isAdjustable = isAdjustable
418 exports.area = area
419 exports.getSessionStore = getSessionStore
420
421 exports.loadCss = loadCss
422
423 exports.simulateClick = simulateClick
424 exports.isEventSimulated = isEventSimulated
425 exports.simulateWheel = simulateWheel
426 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
427 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
428 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
429 exports.writeToClipboard = writeToClipboard
430 exports.timeIt = timeIt
431
432 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
433 exports.isBlacklisted = isBlacklisted
434 exports.getBlacklistedKeys = getBlacklistedKeys
435 exports.updateBlacklist = updateBlacklist
436 exports.splitListString = splitListString
437 exports.getBestPatternMatch = getBestPatternMatch
438
439 exports.getVersion = getVersion
440 exports.parseHTML = parseHTML
441 exports.escapeHTML = escapeHTML
442 exports.createElement = createElement
443 exports.getAllElements = getAllElements
444 exports.isURL = isURL
445 exports.browserSearchSubmission = browserSearchSubmission
446 exports.openTab = openTab
447 exports.normalizedKey = normalizedKey
448 exports.getHintChars = getHintChars
449 exports.removeDuplicates = removeDuplicates
450 exports.removeDuplicateCharacters = removeDuplicateCharacters
451 exports.getResourceURI = getResourceURI
452 exports.ADDON_ID = ADDON_ID
Imprint / Impressum