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 if window = getEventWindow(event)
37 if 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 if window = getEventWindow(event)
51 return getRootWindow(window)
53 getEventTabBrowser = (event) ->
54 cw.gBrowser if cw = getEventRootWindow(event)
56 getRootWindow = (window) ->
57 return window.QueryInterface(Ci.nsIInterfaceRequestor)
58 .getInterface(Ci.nsIWebNavigation)
59 .QueryInterface(Ci.nsIDocShellTreeItem)
61 .QueryInterface(Ci.nsIInterfaceRequestor)
64 isTextInputElement = (element) ->
65 return element instanceof HTMLInputElement or \
66 element instanceof HTMLTextAreaElement
68 isElementEditable = (element) ->
69 return element.isContentEditable or \
70 element instanceof HTMLInputElement or \
71 element instanceof HTMLTextAreaElement or \
72 element instanceof HTMLSelectElement or \
73 element.getAttribute('g_editable') == 'true' or \
74 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
75 element.ownerDocument?.designMode?.toLowerCase() == 'on'
77 getWindowId = (window) ->
78 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
79 .getInterface(Components.interfaces.nsIDOMWindowUtils)
83 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore);
85 # Function that returns a URI to the css file that's part of the extension
88 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
89 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
92 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
93 # The stylesheet is then appended to every document, but it can be overwritten by
96 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
99 if !sss.sheetRegistered(uri, sss.AUTHOR_SHEET)
100 sss.loadAndRegisterSheet(uri, sss.AUTHOR_SHEET)
103 sss.unregisterSheet(uri, sss.AUTHOR_SHEET)
105 # Simulate mouse click with full chain of event
106 # Copied from Vimium codebase
107 simulateClick = (element, modifiers) ->
108 document = element.ownerDocument
109 window = document.defaultView
112 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
113 for event in eventSequence
114 mouseEvent = document.createEvent('MouseEvents')
115 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
116 modifiers.metaKey, 0, null)
117 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
118 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
119 element.dispatchEvent(mouseEvent)
121 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
122 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
123 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
125 # Simulate mouse scroll event by specific offsets given
126 # that mouse cursor is at specified position
127 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
128 windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
129 .getInterface(Ci.nsIDOMWindowUtils)
131 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
132 windowUtils.sendWheelEvent(
133 pX, pY, # Window offset (x, y) in pixels
134 deltaX, deltaY, 0, # Deltas (x, y, z)
135 mode, # Mode (pixel, line, page)
137 0, 0, # Line or Page deltas (x, y)
141 # Write a string into system clipboard
142 writeToClipboard = (window, text) ->
143 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
146 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable);
149 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
150 .getInterface(Ci.nsIWebNavigation)
151 .QueryInterface(Ci.nsILoadContext)
152 trans.init(privacyContext)
154 trans.addDataFlavor('text/unicode');
155 trans.setTransferData('text/unicode', str, text.length * 2)
157 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
159 # Write a string into system clipboard
160 readFromClipboard = (window) ->
161 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
164 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
165 .getInterface(Ci.nsIWebNavigation)
166 .QueryInterface(Ci.nsILoadContext);
167 trans.init(privacyContext);
169 trans.addDataFlavor('text/unicode');
171 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
176 trans.getTransferData('text/unicode', str, strLength)
179 str = str.value.QueryInterface(Ci.nsISupportsString)
180 return str.data.substring(0, strLength.value / 2)
184 # Executes function `func` and mearues how much time it took
185 timeIt = (func, msg) ->
186 start = new Date().getTime()
188 end = new Date().getTime()
190 console.log(msg, end - start)
193 # Checks if the string provided matches one of the black list entries
194 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
195 isBlacklisted = (str, blackList) ->
196 for rule in blackList.split(/[\s,]+/)
197 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
198 if str.match ///^#{ rule }$///
203 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
209 addonId = getPref('addon_id')
210 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
211 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
216 parseHTML = (document, html) ->
217 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
218 flags = parser.SanitizerAllowStyle
219 return parser.parseFragment(html, flags, false, null, document.documentElement)
221 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
224 url = Cc['@mozilla.org/network/io-service;1']
225 .getService(Ci.nsIIOService)
226 .newURI(str, null, null)
227 .QueryInterface(Ci.nsIURL)
232 # Use Firefox services to search for a given string
233 browserSearchSubmission = (str) ->
234 ss = Cc['@mozilla.org/browser/search-service;1']
235 .getService(Ci.nsIBrowserSearchService)
237 engine = ss.currentEngine or ss.defaultEngine
238 return engine.getSubmission(str, null)
240 # Get hint characters, convert them to lower case and fall back
241 # to default hint characters if there are less than 3 chars
243 # Remove duplicate characters from string (case insensitive)
244 removeDuplicateCharacters = (str) ->
246 return str.toLowerCase()
248 .filter((char) -> if seen[char] then false else (seen[char] = true))
252 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
253 if hintChars.length < 2
254 hintChars = getDefaultPref('hint_chars')
258 # Return URI to some file in the extension packaged as resource
259 getResourceURI = do ->
260 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
261 return (path) -> Services.io.newURI(path, null, baseURI)
263 # Escape string to render it usable in regular expressions
264 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
266 exports.Bucket = Bucket
267 exports.getCurrentTabWindow = getCurrentTabWindow
268 exports.getEventWindow = getEventWindow
269 exports.getEventRootWindow = getEventRootWindow
270 exports.getEventTabBrowser = getEventTabBrowser
272 exports.getWindowId = getWindowId
273 exports.getRootWindow = getRootWindow
274 exports.isTextInputElement = isTextInputElement
275 exports.isElementEditable = isElementEditable
276 exports.getSessionStore = getSessionStore
278 exports.loadCss = loadCss
280 exports.simulateClick = simulateClick
281 exports.simulateWheel = simulateWheel
282 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
283 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
284 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
285 exports.readFromClipboard = readFromClipboard
286 exports.writeToClipboard = writeToClipboard
287 exports.timeIt = timeIt
288 exports.isBlacklisted = isBlacklisted
289 exports.getVersion = getVersion
290 exports.parseHTML = parseHTML
291 exports.isURL = isURL
292 exports.browserSearchSubmission = browserSearchSubmission
293 exports.getHintChars = getHintChars
294 exports.getResourceURI = getResourceURI
295 exports.regexpEscape = regexpEscape