2 # Copyright Anton Khodakivskiy 2012, 2013, 2014.
3 # Copyright Simon Lydell 2013, 2014, 2015, 2016.
4 # Copyright Wang Zhuochun 2013.
5 # Copyright Alan Wu 2016.
7 # This file is part of VimFx.
9 # VimFx is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # VimFx is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with VimFx. If not, see <http://www.gnu.org/licenses/>.
23 # This file contains lots of different helper functions.
25 {OS} = Components.utils.import('resource://gre/modules/osfile.jsm', {})
27 nsIClipboardHelper = Cc['@mozilla.org/widget/clipboardhelper;1']
28 .getService(Ci.nsIClipboardHelper)
29 nsIDomUtils = Cc['@mozilla.org/inspector/dom-utils;1']
30 .getService(Ci.inIDOMUtils)
31 nsIEventListenerService = Cc['@mozilla.org/eventlistenerservice;1']
32 .getService(Ci.nsIEventListenerService)
33 nsIFocusManager = Cc['@mozilla.org/focus-manager;1']
34 .getService(Ci.nsIFocusManager)
35 nsIStyleSheetService = Cc['@mozilla.org/content/style-sheet-service;1']
36 .getService(Ci.nsIStyleSheetService)
37 nsIWindowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
38 .getService(Ci.nsIWindowMediator)
40 # For XUL, `instanceof` checks are often better than `.localName` checks,
41 # because some of the below interfaces are extended by many elements.
42 XULDocument = Ci.nsIDOMXULDocument
43 XULButtonElement = Ci.nsIDOMXULButtonElement
44 XULControlElement = Ci.nsIDOMXULControlElement
45 XULMenuListElement = Ci.nsIDOMXULMenuListElement
46 XULTextBoxElement = Ci.nsIDOMXULTextBoxElement
48 # Full chains of events for different mouse actions. Note: 'click' is fired
49 # by Firefox automatically after 'mousedown' and 'mouseup'. Similarly,
50 # 'command' is fired automatically after 'click' on xul pages.
51 EVENTS_CLICK = ['mousedown', 'mouseup']
52 EVENTS_CLICK_XUL = ['click']
53 EVENTS_CONTEXT = ['contextmenu']
54 EVENTS_HOVER_START = ['mouseover', 'mouseenter', 'mousemove']
55 EVENTS_HOVER_END = ['mouseout', 'mouseleave']
59 # Element classification helpers
61 hasMarkableTextNode = (element) ->
62 return Array.some(element.childNodes, (node) ->
63 # Ignore whitespace-only text nodes, and single-letter ones (which are
64 # common in many syntax highlighters).
65 return node.nodeType == 3 and node.data.trim().length > 1
68 isActivatable = (element) ->
69 return element.localName in ['a', 'button'] or
70 (element.localName == 'input' and element.type in [
71 'button', 'submit', 'reset', 'image'
73 element instanceof XULButtonElement
75 isAdjustable = (element) ->
76 return element.localName == 'input' and element.type in [
77 'checkbox', 'radio', 'file', 'color'
78 'date', 'time', 'datetime', 'datetime-local', 'month', 'week'
80 element.localName in ['video', 'audio', 'embed', 'object'] or
81 element instanceof XULControlElement or
82 # Custom video players.
83 includes(element.className, 'video') or
84 includes(element.className, 'player') or
85 # Youtube special case.
86 element.classList?.contains('ytp-button') or
87 # Allow navigating object inspection trees in th devtools with the
88 # arrow keys, even if the arrow keys are used as VimFx shortcuts.
89 isDevtoolsElement(element)
91 isContentEditable = (element) ->
92 return element.isContentEditable or
93 isIframeEditor(element) or
95 element.getAttribute?('g_editable') == 'true' or
96 element.ownerDocument?.body?.getAttribute?('g_editable') == 'true' or
97 # Codeacademy terminals.
98 element.classList?.contains('real-terminal')
100 isDevtoolsElement = (element) ->
101 return false unless element.ownerGlobal
102 return Array.some(element.ownerGlobal.top.frames, isDevtoolsWindow)
104 isDevtoolsWindow = (window) ->
105 return window.location?.href in [
106 'about:devtools-toolbox'
107 'chrome://devtools/content/framework/toolbox.xul'
110 isFocusable = (element) ->
111 return element.tabIndex > -1 and
112 not (element.localName?.endsWith?('box') and
113 element.localName != 'checkbox') and
114 not (element.localName == 'toolbarbutton' and
115 element.parentNode?.localName == 'toolbarbutton') and
116 element.localName not in ['tabs', 'menuitem', 'menuseparator']
118 isIframeEditor = (element) ->
119 return false unless element.localName == 'body'
122 element.id == 'innerdocbody' or
124 (element.classList?.contains('xe_content') and
125 element.classList?.contains('editable')) or
127 element.classList?.contains('wysiwyg') or
129 element.classList?.contains('htmlarea-content-body') or
130 # The wasavi extension.
131 element.hasAttribute?('data-wasavi-state')
133 isIgnoreModeFocusType = (element) ->
135 # The wasavi extension.
136 element.hasAttribute?('data-wasavi-state') or
137 element.closest?('#wasavi_container') or
138 # CodeMirror in Vim mode.
139 (element.localName == 'textarea' and
140 element.closest?('.CodeMirror') and _hasVimEventListener(element))
142 # CodeMirror’s Vim mode is really sucky to detect. The only way seems to be to
143 # check if the there are any event listener functions with Vim-y words in them.
144 _hasVimEventListener = (element) ->
145 for listener in nsIEventListenerService.getListenerInfoFor(element)
146 if listener.listenerObject and
147 /\bvim\b|insertmode/i.test(String(listener.listenerObject))
151 isProperLink = (element) ->
152 # `.getAttribute` is used below instead of `.hasAttribute` to exclude `<a
153 # href="">`s used as buttons on some sites.
154 return element.getAttribute?('href') and
155 (element.localName == 'a' or
156 element.ownerDocument instanceof XULDocument) and
157 not element.href?.endsWith?('#') and
158 not element.href?.endsWith?('#?') and
159 not element.href?.startsWith?('javascript:')
161 isTextInputElement = (element) ->
162 return (element.localName == 'input' and element.type in [
163 'text', 'search', 'tel', 'url', 'email', 'password', 'number'
165 element.localName == 'textarea' or
166 element instanceof XULTextBoxElement or
167 isContentEditable(element)
169 isTypingElement = (element) ->
170 return isTextInputElement(element) or
171 # `<select>` elements can also receive text input: You may type the
172 # text of an item to select it.
173 element.localName == 'select' or
174 element instanceof XULMenuListElement
178 # Active/focused element helpers
180 blurActiveBrowserElement = (vim) ->
181 # - Blurring in the next tick allows to pass `<escape>` to the location bar to
182 # reset it, for example.
183 # - Focusing the current browser afterwards allows to pass `<escape>` as well
184 # as unbound keys to the page. However, focusing the browser also triggers
185 # focus events on `document` and `window` in the current page. Many pages
186 # re-focus some text input on those events, making it impossible to blur
187 # those! Therefore we tell the frame script to suppress those events.
189 activeElement = getActiveElement(window)
190 activeElement.closest('tabmodalprompt')?.abortPrompt()
191 vim._send('browserRefocus')
194 window.gBrowser.selectedBrowser.focus()
197 blurActiveElement = (window) ->
198 # Blurring a frame element also blurs any active elements inside it. Recursing
199 # into the frames and blurring the “real” active element directly would give
200 # focus to the `<body>` of its containing frame, while blurring the top-most
201 # frame gives focus to the top-most `<body>`. This allows to blur fancy text
202 # editors which use an `<iframe>` as their text area.
203 window.document.activeElement?.blur()
205 # Focus an element and tell Firefox that the focus happened because of a user
206 # action (not just because some random programmatic focus). `.FLAG_BYKEY` might
207 # look more appropriate, but it unconditionally selects all text, which
208 # `.FLAG_BYMOUSE` does not.
209 focusElement = (element, options = {}) ->
210 nsIFocusManager.setFocus(element, options.flag ? 'FLAG_BYMOUSE')
211 element.select?() if options.select
213 # NOTE: In frame scripts, `document.activeElement` may be `null` when the page
214 # is loading. Therefore always check if anything was returned, such as:
216 # return unless activeElement = utils.getActiveElement(window)
217 getActiveElement = (window) ->
218 {activeElement} = window.document
219 return null unless activeElement
220 # If the active element is a frame, recurse into it. The easiest way to detect
221 # a frame that works both in browser UI and in web page content is to check
222 # for the presence of `.contentWindow`. However, in non-multi-process,
223 # `<browser>` (sometimes `<xul:browser>`) elements have a `.contentWindow`
224 # pointing to the web page content `window`, which we don’t want to recurse
225 # into. The problem is that there are _some_ `<browser>`s which we _want_ to
226 # recurse into, such as the sidebar (for instance the history sidebar), and
227 # dialogs in `about:preferences`. Checking the `contextmenu` attribute seems
228 # to be a reliable test, catching both the main tab `<browser>`s and bookmarks
229 # opened in the sidebar.
230 if (activeElement.localName == 'browser' and
231 activeElement.getAttribute?('contextmenu') == 'contentAreaContextMenu') or
232 not activeElement.contentWindow
235 return getActiveElement(activeElement.contentWindow)
237 getFocusType = (element) -> switch
238 when isIgnoreModeFocusType(element)
240 when isTypingElement(element)
241 if element.closest?('findbar') then 'findbar' else 'editable'
242 when isActivatable(element)
244 when isAdjustable(element)
253 listen = (element, eventName, listener, useCapture = true) ->
254 element.addEventListener(eventName, listener, useCapture)
256 element.removeEventListener(eventName, listener, useCapture)
259 listenOnce = (element, eventName, listener, useCapture = true) ->
262 element.removeEventListener(eventName, fn, useCapture)
263 listen(element, eventName, fn, useCapture)
265 onRemoved = (element, fn) ->
266 window = element.ownerGlobal
270 return if disconnected
272 mutationObserver.disconnect() unless Cu.isDeadWrapper(mutationObserver)
274 mutationObserver = new window.MutationObserver((changes) ->
275 for change in changes then for removedElement in change.removedNodes
276 if removedElement.contains?(element)
281 mutationObserver.observe(window.document.documentElement, {
285 module.onShutdown(disconnect)
289 simulateMouseEvents = (element, sequence, browserOffset) ->
290 window = element.ownerGlobal
291 rect = element.getBoundingClientRect()
292 topOffset = getTopOffset(element)
294 eventSequence = switch sequence
308 for type in eventSequence
310 when type in EVENTS_CONTEXT
312 when type in EVENTS_CLICK
317 mouseEvent = new window.MouseEvent(type, {
318 # Let the event bubble in order to trigger delegated event listeners.
319 bubbles: type not in ['mouseenter', 'mouseleave']
320 # Make the event cancelable so that `<a href="#">` can be used as a
321 # JavaScript-powered button without scrolling to the top of the page.
322 cancelable: type not in ['mouseenter', 'mouseleave']
323 # These properties are just here for mimicing a real click as much as
328 # `page{X,Y}` are set automatically to the correct values when setting
329 # `client{X,Y}`. `{offset,layer,movement}{X,Y}` are not worth the trouble
332 clientY: rect.top + rect.height / 2
333 screenX: browserOffset.x + topOffset.x
334 screenY: browserOffset.y + topOffset.y + rect.height / 2
337 if type == 'mousemove'
338 # If the below technique is used for this event, the “URL popup” (shown
339 # when hovering or focusing links) does not appear.
340 element.dispatchEvent(mouseEvent)
342 # The last `true` below marks the event as trusted, which some APIs
343 # require, such as `requestFullscreen()`.
344 # (`element.dispatchEvent(mouseEvent)` is not able to do this.)
346 .QueryInterface(Ci.nsIInterfaceRequestor)
347 .getInterface(Ci.nsIDOMWindowUtils)
348 .dispatchDOMEventViaPresShell(element, mouseEvent, true)
352 suppressEvent = (event) ->
353 event.preventDefault()
354 event.stopPropagation()
361 return element.clientWidth * element.clientHeight
363 checkElementOrAncestor = (element, fn) ->
364 window = element.ownerGlobal
365 while element.parentElement
366 return true if fn(element)
367 element = element.parentElement
370 clearSelectionDeep = (window) ->
371 # The selection might be `null` in hidden frames.
372 selection = window.getSelection()
373 selection?.removeAllRanges()
374 for frame in window.frames
375 clearSelectionDeep(frame)
376 # Allow parents to re-gain control of text selection.
377 frame.frameElement.blur()
380 containsDeep = (parent, element) ->
381 parentWindow = parent.ownerGlobal
382 elementWindow = element.ownerGlobal
384 # Owner windows might be missing when opening the devtools.
385 while elementWindow and parentWindow and
386 elementWindow != parentWindow and elementWindow.top != elementWindow
387 element = elementWindow.frameElement
388 elementWindow = element.ownerGlobal
390 return parent.contains(element)
392 createBox = (document, className = '', parent = null, text = null) ->
393 box = document.createElement('box')
394 box.className = "#{className} vimfx-box"
395 box.textContent = text if text?
396 parent.appendChild(box) if parent?
399 getFirstNonEmptyTextNodeBoxQuads = (element) ->
400 for node in element.childNodes then switch node.nodeType
402 unless node.data.trim() == ''
403 boxQuads = node.getBoxQuads()
404 return boxQuads if boxQuads?.length > 0
406 result = getFirstNonEmptyTextNodeBoxQuads(node)
407 return result if result
410 # In quirks mode (when the page lacks a doctype), such as on Hackernews,
411 # `<body>` is considered the root element rather than `<html>`.
412 getRootElement = (document) ->
413 if document.compatMode == 'BackCompat' and document.body?
416 return document.documentElement
418 getText = (element) ->
419 text = element.textContent or element.value or element.placeholder or ''
420 return text.trim().replace(/\s+/, ' ')
422 getTopOffset = (element) ->
423 window = element.ownerGlobal
425 {left: x, top: y} = element.getBoundingClientRect()
426 while window.frameElement
427 frame = window.frameElement
428 frameRect = frame.getBoundingClientRect()
432 computedStyle = frame.ownerGlobal.getComputedStyle(frame)
435 parseFloat(computedStyle.getPropertyValue('border-left-width')) +
436 parseFloat(computedStyle.getPropertyValue('padding-left'))
438 parseFloat(computedStyle.getPropertyValue('border-top-width')) +
439 parseFloat(computedStyle.getPropertyValue('padding-top'))
441 window = window.parent
444 injectTemporaryPopup = (document, contents) ->
445 popup = document.createElement('menupopup')
446 popup.appendChild(contents)
447 document.getElementById('mainPopupSet').appendChild(popup)
448 listenOnce(popup, 'popuphidden', popup.remove.bind(popup))
451 insertText = (input, value) ->
452 {selectionStart, selectionEnd} = input
454 input.value[0...selectionStart] + value + input.value[selectionEnd..]
455 input.selectionStart = input.selectionEnd = selectionStart + value.length
457 isDetached = (element) ->
458 return not element.ownerDocument?.documentElement?.contains?(element)
460 isNonEmptyTextNode = (node) ->
461 return node.nodeType == 3 and node.data.trim() != ''
463 isPositionFixed = (element) ->
464 computedStyle = element.ownerGlobal.getComputedStyle(element)
465 return computedStyle?.getPropertyValue('position') == 'fixed'
467 querySelectorAllDeep = (window, selector) ->
468 elements = Array.from(window.document.querySelectorAll(selector))
469 for frame in window.frames
470 elements.push(querySelectorAllDeep(frame, selector)...)
473 selectAllSubstringMatches = (element, substring, {caseSensitive = true} = {}) ->
474 window = element.ownerGlobal
475 selection = window.getSelection()
476 {textContent} = element
478 format = (string) -> if caseSensitive then string else string.toLowerCase()
480 getAllNonOverlappingRangeOffsets(format(textContent), format(substring))
481 offsetsLength = offsets.length
482 return if offsetsLength == 0
486 [currentOffset] = offsets
487 searchIndex = currentOffset.start
490 walkTextNodes(element, (textNode) ->
491 {length} = textNode.data
492 return false if length == 0
494 while textIndex + length > searchIndex
496 range = window.document.createRange()
497 range.setStart(start.textNode, start.offset)
498 range.setEnd(textNode, currentOffset.end - textIndex)
499 selection.addRange(range)
502 return true if offsetsIndex >= offsetsLength
503 currentOffset = offsets[offsetsIndex]
506 searchIndex = currentOffset.start
509 start = {textNode, offset: currentOffset.start - textIndex}
510 searchIndex = currentOffset.end - 1
516 selectElement = (element) ->
517 window = element.ownerGlobal
518 selection = window.getSelection()
519 range = window.document.createRange()
520 range.selectNodeContents(element)
521 selection.addRange(range)
523 setAttributes = (element, attributes) ->
524 for attribute, value of attributes
525 element.setAttribute(attribute, value)
528 setHover = (element, hover) ->
529 method = if hover then 'addPseudoClassLock' else 'removePseudoClassLock'
530 while element.parentElement
531 nsIDomUtils[method](element, ':hover')
532 element = element.parentElement
535 walkTextNodes = (element, fn) ->
536 for node in element.childNodes then switch node.nodeType
541 stop = walkTextNodes(node, fn)
550 constructor: ({start: @value = 0, @step = 1}) ->
551 tick: -> @value += @step
557 on: (event, listener) ->
558 (@listeners[event] ?= new Set()).add(listener)
560 off: (event, listener) ->
561 @listeners[event]?.delete(listener)
563 emit: (event, data) ->
564 @listeners[event]?.forEach((listener) ->
568 # Returns `[nonMatch, adjacentMatchAfter]`, where `adjacentMatchAfter - nonMatch
569 # == 1`. `fn(n)` is supposed to return `false` for `n <= nonMatch` and `true`
570 # for `n >= adjacentMatchAfter`. Both `nonMatch` and `adjacentMatchAfter` may be
571 # `null` if they cannot be found. Otherwise they’re in the range `min <= n <=
572 # max`. `[null, null]` is returned in non-sensical cases. This function is
573 # intended to be used as a faster alternative to something like this:
575 # adjacentMatchAfter = null
576 # for n in [min..max]
578 # adjacentMatchAfter = n
580 bisect = (min, max, fn) ->
581 return [null, null] unless max - min >= 0 and min % 1 == 0 and max % 1 == 0
584 mid = min + (max - min) // 2
595 when matchMin and matchMax
597 when not matchMin and not matchMax
599 when not matchMin and matchMax
604 getAllNonOverlappingRangeOffsets = (string, substring) ->
606 return [] if length == 0
609 lastOffset = {start: -Infinity, end: -Infinity}
613 index = string.indexOf(substring, index + 1)
615 if index > lastOffset.end
616 lastOffset = {start: index, end: index + length}
617 offsets.push(lastOffset)
619 lastOffset.end = index + length
623 has = (obj, prop) -> Object::hasOwnProperty.call(obj, prop)
625 # Check if `search` exists in `string` (case insensitively). Returns `false` if
626 # `string` doesn’t exist or isn’t a string, such as `<SVG element>.className`.
627 includes = (string, search) ->
628 return false unless typeof string == 'string'
629 return string.toLowerCase().includes(search)
631 # Calls `fn` repeatedly, with at least `interval` ms between each call.
632 interval = (window, interval, fn) ->
634 currentIntervalId = null
637 currentIntervalId = window.setTimeout((-> fn(next)), interval)
640 window.clearTimeout(currentIntervalId)
644 nextTick = (window, fn) -> window.setTimeout((-> fn()) , 0)
646 partition = (array, fn) ->
649 for item, index in array
650 if fn(item, index, array)
653 nonMatching.push(item)
654 return [matching, nonMatching]
656 regexEscape = (s) -> s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
658 removeDuplicateChars = (string) -> removeDuplicates(string.split('')).join('')
660 removeDuplicates = (array) -> Array.from(new Set(array))
662 sum = (numbers) -> numbers.reduce(((sum, number) -> sum + number), 0)
668 expandPath = (path) ->
669 if path.startsWith('~/') or path.startsWith('~\\')
670 return OS.Constants.Path.homeDir + path[1..]
674 formatError = (error) ->
675 stack = String(error.stack?.formattedStack ? error.stack ? '')
677 .filter((line) -> line.includes('.xpi!'))
678 .map((line) -> ' ' + line.replace(/(?:\/<)*@.+\.xpi!/g, '@'))
680 return "#{error}\n#{stack}"
682 getCurrentLocation = ->
683 return unless window = getCurrentWindow()
684 return new window.URL(window.gBrowser.selectedBrowser.currentURI.spec)
686 # This function might return `null` on startup.
687 getCurrentWindow = -> nsIWindowMediator.getMostRecentWindow('navigator:browser')
689 hasEventListeners = (element, type) ->
690 for listener in nsIEventListenerService.getListenerInfoFor(element)
691 if listener.listenerObject and listener.type == type
695 loadCss = (uriString) ->
696 uri = Services.io.newURI(uriString, null, null)
697 method = nsIStyleSheetService.AUTHOR_SHEET
698 unless nsIStyleSheetService.sheetRegistered(uri, method)
699 nsIStyleSheetService.loadAndRegisterSheet(uri, method)
701 nsIStyleSheetService.unregisterSheet(uri, method)
704 observe = (topic, observer) ->
705 observer = {observe: observer} if typeof observer == 'function'
706 Services.obs.addObserver(observer, topic, false)
708 Services.obs.removeObserver(observer, topic, false)
711 # Try to open a button’s dropdown menu, if any.
712 openDropdown = (element) ->
713 if element.ownerDocument instanceof XULDocument and
714 element.getAttribute?('type') == 'menu' and
715 element.open == false # Only change `.open` if it is already a boolean.
718 openPopup = (popup) ->
719 window = popup.ownerGlobal
720 # Show the popup so it gets a height and width.
721 popup.openPopupAtScreen(0, 0)
722 # Center the popup inside the window.
724 window.screenX + window.outerWidth / 2 - popup.clientWidth / 2,
725 window.screenY + window.outerHeight / 2 - popup.clientHeight / 2
728 writeToClipboard = (text) -> nsIClipboardHelper.copyString(text)
741 isIgnoreModeFocusType
746 blurActiveBrowserElement
759 checkElementOrAncestor
763 getFirstNonEmptyTextNodeBoxQuads
773 selectAllSubstringMatches
782 getAllNonOverlappingRangeOffsets