diff --git a/Cargo.lock b/Cargo.lock index deddf0e..39317d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2022,6 +2022,12 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "jni" version = "0.22.4" @@ -2395,6 +2401,7 @@ version = "0.1.0" dependencies = [ "iced", "iced_aw", + "nix", "russh", "russh-sftp", "serde", @@ -2402,6 +2409,7 @@ dependencies = [ "toml", "ttf-parser", "uuid", + "vt100", ] [[package]] @@ -4514,6 +4522,27 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" 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]] name = "walkdir" version = "2.5.0" diff --git a/Cargo.toml b/Cargo.toml index 5b775f9..c49c45e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,3 +13,7 @@ tokio = { version = "1.54.1", features = ["full"] } toml = "0.8" ttf-parser = "0.25" 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"] } diff --git a/src/main.rs b/src/main.rs index fb4bf7d..311d0db 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,8 +9,8 @@ use iced::time::{Duration, Instant}; use iced::widget::text::{IntoFragment, Wrapping}; use iced::widget::{Id, operation}; use iced::widget::{ - button, checkbox, column, container, mouse_area, pick_list, responsive, row, rule, scrollable, - space, stack, text, text_input, toggler, tooltip, + button, canvas, checkbox, column, container, mouse_area, pick_list, responsive, row, rule, + scrollable, space, stack, text, text_input, toggler, tooltip, }; use iced::{ Alignment, Animation, Border, Color, Element, Font, Length, Padding, Point, Rectangle, Shadow, @@ -131,7 +131,7 @@ fn window_title(state: &Moorly, window: window::Id) -> String { .get(&window) .and_then(|state| state.active_tab) { - Some(tab) => format!("{} - Moorly", tab.title()), + Some(tab) => format!("{} - Moorly", tab_title(state, tab)), None => "Moorly".to_owned(), } } @@ -157,6 +157,23 @@ fn pointer_event( } } +/// Committed input-method text, used for dead keys and composed characters +/// that the operating system reports separately from key presses. +fn terminal_ime_event( + event: iced::Event, + status: iced::event::Status, + _window: window::Id, +) -> Option { + if status != iced::event::Status::Ignored { + return None; + } + + match event { + iced::Event::InputMethod(iced::advanced::input_method::Event::Commit(text)) => Some(text), + _ => None, + } +} + /// Key presses are captured by focused text inputs, so palette keys are /// listened for globally instead of through `keyboard::listen`. fn key_press_event( @@ -312,15 +329,52 @@ fn subscription(state: &Moorly) -> Subscription { }, ); + let terminal_target = terminal_input_target(state); + let terminal_keys = keyboard::listen() + .with(terminal_target) + .filter_map(|(target, event)| { + let keyboard::Event::KeyPressed { + key, + text, + modifiers, + repeat: false, + .. + } = event + else { + return None; + }; + + Some(Message::TerminalKey { + id: target?, + key, + text: text.map(|text| text.to_string()), + modifiers, + }) + }); + let terminal_text = iced::event::listen_with(terminal_ime_event) + .with(terminal_target) + .filter_map(|(target, text)| Some(Message::TerminalText { id: target?, text })); + let mut subscriptions = vec![ keyboard, palette_shortcut, + terminal_keys, + terminal_text, iced::time::every(Duration::from_secs(1)).map(|_| Message::ReloadThemes), window::events().map(|(window, event)| Message::WindowEvent(window, event)), iced::event::listen_with(pointer_event), iced::event::listen_with(palette_event), ]; + if state + .terminal_sessions + .values() + .any(|terminal| terminal.exit.is_none()) + { + subscriptions + .push(iced::time::every(Duration::from_millis(16)).map(|_| Message::TerminalTick)); + } + if state.drag.is_some() { subscriptions.push(iced::time::every(Duration::from_millis(16)).map(|_| Message::DragTick)); } @@ -632,6 +686,7 @@ enum SessionEnd { impl SessionEnd { const ALL: [Self; 4] = [Self::Auto, Self::Keep, Self::Reconnect, Self::Close]; + /// Label for SSH profiles and the stored/displayed default. fn label(self) -> &'static str { match self { Self::Auto => "Auto", @@ -640,6 +695,15 @@ impl SessionEnd { Self::Close => "Close", } } + + /// Local terminals restart their shell instead of reconnecting. + fn label_for(self, kind: ProfileKind) -> &'static str { + match (self, kind) { + (Self::Reconnect, ProfileKind::Ssh) => "Reconnect", + (Self::Reconnect, _) => "Restart", + _ => self.label(), + } + } } impl std::fmt::Display for SessionEnd { @@ -648,6 +712,23 @@ impl std::fmt::Display for SessionEnd { } } +/// A session-end option rendered with the label for a profile kind. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct SessionEndChoice { + value: SessionEnd, + kind: ProfileKind, +} + +impl std::fmt::Display for SessionEndChoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.value.label_for(self.kind)) + } +} + +fn session_end_choices(kind: ProfileKind) -> [SessionEndChoice; 4] { + SessionEnd::ALL.map(|value| SessionEndChoice { value, kind }) +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] enum AuthMethod { @@ -1289,7 +1370,7 @@ impl Command { Self::QuickTerminal => "Quick Terminal".to_owned(), Self::QuickSsh => "Quick SSH".to_owned(), Self::MoveToWindow(id) | Self::FocusWindow(id) => window_title(state, *id), - Self::FocusTab(_, tab) => tab.title(), + Self::FocusTab(_, tab) => tab_title(state, *tab), Self::SelectProfile { folder, profile } => state .profile_folders .get(*folder) @@ -1397,7 +1478,7 @@ impl Command { window_state .tabs .iter() - .filter(|tab| fuzzy_match(&tab.title(), query)) + .filter(|tab| fuzzy_match(&tab_title(state, **tab), query)) .map(|tab| Self::FocusTab(*id, *tab)), ); } @@ -1514,6 +1595,16 @@ struct TabDrag { detach: bool, } +/// A local terminal tab. The profile is kept so Reconnect/Restart can start a +/// fresh shell with the same settings after the old process ends. +struct TerminalSession { + session: terminal::Session, + profile: Profile, + start_dir: PathBuf, + title: String, + exit: Option, +} + struct Moorly { windows: HashMap, window_order: Vec, @@ -1582,6 +1673,8 @@ struct Moorly { profile_dialog: Option, dir_picker: Option, next_blank_tab: u32, + terminal_sessions: HashMap, + next_terminal_tab: u32, notifications: notifications::NotificationManager, } @@ -1590,6 +1683,7 @@ enum Tab { Start, Settings, Blank(u32), + Terminal(u32), } impl Tab { @@ -1598,10 +1692,45 @@ impl Tab { Self::Start => "Start".to_owned(), Self::Settings => "Settings".to_owned(), Self::Blank(number) => format!("temp {number}"), + Self::Terminal(_) => "Terminal".to_owned(), } } } +/// Tab title with access to the profile name of terminal tabs. +fn tab_title(state: &Moorly, tab: Tab) -> String { + match tab { + Tab::Terminal(id) => state + .terminal_sessions + .get(&id) + .map(|terminal| terminal.title.clone()) + .unwrap_or_else(|| tab.title()), + _ => tab.title(), + } +} + +/// The terminal that should receive keyboard input, if any. +fn terminal_input_target(state: &Moorly) -> Option { + if state.shortcut_capture.is_some() + || state.profile_dialog.is_some() + || state.dir_picker.is_some() + { + return None; + } + + let window = state.focused_window.or(state.main_window)?; + let window_state = state.windows.get(&window)?; + + if window_state.command_palette_open { + return None; + } + + match window_state.active_tab { + Some(Tab::Terminal(id)) if state.terminal_sessions.contains_key(&id) => Some(id), + _ => None, + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ColorOption { Accent, @@ -4482,6 +4611,8 @@ impl Default for Moorly { profile_dialog: None, dir_picker: None, next_blank_tab: 1, + terminal_sessions: HashMap::new(), + next_terminal_tab: 1, notifications, } } @@ -4501,6 +4632,24 @@ enum Message { CloseQuickAddMenu(window::Id), QuickTerminal(window::Id), QuickSsh(window::Id), + RunProfile { + window: window::Id, + folder: usize, + profile: usize, + new_window: bool, + }, + TerminalTick, + TerminalKey { + id: u32, + key: keyboard::Key, + text: Option, + modifiers: keyboard::Modifiers, + }, + TerminalText { + id: u32, + text: String, + }, + RestartTerminal(u32), ToggleTabsSubmenu(window::Id), AddTab(window::Id), CloseActiveTab(window::Id), @@ -4771,6 +4920,45 @@ fn update(state: &mut Moorly, message: Message) -> Task { state.quick_menu_open = false; } } + Message::RunProfile { + window, + folder, + profile, + new_window, + } => { + return run_profile(state, window, folder, profile, new_window); + } + Message::TerminalTick => { + return terminal_tick(state); + } + Message::TerminalKey { + id, + key, + text, + modifiers, + } => { + if let Some(terminal) = state.terminal_sessions.get_mut(&id) + && terminal.exit.is_none() + && let Some(bytes) = terminal::key_bytes( + &key, + text.as_deref(), + modifiers, + terminal.session.screen().application_cursor(), + ) + { + let _ = terminal.session.write(&bytes); + } + } + Message::TerminalText { id, text } => { + if let Some(terminal) = state.terminal_sessions.get_mut(&id) + && terminal.exit.is_none() + { + let _ = terminal.session.write(text.as_bytes()); + } + } + Message::RestartTerminal(id) => { + restart_terminal(state, id); + } Message::ToggleTabsSubmenu(window) => { if let Some(state) = state.windows.get_mut(&window) { state.tabs_submenu_open = !state.tabs_submenu_open; @@ -4813,6 +5001,19 @@ fn update(state: &mut Moorly, message: Message) -> Task { .get(&window) .and_then(|state| state.active_tab); + let removed: Vec = state + .windows + .get(&window) + .map(|window_state| { + window_state + .tabs + .iter() + .copied() + .filter(|tab| Some(*tab) != active) + .collect() + }) + .unwrap_or_default(); + if let Some(state) = state.windows.get_mut(&window) { match active { Some(active) => state.tabs.retain(|tab| *tab == active), @@ -4822,6 +5023,10 @@ fn update(state: &mut Moorly, message: Message) -> Task { state.tabs_submenu_open = false; } + for tab in removed { + remove_terminal_session(state, tab); + } + if active != Some(Tab::Settings) { state.settings_section = SettingsSection::default(); } @@ -5916,7 +6121,12 @@ fn update(state: &mut Moorly, message: Message) -> Task { Message::ScrollTabsBy(window, amount) => { return scroll_tabs_by(state, window, amount); } - Message::Quit => std::process::exit(0), + Message::Quit => { + // Drop PTY sessions explicitly so their child processes are + // terminated before process::exit bypasses the state destructor. + state.terminal_sessions.clear(); + std::process::exit(0); + } } Task::none() @@ -5999,9 +6209,19 @@ fn window_event(state: &mut Moorly, window: window::Id, event: window::Event) -> } fn remove_window(state: &mut Moorly, window: window::Id) { + let tabs = state + .windows + .get(&window) + .map(|window_state| window_state.tabs.clone()) + .unwrap_or_default(); + state.windows.remove(&window); state.window_order.retain(|id| *id != window); + for tab in tabs { + remove_terminal_session(state, tab); + } + if state.main_window == Some(window) { state.main_window = None; } @@ -6464,10 +6684,17 @@ fn close_tab(state: &mut Moorly, window: window::Id, tab: Tab) -> bool { if tab == Tab::Settings { state.settings_section = SettingsSection::default(); } + remove_terminal_session(state, tab); was_active } +fn remove_terminal_session(state: &mut Moorly, tab: Tab) { + if let Tab::Terminal(id) = tab { + state.terminal_sessions.remove(&id); + } +} + /// Estimated scroll delta that brings the active tab into view, or `None` /// when it already is (or the strip does not overflow). fn tab_reveal_delta(state: &Moorly, window: window::Id) -> Option { @@ -6640,13 +6867,13 @@ fn tab_shell( fn tab_view( window: window::Id, tab: Tab, + title: String, active: bool, hide_close: bool, close_opacity: f32, width: f32, colors: [Color; 9], ) -> Element<'static, Message> { - let title = tab.title(); let padding = Padding::new(10.0); let text_color = colors[ColorOption::Text.index()]; let active_bg = colors[ColorOption::MainBackground.index()]; @@ -6777,7 +7004,7 @@ fn drag_ghost( let outline = colors[ColorOption::ActiveTabOutline.index()]; let ghost = container( - text(fit_title(&drag.tab.title())) + text(fit_title(&tab_title(state, drag.tab))) .size(14) .color(text_color), ) @@ -8333,9 +8560,12 @@ fn profile_dialog_view<'a>( .spacing(2) .width(Length::Fill), pick_list( - SessionEnd::ALL, - Some(draft.session_end), - Message::SessionEndSelected, + session_end_choices(draft.kind), + Some(SessionEndChoice { + value: draft.session_end, + kind: draft.kind, + }), + |choice| Message::SessionEndSelected(choice.value), ) .width(110), ] @@ -8830,7 +9060,12 @@ fn profile_folder_row<'a>( }))) .on_exit(Message::HoverProfile(None)) } else { - profile_row + profile_row.on_double_click(Message::RunProfile { + window, + folder: index, + profile: profile_index, + new_window: false, + }) }; let profile_row = profile_row.on_right_press(Message::OpenProfileMenu { window, @@ -9120,13 +9355,26 @@ fn profile_context_menu( )); 2.0 } else { - // ponytail: profiles cannot start sessions yet; close on Run for now. items = items - .push(menu_item("Run", None, Message::CloseProfileMenu)) + .push(menu_item( + "Run", + None, + Message::RunProfile { + window, + folder: menu.folder, + profile: menu.profile, + new_window: false, + }, + )) .push(menu_item( "Run in a new window", None, - Message::CloseProfileMenu, + Message::RunProfile { + window, + folder: menu.folder, + profile: menu.profile, + new_window: true, + }, )) .push(menu_item( "Hide profile", @@ -9518,6 +9766,572 @@ fn tab_scroll_limits(state: &Moorly, window: window::Id) -> (bool, bool) { (offset > 0.5, offset < max_offset - 0.5) } +const TERMINAL_FOOTER_HEIGHT: f32 = 38.0; + +/// 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( + state: &mut Moorly, + window: window::Id, + folder: usize, + profile_index: usize, + new_window: bool, +) -> Task { + let Some(profile) = state + .profile_folders + .get(folder) + .and_then(|folder| folder.profiles.get(profile_index)) + .cloned() + else { + return Task::none(); + }; + + if profile.kind != ProfileKind::Terminal { + state.notifications.add( + notifications::Notification::new( + notifications::NotificationKind::Warning, + "Only local Terminal profiles can start a session right now.", + ) + .title("Session"), + ); + return Task::none(); + } + + let (start_dir, warning) = profile_start_directory(&profile); + if let Some(warning) = warning { + state.notifications.add( + notifications::Notification::new(notifications::NotificationKind::Warning, warning) + .title("Start directory"), + ); + } + + let size = state + .windows + .get(&window) + .map(|window_state| window_state.size) + .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) { + Ok(session) => session, + Err(error) => { + state.notifications.add( + notifications::Notification::new(notifications::NotificationKind::Error, error) + .title("Could not start terminal"), + ); + return Task::none(); + } + }; + + let id = state.next_terminal_tab; + state.next_terminal_tab += 1; + let title = if profile.name.trim().is_empty() { + "Terminal".to_owned() + } else { + profile.name.clone() + }; + + state.terminal_sessions.insert( + id, + TerminalSession { + session, + profile, + start_dir, + title, + exit: None, + }, + ); + + let tab = Tab::Terminal(id); + + if new_window { + let settings = window::Settings { + size, + exit_on_close_request: false, + ..window::Settings::default() + }; + let (id, open) = window::open(settings); + state + .windows + .insert(id, WindowState::with_tab(tab, size, None)); + state.window_order.push(id); + state.focused_window = Some(id); + + return open.map(|_| Message::Ignore); + } + + if let Some(window_state) = state.windows.get_mut(&window) { + window_state.tabs.push(tab); + window_state.active_tab = Some(tab); + window_state.quick_menu_open = false; + } + + scroll_tabs_to_end(state, window) +} + +fn terminal_area(size: Size, ended: bool) -> Size { + let footer = if ended { TERMINAL_FOOTER_HEIGHT } else { 0.0 }; + Size::new( + size.width.max(1.0), + (size.height - MENUBAR_HEIGHT - footer).max(1.0), + ) +} + +fn terminal_grid(state: &Moorly, size: Size, ended: bool) -> (u16, u16) { + terminal::grid_size(terminal_area(size, ended), state.typography.terminal.size) +} + +fn window_for_terminal(state: &Moorly, id: u32) -> Option { + state.windows.iter().find_map(|(window, window_state)| { + window_state + .tabs + .contains(&Tab::Terminal(id)) + .then_some(*window) + }) +} + +fn terminal_tick(state: &mut Moorly) -> Task { + let ids: Vec = state.terminal_sessions.keys().copied().collect(); + let font_size = state.typography.terminal.size; + let mut ended = Vec::new(); + + for id in ids { + let window = window_for_terminal(state, id); + let size = window + .and_then(|window| state.windows.get(&window)) + .map(|window_state| window_state.size); + + let Some(terminal) = state.terminal_sessions.get_mut(&id) else { + continue; + }; + + if terminal.exit.is_none() + && let Some(exit) = terminal.session.poll() + { + terminal.exit = Some(exit); + ended.push(id); + } + + if let Some(size) = size { + let (rows, cols) = + terminal::grid_size(terminal_area(size, terminal.exit.is_some()), font_size); + let (current_rows, current_cols) = terminal.session.screen().size(); + + if (rows, cols) != (current_rows.get(), current_cols.get()) { + let _ = terminal.session.resize(rows, cols); + } + } + } + + let mut tasks = Vec::new(); + for id in ended { + tasks.push(finish_terminal(state, id)); + } + + Task::batch(tasks) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SessionEndAction { + Keep, + Restart, + Close, +} + +/// Existing option semantics: Auto closes after a clean exit and keeps the tab +/// after a failure; Keep always keeps; Reconnect/Restart always starts again; +/// Close always closes. +fn session_end_action( + session_end: SessionEnd, + exit: Option, +) -> SessionEndAction { + match session_end { + SessionEnd::Auto => { + if exit.is_some_and(|exit| exit.code == Some(0)) { + SessionEndAction::Close + } else { + SessionEndAction::Keep + } + } + SessionEnd::Keep => SessionEndAction::Keep, + SessionEnd::Reconnect => SessionEndAction::Restart, + SessionEnd::Close => SessionEndAction::Close, + } +} + +fn finish_terminal(state: &mut Moorly, id: u32) -> Task { + let Some(terminal) = state.terminal_sessions.get(&id) else { + return Task::none(); + }; + let action = session_end_action(terminal.profile.session_end, terminal.exit); + let window = window_for_terminal(state, id); + + match action { + SessionEndAction::Keep => Task::none(), + SessionEndAction::Restart => { + restart_terminal(state, id); + Task::none() + } + SessionEndAction::Close => { + let Some(window) = window else { + return Task::none(); + }; + let was_active = close_tab(state, window, Tab::Terminal(id)); + + Task::batch([ + if was_active { + reveal_active_tab(state, window) + } else { + Task::none() + }, + close_window_if_empty(state, window), + ]) + } + } +} + +fn restart_terminal(state: &mut Moorly, id: u32) { + let Some((profile, size)) = state.terminal_sessions.get(&id).map(|terminal| { + ( + terminal.profile.clone(), + window_for_terminal(state, id) + .and_then(|window| state.windows.get(&window)) + .map(|window_state| window_state.size) + .unwrap_or(Size::new(900.0, 600.0)), + ) + }) else { + return; + }; + + let (start_dir, warning) = profile_start_directory(&profile); + if let Some(warning) = warning { + state.notifications.add( + notifications::Notification::new(notifications::NotificationKind::Warning, warning) + .title("Start directory"), + ); + } + + let (rows, cols) = terminal_grid(state, size, false); + + match terminal::Session::spawn(&start_dir, rows, cols) { + Ok(session) => { + if let Some(terminal) = state.terminal_sessions.get_mut(&id) { + terminal.session = session; + terminal.start_dir = start_dir; + terminal.exit = None; + } + } + Err(error) => { + state.notifications.add( + notifications::Notification::new(notifications::NotificationKind::Error, error) + .title("Could not restart terminal"), + ); + } + } +} + +/// Resolves the configured start directory, falling back to home with a +/// user-facing warning when it cannot be used. +fn profile_start_directory(profile: &Profile) -> (PathBuf, Option) { + let path = resolve_start_path(&profile.start_path); + + if path.is_dir() && std::fs::read_dir(&path).is_ok() { + return (path, None); + } + + let home = home_dir(); + let fallback = if home.is_dir() { + home + } else { + PathBuf::from(if cfg!(windows) { "C:\\" } else { "/" }) + }; + + let message = if profile.start_path.trim().is_empty() || profile.start_path.trim() == "~" { + format!( + "The home directory is not accessible. Using {}.", + fallback.display() + ) + } else { + format!( + "Start directory {} is not accessible. Using {}.", + path.display(), + fallback.display() + ) + }; + + (fallback, Some(message)) +} + +struct TerminalCanvas<'a> { + screen: &'a vt100::Screen, + theme: terminal::Theme, + font: Font, + font_size: f32, +} + +#[derive(Clone, Copy, PartialEq)] +struct CellStyle { + foreground: Color, + background: Color, + bold: bool, + italic: bool, + underline: bool, +} + +impl canvas::Program for TerminalCanvas<'_> { + type State = (); + + fn draw( + &self, + _state: &Self::State, + renderer: &iced::Renderer, + _theme: &iced::Theme, + bounds: Rectangle, + _cursor: mouse::Cursor, + ) -> Vec { + let cell = terminal::cell_size(self.font_size); + let (rows, cols) = self.screen.size(); + let mut frame = canvas::Frame::new(renderer, bounds.size()); + frame.fill_rectangle(Point::ORIGIN, bounds.size(), self.theme.background); + + for row in 0..rows.get() { + let mut run: Option<(u16, u16, String, CellStyle)> = None; + + for col in 0..cols.get() { + let Some(cell_ref) = self.screen.cell(row, col) else { + continue; + }; + + if cell_ref.is_wide_continuation() { + if let Some((_, end, _, _)) = run.as_mut() { + *end = col + 1; + } + continue; + } + + let style = cell_style(cell_ref, self.theme); + + if let Some((start, end, text, current)) = run.as_mut() { + if *current == style { + text.push_str(cell_ref.contents()); + *end = col + 1; + continue; + } + + draw_run( + &mut frame, + *start, + *end, + text, + *current, + row, + cell, + self.font.clone(), + self.font_size, + self.theme.background, + ); + } + + run = Some((col, col + 1, cell_ref.contents().to_owned(), style)); + } + + if let Some((start, end, text, style)) = run { + draw_run( + &mut frame, + start, + end, + &text, + style, + row, + cell, + self.font.clone(), + self.font_size, + self.theme.background, + ); + } + } + + if !self.screen.hide_cursor() { + let (row, col) = self.screen.cursor_position(); + let position = Point::new(col as f32 * cell.width, row as f32 * cell.height); + frame.fill_rectangle(position, cell, self.theme.cursor); + + if let Some(cell_ref) = self.screen.cell(row, col) + && !cell_ref.is_wide_continuation() + && !cell_ref.contents().is_empty() + { + frame.fill_text(canvas::Text { + content: cell_ref.contents().to_owned(), + position, + color: self.theme.background, + size: self.font_size.into(), + line_height: iced::widget::text::LineHeight::Relative(1.0), + font: self.font.clone(), + ..canvas::Text::default() + }); + } + } + + vec![frame.into_geometry()] + } +} + +fn cell_style(cell: &vt100::Cell, theme: terminal::Theme) -> CellStyle { + let (foreground, background) = if cell.inverse() { + (cell.bgcolor(), cell.fgcolor()) + } else { + (cell.fgcolor(), cell.bgcolor()) + }; + + let mut foreground = theme.color(foreground, theme.foreground); + let background = theme.color(background, theme.background); + + if cell.bold() + && let vt100::Color::Idx(index) = cell.fgcolor() + && index < 8 + { + foreground = theme.ansi[(index + 8) as usize]; + } + + if cell.dim() { + foreground = foreground.scale_alpha(0.65); + } + + CellStyle { + foreground, + background, + bold: cell.bold(), + italic: cell.italic(), + underline: cell.underline(), + } +} + +#[allow(clippy::too_many_arguments)] +fn draw_run( + frame: &mut canvas::Frame, + start: u16, + end: u16, + text: &str, + style: CellStyle, + row: u16, + cell: Size, + font: Font, + font_size: f32, + default_background: Color, +) { + let x = start as f32 * cell.width; + let y = row as f32 * cell.height; + let width = (end.saturating_sub(start)) as f32 * cell.width; + + if style.background != default_background { + frame.fill_rectangle( + Point::new(x, y), + Size::new(width, cell.height), + style.background, + ); + } + + if !text.is_empty() { + let mut font = font; + if style.bold { + font.weight = font::Weight::Bold; + } + if style.italic { + font.style = font::Style::Italic; + } + + frame.fill_text(canvas::Text { + content: text.to_owned(), + position: Point::new(x, y), + color: style.foreground, + size: font_size.into(), + line_height: iced::widget::text::LineHeight::Relative(1.0), + font, + ..canvas::Text::default() + }); + } + + if style.underline { + frame.fill_rectangle( + Point::new(x, y + cell.height - 1.0), + Size::new(width, 1.0), + style.foreground, + ); + } +} + +fn terminal_page<'a>(state: &'a Moorly, window: window::Id, id: u32) -> Element<'a, Message> { + let Some(terminal_session) = state.terminal_sessions.get(&id) else { + return container(text("This terminal session has ended.").size(13)) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Alignment::Center) + .align_y(Alignment::Center) + .into(); + }; + + let theme = terminal::Theme::DARK; + let view = canvas::Canvas::new(TerminalCanvas { + screen: terminal_session.session.screen(), + theme, + font: typography_font(&state.typography.terminal), + font_size: state.typography.terminal.size, + }) + .width(Length::Fill) + .height(Length::Fill); + + let mut content = column![ + container(view) + .width(Length::Fill) + .height(Length::Fill) + .style(move |_| container::Style { + background: Some(theme.background.into()), + text_color: Some(theme.foreground), + ..container::Style::default() + }) + ]; + + if let Some(exit) = terminal_session.exit { + let status = match (exit.code, exit.signal) { + (Some(0), _) => "Session ended.".to_owned(), + (Some(code), _) => format!("Session ended with exit code {code}."), + (None, Some(signal)) => format!("Session terminated by signal {signal}."), + (None, None) => "Session ended.".to_owned(), + }; + let restart = SessionEnd::Reconnect.label_for(terminal_session.profile.kind); + + let footer = container( + row![ + text(status).size(12).color(theme.foreground), + space::horizontal(), + button(restart) + .on_press(Message::RestartTerminal(id)) + .padding([4, 10]) + .style(theme::outlined_option), + button("Close") + .on_press(Message::CloseTab(window, Tab::Terminal(id))) + .padding([4, 10]) + .style(theme::outlined_option), + ] + .spacing(8) + .align_y(Alignment::Center), + ) + .width(Length::Fill) + .height(TERMINAL_FOOTER_HEIGHT) + .padding([0, 10]) + .align_y(Alignment::Center) + .style(move |_| container::Style { + background: Some(theme.background.scale_alpha(0.97).into()), + text_color: Some(theme.foreground), + ..container::Style::default() + }); + + content = content.push(footer); + } + + content.into() +} + fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { let Some(window_state) = state.windows.get(&window) else { return container(space::horizontal()) @@ -9557,6 +10371,10 @@ fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { (*tab, opacity) }) .collect(); + let titles: HashMap = tabs + .iter() + .map(|tab| (*tab, tab_title(state, *tab))) + .collect(); let tab_strip = responsive(move |size| { let width = tab_width(size.width, tabs.len()); @@ -9566,6 +10384,7 @@ fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { tab_row = tab_row.push(tab_view( window, tab, + titles.get(&tab).cloned().unwrap_or_else(|| tab.title()), active_tab == Some(tab), hide_close, close_opacities.get(&tab).copied().unwrap_or(0.0), @@ -9636,6 +10455,7 @@ fn main_view(state: &Moorly, window: window::Id) -> Element<'_, Message> { let main_area: Element<'_, Message> = match active_tab { Some(Tab::Start) => start_page(state, window), Some(Tab::Settings) => settings_page(state, window), + Some(Tab::Terminal(id)) => terminal_page(state, window, id), _ => container(column![]) .width(Length::Fill) .height(Length::Fill) @@ -10055,6 +10875,8 @@ mod tests { profile_dialog: None, dir_picker: None, next_blank_tab: 1, + terminal_sessions: Default::default(), + next_terminal_tab: 1, notifications: super::notifications::NotificationManager::default(), } } @@ -10870,6 +11692,17 @@ mod tests { assert_eq!(super::Shortcut::parse("Hyper+K"), None); } + #[test] + fn committed_input_method_text_is_forwarded() { + let event = + iced::Event::InputMethod(iced::advanced::input_method::Event::Commit("ä".to_owned())); + + assert_eq!( + super::terminal_ime_event(event, iced::event::Status::Ignored, test_window()), + Some("ä".to_owned()) + ); + } + #[test] fn space_shortcuts_match_the_space_key() { let shortcut = super::Shortcut::parse("Ctrl+Shift+Space").unwrap(); @@ -11725,6 +12558,281 @@ mod tests { assert_eq!(state.profile_folders[0].profiles[0].start_path, "/tmp"); } + #[test] + fn session_end_labels_depend_on_the_profile_kind() { + use super::{ProfileKind, SessionEnd}; + + assert_eq!( + SessionEnd::Reconnect.label_for(ProfileKind::Ssh), + "Reconnect" + ); + assert_eq!( + SessionEnd::Reconnect.label_for(ProfileKind::Terminal), + "Restart" + ); + assert_eq!(SessionEnd::Reconnect.to_string(), "Reconnect"); + + let ssh: Vec = super::session_end_choices(ProfileKind::Ssh) + .iter() + .map(ToString::to_string) + .collect(); + let terminal: Vec = super::session_end_choices(ProfileKind::Terminal) + .iter() + .map(ToString::to_string) + .collect(); + + assert_eq!(ssh, ["Auto", "Keep", "Reconnect", "Close"]); + assert_eq!(terminal, ["Auto", "Keep", "Restart", "Close"]); + } + + #[test] + fn all_session_end_options_choose_the_expected_action() { + use super::terminal::ExitInfo; + use super::{SessionEnd, SessionEndAction}; + + let clean = Some(ExitInfo { + code: Some(0), + signal: None, + }); + let failed = Some(ExitInfo { + code: Some(1), + signal: None, + }); + + assert_eq!( + super::session_end_action(SessionEnd::Auto, clean), + SessionEndAction::Close + ); + assert_eq!( + super::session_end_action(SessionEnd::Auto, failed), + SessionEndAction::Keep + ); + assert_eq!( + super::session_end_action(SessionEnd::Keep, clean), + SessionEndAction::Keep + ); + assert_eq!( + super::session_end_action(SessionEnd::Reconnect, failed), + SessionEndAction::Restart + ); + assert_eq!( + super::session_end_action(SessionEnd::Close, clean), + SessionEndAction::Close + ); + } + + #[test] + fn terminal_start_directory_defaults_to_home_and_falls_back() { + let mut profile = profile("Term"); + profile.kind = super::ProfileKind::Terminal; + profile.start_path = String::new(); + + let (directory, warning) = super::profile_start_directory(&profile); + assert_eq!(directory, super::home_dir()); + assert!(warning.is_none()); + + profile.start_path = "/definitely/not/a/moorly/directory".to_owned(); + let (directory, warning) = super::profile_start_directory(&profile); + assert_eq!(directory, super::home_dir()); + assert!(warning.is_some()); + + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let root = std::env::temp_dir().join(format!("moorly-start-test-{stamp}")); + std::fs::create_dir_all(&root).unwrap(); + profile.start_path = root.to_string_lossy().into_owned(); + + let (directory, warning) = super::profile_start_directory(&profile); + assert_eq!(directory, root); + assert!(warning.is_none()); + + std::fs::remove_dir_all(&directory).unwrap(); + } + + fn terminal_for_session_end(session_end: super::SessionEnd) -> (Moorly, iced::window::Id, u32) { + let mut state = state(); + let window = test_window(); + let id = 77; + let mut profile = profile("Shell"); + profile.kind = super::ProfileKind::Terminal; + profile.session_end = session_end; + profile.start_path = "/".to_owned(); + + state.terminal_sessions.insert( + id, + super::TerminalSession { + session: super::terminal::Session::spawn(std::path::Path::new("/"), 24, 80) + .unwrap(), + profile, + start_dir: std::path::PathBuf::from("/"), + title: "Shell".to_owned(), + exit: None, + }, + ); + state + .windows + .get_mut(&window) + .unwrap() + .tabs + .push(Tab::Terminal(id)); + state.windows.get_mut(&window).unwrap().active_tab = Some(Tab::Terminal(id)); + + (state, window, id) + } + + #[test] + fn session_end_options_close_keep_or_restart_the_terminal_tab() { + use super::terminal::ExitInfo; + + // Auto: a clean exit closes the tab. + let (mut state, window, id) = terminal_for_session_end(super::SessionEnd::Auto); + state.terminal_sessions.get_mut(&id).unwrap().exit = Some(ExitInfo { + code: Some(0), + signal: None, + }); + let _ = super::finish_terminal(&mut state, id); + assert!( + state + .windows + .get(&window) + .is_none_or(|window| !window.tabs.contains(&Tab::Terminal(id))) + ); + assert!(!state.terminal_sessions.contains_key(&id)); + + // Auto: a failure keeps the tab so the user can read the output. + let (mut state, window, id) = terminal_for_session_end(super::SessionEnd::Auto); + state.terminal_sessions.get_mut(&id).unwrap().exit = Some(ExitInfo { + code: Some(1), + signal: None, + }); + let _ = super::finish_terminal(&mut state, id); + assert!(state.windows[&window].tabs.contains(&Tab::Terminal(id))); + assert!(state.terminal_sessions[&id].exit.is_some()); + + // Keep always leaves the tab open. + let (mut state, window, id) = terminal_for_session_end(super::SessionEnd::Keep); + state.terminal_sessions.get_mut(&id).unwrap().exit = Some(ExitInfo { + code: Some(0), + signal: None, + }); + let _ = super::finish_terminal(&mut state, id); + assert!(state.windows[&window].tabs.contains(&Tab::Terminal(id))); + + // Close always closes the tab. + let (mut state, window, id) = terminal_for_session_end(super::SessionEnd::Close); + state.terminal_sessions.get_mut(&id).unwrap().exit = Some(ExitInfo { + code: Some(0), + signal: None, + }); + let _ = super::finish_terminal(&mut state, id); + assert!( + state + .windows + .get(&window) + .is_none_or(|window| !window.tabs.contains(&Tab::Terminal(id))) + ); + assert!(!state.terminal_sessions.contains_key(&id)); + + // Reconnect/Restart starts a fresh shell in the same tab. + let (mut state, window, id) = terminal_for_session_end(super::SessionEnd::Reconnect); + state.terminal_sessions.get_mut(&id).unwrap().exit = Some(ExitInfo { + code: Some(0), + signal: None, + }); + let _ = super::finish_terminal(&mut state, id); + assert!(state.windows[&window].tabs.contains(&Tab::Terminal(id))); + assert!(state.terminal_sessions[&id].exit.is_none()); + assert_eq!(state.windows[&window].active_tab, Some(Tab::Terminal(id))); + + state.terminal_sessions.clear(); + } + + #[test] + fn running_a_terminal_profile_opens_and_closes_a_session() { + let mut state = state(); + let window = test_window(); + let mut profile = profile("Shell"); + profile.kind = super::ProfileKind::Terminal; + profile.start_path = std::env::temp_dir().to_string_lossy().into_owned(); + state.profile_folders[0].profiles.push(profile); + + let _ = update( + &mut state, + Message::RunProfile { + window, + folder: 0, + profile: 0, + new_window: false, + }, + ); + + let tab = *state.windows[&window].tabs.last().unwrap(); + let id = match tab { + Tab::Terminal(id) => id, + other => panic!("expected a terminal tab, got {other:?}"), + }; + let terminal = state.terminal_sessions.get(&id).unwrap(); + assert_eq!( + terminal.start_dir, + std::path::PathBuf::from(std::env::temp_dir()) + ); + assert_eq!(terminal.profile.kind, super::ProfileKind::Terminal); + assert_eq!(state.windows[&window].active_tab, Some(tab)); + + let _ = update(&mut state, Message::CloseTab(window, tab)); + assert!(!state.terminal_sessions.contains_key(&id)); + } + + #[test] + fn moving_a_terminal_tab_keeps_its_session_identity() { + let mut state = state(); + let source = test_window(); + let destination = iced::window::Id::unique(); + let id = 42; + + state.terminal_sessions.insert( + id, + super::TerminalSession { + session: super::terminal::Session::spawn(std::path::Path::new("/"), 24, 80) + .unwrap(), + profile: profile("Shell"), + start_dir: std::path::PathBuf::from("/"), + title: "Shell".to_owned(), + exit: None, + }, + ); + state + .windows + .get_mut(&source) + .unwrap() + .tabs + .push(Tab::Terminal(id)); + state.windows.get_mut(&source).unwrap().active_tab = Some(Tab::Terminal(id)); + state.windows.insert( + destination, + super::WindowState::new(false, iced::Size::new(800.0, 600.0)), + ); + state.window_order.push(destination); + + super::move_tab_to_window(&mut state, source, destination, Tab::Terminal(id)); + + assert!(state.terminal_sessions.contains_key(&id)); + assert!(!state.windows[&source].tabs.contains(&Tab::Terminal(id))); + assert!( + state.windows[&destination] + .tabs + .contains(&Tab::Terminal(id)) + ); + assert_eq!( + state.windows[&destination].active_tab, + Some(Tab::Terminal(id)) + ); + + state.terminal_sessions.clear(); + } + #[test] fn directory_picker_lists_subdirectories() { let stamp = std::time::SystemTime::now() diff --git a/src/terminal.rs b/src/terminal.rs index 21cf664..2af989d 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -1,8 +1,13 @@ -//! Terminal appearance is deliberately independent from the application theme. -//! It is stored and configured separately so terminal colors do not change -//! when the GUI switches between light and dark. +//! 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 { @@ -44,4 +49,870 @@ impl Theme { 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, + pub signal: Option, +} + +/// 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 { + 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 { + 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> { + 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; + + 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 { + 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 { + 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(not(unix))] +mod pty { + use std::path::Path; + + use super::ExitInfo; + + 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 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), + 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)); + } + } } diff --git a/vendor/iced_aw/Cargo.toml b/vendor/iced_aw/Cargo.toml index e168edb..fc4c47f 100644 --- a/vendor/iced_aw/Cargo.toml +++ b/vendor/iced_aw/Cargo.toml @@ -92,8 +92,9 @@ wrap = [] [lib] 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 = [ - "cdylib", "rlib", ] path = "src/lib.rs"