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