Skip to content

armgit / herdr

Public Imported from GitHub
0

the runtime your coding agents live on

fix: hidden pane memory and new pane spawn size (#4873)

Can Celik5da0a01e1eed
diff --git a/src/app/api.rs b/src/app/api.rs
index 20ca9d0f2..66fc30646 100644
--- a/src/app/api.rs
+++ b/src/app/api.rs
@@ -566,7 +566,13 @@ impl App {
.terminal_runtimes
.get(&terminal_id)
.map(|runtime| runtime.current_size())
- .unwrap_or_else(|| self.state.estimate_pane_size());
+ .unwrap_or_else(|| {
+ self.state
+ .new_pane_size(crate::ui::NewPanePlacement::Existing {
+ ws_idx,
+ pane: pane_id,
+ })
+ });
let Some(launch_env) = self.pane_launch_env(ws_idx, pane_id, Vec::new()) else {
return false;
};
diff --git a/src/app/api/layouts.rs b/src/app/api/layouts.rs
index 741904343..bde3421f0 100644
--- a/src/app/api/layouts.rs
+++ b/src/app/api/layouts.rs
@@ -89,7 +89,13 @@ impl App {
});
let root_leaf = first_layout_leaf(&params.root);
let first_cwd = self.layout_root_cwd(ws_idx, replace_target, root_leaf);
- let (rows, cols) = self.state.estimate_pane_size();
+ let pane_sizes = self
+ .state
+ .new_layout_pane_sizes(&final_tile_layout(&params.root));
+ // Sizes come from the same tree the panes are built from, in pane order.
+ let Some(&(rows, cols)) = pane_sizes.first() else {
+ return encode_error(id, "invalid_layout", "layout has no panes");
+ };
let default_shell = self.state.default_shell.clone();
let scrollback_limit_bytes = self.state.pane_scrollback_limit_bytes;
let host_terminal_theme = self.state.host_terminal_theme;
@@ -145,7 +151,9 @@ impl App {
}
self.apply_layout_pane_label(ws_idx, new_root_pane, root_leaf);
- if let Err(message) = self.apply_layout_node_to_pane(ws_idx, new_root_pane, &params.root) {
+ if let Err(message) =
+ self.apply_layout_node_to_pane(ws_idx, new_root_pane, &params.root, &pane_sizes)
+ {
self.rollback_layout_tab(ws_idx, new_root_pane);
return encode_error(id, "layout_apply_failed", message);
}
@@ -362,6 +370,7 @@ impl App {
ws_idx: usize,
pane_id: PaneId,
node: &LayoutNode,
+ pane_sizes: &[(u16, u16)],
) -> Result<(), String> {
match node {
LayoutNode::Pane { pane } => {
@@ -374,16 +383,21 @@ impl App {
first,
second,
} => {
- let second_leaf = first_layout_leaf(second);
+ let (first_sizes, second_sizes) =
+ pane_sizes.split_at(layout_leaf_count(first).min(pane_sizes.len()));
+ let Some(&size) = second_sizes.first() else {
+ return Err("layout pane sizes do not match the layout".into());
+ };
let new_pane = self.layout_split_pane(
ws_idx,
pane_id,
direction.clone(),
*ratio,
- second_leaf,
+ first_layout_leaf(second),
+ size,
)?;
- self.apply_layout_node_to_pane(ws_idx, pane_id, first)?;
- self.apply_layout_node_to_pane(ws_idx, new_pane, second)
+ self.apply_layout_node_to_pane(ws_idx, pane_id, first, first_sizes)?;
+ self.apply_layout_node_to_pane(ws_idx, new_pane, second, second_sizes)
}
}
}
@@ -395,8 +409,9 @@ impl App {
direction: SplitDirection,
ratio: f32,
pane: &LayoutPane,
+ (rows, cols): (u16, u16),
) -> Result<PaneId, String> {
- let (rows, cols) = self.state.estimate_pane_size();
+ let direction = layout_direction(&direction);
let default_shell = self.state.default_shell.clone();
let scrollback_limit_bytes = self.state.pane_scrollback_limit_bytes;
let host_terminal_theme = self.state.host_terminal_theme;
@@ -408,10 +423,6 @@ impl App {
.or_else(|| self.launch_cwd_for_pane_in_workspace(ws_idx, target_pane_id));
let extra_env = super::env::normalize_launch_env(pane.env.clone())
.map_err(|(_, message)| message.to_string())?;
- let direction = match direction {
- SplitDirection::Right => Direction::Horizontal,
- SplitDirection::Down => Direction::Vertical,
- };
let command = layout_command(pane)?;
let result = {
let Some(ws) = self.state.workspaces.get_mut(ws_idx) else {
@@ -515,6 +526,47 @@ impl App {
}
}
+fn layout_direction(direction: &SplitDirection) -> Direction {
+ match direction {
+ SplitDirection::Right => Direction::Horizontal,
+ SplitDirection::Down => Direction::Vertical,
+ }
+}
+
+fn layout_leaf_count(node: &LayoutNode) -> usize {
+ match node {
+ LayoutNode::Pane { .. } => 1,
+ LayoutNode::Split { first, second, .. } => {
+ layout_leaf_count(first) + layout_leaf_count(second)
+ }
+ }
+}
+
+/// The tab layout `root` will produce, with placeholder pane ids in pane order.
+fn final_tile_layout(root: &LayoutNode) -> crate::layout::TileLayout {
+ fn build(node: &LayoutNode, next_id: &mut u32) -> Node {
+ match node {
+ LayoutNode::Pane { .. } => {
+ *next_id += 1;
+ Node::Pane(PaneId::from_raw(*next_id))
+ }
+ LayoutNode::Split {
+ direction,
+ ratio,
+ first,
+ second,
+ } => Node::Split {
+ direction: layout_direction(direction),
+ ratio: crate::layout::valid_split_ratio(*ratio),
+ first: Box::new(build(first, next_id)),
+ second: Box::new(build(second, next_id)),
+ },
+ }
+ }
+ let root = build(root, &mut 0);
+ crate::layout::TileLayout::from_saved(root, PaneId::from_raw(1))
+}
+
fn first_layout_leaf(node: &LayoutNode) -> &LayoutPane {
match node {
LayoutNode::Pane { pane } => pane,
@@ -723,6 +775,81 @@ mod tests {
assert_eq!(error.error.code, "split_not_found");
}
+ #[tokio::test]
+ async fn layout_apply_starts_every_pane_at_its_final_size() {
+ let mut app = app_with_workspace();
+ let area = ratatui::layout::Rect::new(0, 0, 120, 40);
+ crate::ui::compute_view_without_resizing_panes(
+ &mut app.state,
+ &app.terminal_runtimes,
+ area,
+ );
+ let pane = || {
+ Box::new(LayoutNode::Pane {
+ pane: LayoutPane::default(),
+ })
+ };
+ let split = |direction, ratio, first, second| {
+ Box::new(LayoutNode::Split {
+ direction,
+ ratio,
+ first,
+ second,
+ })
+ };
+ let root = split(
+ SplitDirection::Right,
+ 0.6,
+ split(SplitDirection::Down, 0.3, pane(), pane()),
+ split(
+ SplitDirection::Down,
+ 0.95,
+ pane(),
+ split(SplitDirection::Right, 0.5, pane(), pane()),
+ ),
+ );
+
+ let response = app.handle_layout_apply(
+ "req".into(),
+ LayoutApplyParams {
+ workspace_id: None,
+ tab_id: None,
+ tab_label: None,
+ focus: false,
+ root: *root,
+ },
+ );
+
+ let _: SuccessResponse = serde_json::from_str(&response).unwrap();
+ let tab_idx = app.state.workspaces[0].tabs.len() - 1;
+ assert_ne!(app.state.workspaces[0].active_tab_index(), tab_idx);
+ let sizes = |app: &App| {
+ app.state.workspaces[0].tabs[tab_idx]
+ .layout
+ .pane_ids()
+ .into_iter()
+ .map(|pane_id| {
+ app.state
+ .runtime_for_pane_in_workspace(&app.terminal_runtimes, 0, pane_id)
+ .unwrap()
+ .current_size()
+ })
+ .collect::<Vec<_>>()
+ };
+ let spawned = sizes(&app);
+ assert_eq!(spawned.len(), 5);
+ crate::ui::resize_tab_surface(
+ &app.state,
+ &app.terminal_runtimes,
+ 0,
+ tab_idx,
+ area,
+ crate::kitty_graphics::HostCellSize::default(),
+ );
+ assert_eq!(sizes(&app), spawned);
+ shutdown_test_runtimes(&mut app);
+ }
+
#[tokio::test]
async fn layout_apply_replaces_tab_with_requested_tree() {
let mut app = app_with_workspace();
diff --git a/src/app/api/panes.rs b/src/app/api/panes.rs
index e4e03e71b..9e7be30de 100644
--- a/src/app/api/panes.rs
+++ b/src/app/api/panes.rs
@@ -52,7 +52,18 @@ impl App {
Ok(env) => env,
Err((code, message)) => return encode_error(id, &code, message),
};
- let (rows, cols) = self.state.estimate_pane_size();
+ let direction = match params.direction {
+ crate::api::schema::SplitDirection::Right => ratatui::layout::Direction::Horizontal,
+ crate::api::schema::SplitDirection::Down => ratatui::layout::Direction::Vertical,
+ };
+ let (rows, cols) = self
+ .state
+ .new_pane_size(crate::ui::NewPanePlacement::Split {
+ ws_idx,
+ target: target_pane_id,
+ direction,
+ ratio: params.ratio.unwrap_or(0.5),
+ });
let split_cwd = params.cwd.map(std::path::PathBuf::from).or_else(|| {
let follow_cwd = self.launch_cwd_for_pane_in_workspace(ws_idx, target_pane_id);
Some(self.resolve_new_terminal_cwd(follow_cwd))
@@ -65,10 +76,6 @@ impl App {
let Some(ws) = self.state.workspaces.get_mut(ws_idx) else {
return encode_error(id, "pane_not_found", "pane not found");
};
- let direction = match params.direction {
- crate::api::schema::SplitDirection::Right => ratatui::layout::Direction::Horizontal,
- crate::api::schema::SplitDirection::Down => ratatui::layout::Direction::Vertical,
- };
let shell_config = crate::pane::PaneShellConfig::new(&default_shell, self.state.shell_mode);
let split_result = match params.ratio {
Some(ratio) => ws.split_pane_with_ratio(
diff --git a/src/app/api/plugins/mod.rs b/src/app/api/plugins/mod.rs
index c9b37bfeb..9644453d8 100644
--- a/src/app/api/plugins/mod.rs
+++ b/src/app/api/plugins/mod.rs
@@ -1694,7 +1694,8 @@ command = ["cmd.exe", "/d", "/c", "slot.cmd", "default"]
let expected = child_cwd.join(where_probe).canonicalize().unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
loop {
- let text = runtime.recent_unwrapped_text(20);
+ // The pane is a narrow split, so the long path wraps across many rows.
+ let text = runtime.recent_unwrapped_text(400);
if text.lines().any(|line| {
std::fs::canonicalize(line.trim()).is_ok_and(|path| path == expected)
}) {
diff --git a/src/app/api/plugins/panes.rs b/src/app/api/plugins/panes.rs
index 057918861..a4f30b0ce 100644
--- a/src/app/api/plugins/panes.rs
+++ b/src/app/api/plugins/panes.rs
@@ -115,7 +115,17 @@ impl App {
crate::api::schema::SplitDirection::Right => Direction::Horizontal,
crate::api::schema::SplitDirection::Down => Direction::Vertical,
};
- let (rows, cols) = self.state.estimate_pane_size();
+ let new_pane_placement = if placement == PluginPanePlacement::Zoomed {
+ crate::ui::NewPanePlacement::ZoomedOverlay
+ } else {
+ crate::ui::NewPanePlacement::Split {
+ ws_idx,
+ target: target_pane,
+ direction,
+ ratio: 0.5,
+ }
+ };
+ let (rows, cols) = self.state.new_pane_size(new_pane_placement);
let previous_focus = self.state.current_pane_focus_target();
let Some(ws) = self.state.workspaces.get_mut(ws_idx) else {
return encode_error(id, "workspace_not_found", "workspace not found");
@@ -123,8 +133,8 @@ impl App {
let result = ws.split_pane_argv_command(
target_pane,
direction,
- rows.max(4),
- cols.max(10),
+ rows,
+ cols,
Some(cwd),
&pane.command,
extra_env,
@@ -195,13 +205,13 @@ impl App {
Ok(env) => env,
Err((code, message)) => return encode_error(id, &code, message),
};
- let (rows, cols) = self.state.estimate_pane_size();
+ let (rows, cols) = self.state.new_pane_size(crate::ui::NewPanePlacement::Alone);
let Some(ws) = self.state.workspaces.get_mut(ws_idx) else {
return encode_error(id, "workspace_not_found", "workspace not found");
};
let (tab_idx, terminal, runtime) = match ws.create_tab_argv_command(
- rows.max(4),
- cols.max(10),
+ rows,
+ cols,
cwd,
&pane.command,
extra_env,
diff --git a/src/app/api/tabs.rs b/src/app/api/tabs.rs
index c1bd86e9e..d8a6dc5a1 100644
--- a/src/app/api/tabs.rs
+++ b/src/app/api/tabs.rs
@@ -65,7 +65,7 @@ impl App {
let cwd = cwd.map(PathBuf::from).unwrap_or_else(|| {
self.resolve_new_terminal_cwd(self.focused_pane_cwd_in_workspace(ws_idx))
});
- let (rows, cols) = self.state.estimate_pane_size();
+ let (rows, cols) = self.state.new_pane_size(crate::ui::NewPanePlacement::Alone);
let default_shell = self.state.default_shell.clone();
let scrollback_limit_bytes = self.state.pane_scrollback_limit_bytes;
let host_terminal_theme = self.state.host_terminal_theme;
diff --git a/src/app/creation.rs b/src/app/creation.rs
index db2b584de..21e976ce8 100644
--- a/src/app/creation.rs
+++ b/src/app/creation.rs
@@ -129,7 +129,7 @@ impl App {
focus: bool,
extra_env: Vec<(String, String)>,
) -> std::io::Result<usize> {
- let (rows, cols) = self.state.estimate_pane_size();
+ let (rows, cols) = self.state.new_pane_size(crate::ui::NewPanePlacement::Alone);
let (ws, terminal, runtime) = Workspace::new_with_extra_env(
initial_cwd,
rows,
diff --git a/src/app/custom_commands.rs b/src/app/custom_commands.rs
index a2245884c..6e8a6c016 100644
--- a/src/app/custom_commands.rs
+++ b/src/app/custom_commands.rs
@@ -369,9 +369,9 @@ impl App {
return Err(std::io::Error::other("no active workspace"));
};
let previous_focus_target = self.state.current_pane_focus_target();
- let (rows, cols) = self.state.estimate_pane_size();
- let new_rows = rows.max(4);
- let new_cols = cols.max(10);
+ let (rows, cols) = self
+ .state
+ .new_pane_size(crate::ui::NewPanePlacement::ZoomedOverlay);
let (env, _) = self.custom_command_env();
let ws = self
@@ -393,8 +393,8 @@ impl App {
});
let new_pane = ws.split_focused_command(
Direction::Horizontal,
- new_rows,
- new_cols,
+ rows,
+ cols,
cwd,
command,
env,
@@ -448,9 +448,9 @@ impl App {
return Err(std::io::Error::other("no active workspace"));
};
let previous_focus_target = self.state.current_pane_focus_target();
- let (rows, cols) = self.state.estimate_pane_size();
- let new_rows = rows.max(4);
- let new_cols = cols.max(10);
+ let (rows, cols) = self
+ .state
+ .new_pane_size(crate::ui::NewPanePlacement::ZoomedOverlay);
let ws = self
.state
@@ -480,8 +480,8 @@ impl App {
let result = ws.split_pane_argv_command(
previous_focus,
Direction::Horizontal,
- new_rows,
- new_cols,
+ rows,
+ cols,
cwd,
argv,
extra_env,
diff --git a/src/app/mod.rs b/src/app/mod.rs
index 8fad961cf..8d6392e52 100644
--- a/src/app/mod.rs
+++ b/src/app/mod.rs
@@ -2764,6 +2764,83 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn hidden_panes_start_at_the_size_their_tab_layout_gives_them() {
+ let mut app = test_app();
+ let mut visible = Workspace::test_new("visible-with-tiny-first-pane");
+ let first = visible.tabs[0].root_pane;
+ for _ in 0..4 {
+ visible.tabs[0].layout.focus_pane(first);
+ visible.test_split(ratatui::layout::Direction::Vertical);
+ }
+ app.state.workspaces = vec![visible];
+ app.state.ensure_test_terminals();
+ app.state.active = Some(0);
+ app.state.selected = 0;
+ let area = Rect::new(0, 0, 120, 40);
+ crate::ui::compute_view_without_resizing_panes(
+ &mut app.state,
+ &app.terminal_runtimes,
+ area,
+ );
+ assert!(app.state.view.pane_infos[0].rect.height <= 3);
+
+ let size_of = |app: &App, ws_idx: usize, pane_id| {
+ app.state
+ .runtime_for_pane_in_workspace(&app.terminal_runtimes, ws_idx, pane_id)
+ .unwrap()
+ .current_size()
+ };
+ let relayout = |app: &App, ws_idx: usize| {
+ crate::ui::resize_tab_surface(
+ &app.state,
+ &app.terminal_runtimes,
+ ws_idx,
+ 0,
+ area,
+ crate::kitty_graphics::HostCellSize::default(),
+ );
+ };
+
+ let ws_idx = app
+ .create_workspace_with_options(std::env::temp_dir(), false)
+ .unwrap();
+ assert_eq!(app.state.active, Some(0));
+ let root = app.state.workspaces[ws_idx].tabs[0].root_pane;
+ let spawned = size_of(&app, ws_idx, root);
+ relayout(&app, ws_idx);
+ assert_eq!(size_of(&app, ws_idx, root), spawned);
+ assert!(spawned.0 > 30, "hidden root spawned at {spawned:?}");
+
+ let response =
+ app.handle_api_request_after_internal_events_drained(crate::api::schema::Request {
+ id: "req_hidden_split_size".into(),
+ method: crate::api::schema::Method::PaneSplit(
+ crate::api::schema::PaneSplitParams {
+ workspace_id: None,
+ target_pane_id: Some(app.pane_info(ws_idx, root).unwrap().pane_id),
+ direction: crate::api::schema::SplitDirection::Down,
+ ratio: Some(0.3),
+ cwd: None,
+ focus: false,
+ right_click: Default::default(),
+ env: Default::default(),
+ },
+ ),
+ });
+ let response: serde_json::Value = serde_json::from_str(&response).unwrap();
+ let (_, new_pane) = app
+ .parse_pane_id(response["result"]["pane"]["pane_id"].as_str().unwrap())
+ .unwrap();
+ let spawned = size_of(&app, ws_idx, new_pane);
+ relayout(&app, ws_idx);
+ assert_eq!(size_of(&app, ws_idx, new_pane), spawned);
+
+ for (_terminal_id, runtime) in app.terminal_runtimes.drain().collect::<Vec<_>>() {
+ runtime.shutdown();
+ }
+ }
+
#[tokio::test]
async fn pane_split_request_uses_active_focused_pane_when_target_is_omitted() {
let _guard = config_env_lock().lock().unwrap();
diff --git a/src/app/popup.rs b/src/app/popup.rs
index 0643ea8f2..988b3cb6f 100644
--- a/src/app/popup.rs
+++ b/src/app/popup.rs
@@ -142,8 +142,8 @@ impl App {
{
self.state.view.terminal_area
} else {
- let (estimated_rows, estimated_cols) = self.state.estimate_pane_size();
- ratatui::layout::Rect::new(0, 0, estimated_cols, estimated_rows)
+ let (cols, rows) = self.state.headless_size;
+ ratatui::layout::Rect::new(0, 0, cols, rows)
};
let Some(resolved_geometry) =
resolve_popup_geometry(geometry.width, geometry.height, terminal_area)
diff --git a/src/app/state.rs b/src/app/state.rs
index 65c06a6c3..f30279d6c 100644
--- a/src/app/state.rs
+++ b/src/app/state.rs
@@ -920,11 +920,27 @@ impl AppState {
})
}
- pub fn estimate_pane_size(&self) -> (u16, u16) {
- if let Some(info) = self.view.pane_infos.first() {
- (info.rect.height, info.rect.width)
+ /// Rows and columns a pane being created at `placement` will have once its
+ /// tab is laid out, including tabs that are not on screen.
+ pub(crate) fn new_pane_size(&self, placement: crate::ui::NewPanePlacement) -> (u16, u16) {
+ crate::ui::new_pane_terminal_size(self, self.new_pane_area(), placement)
+ }
+
+ /// Rows and columns for every pane of a tab about to be built as `layout`,
+ /// in pane order.
+ pub(crate) fn new_layout_pane_sizes(
+ &self,
+ layout: &crate::layout::TileLayout,
+ ) -> Vec<(u16, u16)> {
+ crate::ui::new_layout_terminal_sizes(self, self.new_pane_area(), layout)
+ }
+
+ fn new_pane_area(&self) -> Rect {
+ let area = self.view.terminal_area;
+ if area.width == 0 || area.height == 0 {
+ Rect::new(0, 0, self.headless_size.0, self.headless_size.1)
} else {
- (self.headless_size.1, self.headless_size.0)
+ area
}
}
@@ -1310,11 +1326,15 @@ mod tests {
use crossterm::event::KeyEvent;
#[test]
- fn pane_size_estimate_uses_headless_size_before_first_view() {
+ fn new_pane_size_uses_headless_size_before_first_view() {
let mut state = AppState::test_new();
state.headless_size = (132, 41);
+ state.pane_scrollbars = false;
- assert_eq!(state.estimate_pane_size(), (41, 132));
+ assert_eq!(
+ state.new_pane_size(crate::ui::NewPanePlacement::Alone),
+ (41, 132)
+ );
}
#[test]
diff --git a/src/layout.rs b/src/layout.rs
index 5ce72250b..aaa207ae3 100644
--- a/src/layout.rs
+++ b/src/layout.rs
@@ -129,6 +129,29 @@ impl TileLayout {
result
}
+ /// Compute pane rects as they will be after splitting `target`, without
+ /// changing the layout. Returns the rects and the new pane's index; the
+ /// new pane's entry carries `target`'s id.
+ pub fn panes_after_split(
+ &self,
+ area: Rect,
+ target: PaneId,
+ direction: Direction,
+ ratio: f32,
+ ) -> Option<(Vec<PaneInfo>, usize)> {
+ let mut panes = self.panes(area);
+ let index = panes.iter().position(|info| info.id == target)?;
+ let (first, second) = split_rect(panes[index].rect, direction, valid_split_ratio(ratio));
+ panes[index].rect = first;
+ panes[index].inner_rect = first;
+ let mut new_pane = panes[index].clone();
+ new_pane.rect = second;
+ new_pane.inner_rect = second;
+ new_pane.is_focused = false;
+ panes.insert(index + 1, new_pane);
+ Some((panes, index + 1))
+ }
+
/// Collect all split boundaries for mouse drag resize.
pub fn splits(&self, area: Rect) -> Vec<SplitBorder> {
let mut result = Vec::new();
@@ -602,7 +625,7 @@ fn split_node(target: PaneId, direction: Direction, new_id: PaneId, split_ratio:
}
}
-fn valid_split_ratio(ratio: f32) -> f32 {
+pub(crate) fn valid_split_ratio(ratio: f32) -> f32 {
if ratio.is_finite() {
ratio.clamp(0.1, 0.9)
} else {
@@ -789,6 +812,37 @@ mod tests {
);
}
+ #[test]
+ fn panes_after_split_predicts_the_real_split_geometry() {
+ let area = Rect::new(3, 1, 121, 37);
+ let (mut layout, root) = TileLayout::new();
+ let right = layout.split_pane(root, Direction::Horizontal, 0.6).unwrap();
+ let bottom_left = layout.split_pane(root, Direction::Vertical, 0.4).unwrap();
+ for (target, direction, ratio) in [
+ (bottom_left, Direction::Horizontal, 0.5),
+ (right, Direction::Vertical, 0.3),
+ (root, Direction::Horizontal, f32::NAN),
+ ] {
+ let (predicted, new_index) = layout
+ .panes_after_split(area, target, direction, ratio)
+ .unwrap();
+ let new_id = layout.split_pane(target, direction, ratio).unwrap();
+ let actual: Vec<_> = layout
+ .panes(area)
+ .into_iter()
+ .map(|info| info.rect)
+ .collect();
+ assert_eq!(
+ predicted.iter().map(|info| info.rect).collect::<Vec<_>>(),
+ actual
+ );
+ assert_eq!(layout.pane_ids()[new_index], new_id);
+ }
+ assert!(layout
+ .panes_after_split(area, PaneId::alloc(), Direction::Vertical, 0.5)
+ .is_none());
+ }
+
#[test]
#[ignore = "manual BSP allocation and traversal scaling profile"]
fn bsp_layout_profile() {
diff --git a/src/pane.rs b/src/pane.rs
index 3518d11ed..6e96e3b85 100644
--- a/src/pane.rs
+++ b/src/pane.rs
@@ -66,6 +66,9 @@ const RELEASE_REACQUIRE_SUPPRESSION: std::time::Duration = std::time::Duration::
const TERMINAL_COMPRESSION_IDLE: std::time::Duration = std::time::Duration::from_millis(250);
const TERMINAL_COMPRESSION_STEP: std::time::Duration = std::time::Duration::from_millis(1);
pub(crate) const PANE_TERM: &str = crate::ghostty::TERM;
+/// Smallest terminal grid a pane is resized to.
+pub(crate) const MIN_PANE_ROWS: u16 = 2;
+pub(crate) const MIN_PANE_COLS: u16 = 4;
const PANE_COLORTERM: &str = "truecolor";
fn terminal_compression_permits() -> Arc<tokio::sync::Semaphore> {
@@ -3184,8 +3187,8 @@ impl PaneRuntime {
/// Resize if the dimensions actually changed.
pub fn resize(&self, rows: u16, cols: u16, cell_width_px: u32, cell_height_px: u32) {
- let rows = rows.max(2);
- let cols = cols.max(4);
+ let rows = rows.max(MIN_PANE_ROWS);
+ let cols = cols.max(MIN_PANE_COLS);
let size = (rows, cols, cell_width_px, cell_height_px);
if self.current_size.get() == size {
return;
diff --git a/src/pane/terminal.rs b/src/pane/terminal.rs
index 4e27e45a9..d43aca1a8 100644
--- a/src/pane/terminal.rs
+++ b/src/pane/terminal.rs
@@ -1162,12 +1162,12 @@ impl GhosttyPaneTerminal {
})
.map_err(|e| std::io::Error::other(e.to_string()))?;
- let mut render_state =
+ let render_state =
crate::ghostty::RenderState::new().map_err(|e| std::io::Error::other(e.to_string()))?;
- let initial_colors = render_state
- .update(&terminal)
- .ok()
- .and_then(|_| render_state.colors().ok());
+ // Callers pass a terminal with unset default colors, so an updated render
+ // state would report the same baseline as an empty one. Updating here would
+ // build a cell snapshot at the spawn size, which hidden panes keep alive.
+ let initial_colors = render_state.colors().ok();
let initial_default_foreground = initial_colors.map(|colors| colors.foreground);
let initial_default_background = initial_colors.map(|colors| colors.background);
let mut key_encoder =
@@ -6126,6 +6126,64 @@ mod tests {
assert_eq!(row, "restored history");
}
+ #[test]
+ fn new_pane_terminal_defers_render_snapshot_and_keeps_baseline_colors() {
+ let (tx, _rx) = mpsc::channel(4);
+ let terminal = crate::ghostty::Terminal::new(200, 60, 0).unwrap();
+ let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
+
+ let mut reference_state = crate::ghostty::RenderState::new().unwrap();
+ reference_state
+ .update(&crate::ghostty::Terminal::new(1, 1, 0).unwrap())
+ .unwrap();
+ let reference = reference_state.colors().unwrap();
+
+ let core = pane.core.lock().unwrap();
+ assert_eq!(core.render_state.rows().unwrap(), 0);
+ assert_eq!(core.render_state.cols().unwrap(), 0);
+ assert_eq!(core.initial_default_foreground, Some(reference.foreground));
+ assert_eq!(core.initial_default_background, Some(reference.background));
+ }
+
+ #[test]
+ fn pane_created_large_renders_correctly_after_shrinking_before_first_draw() {
+ let (tx, _rx) = mpsc::channel(4);
+ let terminal = crate::ghostty::Terminal::new(200, 60, 100).unwrap();
+ let pane = GhosttyPaneTerminal::new(terminal, tx).unwrap();
+ pane.seed_history_ansi("restored\r\n");
+ pane.resize(5, 20, 0, 0);
+ {
+ let mut core = pane.core.lock().unwrap();
+ core.terminal
+ .write(b"\x1b]10;#abcdef\x07\x1b]11;#123456\x07hi");
+ }
+
+ let backend = ratatui::backend::TestBackend::new(20, 5);
+ let mut terminal = ratatui::Terminal::new(backend).unwrap();
+ terminal
+ .draw(|frame| pane.render(frame, Rect::new(0, 0, 20, 5), true))
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let row = |y| (0..20).map(|x| buffer[(x, y)].symbol()).collect::<String>();
+ assert_eq!(row(0).trim_end(), "restored");
+ assert_eq!(row(1).trim_end(), "hi");
+ assert_eq!(
+ buffer[(0, 1)].style().fg,
+ Some(Color::Rgb(0xab, 0xcd, 0xef))
+ );
+ assert_eq!(
+ buffer[(0, 1)].style().bg,
+ Some(Color::Rgb(0x12, 0x34, 0x56))
+ );
+ assert_eq!(
+ buffer[(19, 4)].style().bg,
+ Some(Color::Rgb(0x12, 0x34, 0x56))
+ );
+ let cursor = pane.cursor_state().unwrap();
+ assert_eq!((cursor.x, cursor.y), (2, 1));
+ }
+
#[test]
fn render_leaves_unknown_host_default_background_transparent() {
let (tx, _rx) = mpsc::channel(4);
diff --git a/src/ui.rs b/src/ui.rs
index 8fb7c7d30..4ec80dbaf 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -19,7 +19,8 @@ pub(crate) use self::onboarding::{
pub(crate) use self::panes::popup_pane_rects;
use self::panes::resize_popup_pane;
pub(crate) use self::panes::{
- apply_pane_chrome, pane_inner_rect, pane_is_scrolled_back, render_selection_highlight,
+ apply_pane_chrome, new_layout_terminal_sizes, new_pane_terminal_size, pane_inner_rect,
+ pane_is_scrolled_back, render_selection_highlight, NewPanePlacement,
};
pub(crate) use self::release_notes::{
product_announcement_display_lines, product_announcement_scroll_metrics,
diff --git a/src/ui/panes.rs b/src/ui/panes.rs
index adf1f3d30..6a91f18ac 100644
--- a/src/ui/panes.rs
+++ b/src/ui/panes.rs
@@ -1,6 +1,6 @@
use ratatui::{
buffer::Buffer,
- layout::Rect,
+ layout::{Direction, Rect},
style::{Color, Modifier, Style},
widgets::{Block, Borders, Paragraph, Wrap},
Frame,
@@ -13,7 +13,7 @@ use super::text::truncate_end;
use super::widgets::panel_contrast_fg;
use crate::app::state::Palette;
use crate::app::AppState;
-use crate::layout::PaneInfo;
+use crate::layout::{PaneId, PaneInfo};
use crate::popup_size::resolve_popup_geometry;
use crate::terminal::{TerminalRuntime, TerminalRuntimeRegistry};
@@ -34,7 +34,11 @@ fn pane_border_title(label: &str, pane_width: u16, _focused: bool) -> Option<Str
// Full view computation reaches this helper for active and background panes.
// Keep terminal queries narrow, allocation-free, and short under the core lock.
fn terminal_inner_rect(rt: &TerminalRuntime, pane_inner: Rect, pane_scrollbars: bool) -> Rect {
- if !pane_scrollbars || pane_inner.width <= 4 || rt.alternate_screen_active() {
+ terminal_inner_rect_for(pane_inner, pane_scrollbars && !rt.alternate_screen_active())
+}
+
+fn terminal_inner_rect_for(pane_inner: Rect, scrollbar_gutter: bool) -> Rect {
+ if !scrollbar_gutter || pane_inner.width <= 4 {
return pane_inner;
}
@@ -46,6 +50,108 @@ fn terminal_inner_rect(rt: &TerminalRuntime, pane_inner: Rect, pane_scrollbars:
)
}
+fn zoomed_pane_borders(app: &AppState, multi_pane: bool) -> Borders {
+ if app.pane_borders.shows_borders(multi_pane) && app.pane_outer_borders {
+ Borders::ALL
+ } else {
+ Borders::NONE
+ }
+}
+
+/// Where a pane that is about to be created will sit in its tab.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum NewPanePlacement {
+ /// The only pane of a new tab or workspace.
+ Alone,
+ /// The pane created by splitting `target` in workspace `ws_idx`.
+ Split {
+ ws_idx: usize,
+ target: PaneId,
+ direction: Direction,
+ ratio: f32,
+ },
+ /// A pane split off and immediately zoomed over its tab.
+ ZoomedOverlay,
+ /// An existing pane in workspace `ws_idx` getting a new terminal.
+ Existing { ws_idx: usize, pane: PaneId },
+}
+
+/// Terminal rows and columns a new pane gets once its tab is laid out in
+/// `area`, so its program starts at that size instead of being resized.
+pub(crate) fn new_pane_terminal_size(
+ app: &AppState,
+ area: Rect,
+ placement: NewPanePlacement,
+) -> (u16, u16) {
+ let laid_out = |panes: Vec<PaneInfo>, index: usize| {
+ let infos = apply_pane_chrome(
+ panes,
+ app.pane_borders,
+ app.pane_gaps,
+ app.pane_outer_borders,
+ );
+ pane_inner_rect(infos[index].rect, infos[index].borders)
+ };
+ // A lone pane has no neighbors, so its chrome matches a zoomed single pane.
+ let alone = || pane_inner_rect(area, zoomed_pane_borders(app, false));
+ let tab_for = |ws_idx: usize, pane: PaneId| {
+ let ws = app.workspaces.get(ws_idx)?;
+ ws.tabs.get(ws.find_tab_index_for_pane(pane)?)
+ };
+ let pane_inner = match placement {
+ NewPanePlacement::Alone => alone(),
+ NewPanePlacement::Existing { ws_idx, pane } => tab_for(ws_idx, pane)
+ .and_then(|tab| {
+ if tab.zoomed && tab.layout.focused() == pane {
+ let multi_pane = tab.layout.pane_count() > 1;
+ return Some(pane_inner_rect(area, zoomed_pane_borders(app, multi_pane)));
+ }
+ let panes = tab.layout.panes(area);
+ let index = panes.iter().position(|info| info.id == pane)?;
+ Some(laid_out(panes, index))
+ })
+ .unwrap_or_else(alone),
+ NewPanePlacement::ZoomedOverlay => pane_inner_rect(area, zoomed_pane_borders(app, true)),
+ NewPanePlacement::Split {
+ ws_idx,
+ target,
+ direction,
+ ratio,
+ } => tab_for(ws_idx, target)
+ .and_then(|tab| tab.layout.panes_after_split(area, target, direction, ratio))
+ .map(|(panes, new_index)| laid_out(panes, new_index))
+ .unwrap_or_else(alone),
+ };
+ new_terminal_size(app, pane_inner)
+}
+
+/// Terminal rows and columns for every pane of `layout` laid out in `area`, in
+/// pane order, so a multi-pane layout can start each program at its final size.
+pub(crate) fn new_layout_terminal_sizes(
+ app: &AppState,
+ area: Rect,
+ layout: &crate::layout::TileLayout,
+) -> Vec<(u16, u16)> {
+ apply_pane_chrome(
+ layout.panes(area),
+ app.pane_borders,
+ app.pane_gaps,
+ app.pane_outer_borders,
+ )
+ .into_iter()
+ .map(|info| new_terminal_size(app, pane_inner_rect(info.rect, info.borders)))
+ .collect()
+}
+
+fn new_terminal_size(app: &AppState, pane_inner: Rect) -> (u16, u16) {
+ // A new program starts on the primary screen, which reserves the gutter.
+ let inner = terminal_inner_rect_for(pane_inner, app.pane_scrollbars);
+ (
+ inner.height.max(crate::pane::MIN_PANE_ROWS),
+ inner.width.max(crate::pane::MIN_PANE_COLS),
+ )
+}
+
pub(crate) fn pane_inner_rect(area: Rect, borders: Borders) -> Rect {
if borders.is_empty() {
area
@@ -220,12 +326,7 @@ pub(super) fn resize_tab_panes(
if let Some((terminal_id, rt)) =
runtime_for_tab_pane(app, terminal_runtimes, workspace_index, tab, focused_id)
{
- let borders = if app.pane_borders.shows_borders(multi_pane) && app.pane_outer_borders {
- Borders::ALL
- } else {
- Borders::NONE
- };
- let pane_inner = pane_inner_rect(area, borders);
+ let pane_inner = pane_inner_rect(area, zoomed_pane_borders(app, multi_pane));
let inner_rect = terminal_inner_rect(rt, pane_inner, app.pane_scrollbars);
if !app.direct_attach_resize_locks.contains(terminal_id) {
rt.resize(
@@ -285,11 +386,7 @@ pub(super) fn compute_pane_infos_for_tab(
if tab.zoomed {
let focused_id = tab.layout.focused();
- let borders = if app.pane_borders.shows_borders(multi_pane) && app.pane_outer_borders {
- Borders::ALL
- } else {
- Borders::NONE
- };
+ let borders = zoomed_pane_borders(app, multi_pane);
let pane_inner = pane_inner_rect(area, borders);
let mut inner_rect = pane_inner;
let mut scrollbar_rect = None;