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