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