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.ownerDocument?.designMode?.toLowerCase() == 'on' or \
83 element.getAttribute?('g_editable') == 'true' or \
84 element.getAttribute?('contenteditable')?.toLowerCase() == 'true' or \
85 element.ownerDocument?.designMode?.toLowerCase() == 'on'
87 isElementVisible = (element) ->
88 document = element.ownerDocument
89 window = document.defaultView
90 if computedStyle = window.getComputedStyle(element, null)
91 return computedStyle.getPropertyValue('visibility') == 'visible' and \
92 computedStyle.getPropertyValue('display') != 'none' and \
93 computedStyle.getPropertyValue('opacity') != '0'
95 getWindowId = (window) ->
97 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
98 .getInterface(Components.interfaces.nsIDOMWindowUtils)
102 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
104 # Function that returns a URI to the css file that's part of the extension
107 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
108 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
111 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
112 # The stylesheet is then appended to every document, but it can be overwritten by
115 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
118 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
119 # by users often make the hint markers unreadable, for example. Just using `!important` in the
121 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
122 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
125 sss.unregisterSheet(uri, sss.AGENT_SHEET)
127 # Simulate mouse click with full chain of event
128 # Copied from Vimium codebase
129 simulateClick = (element, modifiers = {}) ->
130 document = element.ownerDocument
131 window = document.defaultView
133 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
134 for event in eventSequence
135 mouseEvent = document.createEvent('MouseEvents')
136 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
137 modifiers.metaKey, 0, null)
138 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
139 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
140 element.dispatchEvent(mouseEvent)
142 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
143 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
144 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
146 # Simulate mouse scroll event by specific offsets given
147 # that mouse cursor is at specified position
148 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
150 .QueryInterface(Ci.nsIInterfaceRequestor)
151 .getInterface(Ci.nsIDOMWindowUtils)
153 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
154 windowUtils.sendWheelEvent(
155 pX, pY, # Window offset (x, y) in pixels
156 deltaX, deltaY, 0, # Deltas (x, y, z)
157 mode, # Mode (pixel, line, page)
159 0, 0, # Line or Page deltas (x, y)
163 # Write a string to the system clipboard
164 writeToClipboard = (text) ->
165 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1'].getService(Ci.nsIClipboardHelper)
166 clipboardHelper.copyString(text)
168 # Read the system clipboard
169 readFromClipboard = (window) ->
170 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
173 privacyContext = window
174 .QueryInterface(Ci.nsIInterfaceRequestor)
175 .getInterface(Ci.nsIWebNavigation)
176 .QueryInterface(Ci.nsILoadContext)
177 trans.init(privacyContext)
179 trans.addDataFlavor('text/unicode')
181 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
182 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
187 trans.getTransferData('text/unicode', str, strLength)
190 str = str.value.QueryInterface(Ci.nsISupportsString)
191 return str.data.substring(0, strLength.value / 2)
195 # Executes function `func` and mearues how much time it took
196 timeIt = (func, msg) ->
197 start = new Date().getTime()
199 end = new Date().getTime()
201 console.log(msg, end - start)
204 isBlacklisted = (str) ->
205 matchingRules = getMatchingBlacklistRules(str)
206 return (matchingRules.length != 0)
208 # Returns all rules in the blacklist that match the provided string
209 getMatchingBlacklistRules = (str) ->
210 return getBlacklist().filter((rule) -> /// ^#{ simpleWildcards(rule) }$ ///i.test(str))
213 return splitListString(getPref('black_list'))
215 setBlacklist = (blacklist) ->
216 setPref('black_list', blacklist.join(','))
218 updateBlacklist = ({ add, remove } = {}) ->
219 blacklist = getBlacklist()
222 blacklist.push(splitListString(add)...)
224 blacklist = blacklist.filter((rule) -> rule != '')
225 blacklist = removeDuplicates(blacklist)
228 for rule in splitListString(remove) when rule in blacklist
229 blacklist.splice(blacklist.indexOf(rule), 1)
231 setBlacklist(blacklist)
233 # Splits a comma/space separated list into an array
234 splitListString = (str) ->
235 return str.split(/\s*,[\s,]*/)
237 # Prepares a string to be used in a regexp, where "*" matches zero or more characters
238 # and "!" matches one character.
239 simpleWildcards = (string) ->
240 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
242 # Returns the first element that matches a pattern, favoring earlier patterns.
243 # The patterns are `simpleWildcards`s and must match either in the beginning or
244 # at the end of the text of the element. Moreover, a pattern does not match in
245 # the middle of words, so "previous" does not match "previously". If that is
246 # desired, a pattern such as "previous*" can be used instead.
247 # Note: We cannot use `\b` word boundaries, because they don’t work well with
248 # non-English characters. Instead we match a space as word boundary. Therefore
249 # we normalize the whitespace and add spaces at the edges of the element text.
250 getBestPatternMatch = (patterns, elements) ->
251 for pattern in patterns
252 wildcarded = simpleWildcards(pattern)
253 regexp = /// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i
254 for element in elements
255 text = " #{ element.textContent } ".replace(/\s+/g, ' ')
261 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
267 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
268 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
273 parseHTML = (document, html) ->
274 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
275 flags = parser.SanitizerAllowStyle
276 return parser.parseFragment(html, flags, false, null, document.documentElement)
278 createElement = (document, type, attributes = {}) ->
279 element = document.createElement(type)
281 for attribute, value of attributes
282 element.setAttribute(attribute, value)
284 if document instanceof HTMLDocument
285 element.classList.add('VimFxReset')
289 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
292 url = Cc['@mozilla.org/network/io-service;1']
293 .getService(Ci.nsIIOService)
294 .newURI(str, null, null)
295 .QueryInterface(Ci.nsIURL)
300 # Use Firefox services to search for a given string
301 browserSearchSubmission = (str) ->
302 ss = Cc['@mozilla.org/browser/search-service;1']
303 .getService(Ci.nsIBrowserSearchService)
305 engine = ss.currentEngine or ss.defaultEngine
306 return engine.getSubmission(str, null)
308 # Get hint characters, convert them to lower case, and filter duplicates
310 hintChars = getPref('hint_chars')
311 # Make sure that hint chars contain at least two characters
312 if !hintChars or hintChars.length < 2
315 return removeDuplicateCharacters(hintChars)
317 # Remove duplicate characters from string (case insensitive)
318 removeDuplicateCharacters = (str) ->
319 return removeDuplicates( str.toLowerCase().split('') ).join('')
321 # Return URI to some file in the extension packaged as resource
322 getResourceURI = do ->
323 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
324 return (path) -> return Services.io.newURI(path, null, baseURI)
326 # Escape string to render it usable in regular expressions
327 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
329 removeDuplicates = (array) ->
331 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
333 ACTION_ELEMENT_TAGS = [
339 ACTION_ELEMENT_PROPERTIES = [
346 "contains(@class, 'button')"
347 "contains(@class, 'js-new-tweets-bar')"
350 EDITABLE_ELEMENT_TAGS = [
353 "input[not(@type='hidden' or @disabled)]"
356 EDITABLE_ELEMENT_PROPERTIES = [
357 "@contenteditable=''"
358 "translate(@contenteditable, 'TRUE', 'true')='true'"
361 FOCUSABLE_ELEMENT_TAGS = [
367 FOCUSABLE_ELEMENT_PROPERTIES = [
371 getMarkableElements = do ->
372 xpathify = (tags, properties)->
374 .concat("*[#{ properties.join(' or ') }]")
375 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
379 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
380 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
381 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
383 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
384 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
387 # The actual function that will return the desired elements
388 return (document, { type }) ->
389 return xpathQueryAll(document, xpaths[type])
391 xpathHelper = (node, query, resultType) ->
392 document = node.ownerDocument ? node
393 namespaceResolver = (namespace) ->
394 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
395 return document.evaluate(query, node, namespaceResolver, resultType, null)
397 xpathQuery = (node, query) ->
398 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
399 return result.singleNodeValue
401 xpathQueryAll = (node, query) ->
402 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
403 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
406 exports.Bucket = Bucket
407 exports.getEventWindow = getEventWindow
408 exports.getEventRootWindow = getEventRootWindow
409 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
410 exports.getRootWindow = getRootWindow
411 exports.getCurrentTabWindow = getCurrentTabWindow
413 exports.getWindowId = getWindowId
414 exports.blurActiveElement = blurActiveElement
415 exports.isTextInputElement = isTextInputElement
416 exports.isElementEditable = isElementEditable
417 exports.isElementVisible = isElementVisible
418 exports.getSessionStore = getSessionStore
420 exports.loadCss = loadCss
422 exports.simulateClick = simulateClick
423 exports.simulateWheel = simulateWheel
424 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
425 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
426 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
427 exports.readFromClipboard = readFromClipboard
428 exports.writeToClipboard = writeToClipboard
429 exports.timeIt = timeIt
431 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
432 exports.isBlacklisted = isBlacklisted
433 exports.updateBlacklist = updateBlacklist
434 exports.splitListString = splitListString
435 exports.getBestPatternMatch = getBestPatternMatch
437 exports.getVersion = getVersion
438 exports.parseHTML = parseHTML
439 exports.createElement = createElement
440 exports.isURL = isURL
441 exports.browserSearchSubmission = browserSearchSubmission
442 exports.getHintChars = getHintChars
443 exports.removeDuplicates = removeDuplicates
444 exports.removeDuplicateCharacters = removeDuplicateCharacters
445 exports.getResourceURI = getResourceURI
446 exports.getMarkableElements = getMarkableElements
447 exports.xpathQuery = xpathQuery
448 exports.xpathQueryAll = xpathQueryAll
449 exports.ADDON_ID = ADDON_ID