2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
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 nsIClipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
25 .getService(Ci.nsIClipboardHelper)
26 nsIDomUtils = Cc['@mozilla.org/inspector/dom-utils;1']
27 .getService(Ci.inIDOMUtils)
28 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
29 .getService(Ci.nsIFocusManager)
30 nsIStyleSheetService = Cc['@mozilla.org/content/style-sheet-service;1']
31 .getService(Ci.nsIStyleSheetService)
32 nsIWindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
33 .getService(Ci.nsIWindowMediator)
35 HTMLAnchorElement = Ci.nsIDOMHTMLAnchorElement
36 HTMLButtonElement = Ci.nsIDOMHTMLButtonElement
37 HTMLInputElement = Ci.nsIDOMHTMLInputElement
38 HTMLTextAreaElement = Ci.nsIDOMHTMLTextAreaElement
39 HTMLSelectElement = Ci.nsIDOMHTMLSelectElement
40 HTMLBodyElement = Ci.nsIDOMHTMLBodyElement
41 XULDocument = Ci.nsIDOMXULDocument
42 XULButtonElement = Ci.nsIDOMXULButtonElement
43 XULControlElement = Ci.nsIDOMXULControlElement
44 XULMenuListElement = Ci.nsIDOMXULMenuListElement
45 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
47 # Full chains of events for different mouse actions. ('command' is for XUL
49 EVENTS_CLICK = ['mousedown', 'mouseup', 'click', 'command']
50 EVENTS_HOVER_START = ['mouseover', 'mouseenter', 'mousemove']
51 EVENTS_HOVER_END = ['mouseout', 'mouseleave']
55 # Element classification helpers
57 isActivatable = (element) ->
58 return element instanceof HTMLAnchorElement or
59 element instanceof HTMLButtonElement or
60 (element instanceof HTMLInputElement and element.type in [
61 'button', 'submit', 'reset', 'image'
63 element instanceof XULButtonElement
65 isAdjustable = (element) ->
66 return element instanceof HTMLInputElement and element.type in [
67 'checkbox', 'radio', 'file', 'color'
68 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
70 element instanceof XULControlElement or
71 # Youtube special case.
72 element.classList?.contains('html5-video-player') or
73 element.classList?.contains('ytp-button')
75 isContentEditable = (element) ->
76 return element.isContentEditable or
77 isIframeEditor(element) or
79 element.getAttribute?('g_editable') == 'true' or
80 element.ownerDocument?.body?.getAttribute('g_editable') == 'true'
82 isIframeEditor = (element) ->
83 return false unless element instanceof HTMLBodyElement
86 element.id == 'innerdocbody' or
88 (element.classList.contains('xe_content') and
89 element.classList.contains('editable')) or
91 element.classList.contains('wysiwyg')
93 isProperLink = (element) ->
94 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
95 # href="">`s used as buttons on some sites.
96 return element.getAttribute('href') and
97 (element instanceof HTMLAnchorElement or
98 element.ownerDocument instanceof XULDocument) and
99 not element.href.endsWith('#') 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 element instanceof XULTextBoxElement or
109 isContentEditable(element)
111 isTypingElement = (element) ->
112 return isTextInputElement(element) or
113 # `<select>` elements can also receive text input: You may type the
114 # text of an item to select it.
115 element instanceof HTMLSelectElement or
116 element instanceof XULMenuListElement
120 # Active/focused element helpers
122 # NOTE: In frame scripts, `document.activeElement` may be `null` when the page
123 # is loading. Therefore always check if anything was returned, such as:
125 # return unless activeElement = utils.getActiveElement(window)
126 getActiveElement = (window) ->
127 {activeElement} = window.document
128 return null unless activeElement
129 # If the active element is a frame, recurse into it. The easiest way to detect
130 # a frame that works both in browser UI and in web page content is to check
131 # for the presence of `.contentWindow`. However, in non-multi-process
132 # `<browser>` (sometimes `<xul:browser>`) elements have a `.contentWindow`
133 # pointing to the web page content `window`, which we don’t want to recurse
134 # into. `.localName` is `.nodeName` without `xul:` (if it exists). This seems
135 # to be the only way to detect such elements.
136 if activeElement.localName != 'browser' and activeElement.contentWindow
137 return getActiveElement(activeElement.contentWindow)
141 blurActiveElement = (window) ->
142 # Blurring a frame element also blurs any active elements inside it. Recursing
143 # into the frames and blurring the “real” active element directly would give
144 # focus to the `<body>` of its containing frame, while blurring the top-most
145 # frame gives focus to the top-most `<body>`. This allows to blur fancy text
146 # editors which use an `<iframe>` as their text area.
147 window.document.activeElement?.blur()
149 blurActiveBrowserElement = (vim) ->
150 # - Blurring in the next tick allows to pass `<escape>` to the location bar to
151 # reset it, for example.
152 # - Focusing the current browser afterwards allows to pass `<escape>` as well
153 # as unbound keys to the page. However, focusing the browser also triggers
154 # focus events on `document` and `window` in the current page. Many pages
155 # re-focus some text input on those events, making it impossible to blur
156 # those! Therefore we tell the frame script to suppress those events.
158 activeElement = getActiveElement(window)
159 vim._send('browserRefocus')
162 window.gBrowser.selectedBrowser.focus()
165 # Focus an element and tell Firefox that the focus happened because of a user
166 # action (not just because some random programmatic focus). `.FLAG_BYKEY` might
167 # look more appropriate, but it unconditionally selects all text, which
168 # `.FLAG_BYMOUSE` does not.
169 focusElement = (element, options = {}) ->
170 nsIFocusManager.setFocus(element, options.flag ? 'FLAG_BYMOUSE')
171 element.select?() if options.select
173 getFocusType = (element) -> switch
174 when isTypingElement(element)
176 when isActivatable(element)
178 when isAdjustable(element)
187 listen = (element, eventName, listener, useCapture = true) ->
188 element.addEventListener(eventName, listener, useCapture)
190 element.removeEventListener(eventName, listener, useCapture)
193 listenOnce = (element, eventName, listener, useCapture = true) ->
196 element.removeEventListener(eventName, fn, useCapture)
197 listen(element, eventName, fn, useCapture)
199 onRemoved = (window, element, fn) ->
200 mutationObserver = new window.MutationObserver((changes) ->
201 for change in changes then for removedElement in change.removedNodes
202 if removedElement == element
203 mutationObserver.disconnect()
207 mutationObserver.observe(element.parentNode, {childList: true})
208 module.onShutdown(mutationObserver.disconnect.bind(mutationObserver))
210 suppressEvent = (event) ->
211 event.preventDefault()
212 event.stopPropagation()
214 simulateMouseEvents = (element, sequenceType) ->
215 window = element.ownerGlobal
216 rect = element.getBoundingClientRect()
218 eventSequence = switch sequenceType
219 when 'click' then EVENTS_CLICK
220 when 'hover-start' then EVENTS_HOVER_START
221 when 'hover-end' then EVENTS_HOVER_END
223 for type in eventSequence
224 mouseEvent = new window.MouseEvent(type, {
225 # Let the event bubble in order to trigger delegated event listeners.
226 bubbles: type not in ['mouseenter', 'mouseleave']
227 # Make the event cancelable so that `<a href="#">` can be used as a
228 # JavaScript-powered button without scrolling to the top of the page.
229 cancelable: type not in ['mouseenter', 'mouseleave']
230 # These properties are just here for mimicing a real click as much as
232 buttons: if type in EVENTS_CLICK then 1 else 0
233 detail: if type in EVENTS_CLICK then 1 else 0
235 # `page{X,Y}` are set automatically to the correct values when setting
236 # `client{X,Y}`. `{offset,layer,movement}{X,Y}` are not worth the trouble
240 # To exactly calculate `screen{X,Y}` one has to to check where the web
241 # page content area is inside the browser chrome and go through all parent
242 # frames as well. This is good enough. YAGNI for now.
243 screenX: window.screenX + rect.left
244 screenY: window.screenY + rect.top
246 element.dispatchEvent(mouseEvent)
255 return element.clientWidth * element.clientHeight
257 containsDeep = (parent, element) ->
258 parentWindow = parent.ownerGlobal
259 elementWindow = element.ownerGlobal
261 # Owner windows might be missing when opening the devtools.
262 while elementWindow and parentWindow and
263 elementWindow != parentWindow and elementWindow.top != elementWindow
264 element = elementWindow.frameElement
265 elementWindow = element.ownerGlobal
267 return parent.contains(element)
269 createBox = (document, className = '', parent = null, text = null) ->
270 box = document.createElement('box')
271 box.className = "#{className} vimfx-box"
272 box.textContent = text if text?
273 parent.appendChild(box) if parent?
276 injectTemporaryPopup = (document, contents) ->
277 popup = document.createElement('menupopup')
278 popup.appendChild(contents)
279 document.getElementById('mainPopupSet').appendChild(popup)
280 listenOnce(popup, 'popuphidden', popup.remove.bind(popup))
283 insertText = (input, value) ->
284 {selectionStart, selectionEnd} = input
286 input.value[0...selectionStart] + value + input.value[selectionEnd..]
287 input.selectionStart = input.selectionEnd = selectionStart + value.length
289 querySelectorAllDeep = (window, selector) ->
290 elements = Array.from(window.document.querySelectorAll(selector))
291 for frame in window.frames
292 elements.push(querySelectorAllDeep(frame, selector)...)
295 scroll = (element, args) ->
296 {method, type, directions, amounts, properties, adjustment, smooth} = args
298 for direction, index in directions
299 amount = amounts[index]
300 options[direction] = -Math.sign(amount) * adjustment + switch type
301 when 'lines' then amount
302 when 'pages' then amount * element[properties[index]]
303 when 'other' then Math.min(amount, element[properties[index]])
304 options.behavior = 'smooth' if smooth
305 element[method](options)
307 setAttributes = (element, attributes) ->
308 for attribute, value of attributes
309 element.setAttribute(attribute, value)
312 setHover = (element, hover) ->
313 method = if hover then 'addPseudoClassLock' else 'removePseudoClassLock'
314 while element.parentElement
315 nsIDomUtils[method](element, ':hover')
316 element = element.parentElement
324 constructor: ({start: @value = 0, @step = 1}) ->
325 tick: -> @value += @step
331 on: (event, listener) ->
332 (@listeners[event] ?= []).push(listener)
334 emit: (event, data) ->
335 for listener in @listeners[event] ? []
339 has = (obj, prop) -> Object::hasOwnProperty.call(obj, prop)
341 nextTick = (window, fn) -> window.setTimeout(fn, 0)
343 regexEscape = (s) -> s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
345 removeDuplicates = (array) -> Array.from(new Set(array))
347 # Remove duplicate characters from string (case insensitive).
348 removeDuplicateCharacters = (str) ->
349 return removeDuplicates( str.toLowerCase().split('') ).join('')
351 # Calls `fn` repeatedly, with at least `interval` ms between each call.
352 setInterval = (window, interval, fn) ->
354 currentIntervalId = null
357 currentIntervalId = window.setTimeout((-> fn(next)), interval)
360 window.clearTimeout(currentIntervalId)
368 formatError = (error) ->
369 stack = String(error.stack?.formattedStack ? error.stack ? '')
371 .filter((line) -> line.includes('.xpi!'))
372 .map((line) -> ' ' + line.replace(/(?:\/<)*@.+\.xpi!/g, '@'))
374 return "#{error}\n#{stack}"
376 getCurrentLocation = ->
377 window = getCurrentWindow()
378 return new window.URL(window.gBrowser.selectedBrowser.currentURI.spec)
380 getCurrentWindow = -> nsIWindowMediator.getMostRecentWindow('navigator:browser')
383 uri = Services.io.newURI("chrome://vimfx/skin/#{name}.css", null, null)
384 method = nsIStyleSheetService.AUTHOR_SHEET
385 unless nsIStyleSheetService.sheetRegistered(uri, method)
386 nsIStyleSheetService.loadAndRegisterSheet(uri, method)
388 nsIStyleSheetService.unregisterSheet(uri, method)
391 observe = (topic, observer) ->
392 observer = {observe: observer} if typeof observer == 'function'
393 Services.obs.addObserver(observer, topic, false)
395 Services.obs.removeObserver(observer, topic, false)
398 openPopup = (popup) ->
399 window = popup.ownerGlobal
400 # Show the popup so it gets a height and width.
401 popup.openPopupAtScreen(0, 0)
402 # Center the popup inside the window.
404 window.screenX + window.outerWidth / 2 - popup.clientWidth / 2,
405 window.screenY + window.outerHeight / 2 - popup.clientHeight / 2
408 openTab = (window, url, options) ->
410 window.TreeStyleTabService?.readyToOpenChildTab(gBrowser.selectedTab)
411 gBrowser.loadOneTab(url, options)
413 writeToClipboard = (text) -> nsIClipboardHelper.copyString(text)
427 blurActiveBrowserElement
453 removeDuplicateCharacters