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 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
32 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
33 HTMLInputElement = Ci.nsIDOMHTMLInputElement
34 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
35 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
36 XULMenuListElement = Ci.nsIDOMXULMenuListElement
37 XULDocument = Ci.nsIDOMXULDocument
38 XULElement = Ci.nsIDOMXULElement
39 XPathResult = Ci.nsIDOMXPathResult
40 HTMLDocument = Ci.nsIDOMHTMLDocument
41 HTMLElement = Ci.nsIDOMHTMLElement
42 Window = Ci.nsIDOMWindow
43 ChromeWindow = Ci.nsIDOMChromeWindow
46 constructor: (@newFunc) ->
47 @bucket = new WeakMap()
51 return @bucket.get(obj)
54 @bucket.set(obj, value)
60 getEventWindow = (event) ->
61 if event.originalTarget instanceof Window
62 return event.originalTarget
64 doc = event.originalTarget.ownerDocument or event.originalTarget
65 if doc instanceof HTMLDocument or doc instanceof XULDocument
66 return doc.defaultView
68 getEventRootWindow = (event) ->
69 return unless window = getEventWindow(event)
70 return getRootWindow(window)
72 getEventCurrentTabWindow = (event) ->
73 return unless rootWindow = getEventRootWindow(event)
74 return getCurrentTabWindow(rootWindow)
76 getRootWindow = (window) ->
78 .QueryInterface(Ci.nsIInterfaceRequestor)
79 .getInterface(Ci.nsIWebNavigation)
80 .QueryInterface(Ci.nsIDocShellTreeItem)
82 .QueryInterface(Ci.nsIInterfaceRequestor)
85 getCurrentTabWindow = (window) ->
86 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
88 blurActiveElement = (window) ->
89 # Only blur focusable elements, in order to interfere with the browser as
91 { activeElement } = window.document
92 if activeElement and activeElement.tabIndex > -1
95 isProperLink = (element) ->
96 return element instanceof HTMLAnchorElement and
97 not element.href.endsWith('#') and
98 not element.href.startsWith('javascript:')
100 isTextInputElement = (element) ->
101 return (element instanceof HTMLInputElement and element.type in [
102 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
104 element instanceof HTMLTextAreaElement or
105 # `<select>` elements can also receive text input: You may type the
106 # text of an item to select it.
107 element instanceof HTMLSelectElement or
108 element instanceof XULMenuListElement
110 isContentEditable = (element) ->
111 return element.isContentEditable or
112 isGoogleEditable(element)
114 isGoogleEditable = (element) ->
115 # `g_editable` is a non-standard attribute commonly used by Google.
116 return element.getAttribute?('g_editable') == 'true' or
117 (element instanceof HTMLElement and
118 element.ownerDocument.body?.getAttribute('g_editable') == 'true')
120 isActivatable = (element) ->
121 return element instanceof HTMLAnchorElement or
122 element instanceof HTMLButtonElement or
123 (element instanceof HTMLInputElement and element.type in [
124 'button', 'submit', 'reset', 'image'
127 isAdjustable = (element) ->
128 return element instanceof HTMLInputElement and element.type in [
129 'checkbox', 'radio', 'file', 'color'
130 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
134 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
137 sss = Cc['@mozilla.org/content/style-sheet-service;1']
138 .getService(Ci.nsIStyleSheetService)
140 uri = getResourceURI("resources/#{ name }.css")
141 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
142 # website themes installed by users often make the hint markers unreadable,
143 # for example. Just using `!important` in the CSS is not enough.
144 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
145 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
148 sss.unregisterSheet(uri, sss.AGENT_SHEET)
151 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
152 # memory. This approach is better than for example setting `event.simulated =
153 # true`, since that tells the sites that the click was simulated, and allows
155 simulated_events = new WeakMap()
157 # Simulate mouse click with a full chain of events. Copied from Vimium
159 simulateClick = (element, modifiers = {}) ->
160 document = element.ownerDocument
161 window = document.defaultView
163 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
164 for event in eventSequence
165 mouseEvent = document.createEvent('MouseEvents')
166 mouseEvent.initMouseEvent(
167 event, true, true, window, 1, 0, 0, 0, 0,
168 modifiers.ctrlKey, false, false, modifiers.metaKey,
171 simulated_events.set(mouseEvent, true)
172 # Debugging note: Firefox will not execute the element's default action if
173 # we dispatch this click event, but Webkit will. Dispatching a click on an
174 # input box does not seem to focus it; we do that separately.
175 element.dispatchEvent(mouseEvent)
177 isEventSimulated = (event) ->
178 return simulated_events.has(event)
180 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
181 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
182 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
184 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
185 # specified position.
186 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
188 .QueryInterface(Ci.nsIInterfaceRequestor)
189 .getInterface(Ci.nsIDOMWindowUtils)
191 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
192 windowUtils.sendWheelEvent(
193 pX, pY, # Window offset (x, y) in pixels.
194 deltaX, deltaY, 0, # Deltas (x, y, z).
195 mode, # Mode (pixel, line, page).
197 0, 0, # Line or Page deltas (x, y).
201 # Write a string to the system clipboard.
202 writeToClipboard = (text) ->
203 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
204 .getService(Ci.nsIClipboardHelper)
205 clipboardHelper.copyString(text)
207 # Executes function `func` and mearues how much time it took.
208 timeIt = (func, name) ->
211 console.timeEnd(name)
214 isBlacklisted = (str) ->
215 matchingRules = getMatchingBlacklistRules(str)
216 return (matchingRules.length != 0)
218 # Returns all blacklisted keys in matching rules.
219 getBlacklistedKeys = (str) ->
220 matchingRules = getMatchingBlacklistRules(str)
222 for rule in matchingRules when /##/.test(rule)
223 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
224 return blacklistedKeys
226 # Returns all rules in the blacklist that match the provided string.
227 getMatchingBlacklistRules = (str) ->
228 return getBlacklist().filter((rule) ->
229 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
233 return splitListString(getPref('black_list'))
235 setBlacklist = (blacklist) ->
236 setPref('black_list', blacklist.join(','))
238 updateBlacklist = ({ add, remove } = {}) ->
239 blacklist = getBlacklist()
242 blacklist.push(splitListString(add)...)
244 blacklist = blacklist.filter((rule) -> rule != '')
245 blacklist = removeDuplicates(blacklist)
248 for rule in splitListString(remove) when rule in blacklist
249 blacklist.splice(blacklist.indexOf(rule), 1)
251 setBlacklist(blacklist)
253 # Splits a comma/space separated list into an array.
254 splitListString = (str) ->
255 return str.split(/\s*,[\s,]*/)
257 # Prepares a string to be used in a regexp, where "*" matches zero or more
258 # characters and "!" matches one character.
259 simpleWildcards = (string) ->
260 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
262 # Returns the first element that matches a pattern, favoring earlier patterns.
263 # The patterns are case insensitive `simpleWildcards`s and must match either in
264 # the beginning or at the end of a string. Moreover, a pattern does not match
265 # in the middle of words, so "previous" does not match "previously". If that is
266 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
267 # use `\b` word boundaries, because they don’t work well with non-English
268 # characters. Instead we match a space as word boundary. Therefore we normalize
269 # the whitespace and add spaces at the edges of the element text.
270 getBestPatternMatch = (patterns, attrs, elements) ->
272 for pattern in patterns
273 wildcarded = simpleWildcards(pattern)
274 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
276 # Helper function that matches a string against all the patterns.
278 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
280 if re.test(normalizedText)
284 # First search in attributes (favoring earlier attributes) as it's likely
285 # that they are more specific than text contexts.
287 for element in elements
288 if matches(element.getAttribute(attr))
291 # Then search in element contents.
292 for element in elements
293 if matches(element.textContent)
298 # Get VimFx verion. AddonManager only provides async API to access addon data,
299 # so it's a bit tricky...
304 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
305 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
310 parseHTML = (document, html) ->
311 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
312 flags = parser.SanitizerAllowStyle
313 return parser.parseFragment(html, flags, false, null,
314 document.documentElement)
318 .replace(/&/g, '&')
319 .replace(/</g, '<')
320 .replace(/>/g, '>')
321 .replace(/"/g, '"')
322 .replace(/'/g, ''')
324 createElement = (document, type, attributes = {}) ->
325 element = document.createElement(type)
327 for attribute, value of attributes
328 element.setAttribute(attribute, value)
330 if document instanceof HTMLDocument
331 element.classList.add('VimFxReset')
337 url = Cc['@mozilla.org/network/io-service;1']
338 .getService(Ci.nsIIOService)
339 .newURI(str, null, null)
340 .QueryInterface(Ci.nsIURL)
345 # Use Firefox services to search for a given string.
346 browserSearchSubmission = (str) ->
347 ss = Cc['@mozilla.org/browser/search-service;1']
348 .getService(Ci.nsIBrowserSearchService)
350 engine = ss.currentEngine or ss.defaultEngine
351 return engine.getSubmission(str, null)
353 normalizedKey = (key) -> key.map(notation.normalize).join('')
355 # Get hint characters, convert them to lower case, and filter duplicates.
357 hintChars = getPref('hint_chars')
358 # Make sure that hint chars contain at least two characters.
359 if not hintChars or hintChars.length < 2
362 return removeDuplicateCharacters(hintChars)
364 # Remove duplicate characters from string (case insensitive).
365 removeDuplicateCharacters = (str) ->
366 return removeDuplicates( str.toLowerCase().split('') ).join('')
368 # Return URI to some file in the extension packaged as resource.
369 getResourceURI = do ->
370 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
371 return (path) -> return Services.io.newURI(path, null, baseURI)
373 # Escape a string to render it usable in regular expressions.
374 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
376 removeDuplicates = (array) ->
377 # coffeelint: disable=no_backticks
378 return `[...new Set(array)]`
379 # coffeelint: enable=no_backticks
381 exports.Bucket = Bucket
382 exports.getEventWindow = getEventWindow
383 exports.getEventRootWindow = getEventRootWindow
384 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
385 exports.getRootWindow = getRootWindow
386 exports.getCurrentTabWindow = getCurrentTabWindow
388 exports.blurActiveElement = blurActiveElement
389 exports.isProperLink = isProperLink
390 exports.isTextInputElement = isTextInputElement
391 exports.isContentEditable = isContentEditable
392 exports.isActivatable = isActivatable
393 exports.isAdjustable = isAdjustable
394 exports.getSessionStore = getSessionStore
396 exports.loadCss = loadCss
398 exports.simulateClick = simulateClick
399 exports.isEventSimulated = isEventSimulated
400 exports.simulateWheel = simulateWheel
401 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
402 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
403 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
404 exports.writeToClipboard = writeToClipboard
405 exports.timeIt = timeIt
407 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
408 exports.isBlacklisted = isBlacklisted
409 exports.getBlacklistedKeys = getBlacklistedKeys
410 exports.updateBlacklist = updateBlacklist
411 exports.splitListString = splitListString
412 exports.getBestPatternMatch = getBestPatternMatch
414 exports.getVersion = getVersion
415 exports.parseHTML = parseHTML
416 exports.escapeHTML = escapeHTML
417 exports.createElement = createElement
418 exports.isURL = isURL
419 exports.browserSearchSubmission = browserSearchSubmission
420 exports.normalizedKey = normalizedKey
421 exports.getHintChars = getHintChars
422 exports.removeDuplicates = removeDuplicates
423 exports.removeDuplicateCharacters = removeDuplicateCharacters
424 exports.getResourceURI = getResourceURI
425 exports.ADDON_ID = ADDON_ID