]> git.gir.st - VimFx.git/blob - extension/lib/utils.coffee
Treat the Youtube video player as an adjustable element
[VimFx.git] / extension / lib / utils.coffee
1 ###
2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
4 # Copyright Wang Zhuochun 2013.
5 #
6 # This file is part of VimFx.
7 #
8 # VimFx is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # VimFx is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
20 ###
21
22 notation = require('vim-like-key-notation')
23 { getPref
24 , setPref
25 } = require('./prefs')
26
27 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
28
29 { classes: Cc, interfaces: Ci, utils: Cu } = Components
30
31 Window = Ci.nsIDOMWindow
32 ChromeWindow = Ci.nsIDOMChromeWindow
33 Element = Ci.nsIDOMElement
34 HTMLDocument = Ci.nsIDOMHTMLDocument
35 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
36 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
37 HTMLInputElement = Ci.nsIDOMHTMLInputElement
38 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
39 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
40 XULDocument = Ci.nsIDOMXULDocument
41 XULButtonElement = Ci.nsIDOMXULButtonElement
42 XULControlElement = Ci.nsIDOMXULControlElement
43 XULMenuListElement = Ci.nsIDOMXULMenuListElement
44 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
45
46 class Bucket
47 constructor: (@newFunc) ->
48 @bucket = new WeakMap()
49
50 get: (obj) ->
51 if @bucket.has(obj)
52 return @bucket.get(obj)
53 else
54 value = @newFunc(obj)
55 @bucket.set(obj, value)
56 return value
57
58 forget: (obj) ->
59 @bucket.delete(obj)
60
61 getEventWindow = (event) ->
62 if event.originalTarget instanceof Window
63 return event.originalTarget
64 else
65 doc = event.originalTarget.ownerDocument or event.originalTarget
66 if doc instanceof HTMLDocument or doc instanceof XULDocument
67 return doc.defaultView
68
69 getEventRootWindow = (event) ->
70 return unless window = getEventWindow(event)
71 return getRootWindow(window)
72
73 getEventCurrentTabWindow = (event) ->
74 return unless rootWindow = getEventRootWindow(event)
75 return getCurrentTabWindow(rootWindow)
76
77 getRootWindow = (window) ->
78 return window
79 .QueryInterface(Ci.nsIInterfaceRequestor)
80 .getInterface(Ci.nsIWebNavigation)
81 .QueryInterface(Ci.nsIDocShellTreeItem)
82 .rootTreeItem
83 .QueryInterface(Ci.nsIInterfaceRequestor)
84 .getInterface(Window)
85
86 getCurrentTabWindow = (window) ->
87 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
88
89 blurActiveElement = (window) ->
90 # Only blur focusable elements, in order to interfere with the browser as
91 # little as possible.
92 { activeElement } = window.document
93 if activeElement and activeElement.tabIndex > -1
94 activeElement.blur()
95
96 isProperLink = (element) ->
97 return element.hasAttribute('href') and
98 (element instanceof HTMLAnchorElement or
99 element.ownerDocument instanceof XULDocument) and
100 not element.href.endsWith('#') and
101 not element.href.startsWith('javascript:')
102
103 isTextInputElement = (element) ->
104 return (element instanceof HTMLInputElement and element.type in [
105 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
106 ]) or
107 element instanceof HTMLTextAreaElement or
108 # `<select>` elements can also receive text input: You may type the
109 # text of an item to select it.
110 element instanceof HTMLSelectElement or
111 element instanceof XULMenuListElement or
112 element instanceof XULTextBoxElement
113
114 isContentEditable = (element) ->
115 return element.isContentEditable or
116 isGoogleEditable(element)
117
118 isGoogleEditable = (element) ->
119 # `g_editable` is a non-standard attribute commonly used by Google.
120 return element.getAttribute?('g_editable') == 'true' or
121 element.ownerDocument.body?.getAttribute('g_editable') == 'true'
122
123 isActivatable = (element) ->
124 return element instanceof HTMLAnchorElement or
125 element instanceof HTMLButtonElement or
126 (element instanceof HTMLInputElement and element.type in [
127 'button', 'submit', 'reset', 'image'
128 ]) or
129 element instanceof XULButtonElement
130
131 isAdjustable = (element) ->
132 return element instanceof HTMLInputElement and element.type in [
133 'checkbox', 'radio', 'file', 'color'
134 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
135 ] or
136 element instanceof XULControlElement or
137 # Youtube special case.
138 element.classList?.contains('html5-video-player') or
139 element.classList?.contains('ytp-button')
140
141 area = (element) ->
142 return element.clientWidth * element.clientHeight
143
144 getSessionStore = ->
145 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
146
147 loadCss = do ->
148 sss = Cc['@mozilla.org/content/style-sheet-service;1']
149 .getService(Ci.nsIStyleSheetService)
150 return (name) ->
151 uri = getResourceURI("resources/#{ name }.css")
152 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
153 # website themes installed by users often make the hint markers unreadable,
154 # for example. Just using `!important` in the CSS is not enough.
155 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
156 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
157
158 module.onShutdown(->
159 sss.unregisterSheet(uri, sss.AGENT_SHEET)
160 )
161
162 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
163 # memory. This approach is better than for example setting `event.simulated =
164 # true`, since that tells the sites that the click was simulated, and allows
165 # sites to spoof it.
166 simulated_events = new WeakMap()
167
168 # Simulate mouse click with a full chain of events. ('command' is for XUL
169 # elements.)
170 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click', 'command']
171 simulateClick = (element) ->
172 window = element.ownerDocument.defaultView
173 for type in eventSequence
174 mouseEvent = new window.MouseEvent(type, {
175 # Let the event bubble in order to trigger delegated event listeners.
176 bubbles: true
177 })
178 element.dispatchEvent(mouseEvent)
179
180 isEventSimulated = (event) ->
181 return simulated_events.has(event)
182
183 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
184 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
185 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
186
187 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
188 # specified position.
189 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
190 windowUtils = window
191 .QueryInterface(Ci.nsIInterfaceRequestor)
192 .getInterface(Ci.nsIDOMWindowUtils)
193
194 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
195 windowUtils.sendWheelEvent(
196 pX, pY, # Window offset (x, y) in pixels.
197 deltaX, deltaY, 0, # Deltas (x, y, z).
198 mode, # Mode (pixel, line, page).
199 0, # Key Modifiers.
200 0, 0, # Line or Page deltas (x, y).
201 0 # Options.
202 )
203
204 # Write a string to the system clipboard.
205 writeToClipboard = (text) ->
206 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
207 .getService(Ci.nsIClipboardHelper)
208 clipboardHelper.copyString(text)
209
210 # Executes function `func` and mearues how much time it took.
211 timeIt = (func, name) ->
212 console.time(name)
213 result = func()
214 console.timeEnd(name)
215 return result
216
217 isBlacklisted = (str) ->
218 matchingRules = getMatchingBlacklistRules(str)
219 return (matchingRules.length != 0)
220
221 # Returns all blacklisted keys in matching rules.
222 getBlacklistedKeys = (str) ->
223 matchingRules = getMatchingBlacklistRules(str)
224 blacklistedKeys = []
225 for rule in matchingRules when /##/.test(rule)
226 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
227 return blacklistedKeys
228
229 # Returns all rules in the blacklist that match the provided string.
230 getMatchingBlacklistRules = (str) ->
231 return getBlacklist().filter((rule) ->
232 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
233 )
234
235 getBlacklist = ->
236 return splitListString(getPref('black_list'))
237
238 setBlacklist = (blacklist) ->
239 setPref('black_list', blacklist.join(','))
240
241 updateBlacklist = ({ add, remove } = {}) ->
242 blacklist = getBlacklist()
243
244 if add
245 blacklist.push(splitListString(add)...)
246
247 blacklist = blacklist.filter((rule) -> rule != '')
248 blacklist = removeDuplicates(blacklist)
249
250 if remove
251 for rule in splitListString(remove) when rule in blacklist
252 blacklist.splice(blacklist.indexOf(rule), 1)
253
254 setBlacklist(blacklist)
255
256 # Splits a comma/space separated list into an array.
257 splitListString = (str) ->
258 return str.split(/\s*,[\s,]*/)
259
260 # Prepares a string to be used in a regexp, where "*" matches zero or more
261 # characters and "!" matches one character.
262 simpleWildcards = (string) ->
263 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
264
265 # Returns the first element that matches a pattern, favoring earlier patterns.
266 # The patterns are case insensitive `simpleWildcards`s and must match either in
267 # the beginning or at the end of a string. Moreover, a pattern does not match
268 # in the middle of words, so "previous" does not match "previously". If that is
269 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
270 # use `\b` word boundaries, because they don’t work well with non-English
271 # characters. Instead we match a space as word boundary. Therefore we normalize
272 # the whitespace and add spaces at the edges of the element text.
273 getBestPatternMatch = (patterns, attrs, elements) ->
274 regexps = []
275 for pattern in patterns
276 wildcarded = simpleWildcards(pattern)
277 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
278
279 # Helper function that matches a string against all the patterns.
280 matches = (text) ->
281 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
282 for re in regexps
283 if re.test(normalizedText)
284 return true
285 return false
286
287 # First search in attributes (favoring earlier attributes) as it's likely
288 # that they are more specific than text contexts.
289 for attr in attrs
290 for element in elements
291 if matches(element.getAttribute(attr))
292 return element
293
294 # Then search in element contents.
295 for element in elements
296 if matches(element.textContent)
297 return element
298
299 return null
300
301 # Get VimFx verion. AddonManager only provides async API to access addon data,
302 # so it's a bit tricky...
303 getVersion = do ->
304 version = null
305
306 scope = {}
307 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
308 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
309
310 return ->
311 return version
312
313 parseHTML = (document, html) ->
314 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
315 flags = parser.SanitizerAllowStyle
316 return parser.parseFragment(html, flags, false, null,
317 document.documentElement)
318
319 escapeHTML = (s) ->
320 return s
321 .replace(/&/g, '&amp;')
322 .replace(/</g, '&lt;')
323 .replace(/>/g, '&gt;')
324 .replace(/"/g, '&quot;')
325 .replace(/'/g, '&apos;')
326
327 createElement = (document, type, attributes = {}) ->
328 element = document.createElement(type)
329
330 for attribute, value of attributes
331 element.setAttribute(attribute, value)
332
333 if document instanceof HTMLDocument
334 element.classList.add('VimFxReset')
335
336 return element
337
338 getAllElements = (document) -> switch
339 when document instanceof HTMLDocument
340 return document.getElementsByTagName('*')
341 when document instanceof XULDocument
342 elements = []
343 getAllRegular = (element) ->
344 for child in element.getElementsByTagName('*')
345 elements.push(child)
346 getAllAnonymous(child)
347 return
348 getAllAnonymous = (element) ->
349 for child in document.getAnonymousNodes(element) or []
350 continue unless child instanceof Element
351 elements.push(child)
352 getAllRegular(child)
353 return
354 getAllRegular(document.documentElement)
355 return elements
356
357 isURL = (str) ->
358 try
359 url = Cc['@mozilla.org/network/io-service;1']
360 .getService(Ci.nsIIOService)
361 .newURI(str, null, null)
362 .QueryInterface(Ci.nsIURL)
363 return true
364 catch err
365 return false
366
367 # Use Firefox services to search for a given string.
368 browserSearchSubmission = (str) ->
369 ss = Cc['@mozilla.org/browser/search-service;1']
370 .getService(Ci.nsIBrowserSearchService)
371
372 engine = ss.currentEngine or ss.defaultEngine
373 return engine.getSubmission(str, null)
374
375 openTab = (rootWindow, url, options) ->
376 { gBrowser } = rootWindow
377 rootWindow.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
378 gBrowser.loadOneTab(url, options)
379
380 normalizedKey = (key) -> key.map(notation.normalize).join('')
381
382 # Get hint characters, convert them to lower case, and filter duplicates.
383 getHintChars = ->
384 hintChars = getPref('hint_chars')
385 # Make sure that hint chars contain at least two characters.
386 if not hintChars or hintChars.length < 2
387 hintChars = 'fj'
388
389 return removeDuplicateCharacters(hintChars)
390
391 # Remove duplicate characters from string (case insensitive).
392 removeDuplicateCharacters = (str) ->
393 return removeDuplicates( str.toLowerCase().split('') ).join('')
394
395 # Return URI to some file in the extension packaged as resource.
396 getResourceURI = do ->
397 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
398 return (path) -> return Services.io.newURI(path, null, baseURI)
399
400 # Escape a string to render it usable in regular expressions.
401 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
402
403 removeDuplicates = (array) ->
404 # coffeelint: disable=no_backticks
405 return `[...new Set(array)]`
406 # coffeelint: enable=no_backticks
407
408 exports.Bucket = Bucket
409 exports.getEventWindow = getEventWindow
410 exports.getEventRootWindow = getEventRootWindow
411 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
412 exports.getRootWindow = getRootWindow
413 exports.getCurrentTabWindow = getCurrentTabWindow
414
415 exports.blurActiveElement = blurActiveElement
416 exports.isProperLink = isProperLink
417 exports.isTextInputElement = isTextInputElement
418 exports.isContentEditable = isContentEditable
419 exports.isActivatable = isActivatable
420 exports.isAdjustable = isAdjustable
421 exports.area = area
422 exports.getSessionStore = getSessionStore
423
424 exports.loadCss = loadCss
425
426 exports.simulateClick = simulateClick
427 exports.isEventSimulated = isEventSimulated
428 exports.simulateWheel = simulateWheel
429 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
430 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
431 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
432 exports.writeToClipboard = writeToClipboard
433 exports.timeIt = timeIt
434
435 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
436 exports.isBlacklisted = isBlacklisted
437 exports.getBlacklistedKeys = getBlacklistedKeys
438 exports.updateBlacklist = updateBlacklist
439 exports.splitListString = splitListString
440 exports.getBestPatternMatch = getBestPatternMatch
441
442 exports.getVersion = getVersion
443 exports.parseHTML = parseHTML
444 exports.escapeHTML = escapeHTML
445 exports.createElement = createElement
446 exports.getAllElements = getAllElements
447 exports.isURL = isURL
448 exports.browserSearchSubmission = browserSearchSubmission
449 exports.openTab = openTab
450 exports.normalizedKey = normalizedKey
451 exports.getHintChars = getHintChars
452 exports.removeDuplicates = removeDuplicates
453 exports.removeDuplicateCharacters = removeDuplicateCharacters
454 exports.getResourceURI = getResourceURI
455 exports.ADDON_ID = ADDON_ID
Imprint / Impressum