]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Fix #190: Improve blacklisting UI
[VimFx.git] / extension / packages / utils.coffee
1 { unload } = require 'unload'
2 { getPref
3 , setPref
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 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
101 # by users often make the hint markers unreadable, for example. Just using `!important` in the
102 # CSS is not enough.
103 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
104 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
105
106 unload ->
107 sss.unregisterSheet(uri, sss.AGENT_SHEET)
108
109 # Simulate mouse click with full chain of event
110 # Copied from Vimium codebase
111 simulateClick = (element, modifiers) ->
112 document = element.ownerDocument
113 window = document.defaultView
114 modifiers ||= {}
115
116 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
117 for event in eventSequence
118 mouseEvent = document.createEvent('MouseEvents')
119 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
120 modifiers.metaKey, 0, null)
121 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
122 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
123 element.dispatchEvent(mouseEvent)
124
125 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
126 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
127 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
128
129 # Simulate mouse scroll event by specific offsets given
130 # that mouse cursor is at specified position
131 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
132 windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
133 .getInterface(Ci.nsIDOMWindowUtils)
134
135 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
136 windowUtils.sendWheelEvent(
137 pX, pY, # Window offset (x, y) in pixels
138 deltaX, deltaY, 0, # Deltas (x, y, z)
139 mode, # Mode (pixel, line, page)
140 0, # Key Modifiers
141 0, 0, # Line or Page deltas (x, y)
142 0 # Options
143 )
144
145 # Write a string into system clipboard
146 writeToClipboard = (window, text) ->
147 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
148 str.data = text
149
150 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
151
152 if trans.init
153 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
154 .getInterface(Ci.nsIWebNavigation)
155 .QueryInterface(Ci.nsILoadContext)
156 trans.init(privacyContext)
157
158 trans.addDataFlavor('text/unicode')
159 trans.setTransferData('text/unicode', str, text.length * 2)
160
161 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
162
163 # Write a string into system clipboard
164 readFromClipboard = (window) ->
165 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
166
167 if trans.init
168 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
169 .getInterface(Ci.nsIWebNavigation)
170 .QueryInterface(Ci.nsILoadContext)
171 trans.init(privacyContext)
172
173 trans.addDataFlavor('text/unicode')
174
175 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
176
177 str = {}
178 strLength = {}
179
180 trans.getTransferData('text/unicode', str, strLength)
181
182 if str
183 str = str.value.QueryInterface(Ci.nsISupportsString)
184 return str.data.substring(0, strLength.value / 2)
185
186 return undefined
187
188 # Executes function `func` and mearues how much time it took
189 timeIt = (func, msg) ->
190 start = new Date().getTime()
191 result = func()
192 end = new Date().getTime()
193
194 console.log(msg, end - start)
195 return result
196
197 # Checks if the string provided matches one of the black list entries
198 isBlacklisted = (str) ->
199 for rule in getBlacklist()
200 # Wildcards: * and !
201 regexifiedRule = rule.replace(/\*/g, '.*').replace(/!/g, '.')
202 if str.match(///^#{ regexifiedRule }$///)
203 return {blacklisted: true, matchedRule: rule}
204
205 return false
206
207 getBlacklist = ->
208 # Comma/space separated list
209 return getPref('black_list').split(/[\s,]+/)
210
211 setBlacklist = (blacklist) ->
212 setPref('black_list', blacklist.join(', '))
213
214 updateBlacklist = ({ add, remove} = {}) ->
215 blacklist = getBlacklist()
216
217 if add
218 blacklist.push(add)
219
220 # Remove duplicates and empty rules
221 seen = {}
222 blacklist = blacklist
223 .filter((rule) -> if seen[rule] or rule == '' then false else (seen[rule] = true))
224
225 if remove and remove in blacklist
226 blacklist.splice(blacklist.indexOf(remove), 1)
227
228 setBlacklist(blacklist)
229
230 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
231 getVersion = do ->
232 version = null
233
234 if version == null
235 scope = {}
236 addonId = getPref('addon_id')
237 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
238 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
239
240 return ->
241 return version
242
243 parseHTML = (document, html) ->
244 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
245 flags = parser.SanitizerAllowStyle
246 return parser.parseFragment(html, flags, false, null, document.documentElement)
247
248 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
249 isURL = (str) ->
250 try
251 url = Cc['@mozilla.org/network/io-service;1']
252 .getService(Ci.nsIIOService)
253 .newURI(str, null, null)
254 .QueryInterface(Ci.nsIURL)
255 return true
256 catch err
257 return false
258
259 # Use Firefox services to search for a given string
260 browserSearchSubmission = (str) ->
261 ss = Cc['@mozilla.org/browser/search-service;1']
262 .getService(Ci.nsIBrowserSearchService)
263
264 engine = ss.currentEngine or ss.defaultEngine
265 return engine.getSubmission(str, null)
266
267 # Get hint characters, convert them to lower case and fall back
268 # to default hint characters if there are less than 3 chars
269 getHintChars = ->
270 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
271 if hintChars.length < 2
272 hintChars = getDefaultPref('hint_chars')
273
274 return hintChars
275
276 # Remove duplicate characters from string (case insensitive)
277 removeDuplicateCharacters = (str) ->
278 seen = {}
279 return str
280 .toLowerCase()
281 .split('')
282 .filter((char) -> if seen[char] then false else (seen[char] = true))
283 .join('')
284
285 # Return URI to some file in the extension packaged as resource
286 getResourceURI = do ->
287 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
288 return (path) -> Services.io.newURI(path, null, baseURI)
289
290 # Escape string to render it usable in regular expressions
291 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
292
293 exports.Bucket = Bucket
294 exports.getCurrentTabWindow = getCurrentTabWindow
295 exports.getEventWindow = getEventWindow
296 exports.getEventRootWindow = getEventRootWindow
297 exports.getEventTabBrowser = getEventTabBrowser
298
299 exports.getWindowId = getWindowId
300 exports.getRootWindow = getRootWindow
301 exports.isTextInputElement = isTextInputElement
302 exports.isElementEditable = isElementEditable
303 exports.getSessionStore = getSessionStore
304
305 exports.loadCss = loadCss
306
307 exports.simulateClick = simulateClick
308 exports.simulateWheel = simulateWheel
309 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
310 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
311 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
312 exports.readFromClipboard = readFromClipboard
313 exports.writeToClipboard = writeToClipboard
314 exports.timeIt = timeIt
315
316 exports.isBlacklisted = isBlacklisted
317 exports.getBlacklist = getBlacklist
318 exports.setBlacklist = setBlacklist
319 exports.updateBlacklist = updateBlacklist
320
321 exports.getVersion = getVersion
322 exports.parseHTML = parseHTML
323 exports.isURL = isURL
324 exports.browserSearchSubmission = browserSearchSubmission
325 exports.getHintChars = getHintChars
326 exports.removeDuplicateCharacters = removeDuplicateCharacters
327 exports.getResourceURI = getResourceURI
328 exports.regexpEscape = regexpEscape
Imprint / Impressum