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