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 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
131 # memory. This approach is better than for example setting `event.simulated =
132 # true`, since that tells the sites that the click was simulated, and allows
134 simulated_events = new WeakMap()
136 # Simulate mouse click with full chain of event
137 # Copied from Vimium codebase
138 simulateClick = (element, modifiers = {}) ->
139 document = element.ownerDocument
140 window = document.defaultView
142 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
143 for event in eventSequence
144 mouseEvent = document.createEvent('MouseEvents')
145 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
146 modifiers.metaKey, 0, null)
147 simulated_events.set(mouseEvent, true)
148 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
149 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
150 element.dispatchEvent(mouseEvent)
152 isEventSimulated = (event) ->
153 return simulated_events.has(event)
155 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
156 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
157 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
159 # Simulate mouse scroll event by specific offsets given
160 # that mouse cursor is at specified position
161 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
163 .QueryInterface(Ci.nsIInterfaceRequestor)
164 .getInterface(Ci.nsIDOMWindowUtils)
166 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
167 windowUtils.sendWheelEvent(
168 pX, pY, # Window offset (x, y) in pixels
169 deltaX, deltaY, 0, # Deltas (x, y, z)
170 mode, # Mode (pixel, line, page)
172 0, 0, # Line or Page deltas (x, y)
176 # Write a string to the system clipboard
177 writeToClipboard = (text) ->
178 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1'].getService(Ci.nsIClipboardHelper)
179 clipboardHelper.copyString(text)
181 # Read the system clipboard
182 readFromClipboard = (window) ->
183 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
186 privacyContext = window
187 .QueryInterface(Ci.nsIInterfaceRequestor)
188 .getInterface(Ci.nsIWebNavigation)
189 .QueryInterface(Ci.nsILoadContext)
190 trans.init(privacyContext)
192 trans.addDataFlavor('text/unicode')
194 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
195 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
200 trans.getTransferData('text/unicode', str, strLength)
203 str = str.value.QueryInterface(Ci.nsISupportsString)
204 return str.data.substring(0, strLength.value / 2)
208 # Executes function `func` and mearues how much time it took
209 timeIt = (func, msg) ->
210 start = new Date().getTime()
212 end = new Date().getTime()
214 console.log(msg, end - start)
217 isBlacklisted = (str) ->
218 matchingRules = getMatchingBlacklistRules(str)
219 return (matchingRules.length != 0)
221 # Returns all rules in the blacklist that match the provided string
222 getMatchingBlacklistRules = (str) ->
223 return getBlacklist().filter((rule) -> /// ^#{ simpleWildcards(rule) }$ ///i.test(str))
226 return splitListString(getPref('black_list'))
228 setBlacklist = (blacklist) ->
229 setPref('black_list', blacklist.join(','))
231 updateBlacklist = ({ add, remove } = {}) ->
232 blacklist = getBlacklist()
235 blacklist.push(splitListString(add)...)
237 blacklist = blacklist.filter((rule) -> rule != '')
238 blacklist = removeDuplicates(blacklist)
241 for rule in splitListString(remove) when rule in blacklist
242 blacklist.splice(blacklist.indexOf(rule), 1)
244 setBlacklist(blacklist)
246 # Splits a comma/space separated list into an array
247 splitListString = (str) ->
248 return str.split(/\s*,[\s,]*/)
250 # Prepares a string to be used in a regexp, where "*" matches zero or more characters
251 # and "!" matches one character.
252 simpleWildcards = (string) ->
253 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
255 # Returns the first element that matches a pattern, favoring earlier patterns.
256 # The patterns are case insensitive `simpleWildcards`s and must match either in
257 # the beginning or at the end of a string. Moreover, a pattern does not match
258 # in the middle of words, so "previous" does not match "previously". If that is
259 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
260 # use `\b` word boundaries, because they don’t work well with non-English
261 # characters. Instead we match a space as word boundary. Therefore we normalize
262 # the whitespace and add spaces at the edges of the element text.
263 getBestPatternMatch = (patterns, attrs, elements) ->
265 for pattern in patterns
266 wildcarded = simpleWildcards(pattern)
267 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
269 # Helper function that matches a string against all the patterns.
271 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
273 if re.test(normalizedText)
277 # First search in attributes (favoring earlier attributes) as it's likely
278 # that they are more specific than text contexts.
280 for element in elements
281 if matches(element.getAttribute(attr))
284 # Then search in element contents.
285 for element in elements
286 if matches(element.textContent)
291 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
297 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
298 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
303 parseHTML = (document, html) ->
304 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
305 flags = parser.SanitizerAllowStyle
306 return parser.parseFragment(html, flags, false, null, document.documentElement)
308 createElement = (document, type, attributes = {}) ->
309 element = document.createElement(type)
311 for attribute, value of attributes
312 element.setAttribute(attribute, value)
314 if document instanceof HTMLDocument
315 element.classList.add('VimFxReset')
319 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
322 url = Cc['@mozilla.org/network/io-service;1']
323 .getService(Ci.nsIIOService)
324 .newURI(str, null, null)
325 .QueryInterface(Ci.nsIURL)
330 # Use Firefox services to search for a given string
331 browserSearchSubmission = (str) ->
332 ss = Cc['@mozilla.org/browser/search-service;1']
333 .getService(Ci.nsIBrowserSearchService)
335 engine = ss.currentEngine or ss.defaultEngine
336 return engine.getSubmission(str, null)
338 # Get hint characters, convert them to lower case, and filter duplicates
340 hintChars = getPref('hint_chars')
341 # Make sure that hint chars contain at least two characters
342 if !hintChars or hintChars.length < 2
345 return removeDuplicateCharacters(hintChars)
347 # Remove duplicate characters from string (case insensitive)
348 removeDuplicateCharacters = (str) ->
349 return removeDuplicates( str.toLowerCase().split('') ).join('')
351 # Return URI to some file in the extension packaged as resource
352 getResourceURI = do ->
353 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
354 return (path) -> return Services.io.newURI(path, null, baseURI)
356 # Escape string to render it usable in regular expressions
357 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
359 removeDuplicates = (array) ->
361 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
363 # Why isn’t `a[@href]` used, when `area[@href]` is? Some sites (such as
364 # StackExchange sites) leave out the `href` property and use the anchor as a
365 # JavaScript-powered button (instead of just using the `button` element).
366 ACTION_ELEMENT_TAGS = [
372 ACTION_ELEMENT_PROPERTIES = [
379 "contains(@class, 'button')"
380 "contains(@class, 'js-new-tweets-bar')"
383 EDITABLE_ELEMENT_TAGS = [
386 "input[not(@type='hidden' or @disabled)]"
389 EDITABLE_ELEMENT_PROPERTIES = [
390 "@contenteditable=''"
391 "translate(@contenteditable, 'TRUE', 'true')='true'"
394 FOCUSABLE_ELEMENT_TAGS = [
400 FOCUSABLE_ELEMENT_PROPERTIES = [
404 getMarkableElements = do ->
405 xpathify = (tags, properties)->
407 .concat("*[#{ properties.join(' or ') }]")
408 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
412 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
413 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
414 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
416 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
417 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
420 # The actual function that will return the desired elements
421 return (document, { type }) ->
422 return xpathQueryAll(document, xpaths[type])
424 xpathHelper = (node, query, resultType) ->
425 document = node.ownerDocument ? node
426 namespaceResolver = (namespace) ->
427 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
428 return document.evaluate(query, node, namespaceResolver, resultType, null)
430 xpathQuery = (node, query) ->
431 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
432 return result.singleNodeValue
434 xpathQueryAll = (node, query) ->
435 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
436 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
439 exports.Bucket = Bucket
440 exports.getEventWindow = getEventWindow
441 exports.getEventRootWindow = getEventRootWindow
442 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
443 exports.getRootWindow = getRootWindow
444 exports.getCurrentTabWindow = getCurrentTabWindow
446 exports.getWindowId = getWindowId
447 exports.blurActiveElement = blurActiveElement
448 exports.isTextInputElement = isTextInputElement
449 exports.isElementEditable = isElementEditable
450 exports.isElementVisible = isElementVisible
451 exports.getSessionStore = getSessionStore
453 exports.loadCss = loadCss
455 exports.simulateClick = simulateClick
456 exports.isEventSimulated = isEventSimulated
457 exports.simulateWheel = simulateWheel
458 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
459 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
460 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
461 exports.readFromClipboard = readFromClipboard
462 exports.writeToClipboard = writeToClipboard
463 exports.timeIt = timeIt
465 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
466 exports.isBlacklisted = isBlacklisted
467 exports.updateBlacklist = updateBlacklist
468 exports.splitListString = splitListString
469 exports.getBestPatternMatch = getBestPatternMatch
471 exports.getVersion = getVersion
472 exports.parseHTML = parseHTML
473 exports.createElement = createElement
474 exports.isURL = isURL
475 exports.browserSearchSubmission = browserSearchSubmission
476 exports.getHintChars = getHintChars
477 exports.removeDuplicates = removeDuplicates
478 exports.removeDuplicateCharacters = removeDuplicateCharacters
479 exports.getResourceURI = getResourceURI
480 exports.getMarkableElements = getMarkableElements
481 exports.xpathQuery = xpathQuery
482 exports.xpathQueryAll = xpathQueryAll
483 exports.ADDON_ID = ADDON_ID