hyper/app/session.js

91 lines
2 KiB
JavaScript
Raw Normal View History

const {EventEmitter} = require('events');
const {StringDecoder} = require('string_decoder');
const {app} = require('electron');
const defaultShell = require('default-shell');
const {getDecoratedEnv} = require('./plugins');
const {productName, version} = require('./package');
const config = require('./config');
2016-06-30 22:01:04 -08:00
2016-07-13 13:06:05 -08:00
let spawn;
try {
spawn = require('child_pty').spawn;
} catch (err) {
console.error(
'A native module failed to load. Typically this means ' +
'you installed the modules incorrectly.\n Use `scripts/install.sh` ' +
'to trigger the installation.\n ' +
2016-10-06 07:28:43 -08:00
'More information: https://github.com/zeit/hyper/issues/72'
2016-07-13 13:06:05 -08:00
);
}
const envFromConfig = config.getConfig().env || {};
2016-06-30 22:01:04 -08:00
module.exports = class Session extends EventEmitter {
constructor({rows, cols: columns, cwd, shell, shellArgs}) {
2016-06-30 22:01:04 -08:00
super();
const baseEnv = Object.assign({}, process.env, {
LANG: app.getLocale().replace('-', '_') + '.UTF-8',
TERM: 'xterm-256color',
TERM_PROGRAM: productName,
TERM_PROGRAM_VERSION: version
}, envFromConfig);
const decoder = new StringDecoder('utf8');
const defaultShellArgs = ['--login'];
this.pty = spawn(shell || defaultShell, shellArgs || defaultShellArgs, {
2016-07-03 12:35:45 -08:00
columns,
2016-06-30 22:01:04 -08:00
rows,
cwd,
env: getDecoratedEnv(baseEnv)
2016-06-30 22:01:04 -08:00
});
this.pty.stdout.on('data', data => {
if (this.ended) {
return;
}
this.emit('data', decoder.write(data));
2016-06-30 22:01:04 -08:00
});
this.pty.on('exit', () => {
if (!this.ended) {
this.ended = true;
this.emit('exit');
}
});
2016-07-23 16:57:47 -08:00
this.shell = shell || defaultShell;
2016-06-30 22:01:04 -08:00
}
exit() {
2016-06-30 22:01:04 -08:00
this.destroy();
}
write(data) {
2016-06-30 22:01:04 -08:00
this.pty.stdin.write(data);
}
resize({cols: columns, rows}) {
2016-06-30 22:01:04 -08:00
try {
this.pty.stdout.resize({columns, rows});
2016-06-30 22:01:04 -08:00
} catch (err) {
2016-06-30 22:25:19 -08:00
console.error(err.stack);
2016-06-30 22:01:04 -08:00
}
}
destroy() {
2016-07-03 12:35:45 -08:00
try {
this.pty.kill('SIGHUP');
} catch (err) {
console.error('exit error', err.stack);
}
2016-06-30 22:01:04 -08:00
this.emit('exit');
this.ended = true;
}
};