]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Closes #71. Collon will open Developer Toolbar, Esc will close it
[VimFx.git] / extension / packages / utils.coffee
1 { interfaces: Ci, classes: Cc, utils: Cu } = Components
2
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
12
13 _sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService)
14 _clip = Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard)
15
16 { getPref } = require 'prefs'
17
18 class Bucket
19 constructor: (@idFunc, @newFunc) ->
20 @bucket = {}
21
22 get: (obj) ->
23 id = @idFunc obj
24 if container = @bucket[id]
25 return container
26 else
27 return @bucket[id] = @newFunc obj
28
29 forget: (obj) ->
30 delete @bucket[id] if id = @idFunc obj
31
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
37
38 # Returns the window associated with the event
39 getEventWindow = (event) ->
40 if event.originalTarget instanceof Window
41 return event.originalTarget
42 else
43 doc = event.originalTarget.ownerDocument or event.originalTarget
44 if doc instanceof HTMLDocument or doc instanceof XULDocument
45 return doc.defaultView
46
47 getEventRootWindow = (event) ->
48 if window = getEventWindow event
49 return getRootWindow window
50
51 getEventTabBrowser = (event) ->
52 cw.gBrowser if cw = getEventRootWindow event
53
54 getRootWindow = (window) ->
55 return window.QueryInterface(Ci.nsIInterfaceRequestor)
56 .getInterface(Ci.nsIWebNavigation)
57 .QueryInterface(Ci.nsIDocShellTreeItem)
58 .rootTreeItem
59 .QueryInterface(Ci.nsIInterfaceRequestor)
60 .getInterface(Window);
61
62 isElementEditable = (element) ->
63 return element.isContentEditable or \
64 element instanceof HTMLInputElement or \
65 element instanceof HTMLTextAreaElement or \
66 element instanceof HTMLSelectElement or \
67 element.getAttribute('g_editable') == 'true' or \
68 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
69 element.ownerDocument?.designMode?.toLowerCase() == 'on'
70
71 getWindowId = (window) ->
72 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
73 .getInterface(Components.interfaces.nsIDOMWindowUtils)
74 .outerWindowID
75
76 getSessionStore = ->
77 Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
78
79 # Function that returns a URI to the css file that's part of the extension
80 cssUri = do () ->
81 (name) ->
82 baseURI = Services.io.newURI __SCRIPT_URI_SPEC__, null, null
83 uri = Services.io.newURI "resources/#{ name }.css", null, baseURI
84 return uri
85
86 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
87 # The stylesheet is then appended to every document, but it can be overwritten by
88 # any user css
89 loadCss = (name) ->
90 uri = cssUri(name)
91 if !_sss.sheetRegistered(uri, _sss.AGENT_SHEET)
92 _sss.loadAndRegisterSheet(uri, _sss.AGENT_SHEET)
93
94 unload ->
95 _sss.unregisterSheet(uri, _sss.AGENT_SHEET)
96
97 # Simulate mouse click with full chain of event
98 # Copied from Vimium codebase
99 simulateClick = (element, modifiers) ->
100 document = element.ownerDocument
101 window = document.defaultView
102 modifiers ||= {}
103
104 eventSequence = ["mouseover", "mousedown", "mouseup", "click"]
105 for event in eventSequence
106 mouseEvent = document.createEvent("MouseEvents")
107 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
108 modifiers.metaKey, 0, null)
109 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
110 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
111 element.dispatchEvent(mouseEvent)
112
113 # Write a string into system clipboard
114 writeToClipboard = (window, text) ->
115 str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
116 str.data = text
117
118 trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
119
120 if trans.init
121 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
122 .getInterface(Ci.nsIWebNavigation)
123 .QueryInterface(Ci.nsILoadContext);
124 trans.init(privacyContext);
125
126 trans.addDataFlavor("text/unicode");
127 trans.setTransferData("text/unicode", str, text.length * 2);
128
129 _clip.setData trans, null, Ci.nsIClipboard.kGlobalClipboard
130 #
131 # Write a string into system clipboard
132 readFromClipboard = (window) ->
133 trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
134
135 if trans.init
136 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
137 .getInterface(Ci.nsIWebNavigation)
138 .QueryInterface(Ci.nsILoadContext);
139 trans.init(privacyContext);
140
141 trans.addDataFlavor("text/unicode");
142
143 _clip.getData trans, Ci.nsIClipboard.kGlobalClipboard
144
145 str = {}
146 strLength = {}
147
148 trans.getTransferData("text/unicode", str, strLength)
149
150 if str
151 str = str.value.QueryInterface(Ci.nsISupportsString);
152 return str.data.substring 0, strLength.value / 2
153
154 return undefined
155
156 # Executes function `func` and mearues how much time it took
157 timeIt = (func, msg) ->
158 start = new Date().getTime()
159 result = func()
160 end = new Date().getTime()
161
162 console.log msg, end - start
163 return result
164
165 # Checks if the string provided matches one of the black list entries
166 # `blackList`: comma/space separated list of URLs with wildcards (* and !)
167 isBlacklisted = (str, blackList) ->
168 for rule in blackList.split(/[\s,]+/)
169 rule = rule.replace(/\*/g, '.*').replace(/\!/g, '.')
170 if str.match new RegExp("^#{ rule }$")
171 return true
172
173 return false
174
175 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
176 getVersion = do ->
177 version = null
178
179 if version == null
180 scope = {}
181 addonId = getPref 'addon_id'
182 Cu.import("resource://gre/modules/AddonManager.jsm", scope);
183 scope.AddonManager.getAddonByID addonId, ((addon) -> version = addon.version)
184
185 -> version
186
187 # Simulate smooth scrolling
188 smoothScroll = (window, dx, dy, msecs) ->
189 if msecs <= 0 || !Services.prefs.getBoolPref 'general.smoothScroll'
190 window.scrollBy dx, dy
191 else
192 # Callback
193 fn = (_x, _y) ->
194 window.scrollBy(_x, _y)
195 # Number of steps
196 delta = 10
197 l = Math.round(msecs / delta)
198 while l > 0
199 x = Math.round(dx / l)
200 y = Math.round(dy / l)
201 dx -= x
202 dy -= y
203
204 l -= 1
205 window.setTimeout fn, l * delta, x, y
206
207 parseHTML = (document, html) ->
208 parser = Cc["@mozilla.org/parserutils;1"].getService(Ci.nsIParserUtils)
209 flags = parser.SanitizerAllowStyle
210 return parser.parseFragment(html, flags, false, null, document.documentElement)
211
212 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
213 isURL = (str) ->
214 try
215 url = Cc["@mozilla.org/network/io-service;1"]
216 .getService(Ci.nsIIOService)
217 .newURI(str, null, null)
218 .QueryInterface(Ci.nsIURL)
219 return true
220 catch err
221 return false
222
223 # Use Firefox services to search for a given string
224 browserSearchSubmission = (str) ->
225 ss = Cc["@mozilla.org/browser/search-service;1"]
226 .getService(Ci.nsIBrowserSearchService)
227
228 engine = ss.currentEngine or ss.defaultEngine
229 return engine.getSubmission(str, null)
230
231 # DeveloperToolbar getter
232 developerToolbar = (chromeWindow) ->
233 tmp = {}
234 Cu.import("chrome://browser/content/browser.js")
235 new tmp.DeveloperToolbar(window, document.getElementById("developer-toolbar"))
236
237 exports.Bucket = Bucket
238 exports.getCurrentTabWindow = getCurrentTabWindow
239 exports.getEventWindow = getEventWindow
240 exports.getEventRootWindow = getEventRootWindow
241 exports.getEventTabBrowser = getEventTabBrowser
242
243 exports.getWindowId = getWindowId
244 exports.getRootWindow = getRootWindow
245 exports.isElementEditable = isElementEditable
246 exports.getSessionStore = getSessionStore
247
248 exports.loadCss = loadCss
249
250 exports.simulateClick = simulateClick
251 exports.smoothScroll = smoothScroll
252 exports.readFromClipboard = readFromClipboard
253 exports.writeToClipboard = writeToClipboard
254 exports.timeIt = timeIt
255 exports.isBlacklisted = isBlacklisted
256 exports.getVersion = getVersion
257 exports.parseHTML = parseHTML
258 exports.isURL = isURL
259 exports.browserSearchSubmission = browserSearchSubmission
260 exports.developerToolbar = developerToolbar
Imprint / Impressum