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 getWindowId = (window) ->
81 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
82 .getInterface(Components.interfaces.nsIDOMWindowUtils)
86 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
88 # Function that returns a URI to the css file that's part of the extension
91 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
92 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
95 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
96 # The stylesheet is then appended to every document, but it can be overwritten by
99 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
102 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
103 # by users often make the hint markers unreadable, for example. Just using `!important` in the
105 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
106 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
109 sss.unregisterSheet(uri, sss.AGENT_SHEET)
111 # Simulate mouse click with full chain of event
112 # Copied from Vimium codebase
113 simulateClick = (element, modifiers = {}) ->
114 document = element.ownerDocument
115 window = document.defaultView
117 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
118 for event in eventSequence
119 mouseEvent = document.createEvent('MouseEvents')
120 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
121 modifiers.metaKey, 0, null)
122 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
123 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
124 element.dispatchEvent(mouseEvent)
126 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
127 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
128 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
130 # Simulate mouse scroll event by specific offsets given
131 # that mouse cursor is at specified position
132 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
134 .QueryInterface(Ci.nsIInterfaceRequestor)
135 .getInterface(Ci.nsIDOMWindowUtils)
137 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
138 windowUtils.sendWheelEvent(
139 pX, pY, # Window offset (x, y) in pixels
140 deltaX, deltaY, 0, # Deltas (x, y, z)
141 mode, # Mode (pixel, line, page)
143 0, 0, # Line or Page deltas (x, y)
147 # Write a string into system clipboard
148 writeToClipboard = (window, text) ->
149 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
152 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
155 privacyContext = window
156 .QueryInterface(Ci.nsIInterfaceRequestor)
157 .getInterface(Ci.nsIWebNavigation)
158 .QueryInterface(Ci.nsILoadContext)
159 trans.init(privacyContext)
161 trans.addDataFlavor('text/unicode')
162 trans.setTransferData('text/unicode', str, text.length * 2)
164 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
166 # Write a string into system clipboard
167 readFromClipboard = (window) ->
168 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
171 privacyContext = window
172 .QueryInterface(Ci.nsIInterfaceRequestor)
173 .getInterface(Ci.nsIWebNavigation)
174 .QueryInterface(Ci.nsILoadContext)
175 trans.init(privacyContext)
177 trans.addDataFlavor('text/unicode')
179 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
184 trans.getTransferData('text/unicode', str, strLength)
187 str = str.value.QueryInterface(Ci.nsISupportsString)
188 return str.data.substring(0, strLength.value / 2)
192 # Executes function `func` and mearues how much time it took
193 timeIt = (func, msg) ->
194 start = new Date().getTime()
196 end = new Date().getTime()
198 console.log(msg, end - start)
201 # Checks if the string provided matches one of the black list entries
202 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
203 isBlacklisted = (str, blackList) ->
204 for rule in blackList.split(/[\s,]+/)
205 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
206 if str.match ///^#{ rule }$///
211 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
217 addonId = getPref('addon_id')
218 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
219 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
224 parseHTML = (document, html) ->
225 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
226 flags = parser.SanitizerAllowStyle
227 return parser.parseFragment(html, flags, false, null, document.documentElement)
229 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
232 url = Cc['@mozilla.org/network/io-service;1']
233 .getService(Ci.nsIIOService)
234 .newURI(str, null, null)
235 .QueryInterface(Ci.nsIURL)
240 # Use Firefox services to search for a given string
241 browserSearchSubmission = (str) ->
242 ss = Cc['@mozilla.org/browser/search-service;1']
243 .getService(Ci.nsIBrowserSearchService)
245 engine = ss.currentEngine or ss.defaultEngine
246 return engine.getSubmission(str, null)
248 # Get hint characters, convert them to lower case and fall back
249 # to default hint characters if there are less than 3 chars
251 # Remove duplicate characters from string (case insensitive)
252 removeDuplicateCharacters = (str) ->
257 .filter((char) -> if seen[char] then false else (seen[char] = true))
261 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
262 if hintChars.length < 2
263 hintChars = getDefaultPref('hint_chars')
267 # Return URI to some file in the extension packaged as resource
268 getResourceURI = do ->
269 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
270 return (path) -> return Services.io.newURI(path, null, baseURI)
272 exports.Bucket = Bucket
273 exports.getCurrentTabWindow = getCurrentTabWindow
274 exports.getEventWindow = getEventWindow
275 exports.getEventRootWindow = getEventRootWindow
276 exports.getEventTabBrowser = getEventTabBrowser
278 exports.getWindowId = getWindowId
279 exports.getRootWindow = getRootWindow
280 exports.isTextInputElement = isTextInputElement
281 exports.isElementEditable = isElementEditable
282 exports.getSessionStore = getSessionStore
284 exports.loadCss = loadCss
286 exports.simulateClick = simulateClick
287 exports.simulateWheel = simulateWheel
288 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
289 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
290 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
291 exports.readFromClipboard = readFromClipboard
292 exports.writeToClipboard = writeToClipboard
293 exports.timeIt = timeIt
294 exports.isBlacklisted = isBlacklisted
295 exports.getVersion = getVersion
296 exports.parseHTML = parseHTML
297 exports.isURL = isURL
298 exports.browserSearchSubmission = browserSearchSubmission
299 exports.getHintChars = getHintChars
300 exports.getResourceURI = getResourceURI