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 editable elements, in order to interfere with the browser as
91 { activeElement } = window.document
92 if activeElement and isElementEditable(activeElement)
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
106 isContentEditable = (element) ->
107 return element.isContentEditable or
108 isGoogleEditable(element)
110 isGoogleEditable = (element) ->
111 # `g_editable` is a non-standard attribute commonly used by Google.
112 return element.getAttribute?('g_editable') == 'true' or
113 (element instanceof HTMLElement and
114 element.ownerDocument.body?.getAttribute('g_editable') == 'true')
116 isElementEditable = (element) ->
117 return element instanceof HTMLInputElement or
118 element instanceof HTMLTextAreaElement or
119 element instanceof HTMLSelectElement or
120 element instanceof XULMenuListElement or
121 isContentEditable(element)
124 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
127 sss = Cc['@mozilla.org/content/style-sheet-service;1']
128 .getService(Ci.nsIStyleSheetService)
130 uri = getResourceURI("resources/#{ name }.css")
131 # `AGENT_SHEET` is used to override userContent.css and Stylish. Custom
132 # website themes installed by users often make the hint markers unreadable,
133 # for example. Just using `!important` in the CSS is not enough.
134 unless sss.sheetRegistered(uri, sss.AGENT_SHEET)
135 sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET)
138 sss.unregisterSheet(uri, sss.AGENT_SHEET)
141 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
142 # memory. This approach is better than for example setting `event.simulated =
143 # true`, since that tells the sites that the click was simulated, and allows
145 simulated_events = new WeakMap()
147 # Simulate mouse click with a full chain of events. Copied from Vimium
149 simulateClick = (element, modifiers = {}) ->
150 document = element.ownerDocument
151 window = document.defaultView
153 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click']
154 for event in eventSequence
155 mouseEvent = document.createEvent('MouseEvents')
156 mouseEvent.initMouseEvent(
157 event, true, true, window, 1, 0, 0, 0, 0,
158 modifiers.ctrlKey, false, false, modifiers.metaKey,
161 simulated_events.set(mouseEvent, true)
162 # Debugging note: Firefox will not execute the element's default action if
163 # we dispatch this click event, but Webkit will. Dispatching a click on an
164 # input box does not seem to focus it; we do that separately.
165 element.dispatchEvent(mouseEvent)
167 isEventSimulated = (event) ->
168 return simulated_events.has(event)
170 WHEEL_MODE_PIXEL = Ci.nsIDOMWheelEvent.DOM_DELTA_PIXEL
171 WHEEL_MODE_LINE = Ci.nsIDOMWheelEvent.DOM_DELTA_LINE
172 WHEEL_MODE_PAGE = Ci.nsIDOMWheelEvent.DOM_DELTA_PAGE
174 # Simulate mouse scroll event by specific offsets given that mouse cursor is at
175 # specified position.
176 simulateWheel = (window, deltaX, deltaY, mode = WHEEL_MODE_PIXEL) ->
178 .QueryInterface(Ci.nsIInterfaceRequestor)
179 .getInterface(Ci.nsIDOMWindowUtils)
181 [pX, pY] = [window.innerWidth / 2, window.innerHeight / 2]
182 windowUtils.sendWheelEvent(
183 pX, pY, # Window offset (x, y) in pixels.
184 deltaX, deltaY, 0, # Deltas (x, y, z).
185 mode, # Mode (pixel, line, page).
187 0, 0, # Line or Page deltas (x, y).
191 # Write a string to the system clipboard.
192 writeToClipboard = (text) ->
193 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
194 .getService(Ci.nsIClipboardHelper)
195 clipboardHelper.copyString(text)
197 # Executes function `func` and mearues how much time it took.
198 timeIt = (func, name) ->
201 console.timeEnd(name)
204 isBlacklisted = (str) ->
205 matchingRules = getMatchingBlacklistRules(str)
206 return (matchingRules.length != 0)
208 # Returns all blacklisted keys in matching rules.
209 getBlacklistedKeys = (str) ->
210 matchingRules = getMatchingBlacklistRules(str)
212 for rule in matchingRules when /##/.test(rule)
213 blacklistedKeys.push(x) for x in rule.split('##')[1].split('#')
214 return blacklistedKeys
216 # Returns all rules in the blacklist that match the provided string.
217 getMatchingBlacklistRules = (str) ->
218 return getBlacklist().filter((rule) ->
219 /// ^#{ simpleWildcards(rule.split('##')[0]) }$ ///i.test(str)
223 return splitListString(getPref('black_list'))
225 setBlacklist = (blacklist) ->
226 setPref('black_list', blacklist.join(','))
228 updateBlacklist = ({ add, remove } = {}) ->
229 blacklist = getBlacklist()
232 blacklist.push(splitListString(add)...)
234 blacklist = blacklist.filter((rule) -> rule != '')
235 blacklist = removeDuplicates(blacklist)
238 for rule in splitListString(remove) when rule in blacklist
239 blacklist.splice(blacklist.indexOf(rule), 1)
241 setBlacklist(blacklist)
243 # Splits a comma/space separated list into an array.
244 splitListString = (str) ->
245 return str.split(/\s*,[\s,]*/)
247 # Prepares a string to be used in a regexp, where "*" matches zero or more
248 # characters and "!" matches one character.
249 simpleWildcards = (string) ->
250 return regexpEscape(string).replace(/\\\*/g, '.*').replace(/!/g, '.')
252 # Returns the first element that matches a pattern, favoring earlier patterns.
253 # The patterns are case insensitive `simpleWildcards`s and must match either in
254 # the beginning or at the end of a string. Moreover, a pattern does not match
255 # in the middle of words, so "previous" does not match "previously". If that is
256 # desired, a pattern such as "previous*" can be used instead. Note: We cannot
257 # use `\b` word boundaries, because they don’t work well with non-English
258 # characters. Instead we match a space as word boundary. Therefore we normalize
259 # the whitespace and add spaces at the edges of the element text.
260 getBestPatternMatch = (patterns, attrs, elements) ->
262 for pattern in patterns
263 wildcarded = simpleWildcards(pattern)
264 regexps.push(/// ^\s(?:#{ wildcarded })\s | \s(?:#{ wildcarded })\s$ ///i)
266 # Helper function that matches a string against all the patterns.
268 normalizedText = " #{ text } ".replace(/\s+/g, ' ')
270 if re.test(normalizedText)
274 # First search in attributes (favoring earlier attributes) as it's likely
275 # that they are more specific than text contexts.
277 for element in elements
278 if matches(element.getAttribute(attr))
281 # Then search in element contents.
282 for element in elements
283 if matches(element.textContent)
288 # Get VimFx verion. AddonManager only provides async API to access addon data,
289 # so it's a bit tricky...
294 Cu.import('resource://gre/modules/AddonManager.jsm', scope)
295 scope.AddonManager.getAddonByID(ADDON_ID, (addon) -> version = addon.version)
300 parseHTML = (document, html) ->
301 parser = Cc['@mozilla.org/parserutils;1'].getService(Ci.nsIParserUtils)
302 flags = parser.SanitizerAllowStyle
303 return parser.parseFragment(html, flags, false, null,
304 document.documentElement)
308 .replace(/&/g, '&')
309 .replace(/</g, '<')
310 .replace(/>/g, '>')
311 .replace(/"/g, '"')
312 .replace(/'/g, ''')
314 createElement = (document, type, attributes = {}) ->
315 element = document.createElement(type)
317 for attribute, value of attributes
318 element.setAttribute(attribute, value)
320 if document instanceof HTMLDocument
321 element.classList.add('VimFxReset')
327 url = Cc['@mozilla.org/network/io-service;1']
328 .getService(Ci.nsIIOService)
329 .newURI(str, null, null)
330 .QueryInterface(Ci.nsIURL)
335 # Use Firefox services to search for a given string.
336 browserSearchSubmission = (str) ->
337 ss = Cc['@mozilla.org/browser/search-service;1']
338 .getService(Ci.nsIBrowserSearchService)
340 engine = ss.currentEngine or ss.defaultEngine
341 return engine.getSubmission(str, null)
343 normalizedKey = (key) -> key.map(notation.normalize).join('')
345 # Get hint characters, convert them to lower case, and filter duplicates.
347 hintChars = getPref('hint_chars')
348 # Make sure that hint chars contain at least two characters.
349 if not hintChars or hintChars.length < 2
352 return removeDuplicateCharacters(hintChars)
354 # Remove duplicate characters from string (case insensitive).
355 removeDuplicateCharacters = (str) ->
356 return removeDuplicates( str.toLowerCase().split('') ).join('')
358 # Return URI to some file in the extension packaged as resource.
359 getResourceURI = do ->
360 baseURI = Services.io.newURI(__SCRIPT_URI_SPEC__, null, null)
361 return (path) -> return Services.io.newURI(path, null, baseURI)
363 # Escape a string to render it usable in regular expressions.
364 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
366 removeDuplicates = (array) ->
367 # coffeelint: disable=no_backticks
368 return `[...new Set(array)]`
369 # coffeelint: enable=no_backticks
371 exports.Bucket = Bucket
372 exports.getEventWindow = getEventWindow
373 exports.getEventRootWindow = getEventRootWindow
374 exports.getEventCurrentTabWindow = getEventCurrentTabWindow
375 exports.getRootWindow = getRootWindow
376 exports.getCurrentTabWindow = getCurrentTabWindow
378 exports.blurActiveElement = blurActiveElement
379 exports.isProperLink = isProperLink
380 exports.isTextInputElement = isTextInputElement
381 exports.isContentEditable = isContentEditable
382 exports.isElementEditable = isElementEditable
383 exports.getSessionStore = getSessionStore
385 exports.loadCss = loadCss
387 exports.simulateClick = simulateClick
388 exports.isEventSimulated = isEventSimulated
389 exports.simulateWheel = simulateWheel
390 exports.WHEEL_MODE_PIXEL = WHEEL_MODE_PIXEL
391 exports.WHEEL_MODE_LINE = WHEEL_MODE_LINE
392 exports.WHEEL_MODE_PAGE = WHEEL_MODE_PAGE
393 exports.writeToClipboard = writeToClipboard
394 exports.timeIt = timeIt
396 exports.getMatchingBlacklistRules = getMatchingBlacklistRules
397 exports.isBlacklisted = isBlacklisted
398 exports.getBlacklistedKeys = getBlacklistedKeys
399 exports.updateBlacklist = updateBlacklist
400 exports.splitListString = splitListString
401 exports.getBestPatternMatch = getBestPatternMatch
403 exports.getVersion = getVersion
404 exports.parseHTML = parseHTML
405 exports.escapeHTML = escapeHTML
406 exports.createElement = createElement
407 exports.isURL = isURL
408 exports.browserSearchSubmission = browserSearchSubmission
409 exports.normalizedKey = normalizedKey
410 exports.getHintChars = getHintChars
411 exports.removeDuplicates = removeDuplicates
412 exports.removeDuplicateCharacters = removeDuplicateCharacters
413 exports.getResourceURI = getResourceURI
414 exports.ADDON_ID = ADDON_ID