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 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
22 constructor: (@idFunc, @newFunc) ->
27 if container = @bucket[id]
30 return @bucket[id] = @newFunc(obj)
33 delete @bucket[id] if id = @idFunc(obj)
35 # Returns the `window` from the currently active tab.
36 getCurrentTabWindow = (event) ->
37 if window = getEventWindow(event)
38 if rootWindow = getRootWindow(window)
39 return rootWindow.gBrowser.selectedTab.linkedBrowser.contentWindow
41 # Returns the window associated with the event
42 getEventWindow = (event) ->
43 if event.originalTarget instanceof Window
44 return event.originalTarget
46 doc = event.originalTarget.ownerDocument or event.originalTarget
47 if doc instanceof HTMLDocument or doc instanceof XULDocument
48 return doc.defaultView
50 getEventRootWindow = (event) ->
51 if window = getEventWindow(event)
52 return getRootWindow(window)
54 getEventTabBrowser = (event) ->
55 cw.gBrowser if cw = getEventRootWindow(event)
57 getRootWindow = (window) ->
58 return window.QueryInterface(Ci.nsIInterfaceRequestor)
59 .getInterface(Ci.nsIWebNavigation)
60 .QueryInterface(Ci.nsIDocShellTreeItem)
62 .QueryInterface(Ci.nsIInterfaceRequestor)
65 isTextInputElement = (element) ->
66 return element instanceof HTMLInputElement or \
67 element instanceof HTMLTextAreaElement
69 isElementEditable = (element) ->
70 return element.isContentEditable or \
71 element instanceof HTMLInputElement or \
72 element instanceof HTMLTextAreaElement or \
73 element instanceof HTMLSelectElement or \
74 element.getAttribute('g_editable') == 'true' or \
75 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
76 element.ownerDocument?.designMode?.toLowerCase() == 'on'
78 getWindowId = (window) ->
79 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
80 .getInterface(Components.interfaces.nsIDOMWindowUtils)
84 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore);
86 # Function that returns a URI to the css file that's part of the extension
89 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
90 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
93 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
94 # The stylesheet is then appended to every document, but it can be overwritten by
97 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
100 if !sss.sheetRegistered(uri, sss.AUTHOR_SHEET)
101 sss.loadAndRegisterSheet(uri, sss.AUTHOR_SHEET)
104 sss.unregisterSheet(uri, sss.AUTHOR_SHEET)
106 # Simulate mouse click with full chain of event
107 # Copied from Vimium codebase
108 simulateClick = (element, modifiers) ->
109 document = element.ownerDocument
110 window = document.defaultView
113 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
114 for event in eventSequence
115 mouseEvent = document.createEvent('MouseEvents')
116 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
117 modifiers.metaKey, 0, null)
118 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
119 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
120 element.dispatchEvent(mouseEvent)
122 # Write a string into system clipboard
123 writeToClipboard = (window, text) ->
124 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
127 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable);
130 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
131 .getInterface(Ci.nsIWebNavigation)
132 .QueryInterface(Ci.nsILoadContext)
133 trans.init(privacyContext)
135 trans.addDataFlavor('text/unicode');
136 trans.setTransferData('text/unicode', str, text.length * 2)
138 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
140 # Write a string into system clipboard
141 readFromClipboard = (window) ->
142 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
145 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
146 .getInterface(Ci.nsIWebNavigation)
147 .QueryInterface(Ci.nsILoadContext);
148 trans.init(privacyContext);
150 trans.addDataFlavor('text/unicode');
152 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
157 trans.getTransferData('text/unicode', str, strLength)
160 str = str.value.QueryInterface(Ci.nsISupportsString)
161 return str.data.substring(0, strLength.value / 2)
165 # Executes function `func` and mearues how much time it took
166 timeIt = (func, msg) ->
167 start = new Date().getTime()
169 end = new Date().getTime()
171 console.log(msg, end - start)
174 # Checks if the string provided matches one of the black list entries
175 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
176 isBlacklisted = (str, blackList) ->
177 for rule in blackList.split(/[\s,]+/)
178 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
179 if str.match ///^#{ rule }$///
184 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
190 addonId = getPref('addon_id')
191 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
192 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
197 # Simulate smooth scrolling
198 smoothScroll = (window, dx, dy, msecs) ->
199 if msecs <= 0 || !Services.prefs.getBoolPref('general.smoothScroll')
200 window.scrollBy(dx, dy)
204 window.scrollBy(_x, _y)
207 l = Math.round(msecs / delta)
209 x = Math.round(dx / l)
210 y = Math.round(dy / l)
215 window.setTimeout(fn, l * delta, x, y)
217 parseHTML = (document, html) ->
218 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
219 flags = parser.SanitizerAllowStyle
220 return parser.parseFragment(html, flags, false, null, document.documentElement)
222 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
225 url = Cc['@mozilla.org/network/io-service;1']
226 .getService(Ci.nsIIOService)
227 .newURI(str, null, null)
228 .QueryInterface(Ci.nsIURL)
233 # Use Firefox services to search for a given string
234 browserSearchSubmission = (str) ->
235 ss = Cc['@mozilla.org/browser/search-service;1']
236 .getService(Ci.nsIBrowserSearchService)
238 engine = ss.currentEngine or ss.defaultEngine
239 return engine.getSubmission(str, null)
241 # Get hint characters, convert them to lower case and fall back
242 # to default hint characters if there are less than 3 chars
244 # Remove duplicate characters from string (case insensitive)
245 removeDuplicateCharacters = (str) ->
247 return str.toLowerCase()
249 .filter((char) -> if seen[char] then false else (seen[char] = true))
253 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
254 if hintChars.length < 3
255 hintChars = getDefaultPref('hint_chars')
259 # Return URI to some file in the extension packaged as resource
260 getResourceURI = do ->
261 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
262 return (path) -> Services.io.newURI(path, null, baseURI)
264 # Escape string to render it usable in regular expressions
265 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
267 exports.Bucket = Bucket
268 exports.getCurrentTabWindow = getCurrentTabWindow
269 exports.getEventWindow = getEventWindow
270 exports.getEventRootWindow = getEventRootWindow
271 exports.getEventTabBrowser = getEventTabBrowser
273 exports.getWindowId = getWindowId
274 exports.getRootWindow = getRootWindow
275 exports.isTextInputElement = isTextInputElement
276 exports.isElementEditable = isElementEditable
277 exports.getSessionStore = getSessionStore
279 exports.loadCss = loadCss
281 exports.simulateClick = simulateClick
282 exports.smoothScroll = smoothScroll
283 exports.readFromClipboard = readFromClipboard
284 exports.writeToClipboard = writeToClipboard
285 exports.timeIt = timeIt
286 exports.isBlacklisted = isBlacklisted
287 exports.getVersion = getVersion
288 exports.parseHTML = parseHTML
289 exports.isURL = isURL
290 exports.browserSearchSubmission = browserSearchSubmission
291 exports.getHintChars = getHintChars
292 exports.getResourceURI = getResourceURI
293 exports.regexpEscape = regexpEscape