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
22 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
25 constructor: (@idFunc, @newFunc) ->
30 if container = @bucket[id]
33 return @bucket[id] = @newFunc(obj)
36 delete @bucket[id] if id = @idFunc(obj)
38 getEventWindow = (event) ->
39 if event.originalTarget instanceof Window
40 return event.originalTarget
42 doc = event.originalTarget.ownerDocument or event.originalTarget
43 if doc instanceof HTMLDocument or doc instanceof XULDocument
44 return doc.defaultView
46 getEventRootWindow = (event) ->
47 return unless window = getEventWindow(event)
48 return getRootWindow(window)
50 getEventCurrentTabWindow = (event) ->
51 return unless rootWindow = getEventRootWindow(event)
52 return getCurrentTabWindow(rootWindow)
54 getRootWindow = (window) ->
56 .QueryInterface(Ci.nsIInterfaceRequestor)
57 .getInterface(Ci.nsIWebNavigation)
58 .QueryInterface(Ci.nsIDocShellTreeItem)
60 .QueryInterface(Ci.nsIInterfaceRequestor)
63 getCurrentTabWindow = (window) ->
64 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
66 blurActiveElement = (window) ->
67 # Only blur editable elements, in order not to interfere with the browser too much. TODO: Is that
68 # really needed? What if a website has made more elements focusable -- shouldn't those also be
70 { activeElement } = window.document
71 if isElementEditable(activeElement)
74 isTextInputElement = (element) ->
75 return element instanceof HTMLInputElement or \
76 element instanceof HTMLTextAreaElement
78 isElementEditable = (element) ->
79 return element.isContentEditable or \
80 element instanceof HTMLInputElement or \
81 element instanceof HTMLTextAreaElement or \
82 element instanceof HTMLSelectElement or \
83 element instanceof XULMenuListElement or \
84 element.getAttribute('g_editable') == 'true' or \
85 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
86 element.ownerDocument?.designMode?.toLowerCase() == 'on'
88 getWindowId = (window) ->
90 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
91 .getInterface(Components.interfaces.nsIDOMWindowUtils)
95 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
97 # Function that returns a URI to the css file that's part of the extension
100 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
101 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
104 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
105 # The stylesheet is then appended to every document, but it can be overwritten by
108 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
111 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
112 # by users often make the hint markers unreadable, for example. Just using `!important` in the
114 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
115 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
118 sss.unregisterSheet(uri, sss.AGENT_SHEET)
120 # Simulate mouse click with full chain of event
121 # Copied from Vimium codebase
122 simulateClick = (element, modifiers = {}) ->
123 document = element.ownerDocument
124 window = document.defaultView
126 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
127 for event in eventSequence
128 mouseEvent = document.createEvent('MouseEvents')
129 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
130 modifiers.metaKey, 0, null)
131 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
132 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
133 element.dispatchEvent(mouseEvent)
135 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
136 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
137 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
139 # Simulate mouse scroll event by specific offsets given
140 # that mouse cursor is at specified position
141 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
143 .QueryInterface(Ci.nsIInterfaceRequestor)
144 .getInterface(Ci.nsIDOMWindowUtils)
146 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
147 windowUtils.sendWheelEvent(
148 pX, pY, # Window offset (x, y) in pixels
149 deltaX, deltaY, 0, # Deltas (x, y, z)
150 mode, # Mode (pixel, line, page)
152 0, 0, # Line or Page deltas (x, y)
156 # Write a string into system clipboard
157 writeToClipboard = (window, text) ->
158 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
161 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
164 privacyContext = window
165 .QueryInterface(Ci.nsIInterfaceRequestor)
166 .getInterface(Ci.nsIWebNavigation)
167 .QueryInterface(Ci.nsILoadContext)
168 trans.init(privacyContext)
170 trans.addDataFlavor('text/unicode')
171 trans.setTransferData('text/unicode', str, text.length * 2)
173 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
175 # Write a string into system clipboard
176 readFromClipboard = (window) ->
177 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
180 privacyContext = window
181 .QueryInterface(Ci.nsIInterfaceRequestor)
182 .getInterface(Ci.nsIWebNavigation)
183 .QueryInterface(Ci.nsILoadContext)
184 trans.init(privacyContext)
186 trans.addDataFlavor('text/unicode')
188 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
193 trans.getTransferData('text/unicode', str, strLength)
196 str = str.value.QueryInterface(Ci.nsISupportsString)
197 return str.data.substring(0, strLength.value / 2)
201 # Executes function `func` and mearues how much time it took
202 timeIt = (func, msg) ->
203 start = new Date().getTime()
205 end = new Date().getTime()
207 console.log(msg, end - start)
210 isBlacklisted = (str) ->
211 matchingRules = getMatchingBlacklistRules(str)
212 return (matchingRules.length != 0)
214 # Returns all rules in the blacklist that match the provided string
215 getMatchingBlacklistRules = (str) ->
217 for rule in getBlacklist()
219 regexifiedRule = regexpEscape(rule).replace(/\\\*/g, '.*').replace(/!/g, '.')
220 if str.match(///^#{ regexifiedRule }$///)
221 matchingRules.push(rule)
226 return splitBlacklistString(getPref('black_list'))
228 setBlacklist = (blacklist) ->
229 setPref('black_list', blacklist.join(', '))
231 splitBlacklistString = (str) ->
232 # Comma/space separated list
233 return str.split(/[\s,]+/)
235 updateBlacklist = ({ add, remove} = {}) ->
236 blacklist = getBlacklist()
239 blacklist.push(splitBlacklistString(add)...)
241 blacklist = blacklist.filter((rule) -> rule != '')
242 blacklist = removeDuplicates(blacklist)
245 for rule in splitBlacklistString(remove) when rule in blacklist
246 blacklist.splice(blacklist.indexOf(rule), 1)
248 setBlacklist(blacklist)
250 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
256 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
257 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
262 parseHTML = (document, html) ->
263 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
264 flags = parser.SanitizerAllowStyle
265 return parser.parseFragment(html, flags, false, null, document.documentElement)
267 createElement = (document, type, attributes = {}) ->
268 element = document.createElement(type)
270 for attribute, value of attributes
271 element.setAttribute(attribute, value)
273 if document instanceof HTMLDocument
274 element.classList.add('VimFxReset')
278 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
281 url = Cc['@mozilla.org/network/io-service;1']
282 .getService(Ci.nsIIOService)
283 .newURI(str, null, null)
284 .QueryInterface(Ci.nsIURL)
289 # Use Firefox services to search for a given string
290 browserSearchSubmission = (str) ->
291 ss = Cc['@mozilla.org/browser/search-service;1']
292 .getService(Ci.nsIBrowserSearchService)
294 engine = ss.currentEngine or ss.defaultEngine
295 return engine.getSubmission(str, null)
297 # Get hint characters, convert them to lower case, and filter duplicates
299 hintChars = getPref('hint_chars')
300 # Make sure that hint chars contain at least two characters
301 if hintChars.length < 2
304 return removeDuplicateCharacters(hintChars)
306 # Remove duplicate characters from string (case insensitive)
307 removeDuplicateCharacters = (str) ->
308 return removeDuplicates( str.toLowerCase().split('') ).join('')
310 # Return URI to some file in the extension packaged as resource
311 getResourceURI = do ->
312 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
313 return (path) -> return Services.io.newURI(path, null, baseURI)
315 # Escape string to render it usable in regular expressions
316 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
318 removeDuplicates = (array) ->
320 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
322 # Returns elements that qualify as links
323 # Generates and memoizes an XPath query internally
324 getDomElements = (elements) ->
325 reduce = (m, rule) -> m.concat(["//#{ rule }", "//xhtml:#{ rule }"])
326 xpath = elements.reduce(reduce, []).join(' | ')
328 namespaceResolver = (namespace) ->
329 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
331 # The actual function that will return the desired elements
332 return (document, resultType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) ->
333 return document.evaluate(xpath, document.documentElement, namespaceResolver, resultType, null)
335 exports.Bucket = Bucket
336 exports.getEventWindow = getEventWindow
337 exports.getEventRootWindow = getEventRootWindow
338 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
339 exports.getRootWindow = getRootWindow
340 exports.getCurrentTabWindow = getCurrentTabWindow
342 exports.getWindowId = getWindowId
343 exports.blurActiveElement = blurActiveElement
344 exports.isTextInputElement = isTextInputElement
345 exports.isElementEditable = isElementEditable
346 exports.getSessionStore = getSessionStore
348 exports.loadCss = loadCss
350 exports.simulateClick = simulateClick
351 exports.simulateWheel = simulateWheel
352 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
353 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
354 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
355 exports.readFromClipboard = readFromClipboard
356 exports.writeToClipboard = writeToClipboard
357 exports.timeIt = timeIt
359 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
360 exports.isBlacklisted = isBlacklisted
361 exports.updateBlacklist = updateBlacklist
363 exports.getVersion = getVersion
364 exports.parseHTML = parseHTML
365 exports.createElement = createElement
366 exports.isURL = isURL
367 exports.browserSearchSubmission = browserSearchSubmission
368 exports.getHintChars = getHintChars
369 exports.removeDuplicateCharacters = removeDuplicateCharacters
370 exports.getResourceURI = getResourceURI
371 exports.getDomElements = getDomElements
372 exports.ADDON_ID = ADDON_ID