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