cleanup session creation and fix types

This commit is contained in:
Labhansh Agrawal 2023-06-26 19:43:05 +05:30
parent 5f0e80df08
commit 4d2a1668e4
4 changed files with 50 additions and 52 deletions

View file

@ -84,11 +84,11 @@ class DataBatcher extends EventEmitter {
interface SessionOptions { interface SessionOptions {
uid: string; uid: string;
rows: number; rows?: number;
cols: number; cols?: number;
cwd: string; cwd?: string;
shell: string; shell?: string;
shellArgs: string[]; shellArgs?: string[];
} }
export default class Session extends EventEmitter { export default class Session extends EventEmitter {
pty: IPty | null; pty: IPty | null;
@ -106,22 +106,23 @@ export default class Session extends EventEmitter {
this.init(options); this.init(options);
} }
init({uid, rows, cols: columns, cwd, shell: _shell, shellArgs: _shellArgs}: SessionOptions) { init({uid, rows, cols, cwd, shell: _shell, shellArgs: _shellArgs}: SessionOptions) {
const defaultShellArgs = ['--login'];
const shell = _shell || defaultShell;
const shellArgs = _shellArgs || defaultShellArgs;
const cleanEnv = const cleanEnv =
process.env['APPIMAGE'] && process.env['APPDIR'] ? shellEnv.sync(_shell || defaultShell) : process.env; process.env['APPIMAGE'] && process.env['APPDIR'] ? shellEnv.sync(_shell || defaultShell) : process.env;
const baseEnv = Object.assign( const baseEnv: Record<string, string> = {
{}, ...cleanEnv,
cleanEnv,
{
LANG: `${osLocale.sync().replace(/-/, '_')}.UTF-8`, LANG: `${osLocale.sync().replace(/-/, '_')}.UTF-8`,
TERM: 'xterm-256color', TERM: 'xterm-256color',
COLORTERM: 'truecolor', COLORTERM: 'truecolor',
TERM_PROGRAM: productName, TERM_PROGRAM: productName,
TERM_PROGRAM_VERSION: version TERM_PROGRAM_VERSION: version,
}, ...envFromConfig
envFromConfig };
);
// path to AppImage mount point is added to PATH environment variable automatically // path to AppImage mount point is added to PATH environment variable automatically
// which conflicts with the cli // which conflicts with the cli
if (baseEnv['APPIMAGE'] && baseEnv['APPDIR']) { if (baseEnv['APPIMAGE'] && baseEnv['APPDIR']) {
@ -137,10 +138,8 @@ export default class Session extends EventEmitter {
delete baseEnv.GOOGLE_API_KEY; delete baseEnv.GOOGLE_API_KEY;
} }
const defaultShellArgs = ['--login'];
const options: IWindowsPtyForkOptions = { const options: IWindowsPtyForkOptions = {
cols: columns, cols,
rows, rows,
cwd, cwd,
env: getDecoratedEnv(baseEnv) env: getDecoratedEnv(baseEnv)
@ -151,9 +150,6 @@ export default class Session extends EventEmitter {
options.useConpty = useConpty; options.useConpty = useConpty;
} }
const shell = _shell || defaultShell;
const shellArgs = _shellArgs || defaultShellArgs;
try { try {
this.pty = spawn(shell, shellArgs, options); this.pty = spawn(shell, shellArgs, options);
} catch (_err) { } catch (_err) {
@ -191,7 +187,7 @@ fallback to default shell config: ${JSON.stringify(defaultShellConfig, undefined
`; `;
console.warn(msg); console.warn(msg);
this.batcher?.write(msg.replace(/\n/g, '\r\n') as any); this.batcher?.write(msg.replace(/\n/g, '\r\n') as any);
this.init({uid, rows, cols: columns, cwd, ...defaultShellConfig}); this.init({uid, rows, cols, cwd, ...defaultShellConfig});
} else { } else {
this.ended = true; this.ended = true;
this.emit('exit'); this.emit('exit');

View file

@ -19,6 +19,7 @@ import {enable as remoteEnable} from '@electron/remote/main';
import type {configOptions} from '../../lib/config'; import type {configOptions} from '../../lib/config';
import {getWorkingDirectoryFromPID} from 'native-process-working-directory'; import {getWorkingDirectoryFromPID} from 'native-process-working-directory';
import {existsSync} from 'fs'; import {existsSync} from 'fs';
import type {sessionExtraOptions} from '../../common';
export function newWindow( export function newWindow(
options_: BrowserWindowConstructorOptions, options_: BrowserWindowConstructorOptions,
@ -125,21 +126,24 @@ export function newWindow(
} }
}); });
function createSession(extraOptions: any = {}) { function createSession(extraOptions: sessionExtraOptions = {}) {
const uid = uuidv4(); const uid = uuidv4();
const extraOptionsFiltered: any = {}; const extraOptionsFiltered: sessionExtraOptions = {};
Object.keys(extraOptions).forEach((key) => { Object.keys(extraOptions).forEach((key) => {
if (extraOptions[key] !== undefined) extraOptionsFiltered[key] = extraOptions[key]; if (extraOptions[key] !== undefined) extraOptionsFiltered[key] = extraOptions[key];
}); });
let cwd = ''; let cwd = '';
if (cfg.preserveCWD === undefined || cfg.preserveCWD) { if (cfg.preserveCWD === undefined || cfg.preserveCWD) {
const activePID = extraOptionsFiltered.activeUid && sessions.get(extraOptionsFiltered.activeUid)?.pty?.pid; const activeUid = extraOptionsFiltered.activeUid;
const activePID = activeUid ? sessions.get(activeUid)?.pty?.pid : undefined;
if (activePID !== undefined) {
try { try {
cwd = activePID && getWorkingDirectoryFromPID(activePID); cwd = getWorkingDirectoryFromPID(activePID) || '';
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
}
cwd = cwd && isAbsolute(cwd) && existsSync(cwd) ? cwd : ''; cwd = cwd && isAbsolute(cwd) && existsSync(cwd) ? cwd : '';
} }
@ -172,7 +176,7 @@ export function newWindow(
splitDirection: options.splitDirection, splitDirection: options.splitDirection,
shell: session.shell, shell: session.shell,
pid: session.pty ? session.pty.pid : null, pid: session.pty ? session.pty.pid : null,
activeUid: options.activeUid activeUid: options.activeUid ?? undefined
}); });
session.on('data', (data: string) => { session.on('data', (data: string) => {
@ -238,11 +242,12 @@ export function newWindow(
// Same deal as above, grabbing the window titlebar when the window // Same deal as above, grabbing the window titlebar when the window
// is maximized on Windows results in unmaximize, without hitting any // is maximized on Windows results in unmaximize, without hitting any
// app buttons // app buttons
for (const ev of ['maximize', 'unmaximize', 'minimize', 'restore'] as any) { const onGeometryChange = () => rpc.emit('windowGeometry change', {isMaximized: window.isMaximized()});
window.on(ev, () => { window.on('maximize', onGeometryChange);
rpc.emit('windowGeometry change', {isMaximized: window.isMaximized()}); window.on('unmaximize', onGeometryChange);
}); window.on('minimize', onGeometryChange);
} window.on('restore', onGeometryChange);
window.on('move', () => { window.on('move', () => {
const position = window.getPosition(); const position = window.getPosition();
rpc.emit('move', {bounds: {x: position[0], y: position[1]}}); rpc.emit('move', {bounds: {x: position[0], y: position[1]}});

10
common.d.ts vendored
View file

@ -4,8 +4,8 @@ import type {ExecFileOptions, ExecOptions} from 'child_process';
export type Session = { export type Session = {
uid: string; uid: string;
rows: number | null; rows?: number | null;
cols: number | null; cols?: number | null;
splitDirection?: 'HORIZONTAL' | 'VERTICAL'; splitDirection?: 'HORIZONTAL' | 'VERTICAL';
shell: string | null; shell: string | null;
pid: number | null; pid: number | null;
@ -13,10 +13,14 @@ export type Session = {
}; };
export type sessionExtraOptions = { export type sessionExtraOptions = {
cwd: string | undefined; cwd?: string;
splitDirection?: 'HORIZONTAL' | 'VERTICAL'; splitDirection?: 'HORIZONTAL' | 'VERTICAL';
activeUid?: string | null; activeUid?: string | null;
isNewGroup?: boolean; isNewGroup?: boolean;
rows?: number;
cols?: number;
shell?: string;
shellArgs?: string[];
}; };
export type MainEvents = { export type MainEvents = {

View file

@ -15,17 +15,10 @@ import {
SESSION_SET_XTERM_TITLE, SESSION_SET_XTERM_TITLE,
SESSION_SEARCH SESSION_SEARCH
} from '../constants/sessions'; } from '../constants/sessions';
import type {HyperState, session, HyperDispatch, HyperActions} from '../hyper'; import type {HyperState, HyperDispatch, HyperActions} from '../hyper';
import type {Session} from '../../common';
export function addSession({ export function addSession({uid, shell, pid, cols = null, rows = null, splitDirection, activeUid}: Session) {
uid,
shell,
pid,
cols,
rows,
splitDirection,
activeUid
}: Pick<session, 'uid' | 'shell' | 'pid' | 'cols' | 'rows' | 'splitDirection' | 'activeUid'>) {
return (dispatch: HyperDispatch, getState: () => HyperState) => { return (dispatch: HyperDispatch, getState: () => HyperState) => {
const {sessions} = getState(); const {sessions} = getState();
const now = Date.now(); const now = Date.now();