]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Let un-blacklist remove _all_ matching rules
[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 getEventWindow = (event) ->
36 if event.originalTarget instanceof Window
37 return event.originalTarget
38 else
39 doc = event.originalTarget.ownerDocument or event.originalTarget
40 if doc instanceof HTMLDocument or doc instanceof XULDocument
41 return doc.defaultView
42
43 getEventRootWindow = (event) ->
44 return unless window = getEventWindow(event)
45 return getRootWindow(window)
46
47 getEventCurrentTabWindow = (event) ->
48 return unless rootWindow = getEventRootWindow(event)
49 return getCurrentTabWindow(rootWindow)
50
51 getRootWindow = (window) ->
52 return window.QueryInterface(Ci.nsIInterfaceRequestor)
53 .getInterface(Ci.nsIWebNavigation)
54 .QueryInterface(Ci.nsIDocShellTreeItem)
55 .rootTreeItem
56 .QueryInterface(Ci.nsIInterfaceRequestor)
57 .getInterface(Window)
58
59 getCurrentTabWindow = (window) ->
60 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
61
62 isTextInputElement = (element) ->
63 return element instanceof HTMLInputElement or \
64 element instanceof HTMLTextAreaElement
65
66 isElementEditable = (element) ->
67 return element.isContentEditable or \
68 element instanceof HTMLInputElement or \
69 element instanceof HTMLTextAreaElement or \
70 element instanceof HTMLSelectElement or \
71 element.getAttribute('g_editable') == 'true' or \
72 element.getAttribute('contenteditable')?.toLowerCase() == 'true' or \
73 element.ownerDocument?.designMode?.toLowerCase() == 'on'
74
75 getWindowId = (window) ->
76 return window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
77 .getInterface(Components.interfaces.nsIDOMWindowUtils)
78 .outerWindowID
79
80 getSessionStore = ->
81 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
82
83 # Function that returns a URI to the css file that's part of the extension
84 cssUri = do ->
85 (name) ->
86 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
87 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
88 return uri
89
90 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
91 # The stylesheet is then appended to every document, but it can be overwritten by
92 # any user css
93 loadCss = do ->
94 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
95 return (name) ->
96 uri = cssUri(name)
97 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
98 # by users often make the hint markers unreadable, for example. Just using `!important` in the
99 # CSS is not enough.
100 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
101 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
102
103 unload ->
104 sss.unregisterSheet(uri, sss.AGENT_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 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
123 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
124 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
125
126 # Simulate mouse scroll event by specific offsets given
127 # that mouse cursor is at specified position
128 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
129 windowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
130 .getInterface(Ci.nsIDOMWindowUtils)
131
132 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
133 windowUtils.sendWheelEvent(
134 pX, pY, # Window offset (x, y) in pixels
135 deltaX, deltaY, 0, # Deltas (x, y, z)
136 mode, # Mode (pixel, line, page)
137 0, # Key Modifiers
138 0, 0, # Line or Page deltas (x, y)
139 0 # Options
140 )
141
142 # Write a string into system clipboard
143 writeToClipboard = (window, text) ->
144 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
145 str.data = text
146
147 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
148
149 if trans.init
150 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
151 .getInterface(Ci.nsIWebNavigation)
152 .QueryInterface(Ci.nsILoadContext)
153 trans.init(privacyContext)
154
155 trans.addDataFlavor('text/unicode')
156 trans.setTransferData('text/unicode', str, text.length * 2)
157
158 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
159
160 # Write a string into system clipboard
161 readFromClipboard = (window) ->
162 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
163
164 if trans.init
165 privacyContext = window.QueryInterface(Ci.nsIInterfaceRequestor)
166 .getInterface(Ci.nsIWebNavigation)
167 .QueryInterface(Ci.nsILoadContext)
168 trans.init(privacyContext)
169
170 trans.addDataFlavor('text/unicode')
171
172 _clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
173
174 str = {}
175 strLength = {}
176
177 trans.getTransferData('text/unicode', str, strLength)
178
179 if str
180 str = str.value.QueryInterface(Ci.nsISupportsString)
181 return str.data.substring(0, strLength.value / 2)
182
183 return undefined
184
185 # Executes function `func` and mearues how much time it took
186 timeIt = (func, msg) ->
187 start = new Date().getTime()
188 result = func()
189 end = new Date().getTime()
190
191 console.log(msg, end - start)
192 return result
193
194 isBlacklisted = (str) ->
195 matchingRules = getMatchingBlacklistRules(str)
196 return (matchingRules.length != 0)
197
198 # Returns all rules in the blacklist that match the provided string
199 getMatchingBlacklistRules = (str) ->
200 matchingRules = []
201 for rule in getBlacklist()
202 # Wildcards: * and !
203 regexifiedRule = regexpEscape(rule).replace(/\\\*/g, '.*').replace(/!/g, '.')
204 if str.match(///^#{ regexifiedRule }$///)
205 matchingRules.push(rule)
206
207 return matchingRules
208
209 getBlacklist = ->
210 return splitBlacklistString(getPref('black_list'))
211
212 setBlacklist = (blacklist) ->
213 setPref('black_list', blacklist.join(', '))
214
215 splitBlacklistString = (str) ->
216 # Comma/space separated list
217 return str.split(/[\s,]+/)
218
219 updateBlacklist = ({ add, remove} = {}) ->
220 blacklist = getBlacklist()
221
222 if add
223 blacklist.push(splitBlacklistString(add)...)
224
225 blacklist = blacklist.filter((rule) -> rule != '')
226 blacklist = removeDuplicates(blacklist)
227
228 if remove
229 for rule in splitBlacklistString(remove) when rule in blacklist
230 blacklist.splice(blacklist.indexOf(rule), 1)
231
232 setBlacklist(blacklist)
233
234 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
235 getVersion = do ->
236 version = null
237
238 if version == null
239 scope = {}
240 addonId = getPref('addon_id')
241 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
242 scope.AddonManager.getAddonByID(addonId, (addon) -> version = addon.version)
243
244 return ->
245 return version
246
247 parseHTML = (document, html) ->
248 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
249 flags = parser.SanitizerAllowStyle
250 return parser.parseFragment(html, flags, false, null, document.documentElement)
251
252 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
253 isURL = (str) ->
254 try
255 url = Cc['@mozilla.org/network/io-service;1']
256 .getService(Ci.nsIIOService)
257 .newURI(str, null, null)
258 .QueryInterface(Ci.nsIURL)
259 return true
260 catch err
261 return false
262
263 # Use Firefox services to search for a given string
264 browserSearchSubmission = (str) ->
265 ss = Cc['@mozilla.org/browser/search-service;1']
266 .getService(Ci.nsIBrowserSearchService)
267
268 engine = ss.currentEngine or ss.defaultEngine
269 return engine.getSubmission(str, null)
270
271 # Get hint characters, convert them to lower case and fall back
272 # to default hint characters if there are less than 3 chars
273 getHintChars = ->
274 hintChars = removeDuplicateCharacters(getPref('hint_chars'))
275 if hintChars.length < 2
276 hintChars = getDefaultPref('hint_chars')
277
278 return hintChars
279
280 # Remove duplicate characters from string (case insensitive)
281 removeDuplicateCharacters = (str) ->
282 return removeDuplicates( str.toLowerCase().split('') ).join('')
283
284 # Return URI to some file in the extension packaged as resource
285 getResourceURI = do ->
286 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
287 return (path) -> Services.io.newURI(path, null, baseURI)
288
289 # Escape string to render it usable in regular expressions
290 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
291
292 removeDuplicates = (array) ->
293 seen = {}
294 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
295
296 exports.Bucket = Bucket
297 exports.getEventWindow = getEventWindow
298 exports.getEventRootWindow = getEventRootWindow
299 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
300 exports.getRootWindow = getRootWindow
301 exports.getCurrentTabWindow = getCurrentTabWindow
302
303 exports.getWindowId = getWindowId
304 exports.isTextInputElement = isTextInputElement
305 exports.isElementEditable = isElementEditable
306 exports.getSessionStore = getSessionStore
307
308 exports.loadCss = loadCss
309
310 exports.simulateClick = simulateClick
311 exports.simulateWheel = simulateWheel
312 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
313 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
314 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
315 exports.readFromClipboard = readFromClipboard
316 exports.writeToClipboard = writeToClipboard
317 exports.timeIt = timeIt
318
319 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
320 exports.isBlacklisted = isBlacklisted
321 exports.updateBlacklist = updateBlacklist
322
323 exports.getVersion = getVersion
324 exports.parseHTML = parseHTML
325 exports.isURL = isURL
326 exports.browserSearchSubmission = browserSearchSubmission
327 exports.getHintChars = getHintChars
328 exports.removeDuplicateCharacters = removeDuplicateCharacters
329 exports.getResourceURI = getResourceURI
330 exports.regexpEscape = regexpEscape
Imprint / Impressum