]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Refactor preferences defaults, prepare for enabling preferences sync
[VimFx.git] / extension / packages / utils.coffee
1 { unload } = require 'unload'
2 { getPref
3 , setPref
4 } = require 'prefs'
5
6 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
7
8 { classes: Cc, interfaces: Ci, utils: Cu } = Components
9
10 HTMLInputElement = Ci.nsIDOMHTMLInputElement
11 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
12 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
13 XULDocument = Ci.nsIDOMXULDocument
14 XULElement = Ci.nsIDOMXULElement
15 XPathResult = Ci.nsIDOMXPathResult
16 HTMLDocument = Ci.nsIDOMHTMLDocument
17 HTMLElement = Ci.nsIDOMHTMLElement
18 Window = Ci.nsIDOMWindow
19 ChromeWindow = Ci.nsIDOMChromeWindow
20
21 _clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
22
23 class Bucket
24 constructor: (@idFunc, @newFunc) ->
25 @bucket = {}
26
27 get: (obj) ->
28 id = @idFunc(obj)
29 if container = @bucket[id]
30 return container
31 else
32 return @bucket[id] = @newFunc(obj)
33
34 forget: (obj) ->
35 delete @bucket[id] if id = @idFunc(obj)
36
37 getEventWindow = (event) ->
38 if event.originalTarget instanceof Window
39 return event.originalTarget
40 else
41 doc = event.originalTarget.ownerDocument or event.originalTarget
42 if doc instanceof HTMLDocument or doc instanceof XULDocument
43 return doc.defaultView
44
45 getEventRootWindow = (event) ->
46 return unless window = getEventWindow(event)
47 return getRootWindow(window)
48
49 getEventCurrentTabWindow = (event) ->
50 return unless rootWindow = getEventRootWindow(event)
51 return getCurrentTabWindow(rootWindow)
52
53 getRootWindow = (window) ->
54 return window
55 .QueryInterface(Ci.nsIInterfaceRequestor)
56 .getInterface(Ci.nsIWebNavigation)
57 .QueryInterface(Ci.nsIDocShellTreeItem)
58 .rootTreeItem
59 .QueryInterface(Ci.nsIInterfaceRequestor)
60 .getInterface(Window)
61
62 getCurrentTabWindow = (window) ->
63 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
64
65 blurActiveElement = (window) ->
66 # Only blur editable elements, in order not to interfere with the browser too much. TODO: Is that
67 # really needed? What if a website has made more elements focusable -- shouldn't those also be
68 # blurred?
69 { activeElement } = window.document
70 if isElementEditable(activeElement)
71 activeElement.blur()
72
73 isTextInputElement = (element) ->
74 return element instanceof HTMLInputElement or \
75 element instanceof HTMLTextAreaElement
76
77 isElementEditable = (element) ->
78 return element.isContentEditable or \
79 element instanceof HTMLInputElement or \
80 element instanceof HTMLTextAreaElement or \
81 element instanceof HTMLSelectElement or \
82 element.getAttribute('g_editable') == 'true' or \
83 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
84 element.ownerDocument?.designMode?.toLowerCase() == 'on'
85
86 getWindowId = (window) ->
87 return window
88 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
89 .getInterface(Components.interfaces.nsIDOMWindowUtils)
90 .outerWindowID
91
92 getSessionStore = ->
93 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
94
95 # Function that returns a URI to the css file that's part of the extension
96 cssUri = do ->
97 (name) ->
98 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
99 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
100 return uri
101
102 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
103 # The stylesheet is then appended to every document, but it can be overwritten by
104 # any user css
105 loadCss = do ->
106 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
107 return (name) ->
108 uri = cssUri(name)
109 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
110 # by users often make the hint markers unreadable, for example. Just using `!important` in the
111 # CSS is not enough.
112 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
113 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
114
115 unload ->
116 sss.unregisterSheet(uri, sss.AGENT_SHEET)
117
118 # Simulate mouse click with full chain of event
119 # Copied from Vimium codebase
120 simulateClick = (element, modifiers = {}) ->
121 document = element.ownerDocument
122 window = document.defaultView
123
124 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
125 for event in eventSequence
126 mouseEvent = document.createEvent('MouseEvents')
127 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
128 modifiers.metaKey, 0, null)
129 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
130 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
131 element.dispatchEvent(mouseEvent)
132
133 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
134 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
135 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
136
137 # Simulate mouse scroll event by specific offsets given
138 # that mouse cursor is at specified position
139 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
140 windowUtils = window
141 .QueryInterface(Ci.nsIInterfaceRequestor)
142 .getInterface(Ci.nsIDOMWindowUtils)
143
144 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
145 windowUtils.sendWheelEvent(
146 pX, pY, # Window offset (x, y) in pixels
147 deltaX, deltaY, 0, # Deltas (x, y, z)
148 mode, # Mode (pixel, line, page)
149 0, # Key Modifiers
150 0, 0, # Line or Page deltas (x, y)
151 0 # Options
152 )
153
154 # Write a string into system clipboard
155 writeToClipboard = (window, text) ->
156 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
157 str.data = text
158
159 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
160
161 if trans.init
162 privacyContext = window
163 .QueryInterface(Ci.nsIInterfaceRequestor)
164 .getInterface(Ci.nsIWebNavigation)
165 .QueryInterface(Ci.nsILoadContext)
166 trans.init(privacyContext)
167
168 trans.addDataFlavor('text/unicode')
169 trans.setTransferData('text/unicode', str, text.length * 2)
170
171 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
172
173 # Write a string into system clipboard
174 readFromClipboard = (window) ->
175 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
176
177 if trans.init
178 privacyContext = window
179 .QueryInterface(Ci.nsIInterfaceRequestor)
180 .getInterface(Ci.nsIWebNavigation)
181 .QueryInterface(Ci.nsILoadContext)
182 trans.init(privacyContext)
183
184 trans.addDataFlavor('text/unicode')
185
186 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
187
188 str = {}
189 strLength = {}
190
191 trans.getTransferData('text/unicode', str, strLength)
192
193 if str
194 str = str.value.QueryInterface(Ci.nsISupportsString)
195 return str.data.substring(0, strLength.value / 2)
196
197 return undefined
198
199 # Executes function `func` and mearues how much time it took
200 timeIt = (func, msg) ->
201 start = new Date().getTime()
202 result = func()
203 end = new Date().getTime()
204
205 console.log(msg, end - start)
206 return result
207
208 isBlacklisted = (str) ->
209 matchingRules = getMatchingBlacklistRules(str)
210 return (matchingRules.length != 0)
211
212 # Returns all rules in the blacklist that match the provided string
213 getMatchingBlacklistRules = (str) ->
214 matchingRules = []
215 for rule in getBlacklist()
216 # Wildcards: * and !
217 regexifiedRule = regexpEscape(rule).replace(/\\\*/g, '.*').replace(/!/g, '.')
218 if str.match(///^#{ regexifiedRule }$///)
219 matchingRules.push(rule)
220
221 return matchingRules
222
223 getBlacklist = ->
224 return splitBlacklistString(getPref('black_list'))
225
226 setBlacklist = (blacklist) ->
227 setPref('black_list', blacklist.join(', '))
228
229 splitBlacklistString = (str) ->
230 # Comma/space separated list
231 return str.split(/[\s,]+/)
232
233 updateBlacklist = ({ add, remove} = {}) ->
234 blacklist = getBlacklist()
235
236 if add
237 blacklist.push(splitBlacklistString(add)...)
238
239 blacklist = blacklist.filter((rule) -> rule != '')
240 blacklist = removeDuplicates(blacklist)
241
242 if remove
243 for rule in splitBlacklistString(remove) when rule in blacklist
244 blacklist.splice(blacklist.indexOf(rule), 1)
245
246 setBlacklist(blacklist)
247
248 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
249 getVersion = do ->
250 version = null
251
252 if version == null
253 scope = {}
254 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
255 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
256
257 return ->
258 return version
259
260 parseHTML = (document, html) ->
261 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
262 flags = parser.SanitizerAllowStyle
263 return parser.parseFragment(html, flags, false, null, document.documentElement)
264
265 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
266 isURL = (str) ->
267 try
268 url = Cc['@mozilla.org/network/io-service;1']
269 .getService(Ci.nsIIOService)
270 .newURI(str, null, null)
271 .QueryInterface(Ci.nsIURL)
272 return true
273 catch err
274 return false
275
276 # Use Firefox services to search for a given string
277 browserSearchSubmission = (str) ->
278 ss = Cc['@mozilla.org/browser/search-service;1']
279 .getService(Ci.nsIBrowserSearchService)
280
281 engine = ss.currentEngine or ss.defaultEngine
282 return engine.getSubmission(str, null)
283
284 # Get hint characters, convert them to lower case, and filter duplicates
285 getHintChars = ->
286 hintChars = getPref('hint_chars')
287 # Make sure that hint chars contain at least two characters
288 if hintChars.length < 2
289 hintChars = 'fj'
290
291 return removeDuplicateCharacters(hintChars)
292
293 # Remove duplicate characters from string (case insensitive)
294 removeDuplicateCharacters = (str) ->
295 return removeDuplicates( str.toLowerCase().split('') ).join('')
296
297 # Return URI to some file in the extension packaged as resource
298 getResourceURI = do ->
299 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
300 return (path) -> return Services.io.newURI(path, null, baseURI)
301
302 # Escape string to render it usable in regular expressions
303 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
304
305 removeDuplicates = (array) ->
306 seen = {}
307 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
308
309 # Returns elements that qualify as links
310 # Generates and memoizes an XPath query internally
311 getDomElements = (elements) ->
312 reduce = (m, rule) -> m.concat(["//#{ rule }", "//xhtml:#{ rule }"])
313 xpath = elements.reduce(reduce, []).join(' | ')
314
315 namespaceResolver = (namespace) ->
316 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
317
318 # The actual function that will return the desired elements
319 return (document, resultType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) ->
320 return document.evaluate(xpath, document.documentElement, namespaceResolver, resultType, null)
321
322 exports.Bucket = Bucket
323 exports.getEventWindow = getEventWindow
324 exports.getEventRootWindow = getEventRootWindow
325 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
326 exports.getRootWindow = getRootWindow
327 exports.getCurrentTabWindow = getCurrentTabWindow
328
329 exports.getWindowId = getWindowId
330 exports.blurActiveElement = blurActiveElement
331 exports.isTextInputElement = isTextInputElement
332 exports.isElementEditable = isElementEditable
333 exports.getSessionStore = getSessionStore
334
335 exports.loadCss = loadCss
336
337 exports.simulateClick = simulateClick
338 exports.simulateWheel = simulateWheel
339 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
340 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
341 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
342 exports.readFromClipboard = readFromClipboard
343 exports.writeToClipboard = writeToClipboard
344 exports.timeIt = timeIt
345
346 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
347 exports.isBlacklisted = isBlacklisted
348 exports.updateBlacklist = updateBlacklist
349
350 exports.getVersion = getVersion
351 exports.parseHTML = parseHTML
352 exports.isURL = isURL
353 exports.browserSearchSubmission = browserSearchSubmission
354 exports.getHintChars = getHintChars
355 exports.removeDuplicateCharacters = removeDuplicateCharacters
356 exports.getResourceURI = getResourceURI
357 exports.getDomElements = getDomElements
358 exports.ADDON_ID = ADDON_ID
Imprint / Impressum