1 { interfaces: Ci, classes: Cc, utils: Cu } = Components
3 HTMLInputElement = Ci.nsIDOMHTMLInputElement
4 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
5 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
6 XULDocument = Ci.nsIDOMXULDocument
7 XULElement = Ci.nsIDOMXULElement
8 HTMLDocument = Ci.nsIDOMHTMLDocument
9 HTMLElement = Ci.nsIDOMHTMLElement
10 Window = Ci.nsIDOMWindow
11 ChromeWindow = Ci.nsIDOMChromeWindow
13 _sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService)
14 _clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard)
16 { getPref } = require 'prefs'
19 constructor: (@idFunc, @newFunc) ->
24 if container = @bucket[id]
27 return @bucket[id] = @newFunc obj
30 delete @bucket[id] if id = @idFunc obj
32 # Returns the `window` from the currently active tab.
33 getCurrentTabWindow = (event) ->
34 if window = getEventWindow event
35 if rootWindow = getRootWindow window
36 return rootWindow.gBrowser.selectedTab.linkedBrowser.contentWindow
38 # Returns the window associated with the event
39 getEventWindow = (event) ->
40 if event.originalTarget instanceof Window
41 return event.originalTarget
43 doc = event.originalTarget.ownerDocument or event.originalTarget
44 if doc instanceof HTMLDocument or doc instanceof XULDocument
45 return doc.defaultView
47 getEventRootWindow = (event) ->
48 if window = getEventWindow event
49 return getRootWindow window
51 getEventTabBrowser = (event) ->
52 cw.gBrowser if cw = getEventRootWindow event
54 getRootWindow = (window) ->
55 return window.QueryInterface(Ci.nsIInterfaceRequestor)
56 .getInterface(Ci.nsIWebNavigation)
57 .QueryInterface(Ci.nsIDocShellTreeItem)
59 .QueryInterface(Ci.nsIInterfaceRequestor)
60 .getInterface(Window);
62 isTextInputElement = (element) ->
63 return element instanceof HTMLInputElement or \
64 element instanceof HTMLTextAreaElement
66 isElementEditable = (element) ->
67 return element.isContentEditable or \
68 element instanceof HTMLInputElement or \
69 element instanceof HTMLTextAreaElement or \
70 element instanceof HTMLSelectElement or \
71 element.getAttribute('g_editable') == 'true' or \
72 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
73 element.ownerDocument?.designMode?.toLowerCase() == 'on'
75 getWindowId = (window) ->
76 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
77 .getInterface(Components.interfaces.nsIDOMWindowUtils)
81 Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
83 # Function that returns a URI to the css file that's part of the extension
86 baseURI = Services.io.newURI __SCRIPT_URI_SPEC__, null, null
87 uri = Services.io.newURI "resources/#{ name }.css", null, baseURI
90 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
91 # The stylesheet is then appended to every document, but it can be overwritten by
95 if !_sss.sheetRegistered(uri, _sss.AGENT_SHEET)
96 _sss.loadAndRegisterSheet(uri, _sss.AGENT_SHEET)
99 _sss.unregisterSheet(uri, _sss.AGENT_SHEET)
101 # Simulate mouse click with full chain of event
102 # Copied from Vimium codebase
103 simulateClick = (element, modifiers) ->
104 document = element.ownerDocument
105 window = document.defaultView
108 eventSequence = ["mouseover", "mousedown", "mouseup", "click"]
109 for event in eventSequence
110 mouseEvent = document.createEvent("MouseEvents")
111 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
112 modifiers.metaKey, 0, null)
113 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
114 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
115 element.dispatchEvent(mouseEvent)
117 # Write a string into system clipboard
118 writeToClipboard = (window, text) ->
119 str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
122 trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
125 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
126 .getInterface(Ci.nsIWebNavigation)
127 .QueryInterface(Ci.nsILoadContext);
128 trans.init(privacyContext);
130 trans.addDataFlavor("text/unicode");
131 trans.setTransferData("text/unicode", str, text.length * 2);
133 _clip.setData trans, null, Ci.nsIClipboard.kGlobalClipboard
135 # Write a string into system clipboard
136 readFromClipboard = (window) ->
137 trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
140 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
141 .getInterface(Ci.nsIWebNavigation)
142 .QueryInterface(Ci.nsILoadContext);
143 trans.init(privacyContext);
145 trans.addDataFlavor("text/unicode");
147 _clip.getData trans, Ci.nsIClipboard.kGlobalClipboard
152 trans.getTransferData("text/unicode", str, strLength)
155 str = str.value.QueryInterface(Ci.nsISupportsString);
156 return str.data.substring 0, strLength.value / 2
160 # Executes function `func` and mearues how much time it took
161 timeIt = (func, msg) ->
162 start = new Date().getTime()
164 end = new Date().getTime()
166 console.log msg, end - start
169 # Checks if the string provided matches one of the black list entries
170 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
171 isBlacklisted = (str, blackList) ->
172 for rule in blackList.split(/[\s,]+/)
173 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
174 if str.match new RegExp("^#{ rule }$")
179 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
185 addonId = getPref 'addon_id'
186 Cu.import("resource://gre/modules/AddonManager.jsm", scope);
187 scope.AddonManager.getAddonByID addonId, ((addon) -> version = addon.version)
191 # Simulate smooth scrolling
192 smoothScroll = (window, dx, dy, msecs) ->
193 if msecs <= 0 || !Services.prefs.getBoolPref 'general.smoothScroll'
194 window.scrollBy dx, dy
198 window.scrollBy(_x, _y)
201 l = Math.round(msecs / delta)
203 x = Math.round(dx / l)
204 y = Math.round(dy / l)
209 window.setTimeout fn, l * delta, x, y
211 parseHTML = (document, html) ->
212 parser = Cc["@mozilla.org/parserutils;1"].getService(Ci.nsIParserUtils)
213 flags = parser.SanitizerAllowStyle
214 return parser.parseFragment(html, flags, false, null, document.documentElement)
216 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
219 url = Cc["@mozilla.org/network/io-service;1"]
220 .getService(Ci.nsIIOService)
221 .newURI(str, null, null)
222 .QueryInterface(Ci.nsIURL)
227 # Use Firefox services to search for a given string
228 browserSearchSubmission = (str) ->
229 ss = Cc["@mozilla.org/browser/search-service;1"]
230 .getService(Ci.nsIBrowserSearchService)
232 engine = ss.currentEngine or ss.defaultEngine
233 return engine.getSubmission(str, null)
235 # Adds a class the the `element.className` trying to keep the whole class string
236 # will formed (without extra spaces at the tails)
237 addClass = (element, klass) ->
238 if (element.className?.search klass) == -1
240 element.className += " #{ klass }"
242 element.className = klass
244 # Remove a class from the `element.className`
245 removeClass = (element, klass) ->
246 name = element.className.replace new RegExp("\\s*#{ klass }"), ""
247 element.className = name or null
249 exports.Bucket = Bucket
250 exports.getCurrentTabWindow = getCurrentTabWindow
251 exports.getEventWindow = getEventWindow
252 exports.getEventRootWindow = getEventRootWindow
253 exports.getEventTabBrowser = getEventTabBrowser
255 exports.getWindowId = getWindowId
256 exports.getRootWindow = getRootWindow
257 exports.isTextInputElement = isTextInputElement
258 exports.isElementEditable = isElementEditable
259 exports.getSessionStore = getSessionStore
261 exports.loadCss = loadCss
263 exports.simulateClick = simulateClick
264 exports.smoothScroll = smoothScroll
265 exports.readFromClipboard = readFromClipboard
266 exports.writeToClipboard = writeToClipboard
267 exports.timeIt = timeIt
268 exports.isBlacklisted = isBlacklisted
269 exports.getVersion = getVersion
270 exports.parseHTML = parseHTML
271 exports.isURL = isURL
272 exports.browserSearchSubmission = browserSearchSubmission
273 exports.addClass = addClass
274 exports.removeClass = removeClass