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 { classes: Cc, interfaces: Ci, utils: Cu } = Components
24 Window = Ci.nsIDOMWindow
25 ChromeWindow = Ci.nsIDOMChromeWindow
26 Element = Ci.nsIDOMElement
27 HTMLDocument = Ci.nsIDOMHTMLDocument
28 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
29 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
30 HTMLInputElement = Ci.nsIDOMHTMLInputElement
31 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
32 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
33 XULDocument = Ci.nsIDOMXULDocument
34 XULButtonElement = Ci.nsIDOMXULButtonElement
35 XULControlElement = Ci.nsIDOMXULControlElement
36 XULMenuListElement = Ci.nsIDOMXULMenuListElement
37 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
40 constructor: (@newFunc, @observer = null) ->
41 @bucket = new WeakMap()
45 value = @bucket.get(obj)
48 @bucket.set(obj, value)
49 @observer.emit('bucket.get', value) if @observer
59 on: (event, listener) ->
60 (@listeners[event] ?= []).push(listener)
62 emit: (event, data) ->
63 for listener in @listeners[event] ? []
67 getEventWindow = (event) ->
68 if event.originalTarget instanceof Window
69 return event.originalTarget
71 doc = event.originalTarget.ownerDocument or event.originalTarget
72 if doc instanceof HTMLDocument or doc instanceof XULDocument
73 return doc.defaultView
75 getEventRootWindow = (event) ->
76 return unless window = getEventWindow(event)
77 return getRootWindow(window)
79 getEventCurrentTabWindow = (event) ->
80 return unless rootWindow = getEventRootWindow(event)
81 return getCurrentTabWindow(rootWindow)
83 getRootWindow = (window) ->
85 .QueryInterface(Ci.nsIInterfaceRequestor)
86 .getInterface(Ci.nsIWebNavigation)
87 .QueryInterface(Ci.nsIDocShellTreeItem)
89 .QueryInterface(Ci.nsIInterfaceRequestor)
92 getCurrentTabWindow = (window) ->
93 return window.gBrowser.selectedTab.linkedBrowser.contentWindow
95 blurActiveElement = (window) ->
96 # Only blur focusable elements, in order to interfere with the browser as
98 { activeElement } = window.document
99 if activeElement and activeElement.tabIndex > -1
102 # Focus an element and tell Firefox that the focus happened because of a user
103 # keypress (not just because some random programmatic focus).
104 focusElement = (element, options = {}) ->
105 focusManager = Cc['@mozilla.org/focus-manager;1']
106 .getService(Ci.nsIFocusManager)
107 focusManager.setFocus(element, focusManager.FLAG_BYKEY)
108 element.select?() if options.select
110 isProperLink = (element) ->
111 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
112 # href="">`s used as buttons on some sites.
113 return element.getAttribute('href') and
114 (element instanceof HTMLAnchorElement or
115 element.ownerDocument instanceof XULDocument) and
116 not element.href.endsWith('#') and
117 not element.href.startsWith('javascript:')
119 isTextInputElement = (element) ->
120 return (element instanceof HTMLInputElement and element.type in [
121 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
123 element instanceof HTMLTextAreaElement or
124 # `<select>` elements can also receive text input: You may type the
125 # text of an item to select it.
126 element instanceof HTMLSelectElement or
127 element instanceof XULMenuListElement or
128 element instanceof XULTextBoxElement
130 isContentEditable = (element) ->
131 return element.isContentEditable or
132 isGoogleEditable(element)
134 isGoogleEditable = (element) ->
135 # `g_editable` is a non-standard attribute commonly used by Google.
136 return element.getAttribute?('g_editable') == 'true' or
137 element.ownerDocument.body?.getAttribute('g_editable') == 'true'
139 isActivatable = (element) ->
140 return element instanceof HTMLAnchorElement or
141 element instanceof HTMLButtonElement or
142 (element instanceof HTMLInputElement and element.type in [
143 'button', 'submit', 'reset', 'image'
145 element instanceof XULButtonElement
147 isAdjustable = (element) ->
148 return element instanceof HTMLInputElement and element.type in [
149 'checkbox', 'radio', 'file', 'color'
150 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
152 element instanceof XULControlElement or
153 # Youtube special case.
154 element.classList?.contains('html5-video-player') or
155 element.classList?.contains('ytp-button')
158 return element.clientWidth * element.clientHeight
161 Cc['@mozilla.org/browser/sessionstore;1'].getService(Ci.nsISessionStore)
164 sss = Cc['@mozilla.org/content/style-sheet-service;1']
165 .getService(Ci.nsIStyleSheetService)
166 uri = Services.io.newURI("chrome://vimfx/skin/#{ name }.css", null, null)
167 method = sss.AUTHOR_SHEET
168 unless sss.sheetRegistered(uri, method)
169 sss.loadAndRegisterSheet(uri, method)
172 sss.unregisterSheet(uri, method)
175 # Store events that we’ve simulated. A `WeakMap` is used in order not to leak
176 # memory. This approach is better than for example setting `event.simulated =
177 # true`, since that tells the sites that the click was simulated, and allows
179 simulated_events = new WeakMap()
181 # Simulate mouse click with a full chain of events. ('command' is for XUL
183 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click', 'command']
184 simulateClick = (element) ->
185 window = element.ownerDocument.defaultView
186 for type in eventSequence
187 mouseEvent = new window.MouseEvent(type, {
188 # Let the event bubble in order to trigger delegated event listeners.
190 # Make the event cancelable so that `<a href="#">` can be used as a
191 # JavaScript-powered button without scrolling to the top of the page.
194 element.dispatchEvent(mouseEvent)
196 isEventSimulated = (event) ->
197 return simulated_events.has(event)
199 # Write a string to the system clipboard.
200 writeToClipboard = (text) ->
201 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
202 .getService(Ci.nsIClipboardHelper)
203 clipboardHelper.copyString(text)
205 # Executes function `func` and measures how much time it took.
206 timeIt = (func, name) ->
209 console.timeEnd(name)
212 createBox = (document, className, parent = null, text = null) ->
213 box = document.createElement('box')
214 box.className = className
215 box.textContent = text if text?
216 parent.appendChild(box) if parent?
219 setAttributes = (element, attributes) ->
220 for attribute, value of attributes
221 element.setAttribute(attribute, value)
224 insertText = (input, value) ->
225 { selectionStart, selectionEnd } = input
227 input.value[0...selectionStart] + value + input.value[selectionEnd..]
228 input.selectionStart = input.selectionEnd = selectionStart + value.length
230 openTab = (rootWindow, url, options) ->
231 { gBrowser } = rootWindow
232 rootWindow.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
233 gBrowser.loadOneTab(url, options)
235 # Remove duplicate characters from string (case insensitive).
236 removeDuplicateCharacters = (str) ->
237 return removeDuplicates( str.toLowerCase().split('') ).join('')
239 # Escape a string to render it usable in regular expressions.
240 regexpEscape = (s) -> s and s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
242 removeDuplicates = (array) ->
243 # coffeelint: disable=no_backticks
244 return `[...new Set(array)]`
245 # coffeelint: enable=no_backticks
247 formatError = (error) ->
248 stack = String(error.stack?.formattedStack ? error.stack ? '')
250 .filter((line) -> line.contains('.xpi!'))
251 .map((line) -> ' ' + line.replace(/(?:\/<)*@.+\.xpi!/g, '@'))
253 return "#{ error }\n#{ stack }"
255 observe = (topic, observer) ->
256 observer = {observe: observer} if typeof observer == 'function'
257 Services.obs.addObserver(observer, topic, false)
259 Services.obs.removeObserver(observer, topic, false)
262 has = Function::call.bind(Object::hasOwnProperty)
265 constructor: ({start, step}) ->
268 tick: -> @value += @step
275 getEventCurrentTabWindow
302 removeDuplicateCharacters