2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015.
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 # This file contains lots of different helper functions.
24 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
25 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
26 HTMLInputElement = Ci.nsIDOMHTMLInputElement
27 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
28 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
29 HTMLFrameElement = Ci.nsIDOMHTMLFrameElement
30 HTMLIFrameElement = Ci.nsIDOMHTMLIFrameElement
31 XULDocument = Ci.nsIDOMXULDocument
32 XULButtonElement = Ci.nsIDOMXULButtonElement
33 XULControlElement = Ci.nsIDOMXULControlElement
34 XULMenuListElement = Ci.nsIDOMXULMenuListElement
35 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
41 # Element classification helpers
43 isActivatable = (element) ->
44 return element instanceof HTMLAnchorElement or
45 element instanceof HTMLButtonElement or
46 (element instanceof HTMLInputElement and element.type in [
47 'button', 'submit', 'reset', 'image'
49 element instanceof XULButtonElement
51 isAdjustable = (element) ->
52 return element instanceof HTMLInputElement and element.type in [
53 'checkbox', 'radio', 'file', 'color'
54 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
56 element instanceof XULControlElement or
57 # Youtube special case.
58 element.classList?.contains('html5-video-player') or
59 element.classList?.contains('ytp-button')
61 isContentEditable = (element) ->
62 return element.isContentEditable or
63 # `g_editable` is a non-standard attribute commonly used by Google.
64 element.getAttribute?('g_editable') == 'true' or
65 element.ownerDocument?.body?.getAttribute('g_editable') == 'true'
67 isProperLink = (element) ->
68 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
69 # href="">`s used as buttons on some sites.
70 return element.getAttribute('href') and
71 (element instanceof HTMLAnchorElement or
72 element.ownerDocument instanceof XULDocument) and
73 not element.href.endsWith('#') and
74 not element.href.endsWith('#?') and
75 not element.href.startsWith('javascript:')
77 isTextInputElement = (element) ->
78 return (element instanceof HTMLInputElement and element.type in [
79 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
81 element instanceof HTMLTextAreaElement or
82 element instanceof XULTextBoxElement
84 isTypingElement = (element) ->
85 return isTextInputElement(element) or
86 # `<select>` elements can also receive text input: You may type the
87 # text of an item to select it.
88 element instanceof HTMLSelectElement or
89 element instanceof XULMenuListElement
93 # Active/focused element helpers
95 getActiveElement = (window) ->
96 {activeElement} = window.document
97 if activeElement instanceof HTMLFrameElement or
98 activeElement instanceof HTMLIFrameElement
99 return getActiveElement(activeElement.contentWindow)
103 blurActiveElement = (window) ->
104 return unless activeElement = getActiveElement(window)
107 blurActiveBrowserElement = (vim) ->
108 # - Blurring in the next tick allows to pass `<escape>` to the location bar to
109 # reset it, for example.
110 # - Focusing the current browser afterwards allows to pass `<escape>` as well
111 # as unbound keys to the page. However, focusing the browser also triggers
112 # focus events on `document` and `window` in the current page. Many pages
113 # re-focus some text input on those events, making it impossible to blur
114 # those! Therefore we tell the frame script to suppress those events.
116 activeElement = getActiveElement(window)
117 vim._send('browserRefocus')
120 window.gBrowser.selectedBrowser.focus()
123 # Focus an element and tell Firefox that the focus happened because of a user
124 # keypress (not just because some random programmatic focus).
125 focusElement = (element, options = {}) ->
126 focusManager = Cc['@mozilla.org/focus-manager;1']
127 .getService(Ci.nsIFocusManager)
128 focusManager.setFocus(element, focusManager.FLAG_BYKEY)
129 element.select?() if options.select
131 moveFocus = (direction) ->
132 focusManager = Cc['@mozilla.org/focus-manager;1']
133 .getService(Ci.nsIFocusManager)
136 focusManager.MOVEFOCUS_BACKWARD
138 focusManager.MOVEFOCUS_FORWARD
139 focusManager.moveFocus(
140 null, # Use current window.
141 null, # Move relative to the currently focused element.
143 focusManager.FLAG_BYKEY
146 getFocusType = (event) ->
147 target = event.originalTarget
149 when isTypingElement(target) or isContentEditable(target)
151 when isActivatable(target)
153 when isAdjustable(target)
162 listen = (element, eventName, listener, useCapture = true) ->
163 element.addEventListener(eventName, listener, useCapture)
165 element.removeEventListener(eventName, listener, useCapture)
168 listenOnce = (element, eventName, listener, useCapture = true) ->
171 element.removeEventListener(eventName, fn, useCapture)
172 listen(element, eventName, fn, useCapture)
174 onRemoved = (window, element, fn) ->
175 mutationObserver = new window.MutationObserver((changes) ->
176 for change in changes then for removedElement in change.removedNodes
177 if removedElement == element
178 mutationObserver.disconnect()
182 mutationObserver.observe(element.parentNode, {childList: true})
183 module.onShutdown(mutationObserver.disconnect.bind(mutationObserver))
185 suppressEvent = (event) ->
186 event.preventDefault()
187 event.stopPropagation()
189 # Simulate mouse click with a full chain of events. ('command' is for XUL
191 eventSequence = ['mouseover', 'mousedown', 'mouseup', 'click', 'command']
192 simulateClick = (element) ->
193 window = element.ownerDocument.defaultView
194 for type in eventSequence
195 mouseEvent = new window.MouseEvent(type, {
196 # Let the event bubble in order to trigger delegated event listeners.
198 # Make the event cancelable so that `<a href="#">` can be used as a
199 # JavaScript-powered button without scrolling to the top of the page.
202 element.dispatchEvent(mouseEvent)
210 return element.clientWidth * element.clientHeight
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 insertText = (input, value) ->
220 {selectionStart, selectionEnd} = input
222 input.value[0...selectionStart] + value + input.value[selectionEnd..]
223 input.selectionStart = input.selectionEnd = selectionStart + value.length
225 querySelectorAllDeep = (window, selector) ->
226 elements = Array.from(window.document.querySelectorAll(selector))
227 for frame in window.frames
228 elements.push(querySelectorAllDeep(frame, selector)...)
231 setAttributes = (element, attributes) ->
232 for attribute, value of attributes
233 element.setAttribute(attribute, value)
241 constructor: ({start: @value = 0, @step = 1}) ->
242 tick: -> @value += @step
248 on: (event, listener) ->
249 (@listeners[event] ?= []).push(listener)
251 emit: (event, data) ->
252 for listener in @listeners[event] ? []
256 has = (obj, prop) -> Object::hasOwnProperty.call(obj, prop)
258 nextTick = (window, fn) -> window.setTimeout(fn, 0)
260 regexEscape = (s) -> s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
262 removeDuplicates = (array) -> Array.from(new Set(array))
264 # Remove duplicate characters from string (case insensitive).
265 removeDuplicateCharacters = (str) ->
266 return removeDuplicates( str.toLowerCase().split('') ).join('')
272 formatError = (error) ->
273 stack = String(error.stack?.formattedStack ? error.stack ? '')
275 .filter((line) -> line.includes('.xpi!'))
276 .map((line) -> ' ' + line.replace(/(?:\/<)*@.+\.xpi!/g, '@'))
278 return "#{error}\n#{stack}"
280 getCurrentLocation = ->
281 window = getCurrentWindow()
282 return new window.URL(window.gBrowser.selectedBrowser.currentURI.spec)
284 getCurrentWindow = ->
285 windowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
286 .getService(Components.interfaces.nsIWindowMediator)
287 return windowMediator.getMostRecentWindow('navigator:browser')
290 sss = Cc['@mozilla.org/content/style-sheet-service;1']
291 .getService(Ci.nsIStyleSheetService)
292 uri = Services.io.newURI("chrome://vimfx/skin/#{name}.css", null, null)
293 method = sss.AUTHOR_SHEET
294 unless sss.sheetRegistered(uri, method)
295 sss.loadAndRegisterSheet(uri, method)
297 sss.unregisterSheet(uri, method)
300 observe = (topic, observer) ->
301 observer = {observe: observer} if typeof observer == 'function'
302 Services.obs.addObserver(observer, topic, false)
304 Services.obs.removeObserver(observer, topic, false)
307 openTab = (window, url, options) ->
309 window.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
310 gBrowser.loadOneTab(url, options)
312 writeToClipboard = (text) ->
313 clipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
314 .getService(Ci.nsIClipboardHelper)
315 clipboardHelper.copyString(text)
329 blurActiveBrowserElement
352 removeDuplicateCharacters