1 { unloader } = require 'unloader'
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 to interfere with the browser as
66 { activeElement } = window.document
67 if activeElement and isElementEditable(activeElement)
70 isTextInputElement = (element) ->
71 return element instanceof HTMLInputElement or
72 element instanceof HTMLTextAreaElement
74 isElementEditable = (element) ->
75 return element.isContentEditable or
76 element instanceof HTMLInputElement or
77 element instanceof HTMLTextAreaElement or
78 element instanceof HTMLSelectElement or
79 element instanceof XULMenuListElement or
80 element.isContentEditable or
81 isElementGoogleEditable(element)
83 isElementGoogleEditable = (element) ->
84 # `g_editable` is a non-standard attribute commonly used by Google.
85 return element.getAttribute?('g_editable') == 'true' or
86 (element instanceof HTMLElement and
87 element.ownerDocument.body?.getAttribute('g_editable') == 'true')
89 isElementVisible = (element) ->
90 document = element.ownerDocument
91 window = document.defaultView
92 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)
101 sss = Cc['@mozilla.org/content/style-sheet-service;1']
102 .getService(Ci.nsIStyleSheetService)
104 uri = getResourceURI("resources/#{ name }.css")
105 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
106 # website themes installed by users often make the hint markers unreadable,
107 # for example. Just using `!important` in the CSS is not enough.
108 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
109 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
112 sss.unregisterSheet(uri, sss.AGENT_SHEET)
115 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
116 # memory. This approach is better than for example setting `event.simulated =
117 # true`, since that tells the sites that the click was simulated, and allows
119 simulated_events = new WeakMap()
121 # Simulate mouse click with a full chain of events. Copied from Vimium
123 simulateClick = (element, modifiers = {}) ->
124 document = element.ownerDocument
125 window = document.defaultView
127 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
128 for event in eventSequence
129 mouseEvent = document.createEvent('MouseEvents')
130 mouseEvent.initMouseEvent(
131 event, true, true, window, 1, 0, 0, 0, 0,
132 modifiers.ctrlKey, false, false, modifiers.metaKey,
135 simulated_events.set(mouseEvent, true)
136 # Debugging note: Firefox will not execute the element's default action if
137 # we dispatch this click event, but Webkit will. Dispatching a click on an
138 # input box does not seem to focus it; we do that separately.
139 element.dispatchEvent(mouseEvent)
141 isEventSimulated = (event) ->
142 return simulated_events.has(event)
144 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
145 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
146 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
148 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
149 # specified position.
150 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
152 .QueryInterface(Ci.nsIInterfaceRequestor)
153 .getInterface(Ci.nsIDOMWindowUtils)
155 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
156 windowUtils.sendWheelEvent(
157 pX, pY, # Window offset (x, y) in pixels.
158 deltaX, deltaY, 0, # Deltas (x, y, z).
159 mode, # Mode (pixel, line, page).
161 0, 0, # Line or Page deltas (x, y).
165 # Write a string to the system clipboard.
166 writeToClipboard = (text) ->
167 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
168 .getService(Ci.nsIClipboardHelper)
169 clipboardHelper.copyString(text)
171 # Read the system clipboard.
172 readFromClipboard = (window) ->
173 trans = Cc['@mozilla.org/widget/transferable;1']
174 .createInstance(Ci.nsITransferable)
177 privacyContext = window
178 .QueryInterface(Ci.nsIInterfaceRequestor)
179 .getInterface(Ci.nsIWebNavigation)
180 .QueryInterface(Ci.nsILoadContext)
181 trans.init(privacyContext)
183 trans.addDataFlavor('text/unicode')
185 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
186 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
191 trans.getTransferData('text/unicode', str, strLength)
194 str = str.value.QueryInterface(Ci.nsISupportsString)
195 return str.data.substring(0, strLength.value / 2)
199 # Executes function `func` and mearues how much time it took.
200 timeIt = (func, name) ->
203 console.timeEnd(name)
206 isBlacklisted = (str) ->
207 matchingRules = getMatchingBlacklistRules(str)
208 return (matchingRules.length != 0)
210 # Returns all rules in the blacklist that match the provided string.
211 getMatchingBlacklistRules = (str) ->
212 return getBlacklist().filter((rule) ->
213 /// ^#{ simpleWildcards(rule) }$ ///i.test(str)
217 return splitListString(getPref('black_list'))
219 setBlacklist = (blacklist) ->
220 setPref('black_list', blacklist.join(','))
222 updateBlacklist = ({ add, remove } = {}) ->
223 blacklist = getBlacklist()
226 blacklist.push(splitListString(add)...)
228 blacklist = blacklist.filter((rule) -> rule != '')
229 blacklist = removeDuplicates(blacklist)
232 for rule in splitListString(remove) when rule in blacklist
233 blacklist.splice(blacklist.indexOf(rule), 1)
235 setBlacklist(blacklist)
237 # Splits a comma/space separated list into an array.
238 splitListString = (str) ->
239 return str.split(/\s*,[\s,]*/)
241 # Prepares a string to be used in a regexp, where "*" matches zero or more
242 # characters and "!" matches one character.
243 simpleWildcards = (string) ->
244 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
246 # Returns the first element that matches a pattern, favoring earlier patterns.
247 # The patterns are case insensitive `simpleWildcards`s and must match either in
248 # the beginning or at the end of a string. Moreover, a pattern does not match
249 # in the middle of words, so "previous" does not match "previously". If that is
250 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
251 # use `\b` word boundaries, because they don’t work well with non-English
252 # characters. Instead we match a space as word boundary. Therefore we normalize
253 # the whitespace and add spaces at the edges of the element text.
254 getBestPatternMatch = (patterns, attrs, elements) ->
256 for pattern in patterns
257 wildcarded = simpleWildcards(pattern)
258 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
260 # Helper function that matches a string against all the patterns.
262 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
264 if re.test(normalizedText)
268 # First search in attributes (favoring earlier attributes) as it's likely
269 # that they are more specific than text contexts.
271 for element in elements
272 if matches(element.getAttribute(attr))
275 # Then search in element contents.
276 for element in elements
277 if matches(element.textContent)
282 # Get VimFx verion. AddonManager only provides async API to access addon data,
283 # so it's a bit tricky...
288 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
289 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
294 parseHTML = (document, html) ->
295 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
296 flags = parser.SanitizerAllowStyle
297 return parser.parseFragment(html, flags, false, null,
298 document.documentElement)
300 createElement = (document, type, attributes = {}) ->
301 element = document.createElement(type)
303 for attribute, value of attributes
304 element.setAttribute(attribute, value)
306 if document instanceof HTMLDocument
307 element.classList.add('VimFxReset')
313 url = Cc['@mozilla.org/network/io-service;1']
314 .getService(Ci.nsIIOService)
315 .newURI(str, null, null)
316 .QueryInterface(Ci.nsIURL)
321 # Use Firefox services to search for a given string.
322 browserSearchSubmission = (str) ->
323 ss = Cc['@mozilla.org/browser/search-service;1']
324 .getService(Ci.nsIBrowserSearchService)
326 engine = ss.currentEngine or ss.defaultEngine
327 return engine.getSubmission(str, null)
329 # Get hint characters, convert them to lower case, and filter duplicates.
331 hintChars = getPref('hint_chars')
332 # Make sure that hint chars contain at least two characters.
333 if not hintChars or hintChars.length < 2
336 return removeDuplicateCharacters(hintChars)
338 # Remove duplicate characters from string (case insensitive).
339 removeDuplicateCharacters = (str) ->
340 return removeDuplicates( str.toLowerCase().split('') ).join('')
342 # Return URI to some file in the extension packaged as resource.
343 getResourceURI = do ->
344 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
345 return (path) -> return Services.io.newURI(path, null, baseURI)
347 # Escape a string to render it usable in regular expressions.
348 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
350 removeDuplicates = (array) ->
351 return `[...new Set(array)]`
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 = [
360 # When viewing an image directly, and it is larger than the viewport,
361 # clicking it toggles zoom.
362 "img[contains(@class, 'decoded') and
363 (contains(@class, 'overflowing') or
364 contains(@class, 'shrinkToFit'))]"
367 ACTION_ELEMENT_PROPERTIES = [
374 "contains(@class, 'button')"
375 "contains(@class, 'js-new-tweets-bar')"
378 EDITABLE_ELEMENT_TAGS = [
381 "input[not(@type='hidden' or @disabled)]"
384 EDITABLE_ELEMENT_PROPERTIES = [
385 "@contenteditable=''"
386 "translate(@contenteditable, 'TRUE', 'true')='true'"
389 FOCUSABLE_ELEMENT_TAGS = [
395 FOCUSABLE_ELEMENT_PROPERTIES = [
399 getMarkableElements = do ->
400 xpathify = (tags, properties)->
402 .concat("*[#{ properties.join(' or ') }]")
403 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
407 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
408 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
409 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
411 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
412 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
415 # The actual function that will return the desired elements.
416 return (document, { type }) ->
417 return xpathQueryAll(document, xpaths[type])
419 xpathHelper = (node, query, resultType) ->
420 document = node.ownerDocument ? node
421 namespaceResolver = (namespace) ->
422 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
423 return document.evaluate(query, node, namespaceResolver, resultType, null)
425 xpathQuery = (node, query) ->
426 result = xpathHelper(node, query, XPathResult.FIRST_ORDERED_NODE_TYPE)
427 return result.singleNodeValue
429 xpathQueryAll = (node, query) ->
430 result = xpathHelper(node, query, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE)
431 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
434 exports.Bucket = Bucket
435 exports.getEventWindow = getEventWindow
436 exports.getEventRootWindow = getEventRootWindow
437 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
438 exports.getRootWindow = getRootWindow
439 exports.getCurrentTabWindow = getCurrentTabWindow
441 exports.blurActiveElement = blurActiveElement
442 exports.isTextInputElement = isTextInputElement
443 exports.isElementEditable = isElementEditable
444 exports.isElementVisible = isElementVisible
445 exports.getSessionStore = getSessionStore
447 exports.loadCss = loadCss
449 exports.simulateClick = simulateClick
450 exports.isEventSimulated = isEventSimulated
451 exports.simulateWheel = simulateWheel
452 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
453 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
454 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
455 exports.readFromClipboard = readFromClipboard
456 exports.writeToClipboard = writeToClipboard
457 exports.timeIt = timeIt
459 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
460 exports.isBlacklisted = isBlacklisted
461 exports.updateBlacklist = updateBlacklist
462 exports.splitListString = splitListString
463 exports.getBestPatternMatch = getBestPatternMatch
465 exports.getVersion = getVersion
466 exports.parseHTML = parseHTML
467 exports.createElement = createElement
468 exports.isURL = isURL
469 exports.browserSearchSubmission = browserSearchSubmission
470 exports.getHintChars = getHintChars
471 exports.removeDuplicates = removeDuplicates
472 exports.removeDuplicateCharacters = removeDuplicateCharacters
473 exports.getResourceURI = getResourceURI
474 exports.getMarkableElements = getMarkableElements
475 exports.xpathQuery = xpathQuery
476 exports.xpathQueryAll = xpathQueryAll
477 exports.ADDON_ID = ADDON_ID