1 { unload } = require 'unload'
2 { console } = require 'console'
7 { classes: Cc, interfaces: Ci, utils: Cu } = Components
9 HTMLInputElement = Ci.nsIDOMHTMLInputElement
10 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
11 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
12 XULDocument = Ci.nsIDOMXULDocument
13 XULElement = Ci.nsIDOMXULElement
14 HTMLDocument = Ci.nsIDOMHTMLDocument
15 HTMLElement = Ci.nsIDOMHTMLElement
16 Window = Ci.nsIDOMWindow
17 ChromeWindow = Ci.nsIDOMChromeWindow
19 _sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
20 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
23 constructor: (@idFunc, @newFunc) ->
28 if container = @bucket[id]
31 return @bucket[id] = @newFunc(obj)
34 delete @bucket[id] if id = @idFunc(obj)
36 # Returns the `window` from the currently active tab.
37 getCurrentTabWindow = (event) ->
38 if window = getEventWindow(event)
39 if rootWindow = getRootWindow(window)
40 return rootWindow.gBrowser.selectedTab.linkedBrowser.contentWindow
42 # Returns the window associated with the event
43 getEventWindow = (event) ->
44 if event.originalTarget instanceof Window
45 return event.originalTarget
47 doc = event.originalTarget.ownerDocument or event.originalTarget
48 if doc instanceof HTMLDocument or doc instanceof XULDocument
49 return doc.defaultView
51 getEventRootWindow = (event) ->
52 if window = getEventWindow(event)
53 return getRootWindow(window)
55 getEventTabBrowser = (event) ->
56 cw.gBrowser if cw = getEventRootWindow(event)
58 getRootWindow = (window) ->
59 return window.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) ->
80 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
81 .getInterface(Components.interfaces.nsIDOMWindowUtils)
85 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore);
87 # Function that returns a URI to the css file that's part of the extension
90 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
91 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
94 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
95 # The stylesheet is then appended to every document, but it can be overwritten by
99 if !_sss.sheetRegistered(uri, _sss.AGENT_SHEET)
100 _sss.loadAndRegisterSheet(uri, _sss.AGENT_SHEET)
103 _sss.unregisterSheet(uri, _sss.AGENT_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 # Write a string into system clipboard
122 writeToClipboard = (window, text) ->
123 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
126 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable);
129 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
130 .getInterface(Ci.nsIWebNavigation)
131 .QueryInterface(Ci.nsILoadContext)
132 trans.init(privacyContext)
134 trans.addDataFlavor('text/unicode');
135 trans.setTransferData('text/unicode', str, text.length * 2)
137 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
139 # Write a string into system clipboard
140 readFromClipboard = (window) ->
141 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
144 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
145 .getInterface(Ci.nsIWebNavigation)
146 .QueryInterface(Ci.nsILoadContext);
147 trans.init(privacyContext);
149 trans.addDataFlavor('text/unicode');
151 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
156 trans.getTransferData('text/unicode', str, strLength)
159 str = str.value.QueryInterface(Ci.nsISupportsString)
160 return str.data.substring(0, strLength.value / 2)
164 # Executes function `func` and mearues how much time it took
165 timeIt = (func, msg) ->
166 start = new Date().getTime()
168 end = new Date().getTime()
170 console.log(msg, end - start)
173 # Checks if the string provided matches one of the black list entries
174 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
175 isBlacklisted = (str, blackList) ->
176 for rule in blackList.split(/[\s,]+/)
177 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
178 if str.match ///^#{ rule }$///
183 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
189 addonId = getPref('addon_id')
190 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
191 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
196 # Simulate smooth scrolling
197 smoothScroll = (window, dx, dy, msecs) ->
198 if msecs <= 0 || !Services.prefs.getBoolPref('general.smoothScroll')
199 window.scrollBy(dx, dy)
203 window.scrollBy(_x, _y)
206 l = Math.round(msecs / delta)
208 x = Math.round(dx / l)
209 y = Math.round(dy / l)
214 window.setTimeout(fn, l * delta, x, y)
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 < 3
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.smoothScroll = smoothScroll
282 exports.readFromClipboard = readFromClipboard
283 exports.writeToClipboard = writeToClipboard
284 exports.timeIt = timeIt
285 exports.isBlacklisted = isBlacklisted
286 exports.getVersion = getVersion
287 exports.parseHTML = parseHTML
288 exports.isURL = isURL
289 exports.browserSearchSubmission = browserSearchSubmission
290 exports.getHintChars = getHintChars
291 exports.getResourceURI = getResourceURI
292 exports.regexpEscape = regexpEscape