2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014.
4 # Copyright Wang Zhuochun 2013.
6 # This file is part of VimFx.
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.
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.
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/>.
22 notation = require('vim-like-key-notation')
25 } = require('./prefs')
27 ADDON_ID = 'VimFx@akhodakivskiy.github.com'
29 { classes: Cc, interfaces: Ci, utils: Cu } = Components
31 Window = Ci.nsIDOMWindow
32 ChromeWindow = Ci.nsIDOMChromeWindow
33 Element = Ci.nsIDOMElement
34 HTMLDocument = Ci.nsIDOMHTMLDocument
35 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
36 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
37 HTMLInputElement = Ci.nsIDOMHTMLInputElement
38 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
39 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
40 XULDocument = Ci.nsIDOMXULDocument
41 XULButtonElement = Ci.nsIDOMXULButtonElement
42 XULControlElement = Ci.nsIDOMXULControlElement
43 XULMenuListElement = Ci.nsIDOMXULMenuListElement
44 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
47 constructor: (@newFunc) ->
48 @bucket = new WeakMap()
52 return @bucket.get(obj)
55 @bucket.set(obj, value)
61 getEventWindow = (event) ->
62 if event.originalTarget instanceof Window
63 return event.originalTarget
65 doc = event.originalTarget.ownerDocument or event.originalTarget
66 if doc instanceof HTMLDocument or doc instanceof XULDocument
67 return doc.defaultView
69 getEventRootWindow = (event) ->
70 return unless window = getEventWindow(event)
71 return getRootWindow(window)
73 getEventCurrentTabWindow = (event) ->
74 return unless rootWindow = getEventRootWindow(event)
75 return getCurrentTabWindow(rootWindow)
77 getRootWindow = (window) ->
79 .QueryInterface(Ci.nsIInterfaceRequestor)
80 .getInterface(Ci.nsIWebNavigation)
81 .QueryInterface(Ci.nsIDocShellTreeItem)
83 .QueryInterface(Ci.nsIInterfaceRequestor)
86 getCurrentTabWindow = (window) ->
87 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
89 blurActiveElement = (window) ->
90 # Only blur focusable elements, in order to interfere with the browser as
92 { activeElement } = window.document
93 if activeElement and activeElement.tabIndex > -1
96 isProperLink = (element) ->
97 return element.hasAttribute('href') and
98 (element instanceof HTMLAnchorElement or
99 element.ownerDocument instanceof XULDocument) and
100 not element.href.endsWith('#') and
101 not element.href.startsWith('javascript:')
103 isTextInputElement = (element) ->
104 return (element instanceof HTMLInputElement and element.type in [
105 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
107 element instanceof HTMLTextAreaElement or
108 # `<select>` elements can also receive text input: You may type the
109 # text of an item to select it.
110 element instanceof HTMLSelectElement or
111 element instanceof XULMenuListElement or
112 element instanceof XULTextBoxElement
114 isContentEditable = (element) ->
115 return element.isContentEditable or
116 isGoogleEditable(element)
118 isGoogleEditable = (element) ->
119 # `g_editable` is a non-standard attribute commonly used by Google.
120 return element.getAttribute?('g_editable') == 'true' or
121 element.ownerDocument.body?.getAttribute('g_editable') == 'true'
123 isActivatable = (element) ->
124 return element instanceof HTMLAnchorElement or
125 element instanceof HTMLButtonElement or
126 (element instanceof HTMLInputElement and element.type in [
127 'button', 'submit', 'reset', 'image'
129 element instanceof XULButtonElement
131 isAdjustable = (element) ->
132 return element instanceof HTMLInputElement and element.type in [
133 'checkbox', 'radio', 'file', 'color'
134 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
136 element instanceof XULControlElement or
137 # Youtube special case.
138 element.classList?.contains('html5-video-player') or
139 element.classList?.contains('ytp-button')
142 return element.clientWidth * element.clientHeight
145 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
148 sss = Cc['@mozilla.org/content/style-sheet-service;1']
149 .getService(Ci.nsIStyleSheetService)
151 uri = getResourceURI("resources/#{ name }.css")
152 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
153 # website themes installed by users often make the hint markers unreadable,
154 # for example. Just using `!important` in the CSS is not enough.
155 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
156 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
159 sss.unregisterSheet(uri, sss.AGENT_SHEET)
162 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
163 # memory. This approach is better than for example setting `event.simulated =
164 # true`, since that tells the sites that the click was simulated, and allows
166 simulated_events = new WeakMap()
168 # Simulate mouse click with a full chain of events. ('command' is for XUL
170 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click', 'command']
171 simulateClick = (element) ->
172 window = element.ownerDocument.defaultView
173 for type in eventSequence
174 mouseEvent = new window.MouseEvent(type, {
175 # Let the event bubble in order to trigger delegated event listeners.
177 # Make the event cancelable so that `<a href="#">` can be used as a
178 # JavaScript-powered button without scrolling to the top of the page.
181 element.dispatchEvent(mouseEvent)
183 isEventSimulated = (event) ->
184 return simulated_events.has(event)
186 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
187 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
188 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
190 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
191 # specified position.
192 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
194 .QueryInterface(Ci.nsIInterfaceRequestor)
195 .getInterface(Ci.nsIDOMWindowUtils)
197 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
198 windowUtils.sendWheelEvent(
199 pX, pY, # Window offset (x, y) in pixels.
200 deltaX, deltaY, 0, # Deltas (x, y, z).
201 mode, # Mode (pixel, line, page).
203 0, 0, # Line or Page deltas (x, y).
207 # Write a string to the system clipboard.
208 writeToClipboard = (text) ->
209 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
210 .getService(Ci.nsIClipboardHelper)
211 clipboardHelper.copyString(text)
213 # Executes function `func` and measures how much time it took.
214 timeIt = (func, name) ->
217 console.timeEnd(name)
220 isBlacklisted = (str) ->
221 matchingRules = getMatchingBlacklistRules(str)
222 return (matchingRules.length != 0)
224 # Returns all blacklisted keys in matching rules.
225 getBlacklistedKeys = (str) ->
226 matchingRules = getMatchingBlacklistRules(str)
228 for rule in matchingRules when /##/.test(rule)
229 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
230 return blacklistedKeys
232 # Returns all rules in the blacklist that match the provided string.
233 getMatchingBlacklistRules = (str) ->
234 return getBlacklist().filter((rule) ->
235 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
239 return splitListString(getPref('black_list'))
241 setBlacklist = (blacklist) ->
242 setPref('black_list', blacklist.join(','))
244 updateBlacklist = ({ add, remove } = {}) ->
245 blacklist = getBlacklist()
248 blacklist.push(splitListString(add)...)
250 blacklist = blacklist.filter((rule) -> rule != '')
251 blacklist = removeDuplicates(blacklist)
254 for rule in splitListString(remove) when rule in blacklist
255 blacklist.splice(blacklist.indexOf(rule), 1)
257 setBlacklist(blacklist)
259 # Splits a comma/space separated list into an array.
260 splitListString = (str) ->
261 return str.split(/\s*,[\s,]*/)
263 # Prepares a string to be used in a regexp, where "*" matches zero or more
264 # characters and "!" matches one character.
265 simpleWildcards = (string) ->
266 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
268 # Returns the first element that matches a pattern, favoring earlier patterns.
269 # The patterns are case insensitive `simpleWildcards`s and must match either in
270 # the beginning or at the end of a string. Moreover, a pattern does not match
271 # in the middle of words, so "previous" does not match "previously". If that is
272 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
273 # use `\b` word boundaries, because they don’t work well with non-English
274 # characters. Instead we match a space as word boundary. Therefore we normalize
275 # the whitespace and add spaces at the edges of the element text.
276 getBestPatternMatch = (patterns, attrs, elements) ->
278 for pattern in patterns
279 wildcarded = simpleWildcards(pattern)
280 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
282 # Helper function that matches a string against all the patterns.
284 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
286 if re.test(normalizedText)
290 # First search in attributes (favoring earlier attributes) as it's likely
291 # that they are more specific than text contexts.
293 for element in elements
294 if matches(element.getAttribute(attr))
297 # Then search in element contents.
298 for element in elements
299 if matches(element.textContent)
304 # Get VimFx verion. AddonManager only provides async API to access addon data,
305 # so it's a bit tricky...
310 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
311 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
316 parseHTML = (document, html) ->
317 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
318 flags = parser.SanitizerAllowStyle
319 return parser.parseFragment(html, flags, false, null,
320 document.documentElement)
324 .replace(/&/g, '&')
325 .replace(/</g, '<')
326 .replace(/>/g, '>')
327 .replace(/"/g, '"')
328 .replace(/'/g, ''')
330 createElement = (document, type, attributes = {}) ->
331 element = document.createElement(type)
333 for attribute, value of attributes
334 element.setAttribute(attribute, value)
336 if document instanceof HTMLDocument
337 element.classList.add('VimFxReset')
343 url = Cc['@mozilla.org/network/io-service;1']
344 .getService(Ci.nsIIOService)
345 .newURI(str, null, null)
346 .QueryInterface(Ci.nsIURL)
351 # Use Firefox services to search for a given string.
352 browserSearchSubmission = (str) ->
353 ss = Cc['@mozilla.org/browser/search-service;1']
354 .getService(Ci.nsIBrowserSearchService)
356 engine = ss.currentEngine or ss.defaultEngine
357 return engine.getSubmission(str, null)
359 openTab = (rootWindow, url, options) ->
360 { gBrowser } = rootWindow
361 rootWindow.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
362 gBrowser.loadOneTab(url, options)
364 normalizedKey = (key) -> key.map(notation.normalize).join('')
366 # Get hint characters, convert them to lower case, and filter duplicates.
368 hintChars = getPref('hint_chars')
369 # Make sure that hint chars contain at least two characters.
370 if not hintChars or hintChars.length < 2
373 return removeDuplicateCharacters(hintChars)
375 # Remove duplicate characters from string (case insensitive).
376 removeDuplicateCharacters = (str) ->
377 return removeDuplicates( str.toLowerCase().split('') ).join('')
379 # Return URI to some file in the extension packaged as resource.
380 getResourceURI = do ->
381 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
382 return (path) -> return Services.io.newURI(path, null, baseURI)
384 # Escape a string to render it usable in regular expressions.
385 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
387 removeDuplicates = (array) ->
388 # coffeelint: disable=no_backticks
389 return `[...new Set(array)]`
390 # coffeelint: enable=no_backticks
392 exports.Bucket = Bucket
393 exports.getEventWindow = getEventWindow
394 exports.getEventRootWindow = getEventRootWindow
395 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
396 exports.getRootWindow = getRootWindow
397 exports.getCurrentTabWindow = getCurrentTabWindow
399 exports.blurActiveElement = blurActiveElement
400 exports.isProperLink = isProperLink
401 exports.isTextInputElement = isTextInputElement
402 exports.isContentEditable = isContentEditable
403 exports.isActivatable = isActivatable
404 exports.isAdjustable = isAdjustable
406 exports.getSessionStore = getSessionStore
408 exports.loadCss = loadCss
410 exports.simulateClick = simulateClick
411 exports.isEventSimulated = isEventSimulated
412 exports.simulateWheel = simulateWheel
413 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
414 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
415 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
416 exports.writeToClipboard = writeToClipboard
417 exports.timeIt = timeIt
419 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
420 exports.isBlacklisted = isBlacklisted
421 exports.getBlacklistedKeys = getBlacklistedKeys
422 exports.updateBlacklist = updateBlacklist
423 exports.splitListString = splitListString
424 exports.getBestPatternMatch = getBestPatternMatch
426 exports.getVersion = getVersion
427 exports.parseHTML = parseHTML
428 exports.escapeHTML = escapeHTML
429 exports.createElement = createElement
430 exports.isURL = isURL
431 exports.browserSearchSubmission = browserSearchSubmission
432 exports.openTab = openTab
433 exports.normalizedKey = normalizedKey
434 exports.getHintChars = getHintChars
435 exports.removeDuplicates = removeDuplicates
436 exports.removeDuplicateCharacters = removeDuplicateCharacters
437 exports.getResourceURI = getResourceURI
438 exports.ADDON_ID = ADDON_ID