diff --git a/Cargo.lock b/Cargo.lock index 39317d6..038e1a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2410,6 +2410,7 @@ dependencies = [ "ttf-parser", "uuid", "vt100", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index c49c45e..4151098 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,3 +17,12 @@ vt100 = "0.18.1" [target.'cfg(unix)'.dependencies] nix = { version = "0.31.3", features = ["term", "process", "signal", "fs"] } + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61.2", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Console", + "Win32_System_Pipes", + "Win32_System_Threading", +] } diff --git a/src/main.rs b/src/main.rs index 311d0db..b293ebd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -995,6 +995,10 @@ fn home_dir() -> PathBuf { home.push(path); Some(home) }) + // HOMEPATH on its own is relative ("\\Users\\name"), so it is + // only used together with HOMEDRIVE. The config folder's + // variable is a safe absolute fallback. + .or_else(|| std::env::var_os("APPDATA").map(PathBuf::from)) .unwrap_or_else(|| PathBuf::from("C:\\")) } else { std::env::var_os("HOME") @@ -1005,17 +1009,33 @@ fn home_dir() -> PathBuf { fn default_start_path() -> String { if cfg!(windows) { - std::env::var("HOMEPATH").unwrap_or_else(|_| home_dir().to_string_lossy().into_owned()) + app_data_dir().to_string_lossy().into_owned() } else { "~/".to_owned() } } +/// Windows profile files live under `%APPDATA%`; an unconfigured start +/// directory uses the same variable and falls back to the user's home. +fn app_data_dir() -> PathBuf { + std::env::var_os("APPDATA") + .map(PathBuf::from) + .unwrap_or_else(home_dir) +} + /// Resolves a typed path, expanding `~` to the home directory. fn resolve_start_path(input: &str) -> PathBuf { let input = input.trim(); - if input.is_empty() || input == "~" { + if input.is_empty() { + return if cfg!(windows) { + app_data_dir() + } else { + home_dir() + }; + } + + if input == "~" { return home_dir(); } @@ -9768,6 +9788,16 @@ fn tab_scroll_limits(state: &Moorly, window: window::Id) -> (bool, bool) { const TERMINAL_FOOTER_HEIGHT: f32 = 38.0; +/// Local profile kinds that can start a shell on this platform. PowerShell is +/// a Windows shell; SSH keeps its existing path. +fn local_shell(kind: ProfileKind) -> Option { + match kind { + ProfileKind::Terminal => Some(terminal::Shell::Default), + ProfileKind::PowerShell if cfg!(windows) => Some(terminal::Shell::PowerShell), + _ => None, + } +} + /// Starts a local terminal from a profile, either in the current window or in /// a fresh one. SSH profiles keep their existing (not yet implemented) path. fn run_profile( @@ -9786,7 +9816,7 @@ fn run_profile( return Task::none(); }; - if profile.kind != ProfileKind::Terminal { + let Some(shell) = local_shell(profile.kind) else { state.notifications.add( notifications::Notification::new( notifications::NotificationKind::Warning, @@ -9795,7 +9825,7 @@ fn run_profile( .title("Session"), ); return Task::none(); - } + }; let (start_dir, warning) = profile_start_directory(&profile); if let Some(warning) = warning { @@ -9812,7 +9842,7 @@ fn run_profile( .unwrap_or(Size::new(900.0, 600.0)); let (rows, cols) = terminal_grid(state, size, false); - let session = match terminal::Session::spawn(&start_dir, rows, cols) { + let session = match terminal::Session::spawn_with(&start_dir, rows, cols, shell) { Ok(session) => session, Err(error) => { state.notifications.add( @@ -9905,8 +9935,10 @@ fn terminal_tick(state: &mut Moorly) -> Task { continue; }; - if terminal.exit.is_none() - && let Some(exit) = terminal.session.poll() + // Keep draining output after the process exits so the final ConPTY + // frame is rendered before the tab footer appears. + if let Some(exit) = terminal.session.poll() + && terminal.exit.is_none() { terminal.exit = Some(exit); ended.push(id); @@ -10012,8 +10044,11 @@ fn restart_terminal(state: &mut Moorly, id: u32) { } let (rows, cols) = terminal_grid(state, size, false); + let Some(shell) = local_shell(profile.kind) else { + return; + }; - match terminal::Session::spawn(&start_dir, rows, cols) { + match terminal::Session::spawn_with(&start_dir, rows, cols, shell) { Ok(session) => { if let Some(terminal) = state.terminal_sessions.get_mut(&id) { terminal.session = session; @@ -12558,6 +12593,39 @@ mod tests { assert_eq!(state.profile_folders[0].profiles[0].start_path, "/tmp"); } + #[test] + fn profile_kind_selects_a_local_shell() { + use super::terminal::Shell; + use super::{ProfileKind, local_shell}; + + assert_eq!(local_shell(ProfileKind::Terminal), Some(Shell::Default)); + assert_eq!(local_shell(ProfileKind::Ssh), None); + + if cfg!(windows) { + assert_eq!( + local_shell(ProfileKind::PowerShell), + Some(Shell::PowerShell) + ); + } else { + assert_eq!(local_shell(ProfileKind::PowerShell), None); + } + } + + #[test] + fn default_start_path_is_never_relative() { + let path = super::default_start_path(); + assert!(!path.trim().is_empty()); + + if cfg!(windows) { + assert!( + std::path::Path::new(&path).is_absolute(), + "default start path {path} is not absolute" + ); + } else { + assert_eq!(path, "~/"); + } + } + #[test] fn session_end_labels_depend_on_the_profile_kind() { use super::{ProfileKind, SessionEnd}; @@ -12627,8 +12695,13 @@ mod tests { profile.kind = super::ProfileKind::Terminal; profile.start_path = String::new(); + let expected = if cfg!(windows) { + super::app_data_dir() + } else { + super::home_dir() + }; let (directory, warning) = super::profile_start_directory(&profile); - assert_eq!(directory, super::home_dir()); + assert_eq!(directory, expected); assert!(warning.is_none()); profile.start_path = "/definitely/not/a/moorly/directory".to_owned(); diff --git a/src/terminal.rs b/src/terminal.rs index 2af989d..63baf37 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -128,6 +128,14 @@ pub struct ExitInfo { 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, +} + /// A running terminal session: an emulator fed by a local PTY. pub struct Session { emulator: Emulator, @@ -136,7 +144,16 @@ pub struct Session { impl Session { pub fn spawn(start_dir: &Path, rows: u16, cols: u16) -> Result { - let pty = pty::Pty::spawn(start_dir, rows, cols)?; + Self::spawn_with(start_dir, rows, cols, Shell::Default) + } + + pub fn spawn_with( + start_dir: &Path, + rows: u16, + cols: u16, + shell: Shell, + ) -> Result { + let pty = pty::Pty::spawn_with(start_dir, rows, cols, shell)?; Ok(Self { emulator: Emulator::new(rows, cols), @@ -172,7 +189,7 @@ impl Session { self.emulator.screen() } - #[cfg(test)] + #[cfg(all(test, unix))] fn pid(&self) -> i32 { self.pty.pid() } @@ -422,7 +439,7 @@ mod pty { use nix::sys::wait::{WaitStatus, waitpid}; use nix::unistd::Pid; - use super::ExitInfo; + use super::{ExitInfo, Shell}; pub enum Event { Output(Vec), @@ -445,6 +462,15 @@ mod pty { Self::spawn_shell(start_dir, rows, cols, &shell) } + pub fn spawn_with( + start_dir: &Path, + rows: u16, + cols: u16, + _shell: Shell, + ) -> Result { + Self::spawn(start_dir, rows, cols) + } + fn spawn_shell( start_dir: &Path, rows: u16, @@ -626,11 +652,375 @@ mod pty { } } -#[cfg(not(unix))] +#[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 = match shell { + Shell::PowerShell => OsString::from("powershell.exe"), + Shell::Default => std::env::var_os("COMSPEC") + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| OsString::from("cmd.exe")), + }; + + 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; + use super::{ExitInfo, Shell}; pub enum Event { Output(Vec), @@ -644,6 +1034,15 @@ mod pty { 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()) }