1 { unload } = require 'unload'
6 { classes: Cc, interfaces: Ci, utils: Cu } = Components
8 HTMLInputElement = Ci.nsIDOMHTMLInputElement
9 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
10 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
11 XULDocument = Ci.nsIDOMXULDocument
12 XULElement = Ci.nsIDOMXULElement
13 HTMLDocument = Ci.nsIDOMHTMLDocument
14 HTMLElement = Ci.nsIDOMHTMLElement
15 Window = Ci.nsIDOMWindow
16 ChromeWindow = Ci.nsIDOMChromeWindow
18 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
21 constructor: (@idFunc, @newFunc) ->
26 if container = @bucket[id]
29 return @bucket[id] = @newFunc(obj)
32 delete @bucket[id] if id = @idFunc(obj)
34 # Returns the `window` from the currently active tab.
35 getCurrentTabWindow = (event) ->
36 return unless window = getEventWindow(event)
37 return unless rootWindow = getRootWindow(window)
38 return rootWindow.gBrowser.selectedTab.linkedBrowser.contentWindow
40 # Returns the window associated with the event
41 getEventWindow = (event) ->
42 if event.originalTarget instanceof Window
43 return event.originalTarget
45 doc = event.originalTarget.ownerDocument or event.originalTarget
46 if doc instanceof HTMLDocument or doc instanceof XULDocument
47 return doc.defaultView
49 getEventRootWindow = (event) ->
50 return unless window = getEventWindow(event)
51 return getRootWindow(window)
53 getEventTabBrowser = (event) ->
54 return unless rootWindow = getEventRootWindow(event)
55 return rootWindow.gBrowser
57 getRootWindow = (window) ->
59 .QueryInterface(Ci.nsIInterfaceRequestor)
60 .getInterface(Ci.nsIWebNavigation)
61 .QueryInterface(Ci.nsIDocShellTreeItem)
63 .QueryInterface(Ci.nsIInterfaceRequestor)
66 isTextInputElement = (element) ->
67 return element instanceof HTMLInputElement or \
68 element instanceof HTMLTextAreaElement
70 isElementEditable = (element) ->
71 return element.isContentEditable or \
72 element instanceof HTMLInputElement or \
73 element instanceof HTMLTextAreaElement or \
74 element instanceof HTMLSelectElement or \
75 element.getAttribute('g_editable') == 'true' or \
76 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
77 element.ownerDocument?.designMode?.toLowerCase() == 'on'
79 blurActiveElement = (window) ->
80 # Only blur editable elements, in order not to interfere with the browser too much. TODO: Is that
81 # really needed? What if a website has made more elements focusable -- shouldn't those also be
83 { activeElement } = window.document
84 if isElementEditable(activeElement)
87 getWindowId = (window) ->
89 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
90 .getInterface(Components.interfaces.nsIDOMWindowUtils)
94 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
96 # Function that returns a URI to the css file that's part of the extension
99 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
100 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
103 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
104 # The stylesheet is then appended to every document, but it can be overwritten by
107 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
110 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
111 # by users often make the hint markers unreadable, for example. Just using `!important` in the
113 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
114 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
117 sss.unregisterSheet(uri, sss.AGENT_SHEET)
119 # Simulate mouse click with full chain of event
120 # Copied from Vimium codebase
121 simulateClick = (element, modifiers = {}) ->
122 document = element.ownerDocument
123 window = document.defaultView
125 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
126 for event in eventSequence
127 mouseEvent = document.createEvent('MouseEvents')
128 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
129 modifiers.metaKey, 0, null)
130 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
131 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
132 element.dispatchEvent(mouseEvent)
134 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
135 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
136 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
138 # Simulate mouse scroll event by specific offsets given
139 # that mouse cursor is at specified position
140 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
142 .QueryInterface(Ci.nsIInterfaceRequestor)
143 .getInterface(Ci.nsIDOMWindowUtils)
145 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
146 windowUtils.sendWheelEvent(
147 pX, pY, # Window offset (x, y) in pixels
148 deltaX, deltaY, 0, # Deltas (x, y, z)
149 mode, # Mode (pixel, line, page)
151 0, 0, # Line or Page deltas (x, y)
155 # Write a string into system clipboard
156 writeToClipboard = (window, text) ->
157 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
160 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
163 privacyContext = window
164 .QueryInterface(Ci.nsIInterfaceRequestor)
165 .getInterface(Ci.nsIWebNavigation)
166 .QueryInterface(Ci.nsILoadContext)
167 trans.init(privacyContext)
169 trans.addDataFlavor('text/unicode')
170 trans.setTransferData('text/unicode', str, text.length * 2)
172 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
174 # Write a string into system clipboard
175 readFromClipboard = (window) ->
176 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
179 privacyContext = window
180 .QueryInterface(Ci.nsIInterfaceRequestor)
181 .getInterface(Ci.nsIWebNavigation)
182 .QueryInterface(Ci.nsILoadContext)
183 trans.init(privacyContext)
185 trans.addDataFlavor('text/unicode')
187 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
192 trans.getTransferData('text/unicode', str, strLength)
195 str = str.value.QueryInterface(Ci.nsISupportsString)
196 return str.data.substring(0, strLength.value / 2)
200 # Executes function `func` and mearues how much time it took
201 timeIt = (func, msg) ->
202 start = new Date().getTime()
204 end = new Date().getTime()
206 console.log(msg, end - start)
209 # Checks if the string provided matches one of the black list entries
210 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
211 isBlacklisted = (str, blackList) ->
212 for rule in blackList.split(/[\s,]+/)
213 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
214 if str.match ///^#{ rule }$///
219 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
225 addonId = getPref('addon_id')
226 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
227 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
232 parseHTML = (document, html) ->
233 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
234 flags = parser.SanitizerAllowStyle
235 return parser.parseFragment(html, flags, false, null, document.documentElement)
237 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
240 url = Cc['@mozilla.org/network/io-service;1']
241 .getService(Ci.nsIIOService)
242 .newURI(str, null, null)
243 .QueryInterface(Ci.nsIURL)
248 # Use Firefox services to search for a given string
249 browserSearchSubmission = (str) ->
250 ss = Cc['@mozilla.org/browser/search-service;1']
251 .getService(Ci.nsIBrowserSearchService)
253 engine = ss.currentEngine or ss.defaultEngine
254 return engine.getSubmission(str, null)
256 # Get hint characters, convert them to lower case and fall back
257 # to default hint characters if there are less than 3 chars
259 # Remove duplicate characters from string (case insensitive)
260 removeDuplicateCharacters = (str) ->
265 .filter((char) -> if seen[char] then false else (seen[char] = true))
269 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
270 if hintChars.length < 2
271 hintChars = getDefaultPref('hint_chars')
275 # Return URI to some file in the extension packaged as resource
276 getResourceURI = do ->
277 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
278 return (path) -> return Services.io.newURI(path, null, baseURI)
280 exports.Bucket = Bucket
281 exports.getCurrentTabWindow = getCurrentTabWindow
282 exports.getEventWindow = getEventWindow
283 exports.getEventRootWindow = getEventRootWindow
284 exports.getEventTabBrowser = getEventTabBrowser
286 exports.getWindowId = getWindowId
287 exports.getRootWindow = getRootWindow
288 exports.isTextInputElement = isTextInputElement
289 exports.isElementEditable = isElementEditable
290 exports.blurActiveElement = blurActiveElement
291 exports.getSessionStore = getSessionStore
293 exports.loadCss = loadCss
295 exports.simulateClick = simulateClick
296 exports.simulateWheel = simulateWheel
297 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
298 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
299 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
300 exports.readFromClipboard = readFromClipboard
301 exports.writeToClipboard = writeToClipboard
302 exports.timeIt = timeIt
303 exports.isBlacklisted = isBlacklisted
304 exports.getVersion = getVersion
305 exports.parseHTML = parseHTML
306 exports.isURL = isURL
307 exports.browserSearchSubmission = browserSearchSubmission
308 exports.getHintChars = getHintChars
309 exports.getResourceURI = getResourceURI