]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
fix recursion in isElementGoogleEditable impl
[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, elements) ->
254 for pattern in patterns
255 wildcarded = simpleWildcards(pattern)
256 regexp = /// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i
257 for element in elements
258 text = " #{ element.textContent } ".replace(/\s+/g, ' ')
259 if regexp.test(text)
260 return element
261
262 return null
263
264 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
265 getVersion = do ->
266 version = null
267
268 if version == null
269 scope = {}
270 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
271 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
272
273 return ->
274 return version
275
276 parseHTML = (document, html) ->
277 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
278 flags = parser.SanitizerAllowStyle
279 return parser.parseFragment(html, flags, false, null, document.documentElement)
280
281 createElement = (document, type, attributes = {}) ->
282 element = document.createElement(type)
283
284 for attribute, value of attributes
285 element.setAttribute(attribute, value)
286
287 if document instanceof HTMLDocument
288 element.classList.add('VimFxReset')
289
290 return element
291
292 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
293 isURL = (str) ->
294 try
295 url = Cc['@mozilla.org/network/io-service;1']
296 .getService(Ci.nsIIOService)
297 .newURI(str, null, null)
298 .QueryInterface(Ci.nsIURL)
299 return true
300 catch err
301 return false
302
303 # Use Firefox services to search for a given string
304 browserSearchSubmission = (str) ->
305 ss = Cc['@mozilla.org/browser/search-service;1']
306 .getService(Ci.nsIBrowserSearchService)
307
308 engine = ss.currentEngine or ss.defaultEngine
309 return engine.getSubmission(str, null)
310
311 # Get hint characters, convert them to lower case, and filter duplicates
312 getHintChars = ->
313 hintChars = getPref('hint_chars')
314 # Make sure that hint chars contain at least two characters
315 if !hintChars or hintChars.length < 2
316 hintChars = 'fj'
317
318 return removeDuplicateCharacters(hintChars)
319
320 # Remove duplicate characters from string (case insensitive)
321 removeDuplicateCharacters = (str) ->
322 return removeDuplicates( str.toLowerCase().split('') ).join('')
323
324 # Return URI to some file in the extension packaged as resource
325 getResourceURI = do ->
326 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
327 return (path) -> return Services.io.newURI(path, null, baseURI)
328
329 # Escape string to render it usable in regular expressions
330 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
331
332 removeDuplicates = (array) ->
333 seen = {}
334 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
335
336 # Why isn’t `a[@href]` used, when `area[@href]` is? Some sites (such as
337 # StackExchange sites) leave out the `href` property and use the anchor as a
338 # JavaScript-powered button (instead of just using the `button` element).
339 ACTION_ELEMENT_TAGS = [
340 "a"
341 "area[@href]"
342 "button"
343 ]
344
345 ACTION_ELEMENT_PROPERTIES = [
346 "@onclick"
347 "@onmousedown"
348 "@onmouseup"
349 "@oncommand"
350 "@role='link'"
351 "@role='button'"
352 "contains(@class, 'button')"
353 "contains(@class, 'js-new-tweets-bar')"
354 ]
355
356 EDITABLE_ELEMENT_TAGS = [
357 "textarea"
358 "select"
359 "input[not(@type='hidden' or @disabled)]"
360 ]
361
362 EDITABLE_ELEMENT_PROPERTIES = [
363 "@contenteditable=''"
364 "translate(@contenteditable, 'TRUE', 'true')='true'"
365 ]
366
367 FOCUSABLE_ELEMENT_TAGS = [
368 "iframe"
369 "embed"
370 "object"
371 ]
372
373 FOCUSABLE_ELEMENT_PROPERTIES = [
374 "@tabindex!=-1"
375 ]
376
377 getMarkableElements = do ->
378 xpathify = (tags, properties)->
379 return tags
380 .concat("*[#{ properties.join(' or ') }]")
381 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
382 .join(" | ")
383
384 xpaths =
385 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
386 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
387 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
388 all: xpathify(
389 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
390 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
391 )
392
393 # The actual function that will return the desired elements
394 return (document, { type }) ->
395 return xpathQueryAll(document, xpaths[type])
396
397 xpathHelper = (node, query, resultType) ->
398 document = node.ownerDocument ? node
399 namespaceResolver = (namespace) ->
400 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
401 return document.evaluate(query, node, namespaceResolver, resultType, null)
402
403 xpathQuery = (node, query) ->
404 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
405 return result.singleNodeValue
406
407 xpathQueryAll = (node, query) ->
408 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
409 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
410
411
412 exports.Bucket = Bucket
413 exports.getEventWindow = getEventWindow
414 exports.getEventRootWindow = getEventRootWindow
415 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
416 exports.getRootWindow = getRootWindow
417 exports.getCurrentTabWindow = getCurrentTabWindow
418
419 exports.getWindowId = getWindowId
420 exports.blurActiveElement = blurActiveElement
421 exports.isTextInputElement = isTextInputElement
422 exports.isElementEditable = isElementEditable
423 exports.isElementVisible = isElementVisible
424 exports.getSessionStore = getSessionStore
425
426 exports.loadCss = loadCss
427
428 exports.simulateClick = simulateClick
429 exports.simulateWheel = simulateWheel
430 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
431 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
432 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
433 exports.readFromClipboard = readFromClipboard
434 exports.writeToClipboard = writeToClipboard
435 exports.timeIt = timeIt
436
437 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
438 exports.isBlacklisted = isBlacklisted
439 exports.updateBlacklist = updateBlacklist
440 exports.splitListString = splitListString
441 exports.getBestPatternMatch = getBestPatternMatch
442
443 exports.getVersion = getVersion
444 exports.parseHTML = parseHTML
445 exports.createElement = createElement
446 exports.isURL = isURL
447 exports.browserSearchSubmission = browserSearchSubmission
448 exports.getHintChars = getHintChars
449 exports.removeDuplicates = removeDuplicates
450 exports.removeDuplicateCharacters = removeDuplicateCharacters
451 exports.getResourceURI = getResourceURI
452 exports.getMarkableElements = getMarkableElements
453 exports.xpathQuery = xpathQuery
454 exports.xpathQueryAll = xpathQueryAll
455 exports.ADDON_ID = ADDON_ID
Imprint / Impressum