]> git.gir.st - VimFx.git/blob - extension/lib/utils.coffee
Improve placement of hint markers when zoomed
[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 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
98 # href="">`s used as buttons on some sites.
99 return element.getAttribute('href') and
100 (element instanceof HTMLAnchorElement or
101 element.ownerDocument instanceof XULDocument) and
102 not element.href.endsWith('#') and
103 not element.href.startsWith('javascript:')
104
105 isTextInputElement = (element) ->
106 return (element instanceof HTMLInputElement and element.type in [
107 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
108 ]) or
109 element instanceof HTMLTextAreaElement or
110 # `<select>` elements can also receive text input: You may type the
111 # text of an item to select it.
112 element instanceof HTMLSelectElement or
113 element instanceof XULMenuListElement or
114 element instanceof XULTextBoxElement
115
116 isContentEditable = (element) ->
117 return element.isContentEditable or
118 isGoogleEditable(element)
119
120 isGoogleEditable = (element) ->
121 # `g_editable` is a non-standard attribute commonly used by Google.
122 return element.getAttribute?('g_editable') == 'true' or
123 element.ownerDocument.body?.getAttribute('g_editable') == 'true'
124
125 isActivatable = (element) ->
126 return element instanceof HTMLAnchorElement or
127 element instanceof HTMLButtonElement or
128 (element instanceof HTMLInputElement and element.type in [
129 'button', 'submit', 'reset', 'image'
130 ]) or
131 element instanceof XULButtonElement
132
133 isAdjustable = (element) ->
134 return element instanceof HTMLInputElement and element.type in [
135 'checkbox', 'radio', 'file', 'color'
136 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
137 ] or
138 element instanceof XULControlElement or
139 # Youtube special case.
140 element.classList?.contains('html5-video-player') or
141 element.classList?.contains('ytp-button')
142
143 area = (element) ->
144 return element.clientWidth * element.clientHeight
145
146 getSessionStore = ->
147 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
148
149 loadCss = do ->
150 sss = Cc['@mozilla.org/content/style-sheet-service;1']
151 .getService(Ci.nsIStyleSheetService)
152 return (name) ->
153 uri = getResourceURI("resources/#{ name }.css")
154 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
155 # website themes installed by users often make the hint markers unreadable,
156 # for example. Just using `!important` in the CSS is not enough.
157 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
158 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
159
160 module.onShutdown(->
161 sss.unregisterSheet(uri, sss.AGENT_SHEET)
162 )
163
164 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
165 # memory. This approach is better than for example setting `event.simulated =
166 # true`, since that tells the sites that the click was simulated, and allows
167 # sites to spoof it.
168 simulated_events = new WeakMap()
169
170 # Simulate mouse click with a full chain of events. ('command' is for XUL
171 # elements.)
172 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click', 'command']
173 simulateClick = (element) ->
174 window = element.ownerDocument.defaultView
175 for type in eventSequence
176 mouseEvent = new window.MouseEvent(type, {
177 # Let the event bubble in order to trigger delegated event listeners.
178 bubbles: true
179 # Make the event cancelable so that `<a href="#">` can be used as a
180 # JavaScript-powered button without scrolling to the top of the page.
181 cancelable: true
182 })
183 element.dispatchEvent(mouseEvent)
184
185 isEventSimulated = (event) ->
186 return simulated_events.has(event)
187
188 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
189 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
190 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
191
192 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
193 # specified position.
194 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
195 windowUtils = window
196 .QueryInterface(Ci.nsIInterfaceRequestor)
197 .getInterface(Ci.nsIDOMWindowUtils)
198
199 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
200 windowUtils.sendWheelEvent(
201 pX, pY, # Window offset (x, y) in pixels.
202 deltaX, deltaY, 0, # Deltas (x, y, z).
203 mode, # Mode (pixel, line, page).
204 0, # Key Modifiers.
205 0, 0, # Line or Page deltas (x, y).
206 0 # Options.
207 )
208
209 # Write a string to the system clipboard.
210 writeToClipboard = (text) ->
211 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
212 .getService(Ci.nsIClipboardHelper)
213 clipboardHelper.copyString(text)
214
215 # Executes function `func` and measures how much time it took.
216 timeIt = (func, name) ->
217 console.time(name)
218 result = func()
219 console.timeEnd(name)
220 return result
221
222 isBlacklisted = (str) ->
223 matchingRules = getMatchingBlacklistRules(str)
224 return (matchingRules.length != 0)
225
226 # Returns all blacklisted keys in matching rules.
227 getBlacklistedKeys = (str) ->
228 matchingRules = getMatchingBlacklistRules(str)
229 blacklistedKeys = []
230 for rule in matchingRules when /##/.test(rule)
231 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
232 return blacklistedKeys
233
234 # Returns all rules in the blacklist that match the provided string.
235 getMatchingBlacklistRules = (str) ->
236 return getBlacklist().filter((rule) ->
237 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
238 )
239
240 getBlacklist = ->
241 return splitListString(getPref('black_list'))
242
243 setBlacklist = (blacklist) ->
244 setPref('black_list', blacklist.join(','))
245
246 updateBlacklist = ({ add, remove } = {}) ->
247 blacklist = getBlacklist()
248
249 if add
250 blacklist.push(splitListString(add)...)
251
252 blacklist = blacklist.filter((rule) -> rule != '')
253 blacklist = removeDuplicates(blacklist)
254
255 if remove
256 for rule in splitListString(remove) when rule in blacklist
257 blacklist.splice(blacklist.indexOf(rule), 1)
258
259 setBlacklist(blacklist)
260
261 # Splits a comma/space separated list into an array.
262 splitListString = (str) ->
263 return str.split(/\s*,[\s,]*/)
264
265 # Prepares a string to be used in a regexp, where "*" matches zero or more
266 # characters and "!" matches one character.
267 simpleWildcards = (string) ->
268 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
269
270 # Returns the first element that matches a pattern, favoring earlier patterns.
271 # The patterns are case insensitive `simpleWildcards`s and must match either in
272 # the beginning or at the end of a string. Moreover, a pattern does not match
273 # in the middle of words, so "previous" does not match "previously". If that is
274 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
275 # use `\b` word boundaries, because they don’t work well with non-English
276 # characters. Instead we match a space as word boundary. Therefore we normalize
277 # the whitespace and add spaces at the edges of the element text.
278 getBestPatternMatch = (patterns, attrs, elements) ->
279 regexps = []
280 for pattern in patterns
281 wildcarded = simpleWildcards(pattern)
282 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
283
284 # Helper function that matches a string against all the patterns.
285 matches = (text) ->
286 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
287 for re in regexps
288 if re.test(normalizedText)
289 return true
290 return false
291
292 # First search in attributes (favoring earlier attributes) as it's likely
293 # that they are more specific than text contexts.
294 for attr in attrs
295 for element in elements
296 if matches(element.getAttribute(attr))
297 return element
298
299 # Then search in element contents.
300 for element in elements
301 if matches(element.textContent)
302 return element
303
304 return null
305
306 # Get VimFx verion. AddonManager only provides async API to access addon data,
307 # so it's a bit tricky...
308 getVersion = do ->
309 version = null
310
311 scope = {}
312 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
313 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
314
315 return ->
316 return version
317
318 parseHTML = (document, html) ->
319 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
320 flags = parser.SanitizerAllowStyle
321 return parser.parseFragment(html, flags, false, null,
322 document.documentElement)
323
324 escapeHTML = (s) ->
325 return s
326 .replace(/&/g, '&amp;')
327 .replace(/</g, '&lt;')
328 .replace(/>/g, '&gt;')
329 .replace(/"/g, '&quot;')
330 .replace(/'/g, '&apos;')
331
332 createElement = (document, type, attributes = {}) ->
333 element = document.createElement(type)
334
335 for attribute, value of attributes
336 element.setAttribute(attribute, value)
337
338 if document instanceof HTMLDocument
339 element.classList.add('VimFxReset')
340
341 return element
342
343 isURL = (str) ->
344 try
345 url = Cc['@mozilla.org/network/io-service;1']
346 .getService(Ci.nsIIOService)
347 .newURI(str, null, null)
348 .QueryInterface(Ci.nsIURL)
349 return true
350 catch err
351 return false
352
353 # Use Firefox services to search for a given string.
354 browserSearchSubmission = (str) ->
355 ss = Cc['@mozilla.org/browser/search-service;1']
356 .getService(Ci.nsIBrowserSearchService)
357
358 engine = ss.currentEngine or ss.defaultEngine
359 return engine.getSubmission(str, null)
360
361 openTab = (rootWindow, url, options) ->
362 { gBrowser } = rootWindow
363 rootWindow.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
364 gBrowser.loadOneTab(url, options)
365
366 normalizedKey = (key) -> key.map(notation.normalize).join('')
367
368 # Get hint characters, convert them to lower case, and filter duplicates.
369 getHintChars = ->
370 hintChars = getPref('hint_chars')
371 # Make sure that hint chars contain at least two characters.
372 if not hintChars or hintChars.length < 2
373 hintChars = 'fj'
374
375 return removeDuplicateCharacters(hintChars)
376
377 # Remove duplicate characters from string (case insensitive).
378 removeDuplicateCharacters = (str) ->
379 return removeDuplicates( str.toLowerCase().split('') ).join('')
380
381 # Return URI to some file in the extension packaged as resource.
382 getResourceURI = do ->
383 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
384 return (path) -> return Services.io.newURI(path, null, baseURI)
385
386 # Escape a string to render it usable in regular expressions.
387 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
388
389 removeDuplicates = (array) ->
390 # coffeelint: disable=no_backticks
391 return `[...new Set(array)]`
392 # coffeelint: enable=no_backticks
393
394 exports.Bucket = Bucket
395 exports.getEventWindow = getEventWindow
396 exports.getEventRootWindow = getEventRootWindow
397 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
398 exports.getRootWindow = getRootWindow
399 exports.getCurrentTabWindow = getCurrentTabWindow
400
401 exports.blurActiveElement = blurActiveElement
402 exports.isProperLink = isProperLink
403 exports.isTextInputElement = isTextInputElement
404 exports.isContentEditable = isContentEditable
405 exports.isActivatable = isActivatable
406 exports.isAdjustable = isAdjustable
407 exports.area = area
408 exports.getSessionStore = getSessionStore
409
410 exports.loadCss = loadCss
411
412 exports.simulateClick = simulateClick
413 exports.isEventSimulated = isEventSimulated
414 exports.simulateWheel = simulateWheel
415 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
416 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
417 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
418 exports.writeToClipboard = writeToClipboard
419 exports.timeIt = timeIt
420
421 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
422 exports.isBlacklisted = isBlacklisted
423 exports.getBlacklistedKeys = getBlacklistedKeys
424 exports.updateBlacklist = updateBlacklist
425 exports.splitListString = splitListString
426 exports.getBestPatternMatch = getBestPatternMatch
427
428 exports.getVersion = getVersion
429 exports.parseHTML = parseHTML
430 exports.escapeHTML = escapeHTML
431 exports.createElement = createElement
432 exports.isURL = isURL
433 exports.browserSearchSubmission = browserSearchSubmission
434 exports.openTab = openTab
435 exports.normalizedKey = normalizedKey
436 exports.getHintChars = getHintChars
437 exports.removeDuplicates = removeDuplicates
438 exports.removeDuplicateCharacters = removeDuplicateCharacters
439 exports.getResourceURI = getResourceURI
440 exports.ADDON_ID = ADDON_ID
Imprint / Impressum