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 case insensitive `simpleWildcards`s and must match either in
247 # the beginning or at the end of a string. Moreover, a pattern does not match
248 # in the middle of words, so "previous" does not match "previously". If that is
249 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
250 # use `\b` word boundaries, because they don’t work well with non-English
251 # characters. Instead we match a space as word boundary. Therefore we normalize
252 # the whitespace and add spaces at the edges of the element text.
253 getBestPatternMatch = (patterns, attrs, elements) ->
255 for pattern in patterns
256 wildcarded = simpleWildcards(pattern)
257 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
259 # Helper function that matches a string against all the patterns.
261 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
263 if re.test(normalizedText)
267 # First search in attributes (favoring earlier attributes) as it's likely
268 # that they are more specific than text contexts.
270 for element in elements
271 if matches(element.getAttribute(attr))
274 # Then search in element contents.
275 for element in elements
276 if matches(element.textContent)
281 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
287 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
288 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
293 parseHTML = (document, html) ->
294 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
295 flags = parser.SanitizerAllowStyle
296 return parser.parseFragment(html, flags, false, null, document.documentElement)
298 createElement = (document, type, attributes = {}) ->
299 element = document.createElement(type)
301 for attribute, value of attributes
302 element.setAttribute(attribute, value)
304 if document instanceof HTMLDocument
305 element.classList.add('VimFxReset')
309 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
312 url = Cc['@mozilla.org/network/io-service;1']
313 .getService(Ci.nsIIOService)
314 .newURI(str, null, null)
315 .QueryInterface(Ci.nsIURL)
320 # Use Firefox services to search for a given string
321 browserSearchSubmission = (str) ->
322 ss = Cc['@mozilla.org/browser/search-service;1']
323 .getService(Ci.nsIBrowserSearchService)
325 engine = ss.currentEngine or ss.defaultEngine
326 return engine.getSubmission(str, null)
328 # Get hint characters, convert them to lower case, and filter duplicates
330 hintChars = getPref('hint_chars')
331 # Make sure that hint chars contain at least two characters
332 if !hintChars or hintChars.length < 2
335 return removeDuplicateCharacters(hintChars)
337 # Remove duplicate characters from string (case insensitive)
338 removeDuplicateCharacters = (str) ->
339 return removeDuplicates( str.toLowerCase().split('') ).join('')
341 # Return URI to some file in the extension packaged as resource
342 getResourceURI = do ->
343 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
344 return (path) -> return Services.io.newURI(path, null, baseURI)
346 # Escape string to render it usable in regular expressions
347 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
349 removeDuplicates = (array) ->
351 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
353 # Why isn’t `a[@href]` used, when `area[@href]` is? Some sites (such as
354 # StackExchange sites) leave out the `href` property and use the anchor as a
355 # JavaScript-powered button (instead of just using the `button` element).
356 ACTION_ELEMENT_TAGS = [
362 ACTION_ELEMENT_PROPERTIES = [
369 "contains(@class, 'button')"
370 "contains(@class, 'js-new-tweets-bar')"
373 EDITABLE_ELEMENT_TAGS = [
376 "input[not(@type='hidden' or @disabled)]"
379 EDITABLE_ELEMENT_PROPERTIES = [
380 "@contenteditable=''"
381 "translate(@contenteditable, 'TRUE', 'true')='true'"
384 FOCUSABLE_ELEMENT_TAGS = [
390 FOCUSABLE_ELEMENT_PROPERTIES = [
394 getMarkableElements = do ->
395 xpathify = (tags, properties)->
397 .concat("*[#{ properties.join(' or ') }]")
398 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
402 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
403 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
404 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
406 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
407 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
410 # The actual function that will return the desired elements
411 return (document, { type }) ->
412 return xpathQueryAll(document, xpaths[type])
414 xpathHelper = (node, query, resultType) ->
415 document = node.ownerDocument ? node
416 namespaceResolver = (namespace) ->
417 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
418 return document.evaluate(query, node, namespaceResolver, resultType, null)
420 xpathQuery = (node, query) ->
421 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
422 return result.singleNodeValue
424 xpathQueryAll = (node, query) ->
425 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
426 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
429 exports.Bucket = Bucket
430 exports.getEventWindow = getEventWindow
431 exports.getEventRootWindow = getEventRootWindow
432 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
433 exports.getRootWindow = getRootWindow
434 exports.getCurrentTabWindow = getCurrentTabWindow
436 exports.getWindowId = getWindowId
437 exports.blurActiveElement = blurActiveElement
438 exports.isTextInputElement = isTextInputElement
439 exports.isElementEditable = isElementEditable
440 exports.isElementVisible = isElementVisible
441 exports.getSessionStore = getSessionStore
443 exports.loadCss = loadCss
445 exports.simulateClick = simulateClick
446 exports.simulateWheel = simulateWheel
447 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
448 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
449 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
450 exports.readFromClipboard = readFromClipboard
451 exports.writeToClipboard = writeToClipboard
452 exports.timeIt = timeIt
454 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
455 exports.isBlacklisted = isBlacklisted
456 exports.updateBlacklist = updateBlacklist
457 exports.splitListString = splitListString
458 exports.getBestPatternMatch = getBestPatternMatch
460 exports.getVersion = getVersion
461 exports.parseHTML = parseHTML
462 exports.createElement = createElement
463 exports.isURL = isURL
464 exports.browserSearchSubmission = browserSearchSubmission
465 exports.getHintChars = getHintChars
466 exports.removeDuplicates = removeDuplicates
467 exports.removeDuplicateCharacters = removeDuplicateCharacters
468 exports.getResourceURI = getResourceURI
469 exports.getMarkableElements = getMarkableElements
470 exports.xpathQuery = xpathQuery
471 exports.xpathQueryAll = xpathQueryAll
472 exports.ADDON_ID = ADDON_ID