]> git.gir.st - VimFx.git/blob - extension/packages/utils.coffee
Update `command_paste` and `command_paste_tab`
[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 activeElement and 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.ownerDocument?.designMode?.toLowerCase() == 'on' or \
85 element.getAttribute?('g_editable') == 'true' or \
86 element.getAttribute?('contenteditable')?.toLowerCase() == 'true' or \
87 element.ownerDocument?.designMode?.toLowerCase() == 'on'
88
89 isElementVisible = (element) ->
90 document = element.ownerDocument
91 window = document.defaultView
92 if computedStyle = window.getComputedStyle(element, null)
93 return computedStyle.getPropertyValue('visibility') == 'visible' and \
94 computedStyle.getPropertyValue('display') != 'none' and \
95 computedStyle.getPropertyValue('opacity') != '0'
96
97 getWindowId = (window) ->
98 return window
99 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
100 .getInterface(Components.interfaces.nsIDOMWindowUtils)
101 .outerWindowID
102
103 getSessionStore = ->
104 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
105
106 # Function that returns a URI to the css file that's part of the extension
107 cssUri = do ->
108 (name) ->
109 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
110 uri = Services.io.newURI("resources/#{ name }.css", null, baseURI)
111 return uri
112
113 # Loads the css identified by the name in the StyleSheetService as User Stylesheet
114 # The stylesheet is then appended to every document, but it can be overwritten by
115 # any user css
116 loadCss = do ->
117 sss = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService)
118 return (name) ->
119 uri = cssUri(name)
120 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom website themes installed
121 # by users often make the hint markers unreadable, for example. Just using `!important` in the
122 # CSS is not enough.
123 if !sss.sheetRegistered(uri, sss.AGENT_SHEET)
124 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
125
126 unload ->
127 sss.unregisterSheet(uri, sss.AGENT_SHEET)
128
129 # Simulate mouse click with full chain of event
130 # Copied from Vimium codebase
131 simulateClick = (element, modifiers = {}) ->
132 document = element.ownerDocument
133 window = document.defaultView
134
135 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
136 for event in eventSequence
137 mouseEvent = document.createEvent('MouseEvents')
138 mouseEvent.initMouseEvent(event, true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, false, false,
139 modifiers.metaKey, 0, null)
140 # Debugging note: Firefox will not execute the element's default action if we dispatch this click event,
141 # but Webkit will. Dispatching a click on an input box does not seem to focus it; we do that separately
142 element.dispatchEvent(mouseEvent)
143
144 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
145 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
146 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
147
148 # Simulate mouse scroll event by specific offsets given
149 # that mouse cursor is at specified position
150 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
151 windowUtils = window
152 .QueryInterface(Ci.nsIInterfaceRequestor)
153 .getInterface(Ci.nsIDOMWindowUtils)
154
155 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
156 windowUtils.sendWheelEvent(
157 pX, pY, # Window offset (x, y) in pixels
158 deltaX, deltaY, 0, # Deltas (x, y, z)
159 mode, # Mode (pixel, line, page)
160 0, # Key Modifiers
161 0, 0, # Line or Page deltas (x, y)
162 0 # Options
163 )
164
165 # Write a string into system clipboard
166 writeToClipboard = (window, text) ->
167 str = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString)
168 str.data = text
169
170 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
171
172 if trans.init
173 privacyContext = window
174 .QueryInterface(Ci.nsIInterfaceRequestor)
175 .getInterface(Ci.nsIWebNavigation)
176 .QueryInterface(Ci.nsILoadContext)
177 trans.init(privacyContext)
178
179 trans.addDataFlavor('text/unicode')
180 trans.setTransferData('text/unicode', str, text.length * 2)
181
182 _clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard)
183
184 # Read the system clipboard
185 readFromClipboard = (window) ->
186 trans = Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable)
187
188 if trans.init
189 privacyContext = window
190 .QueryInterface(Ci.nsIInterfaceRequestor)
191 .getInterface(Ci.nsIWebNavigation)
192 .QueryInterface(Ci.nsILoadContext)
193 trans.init(privacyContext)
194
195 trans.addDataFlavor('text/unicode')
196
197 clip = Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard)
198 clip.getData(trans, Ci.nsIClipboard.kGlobalClipboard)
199
200 str = {}
201 strLength = {}
202
203 trans.getTransferData('text/unicode', str, strLength)
204
205 if str
206 str = str.value.QueryInterface(Ci.nsISupportsString)
207 return str.data.substring(0, strLength.value / 2)
208
209 return undefined
210
211 # Executes function `func` and mearues how much time it took
212 timeIt = (func, msg) ->
213 start = new Date().getTime()
214 result = func()
215 end = new Date().getTime()
216
217 console.log(msg, end - start)
218 return result
219
220 isBlacklisted = (str) ->
221 matchingRules = getMatchingBlacklistRules(str)
222 return (matchingRules.length != 0)
223
224 # Returns all rules in the blacklist that match the provided string
225 getMatchingBlacklistRules = (str) ->
226 return getBlacklist().filter((rule) -> /// ^#{ simpleWildcards(rule) }$ ///i.test(str))
227
228 getBlacklist = ->
229 return splitListString(getPref('black_list'))
230
231 setBlacklist = (blacklist) ->
232 setPref('black_list', blacklist.join(','))
233
234 updateBlacklist = ({ add, remove } = {}) ->
235 blacklist = getBlacklist()
236
237 if add
238 blacklist.push(splitListString(add)...)
239
240 blacklist = blacklist.filter((rule) -> rule != '')
241 blacklist = removeDuplicates(blacklist)
242
243 if remove
244 for rule in splitListString(remove) when rule in blacklist
245 blacklist.splice(blacklist.indexOf(rule), 1)
246
247 setBlacklist(blacklist)
248
249 # Splits a comma/space separated list into an array
250 splitListString = (str) ->
251 return str.split(/\s*,[\s,]*/)
252
253 # Prepares a string to be used in a regexp, where "*" matches zero or more characters
254 # and "!" matches one character.
255 simpleWildcards = (string) ->
256 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
257
258 # Returns the first element that matches a pattern, favoring earlier patterns.
259 # The patterns are `simpleWildcards`s and must match either in the beginning or
260 # at the end of the text of the element. Moreover, a pattern does not match in
261 # the middle of words, so "previous" does not match "previously". If that is
262 # desired, a pattern such as "previous*" can be used instead.
263 # Note: We cannot use `\b` word boundaries, because they don’t work well with
264 # non-English characters. Instead we match a space as word boundary. Therefore
265 # we normalize the whitespace and add spaces at the edges of the element text.
266 getBestPatternMatch = (patterns, elements) ->
267 for pattern in patterns
268 wildcarded = simpleWildcards(pattern)
269 regexp = /// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i
270 for element in elements
271 text = " #{ element.textContent } ".replace(/\s+/g, ' ')
272 if regexp.test(text)
273 return element
274
275 return null
276
277 # Gets VimFx verions. AddonManager only provides async API to access addon data, so it's a bit tricky...
278 getVersion = do ->
279 version = null
280
281 if version == null
282 scope = {}
283 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
284 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
285
286 return ->
287 return version
288
289 parseHTML = (document, html) ->
290 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
291 flags = parser.SanitizerAllowStyle
292 return parser.parseFragment(html, flags, false, null, document.documentElement)
293
294 createElement = (document, type, attributes = {}) ->
295 element = document.createElement(type)
296
297 for attribute, value of attributes
298 element.setAttribute(attribute, value)
299
300 if document instanceof HTMLDocument
301 element.classList.add('VimFxReset')
302
303 return element
304
305 # Uses nsIIOService to parse a string as a URL and find out if it is a URL
306 isURL = (str) ->
307 try
308 url = Cc['@mozilla.org/network/io-service;1']
309 .getService(Ci.nsIIOService)
310 .newURI(str, null, null)
311 .QueryInterface(Ci.nsIURL)
312 return true
313 catch err
314 return false
315
316 # Use Firefox services to search for a given string
317 browserSearchSubmission = (str) ->
318 ss = Cc['@mozilla.org/browser/search-service;1']
319 .getService(Ci.nsIBrowserSearchService)
320
321 engine = ss.currentEngine or ss.defaultEngine
322 return engine.getSubmission(str, null)
323
324 # Get hint characters, convert them to lower case, and filter duplicates
325 getHintChars = ->
326 hintChars = getPref('hint_chars')
327 # Make sure that hint chars contain at least two characters
328 if hintChars.length < 2
329 hintChars = 'fj'
330
331 return removeDuplicateCharacters(hintChars)
332
333 # Remove duplicate characters from string (case insensitive)
334 removeDuplicateCharacters = (str) ->
335 return removeDuplicates( str.toLowerCase().split('') ).join('')
336
337 # Return URI to some file in the extension packaged as resource
338 getResourceURI = do ->
339 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
340 return (path) -> return Services.io.newURI(path, null, baseURI)
341
342 # Escape string to render it usable in regular expressions
343 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
344
345 removeDuplicates = (array) ->
346 seen = {}
347 return array.filter((item) -> if seen[item] then false else (seen[item] = true))
348
349 ACTION_ELEMENT_TAGS = [
350 "a"
351 "area[@href]"
352 "button"
353 ]
354
355 ACTION_ELEMENT_PROPERTIES = [
356 "@onclick"
357 "@onmousedown"
358 "@onmouseup"
359 "@oncommand"
360 "@role='link'"
361 "@role='button'"
362 "contains(@class, 'button')"
363 "contains(@class, 'js-new-tweets-bar')"
364 ]
365
366 EDITABLE_ELEMENT_TAGS = [
367 "textarea"
368 "select"
369 "input[not(@type='hidden' or @disabled)]"
370 ]
371
372 EDITABLE_ELEMENT_PROPERTIES = [
373 "@contenteditable=''"
374 "translate(@contenteditable, 'TRUE', 'true')='true'"
375 ]
376
377 FOCUSABLE_ELEMENT_TAGS = [
378 "iframe"
379 "embed"
380 "object"
381 ]
382
383 FOCUSABLE_ELEMENT_PROPERTIES = [
384 "@tabindex"
385 ]
386
387 getMarkableElements = do ->
388 xpathify = (tags, properties)->
389 return tags
390 .concat("*[#{ properties.join(' or ') }]")
391 .map((rule) -> "//#{ rule } | //xhtml:#{ rule }")
392 .join(" | ")
393
394 xpaths =
395 action: xpathify(ACTION_ELEMENT_TAGS, ACTION_ELEMENT_PROPERTIES )
396 editable: xpathify(EDITABLE_ELEMENT_TAGS, EDITABLE_ELEMENT_PROPERTIES )
397 focusable: xpathify(FOCUSABLE_ELEMENT_TAGS, FOCUSABLE_ELEMENT_PROPERTIES)
398 all: xpathify(
399 [ACTION_ELEMENT_TAGS..., EDITABLE_ELEMENT_TAGS..., FOCUSABLE_ELEMENT_TAGS... ],
400 [ACTION_ELEMENT_PROPERTIES..., EDITABLE_ELEMENT_PROPERTIES..., FOCUSABLE_ELEMENT_PROPERTIES...]
401 )
402
403 namespaceResolver = (namespace) ->
404 if namespace == 'xhtml' then 'http://www.w3.org/1999/xhtml' else null
405
406 # The actual function that will return the desired elements
407 return (document, { type }, resultType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) ->
408 result = document.evaluate(xpaths[type], document.documentElement, namespaceResolver, resultType, null)
409 return (result.snapshotItem(i) for i in [0...result.snapshotLength] by 1)
410
411
412 exports.Bucket = Bucket
413 exports.getEventWindow = getEventWindow
414 exports.getEventRootWindow = getEventRootWindow
415 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
416 exports.getRootWindow = getRootWindow
417 exports.getCurrentTabWindow = getCurrentTabWindow
418
419 exports.getWindowId = getWindowId
420 exports.blurActiveElement = blurActiveElement
421 exports.isTextInputElement = isTextInputElement
422 exports.isElementEditable = isElementEditable
423 exports.isElementVisible = isElementVisible
424 exports.getSessionStore = getSessionStore
425
426 exports.loadCss = loadCss
427
428 exports.simulateClick = simulateClick
429 exports.simulateWheel = simulateWheel
430 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
431 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
432 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
433 exports.readFromClipboard = readFromClipboard
434 exports.writeToClipboard = writeToClipboard
435 exports.timeIt = timeIt
436
437 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
438 exports.isBlacklisted = isBlacklisted
439 exports.updateBlacklist = updateBlacklist
440 exports.splitListString = splitListString
441 exports.getBestPatternMatch = getBestPatternMatch
442
443 exports.getVersion = getVersion
444 exports.parseHTML = parseHTML
445 exports.createElement = createElement
446 exports.isURL = isURL
447 exports.browserSearchSubmission = browserSearchSubmission
448 exports.getHintChars = getHintChars
449 exports.removeDuplicates = removeDuplicates
450 exports.removeDuplicateCharacters = removeDuplicateCharacters
451 exports.getResourceURI = getResourceURI
452 exports.getMarkableElements = getMarkableElements
453 exports.ADDON_ID = ADDON_ID
Imprint / Impressum