Add server-owned stacked panes with vertical navigation

This commit is contained in:
2026-11-17 02:08:02 -08:00
parent 4655f8149b
commit ec97ef00b0
10 changed files with 1129 additions and 136 deletions
+21
View File
@@ -29,6 +29,8 @@ pub fn action_for_key(key: &Keystroke) -> Option<CommandAction> {
"[" | "{" => 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> {
"}" => 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 [
+47 -2
View File
@@ -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<PaletteItem> {
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<PaletteItem> {
.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),
)
+61 -11
View File
@@ -86,17 +86,21 @@ pub fn control(socket: &Path, command: ClientMessage) -> Result<ServerMessage> {
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::<ClientMessage>(&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::<ClientMessage>(&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();
+8
View File
@@ -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::<Vec<_>>()
);
}
}
break;
}
+55 -3
View File
@@ -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<String>,
},
/// Insert above/below a pane, or current server focus when omitted.
NewStackPane {
pane: Option<PaneId>,
direction: VerticalDirection,
cwd: Option<String>,
},
/// 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<TabInfo>,
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<PaneSnapshot>,
}
#[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<PaneId>,
pub active_pane: PaneId,
/// Side-by-side columns; each expands one of its vertically ordered panes.
pub stacks: Vec<StackInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StackInfo {
pub panes: Vec<StackPaneInfo>,
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)]
+650 -40
View File
@@ -86,6 +86,24 @@ fn clean_title(title: String) -> Option<String> {
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::<Vec<_>>()
})
.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::<ServerMessage>(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::<String>();
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::<Vec<_>>(),
[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();
+167 -68
View File
@@ -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<String>,
focus: FocusHandle,
palette: Option<Entity<CommandPalette>>,
outgoing: Vec<Entity<TerminalPane>>,
outgoing: HashMap<u64, Entity<TerminalPane>>,
outgoing_snapshot: Option<Arc<Snapshot>>,
transition: Option<Slide>,
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<ClientMessage> {
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<u64, Entity<TerminalPane>>,
offset: [f32; 2],
client: Option<&Client>,
) -> Stateful<Div> {
// 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<Div> {
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<Snapshot>,
index: usize,
active: bool,
focus_allowed: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> 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()
+88
View File
@@ -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<f32> {
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
);
}
}