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