1 { unload } = require 'unload'
6 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
8 { classes: Cc, interfaces: Ci, utils: Cu } = Components
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
23 constructor: (@idFunc, @newFunc) ->
28 if container = @bucket[id]
31 return @bucket[id] = @newFunc(obj)
34 delete @bucket[id] if id = @idFunc(obj)
36 getEventWindow = (event) ->
37 if event.originalTarget instanceof Window
38 return event.originalTarget
40 doc = event.originalTarget.ownerDocument or event.originalTarget
41 if doc instanceof HTMLDocument or doc instanceof XULDocument
42 return doc.defaultView
44 getEventRootWindow = (event) ->
45 return unless window = getEventWindow(event)
46 return getRootWindow(window)
48 getEventCurrentTabWindow = (event) ->
49 return unless rootWindow = getEventRootWindow(event)
50 return getCurrentTabWindow(rootWindow)
52 getRootWindow = (window) ->
54 .QueryInterface(Ci.nsIInterfaceRequestor)
55 .getInterface(Ci.nsIWebNavigation)
56 .QueryInterface(Ci.nsIDocShellTreeItem)
58 .QueryInterface(Ci.nsIInterfaceRequestor)
61 getCurrentTabWindow = (window) ->
62 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
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
68 { activeElement } = window.document
69 if activeElement and isElementEditable(activeElement)
72 isTextInputElement = (element) ->
73 return element instanceof HTMLInputElement or \
74 element instanceof HTMLTextAreaElement
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)
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')
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'
98 getWindowId = (window) ->
100 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
101 .getInterface(Components.interfaces.nsIDOMWindowUtils)
105 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
107 # Function that returns a URI to the css file that's part of the extension
110 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
111 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
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
118 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
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
124 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
125 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
128 sss.unregisterSheet(uri, sss.AGENT_SHEET)
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
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)
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
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) ->
153 .QueryInterface(Ci.nsIInterfaceRequestor)
154 .getInterface(Ci.nsIDOMWindowUtils)
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)
162 0, 0, # Line or Page deltas (x, y)
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)
171 # Read the system clipboard
172 readFromClipboard = (window) ->
173 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
176 privacyContext = window
177 .QueryInterface(Ci.nsIInterfaceRequestor)
178 .getInterface(Ci.nsIWebNavigation)
179 .QueryInterface(Ci.nsILoadContext)
180 trans.init(privacyContext)
182 trans.addDataFlavor('text/unicode')
184 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
185 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
190 trans.getTransferData('text/unicode', str, strLength)
193 str = str.value.QueryInterface(Ci.nsISupportsString)
194 return str.data.substring(0, strLength.value / 2)
198 # Executes function `func` and mearues how much time it took
199 timeIt = (func, msg) ->
200 start = new Date().getTime()
202 end = new Date().getTime()
204 console.log(msg, end - start)
207 isBlacklisted = (str) ->
208 matchingRules = getMatchingBlacklistRules(str)
209 return (matchingRules.length != 0)
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))
216 return splitListString(getPref('black_list'))
218 setBlacklist = (blacklist) ->
219 setPref('black_list', blacklist.join(','))
221 updateBlacklist = ({ add, remove } = {}) ->
222 blacklist = getBlacklist()
225 blacklist.push(splitListString(add)...)
227 blacklist = blacklist.filter((rule) -> rule != '')
228 blacklist = removeDuplicates(blacklist)
231 for rule in splitListString(remove) when rule in blacklist
232 blacklist.splice(blacklist.indexOf(rule), 1)
234 setBlacklist(blacklist)
236 # Splits a comma/space separated list into an array
237 splitListString = (str) ->
238 return str.split(/\s*,[\s,]*/)
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, '.')
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
256 for pattern in patterns
257 wildcarded = simpleWildcards(pattern)
258 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
262 if re.test(" #{ text } ".replace(/\s+/g, ' '))
266 # First search in attributes as it's likely that they are more specific
269 for element in elements
270 if matches(element.getAttribute(attr))
273 # Then search in element contents
274 for element in elements
275 if matches(element.textContent)
280 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
286 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
287 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
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)
297 createElement = (document, type, attributes = {}) ->
298 element = document.createElement(type)
300 for attribute, value of attributes
301 element.setAttribute(attribute, value)
303 if document instanceof HTMLDocument
304 element.classList.add('VimFxReset')
308 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
311 url = Cc['@mozilla.org/network/io-service;1']
312 .getService(Ci.nsIIOService)
313 .newURI(str, null, null)
314 .QueryInterface(Ci.nsIURL)
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)
324 engine = ss.currentEngine or ss.defaultEngine
325 return engine.getSubmission(str, null)
327 # Get hint characters, convert them to lower case, and filter duplicates
329 hintChars = getPref('hint_chars')
330 # Make sure that hint chars contain at least two characters
331 if !hintChars or hintChars.length < 2
334 return removeDuplicateCharacters(hintChars)
336 # Remove duplicate characters from string (case insensitive)
337 removeDuplicateCharacters = (str) ->
338 return removeDuplicates( str.toLowerCase().split('') ).join('')
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)
345 # Escape string to render it usable in regular expressions
346 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
348 removeDuplicates = (array) ->
350 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
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 = [
361 ACTION_ELEMENT_PROPERTIES = [
368 "contains(@class, 'button')"
369 "contains(@class, 'js-new-tweets-bar')"
372 EDITABLE_ELEMENT_TAGS = [
375 "input[not(@type='hidden' or @disabled)]"
378 EDITABLE_ELEMENT_PROPERTIES = [
379 "@contenteditable=''"
380 "translate(@contenteditable, 'TRUE', 'true')='true'"
383 FOCUSABLE_ELEMENT_TAGS = [
389 FOCUSABLE_ELEMENT_PROPERTIES = [
393 getMarkableElements = do ->
394 xpathify = (tags, properties)->
396 .concat("*[#{ properties.join(' or ') }]")
397 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
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)
405 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
406 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
409 # The actual function that will return the desired elements
410 return (document, { type }) ->
411 return xpathQueryAll(document, xpaths[type])
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)
419 xpathQuery = (node, query) ->
420 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
421 return result.singleNodeValue
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)
428 exports.Bucket = Bucket
429 exports.getEventWindow = getEventWindow
430 exports.getEventRootWindow = getEventRootWindow
431 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
432 exports.getRootWindow = getRootWindow
433 exports.getCurrentTabWindow = getCurrentTabWindow
435 exports.getWindowId = getWindowId
436 exports.blurActiveElement = blurActiveElement
437 exports.isTextInputElement = isTextInputElement
438 exports.isElementEditable = isElementEditable
439 exports.isElementVisible = isElementVisible
440 exports.getSessionStore = getSessionStore
442 exports.loadCss = loadCss
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
453 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
454 exports.isBlacklisted = isBlacklisted
455 exports.updateBlacklist = updateBlacklist
456 exports.splitListString = splitListString
457 exports.getBestPatternMatch = getBestPatternMatch
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