]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Merge pull request #343 from lydell/better-find-mode
[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 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
124 # memory. This approach is better than for example setting `event.simulated =
125 # true`, since that tells the sites that the click was simulated, and allows
126 # sites to spoof it.
127 simulated_events = new WeakMap()
128
129 # Simulate mouse click with full chain of event
130 # Copied from Vimium codebase
131 simulateClick = (element, modifiers = {}) ->
132 document = element.ownerDocument
133 window = document.defaultView
134
135 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
136 for event in eventSequence
137 mouseEvent = document.createEvent('MouseEvents')
138 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
139 modifiers.metaKey, 0, null)
140 simulated_events.set(mouseEvent, true)
141 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
142 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
143 element.dispatchEvent(mouseEvent)
144
145 isEventSimulated = (event) ->
146 return simulated_events.has(event)
147
148 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
149 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
150 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
151
152 # Simulate mouse scroll event by specific offsets given
153 # that mouse cursor is at specified position
154 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
155 windowUtils = window
156 .QueryInterface(Ci.nsIInterfaceRequestor)
157 .getInterface(Ci.nsIDOMWindowUtils)
158
159 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
160 windowUtils.sendWheelEvent(
161 pX, pY, # Window offset (x, y) in pixels
162 deltaX, deltaY, 0, # Deltas (x, y, z)
163 mode, # Mode (pixel, line, page)
164 0, # Key Modifiers
165 0, 0, # Line or Page deltas (x, y)
166 0 # Options
167 )
168
169 # Write a string to the system clipboard
170 writeToClipboard = (text) ->
171 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1'].getService(Ci.nsIClipboardHelper)
172 clipboardHelper.copyString(text)
173
174 # Read the system clipboard
175 readFromClipboard = (window) ->
176 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
177
178 if trans.init
179 privacyContext = window
180 .QueryInterface(Ci.nsIInterfaceRequestor)
181 .getInterface(Ci.nsIWebNavigation)
182 .QueryInterface(Ci.nsILoadContext)
183 trans.init(privacyContext)
184
185 trans.addDataFlavor('text/unicode')
186
187 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
188 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
189
190 str = {}
191 strLength = {}
192
193 trans.getTransferData('text/unicode', str, strLength)
194
195 if str
196 str = str.value.QueryInterface(Ci.nsISupportsString)
197 return str.data.substring(0, strLength.value / 2)
198
199 return undefined
200
201 # Executes function `func` and mearues how much time it took
202 timeIt = (func, msg) ->
203 start = new Date().getTime()
204 result = func()
205 end = new Date().getTime()
206
207 console.log(msg, end - start)
208 return result
209
210 isBlacklisted = (str) ->
211 matchingRules = getMatchingBlacklistRules(str)
212 return (matchingRules.length != 0)
213
214 # Returns all rules in the blacklist that match the provided string
215 getMatchingBlacklistRules = (str) ->
216 return getBlacklist().filter((rule) -> /// ^#{ simpleWildcards(rule) }$ ///i.test(str))
217
218 getBlacklist = ->
219 return splitListString(getPref('black_list'))
220
221 setBlacklist = (blacklist) ->
222 setPref('black_list', blacklist.join(','))
223
224 updateBlacklist = ({ add, remove } = {}) ->
225 blacklist = getBlacklist()
226
227 if add
228 blacklist.push(splitListString(add)...)
229
230 blacklist = blacklist.filter((rule) -> rule != '')
231 blacklist = removeDuplicates(blacklist)
232
233 if remove
234 for rule in splitListString(remove) when rule in blacklist
235 blacklist.splice(blacklist.indexOf(rule), 1)
236
237 setBlacklist(blacklist)
238
239 # Splits a comma/space separated list into an array
240 splitListString = (str) ->
241 return str.split(/\s*,[\s,]*/)
242
243 # Prepares a string to be used in a regexp, where "*" matches zero or more characters
244 # and "!" matches one character.
245 simpleWildcards = (string) ->
246 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
247
248 # Returns the first element that matches a pattern, favoring earlier patterns.
249 # The patterns are case insensitive `simpleWildcards`s and must match either in
250 # the beginning or at the end of a string. Moreover, a pattern does not match
251 # in the middle of words, so "previous" does not match "previously". If that is
252 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
253 # use `\b` word boundaries, because they don’t work well with non-English
254 # characters. Instead we match a space as word boundary. Therefore we normalize
255 # the whitespace and add spaces at the edges of the element text.
256 getBestPatternMatch = (patterns, attrs, elements) ->
257 regexps = []
258 for pattern in patterns
259 wildcarded = simpleWildcards(pattern)
260 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
261
262 # Helper function that matches a string against all the patterns.
263 matches = (text) ->
264 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
265 for re in regexps
266 if re.test(normalizedText)
267 return true
268 return false
269
270 # First search in attributes (favoring earlier attributes) as it's likely
271 # that they are more specific than text contexts.
272 for attr in attrs
273 for element in elements
274 if matches(element.getAttribute(attr))
275 return element
276
277 # Then search in element contents.
278 for element in elements
279 if matches(element.textContent)
280 return element
281
282 return null
283
284 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
285 getVersion = do ->
286 version = null
287
288 if version == null
289 scope = {}
290 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
291 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
292
293 return ->
294 return version
295
296 parseHTML = (document, html) ->
297 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
298 flags = parser.SanitizerAllowStyle
299 return parser.parseFragment(html, flags, false, null, document.documentElement)
300
301 createElement = (document, type, attributes = {}) ->
302 element = document.createElement(type)
303
304 for attribute, value of attributes
305 element.setAttribute(attribute, value)
306
307 if document instanceof HTMLDocument
308 element.classList.add('VimFxReset')
309
310 return element
311
312 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
313 isURL = (str) ->
314 try
315 url = Cc['@mozilla.org/network/io-service;1']
316 .getService(Ci.nsIIOService)
317 .newURI(str, null, null)
318 .QueryInterface(Ci.nsIURL)
319 return true
320 catch err
321 return false
322
323 # Use Firefox services to search for a given string
324 browserSearchSubmission = (str) ->
325 ss = Cc['@mozilla.org/browser/search-service;1']
326 .getService(Ci.nsIBrowserSearchService)
327
328 engine = ss.currentEngine or ss.defaultEngine
329 return engine.getSubmission(str, null)
330
331 # Get hint characters, convert them to lower case, and filter duplicates
332 getHintChars = ->
333 hintChars = getPref('hint_chars')
334 # Make sure that hint chars contain at least two characters
335 if !hintChars or hintChars.length < 2
336 hintChars = 'fj'
337
338 return removeDuplicateCharacters(hintChars)
339
340 # Remove duplicate characters from string (case insensitive)
341 removeDuplicateCharacters = (str) ->
342 return removeDuplicates( str.toLowerCase().split('') ).join('')
343
344 # Return URI to some file in the extension packaged as resource
345 getResourceURI = do ->
346 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
347 return (path) -> return Services.io.newURI(path, null, baseURI)
348
349 # Escape string to render it usable in regular expressions
350 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
351
352 removeDuplicates = (array) ->
353 seen = {}
354 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
355
356 # Why isn’t `a[@href]` used, when `area[@href]` is? Some sites (such as
357 # StackExchange sites) leave out the `href` property and use the anchor as a
358 # JavaScript-powered button (instead of just using the `button` element).
359 ACTION_ELEMENT_TAGS = [
360 "a"
361 "area[@href]"
362 "button"
363 ]
364
365 ACTION_ELEMENT_PROPERTIES = [
366 "@onclick"
367 "@onmousedown"
368 "@onmouseup"
369 "@oncommand"
370 "@role='link'"
371 "@role='button'"
372 "contains(@class, 'button')"
373 "contains(@class, 'js-new-tweets-bar')"
374 ]
375
376 EDITABLE_ELEMENT_TAGS = [
377 "textarea"
378 "select"
379 "input[not(@type='hidden' or @disabled)]"
380 ]
381
382 EDITABLE_ELEMENT_PROPERTIES = [
383 "@contenteditable=''"
384 "translate(@contenteditable, 'TRUE', 'true')='true'"
385 ]
386
387 FOCUSABLE_ELEMENT_TAGS = [
388 "iframe"
389 "embed"
390 "object"
391 ]
392
393 FOCUSABLE_ELEMENT_PROPERTIES = [
394 "@tabindex!=-1"
395 ]
396
397 getMarkableElements = do ->
398 xpathify = (tags, properties)->
399 return tags
400 .concat("*[#{ properties.join(' or ') }]")
401 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
402 .join(" | ")
403
404 xpaths =
405 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
406 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
407 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
408 all: xpathify(
409 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
410 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
411 )
412
413 # The actual function that will return the desired elements
414 return (document, { type }) ->
415 return xpathQueryAll(document, xpaths[type])
416
417 xpathHelper = (node, query, resultType) ->
418 document = node.ownerDocument ? node
419 namespaceResolver = (namespace) ->
420 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
421 return document.evaluate(query, node, namespaceResolver, resultType, null)
422
423 xpathQuery = (node, query) ->
424 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
425 return result.singleNodeValue
426
427 xpathQueryAll = (node, query) ->
428 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
429 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
430
431
432 exports.Bucket = Bucket
433 exports.getEventWindow = getEventWindow
434 exports.getEventRootWindow = getEventRootWindow
435 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
436 exports.getRootWindow = getRootWindow
437 exports.getCurrentTabWindow = getCurrentTabWindow
438
439 exports.blurActiveElement = blurActiveElement
440 exports.isTextInputElement = isTextInputElement
441 exports.isElementEditable = isElementEditable
442 exports.isElementVisible = isElementVisible
443 exports.getSessionStore = getSessionStore
444
445 exports.loadCss = loadCss
446
447 exports.simulateClick = simulateClick
448 exports.isEventSimulated = isEventSimulated
449 exports.simulateWheel = simulateWheel
450 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
451 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
452 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
453 exports.readFromClipboard = readFromClipboard
454 exports.writeToClipboard = writeToClipboard
455 exports.timeIt = timeIt
456
457 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
458 exports.isBlacklisted = isBlacklisted
459 exports.updateBlacklist = updateBlacklist
460 exports.splitListString = splitListString
461 exports.getBestPatternMatch = getBestPatternMatch
462
463 exports.getVersion = getVersion
464 exports.parseHTML = parseHTML
465 exports.createElement = createElement
466 exports.isURL = isURL
467 exports.browserSearchSubmission = browserSearchSubmission
468 exports.getHintChars = getHintChars
469 exports.removeDuplicates = removeDuplicates
470 exports.removeDuplicateCharacters = removeDuplicateCharacters
471 exports.getResourceURI = getResourceURI
472 exports.getMarkableElements = getMarkableElements
473 exports.xpathQuery = xpathQuery
474 exports.xpathQueryAll = xpathQueryAll
475 exports.ADDON_ID = ADDON_ID
Imprint / Impressum