hyper/lib/components/term.js

366 lines
11 KiB
JavaScript
Raw Normal View History

/* global Blob,URL,requestAnimationFrame,ResizeObserver */
2016-07-13 12:44:24 -08:00
import React from 'react';
2018-01-09 07:33:24 -09:00
import {Terminal} from 'xterm';
import * as fit from 'xterm/lib/addons/fit/fit';
import * as webLinks from 'xterm/lib/addons/webLinks/webLinks';
import * as winptyCompat from 'xterm/lib/addons/winptyCompat/winptyCompat';
2017-10-24 14:06:46 -08:00
import {clipboard} from 'electron';
2018-01-09 07:33:24 -09:00
import * as Color from 'color';
import terms from '../terms';
import processClipboard from '../utils/paste';
2017-06-11 02:42:39 -08:00
Terminal.applyAddon(fit);
Terminal.applyAddon(webLinks);
Terminal.applyAddon(winptyCompat);
2017-06-11 02:42:39 -08:00
// map old hterm constants to xterm.js
const CURSOR_STYLES = {
BEAM: 'bar',
UNDERLINE: 'underline',
BLOCK: 'block'
};
2016-06-30 22:01:04 -08:00
const isWebgl2Supported = (() => {
let isSupported = window.WebGL2RenderingContext ? undefined : false;
return () => {
if (isSupported === undefined) {
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl2', {depth: false, antialias: false});
isSupported = gl instanceof window.WebGL2RenderingContext;
}
return isSupported;
};
})();
2018-01-09 07:33:24 -09:00
const getTermOptions = props => {
// Set a background color only if it is opaque
2018-02-18 03:28:26 -09:00
const needTransparency = Color(props.backgroundColor).alpha() < 1;
const backgroundColor = needTransparency ? 'transparent' : props.backgroundColor;
let useWebGL = false;
if (props.webGLRenderer) {
if (needTransparency) {
// eslint-disable-next-line no-console
console.warn(
'WebGL Renderer has been disabled since it does not support transparent backgrounds yet. ' +
'Falling back to canvas-based rendering.'
);
} else if (!isWebgl2Supported()) {
// eslint-disable-next-line no-console
console.warn('WebGL2 is not supported on your machine. Falling back to canvas-based rendering.');
} else {
useWebGL = true;
}
}
2018-01-09 07:33:24 -09:00
return {
macOptionIsMeta: props.modifierKeys.altIsMeta,
scrollback: props.scrollback,
2018-01-09 07:33:24 -09:00
cursorStyle: CURSOR_STYLES[props.cursorShape],
cursorBlink: props.cursorBlink,
fontFamily: props.fontFamily,
fontSize: props.fontSize,
fontWeight: props.fontWeight,
fontWeightBold: props.fontWeightBold,
lineHeight: props.lineHeight,
letterSpacing: props.letterSpacing,
2018-02-18 03:28:26 -09:00
allowTransparency: needTransparency,
macOptionClickForcesSelection: props.macOptionSelectionMode === 'force',
// HACK: Terminal.setOption breaks if we don't apply these in this order
// TODO: The above notice can be removed once this is addressed:
// https://github.com/xtermjs/xterm.js/pull/1790#issuecomment-450000121
rendererType: useWebGL ? 'webgl' : 'canvas',
experimentalCharAtlas: useWebGL ? 'webgl' : 'dynamic',
2018-01-09 07:33:24 -09:00
theme: {
foreground: props.foregroundColor,
background: backgroundColor,
cursor: props.cursorColor,
cursorAccent: props.cursorAccentColor,
selection: props.selectionColor,
2018-01-09 07:33:24 -09:00
black: props.colors.black,
red: props.colors.red,
green: props.colors.green,
yellow: props.colors.yellow,
blue: props.colors.blue,
magenta: props.colors.magenta,
cyan: props.colors.cyan,
white: props.colors.white,
brightBlack: props.colors.lightBlack,
brightRed: props.colors.lightRed,
brightGreen: props.colors.lightGreen,
brightYellow: props.colors.lightYellow,
brightBlue: props.colors.lightBlue,
brightMagenta: props.colors.lightMagenta,
brightCyan: props.colors.lightCyan,
brightWhite: props.colors.lightWhite
}
};
};
export default class Term extends React.PureComponent {
constructor(props) {
2016-07-13 12:44:24 -08:00
super(props);
2017-09-09 03:42:19 -08:00
props.ref_(props.uid, this);
this.termRef = null;
this.termWrapperRef = null;
this.termRect = null;
this.onWindowPaste = this.onWindowPaste.bind(this);
this.onTermWrapperRef = this.onTermWrapperRef.bind(this);
2017-10-24 14:06:46 -08:00
this.onMouseUp = this.onMouseUp.bind(this);
2018-01-09 07:33:24 -09:00
this.termOptions = {};
2018-12-06 14:56:29 -09:00
this.disposableListeners = [];
2016-07-13 12:44:24 -08:00
}
componentDidMount() {
const {props} = this;
2016-06-30 22:01:04 -08:00
2018-01-09 07:33:24 -09:00
this.termOptions = getTermOptions(props);
this.term = props.term || new Terminal(this.termOptions);
// The parent element for the terminal is attached and removed manually so
// that we can preserve it across mounts and unmounts of the component
this.termRef = props.term ? props.term._core._parent : document.createElement('div');
this.termRef.className = 'term_fit term_term';
this.termWrapperRef.appendChild(this.termRef);
if (!props.term) {
this.term.attachCustomKeyEventHandler(this.keyboardHandler);
this.term.open(this.termRef);
this.term.webLinksInit();
this.term.winptyCompatInit();
2017-08-02 11:05:47 -08:00
}
if (this.props.isTermActive) {
this.term.focus();
}
2017-06-11 02:42:39 -08:00
if (props.onTitle) {
2018-12-06 14:56:29 -09:00
this.disposableListeners.push(this.term.addDisposableListener('title', props.onTitle));
2017-06-11 02:42:39 -08:00
}
2016-07-03 12:35:45 -08:00
2017-06-11 02:42:39 -08:00
if (props.onActive) {
2018-12-06 14:56:29 -09:00
this.disposableListeners.push(this.term.addDisposableListener('focus', props.onActive));
}
2017-06-11 02:42:39 -08:00
if (props.onData) {
2018-12-06 14:56:29 -09:00
this.disposableListeners.push(this.term.addDisposableListener('data', props.onData));
}
2017-06-11 02:42:39 -08:00
if (props.onResize) {
2018-12-06 14:56:29 -09:00
this.disposableListeners.push(
this.term.addDisposableListener('resize', ({cols, rows}) => {
props.onResize(cols, rows);
})
);
}
2016-07-13 12:44:24 -08:00
if (props.onCursorMove) {
2018-12-06 14:56:29 -09:00
this.disposableListeners.push(
this.term.addDisposableListener('cursormove', () => {
const cursorFrame = {
x: this.term._core.buffer.x * this.term._core.renderer.dimensions.actualCellWidth,
y: this.term._core.buffer.y * this.term._core.renderer.dimensions.actualCellHeight,
width: this.term._core.renderer.dimensions.actualCellWidth,
height: this.term._core.renderer.dimensions.actualCellHeight,
col: this.term._core.buffer.y,
row: this.term._core.buffer.x
2018-12-06 14:56:29 -09:00
};
props.onCursorMove(cursorFrame);
})
);
}
window.addEventListener('paste', this.onWindowPaste, {
capture: true
});
terms[this.props.uid] = this;
2016-07-13 12:44:24 -08:00
}
getTermDocument() {
2017-06-11 02:42:39 -08:00
// eslint-disable-next-line no-console
console.warn(
'The underlying terminal engine of Hyper no longer ' +
'uses iframes with individual `document` objects for each ' +
'terminal instance. This method call is retained for ' +
2017-11-01 13:31:44 -08:00
"backwards compatibility reasons. It's ok to attach directly" +
'to the `document` object of the main `window`.'
);
return document;
}
// intercepting paste event for any necessary processing of
// clipboard data, if result is falsy, paste event continues
onWindowPaste(e) {
if (!this.props.isTermActive) return;
const processed = processClipboard();
if (processed) {
e.preventDefault();
e.stopPropagation();
2019-01-06 05:55:16 -09:00
this.term._core.handler(processed);
}
}
2017-11-03 14:01:21 -08:00
onMouseUp(e) {
if (this.props.quickEdit && e.button === 2) {
if (this.term.hasSelection()) {
clipboard.writeText(this.term.getSelection());
this.term.clearSelection();
} else {
document.execCommand('paste');
}
} else if (this.props.copyOnSelect && this.term.hasSelection()) {
2017-10-24 14:06:46 -08:00
clipboard.writeText(this.term.getSelection());
}
}
write(data) {
2017-06-11 02:42:39 -08:00
this.term.write(data);
2016-07-13 12:44:24 -08:00
}
focus() {
2017-06-11 02:42:39 -08:00
this.term.focus();
2016-07-13 12:44:24 -08:00
}
clear() {
2017-06-11 02:42:39 -08:00
this.term.clear();
2017-08-02 11:05:47 -08:00
}
reset() {
2017-08-02 11:05:47 -08:00
this.term.reset();
}
resize(cols, rows) {
2017-08-02 11:05:47 -08:00
this.term.resize(cols, rows);
}
selectAll() {
this.term.selectAll();
}
fitResize() {
2017-11-06 03:26:56 -09:00
if (!this.termWrapperRef) {
return;
}
this.term.fit();
2016-07-03 12:35:45 -08:00
}
keyboardHandler(e) {
// Has Mousetrap flagged this event as a command?
return !e.catched;
}
componentWillReceiveProps(nextProps) {
2016-07-13 12:44:24 -08:00
if (!this.props.cleared && nextProps.cleared) {
this.clear();
2016-07-05 12:14:30 -08:00
}
2018-01-09 07:33:24 -09:00
const nextTermOptions = getTermOptions(nextProps);
// Update only options that have changed.
Object.keys(nextTermOptions)
.filter(option => option !== 'theme' && nextTermOptions[option] !== this.termOptions[option])
.forEach(option => {
try {
this.term.setOption(option, nextTermOptions[option]);
} catch (e) {
if (/The webgl renderer only works with the webgl char atlas/i.test(e.message)) {
// Ignore this because the char atlas will also be changed
} else {
throw e;
}
}
});
2018-01-09 07:33:24 -09:00
// Do we need to update theme?
const shouldUpdateTheme =
!this.termOptions.theme ||
nextTermOptions.rendererType !== this.termOptions.rendererType ||
2018-03-22 11:59:07 -08:00
Object.keys(nextTermOptions.theme).some(
option => nextTermOptions.theme[option] !== this.termOptions.theme[option]
);
2018-01-09 07:33:24 -09:00
if (shouldUpdateTheme) {
this.term.setOption('theme', nextTermOptions.theme);
}
this.termOptions = nextTermOptions;
2017-08-02 11:05:47 -08:00
if (
this.props.fontSize !== nextProps.fontSize ||
this.props.fontFamily !== nextProps.fontFamily ||
this.props.lineHeight !== nextProps.lineHeight ||
this.props.letterSpacing !== nextProps.letterSpacing
) {
2017-08-02 11:05:47 -08:00
// resize to fit the container
this.fitResize();
2017-08-02 11:05:47 -08:00
}
if (nextProps.rows !== this.props.rows || nextProps.cols !== this.props.cols) {
this.resize(nextProps.cols, nextProps.rows);
2017-08-02 11:05:47 -08:00
}
2016-06-30 22:01:04 -08:00
}
2017-09-09 03:42:19 -08:00
onTermWrapperRef(component) {
this.termWrapperRef = component;
if (component) {
this.resizeObserver = new ResizeObserver(() => {
if (this.resizeTimeout) {
return;
}
this.resizeTimeout = setTimeout(() => {
delete this.resizeTimeout;
this.fitResize();
}, 0);
});
this.resizeObserver.observe(component);
} else {
this.resizeObserver.disconnect();
}
2017-09-09 03:42:19 -08:00
}
componentWillUnmount() {
2017-09-09 03:42:19 -08:00
terms[this.props.uid] = null;
this.termWrapperRef.removeChild(this.termRef);
2017-09-09 03:42:19 -08:00
this.props.ref_(this.props.uid, null);
2017-08-02 11:05:47 -08:00
// to clean up the terminal, we remove the listeners
// instead of invoking `destroy`, since it will make the
2017-08-02 11:05:47 -08:00
// term insta un-attachable in the future (which we need
// to do in case of splitting, see `componentDidMount`
2018-12-06 14:56:29 -09:00
this.disposableListeners.forEach(handler => handler.dispose());
this.disposableListeners = [];
2017-08-02 11:05:47 -08:00
window.removeEventListener('paste', this.onWindowPaste, {
capture: true
});
2016-06-30 22:01:04 -08:00
}
render() {
return (
2017-10-24 14:06:46 -08:00
<div
className={`term_fit ${this.props.isTermActive ? 'term_active' : ''}`}
2017-10-24 14:06:46 -08:00
style={{padding: this.props.padding}}
onMouseUp={this.onMouseUp}
>
{this.props.customChildrenBefore}
<div ref={this.onTermWrapperRef} className="term_fit term_wrapper" />
{this.props.customChildren}
<style jsx global>{`
.term_fit {
display: block;
width: 100%;
height: 100%;
}
.term_wrapper {
/* TODO: decide whether to keep this or not based on understanding what xterm-selection is for */
overflow: hidden;
}
`}</style>
2017-08-02 11:05:47 -08:00
</div>
);
2016-06-30 22:01:04 -08:00
}
}