//! Terminal emulation and local PTY transport. //! //! The emulator is intentionally independent from the Iced GUI and from the //! transport. `Emulator` only parses bytes into a screen, so an SSH session can //! later feed it the same way a local PTY does. use std::path::Path; use iced::Color; use iced::keyboard; #[derive(Debug, Clone, Copy, PartialEq)] pub struct Theme { pub background: Color, pub foreground: Color, pub cursor: Color, pub selection: Color, pub ansi: [Color; 16], } impl Default for Theme { fn default() -> Self { Self::DARK } } impl Theme { pub const DARK: Self = Self { background: Color::from_rgb8(0x1e, 0x1e, 0x1e), foreground: Color::from_rgb8(0xd4, 0xd4, 0xd4), cursor: Color::from_rgb8(0xd4, 0xd4, 0xd4), selection: Color::from_rgb8(0x3a, 0x3a, 0x3a), ansi: [ Color::from_rgb8(0x00, 0x00, 0x00), Color::from_rgb8(0xcd, 0x31, 0x31), Color::from_rgb8(0x0d, 0xbc, 0x79), Color::from_rgb8(0xe5, 0xe5, 0x10), Color::from_rgb8(0x24, 0x72, 0xc8), Color::from_rgb8(0xbc, 0x3f, 0xbc), Color::from_rgb8(0x11, 0xa8, 0xcd), Color::from_rgb8(0xe5, 0xe5, 0xe5), Color::from_rgb8(0x66, 0x66, 0x66), Color::from_rgb8(0xf1, 0x4c, 0x4c), Color::from_rgb8(0x23, 0xd1, 0x8b), Color::from_rgb8(0xf5, 0xf5, 0x43), Color::from_rgb8(0x3b, 0x8e, 0xea), Color::from_rgb8(0xd6, 0x70, 0xd6), Color::from_rgb8(0x29, 0xb8, 0xdb), Color::from_rgb8(0xff, 0xff, 0xff), ], }; /// Maps a parsed terminal color to the palette used by the canvas. pub fn color(self, color: vt100::Color, default: Color) -> Color { match color { vt100::Color::Default => default, vt100::Color::Rgb(red, green, blue) => Color::from_rgb8(red, green, blue), vt100::Color::Idx(index) => self.indexed(index), } } fn indexed(self, index: u8) -> Color { if let Some(color) = self.ansi.get(index as usize) { return *color; } if index < 232 { const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255]; let index = index - 16; let red = LEVELS[(index / 36) as usize]; let green = LEVELS[((index % 36) / 6) as usize]; let blue = LEVELS[(index % 6) as usize]; Color::from_rgb8(red, green, blue) } else { let level = 8 + (index - 232) * 10; Color::from_rgb8(level, level, level) } } } /// Size of one character cell for the bundled monospace font. pub fn cell_size(font_size: f32) -> iced::Size { iced::Size::new((font_size * 0.6).max(1.0), (font_size * 1.25).max(1.0)) } /// Rows and columns that fit in `size`, never zero. pub fn grid_size(size: iced::Size, font_size: f32) -> (u16, u16) { let cell = cell_size(font_size); let rows = (size.height / cell.height).floor().max(1.0) as u16; let cols = (size.width / cell.width).floor().max(1.0) as u16; (rows, cols) } /// Default number of scrollback lines kept for each terminal session. pub const DEFAULT_SCROLLBACK_SIZE: usize = 10_000; /// Upper bound for the configurable scrollback size. pub const MAX_SCROLLBACK_SIZE: usize = 1_000_000; /// Parsed terminal screen. This has no knowledge of where the bytes came from. pub struct Emulator { parser: vt100::Parser, } impl Emulator { pub fn new(rows: u16, cols: u16, scrollback: usize) -> Self { let rows = std::num::NonZeroU16::new(rows.max(1)).unwrap(); let cols = std::num::NonZeroU16::new(cols.max(1)).unwrap(); Self { parser: vt100::Parser::new(rows, cols, scrollback), } } pub fn process(&mut self, bytes: &[u8]) { self.parser.process(bytes); } pub fn resize(&mut self, rows: u16, cols: u16) { let rows = std::num::NonZeroU16::new(rows.max(1)).unwrap(); let cols = std::num::NonZeroU16::new(cols.max(1)).unwrap(); self.parser.set_size(rows, cols); } pub fn screen(&self) -> &vt100::Screen { self.parser.screen() } } /// How a process ended. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ExitInfo { pub code: Option, pub signal: Option, } /// Which shell a local terminal should start. The platform transport decides /// how the choice maps to an executable. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Shell { Default, PowerShell, } impl Shell { /// Why this shell cannot run on the current system, or `None` when it can. /// /// Availability is derived from the filesystem each time it is asked, so a /// profile copied from another platform works as soon as the executable is /// installed. It is never stored in profile files. pub fn unavailable_reason(self) -> Option { match self { Self::Default => None, Self::PowerShell => power_shell_program().err(), } } } /// Resolves the executable for a shell, returning a user-facing error when it /// is missing. fn shell_program(shell: Shell) -> Result { match shell { Shell::Default => Ok(default_shell_program()), Shell::PowerShell => power_shell_program().map(std::path::PathBuf::into_os_string), } } #[cfg(unix)] fn default_shell_program() -> std::ffi::OsString { std::env::var_os("SHELL") .filter(|shell| !shell.is_empty()) .unwrap_or_else(|| "/bin/sh".into()) } #[cfg(windows)] fn default_shell_program() -> std::ffi::OsString { std::env::var_os("COMSPEC") .filter(|value| !value.is_empty()) .unwrap_or_else(|| "cmd.exe".into()) } /// Finds PowerShell 7 first, then falls back to Windows PowerShell on Windows. #[cfg(windows)] fn power_shell_program() -> Result { if let Some(path) = find_in_path("pwsh.exe").or_else(|| { std::env::var_os("ProgramFiles") .map(std::path::PathBuf::from) .map(|dir| dir.join("PowerShell").join("7").join("pwsh.exe")) .filter(|path| path.is_file()) }) { return Ok(path); } if let Some(path) = find_in_path("powershell.exe").or_else(|| { std::env::var_os("SystemRoot") .map(std::path::PathBuf::from) .map(|dir| { dir.join("System32") .join("WindowsPowerShell") .join("v1.0") .join("powershell.exe") }) .filter(|path| path.is_file()) }) { return Ok(path); } Err(power_shell_missing()) } #[cfg(unix)] fn power_shell_program() -> Result { find_in_path("pwsh").ok_or_else(power_shell_missing) } fn power_shell_missing() -> String { if cfg!(windows) { "PowerShell was not found. Install PowerShell 7 (pwsh.exe) or enable Windows PowerShell (powershell.exe).".to_owned() } else { "PowerShell was not found. Install PowerShell 7 (pwsh) to run this profile.".to_owned() } } fn find_in_path(name: &str) -> Option { let path = std::env::var_os("PATH")?; find_in_search_path(name, &path) } fn find_in_search_path(name: &str, search_path: &std::ffi::OsStr) -> Option { std::env::split_paths(search_path) .map(|dir| dir.join(name)) .find(|candidate| is_executable(candidate)) } #[cfg(unix)] fn is_executable(path: &Path) -> bool { use std::os::unix::fs::PermissionsExt; path.metadata() .is_ok_and(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0) } #[cfg(windows)] fn is_executable(path: &Path) -> bool { path.is_file() } /// A running terminal session: an emulator fed by a local PTY. pub struct Session { emulator: Emulator, pty: pty::Pty, } impl Session { pub fn spawn(start_dir: &Path, rows: u16, cols: u16) -> Result { Self::spawn_with_scrollback( start_dir, rows, cols, Shell::Default, DEFAULT_SCROLLBACK_SIZE, ) } pub fn spawn_with_scrollback( start_dir: &Path, rows: u16, cols: u16, shell: Shell, scrollback: usize, ) -> Result { let pty = pty::Pty::spawn_with(start_dir, rows, cols, shell)?; Ok(Self { emulator: Emulator::new(rows, cols, scrollback), pty, }) } /// Reads pending output and returns an exit notification when the process /// has ended. pub fn poll(&mut self) -> Option { let mut exit = None; while let Some(event) = self.pty.try_recv() { match event { pty::Event::Output(bytes) => self.emulator.process(&bytes), pty::Event::Exited(info) => exit = Some(info), } } exit } pub fn write(&mut self, bytes: &[u8]) -> Result<(), String> { self.pty.write(bytes) } pub fn resize(&mut self, rows: u16, cols: u16) -> Result<(), String> { self.emulator.resize(rows, cols); self.pty.resize(rows, cols) } pub fn screen(&self) -> &vt100::Screen { self.emulator.screen() } #[cfg(all(test, unix))] fn pid(&self) -> i32 { self.pty.pid() } } /// Converts an Iced key press into the bytes a terminal expects. /// /// `text` is the layout-resolved text supplied by Iced/winit. It already /// includes Shift, AltGr, dead-key composition and Caps Lock, so printable /// input is forwarded as UTF-8 instead of being reconstructed from key codes. pub fn key_bytes( key: &keyboard::Key, text: Option<&str>, modifiers: keyboard::Modifiers, application_cursor: bool, ) -> Option> { if let keyboard::Key::Named(named) = key.as_ref() && is_special_key(named) { return special_key_bytes(named, modifiers, application_cursor); } if let Some(text) = text.filter(|text| !text.is_empty()) { return text_bytes(text, modifiers); } // Fallback for platforms that do not report text for Ctrl/Alt combinations. if let keyboard::Key::Character(character) = key.as_ref() { let mut chars = character.chars(); let character = chars.next()?; if chars.next().is_some() { return None; } if modifiers.control() && !modifiers.alt() { return control_byte(character).map(|byte| vec![byte]); } if modifiers.alt() && !modifiers.control() { let mut bytes = vec![0x1b]; bytes.extend_from_slice(character.to_string().as_bytes()); return Some(bytes); } } None } fn text_bytes(text: &str, modifiers: keyboard::Modifiers) -> Option> { let contains_control = text.chars().any(char::is_control); // Some platforms return the printable character for Ctrl+letter, while // others return the control character already. if !contains_control && modifiers.control() && !modifiers.alt() { let mut chars = text.chars(); if let (Some(character), None) = (chars.next(), chars.next()) && let Some(control) = control_byte(character) { return Some(vec![control]); } } let mut bytes = Vec::new(); // AltGr is reported as Ctrl+Alt on Windows; only a plain Alt is a meta // prefix. This keeps AltGr-produced characters intact. if modifiers.alt() && !modifiers.control() { bytes.push(0x1b); } bytes.extend_from_slice(text.as_bytes()); Some(bytes) } fn is_special_key(named: keyboard::key::Named) -> bool { use keyboard::key::Named; matches!( named, Named::Enter | Named::Tab | Named::Backspace | Named::Escape | Named::ArrowUp | Named::ArrowDown | Named::ArrowLeft | Named::ArrowRight | Named::Home | Named::End | Named::Insert | Named::Delete | Named::PageUp | Named::PageDown | Named::F1 | Named::F2 | Named::F3 | Named::F4 | Named::F5 | Named::F6 | Named::F7 | Named::F8 | Named::F9 | Named::F10 | Named::F11 | Named::F12 ) } fn special_key_bytes( named: keyboard::key::Named, modifiers: keyboard::Modifiers, application_cursor: bool, ) -> Option> { use keyboard::key::Named; let shift = modifiers.shift(); let ctrl = modifiers.control(); let alt = modifiers.alt(); let parameter = 1 + u8::from(shift) + 2 * u8::from(alt) + 4 * u8::from(ctrl); match named { Named::Enter => { let mut bytes = Vec::new(); if alt && !ctrl { bytes.push(0x1b); } bytes.push(b'\r'); Some(bytes) } Named::Backspace => { let mut bytes = Vec::new(); if alt && !ctrl { bytes.push(0x1b); } bytes.push(if ctrl { 0x08 } else { 0x7f }); Some(bytes) } Named::Tab => Some(tab_bytes(shift, ctrl, alt, parameter)), Named::Escape => { let mut bytes = Vec::new(); if alt && !ctrl { bytes.push(0x1b); } bytes.push(0x1b); Some(bytes) } Named::ArrowUp => cursor_key(b'A', parameter, application_cursor), Named::ArrowDown => cursor_key(b'B', parameter, application_cursor), Named::ArrowRight => cursor_key(b'C', parameter, application_cursor), Named::ArrowLeft => cursor_key(b'D', parameter, application_cursor), Named::Home => cursor_key(b'H', parameter, false), Named::End => cursor_key(b'F', parameter, false), Named::Insert => tilde_key(2, parameter), Named::Delete => tilde_key(3, parameter), Named::PageUp => tilde_key(5, parameter), Named::PageDown => tilde_key(6, parameter), Named::F1 => function_key(b'P', parameter), Named::F2 => function_key(b'Q', parameter), Named::F3 => function_key(b'R', parameter), Named::F4 => function_key(b'S', parameter), Named::F5 => tilde_key(15, parameter), Named::F6 => tilde_key(17, parameter), Named::F7 => tilde_key(18, parameter), Named::F8 => tilde_key(19, parameter), Named::F9 => tilde_key(20, parameter), Named::F10 => tilde_key(21, parameter), Named::F11 => tilde_key(23, parameter), Named::F12 => tilde_key(24, parameter), _ => None, } } fn tab_bytes(shift: bool, ctrl: bool, alt: bool, parameter: u8) -> Vec { if shift && !ctrl && !alt { b"\x1b[Z".to_vec() } else if alt && !ctrl && !shift { b"\x1b\t".to_vec() } else if parameter == 1 { b"\t".to_vec() } else { format!("\x1b[1;{parameter}Z").into_bytes() } } fn cursor_key(final_byte: u8, parameter: u8, application_cursor: bool) -> Option> { if parameter == 1 { let mut bytes = if application_cursor { b"\x1bO".to_vec() } else { b"\x1b[".to_vec() }; bytes.push(final_byte); Some(bytes) } else { Some(format!("\x1b[1;{parameter}{}", final_byte as char).into_bytes()) } } fn tilde_key(number: u8, parameter: u8) -> Option> { if parameter == 1 { Some(format!("\x1b[{number}~").into_bytes()) } else { Some(format!("\x1b[{number};{parameter}~").into_bytes()) } } fn function_key(letter: u8, parameter: u8) -> Option> { if parameter == 1 { Some(format!("\x1bO{}", letter as char).into_bytes()) } else { Some(format!("\x1b[1;{parameter}{}", letter as char).into_bytes()) } } fn control_byte(character: char) -> Option { match character { 'a'..='z' => Some(character as u8 & 0x1f), 'A'..='Z' => Some(character as u8 & 0x1f), '@' | ' ' => Some(0), '[' => Some(0x1b), '\\' => Some(0x1c), ']' => Some(0x1d), '^' => Some(0x1e), '_' => Some(0x1f), '?' => Some(0x7f), _ => None, } } #[cfg(unix)] mod pty { use std::ffi::{CString, OsStr}; use std::fs::File; use std::io::{Read, Write}; use std::os::fd::AsRawFd; use std::os::unix::ffi::OsStrExt; use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, channel}; use nix::libc; use nix::pty::{ForkptyResult, Winsize, forkpty}; use nix::sys::signal::{Signal, killpg}; use nix::sys::wait::{WaitStatus, waitpid}; use nix::unistd::Pid; use super::{ExitInfo, Shell}; pub enum Event { Output(Vec), Exited(ExitInfo), } pub struct Pty { master: File, child: Pid, reaped: Arc, events: Receiver, } impl Pty { pub fn spawn(start_dir: &Path, rows: u16, cols: u16) -> Result { Self::spawn_with(start_dir, rows, cols, Shell::Default) } pub fn spawn_with( start_dir: &Path, rows: u16, cols: u16, shell: Shell, ) -> Result { let program = super::shell_program(shell)?; Self::spawn_shell(start_dir, rows, cols, &program) } fn spawn_shell( start_dir: &Path, rows: u16, cols: u16, shell: &OsStr, ) -> Result { let shell = CString::new(shell.as_bytes()) .map_err(|_| "The configured shell path is invalid.".to_owned())?; let cwd = CString::new(start_dir.as_os_str().as_bytes()) .map_err(|_| "The start directory path is invalid.".to_owned())?; // Prepare everything the child needs before forking. Only // async-signal-safe calls are made after forkpty(). let args = [shell.clone()]; let argv: Vec<*const libc::c_char> = args .iter() .map(|arg| arg.as_ptr()) .chain(std::iter::once(std::ptr::null())) .collect(); let mut environment: Vec = std::env::vars_os() .filter(|(key, _)| { !key.eq_ignore_ascii_case("TERM") && !key.eq_ignore_ascii_case("COLORTERM") && !key.eq_ignore_ascii_case("TERM_PROGRAM") }) .filter_map(|(key, value)| { let mut entry = key.into_encoded_bytes(); entry.push(b'='); entry.extend_from_slice(value.into_encoded_bytes().as_slice()); CString::new(entry).ok() }) .collect(); environment.push(CString::new("TERM=xterm-256color").unwrap()); environment.push(CString::new("COLORTERM=truecolor").unwrap()); environment.push(CString::new("TERM_PROGRAM=Moorly").unwrap()); let envp: Vec<*const libc::c_char> = environment .iter() .map(|entry| entry.as_ptr()) .chain(std::iter::once(std::ptr::null())) .collect(); let winsize = Winsize { ws_row: rows.max(1), ws_col: cols.max(1), ws_xpixel: 0, ws_ypixel: 0, }; let result = unsafe { forkpty(Some(&winsize), None) }.map_err(|error| error.to_string())?; match result { ForkptyResult::Parent { master, child } => { let master = File::from(master); let mut reader = master .try_clone() .map_err(|error| format!("Could not read from the terminal: {error}"))?; let (sender, events) = channel(); let reaped = Arc::new(AtomicBool::new(false)); let child_reaped = reaped.clone(); std::thread::spawn(move || { let mut buffer = [0u8; 8192]; loop { match reader.read(&mut buffer) { Ok(0) => break, Ok(count) => { if sender .send(Event::Output(buffer[..count].to_vec())) .is_err() { break; } } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} Err(_) => break, } } let info = match waitpid(child, None) { Ok(WaitStatus::Exited(_, code)) => ExitInfo { code: Some(code), signal: None, }, Ok(WaitStatus::Signaled(_, signal, _)) => ExitInfo { code: None, signal: Some(signal as i32), }, _ => ExitInfo { code: None, signal: None, }, }; child_reaped.store(true, Ordering::SeqCst); let _ = sender.send(Event::Exited(info)); }); Ok(Self { master, child, reaped, events, }) } ForkptyResult::Child => { // SAFETY: all pointers below were allocated before the // fork, and only async-signal-safe functions are used. unsafe { if libc::chdir(cwd.as_ptr()) != 0 { libc::_exit(1); } libc::execve(shell.as_ptr(), argv.as_ptr(), envp.as_ptr()); libc::_exit(1); } } } } pub fn write(&mut self, bytes: &[u8]) -> Result<(), String> { self.master .write_all(bytes) .map_err(|error| error.to_string()) } pub fn resize(&mut self, rows: u16, cols: u16) -> Result<(), String> { let winsize = Winsize { ws_row: rows.max(1), ws_col: cols.max(1), ws_xpixel: 0, ws_ypixel: 0, }; let result = unsafe { libc::ioctl( self.master.as_raw_fd(), libc::TIOCSWINSZ, &winsize as *const Winsize, ) }; if result == -1 { Err(std::io::Error::last_os_error().to_string()) } else { Ok(()) } } pub fn try_recv(&self) -> Option { self.events.try_recv().ok() } #[cfg(test)] pub fn pid(&self) -> i32 { self.child.as_raw() } } impl Drop for Pty { fn drop(&mut self) { // The reader thread reaps the child. Once that has happened the // PID may be reused, so never signal it afterwards. if !self.reaped.load(Ordering::SeqCst) { let _ = killpg(self.child, Signal::SIGHUP); let _ = killpg(self.child, Signal::SIGKILL); } } } #[cfg(test)] impl Pty { pub fn spawn_for_test(start_dir: &Path, rows: u16, cols: u16) -> Result { Self::spawn_shell(start_dir, rows, cols, OsStr::new("/bin/sh")) } } } #[cfg(windows)] mod pty { use std::ffi::{OsStr, OsString}; use std::fs::File; use std::io::{Read, Write}; use std::os::windows::ffi::OsStrExt; use std::os::windows::io::{FromRawHandle, RawHandle}; use std::path::Path; use std::ptr; use std::sync::mpsc::{Receiver, channel}; use windows_sys::Win32::Foundation::{CloseHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows_sys::Win32::System::Console::{ COORD, ClosePseudoConsole, CreatePseudoConsole, HPCON, ResizePseudoConsole, }; use windows_sys::Win32::System::Pipes::CreatePipe; use windows_sys::Win32::System::Threading::{ CreateProcessW, DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT, GetCurrentProcess, GetExitCodeProcess, INFINITE, InitializeProcThreadAttributeList, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, PROCESS_INFORMATION, STARTUPINFOEXW, TerminateProcess, UpdateProcThreadAttribute, WaitForSingleObject, }; use super::{ExitInfo, Shell}; pub enum Event { Output(Vec), Exited(ExitInfo), } pub struct Pty { input: File, process: HANDLE, console: HPCON, events: Receiver, } impl Pty { pub fn spawn(start_dir: &Path, rows: u16, cols: u16) -> Result { Self::spawn_with(start_dir, rows, cols, Shell::Default) } pub fn spawn_with( start_dir: &Path, rows: u16, cols: u16, shell: Shell, ) -> Result { let program = super::shell_program(shell)?; Self::spawn_shell(start_dir, rows, cols, &program) } fn spawn_shell( start_dir: &Path, rows: u16, cols: u16, program: &OsStr, ) -> Result { let size = COORD { X: dimension(cols), Y: dimension(rows), }; let mut input_read: HANDLE = ptr::null_mut(); let mut input_write: HANDLE = ptr::null_mut(); let mut output_read: HANDLE = ptr::null_mut(); let mut output_write: HANDLE = ptr::null_mut(); if unsafe { CreatePipe(&mut input_read, &mut input_write, ptr::null(), 0) } == 0 { return Err(last_error("Could not create the terminal input pipe")); } if unsafe { CreatePipe(&mut output_read, &mut output_write, ptr::null(), 0) } == 0 { let error = last_error("Could not create the terminal output pipe"); close(input_read); close(input_write); return Err(error); } let mut console: HPCON = 0; let created = unsafe { CreatePseudoConsole(size, input_read, output_write, 0, &mut console) }; if created < 0 { close_many(&[input_read, input_write, output_read, output_write]); return Err(hresult("Could not create the pseudoconsole", created)); } let mut attribute_size = 0usize; unsafe { InitializeProcThreadAttributeList(ptr::null_mut(), 1, 0, &mut attribute_size); } if attribute_size == 0 { let error = last_error("Could not size the process attribute list"); close_many(&[input_read, input_write, output_read, output_write]); unsafe { ClosePseudoConsole(console) }; return Err(error); } let mut attributes = vec![0u8; attribute_size]; let mut startup: STARTUPINFOEXW = unsafe { std::mem::zeroed() }; startup.StartupInfo.cb = std::mem::size_of::() as u32; startup.lpAttributeList = attributes.as_mut_ptr().cast(); if unsafe { InitializeProcThreadAttributeList( startup.lpAttributeList, 1, 0, &mut attribute_size, ) } == 0 { let error = last_error("Could not initialize the process attribute list"); close_many(&[input_read, input_write, output_read, output_write]); unsafe { ClosePseudoConsole(console) }; return Err(error); } // `PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE` expects the HPCON value // itself in lpValue, not a pointer to the variable holding it. let updated = unsafe { UpdateProcThreadAttribute( startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE as usize, console as *const _, std::mem::size_of::(), ptr::null_mut(), ptr::null(), ) }; if updated == 0 { let error = last_error("Could not attach the pseudoconsole to the process"); unsafe { DeleteProcThreadAttributeList(startup.lpAttributeList) }; close_many(&[input_read, input_write, output_read, output_write]); unsafe { ClosePseudoConsole(console) }; return Err(error); } // CreateProcessW parses a mutable command line. Quoting keeps // shell paths with spaces intact, and the wide string preserves // Unicode characters in the path. let mut command_line = command_line(program); let current_dir: Vec = start_dir .as_os_str() .encode_wide() .chain(std::iter::once(0)) .collect(); let mut process_info: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; let spawned = unsafe { CreateProcessW( ptr::null(), command_line.as_mut_ptr(), ptr::null(), ptr::null(), 0, EXTENDED_STARTUPINFO_PRESENT, ptr::null(), current_dir.as_ptr(), &startup.StartupInfo, &mut process_info, ) }; unsafe { DeleteProcThreadAttributeList(startup.lpAttributeList) }; if spawned == 0 { let error = last_error("Could not start the shell"); close_many(&[input_read, input_write, output_read, output_write]); unsafe { ClosePseudoConsole(console) }; return Err(error); } // These two ends belong to the pseudoconsole now. Keeping them // open would stop the output pipe from ever reaching EOF. close(input_read); close(output_write); close(process_info.hThread); // The waiter thread needs its own process handle because the Pty // owns the original for termination on drop. let mut wait_process: HANDLE = ptr::null_mut(); if unsafe { windows_sys::Win32::Foundation::DuplicateHandle( GetCurrentProcess(), process_info.hProcess, GetCurrentProcess(), &mut wait_process, 0, 0, DUPLICATE_SAME_ACCESS, ) } == 0 { let error = last_error("Could not prepare the terminal process handle"); unsafe { TerminateProcess(process_info.hProcess, 1); ClosePseudoConsole(console); } close_many(&[process_info.hProcess, input_write, output_read]); return Err(error); } let input = unsafe { File::from_raw_handle(input_write as RawHandle) }; let output = unsafe { File::from_raw_handle(output_read as RawHandle) }; let (sender, events) = channel(); let output_sender = sender.clone(); let mut output = output; std::thread::spawn(move || { read_output(&mut output, output_sender); }); // Raw HANDLE pointers are not `Send`, but Windows handles are // process-wide and safe to use from another thread. let wait_process = wait_process as usize; std::thread::spawn(move || { let wait_process = wait_process as HANDLE; unsafe { WaitForSingleObject(wait_process, INFINITE) }; let mut code = 0u32; let exit = if unsafe { GetExitCodeProcess(wait_process, &mut code) } == 0 { ExitInfo { code: None, signal: None, } } else { ExitInfo { code: Some(code as i32), signal: None, } }; close(wait_process); let _ = sender.send(Event::Exited(exit)); }); Ok(Self { input, process: process_info.hProcess, console, events, }) } pub fn write(&mut self, bytes: &[u8]) -> Result<(), String> { self.input .write_all(bytes) .map_err(|error| error.to_string()) } pub fn resize(&mut self, rows: u16, cols: u16) -> Result<(), String> { let size = COORD { X: dimension(cols), Y: dimension(rows), }; let result = unsafe { ResizePseudoConsole(self.console, size) }; if result < 0 { Err(hresult("Could not resize the pseudoconsole", result)) } else { Ok(()) } } pub fn try_recv(&self) -> Option { self.events.try_recv().ok() } } impl Drop for Pty { fn drop(&mut self) { unsafe { TerminateProcess(self.process, 1); ClosePseudoConsole(self.console); CloseHandle(self.process); } } } fn read_output(output: &mut File, sender: std::sync::mpsc::Sender) { let mut buffer = [0u8; 8192]; loop { match output.read(&mut buffer) { Ok(0) => break, Ok(count) => { if sender .send(Event::Output(buffer[..count].to_vec())) .is_err() { break; } } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} Err(_) => break, } } } fn command_line(program: &OsStr) -> Vec { let mut command = OsString::from("\""); command.push(program); command.push("\""); command.encode_wide().chain(std::iter::once(0)).collect() } fn dimension(value: u16) -> i16 { value.clamp(1, i16::MAX as u16) as i16 } fn close(handle: HANDLE) { if !handle.is_null() { unsafe { CloseHandle(handle) }; } } fn close_many(handles: &[HANDLE]) { for handle in handles { close(*handle); } } fn last_error(context: &str) -> String { format!("{context}: {}", std::io::Error::last_os_error()) } fn hresult(context: &str, result: i32) -> String { format!("{context} (HRESULT 0x{:08x}).", result as u32) } #[cfg(test)] mod tests { use super::*; #[test] fn console_dimensions_are_clamped_to_valid_coords() { assert_eq!(dimension(0), 1); assert_eq!(dimension(80), 80); assert_eq!(dimension(u16::MAX), i16::MAX); } #[test] fn command_lines_keep_spaces_and_unicode() { let mut line = command_line(OsStr::new("C:\\Program Files\\Mörk\\pwsh.exe")); assert_eq!(line.pop(), Some(0)); assert_eq!( String::from_utf16(&line).unwrap(), "\"C:\\Program Files\\Mörk\\pwsh.exe\"" ); } } } #[cfg(not(any(unix, windows)))] mod pty { use std::path::Path; use super::{ExitInfo, Shell}; pub enum Event { Output(Vec), Exited(ExitInfo), } pub struct Pty; impl Pty { pub fn spawn(_start_dir: &Path, _rows: u16, _cols: u16) -> Result { Err("Local terminal sessions are not supported on this platform yet.".to_owned()) } pub fn spawn_with( _start_dir: &Path, _rows: u16, _cols: u16, _shell: Shell, ) -> Result { Self::spawn(_start_dir, _rows, _cols) } pub fn write(&mut self, _bytes: &[u8]) -> Result<(), String> { Err("The terminal is not running.".to_owned()) } pub fn resize(&mut self, _rows: u16, _cols: u16) -> Result<(), String> { Err("The terminal is not running.".to_owned()) } pub fn try_recv(&self) -> Option { None } } } #[cfg(all(test, unix))] mod tests { use std::time::{Duration, Instant}; use super::*; fn session() -> Session { let pty = pty::Pty::spawn_for_test(Path::new("/"), 24, 80).unwrap(); Session { emulator: Emulator::new(24, 80, DEFAULT_SCROLLBACK_SIZE), pty, } } #[test] fn power_shell_lookup_finds_executables_and_reports_missing() { use std::os::unix::fs::PermissionsExt; let root = std::env::temp_dir().join(format!("moorly-pwsh-{}", std::process::id())); let bin = root.join("bin"); std::fs::create_dir_all(&bin).unwrap(); let pwsh = bin.join("pwsh"); std::fs::write(&pwsh, "#!/bin/sh\n").unwrap(); std::fs::set_permissions(&pwsh, std::fs::Permissions::from_mode(0o755)).unwrap(); assert_eq!( find_in_search_path("pwsh", bin.as_os_str()), Some(pwsh.clone()) ); assert_eq!( find_in_search_path("pwsh", root.join("empty").as_os_str()), None ); // A non-executable file is not a usable shell. let plain_dir = root.join("plain"); std::fs::create_dir_all(&plain_dir).unwrap(); std::fs::write(plain_dir.join("pwsh"), "").unwrap(); assert_eq!(find_in_search_path("pwsh", plain_dir.as_os_str()), None); assert!(power_shell_missing().contains("PowerShell")); std::fs::remove_dir_all(&root).unwrap(); } #[test] fn missing_power_shell_never_falls_back_to_the_default_shell() { if Shell::PowerShell.unavailable_reason().is_some() { let result = pty::Pty::spawn_with(Path::new("/"), 24, 80, Shell::PowerShell); assert!(result.is_err(), "PowerShell silently started another shell"); } } #[test] fn grid_never_has_zero_cells() { assert_eq!(grid_size(iced::Size::new(0.0, 0.0), 14.0), (1, 1)); assert_eq!(grid_size(iced::Size::new(800.0, 600.0), 14.0), (34, 95)); } fn character(text: &str) -> keyboard::Key { keyboard::Key::Character(text.into()) } fn named(named: keyboard::key::Named) -> keyboard::Key { keyboard::Key::Named(named) } #[test] fn swedish_layout_text_is_passed_through_unchanged() { use keyboard::Modifiers; // The key without modifiers differs from the produced text, which is // exactly what happens on a Swedish layout. let cases = [ ("2", "@", Modifiers::CTRL | Modifiers::ALT), ("7", "/", Modifiers::SHIFT), ("¨", "~", Modifiers::SHIFT), ("7", "{", Modifiers::CTRL | Modifiers::ALT), ("0", "}", Modifiers::CTRL | Modifiers::ALT), ("8", "[", Modifiers::CTRL | Modifiers::ALT), ("9", "]", Modifiers::CTRL | Modifiers::ALT), ("1", "!", Modifiers::SHIFT), ("3", "#", Modifiers::SHIFT), ("e", "€", Modifiers::CTRL | Modifiers::ALT), ("a", "A", Modifiers::SHIFT), ("\\", "|", Modifiers::CTRL | Modifiers::ALT), ("a", "ä", Modifiers::default()), ]; for (key, text, modifiers) in cases { assert_eq!( key_bytes(&character(key), Some(text), modifiers, false), Some(text.as_bytes().to_vec()), "failed for {text}" ); } } #[test] fn dead_keys_are_sent_only_after_composition() { assert_eq!( key_bytes(&character("¨"), None, keyboard::Modifiers::default(), false), None ); assert_eq!( key_bytes( &character("a"), Some("ä"), keyboard::Modifiers::default(), false ), Some("ä".as_bytes().to_vec()) ); } #[test] fn control_and_alt_modifiers_are_distinguished() { use keyboard::Modifiers; assert_eq!( key_bytes(&character("c"), Some("\u{3}"), Modifiers::CTRL, false), Some(vec![0x03]) ); assert_eq!( key_bytes(&character("c"), Some("c"), Modifiers::CTRL, false), Some(vec![0x03]) ); assert_eq!( key_bytes(&character("d"), Some("\u{4}"), Modifiers::CTRL, false), Some(vec![0x04]) ); assert_eq!( key_bytes(&character("c"), Some("c"), Modifiers::ALT, false), Some(b"\x1bc".to_vec()) ); assert_eq!( key_bytes( &character("2"), Some("@"), Modifiers::CTRL | Modifiers::ALT, false ), Some(b"@".to_vec()) ); } #[test] fn special_keys_keep_their_terminal_sequences() { use keyboard::Modifiers; use keyboard::key::Named; assert_eq!( key_bytes( &named(Named::Enter), Some("\r"), Modifiers::default(), false ), Some(b"\r".to_vec()) ); assert_eq!( key_bytes(&named(Named::Enter), Some("\r"), Modifiers::ALT, false), Some(b"\x1b\r".to_vec()) ); assert_eq!( key_bytes( &named(Named::Backspace), Some("\u{7f}"), Modifiers::default(), false ), Some(vec![0x7f]) ); assert_eq!( key_bytes(&named(Named::Tab), Some("\t"), Modifiers::SHIFT, false), Some(b"\x1b[Z".to_vec()) ); assert_eq!( key_bytes(&named(Named::ArrowUp), None, Modifiers::default(), false), Some(b"\x1b[A".to_vec()) ); assert_eq!( key_bytes(&named(Named::ArrowUp), None, Modifiers::default(), true), Some(b"\x1bOA".to_vec()) ); assert_eq!( key_bytes(&named(Named::ArrowUp), None, Modifiers::SHIFT, false), Some(b"\x1b[1;2A".to_vec()) ); assert_eq!( key_bytes(&named(Named::ArrowUp), None, Modifiers::ALT, false), Some(b"\x1b[1;3A".to_vec()) ); assert_eq!( key_bytes(&named(Named::F1), None, Modifiers::default(), false), Some(b"\x1bOP".to_vec()) ); assert_eq!( key_bytes(&named(Named::F5), None, Modifiers::SHIFT, false), Some(b"\x1b[15;2~".to_vec()) ); } #[test] fn resize_updates_the_emulated_screen_and_the_pty() { let mut session = session(); session.resize(40, 100).unwrap(); let (rows, cols) = session.screen().size(); assert_eq!((rows.get(), cols.get()), (40, 100)); session.write(b"stty size\n").unwrap(); let deadline = Instant::now() + Duration::from_secs(5); let mut resized = false; while Instant::now() < deadline { session.poll(); if session.screen().contents().contains("40 100") { resized = true; break; } std::thread::sleep(Duration::from_millis(20)); } assert!(resized, "the shell did not observe the new window size"); } #[test] fn emulator_uses_the_configured_scrollback() { let emulator = Emulator::new(24, 80, 12_345); assert_eq!(emulator.screen().scrollback_capacity(), 12_345); } #[test] fn shell_runs_in_the_start_directory() { let directory = std::env::temp_dir().join(format!("moorly-terminal-test-{}", std::process::id())); std::fs::create_dir_all(&directory).unwrap(); let mut session = { let pty = pty::Pty::spawn_for_test(&directory, 24, 80).unwrap(); Session { emulator: Emulator::new(24, 80, DEFAULT_SCROLLBACK_SIZE), pty, } }; session.write(b"pwd\n").unwrap(); let deadline = Instant::now() + Duration::from_secs(5); let expected = directory.to_string_lossy().into_owned(); let mut found = false; while Instant::now() < deadline { session.poll(); if session.screen().contents().contains(&expected) { found = true; break; } std::thread::sleep(Duration::from_millis(20)); } drop(session); let _ = std::fs::remove_dir_all(&directory); assert!(found, "shell did not start in {expected}"); } #[test] fn shell_reports_its_exit_status() { let mut session = session(); session.write(b"exit 7\n").unwrap(); let deadline = Instant::now() + Duration::from_secs(5); let mut info = None; while Instant::now() < deadline { if let Some(exit) = session.poll() { info = Some(exit); break; } std::thread::sleep(Duration::from_millis(20)); } assert_eq!(info.and_then(|exit| exit.code), Some(7)); } #[test] fn dropping_a_session_terminates_the_shell() { let session = session(); let pid = session.pid(); drop(session); let deadline = Instant::now() + Duration::from_secs(2); loop { let alive = unsafe { nix::libc::kill(pid, 0) } == 0; if !alive { break; } assert!( Instant::now() < deadline, "shell process {pid} is still alive" ); std::thread::sleep(Duration::from_millis(20)); } } }