Added terminal support for windows 10/11
Moorly CI / windows-build (push) Successful in 3m34s
Moorly CI / linux-build (push) Successful in 3m46s

This commit is contained in:
Squid committed 2026-11-08 16:55:03 +01:00
1 parent 6915fc2857
commit 317b773a18
4 files changed
+496 -14

No files matched your search

+404 -5
View File
@@ -128,6 +128,14 @@ pub struct ExitInfo {
pub signal: Option<i32>,
}
/// 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<Self, String> {
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<Self, String> {
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<u8>),
@@ -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, String> {
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<u8>),
Exited(ExitInfo),
}
pub struct Pty {
input: File,
process: HANDLE,
console: HPCON,
events: Receiver<Event>,
}
impl Pty {
pub fn spawn(start_dir: &Path, rows: u16, cols: u16) -> Result<Self, String> {
Self::spawn_with(start_dir, rows, cols, Shell::Default)
}
pub fn spawn_with(
start_dir: &Path,
rows: u16,
cols: u16,
shell: Shell,
) -> Result<Self, String> {
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<Self, String> {
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::<STARTUPINFOEXW>() 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::<HPCON>(),
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<u16> = 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<Event> {
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<Event>) {
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<u16> {
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<u8>),
@@ -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, String> {
Self::spawn(_start_dir, _rows, _cols)
}
pub fn write(&mut self, _bytes: &[u8]) -> Result<(), String> {
Err("The terminal is not running.".to_owned())
}