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: (@newFunc) ->
24 @bucket = new WeakMap()
28 return @bucket.get(obj)
30 return @bucket.set(obj, @newFunc(obj))
35 getEventWindow = (event) ->
36 if event.originalTarget instanceof Window
37 return event.originalTarget
39 doc = event.originalTarget.ownerDocument or event.originalTarget
40 if doc instanceof HTMLDocument or doc instanceof XULDocument
41 return doc.defaultView
43 getEventRootWindow = (event) ->
44 return unless window = getEventWindow(event)
45 return getRootWindow(window)
47 getEventCurrentTabWindow = (event) ->
48 return unless rootWindow = getEventRootWindow(event)
49 return getCurrentTabWindow(rootWindow)
51 getRootWindow = (window) ->
53 .QueryInterface(Ci.nsIInterfaceRequestor)
54 .getInterface(Ci.nsIWebNavigation)
55 .QueryInterface(Ci.nsIDocShellTreeItem)
57 .QueryInterface(Ci.nsIInterfaceRequestor)
60 getCurrentTabWindow = (window) ->
61 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
63 blurActiveElement = (window) ->
64 # Only blur editable elements, in order not to interfere with the browser too much. TODO: Is that
65 # really needed? What if a website has made more elements focusable -- shouldn't those also be
67 { activeElement } = window.document
68 if activeElement and isElementEditable(activeElement)
71 isTextInputElement = (element) ->
72 return element instanceof HTMLInputElement or \
73 element instanceof HTMLTextAreaElement
75 isElementEditable = (element) ->
76 return element.isContentEditable or \
77 element instanceof HTMLInputElement or \
78 element instanceof HTMLTextAreaElement or \
79 element instanceof HTMLSelectElement or \
80 element instanceof XULMenuListElement or \
81 element.isContentEditable or \
82 isElementGoogleEditable(element)
84 # Non-standard attribute commonly used by Google.
85 isElementGoogleEditable = (element) ->
86 element.getAttribute?('g_editable') == 'true' or \
87 (element instanceof HTMLElement and element.ownerDocument.body?.getAttribute('g_editable') == 'true')
89 isElementVisible = (element) ->
90 document = element.ownerDocument
91 window = document.defaultView
92 if computedStyle = window.getComputedStyle(element, null)
93 return computedStyle.getPropertyValue('visibility') == 'visible' and \
94 computedStyle.getPropertyValue('display') != 'none' and \
95 computedStyle.getPropertyValue('opacity') != '0'
98 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
100 # Function that returns a URI to the css file that's part of the extension
103 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
104 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
107 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
108 # The stylesheet is then appended to every document, but it can be overwritten by
111 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
114 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
115 # by users often make the hint markers unreadable, for example. Just using `!important` in the
117 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
118 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
121 sss.unregisterSheet(uri, sss.AGENT_SHEET)
123 # Simulate mouse click with full chain of event
124 # Copied from Vimium codebase
125 simulateClick = (element, modifiers = {}) ->
126 document = element.ownerDocument
127 window = document.defaultView
129 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
130 for event in eventSequence
131 mouseEvent = document.createEvent('MouseEvents')
132 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
133 modifiers.metaKey, 0, null)
134 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
135 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
136 element.dispatchEvent(mouseEvent)
138 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
139 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
140 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
142 # Simulate mouse scroll event by specific offsets given
143 # that mouse cursor is at specified position
144 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
146 .QueryInterface(Ci.nsIInterfaceRequestor)
147 .getInterface(Ci.nsIDOMWindowUtils)
149 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
150 windowUtils.sendWheelEvent(
151 pX, pY, # Window offset (x, y) in pixels
152 deltaX, deltaY, 0, # Deltas (x, y, z)
153 mode, # Mode (pixel, line, page)
155 0, 0, # Line or Page deltas (x, y)
159 # Write a string to the system clipboard
160 writeToClipboard = (text) ->
161 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1'].getService(Ci.nsIClipboardHelper)
162 clipboardHelper.copyString(text)
164 # Read the system clipboard
165 readFromClipboard = (window) ->
166 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
169 privacyContext = window
170 .QueryInterface(Ci.nsIInterfaceRequestor)
171 .getInterface(Ci.nsIWebNavigation)
172 .QueryInterface(Ci.nsILoadContext)
173 trans.init(privacyContext)
175 trans.addDataFlavor('text/unicode')
177 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
178 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
183 trans.getTransferData('text/unicode', str, strLength)
186 str = str.value.QueryInterface(Ci.nsISupportsString)
187 return str.data.substring(0, strLength.value / 2)
191 # Executes function `func` and mearues how much time it took
192 timeIt = (func, msg) ->
193 start = new Date().getTime()
195 end = new Date().getTime()
197 console.log(msg, end - start)
200 isBlacklisted = (str) ->
201 matchingRules = getMatchingBlacklistRules(str)
202 return (matchingRules.length != 0)
204 # Returns all rules in the blacklist that match the provided string
205 getMatchingBlacklistRules = (str) ->
206 return getBlacklist().filter((rule) -> /// ^#{ simpleWildcards(rule) }$ ///i.test(str))
209 return splitListString(getPref('black_list'))
211 setBlacklist = (blacklist) ->
212 setPref('black_list', blacklist.join(','))
214 updateBlacklist = ({ add, remove } = {}) ->
215 blacklist = getBlacklist()
218 blacklist.push(splitListString(add)...)
220 blacklist = blacklist.filter((rule) -> rule != '')
221 blacklist = removeDuplicates(blacklist)
224 for rule in splitListString(remove) when rule in blacklist
225 blacklist.splice(blacklist.indexOf(rule), 1)
227 setBlacklist(blacklist)
229 # Splits a comma/space separated list into an array
230 splitListString = (str) ->
231 return str.split(/\s*,[\s,]*/)
233 # Prepares a string to be used in a regexp, where "*" matches zero or more characters
234 # and "!" matches one character.
235 simpleWildcards = (string) ->
236 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
238 # Returns the first element that matches a pattern, favoring earlier patterns.
239 # The patterns are case insensitive `simpleWildcards`s and must match either in
240 # the beginning or at the end of a string. Moreover, a pattern does not match
241 # in the middle of words, so "previous" does not match "previously". If that is
242 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
243 # use `\b` word boundaries, because they don’t work well with non-English
244 # characters. Instead we match a space as word boundary. Therefore we normalize
245 # the whitespace and add spaces at the edges of the element text.
246 getBestPatternMatch = (patterns, attrs, elements) ->
248 for pattern in patterns
249 wildcarded = simpleWildcards(pattern)
250 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
252 # Helper function that matches a string against all the patterns.
254 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
256 if re.test(normalizedText)
260 # First search in attributes (favoring earlier attributes) as it's likely
261 # that they are more specific than text contexts.
263 for element in elements
264 if matches(element.getAttribute(attr))
267 # Then search in element contents.
268 for element in elements
269 if matches(element.textContent)
274 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
280 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
281 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
286 parseHTML = (document, html) ->
287 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
288 flags = parser.SanitizerAllowStyle
289 return parser.parseFragment(html, flags, false, null, document.documentElement)
291 createElement = (document, type, attributes = {}) ->
292 element = document.createElement(type)
294 for attribute, value of attributes
295 element.setAttribute(attribute, value)
297 if document instanceof HTMLDocument
298 element.classList.add('VimFxReset')
302 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
305 url = Cc['@mozilla.org/network/io-service;1']
306 .getService(Ci.nsIIOService)
307 .newURI(str, null, null)
308 .QueryInterface(Ci.nsIURL)
313 # Use Firefox services to search for a given string
314 browserSearchSubmission = (str) ->
315 ss = Cc['@mozilla.org/browser/search-service;1']
316 .getService(Ci.nsIBrowserSearchService)
318 engine = ss.currentEngine or ss.defaultEngine
319 return engine.getSubmission(str, null)
321 # Get hint characters, convert them to lower case, and filter duplicates
323 hintChars = getPref('hint_chars')
324 # Make sure that hint chars contain at least two characters
325 if !hintChars or hintChars.length < 2
328 return removeDuplicateCharacters(hintChars)
330 # Remove duplicate characters from string (case insensitive)
331 removeDuplicateCharacters = (str) ->
332 return removeDuplicates( str.toLowerCase().split('') ).join('')
334 # Return URI to some file in the extension packaged as resource
335 getResourceURI = do ->
336 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
337 return (path) -> return Services.io.newURI(path, null, baseURI)
339 # Escape string to render it usable in regular expressions
340 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
342 removeDuplicates = (array) ->
344 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
346 # Why isn’t `a[@href]` used, when `area[@href]` is? Some sites (such as
347 # StackExchange sites) leave out the `href` property and use the anchor as a
348 # JavaScript-powered button (instead of just using the `button` element).
349 ACTION_ELEMENT_TAGS = [
355 ACTION_ELEMENT_PROPERTIES = [
362 "contains(@class, 'button')"
363 "contains(@class, 'js-new-tweets-bar')"
366 EDITABLE_ELEMENT_TAGS = [
369 "input[not(@type='hidden' or @disabled)]"
372 EDITABLE_ELEMENT_PROPERTIES = [
373 "@contenteditable=''"
374 "translate(@contenteditable, 'TRUE', 'true')='true'"
377 FOCUSABLE_ELEMENT_TAGS = [
383 FOCUSABLE_ELEMENT_PROPERTIES = [
387 getMarkableElements = do ->
388 xpathify = (tags, properties)->
390 .concat("*[#{ properties.join(' or ') }]")
391 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
395 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
396 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
397 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
399 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
400 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
403 # The actual function that will return the desired elements
404 return (document, { type }) ->
405 return xpathQueryAll(document, xpaths[type])
407 xpathHelper = (node, query, resultType) ->
408 document = node.ownerDocument ? node
409 namespaceResolver = (namespace) ->
410 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
411 return document.evaluate(query, node, namespaceResolver, resultType, null)
413 xpathQuery = (node, query) ->
414 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
415 return result.singleNodeValue
417 xpathQueryAll = (node, query) ->
418 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
419 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
422 exports.Bucket = Bucket
423 exports.getEventWindow = getEventWindow
424 exports.getEventRootWindow = getEventRootWindow
425 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
426 exports.getRootWindow = getRootWindow
427 exports.getCurrentTabWindow = getCurrentTabWindow
429 exports.blurActiveElement = blurActiveElement
430 exports.isTextInputElement = isTextInputElement
431 exports.isElementEditable = isElementEditable
432 exports.isElementVisible = isElementVisible
433 exports.getSessionStore = getSessionStore
435 exports.loadCss = loadCss
437 exports.simulateClick = simulateClick
438 exports.simulateWheel = simulateWheel
439 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
440 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
441 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
442 exports.readFromClipboard = readFromClipboard
443 exports.writeToClipboard = writeToClipboard
444 exports.timeIt = timeIt
446 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
447 exports.isBlacklisted = isBlacklisted
448 exports.updateBlacklist = updateBlacklist
449 exports.splitListString = splitListString
450 exports.getBestPatternMatch = getBestPatternMatch
452 exports.getVersion = getVersion
453 exports.parseHTML = parseHTML
454 exports.createElement = createElement
455 exports.isURL = isURL
456 exports.browserSearchSubmission = browserSearchSubmission
457 exports.getHintChars = getHintChars
458 exports.removeDuplicates = removeDuplicates
459 exports.removeDuplicateCharacters = removeDuplicateCharacters
460 exports.getResourceURI = getResourceURI
461 exports.getMarkableElements = getMarkableElements
462 exports.xpathQuery = xpathQuery
463 exports.xpathQueryAll = xpathQueryAll
464 exports.ADDON_ID = ADDON_ID