]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Reorganized code, removed memory leaks
[VimFx.git] / extension / packages / utils.coffee
1 { unload } = require 'unload'
2 { console } = require 'console'
3 { getPref
4 , getDefaultPref
5 } = require 'prefs'
6
7 { classes: Cc, interfaces: Ci, utils: Cu } = Components
8
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
18
19 _sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
20 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
21
22 class Bucket
23 constructor: (@idFunc, @newFunc) ->
24 @bucket = {}
25
26 get: (obj) ->
27 id = @idFunc(obj)
28 if container = @bucket[id]
29 return container
30 else
31 return @bucket[id] = @newFunc(obj)
32
33 forget: (obj) ->
34 delete @bucket[id] if id = @idFunc(obj)
35
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
41
42 # Returns the window associated with the event
43 getEventWindow = (event) ->
44 if event.originalTarget instanceof Window
45 return event.originalTarget
46 else
47 doc = event.originalTarget.ownerDocument or event.originalTarget
48 if doc instanceof HTMLDocument or doc instanceof XULDocument
49 return doc.defaultView
50
51 getEventRootWindow = (event) ->
52 if window = getEventWindow(event)
53 return getRootWindow(window)
54
55 getEventTabBrowser = (event) ->
56 cw.gBrowser if cw = getEventRootWindow(event)
57
58 getRootWindow = (window) ->
59 return window.QueryInterface(Ci.nsIInterfaceRequestor)
60 .getInterface(Ci.nsIWebNavigation)
61 .QueryInterface(Ci.nsIDocShellTreeItem)
62 .rootTreeItem
63 .QueryInterface(Ci.nsIInterfaceRequestor)
64 .getInterface(Window)
65
66 isTextInputElement = (element) ->
67 return element instanceof HTMLInputElement or \
68 element instanceof HTMLTextAreaElement
69
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'
78
79 getWindowId = (window) ->
80 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
81 .getInterface(Components.interfaces.nsIDOMWindowUtils)
82 .outerWindowID
83
84 getSessionStore = ->
85 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore);
86
87 # Function that returns a URI to the css file that's part of the extension
88 cssUri = do ->
89 (name) ->
90 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
91 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
92 return uri
93
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
96 # any user css
97 loadCss = (name) ->
98 uri = cssUri(name)
99 if !_sss.sheetRegistered(uri, _sss.AGENT_SHEET)
100 _sss.loadAndRegisterSheet(uri, _sss.AGENT_SHEET)
101
102 unload ->
103 _sss.unregisterSheet(uri, _sss.AGENT_SHEET)
104
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
110 modifiers ||= {}
111
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)
120
121 # Write a string into system clipboard
122 writeToClipboard = (window, text) ->
123 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
124 str.data = text
125
126 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable);
127
128 if trans.init
129 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
130 .getInterface(Ci.nsIWebNavigation)
131 .QueryInterface(Ci.nsILoadContext)
132 trans.init(privacyContext)
133
134 trans.addDataFlavor('text/unicode');
135 trans.setTransferData('text/unicode', str, text.length * 2)
136
137 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
138
139 # Write a string into system clipboard
140 readFromClipboard = (window) ->
141 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
142
143 if trans.init
144 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
145 .getInterface(Ci.nsIWebNavigation)
146 .QueryInterface(Ci.nsILoadContext);
147 trans.init(privacyContext);
148
149 trans.addDataFlavor('text/unicode');
150
151 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
152
153 str = {}
154 strLength = {}
155
156 trans.getTransferData('text/unicode', str, strLength)
157
158 if str
159 str = str.value.QueryInterface(Ci.nsISupportsString)
160 return str.data.substring(0, strLength.value / 2)
161
162 return undefined
163
164 # Executes function `func` and mearues how much time it took
165 timeIt = (func, msg) ->
166 start = new Date().getTime()
167 result = func()
168 end = new Date().getTime()
169
170 console.log(msg, end - start)
171 return result
172
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 }$///
179 return true
180
181 return false
182
183 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
184 getVersion = do ->
185 version = null
186
187 if version == null
188 scope = {}
189 addonId = getPref('addon_id')
190 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
191 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
192
193 return ->
194 return version
195
196 # Simulate smooth scrolling
197 smoothScroll = (window, dx, dy, msecs) ->
198 if msecs <= 0 || !Services.prefs.getBoolPref('general.smoothScroll')
199 window.scrollBy(dx, dy)
200 else
201 # Callback
202 fn = (_x, _y) ->
203 window.scrollBy(_x, _y)
204 # Number of steps
205 delta = 10
206 l = Math.round(msecs / delta)
207 while l > 0
208 x = Math.round(dx / l)
209 y = Math.round(dy / l)
210 dx -= x
211 dy -= y
212
213 l -= 1
214 window.setTimeout(fn, l * delta, x, y)
215
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)
220
221 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
222 isURL = (str) ->
223 try
224 url = Cc['@mozilla.org/network/io-service;1']
225 .getService(Ci.nsIIOService)
226 .newURI(str, null, null)
227 .QueryInterface(Ci.nsIURL)
228 return true
229 catch err
230 return false
231
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)
236
237 engine = ss.currentEngine or ss.defaultEngine
238 return engine.getSubmission(str, null)
239
240 # Get hint characters, convert them to lower case and fall back
241 # to default hint characters if there are less than 3 chars
242 getHintChars = do ->
243 # Remove duplicate characters from string (case insensitive)
244 removeDuplicateCharacters = (str) ->
245 seen = {}
246 return str.toLowerCase()
247 .split('')
248 .filter((char) -> if seen[char] then false else (seen[char] = true))
249 .join('')
250
251 return ->
252 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
253 if hintChars.length < 3
254 hintChars = getDefaultPref('hint_chars')
255
256 return hintChars
257
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)
262
263 # Escape string to render it usable in regular expressions
264 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
265
266 exports.Bucket = Bucket
267 exports.getCurrentTabWindow = getCurrentTabWindow
268 exports.getEventWindow = getEventWindow
269 exports.getEventRootWindow = getEventRootWindow
270 exports.getEventTabBrowser = getEventTabBrowser
271
272 exports.getWindowId = getWindowId
273 exports.getRootWindow = getRootWindow
274 exports.isTextInputElement = isTextInputElement
275 exports.isElementEditable = isElementEditable
276 exports.getSessionStore = getSessionStore
277
278 exports.loadCss = loadCss
279
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
Imprint / Impressum