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