Added working terminal interface for linux
This commit is contained in:
1 parent
6f5a115cff
commit
0c9946d2b4
5 files changed
+2032
-19
No files matched your search
Generated
+29
@@ -2022,6 +2022,12 @@ dependencies = [
|
|||||||
"hybrid-array",
|
"hybrid-array",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itoa"
|
||||||
|
version = "1.0.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jni"
|
name = "jni"
|
||||||
version = "0.22.4"
|
version = "0.22.4"
|
||||||
@@ -2395,6 +2401,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"iced",
|
"iced",
|
||||||
"iced_aw",
|
"iced_aw",
|
||||||
|
"nix",
|
||||||
"russh",
|
"russh",
|
||||||
"russh-sftp",
|
"russh-sftp",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -2402,6 +2409,7 @@ dependencies = [
|
|||||||
"toml",
|
"toml",
|
||||||
"ttf-parser",
|
"ttf-parser",
|
||||||
"uuid",
|
"uuid",
|
||||||
|
"vt100",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4514,6 +4522,27 @@ version = "0.9.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "vt100"
|
||||||
|
version = "0.18.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eb05cdd19ae8707bf6a0a269972c07e6358103a7079faec749dec318a5b3dc23"
|
||||||
|
dependencies = [
|
||||||
|
"itoa",
|
||||||
|
"unicode-width",
|
||||||
|
"vte",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "vte"
|
||||||
|
version = "0.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd"
|
||||||
|
dependencies = [
|
||||||
|
"arrayvec",
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "walkdir"
|
name = "walkdir"
|
||||||
version = "2.5.0"
|
version = "2.5.0"
|
||||||
|
|||||||
@@ -13,3 +13,7 @@ tokio = { version = "1.54.1", features = ["full"] }
|
|||||||
toml = "0.8"
|
toml = "0.8"
|
||||||
ttf-parser = "0.25"
|
ttf-parser = "0.25"
|
||||||
uuid = { version = "1.29.0", features = ["v4"] }
|
uuid = { version = "1.29.0", features = ["v4"] }
|
||||||
|
vt100 = "0.18.1"
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
nix = { version = "0.31.3", features = ["term", "process", "signal", "fs"] }
|
||||||
+1123
-15
File diff suppressed because it is too large.
Load diff
+874
-3
@@ -1,8 +1,13 @@
|
|||||||
//! Terminal appearance is deliberately independent from the application theme.
|
//! Terminal emulation and local PTY transport.
|
||||||
//! It is stored and configured separately so terminal colors do not change
|
//!
|
||||||
//! when the GUI switches between light and dark.
|
//! 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::Color;
|
||||||
|
use iced::keyboard;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub struct Theme {
|
pub struct Theme {
|
||||||
@@ -44,4 +49,870 @@ impl Theme {
|
|||||||
Color::from_rgb8(0xff, 0xff, 0xff),
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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) -> 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, 2000),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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<i32>,
|
||||||
|
pub signal: Option<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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, String> {
|
||||||
|
let pty = pty::Pty::spawn(start_dir, rows, cols)?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
emulator: Emulator::new(rows, cols),
|
||||||
|
pty,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads pending output and returns an exit notification when the process
|
||||||
|
/// has ended.
|
||||||
|
pub fn poll(&mut self) -> Option<ExitInfo> {
|
||||||
|
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(test)]
|
||||||
|
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<Vec<u8>> {
|
||||||
|
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<Vec<u8>> {
|
||||||
|
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<Vec<u8>> {
|
||||||
|
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<u8> {
|
||||||
|
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<Vec<u8>> {
|
||||||
|
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<Vec<u8>> {
|
||||||
|
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<Vec<u8>> {
|
||||||
|
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<u8> {
|
||||||
|
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;
|
||||||
|
|
||||||
|
pub enum Event {
|
||||||
|
Output(Vec<u8>),
|
||||||
|
Exited(ExitInfo),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Pty {
|
||||||
|
master: File,
|
||||||
|
child: Pid,
|
||||||
|
reaped: Arc<AtomicBool>,
|
||||||
|
events: Receiver<Event>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Pty {
|
||||||
|
pub fn spawn(start_dir: &Path, rows: u16, cols: u16) -> Result<Self, String> {
|
||||||
|
let shell = std::env::var_os("SHELL")
|
||||||
|
.filter(|shell| !shell.is_empty())
|
||||||
|
.unwrap_or_else(|| OsStr::new("/bin/sh").to_owned());
|
||||||
|
|
||||||
|
Self::spawn_shell(start_dir, rows, cols, &shell)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_shell(
|
||||||
|
start_dir: &Path,
|
||||||
|
rows: u16,
|
||||||
|
cols: u16,
|
||||||
|
shell: &OsStr,
|
||||||
|
) -> Result<Self, String> {
|
||||||
|
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<CString> = 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<Event> {
|
||||||
|
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, String> {
|
||||||
|
Self::spawn_shell(start_dir, rows, cols, OsStr::new("/bin/sh"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
mod pty {
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use super::ExitInfo;
|
||||||
|
|
||||||
|
pub enum Event {
|
||||||
|
Output(Vec<u8>),
|
||||||
|
Exited(ExitInfo),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Pty;
|
||||||
|
|
||||||
|
impl Pty {
|
||||||
|
pub fn spawn(_start_dir: &Path, _rows: u16, _cols: u16) -> Result<Self, String> {
|
||||||
|
Err("Local terminal sessions are not supported on this platform yet.".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Event> {
|
||||||
|
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),
|
||||||
|
pty,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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 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),
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Vendored
+2
-1
@@ -92,8 +92,9 @@ wrap = []
|
|||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
name = "iced_aw"
|
name = "iced_aw"
|
||||||
|
# rlib only. The upstream cdylib type makes Cargo link iced_aw.dll on Windows
|
||||||
|
# GNU, where MinGW ld fails with "export ordinal too large".
|
||||||
crate-type = [
|
crate-type = [
|
||||||
"cdylib",
|
|
||||||
"rlib",
|
"rlib",
|
||||||
]
|
]
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|||||||
Reference in new issue
Block a user