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 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
100 # by users often make the hint markers unreadable, for example. Just using `!important` in the
102 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
103 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
106 sss.unregisterSheet(uri, sss.AGENT_SHEET)
108 # Simulate mouse click with full chain of event
109 # Copied from Vimium codebase
110 simulateClick = (element, modifiers) ->
111 document = element.ownerDocument
112 window = document.defaultView
115 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
116 for event in eventSequence
117 mouseEvent = document.createEvent('MouseEvents')
118 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
119 modifiers.metaKey, 0, null)
120 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
121 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
122 element.dispatchEvent(mouseEvent)
124 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
125 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
126 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
128 # Simulate mouse scroll event by specific offsets given
129 # that mouse cursor is at specified position
130 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
131 windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
132 .getInterface(Ci.nsIDOMWindowUtils)
134 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
135 windowUtils.sendWheelEvent(
136 pX, pY, # Window offset (x, y) in pixels
137 deltaX, deltaY, 0, # Deltas (x, y, z)
138 mode, # Mode (pixel, line, page)
140 0, 0, # Line or Page deltas (x, y)
144 # Write a string into system clipboard
145 writeToClipboard = (window, text) ->
146 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
149 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
152 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
153 .getInterface(Ci.nsIWebNavigation)
154 .QueryInterface(Ci.nsILoadContext)
155 trans.init(privacyContext)
157 trans.addDataFlavor('text/unicode')
158 trans.setTransferData('text/unicode', str, text.length * 2)
160 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
162 # Write a string into system clipboard
163 readFromClipboard = (window) ->
164 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
167 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
168 .getInterface(Ci.nsIWebNavigation)
169 .QueryInterface(Ci.nsILoadContext)
170 trans.init(privacyContext)
172 trans.addDataFlavor('text/unicode')
174 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
179 trans.getTransferData('text/unicode', str, strLength)
182 str = str.value.QueryInterface(Ci.nsISupportsString)
183 return str.data.substring(0, strLength.value / 2)
187 # Executes function `func` and mearues how much time it took
188 timeIt = (func, msg) ->
189 start = new Date().getTime()
191 end = new Date().getTime()
193 console.log(msg, end - start)
196 # Checks if the string provided matches one of the black list entries
197 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
198 isBlacklisted = (str, blackList) ->
199 for rule in blackList.split(/[\s,]+/)
200 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
201 if str.match ///^#{ rule }$///
206 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
212 addonId = getPref('addon_id')
213 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
214 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
219 parseHTML = (document, html) ->
220 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
221 flags = parser.SanitizerAllowStyle
222 return parser.parseFragment(html, flags, false, null, document.documentElement)
224 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
227 url = Cc['@mozilla.org/network/io-service;1']
228 .getService(Ci.nsIIOService)
229 .newURI(str, null, null)
230 .QueryInterface(Ci.nsIURL)
235 # Use Firefox services to search for a given string
236 browserSearchSubmission = (str) ->
237 ss = Cc['@mozilla.org/browser/search-service;1']
238 .getService(Ci.nsIBrowserSearchService)
240 engine = ss.currentEngine or ss.defaultEngine
241 return engine.getSubmission(str, null)
243 # Get hint characters, convert them to lower case and fall back
244 # to default hint characters if there are less than 3 chars
246 # Remove duplicate characters from string (case insensitive)
247 removeDuplicateCharacters = (str) ->
249 return str.toLowerCase()
251 .filter((char) -> if seen[char] then false else (seen[char] = true))
255 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
256 if hintChars.length < 2
257 hintChars = getDefaultPref('hint_chars')
261 # Return URI to some file in the extension packaged as resource
262 getResourceURI = do ->
263 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
264 return (path) -> Services.io.newURI(path, null, baseURI)
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