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