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