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