From ec97ef00b03604fa481983477147675426506c30 Mon Sep 17 00:00:00 2001 From: James Magahern Date: Tue, 17 Nov 2026 02:04:41 -0800 Subject: [PATCH] Add server-owned stacked panes with vertical navigation --- README.md | 40 ++- THIRD_PARTY_NOTICES.md | 4 +- src/bindings.rs | 21 ++ src/commands.rs | 49 ++- src/launcher.rs | 72 ++++- src/main.rs | 8 + src/protocol.rs | 58 +++- src/server.rs | 690 ++++++++++++++++++++++++++++++++++++++--- src/terminal.rs | 235 ++++++++++---- src/transition.rs | 88 ++++++ 10 files changed, 1129 insertions(+), 136 deletions(-) diff --git a/README.md b/README.md index 251366e..b255c03 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,8 @@ its zygote for new GUI windows, preserving existing windows and shells. Changes to server logic or the protocol still require restarting the server; `--shutdown` also ends its shell sessions. -This build uses protocol version 2. An older server must be restarted before -attaching; the new `psyterm --shutdown` command can stop a version-1 server. +This build uses protocol version 3. An older server must be restarted before +attaching; the new `psyterm --shutdown` command can stop version-1 and version-2 servers. Finish any running work first, since shutdown ends its sessions, then launch `psyterm` again to start the updated server. @@ -112,6 +112,9 @@ run `psyterm --shutdown` on the remote host, for example through SSH. | Alt+Left / Right | Focus the adjacent pane, then adjacent tab at the edge | | Alt+Shift+[ / ] | Switch to the previous / next tab | | Alt+Shift+N or Alt+Shift+Right | Create a tab | +| Alt+Shift+Up / Down | Insert a stacked pane above / below the current pane | +| Alt+Up / Down | Expand the previous / next stacked pane | +| Click a collapsed pane title | Expand and focus that pane | | Ctrl+Shift+Left / Right | Focus the previous / next pane | | Ctrl+Shift+W | Close the focused pane and its shell | | Ctrl+Shift+R | Edit the pane name | @@ -131,11 +134,12 @@ Zellij's modal Ctrl bindings are left to terminal programs. The command palette searches command names and keywords as you type. Arrow keys or Tab select a result; Enter runs it or opens a submenu. Escape returns to the parent menu, then closes the palette. “Switch to tab…” and “Focus pane…” offer -live workspace lists. Commands without shortcuts, such as restoring automatic -pane names, are available here too. Palette input never reaches the shell. +live workspace lists, including collapsed panes. Commands without shortcuts, +such as restoring automatic pane names, are available here too. Palette input +never reaches the shell. -Typing returns to the live screen. Ctrl+C, Ctrl+D, Alt combinations, arrows, -navigation keys, and function keys reach the terminal application. +Typing returns to the live screen. Ctrl+C, Ctrl+D and unbound Alt combinations, +arrows, navigation keys, and function keys reach the terminal application. Alternate-screen applications receive shifted navigation; the wheel sends arrow keys when the application enables alternate scrolling. @@ -146,6 +150,17 @@ with `~`; pane headers and equal-width tabs truncate long names in the middle. It checks shell directories every 500 ms, including while the shell is idle. Manual names survive program title changes and client disconnects; returning to automatic naming uses the latest program title or directory. +Tabs form the horizontal dimension; each column within a tab has an ordered +vertical stack. One pane per stack is expanded, with the other titles above and +below it. Creating or switching stacked panes uses the same curve as tab changes, +with vertical motion. Vertical navigation stops at the first/last pane. Side-by-side +splits create independent columns, each with its own stack. Long collapsed-title +lists scroll, leaving room for the expanded terminal. + +Stack order, expanded panes, titles, and all shells live on the server and survive +GUI detach/reattach. Collapsed shells keep running; their grids are sent only when +expanded, and their output does not redraw unchanged visible grids. + When a shell exits, its pane closes automatically. An empty tab closes too, and focus moves to an adjacent remaining pane or tab when needed. After the last shell exits, the window stays open with `+` available to start another tab. @@ -243,16 +258,21 @@ lifecycle, and server reattachment/layout behavior. Pane tests cover natural shell exit, empty-tab removal, focus preservation, idle directory changes, program/manual name precedence, title resets, and rename persistence. Editor tests cover Unicode selection and composition; protocol tests pin the previous -version's shutdown handshake. +versions’ shutdown handshakes. Stack tests cover insertion, navigation, hidden +output, reattachment, and exit cleanup. Live Hyprland checks verified GUI→zygote→server ancestry, a single-threaded zygote, no server GPU descriptors, two simultaneous GUIs, tabs/splits, and shell survival after detaching. An actual SSH connection to a separate headless server on localhost verified input and reattachment. Replacing a running executable refreshed its zygote while the original GUI and shell stayed alive. -These are Linux checks; remote-network latency and macOS remain unverified. +New live checks cover palette search/submenus and input isolation, Zellij +navigation bindings, stack insertion in both directions, collapsed-pane focus, +exit cleanup, and stack reattachment. A second client's focus changes preserve +palette input. These are Linux checks; remote-network latency and macOS remain +unverified. Linux Wayland is the implemented platform; macOS is a future target. Current -limits include side-by-side panes only, shared per-server viewport state, no -disk-restored sessions, no configuration files, no application mouse reporting, +limits include no arbitrary split trees or floating panes, shared per-server +viewport state, no disk-restored sessions, no configuration files, no application mouse reporting, no Kitty keyboard protocol, no OSC 52 clipboard access, and no clickable links. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e072571..7cfab55 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -33,5 +33,5 @@ ease-out curve, then returns to full opacity for 500 ms. It does not fade in. `src/transition.rs` adapts Neovide's `ease_out_expo` window-position curve from `src/renderer/animation_utils.rs`, used by `rendered_window.rs` with `position_animation_length = 0.15` in `renderer/mod.rs`. This is the same -Neovide revision and MIT license recorded above. Horizontal tab and pane -transitions use this curve; text scrolling has a separate spring in Neovide. +Neovide revision and MIT license recorded above. Horizontal tab/pane and vertical +stack transitions use this curve; text scrolling has a separate spring in Neovide. diff --git a/src/bindings.rs b/src/bindings.rs index c8c6ef1..75fdf33 100644 --- a/src/bindings.rs +++ b/src/bindings.rs @@ -29,6 +29,8 @@ pub fn action_for_key(key: &Keystroke) -> Option { "[" | "{" => CommandAction::PreviousTab, "]" | "}" => CommandAction::NextTab, "n" | "right" => CommandAction::NewTab, + "up" => CommandAction::StackAbove, + "down" => CommandAction::StackBelow, _ => return None, }) } else { @@ -38,6 +40,8 @@ pub fn action_for_key(key: &Keystroke) -> Option { "}" => CommandAction::NextTab, "left" => CommandAction::FocusLeft, "right" => CommandAction::FocusRight, + "up" => CommandAction::FocusAbove, + "down" => CommandAction::FocusBelow, "\\" => CommandAction::SplitPane, _ => return None, }) @@ -80,6 +84,23 @@ mod tests { assert!(matches!(action("cmd-shift-t"), Some(CommandAction::NewTab))); } + #[test] + fn stacked_panes_use_the_requested_vertical_bindings() { + assert!(matches!( + action("alt-shift-up"), + Some(CommandAction::StackAbove) + )); + assert!(matches!( + action("alt-shift-down"), + Some(CommandAction::StackBelow) + )); + assert!(matches!(action("alt-up"), Some(CommandAction::FocusAbove))); + assert!(matches!( + action("alt-down"), + Some(CommandAction::FocusBelow) + )); + } + #[test] fn shell_keys_and_unconfigured_modes_remain_available() { for key in [ diff --git a/src/commands.rs b/src/commands.rs index fb18053..63a1ba8 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -8,6 +8,10 @@ use crate::protocol::{ScrollKind, Snapshot}; pub enum CommandAction { NewTab, SplitPane, + StackAbove, + StackBelow, + FocusAbove, + FocusBelow, ClosePane, RenamePane, ResetPaneName, @@ -231,6 +235,40 @@ pub fn root_items(snapshot: Option<&Snapshot>) -> Vec { Detach, ), ]; + items.extend([ + PaletteItem::action( + "stack-above", + "New stacked pane above", + "create shell vertical up", + Some("Alt+Shift+Up"), + StackAbove, + ) + .available(pane), + PaletteItem::action( + "stack-below", + "New stacked pane below", + "create shell vertical down", + Some("Alt+Shift+Down"), + StackBelow, + ) + .available(pane), + PaletteItem::action( + "focus-above", + "Focus stacked pane above", + "switch vertical up previous", + Some("Alt+Up"), + FocusAbove, + ) + .available(pane), + PaletteItem::action( + "focus-below", + "Focus stacked pane below", + "switch vertical down next", + Some("Alt+Down"), + FocusBelow, + ) + .available(pane), + ]); let tab_items = snapshot .into_iter() .flat_map(|snapshot| snapshot.tabs.iter()) @@ -247,13 +285,20 @@ pub fn root_items(snapshot: Option<&Snapshot>) -> Vec { .collect(); let pane_items = snapshot .into_iter() - .flat_map(|snapshot| snapshot.panes.iter()) + .flat_map(|snapshot| { + snapshot + .tabs + .iter() + .filter(|tab| tab.id == snapshot.active_tab) + }) + .flat_map(|tab| tab.stacks.iter()) + .flat_map(|stack| stack.panes.iter()) .enumerate() .map(|(index, pane)| { PaletteItem::action( format!("pane-{}", pane.id), format!("{} {}", index + 1, pane.title), - "switch focus pane", + "switch focus pane stack", None, FocusPane(pane.id), ) diff --git a/src/launcher.rs b/src/launcher.rs index ec83391..078431c 100644 --- a/src/launcher.rs +++ b/src/launcher.rs @@ -86,17 +86,21 @@ pub fn control(socket: &Path, command: ClientMessage) -> Result { let stream = UnixStream::connect(socket) .with_context(|| format!("connect to psyTerm server at {}", socket.display()))?; let legacy_shutdown = matches!(command, ClientMessage::Shutdown); - let result = control_stream(stream, command, REQUEST_TIMEOUT); - if legacy_shutdown - && protocol::VERSION > 1 - && result - .as_ref() - .is_err_and(|error| error.to_string().contains("protocol")) - { - // Version 1 shares the Hello/Shutdown/Closing wire prefix. Permit only - // an explicit shutdown through that prefix, never old grid decoding. - let stream = UnixStream::connect(socket)?; - return control_stream_version(stream, ClientMessage::Shutdown, REQUEST_TIMEOUT, 1); + let mut result = control_stream(stream, command, REQUEST_TIMEOUT); + if legacy_shutdown { + // Older versions share the Hello/Shutdown/Closing wire prefix. Permit + // only explicit shutdown through it, never decoding older grid layouts. + for version in (1..protocol::VERSION).rev() { + if !result + .as_ref() + .is_err_and(|error| error.to_string().contains("protocol")) + { + break; + } + let stream = UnixStream::connect(socket)?; + result = + control_stream_version(stream, ClientMessage::Shutdown, REQUEST_TIMEOUT, version); + } } result } @@ -672,6 +676,52 @@ mod tests { path } + #[test] + fn explicit_shutdown_negotiates_previous_protocol_prefixes() { + for old_version in 1..protocol::VERSION { + let root = test_dir(); + let socket = root.join("server.sock"); + let listener = UnixListener::bind(&socket).unwrap(); + let peer = thread::spawn(move || { + for expected_attempt in (old_version..=protocol::VERSION).rev() { + let (mut stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(REQUEST_TIMEOUT)).unwrap(); + let hello = protocol::read_message::(&mut stream).unwrap(); + assert!( + matches!(hello, ClientMessage::Hello { version } if version == expected_attempt) + ); + if expected_attempt != old_version { + protocol::write_message( + &mut stream, + &ServerMessage::Error("protocol mismatch".into()), + ) + .unwrap(); + continue; + } + protocol::write_message( + &mut stream, + &ServerMessage::Hello { + version: old_version, + server_pid: std::process::id(), + }, + ) + .unwrap(); + assert!(matches!( + protocol::read_message::(&mut stream).unwrap(), + ClientMessage::Shutdown + )); + protocol::write_message(&mut stream, &ServerMessage::Closing).unwrap(); + } + }); + assert!(matches!( + control(&socket, ClientMessage::Shutdown).unwrap(), + ServerMessage::Closing + )); + peer.join().unwrap(); + fs::remove_dir_all(root).unwrap(); + } + } + #[test] fn private_paths_reject_symlinks_and_shared_directories() { let root = test_dir(); diff --git a/src/main.rs b/src/main.rs index 711204d..9335a29 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,6 +107,14 @@ fn list_sessions(socket: &std::path::Path) -> Result<()> { protocol::ServerMessage::Snapshot(snapshot) => { for tab in snapshot.tabs { println!("tab {} {} panes {:?}", tab.id, tab.title, tab.panes); + for (index, stack) in tab.stacks.iter().enumerate() { + println!( + " stack {} expanded {} panes {:?}", + index + 1, + stack.active_pane, + stack.panes.iter().map(|pane| pane.id).collect::>() + ); + } } break; } diff --git a/src/protocol.rs b/src/protocol.rs index 3b3efb8..af4e5ff 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -10,7 +10,7 @@ use anyhow::{Context, Result, bail}; use bincode::Options; use serde::{Deserialize, Serialize, de::DeserializeOwned}; -pub const VERSION: u32 = 2; +pub const VERSION: u32 = 3; pub const MAX_MESSAGE_BYTES: usize = 16 * 1024 * 1024; pub type PaneId = u64; pub type TabId = u64; @@ -73,6 +73,43 @@ pub enum ClientMessage { pane: PaneId, name: Option, }, + /// Insert above/below a pane, or current server focus when omitted. + NewStackPane { + pane: Option, + direction: VerticalDirection, + cwd: Option, + }, + /// Expand the adjacent pane in this column, stopping at either end. + FocusStackPane { + pane: PaneId, + direction: VerticalDirection, + }, + /// Navigate from authoritative server focus. Horizontal edges switch tabs. + FocusDirection { + direction: Direction, + }, + /// Cycle relative to current server focus, preserving repeated key presses. + CycleTab { + forward: bool, + }, + /// Cycle expanded columns in the current tab, with wraparound. + CyclePane { + forward: bool, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum VerticalDirection { + Up, + Down, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Direction { + Left, + Right, + Up, + Down, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] @@ -129,16 +166,31 @@ pub struct Snapshot { pub revision: u64, pub tabs: Vec, pub active_tab: TabId, - /// Only panes in the active tab are transferred. Every pane remains live on the server. + /// Only expanded panes in the active tab are transferred. Every pane remains live on the server. pub panes: Vec, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TabInfo { pub id: TabId, pub title: String, + /// All pane IDs, flattened in column/stack order. pub panes: Vec, pub active_pane: PaneId, + /// Side-by-side columns; each expands one of its vertically ordered panes. + pub stacks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StackInfo { + pub panes: Vec, + pub active_pane: PaneId, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StackPaneInfo { + pub id: PaneId, + pub title: String, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/src/server.rs b/src/server.rs index 0edc989..e1b535f 100644 --- a/src/server.rs +++ b/src/server.rs @@ -86,6 +86,24 @@ fn clean_title(title: String) -> Option { let title = title.trim(); (!title.is_empty()).then(|| title.to_owned()) } +fn single_pane_stack(pane: PaneId) -> StackInfo { + StackInfo { + panes: vec![StackPaneInfo { + id: pane, + title: "Shell".into(), + }], + active_pane: pane, + } +} + +fn flatten_panes(tab: &mut TabInfo) { + tab.panes = tab + .stacks + .iter() + .flat_map(|stack| stack.panes.iter().map(|pane| pane.id)) + .collect(); +} + struct Client { authenticated: bool, attached: bool, @@ -563,44 +581,63 @@ impl Server { self.dirty = true; } ClientMessage::Split { pane, cwd } => { - let tab = self - .tabs - .iter() - .position(|tab| tab.panes.contains(&pane)) - .context("unknown pane")?; - let occupied: usize = self.tabs[tab] - .panes - .iter() - .filter_map(|id| self.panes.get(id)) - .map(|pane| { - let size = pane.session.size(); - size.num_cols as usize * size.num_lines as usize - }) - .sum(); - ensure!( - occupied + 80 * 24 <= MAX_GRID_CELLS, - "tab grid exceeds {MAX_GRID_CELLS} cells" - ); + let (tab_index, stack_index, _) = self.pane_position(pane)?; + self.ensure_new_pane_fits(tab_index)?; let pane = self.new_pane(cwd)?; - self.tabs[tab].panes.push(pane); - self.tabs[tab].active_pane = pane; - self.active_tab = self.tabs[tab].id; + let tab = &mut self.tabs[tab_index]; + tab.stacks.insert(stack_index + 1, single_pane_stack(pane)); + flatten_panes(tab); + tab.active_pane = pane; + self.active_tab = tab.id; self.dirty = true; } + ClientMessage::NewStackPane { + pane, + direction, + cwd, + } => { + let pane = pane + .or_else(|| { + self.tabs + .iter() + .find(|tab| tab.id == self.active_tab) + .map(|tab| tab.active_pane) + }) + .context("no active pane")?; + let (tab_index, stack_index, pane_index) = self.pane_position(pane)?; + self.ensure_new_pane_fits(tab_index)?; + let pane = self.new_pane(cwd)?; + let tab = &mut self.tabs[tab_index]; + let stack = &mut tab.stacks[stack_index]; + let insert_at = pane_index + usize::from(direction == VerticalDirection::Down); + stack.panes.insert( + insert_at, + StackPaneInfo { + id: pane, + title: "Shell".into(), + }, + ); + stack.active_pane = pane; + tab.active_pane = pane; + flatten_panes(tab); + self.active_tab = tab.id; + self.dirty = true; + } + ClientMessage::FocusStackPane { pane, direction } => { + self.focus_stack_pane(pane, direction)?; + } + ClientMessage::FocusDirection { direction } => { + self.focus_direction(direction)?; + } + ClientMessage::CycleTab { forward } => self.cycle_tab(forward), + ClientMessage::CyclePane { forward } => self.cycle_pane(forward)?, ClientMessage::FocusTab { tab } => { ensure!(self.tabs.iter().any(|entry| entry.id == tab), "unknown tab"); self.active_tab = tab; self.dirty = true; } ClientMessage::FocusPane { pane } => { - let tab = self - .tabs - .iter_mut() - .find(|tab| tab.panes.contains(&pane)) - .context("unknown pane")?; - tab.active_pane = pane; - self.active_tab = tab.id; - self.dirty = true; + self.focus_pane(pane)?; } ClientMessage::ClosePane { pane } => { ensure!(self.remove_pane(pane), "unknown pane"); @@ -615,23 +652,147 @@ impl Server { Ok(()) } + fn pane_position(&self, pane: PaneId) -> Result<(usize, usize, usize)> { + for (tab_index, tab) in self.tabs.iter().enumerate() { + for (stack_index, stack) in tab.stacks.iter().enumerate() { + if let Some(pane_index) = stack.panes.iter().position(|entry| entry.id == pane) { + return Ok((tab_index, stack_index, pane_index)); + } + } + } + anyhow::bail!("unknown pane") + } + + fn ensure_new_pane_fits(&self, tab_index: usize) -> Result<()> { + let occupied: usize = self.tabs[tab_index] + .panes + .iter() + .filter_map(|id| self.panes.get(id)) + .map(|pane| { + let size = pane.session.size(); + size.num_cols as usize * size.num_lines as usize + }) + .sum(); + ensure!( + occupied + 80 * 24 <= MAX_GRID_CELLS, + "tab grid exceeds {MAX_GRID_CELLS} cells" + ); + Ok(()) + } + + fn focus_pane(&mut self, pane: PaneId) -> Result<()> { + let (tab_index, stack_index, _) = self.pane_position(pane)?; + let tab = &mut self.tabs[tab_index]; + tab.stacks[stack_index].active_pane = pane; + tab.active_pane = pane; + self.active_tab = tab.id; + self.dirty = true; + Ok(()) + } + + fn focus_stack_pane(&mut self, pane: PaneId, direction: VerticalDirection) -> Result<()> { + let (tab_index, stack_index, pane_index) = self.pane_position(pane)?; + let stack = &self.tabs[tab_index].stacks[stack_index]; + let next = match direction { + VerticalDirection::Up => pane_index.checked_sub(1), + VerticalDirection::Down => { + (pane_index + 1 < stack.panes.len()).then_some(pane_index + 1) + } + }; + if let Some(index) = next { + self.focus_pane(stack.panes[index].id)?; + } + Ok(()) + } + + fn cycle_tab(&mut self, forward: bool) { + let Some(index) = self.tabs.iter().position(|tab| tab.id == self.active_tab) else { + return; + }; + let count = self.tabs.len(); + let next = if forward { + (index + 1) % count + } else { + (index + count - 1) % count + }; + self.active_tab = self.tabs[next].id; + self.dirty = true; + } + + fn cycle_pane(&mut self, forward: bool) -> Result<()> { + let Some(tab) = self.tabs.iter().find(|tab| tab.id == self.active_tab) else { + return Ok(()); + }; + let index = tab + .stacks + .iter() + .position(|stack| stack.active_pane == tab.active_pane) + .context("focused pane is not expanded")?; + let count = tab.stacks.len(); + let next = if forward { + (index + 1) % count + } else { + (index + count - 1) % count + }; + self.focus_pane(tab.stacks[next].active_pane) + } + + fn focus_direction(&mut self, direction: Direction) -> Result<()> { + let Some(tab_index) = self.tabs.iter().position(|tab| tab.id == self.active_tab) else { + return Ok(()); + }; + let pane = self.tabs[tab_index].active_pane; + match direction { + Direction::Up => self.focus_stack_pane(pane, VerticalDirection::Up), + Direction::Down => self.focus_stack_pane(pane, VerticalDirection::Down), + Direction::Left | Direction::Right => { + let (_, stack_index, _) = self.pane_position(pane)?; + let tab = &self.tabs[tab_index]; + let next = if direction == Direction::Left { + stack_index.checked_sub(1) + } else { + (stack_index + 1 < tab.stacks.len()).then_some(stack_index + 1) + }; + if let Some(index) = next { + self.focus_pane(tab.stacks[index].active_pane)?; + } else { + self.cycle_tab(direction == Direction::Right); + } + Ok(()) + } + } + } + /// The same lifecycle path serves explicit close and a shell's natural exit. fn remove_pane(&mut self, pane: PaneId) -> bool { let Some(removed) = self.panes.remove(&pane) else { return false; }; - if let Some(tab_index) = self.tabs.iter().position(|tab| tab.panes.contains(&pane)) { + if let Ok((tab_index, stack_index, pane_index)) = self.pane_position(pane) { let tab = &mut self.tabs[tab_index]; - let pane_index = tab.panes.iter().position(|id| *id == pane).unwrap(); - tab.panes.remove(pane_index); - if tab.active_pane == pane { - tab.active_pane = tab + let stack = &mut tab.stacks[stack_index]; + stack.panes.remove(pane_index); + if stack.active_pane == pane { + stack.active_pane = stack .panes - .get(pane_index.min(tab.panes.len().saturating_sub(1))) - .copied() - .unwrap_or(0); + .get(pane_index.min(stack.panes.len().saturating_sub(1))) + .map_or(0, |entry| entry.id); } - if tab.panes.is_empty() { + let replacement = stack.active_pane; + if stack.panes.is_empty() { + tab.stacks.remove(stack_index); + } + if tab.active_pane == pane { + tab.active_pane = if replacement != 0 { + replacement + } else { + tab.stacks + .get(stack_index.min(tab.stacks.len().saturating_sub(1))) + .map_or(0, |stack| stack.active_pane) + }; + } + flatten_panes(tab); + if tab.stacks.is_empty() { let removed_tab = self.tabs.remove(tab_index); if self.active_tab == removed_tab.id { self.active_tab = self @@ -722,6 +883,7 @@ impl Server { title: "Shell".into(), panes: vec![pane], active_pane: pane, + stacks: vec![single_pane_stack(pane)], }); self.active_tab = id; Ok(()) @@ -736,7 +898,17 @@ impl Server { return; }; match event { - Event::Wakeup => pane.session.acknowledge_wakeup(), + Event::Wakeup => { + // Hidden PTYs still parse output and must rearm their wakeups, + // but their grids are absent from the current client snapshot. + pane.session.acknowledge_wakeup(); + self.dirty |= self + .tabs + .iter() + .find(|tab| tab.id == self.active_tab) + .is_some_and(|tab| tab.stacks.iter().any(|stack| stack.active_pane == id)); + return; + } Event::Title(title) => pane.program_title = clean_title(title), Event::ResetTitle => pane.program_title = None, Event::PtyWrite(text) => pane.session.write(text.into_bytes()), @@ -770,12 +942,24 @@ impl Server { if let Some(pane) = self.panes.get(&tab.active_pane) { tab.title = pane.title(); } + for stack in &mut tab.stacks { + for entry in &mut stack.panes { + if let Some(pane) = self.panes.get(&entry.id) { + entry.title = pane.title(); + } + } + } } let visible = self .tabs .iter() .find(|tab| tab.id == self.active_tab) - .map(|tab| tab.panes.clone()) + .map(|tab| { + tab.stacks + .iter() + .map(|stack| stack.active_pane) + .collect::>() + }) .unwrap_or_default(); let panes = visible .into_iter() @@ -1166,6 +1350,432 @@ mod tests { ); } + fn active_tab(snapshot: &Snapshot) -> &TabInfo { + snapshot + .tabs + .iter() + .find(|tab| tab.id == snapshot.active_tab) + .unwrap() + } + + fn list_after_commands(client: &mut UnixStream) -> Snapshot { + // A round trip separates older queued snapshots from this inspection. + send(client, ClientMessage::Ping); + loop { + match protocol::read_message::(client).unwrap() { + ServerMessage::Pong => break, + ServerMessage::Error(error) => panic!("server error: {error}"), + _ => {} + } + } + send(client, ClientMessage::List); + snapshot(client, |_| true) + } + + #[test] + fn collapsed_output_rearms_wakeups_without_publishing_unchanged_grids() { + let (sender, receiver) = mpsc::sync_channel(1024); + let mut actor = Server { + shell: Some(Shell::new("/bin/sh".into(), Vec::new())), + panes: HashMap::new(), + tabs: Vec::new(), + active_tab: 0, + next_id: 1, + clients: HashMap::new(), + sender, + revision: 0, + dirty: false, + last_frame: Instant::now(), + last_cwd_refresh: Instant::now(), + }; + actor.new_tab(None).unwrap(); + let hidden = actor.tabs[0].active_pane; + let visible = actor.new_pane(None).unwrap(); + let tab = &mut actor.tabs[0]; + tab.stacks[0].panes.push(StackPaneInfo { + id: visible, + title: "Visible".into(), + }); + tab.stacks[0].active_pane = visible; + tab.active_pane = visible; + flatten_panes(tab); + + // Drive actual PTY/parser events directly so absence of a publish is + // tested through its dirty flag, without timing-dependent socket gaps. + let output = |actor: &mut Server, suffix: &str, expect_dirty: bool| { + actor.panes[&hidden] + .session + .write(format!("printf 'HIDDEN_%s\\n' '{suffix}'\n").into_bytes()); + let needle = format!("HIDDEN_{suffix}"); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let event = receiver + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .unwrap(); + if let Action::Terminal(id, event) = event { + let target_wakeup = id == hidden && matches!(event, Event::Wakeup); + actor.dirty = false; + actor.terminal_event(id, event); + if target_wakeup { + assert_eq!(actor.dirty, expect_dirty); + let term = actor.panes[&hidden].session.term.lock(); + let text = term + .renderable_content() + .display_iter + .map(|cell| cell.cell.c) + .collect::(); + if text.contains(&needle) { + break; + } + } + } + } + }; + output(&mut actor, "FIRST", false); + // A second burst verifies the first suppressed wakeup was acknowledged. + output(&mut actor, "SECOND", false); + let hidden_snapshot = actor.snapshot(); + assert_eq!(hidden_snapshot.panes.len(), 1); + assert_eq!(hidden_snapshot.panes[0].id, visible); + actor.focus_pane(hidden).unwrap(); + assert!(actor.dirty); + assert!(contains(&actor.snapshot(), "HIDDEN_SECOND")); + output(&mut actor, "VISIBLE", true); + } + + #[test] + fn stacks_insert_in_both_directions_and_only_expand_one_grid() { + let server = TestServer::start(); + let mut client = server.client(); + send(&mut client, ClientMessage::Attach); + let initial = snapshot(&mut client, |s| s.panes.len() == 1); + let first = initial.panes[0].id; + input( + &mut client, + first, + "stty -echo; printf '\\033[2J\\033[HSTACK_STATE\\n'\n", + ); + snapshot(&mut client, |s| contains(s, "STACK_STATE")); + send( + &mut client, + ClientMessage::NewStackPane { + pane: Some(first), + direction: VerticalDirection::Down, + cwd: None, + }, + ); + let second = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); + let bottom = active_tab(&second).active_pane; + assert_eq!(active_tab(&second).panes, [first, bottom]); + assert_eq!(active_tab(&second).stacks.len(), 1); + assert_eq!(second.panes.len(), 1); + assert_eq!(second.panes[0].id, bottom); + + send( + &mut client, + ClientMessage::RenamePane { + pane: first, + name: Some("Collapsed source".into()), + }, + ); + snapshot(&mut client, |s| { + active_tab(s).stacks[0].panes[0].title == "Collapsed source" + }); + send( + &mut client, + ClientMessage::NewStackPane { + pane: Some(bottom), + direction: VerticalDirection::Up, + cwd: None, + }, + ); + let third = snapshot(&mut client, |s| active_tab(s).panes.len() == 3); + let middle = active_tab(&third).active_pane; + assert_eq!(active_tab(&third).panes, [first, middle, bottom]); + assert_eq!(third.panes.len(), 1); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Up, + }, + ); + let top = snapshot(&mut client, |s| active_tab(s).active_pane == first); + assert!(contains(&top, "STACK_STATE")); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Up, + }, + ); + assert_eq!( + active_tab(&list_after_commands(&mut client)).active_pane, + first + ); + send( + &mut client, + ClientMessage::FocusStackPane { + pane: first, + direction: VerticalDirection::Down, + }, + ); + snapshot(&mut client, |s| active_tab(s).active_pane == middle); + send(&mut client, ClientMessage::FocusPane { pane: bottom }); + snapshot(&mut client, |s| active_tab(s).active_pane == bottom); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Down, + }, + ); + assert_eq!( + active_tab(&list_after_commands(&mut client)).active_pane, + bottom + ); + } + + #[test] + fn relative_commands_preserve_bursts_without_intermediate_snapshots() { + let server = TestServer::start(); + // A control client does not attach, so the only snapshots are the + // explicit List responses after each complete command burst. + let mut client = server.client(); + let inspect = |client: &mut UnixStream| { + send(client, ClientMessage::List); + snapshot(client, |_| true) + }; + for _ in 0..3 { + send(&mut client, ClientMessage::NewTab { cwd: None }); + } + let initial = inspect(&mut client); + let first_tab = initial.tabs[0].id; + let last_tab = initial.tabs[2].id; + let first_pane = initial.tabs[0].active_pane; + send(&mut client, ClientMessage::FocusTab { tab: first_tab }); + send(&mut client, ClientMessage::CycleTab { forward: true }); + send(&mut client, ClientMessage::CycleTab { forward: true }); + assert_eq!(inspect(&mut client).active_tab, last_tab); + send(&mut client, ClientMessage::CycleTab { forward: false }); + send(&mut client, ClientMessage::CycleTab { forward: false }); + assert_eq!(inspect(&mut client).active_tab, first_tab); + send(&mut client, ClientMessage::CycleTab { forward: false }); + assert_eq!(inspect(&mut client).active_tab, last_tab); + + send(&mut client, ClientMessage::FocusTab { tab: first_tab }); + for _ in 0..2 { + send( + &mut client, + ClientMessage::NewStackPane { + pane: None, + direction: VerticalDirection::Down, + cwd: None, + }, + ); + } + let down = inspect(&mut client); + let order = &active_tab(&down).panes; + assert_eq!(order.len(), 3); + assert_eq!(order[0], first_pane); + // Pane IDs grow with creation order: repeated Down appends in that + // order, rather than repeatedly inserting after the stale first pane. + assert!(order[1] < order[2]); + let last_down = order[2]; + assert_eq!(active_tab(&down).active_pane, last_down); + for _ in 0..2 { + send( + &mut client, + ClientMessage::NewStackPane { + pane: None, + direction: VerticalDirection::Up, + cwd: None, + }, + ); + } + let up = inspect(&mut client); + let order = &active_tab(&up).panes; + assert_eq!(order.len(), 5); + assert_eq!(order[4], last_down); + assert!(order[2] > order[3]); + let expanded = order[2]; + assert_eq!(active_tab(&up).active_pane, expanded); + + send( + &mut client, + ClientMessage::Split { + pane: expanded, + cwd: None, + }, + ); + let middle = active_tab(&inspect(&mut client)).active_pane; + send( + &mut client, + ClientMessage::Split { + pane: middle, + cwd: None, + }, + ); + let right = active_tab(&inspect(&mut client)).active_pane; + send(&mut client, ClientMessage::FocusPane { pane: expanded }); + send(&mut client, ClientMessage::CyclePane { forward: true }); + send(&mut client, ClientMessage::CyclePane { forward: true }); + assert_eq!(active_tab(&inspect(&mut client)).active_pane, right); + send(&mut client, ClientMessage::CyclePane { forward: true }); + assert_eq!(active_tab(&inspect(&mut client)).active_pane, expanded); + send(&mut client, ClientMessage::CyclePane { forward: false }); + send(&mut client, ClientMessage::CyclePane { forward: false }); + assert_eq!(active_tab(&inspect(&mut client)).active_pane, middle); + } + + #[test] + fn horizontal_navigation_moves_between_columns_and_then_tabs() { + let server = TestServer::start(); + let mut client = server.client(); + send(&mut client, ClientMessage::Attach); + let initial = snapshot(&mut client, |s| s.panes.len() == 1); + let first = initial.panes[0].id; + let first_tab = initial.active_tab; + send( + &mut client, + ClientMessage::NewStackPane { + pane: Some(first), + direction: VerticalDirection::Down, + cwd: None, + }, + ); + let stacked = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); + let expanded = active_tab(&stacked).active_pane; + send( + &mut client, + ClientMessage::Split { + pane: first, + cwd: None, + }, + ); + let split = snapshot(&mut client, |s| s.panes.len() == 2); + let right = active_tab(&split).active_pane; + assert_eq!(active_tab(&split).panes, [first, expanded, right]); + assert_eq!(active_tab(&split).stacks.len(), 2); + assert_eq!( + split.panes.iter().map(|pane| pane.id).collect::>(), + [expanded, right] + ); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Left, + }, + ); + snapshot(&mut client, |s| active_tab(s).active_pane == expanded); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Up, + }, + ); + snapshot(&mut client, |s| active_tab(s).active_pane == first); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Right, + }, + ); + snapshot(&mut client, |s| active_tab(s).active_pane == right); + send(&mut client, ClientMessage::NewTab { cwd: None }); + let next_tab = snapshot(&mut client, |s| s.tabs.len() == 2); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Left, + }, + ); + let restored = snapshot(&mut client, |s| s.active_tab == first_tab); + assert_eq!(active_tab(&restored).active_pane, right); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Right, + }, + ); + snapshot(&mut client, |s| s.active_tab == next_tab.active_tab); + send( + &mut client, + ClientMessage::FocusDirection { + direction: Direction::Right, + }, + ); + snapshot(&mut client, |s| s.active_tab == first_tab); + } + + #[test] + fn stack_state_and_collapsed_shells_survive_clients_and_exit_cleanly() { + let server = TestServer::start(); + let mut first_client = server.client(); + send(&mut first_client, ClientMessage::Attach); + let initial = snapshot(&mut first_client, |s| s.panes.len() == 1); + let top = initial.panes[0].id; + send( + &mut first_client, + ClientMessage::NewStackPane { + pane: Some(top), + direction: VerticalDirection::Down, + cwd: None, + }, + ); + let stacked = snapshot(&mut first_client, |s| active_tab(s).panes.len() == 2); + let middle = active_tab(&stacked).active_pane; + send( + &mut first_client, + ClientMessage::NewStackPane { + pane: Some(middle), + direction: VerticalDirection::Down, + cwd: None, + }, + ); + let three = snapshot(&mut first_client, |s| active_tab(s).panes.len() == 3); + let bottom = active_tab(&three).active_pane; + let mut other_client = server.client(); + send(&mut other_client, ClientMessage::Attach); + let mirrored = snapshot(&mut other_client, |s| active_tab(s).panes.len() == 3); + assert_eq!(active_tab(&mirrored).panes, [top, middle, bottom]); + send(&mut other_client, ClientMessage::FocusPane { pane: middle }); + snapshot(&mut other_client, |s| active_tab(s).active_pane == middle); + snapshot(&mut first_client, |s| active_tab(s).active_pane == middle); + send(&mut first_client, ClientMessage::Detach); + send(&mut other_client, ClientMessage::Detach); + drop(first_client); + drop(other_client); + let mut client = server.client(); + send(&mut client, ClientMessage::Attach); + let reattached = snapshot(&mut client, |s| active_tab(s).panes.len() == 3); + assert_eq!(reattached.active_tab, initial.active_tab); + assert_eq!(active_tab(&reattached).stacks[0].active_pane, middle); + assert_eq!(reattached.panes[0].id, middle); + + // A collapsed shell's exit leaves the focused/expanded pane alone. + input(&mut client, top, "exit\n"); + let collapsed_exit = snapshot(&mut client, |s| active_tab(s).panes.len() == 2); + assert_eq!(active_tab(&collapsed_exit).panes, [middle, bottom]); + assert_eq!(collapsed_exit.panes[0].id, middle); + // Explicit close uses the same adjacent fallback as natural exit. + send(&mut client, ClientMessage::ClosePane { pane: middle }); + let closed = snapshot(&mut client, |s| active_tab(s).panes.len() == 1); + assert_eq!(closed.panes[0].id, bottom); + send( + &mut client, + ClientMessage::Split { + pane: bottom, + cwd: None, + }, + ); + let split = snapshot(&mut client, |s| s.panes.len() == 2); + let other = active_tab(&split).active_pane; + input(&mut client, bottom, "exit\n"); + let removed_column = snapshot(&mut client, |s| active_tab(s).stacks.len() == 1); + assert_eq!(removed_column.panes[0].id, other); + input(&mut client, other, "exit\n"); + let empty = snapshot(&mut client, |s| s.tabs.is_empty()); + assert!(empty.panes.is_empty()); + } + #[test] fn natural_shell_exit_removes_panes_and_empty_tabs_without_stealing_focus() { let server = TestServer::start(); diff --git a/src/terminal.rs b/src/terminal.rs index fedf323..1473ae5 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -10,8 +10,8 @@ use crate::{ palette::CommandPalette, pane_name::RenameField, protocol::{ - ClientMessage, PaneSnapshot, ScrollKind, SelectionCommand, SelectionKind, SelectionSide, - Snapshot, + ClientMessage, Direction, PaneSnapshot, ScrollKind, SelectionCommand, SelectionKind, + SelectionSide, Snapshot, StackPaneInfo, VerticalDirection, }, render::{FONT_SIZE, LINE_HEIGHT, RenderCell, Renderer}, transition::Slide, @@ -37,7 +37,8 @@ pub struct Workspace { error: Option, focus: FocusHandle, palette: Option>, - outgoing: Vec>, + outgoing: HashMap>, + outgoing_snapshot: Option>, transition: Option, transition_frame_pending: bool, _updates: Task<()>, @@ -130,45 +131,41 @@ impl Workspace { let message = match action { NewTab => Some(ClientMessage::NewTab { cwd: None }), SplitPane => pane_id.map(|pane| ClientMessage::Split { pane, cwd: None }), + StackAbove | StackBelow => Some(ClientMessage::NewStackPane { + pane: None, + direction: if matches!(action, StackAbove) { + VerticalDirection::Up + } else { + VerticalDirection::Down + }, + cwd: None, + }), + FocusAbove | FocusBelow => Some(ClientMessage::FocusDirection { + direction: if matches!(action, FocusAbove) { + Direction::Up + } else { + Direction::Down + }, + }), ClosePane => pane_id.map(|pane| ClientMessage::ClosePane { pane }), ResetPaneName => pane_id.map(|pane| ClientMessage::RenamePane { pane, name: None }), Copy => pane_id.map(|pane| ClientMessage::Copy { pane }), Scroll(kind) => pane_id.map(|pane| ClientMessage::Scroll { pane, kind }), FocusTab(tab) => Some(ClientMessage::FocusTab { tab }), FocusPane(pane) => Some(ClientMessage::FocusPane { pane }), - PreviousTab | NextTab => self.adjacent_tab(matches!(action, NextTab)), - PreviousPane | NextPane => self.snapshot.as_ref().and_then(|snapshot| { - let index = snapshot - .panes - .iter() - .position(|pane| Some(pane.id) == pane_id)?; - let count = snapshot.panes.len(); - let next = if matches!(action, NextPane) { - (index + 1) % count + PreviousTab | NextTab => Some(ClientMessage::CycleTab { + forward: matches!(action, NextTab), + }), + PreviousPane | NextPane => Some(ClientMessage::CyclePane { + forward: matches!(action, NextPane), + }), + FocusLeft | FocusRight => Some(ClientMessage::FocusDirection { + direction: if matches!(action, FocusLeft) { + Direction::Left } else { - (index + count - 1) % count - }; - Some(ClientMessage::FocusPane { - pane: snapshot.panes[next].id, - }) + Direction::Right + }, }), - FocusLeft | FocusRight => { - let forward = matches!(action, FocusRight); - self.snapshot.as_ref().and_then(|snapshot| { - let index = snapshot - .panes - .iter() - .position(|pane| Some(pane.id) == pane_id)?; - let next = if forward { - index.checked_add(1) - } else { - index.checked_sub(1) - }; - next.and_then(|next| snapshot.panes.get(next)) - .map(|pane| ClientMessage::FocusPane { pane: pane.id }) - .or_else(|| self.adjacent_tab(forward)) - }) - } RenamePane => { if let Some(pane) = pane { pane.update(cx, |pane, cx| pane.begin_rename(window, cx)); @@ -204,22 +201,6 @@ impl Workspace { } } - fn adjacent_tab(&self, forward: bool) -> Option { - let snapshot = self.snapshot.as_ref()?; - let index = snapshot - .tabs - .iter() - .position(|tab| tab.id == snapshot.active_tab)?; - let count = snapshot.tabs.len(); - let next = if forward { - (index + 1) % count - } else { - (index + count - 1) % count - }; - Some(ClientMessage::FocusTab { - tab: snapshot.tabs[next].id, - }) - } pub fn new( client: Client, updates: Updates, @@ -241,20 +222,30 @@ impl Workspace { view.error = Some(error); } if let Some(snapshot) = update.snapshot { + let metadata_changed = view.snapshot.as_ref().is_none_or(|old| { + old.active_tab != snapshot.active_tab + || old.tabs != snapshot.tabs + }); + let focus_allowed = view.palette.is_none(); if let Some(direction) = view .snapshot .as_ref() .and_then(|old| scene_direction(old, &snapshot)) { + view.outgoing_snapshot = view.snapshot.clone(); view.outgoing = view .snapshot .as_ref() .unwrap() .panes .iter() - .filter_map(|data| view.panes.get(&data.id).cloned()) + .filter_map(|data| { + view.panes + .get(&data.id) + .map(|pane| (data.id, pane.clone())) + }) .collect(); - for pane in &view.outgoing { + for pane in view.outgoing.values() { pane.update(cx, |pane, cx| { pane.read_only = true; pane.transitioning = true; @@ -282,7 +273,7 @@ impl Workspace { pane.active = active == Some(data.id); pane.snapshot = snapshot.clone(); pane.index = index; - if pane.active && !was_active { + if pane.active && !was_active && focus_allowed { if let Some(editor) = &pane.rename { editor.read(cx).focus(window); } else { @@ -306,6 +297,7 @@ impl Workspace { frame, index, active == Some(data.id), + focus_allowed, window, cx, ); @@ -324,11 +316,11 @@ impl Workspace { window.set_window_title(&format!("psyTerm — {title}")); view.snapshot = Some(snapshot); if let Some(palette) = &view.palette { - let items = commands::root_items(view.snapshot.as_deref()); - palette.update(cx, |palette, cx| { - palette.set_items(items, cx); - palette.focus(window); - }); + if metadata_changed { + let items = commands::root_items(view.snapshot.as_deref()); + palette + .update(cx, |palette, cx| palette.set_items(items, cx)); + } } else if view.panes.is_empty() { window.focus(&view.focus); } @@ -351,7 +343,8 @@ impl Workspace { error: None, focus, palette: None, - outgoing: Vec::new(), + outgoing: HashMap::new(), + outgoing_snapshot: None, transition: None, transition_frame_pending: false, _updates: task, @@ -368,6 +361,7 @@ impl Render for Workspace { { self.transition = None; self.outgoing.clear(); + self.outgoing_snapshot = None; for pane in self.panes.values() { pane.update(cx, |pane, cx| { pane.transitioning = false; @@ -420,16 +414,12 @@ impl Render for Workspace { .min_h_0() .overflow_hidden() .bg(rgb(chrome::APP_BACKGROUND)); - if !self.outgoing.is_empty() { - body = body.child(scene(outgoing_offset).children(self.outgoing.iter().cloned())); + if let Some(snapshot) = &self.outgoing_snapshot { + body = body.child(pane_scene(snapshot, &self.outgoing, outgoing_offset, None)); } - let mut incoming = scene(incoming_offset); + let mut incoming = scene(incoming_offset).id("incoming-scene"); if let Some(snapshot) = &self.snapshot { - for data in &snapshot.panes { - if let Some(pane) = self.panes.get(&data.id) { - incoming = incoming.child(pane.clone()); - } - } + incoming = pane_scene(snapshot, &self.panes, incoming_offset, Some(&self.client)); if snapshot.panes.is_empty() { incoming = incoming.child( div() @@ -488,6 +478,106 @@ fn scene(offset: [f32; 2]) -> Div { .bg(rgb(chrome::APP_BACKGROUND)) } +fn pane_scene( + snapshot: &Snapshot, + panes: &HashMap>, + offset: [f32; 2], + client: Option<&Client>, +) -> Stateful
{ + // The frozen scene can contain the same collapsed headers as the live + // scene. Keep their hover, scroll, and click state in separate namespaces. + let mut content = scene(offset).id(if client.is_some() { + "incoming-scene" + } else { + "outgoing-scene" + }); + if let Some(tab) = snapshot + .tabs + .iter() + .find(|tab| tab.id == snapshot.active_tab) + { + for stack in &tab.stacks { + let Some(index) = stack + .panes + .iter() + .position(|pane| pane.id == stack.active_pane) + else { + continue; + }; + let mut column = div() + .flex_1() + .min_w_0() + .h_full() + .flex() + .flex_col() + .gap(px(2.)) + .overflow_hidden(); + if index > 0 { + column = column.child(stack_headers( + &stack.panes[..index], + format!("stack-above-{}", stack.active_pane), + client, + )); + } + if let Some(pane) = panes.get(&stack.active_pane) { + column = column.child(pane.clone()); + } + if index + 1 < stack.panes.len() { + column = column.child(stack_headers( + &stack.panes[index + 1..], + format!("stack-below-{}", stack.active_pane), + client, + )); + } + content = content.child(column); + } + } + content +} + +fn stack_headers(entries: &[StackPaneInfo], id: String, client: Option<&Client>) -> Stateful
{ + let mut headers = div() + .id(ElementId::Name(id.into())) + .flex() + .flex_col() + .w_full() + .flex_shrink_0() + .max_h(relative(0.25)) + .overflow_y_scroll(); + for entry in entries { + let pane = entry.id; + let client = client.cloned(); + headers = headers.child( + div() + .id(ElementId::Name(format!("collapsed-pane-{pane}").into())) + .h(px(28.)) + .flex_shrink_0() + .px(px(9.)) + .border_1() + .border_color(rgb(chrome::BORDER)) + .bg(rgb(chrome::TERMINAL_BACKGROUND)) + .font_family(".SystemUIFont") + .text_size(px(11.)) + .text_color(rgb(chrome::PANE_MUTED)) + .cursor_pointer() + .hover(|style| { + style + .bg(rgb(chrome::HOVER_BACKGROUND)) + .text_color(rgb(chrome::PANE_FOCUS)) + }) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click(move |_, _, cx| { + cx.stop_propagation(); + if let Some(client) = &client { + let _ = client.send(ClientMessage::FocusPane { pane }); + } + }) + .child(middle_label(entry.title.clone().into())), + ); + } + headers +} + fn scene_direction(old: &Snapshot, next: &Snapshot) -> Option<[f32; 2]> { if old.panes.is_empty() || next.panes.is_empty() { return None; @@ -505,6 +595,13 @@ fn scene_direction(old: &Snapshot, next: &Snapshot) -> Option<[f32; 2]> { .unwrap_or(0); return Some([if next_index > previous { 1. } else { -1. }, 0.]); } + if let (Some(old_tab), Some(next_tab)) = ( + old.tabs.iter().find(|tab| tab.id == old.active_tab), + next.tabs.iter().find(|tab| tab.id == next.active_tab), + ) && let Some(direction) = crate::transition::stack_direction(old_tab, next_tab) + { + return Some([0., direction]); + } next.panes .iter() .any(|pane| !old.panes.iter().any(|old| old.id == pane.id)) @@ -542,6 +639,7 @@ impl TerminalPane { snapshot: Arc, index: usize, active: bool, + focus_allowed: bool, window: &mut Window, cx: &mut Context, ) -> Self { @@ -554,7 +652,7 @@ impl TerminalPane { .unwrap_or(9.) .max(1.); let focus = cx.focus_handle(); - if active { + if active && focus_allowed { window.focus(&focus); } let activation = cx.observe_window_activation(window, |pane, _, cx| { @@ -980,6 +1078,7 @@ impl Render for TerminalPane { div() .flex_1() .min_w_0() + .min_h_0() .h_full() .flex() .flex_col() diff --git a/src/transition.rs b/src/transition.rs index e89e71b..1f90351 100644 --- a/src/transition.rs +++ b/src/transition.rs @@ -46,6 +46,40 @@ impl Slide { } } +/// Compare persistent stack order rather than viewport rows: inserting above +/// enters from above, and selecting an existing neighbor moves in that direction. +pub fn stack_direction( + old: &crate::protocol::TabInfo, + next: &crate::protocol::TabInfo, +) -> Option { + for next_stack in &next.stacks { + let Some(old_stack) = old.stacks.iter().find(|stack| { + stack + .panes + .iter() + .any(|pane| next_stack.panes.iter().any(|next| next.id == pane.id)) + }) else { + continue; + }; + if old_stack.active_pane == next_stack.active_pane { + continue; + } + for order in [&next_stack.panes, &old_stack.panes] { + if let (Some(before), Some(after)) = ( + order + .iter() + .position(|pane| pane.id == old_stack.active_pane), + order + .iter() + .position(|pane| pane.id == next_stack.active_pane), + ) { + return Some(if after > before { 1. } else { -1. }); + } + } + } + None +} + #[cfg(test)] mod tests { use super::*; @@ -78,4 +112,58 @@ mod tests { ); } } + fn stack(ids: &[u64], active: u64) -> crate::protocol::TabInfo { + crate::protocol::TabInfo { + id: 1, + title: String::new(), + panes: ids.to_vec(), + active_pane: active, + stacks: vec![crate::protocol::StackInfo { + active_pane: active, + panes: ids + .iter() + .map(|id| crate::protocol::StackPaneInfo { + id: *id, + title: String::new(), + }) + .collect(), + }], + } + } + + #[test] + fn stack_insertion_and_focus_follow_vertical_order() { + assert_eq!( + stack_direction(&stack(&[1], 1), &stack(&[2, 1], 2)), + Some(-1.) + ); + assert_eq!( + stack_direction(&stack(&[1], 1), &stack(&[1, 2], 2)), + Some(1.) + ); + assert_eq!( + stack_direction(&stack(&[2, 1, 3], 3), &stack(&[2, 1, 3], 1)), + Some(-1.) + ); + assert_eq!( + stack_direction(&stack(&[2, 1, 3], 1), &stack(&[2, 1, 3], 3)), + Some(1.) + ); + } + + #[test] + fn closing_expanded_pane_uses_old_order_and_collapsed_exit_stays_still() { + assert_eq!( + stack_direction(&stack(&[1, 2, 3], 2), &stack(&[1, 3], 3)), + Some(1.) + ); + assert_eq!( + stack_direction(&stack(&[1, 2, 3], 3), &stack(&[1, 2], 2)), + Some(-1.) + ); + assert_eq!( + stack_direction(&stack(&[1, 2, 3], 1), &stack(&[1, 3], 1)), + None + ); + } }