From 146b4465ba16796eea53bf8e7ead46bd0aee3bc3 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 26 Sep 2020 20:14:28 -0700 Subject: [PATCH] wezterm: update mux protocol for splits refs: https://github.com/wez/wezterm/issues/157 --- docs/changelog.markdown | 3 +- src/frontend/gui/termwindow.rs | 15 +- src/main.rs | 42 ++-- src/mux/domain.rs | 17 +- src/mux/mod.rs | 17 +- src/mux/tab.rs | 291 ++++++++++++++++++++++++-- src/server/client.rs | 3 +- src/server/codec.rs | 76 ++++++- src/server/domain.rs | 258 ++++++++++++++--------- src/server/listener/sessionhandler.rs | 108 ++++++---- src/server/tab/clienttab.rs | 34 ++- src/ssh.rs | 6 +- src/termwiztermtab.rs | 4 +- 13 files changed, 671 insertions(+), 203 deletions(-) diff --git a/docs/changelog.markdown b/docs/changelog.markdown index 3100e5e2d..ae722a897 100644 --- a/docs/changelog.markdown +++ b/docs/changelog.markdown @@ -24,8 +24,7 @@ brief notes about them may accumulate here. number to be zero based. * On Linux systems, wezterm can now attempt to guess the current working directory that shouldbe set in newly spawned local panes/tabs. -* Experimental support for splits/panes. Not currently - supported for multiplexer connections. +* Experimental support for splits/panes. See [#157](https://github.com/wez/wezterm/issues/157) for overall status and additional information. diff --git a/src/frontend/gui/termwindow.rs b/src/frontend/gui/termwindow.rs index f89770106..ffbebf49e 100644 --- a/src/frontend/gui/termwindow.rs +++ b/src/frontend/gui/termwindow.rs @@ -862,12 +862,9 @@ impl TermWindow { tab: &Rc, mux_window_id: MuxWindowId, ) -> anyhow::Result<()> { - let pane = tab - .get_active_pane() - .ok_or_else(|| anyhow!("tab has no panes"))?; - let dims = pane.renderer().get_dimensions(); - let physical_rows = dims.viewport_rows; - let physical_cols = dims.cols; + let size = tab.get_size(); + let physical_rows = size.rows as usize; + let physical_cols = size.cols as usize; let render_metrics = RenderMetrics::new(fontconfig); @@ -1690,11 +1687,13 @@ impl TermWindow { SpawnWhere::SplitPane(direction) => { let mux = Mux::get().unwrap(); if let Some(tab) = mux.get_active_tab_for_window(mux_window_id) { - let pane_index = tab.get_active_idx(); + let pane = tab + .get_active_pane() + .ok_or_else(|| anyhow!("tab to have a pane"))?; log::error!("doing split_pane"); domain - .split_pane(cmd_builder, cwd, tab.tab_id(), pane_index, direction) + .split_pane(cmd_builder, cwd, tab.tab_id(), pane.pane_id(), direction) .await?; } else { log::error!("boop"); diff --git a/src/main.rs b/src/main.rs index 0acf0bedb..b8a197097 100644 --- a/src/main.rs +++ b/src/main.rs @@ -939,22 +939,34 @@ fn run() -> anyhow::Result<()> { }, ]; let mut data = vec![]; - let tabs = block_on(client.list_tabs())?; // FIXME: blocking - for entry in tabs.tabs.iter() { - data.push(vec![ - entry.window_id.to_string(), - entry.tab_id.to_string(), - entry.pane_id.to_string(), - format!("{}x{}", entry.size.cols, entry.size.rows), - entry.title.clone(), - entry - .working_dir - .as_ref() - .map(|url| url.url.as_str()) - .unwrap_or("") - .to_string(), - ]); + let panes = block_on(client.list_panes())?; // FIXME: blocking + + for tabroot in panes.tabs { + let mut cursor = tabroot.into_tree().cursor(); + + loop { + if let Some(entry) = cursor.leaf_mut() { + data.push(vec![ + entry.window_id.to_string(), + entry.tab_id.to_string(), + entry.pane_id.to_string(), + format!("{}x{}", entry.size.cols, entry.size.rows), + entry.title.clone(), + entry + .working_dir + .as_ref() + .map(|url| url.url.as_str()) + .unwrap_or("") + .to_string(), + ]); + } + match cursor.preorder_next() { + Ok(c) => cursor = c, + Err(_) => break, + } + } } + tabulate_output(&cols, &data, &mut std::io::stdout().lock())?; } CliSubCommand::Proxy => { diff --git a/src/mux/domain.rs b/src/mux/domain.rs index f79827a1a..34fb07149 100644 --- a/src/mux/domain.rs +++ b/src/mux/domain.rs @@ -7,7 +7,7 @@ use crate::config::configuration; use crate::localtab::LocalPane; -use crate::mux::tab::{Pane, SplitDirection, Tab, TabId}; +use crate::mux::tab::{Pane, PaneId, SplitDirection, Tab, TabId}; use crate::mux::window::WindowId; use crate::mux::Mux; use anyhow::{bail, Error}; @@ -46,7 +46,7 @@ pub trait Domain: Downcast { command: Option, command_dir: Option, tab: TabId, - pane_index: usize, + pane_id: PaneId, split_direction: SplitDirection, ) -> anyhow::Result>; @@ -152,7 +152,7 @@ impl Domain for LocalDomain { let tab = Rc::new(Tab::new(&size)); tab.assign_pane(&pane); - mux.add_tab(&tab)?; + mux.add_tab_and_active_pane(&tab)?; mux.add_tab_to_window(&tab, window)?; Ok(tab) @@ -163,7 +163,7 @@ impl Domain for LocalDomain { command: Option, command_dir: Option, tab: TabId, - pane_index: usize, + pane_id: PaneId, direction: SplitDirection, ) -> anyhow::Result> { let mux = Mux::get().unwrap(); @@ -172,6 +172,15 @@ impl Domain for LocalDomain { None => anyhow::bail!("Invalid tab id {}", tab), }; + let pane_index = match tab + .iter_panes() + .iter() + .find(|p| p.pane.pane_id() == pane_id) + { + Some(p) => p.index, + None => anyhow::bail!("invalid pane id {}", pane_id), + }; + let split_size = match tab.compute_split_size(pane_index, direction) { Some(s) => s, None => anyhow::bail!("invalid pane index {}", pane_index), diff --git a/src/mux/mod.rs b/src/mux/mod.rs index affac6cf8..ce5333830 100644 --- a/src/mux/mod.rs +++ b/src/mux/mod.rs @@ -199,7 +199,11 @@ impl Mux { Ok(()) } - pub fn add_tab(&self, tab: &Rc) -> Result<(), Error> { + pub fn add_tab_no_panes(&self, tab: &Rc) { + self.tabs.borrow_mut().insert(tab.tab_id(), Rc::clone(tab)); + } + + pub fn add_tab_and_active_pane(&self, tab: &Rc) -> Result<(), Error> { self.tabs.borrow_mut().insert(tab.tab_id(), Rc::clone(tab)); let pane = tab .get_active_pane() @@ -309,6 +313,17 @@ impl Mux { Ok(()) } + pub fn window_containing_tab(&self, tab_id: TabId) -> Option { + for w in self.windows.borrow().values() { + for t in w.iter() { + if t.tab_id() == tab_id { + return Some(w.window_id()); + } + } + } + None + } + pub fn is_empty(&self) -> bool { self.tabs.borrow().is_empty() } diff --git a/src/mux/tab.rs b/src/mux/tab.rs index 79b80381c..5d11ae74b 100644 --- a/src/mux/tab.rs +++ b/src/mux/tab.rs @@ -1,7 +1,8 @@ use crate::keyassignment::PaneDirection; use crate::mux::domain::DomainId; use crate::mux::renderable::Renderable; -use crate::mux::Mux; +use crate::mux::{Mux, WindowId}; +use crate::server::codec::{PaneEntry, PaneNode}; use async_trait::async_trait; use bintree::PathBranch; use downcast_rs::{impl_downcast, Downcast}; @@ -95,7 +96,6 @@ pub struct SearchResult { } /// A Tab is a container of Panes -/// At this time only a single pane is supported pub struct Tab { id: TabId, pane: RefCell>, @@ -138,14 +138,14 @@ impl std::fmt::Debug for PositionedPane { } } -#[derive(Debug, Clone, Copy, Eq, PartialEq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] pub enum SplitDirection { Horizontal, Vertical, } /// The size is of the (first, second) child of the split -#[derive(Debug, Clone, Copy, Eq, PartialEq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] pub struct SplitDirectionAndSize { pub direction: SplitDirection, pub first: PtySize, @@ -166,6 +166,37 @@ impl SplitDirectionAndSize { SplitDirection::Vertical => 0, } } + + pub fn width(&self) -> u16 { + if self.direction == SplitDirection::Horizontal { + self.first.cols + self.second.cols + 1 + } else { + self.first.cols + } + } + + pub fn height(&self) -> u16 { + if self.direction == SplitDirection::Vertical { + self.first.rows + self.second.rows + 1 + } else { + self.first.rows + } + } + + pub fn size(&self) -> PtySize { + let cell_width = self.first.pixel_width / self.first.cols; + let cell_height = self.first.pixel_height / self.first.rows; + + let rows = self.height(); + let cols = self.width(); + + PtySize { + rows, + cols, + pixel_height: cell_height * rows, + pixel_width: cell_width * cols, + } + } } #[derive(Debug, Clone, Copy, Eq, PartialEq)] @@ -184,24 +215,78 @@ pub struct PositionedSplit { pub size: usize, } -impl SplitDirectionAndSize { - pub fn width(&self) -> u16 { - if self.direction == SplitDirection::Horizontal { - self.first.cols + self.second.cols + 1 - } else { - if self.first.cols != self.second.cols { - log::error!("{:#?}", self); - } - assert_eq!(self.first.cols, self.second.cols); - self.first.cols +fn is_pane(pane: &Rc, other: &Option<&Rc>) -> bool { + if let Some(other) = other { + other.pane_id() == pane.pane_id() + } else { + false + } +} + +fn pane_tree( + tree: &Tree, + tab_id: TabId, + window_id: WindowId, + active: Option<&Rc>, + zoomed: Option<&Rc>, +) -> PaneNode { + match tree { + Tree::Empty => PaneNode::Empty, + Tree::Node { left, right, data } => PaneNode::Split { + left: Box::new(pane_tree(&*left, tab_id, window_id, active, zoomed)), + right: Box::new(pane_tree(&*right, tab_id, window_id, active, zoomed)), + node: data.unwrap(), + }, + Tree::Leaf(pane) => { + let dims = pane.renderer().get_dimensions(); + let working_dir = pane.get_current_working_dir(); + + PaneNode::Leaf(PaneEntry { + window_id, + tab_id, + pane_id: pane.pane_id(), + title: pane.get_title(), + is_active_pane: is_pane(pane, &active), + is_zoomed_pane: is_pane(pane, &zoomed), + size: PtySize { + cols: dims.cols as u16, + rows: dims.viewport_rows as u16, + pixel_height: 0, + pixel_width: 0, + }, + working_dir: working_dir.map(Into::into), + }) } } - pub fn height(&self) -> u16 { - if self.direction == SplitDirection::Vertical { - self.first.rows + self.second.rows + 1 - } else { - assert_eq!(self.first.rows, self.second.rows); - self.first.rows +} + +fn build_from_pane_tree( + tree: bintree::Tree, + active: &mut Option>, + zoomed: &mut Option>, + make_pane: &F, +) -> Tree +where + F: Fn(PaneEntry) -> Rc, +{ + match tree { + bintree::Tree::Empty => Tree::Empty, + bintree::Tree::Node { left, right, data } => Tree::Node { + left: Box::new(build_from_pane_tree(*left, active, zoomed, make_pane)), + right: Box::new(build_from_pane_tree(*right, active, zoomed, make_pane)), + data, + }, + bintree::Tree::Leaf(entry) => { + let is_zoomed_pane = entry.is_zoomed_pane; + let is_active_pane = entry.is_active_pane; + let pane = make_pane(entry); + if is_zoomed_pane { + zoomed.replace(Rc::clone(&pane)); + } + if is_active_pane { + active.replace(Rc::clone(&pane)); + } + Tree::Leaf(pane) } } } @@ -217,6 +302,87 @@ impl Tab { } } + /// Called by the multiplexer client when building a local tab to + /// mirror a remote tab. The supplied `root` is the information + /// about our counterpart in the the remote server. + /// This method builds a local tree based on the remote tree which + /// then replaces the local tree structure. + /// + /// The `make_pane` function is provided by the caller, and its purpose + /// is to lookup an existing Pane that corresponds to the provided + /// PaneEntry, or to create a new Pane from that entry. + /// make_pane is expected to add the pane to the mux if it creates + /// a new pane, otherwise the pane won't poll/update in the GUI. + pub fn sync_with_pane_tree(&self, size: PtySize, root: PaneNode, make_pane: F) + where + F: Fn(PaneEntry) -> Rc, + { + let mut active = None; + let mut zoomed = None; + + log::debug!("sync_with_pane_tree with size {:?}", size); + + let t = build_from_pane_tree(root.into_tree(), &mut active, &mut zoomed, &make_pane); + let mut cursor = t.cursor(); + + *self.active.borrow_mut() = 0; + if let Some(active) = active { + // Resolve the active pane to its index + let mut index = 0; + loop { + if let Some(pane) = cursor.leaf_mut() { + if active.pane_id() == pane.pane_id() { + // Found it + *self.active.borrow_mut() = index; + break; + } + index += 1; + } + match cursor.preorder_next() { + Ok(c) => cursor = c, + Err(c) => { + // Didn't find it + cursor = c; + break; + } + } + } + } + self.pane.borrow_mut().replace(cursor.tree()); + *self.zoomed.borrow_mut() = zoomed; + *self.size.borrow_mut() = size; + + self.resize(size); + + log::debug!( + "sync tab: {:#?} zoomed: {} {:#?}", + size, + self.zoomed.borrow().is_some(), + self.iter_panes() + ); + assert!(self.pane.borrow().is_some()); + } + + pub fn codec_pane_tree(&self) -> PaneNode { + let mux = Mux::get().unwrap(); + let tab_id = self.id; + let window_id = match mux.window_containing_tab(tab_id) { + Some(w) => w, + None => { + log::error!("no window contains tab {}", tab_id); + return PaneNode::Empty; + } + }; + + let zoomed = self.zoomed.borrow(); + let active = self.get_active_pane(); + if let Some(root) = self.pane.borrow().as_ref() { + pane_tree(root, tab_id, window_id, active.as_ref(), zoomed.as_ref()) + } else { + PaneNode::Empty + } + } + /// Returns a count of how many panes are in this tab pub fn count_panes(&self) -> usize { let mut count = 0; @@ -237,16 +403,29 @@ impl Tab { } } + pub fn set_zoomed(&self, zoomed: bool) { + if self.zoomed.borrow().is_some() == zoomed { + // Current zoom state matches intended zoom state, + // so we have nothing to do. + return; + } + self.toggle_zoom(); + } + pub fn toggle_zoom(&self) { let size = *self.size.borrow(); if self.zoomed.borrow_mut().take().is_some() { // We were zoomed, but now we are not. // Re-apply the size to the panes + if let Some(pane) = self.get_active_pane() { + pane.set_zoomed(false); + } self.resize(size); } else { // We weren't zoomed, but now we want to zoom. // Locate the active pane if let Some(pane) = self.get_active_pane() { + pane.set_zoomed(true); pane.resize(size).ok(); self.zoomed.borrow_mut().replace(pane); } @@ -391,7 +570,6 @@ impl Tab { /// This works by adjusting the size of the second half of each split. pub fn resize(&self, size: PtySize) { let mut root = self.pane.borrow_mut(); - let mut cursor = root.take().unwrap().cursor(); *self.size.borrow_mut() = size; if let Some(zoomed) = self.zoomed.borrow().as_ref() { @@ -399,6 +577,8 @@ impl Tab { return; } + let mut cursor = root.take().unwrap().cursor(); + loop { // Figure out the available size by looking at our immediate parent node. // If we are the root, look at the provided new size @@ -455,6 +635,61 @@ impl Tab { } } + /// Called when running in the mux server after an individual pane + /// has been resized. + /// Because the split manipulation happened on the GUI we "lost" + /// the information that would have allowed us to call resize_split_by() + /// and instead need to back-infer the split size information. + /// We rely on the client to have resized (or be in the process + /// of resizing) affected panes consistently with its own Tab + /// tree model. + /// This method does a simple tree walk to the leaves to back-propagate + /// the size of the panes up to their containing node split data. + /// Without this step, disconnecting and reconnecting would cause + /// the GUI to use stale size information for the window it spawns + /// to attach this tab. + pub fn rebuild_splits_sizes_from_contained_panes(&self) { + if self.zoomed.borrow().is_some() { + return; + } + + fn compute_size(node: &mut Tree) -> Option { + match node { + Tree::Empty => None, + Tree::Leaf(pane) => { + let dims = pane.renderer().get_dimensions(); + let size = PtySize { + cols: dims.cols as u16, + rows: dims.viewport_rows as u16, + pixel_height: 0, + pixel_width: 0, + }; + Some(size) + } + Tree::Node { left, right, data } => { + if let Some(data) = data { + if let Some(first) = compute_size(left) { + data.first = first; + } + if let Some(second) = compute_size(right) { + data.second = second; + } + Some(data.size()) + } else { + None + } + } + } + } + + let mut root = self.pane.borrow_mut(); + if let Some(root) = root.as_mut() { + if let Some(size) = compute_size(root) { + *self.size.borrow_mut() = size; + } + } + } + /// Given split_index, the topological index of a split returned by /// iter_splits() as PositionedSplit::index, revised the split position /// by the provided delta; positive values move the split to the right/bottom, @@ -839,10 +1074,21 @@ impl Tab { .map(|p| Rc::clone(&p.pane)) } + #[allow(unused)] pub fn get_active_idx(&self) -> usize { *self.active.borrow() } + pub fn set_active_pane(&self, pane: &Rc) { + if let Some(item) = self + .iter_panes() + .iter() + .find(|p| p.pane.pane_id() == pane.pane_id()) + { + *self.active.borrow_mut() = item.index; + } + } + pub fn set_active_idx(&self, pane_index: usize) { *self.active.borrow_mut() = pane_index; } @@ -1007,6 +1253,9 @@ pub trait Pane: Downcast { fn reader(&self) -> anyhow::Result>; fn writer(&self) -> RefMut; fn resize(&self, size: PtySize) -> anyhow::Result<()>; + /// Called as a hint that the pane is being resized as part of + /// a zoom-to-fill-all-the-tab-space operation. + fn set_zoomed(&self, _zoomed: bool) {} fn key_down(&self, key: KeyCode, mods: KeyModifiers) -> anyhow::Result<()>; fn mouse_event(&self, event: MouseEvent) -> anyhow::Result<()>; fn advance_bytes(&self, buf: &[u8]); diff --git a/src/server/client.rs b/src/server/client.rs index f698aa108..fed216f85 100644 --- a/src/server/client.rs +++ b/src/server/client.rs @@ -872,13 +872,14 @@ impl Client { } rpc!(ping, Ping = (), Pong); - rpc!(list_tabs, ListTabs = (), ListTabsResponse); + rpc!(list_panes, ListPanes = (), ListPanesResponse); rpc!(spawn, Spawn, SpawnResponse); rpc!(write_to_pane, WriteToPane, UnitResponse); rpc!(send_paste, SendPaste, UnitResponse); rpc!(key_down, SendKeyDown, UnitResponse); rpc!(mouse_event, SendMouseEvent, UnitResponse); rpc!(resize, Resize, UnitResponse); + rpc!(set_zoomed, SetPaneZoomed, UnitResponse); rpc!( get_tab_render_changes, GetPaneRenderChanges, diff --git a/src/server/codec.rs b/src/server/codec.rs index 507018220..2146db793 100644 --- a/src/server/codec.rs +++ b/src/server/codec.rs @@ -13,7 +13,7 @@ use crate::mux::domain::DomainId; use crate::mux::renderable::{RenderableDimensions, StableCursorPosition}; -use crate::mux::tab::{PaneId, TabId}; +use crate::mux::tab::{PaneId, SplitDirection, SplitDirectionAndSize, TabId}; use crate::mux::window::WindowId; use anyhow::{bail, Context as _, Error}; use leb128; @@ -246,7 +246,7 @@ macro_rules! pdu { /// The overall version of the codec. /// This must be bumped when backwards incompatible changes /// are made to the types and protocol. -pub const CODEC_VERSION: usize = 5; +pub const CODEC_VERSION: usize = 6; // Defines the Pdu enum. // Each struct has an explicit identifying number. @@ -256,8 +256,8 @@ pdu! { ErrorResponse: 0, Ping: 1, Pong: 2, - ListTabs: 3, - ListTabsResponse: 4, + ListPanes: 3, + ListPanesResponse: 4, Spawn: 7, SpawnResponse: 8, WriteToPane: 9, @@ -278,6 +278,7 @@ pdu! { LivenessResponse: 30, SearchScrollbackRequest: 31, SearchScrollbackResponse: 32, + SetPaneZoomed: 33, } impl Pdu { @@ -395,7 +396,7 @@ pub struct GetTlsCredsResponse { } #[derive(Deserialize, Serialize, PartialEq, Debug)] -pub struct ListTabs {} +pub struct ListPanes {} #[derive(Deserialize, Clone, Serialize, PartialEq, Debug)] #[serde(try_from = "String", into = "String")] @@ -430,19 +431,64 @@ impl Into for SerdeUrl { } #[derive(Deserialize, Serialize, PartialEq, Debug)] -pub struct WindowAndTabEntry { - // FIXME: rename to WindowTabPaneEntry ? +pub enum PaneNode { + Empty, + Split { + left: Box, + right: Box, + node: SplitDirectionAndSize, + }, + Leaf(PaneEntry), +} + +impl PaneNode { + pub fn into_tree(self) -> bintree::Tree { + match self { + PaneNode::Empty => bintree::Tree::Empty, + PaneNode::Split { left, right, node } => bintree::Tree::Node { + left: Box::new((*left).into_tree()), + right: Box::new((*right).into_tree()), + data: Some(node), + }, + PaneNode::Leaf(e) => bintree::Tree::Leaf(e), + } + } + + pub fn root_size(&self) -> Option { + match self { + PaneNode::Empty => None, + PaneNode::Split { node, .. } => Some(node.size()), + PaneNode::Leaf(entry) => Some(entry.size), + } + } + + pub fn window_and_tab_ids(&self) -> Option<(WindowId, TabId)> { + match self { + PaneNode::Empty => None, + PaneNode::Split { left, right, .. } => match left.window_and_tab_ids() { + Some(res) => Some(res), + None => right.window_and_tab_ids(), + }, + PaneNode::Leaf(entry) => Some((entry.window_id, entry.tab_id)), + } + } +} + +#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] +pub struct PaneEntry { pub window_id: WindowId, pub tab_id: TabId, - pub pane_id: TabId, + pub pane_id: PaneId, pub title: String, pub size: PtySize, pub working_dir: Option, + pub is_active_pane: bool, + pub is_zoomed_pane: bool, } #[derive(Deserialize, Serialize, PartialEq, Debug)] -pub struct ListTabsResponse { - pub tabs: Vec, +pub struct ListPanesResponse { + pub tabs: Vec, } #[derive(Deserialize, Serialize, PartialEq, Debug)] @@ -450,6 +496,7 @@ pub struct Spawn { pub domain_id: DomainId, /// If None, create a new window for this new tab pub window_id: Option, + pub split: Option<(TabId, PaneId, SplitDirection)>, pub command: Option, pub command_dir: Option, pub size: PtySize, @@ -460,6 +507,7 @@ pub struct SpawnResponse { pub tab_id: TabId, pub pane_id: PaneId, pub window_id: WindowId, + pub size: PtySize, } #[derive(Deserialize, Serialize, PartialEq, Debug)] @@ -529,10 +577,18 @@ pub struct SetClipboard { #[derive(Deserialize, Serialize, PartialEq, Debug)] pub struct Resize { + pub containing_tab_id: TabId, pub pane_id: PaneId, pub size: PtySize, } +#[derive(Deserialize, Serialize, PartialEq, Debug)] +pub struct SetPaneZoomed { + pub containing_tab_id: TabId, + pub pane_id: PaneId, + pub zoomed: bool, +} + #[derive(Deserialize, Serialize, PartialEq, Debug)] pub struct GetPaneRenderChanges { pub pane_id: PaneId, diff --git a/src/server/domain.rs b/src/server/domain.rs index d126ba51c..c3cec1461 100644 --- a/src/server/domain.rs +++ b/src/server/domain.rs @@ -7,7 +7,7 @@ use crate::mux::tab::{Pane, PaneId, SplitDirection, Tab, TabId}; use crate::mux::window::WindowId; use crate::mux::Mux; use crate::server::client::Client; -use crate::server::codec::{ListTabsResponse, Spawn}; +use crate::server::codec::{ListPanesResponse, Spawn}; use crate::server::tab::ClientPane; use anyhow::{anyhow, bail}; use async_trait::async_trait; @@ -219,100 +219,112 @@ impl ClientDomain { pub async fn reattach(domain_id: DomainId, ui: ConnectionUI) -> anyhow::Result<()> { let inner = Self::get_client_inner_for_domain(domain_id)?; - let tabs = inner.client.list_tabs().await?; - Self::process_tab_list(inner, tabs)?; + let panes = inner.client.list_panes().await?; + Self::process_pane_list(inner, panes)?; ui.close(); Ok(()) } - fn process_tab_list(inner: Arc, tabs: ListTabsResponse) -> anyhow::Result<()> { + fn process_pane_list(inner: Arc, panes: ListPanesResponse) -> anyhow::Result<()> { let mux = Mux::get().expect("to be called on main thread"); - log::debug!("ListTabs result {:#?}", tabs); + log::debug!("ListPanes result {:#?}", panes); - for entry in tabs.tabs.iter() { - let tab; + for tabroot in panes.tabs { + let root_size = match tabroot.root_size() { + Some(size) => size, + None => continue, + }; - if let Some(tab_id) = inner.remote_to_local_tab_id(entry.tab_id) { - match mux.get_tab(tab_id) { - Some(t) => tab = t, - None => { - // We likely decided that we hit EOF on the tab and - // removed it from the mux. Let's add it back, but - // with a new id. - inner.remove_old_tab_mapping(entry.tab_id); - tab = Rc::new(Tab::new(&entry.size)); - inner.record_remote_to_local_tab_mapping(entry.tab_id, tab.tab_id()); - } - }; - } else { - tab = Rc::new(Tab::new(&entry.size)); - inner.record_remote_to_local_tab_mapping(entry.tab_id, tab.tab_id()); - } + if let Some((remote_window_id, remote_tab_id)) = tabroot.window_and_tab_ids() { + let tab; - if let Some(pane_id) = inner.remote_to_local_pane_id(entry.pane_id) { - match mux.get_pane(pane_id) { - Some(_pane) => {} - None => { - // We likely decided that we hit EOF on the tab and - // removed it from the mux. Let's add it back, but - // with a new id. - inner.remove_old_pane_mapping(entry.pane_id); + if let Some(tab_id) = inner.remote_to_local_tab_id(remote_tab_id) { + match mux.get_tab(tab_id) { + Some(t) => tab = t, + None => { + // We likely decided that we hit EOF on the tab and + // removed it from the mux. Let's add it back, but + // with a new id. + inner.remove_old_tab_mapping(remote_tab_id); + tab = Rc::new(Tab::new(&root_size)); + inner.record_remote_to_local_tab_mapping(remote_tab_id, tab.tab_id()); + mux.add_tab_no_panes(&tab); + } + }; + } else { + tab = Rc::new(Tab::new(&root_size)); + mux.add_tab_no_panes(&tab); + inner.record_remote_to_local_tab_mapping(remote_tab_id, tab.tab_id()); + } + + log::debug!("tree: {:#?}", tabroot); + tab.sync_with_pane_tree(root_size, tabroot, |entry| { + if let Some(pane_id) = inner.remote_to_local_pane_id(entry.pane_id) { + match mux.get_pane(pane_id) { + Some(pane) => pane, + None => { + // We likely decided that we hit EOF on the tab and + // removed it from the mux. Let's add it back, but + // with a new id. + inner.remove_old_pane_mapping(entry.pane_id); + let pane: Rc = Rc::new(ClientPane::new( + &inner, + entry.tab_id, + entry.pane_id, + entry.size, + &entry.title, + )); + mux.add_pane(&pane).expect("failed to add pane to mux"); + pane + } + } + } else { let pane: Rc = Rc::new(ClientPane::new( &inner, + entry.tab_id, entry.pane_id, entry.size, &entry.title, )); - tab.assign_pane(&pane); - mux.add_pane(&pane)?; + log::debug!( + "attaching to remote pane {:?} -> local pane_id {}", + entry, + pane.pane_id() + ); + mux.add_pane(&pane).expect("failed to add pane to mux"); + pane } - }; - } else { - log::info!( - "attaching to remote pane {} in remote window {} {}", - entry.pane_id, - entry.window_id, - entry.title - ); - let pane: Rc = Rc::new(ClientPane::new( - &inner, - entry.pane_id, - entry.size, - &entry.title, - )); - tab.assign_pane(&pane); - mux.add_tab(&tab)?; - } + }); - if let Some(local_window_id) = inner.remote_to_local_window(entry.window_id) { - let mut window = mux - .get_window_mut(local_window_id) - .expect("no such window!?"); - log::info!("already have a local window for this one"); - if window.idx_by_id(tab.tab_id()).is_none() { - window.push(&tab); + if let Some(local_window_id) = inner.remote_to_local_window(remote_window_id) { + let mut window = mux + .get_window_mut(local_window_id) + .expect("no such window!?"); + if window.idx_by_id(tab.tab_id()).is_none() { + window.push(&tab); + } + } else { + let fonts = Rc::new(FontConfiguration::new()); + let local_window_id = mux.new_empty_window(); + inner.record_remote_to_local_window_mapping(remote_window_id, local_window_id); + mux.add_tab_to_window(&tab, local_window_id)?; + + front_end() + .unwrap() + .spawn_new_window(&fonts, &tab, local_window_id) + .unwrap(); } - } else { - log::info!("spawn new local window"); - let fonts = Rc::new(FontConfiguration::new()); - let local_window_id = mux.new_empty_window(); - inner.record_remote_to_local_window_mapping(entry.window_id, local_window_id); - mux.add_tab_to_window(&tab, local_window_id)?; - - front_end() - .unwrap() - .spawn_new_window(&fonts, &tab, local_window_id) - .unwrap(); } } + Ok(()) } fn finish_attach( domain_id: DomainId, client: Client, - tabs: ListTabsResponse, + panes: ListPanesResponse, ) -> anyhow::Result<()> { let mux = Mux::get().unwrap(); let domain = mux @@ -325,7 +337,7 @@ impl ClientDomain { let inner = Arc::new(ClientInner::new(domain_id, client)); *domain.inner.borrow_mut() = Some(Arc::clone(&inner)); - Self::process_tab_list(inner, tabs)?; + Self::process_pane_list(inner, panes)?; Ok(()) } @@ -355,28 +367,32 @@ impl Domain for ClientDomain { let inner = self .inner() .ok_or_else(|| anyhow!("domain is not attached"))?; - let remote_tab_id = { - let result = inner - .client - .spawn(Spawn { - domain_id: inner.remote_domain_id, - window_id: inner.local_to_remote_window(window), - size, - command, - command_dir, - }) - .await?; + let result = inner + .client + .spawn(Spawn { + domain_id: inner.remote_domain_id, + window_id: inner.local_to_remote_window(window), + split: None, + size, + command, + command_dir, + }) + .await?; - inner.record_remote_to_local_window_mapping(result.window_id, window); + inner.record_remote_to_local_window_mapping(result.window_id, window); - result.tab_id - }; - let pane: Rc = Rc::new(ClientPane::new(&inner, remote_tab_id, size, "wezterm")); + let pane: Rc = Rc::new(ClientPane::new( + &inner, + result.tab_id, + result.pane_id, + size, + "wezterm", + )); let tab = Rc::new(Tab::new(&size)); tab.assign_pane(&pane); let mux = Mux::get().unwrap(); - mux.add_tab(&tab)?; + mux.add_tab_and_active_pane(&tab)?; mux.add_tab_to_window(&tab, window)?; Ok(tab) @@ -384,13 +400,63 @@ impl Domain for ClientDomain { async fn split_pane( &self, - _command: Option, - _command_dir: Option, - _tab: TabId, - _pane_index: usize, - _direction: SplitDirection, + command: Option, + command_dir: Option, + tab_id: TabId, + pane_id: PaneId, + direction: SplitDirection, ) -> anyhow::Result> { - anyhow::bail!("spawn_pane not implemented for mux"); + let inner = self + .inner() + .ok_or_else(|| anyhow!("domain is not attached"))?; + + let mux = Mux::get().unwrap(); + + let tab = mux + .get_tab(tab_id) + .ok_or_else(|| anyhow!("tab_id {} is invalid", tab_id))?; + let local_pane = mux + .get_pane(pane_id) + .ok_or_else(|| anyhow!("pane_id {} is invalid", pane_id))?; + let pane = local_pane + .downcast_ref::() + .ok_or_else(|| anyhow!("pane_id {} is not a ClientPane", pane_id))?; + + let result = inner + .client + .spawn(Spawn { + domain_id: inner.remote_domain_id, + window_id: None, + split: Some((pane.remote_tab_id, pane.remote_pane_id, direction)), + size: PtySize::default(), + command, + command_dir, + }) + .await?; + + let pane: Rc = Rc::new(ClientPane::new( + &inner, + result.tab_id, + result.pane_id, + result.size, + "wezterm", + )); + + let pane_index = match tab + .iter_panes() + .iter() + .find(|p| p.pane.pane_id() == pane_id) + { + Some(p) => p.index, + None => anyhow::bail!("invalid pane id {}", pane_id), + }; + + tab.split_and_insert(pane_index, direction, Rc::clone(&pane)) + .ok(); + + mux.add_pane(&pane)?; + + Ok(pane) } async fn attach(&self) -> anyhow::Result<()> { @@ -417,13 +483,13 @@ impl Domain for ClientDomain { client.verify_version_compat(&ui).await?; - ui.output_str("Version check OK! Requesting tab list...\n"); - let tabs = client.list_tabs().await?; + ui.output_str("Version check OK! Requesting pane list...\n"); + let panes = client.list_panes().await?; ui.output_str(&format!( "Server has {} tabs. Attaching to local UI...\n", - tabs.tabs.len() + panes.tabs.len() )); - ClientDomain::finish_attach(domain_id, client, tabs) + ClientDomain::finish_attach(domain_id, client, panes) } }) .await?; diff --git a/src/server/listener/sessionhandler.rs b/src/server/listener/sessionhandler.rs index 032e97374..b4de5490f 100644 --- a/src/server/listener/sessionhandler.rs +++ b/src/server/listener/sessionhandler.rs @@ -193,7 +193,7 @@ impl SessionHandler { match decoded.pdu { Pdu::Ping(Ping {}) => send_response(Ok(Pdu::Pong(Pong {}))), - Pdu::ListTabs(ListTabs {}) => { + Pdu::ListPanes(ListPanes {}) => { spawn_into_main_thread(async move { catch( move || { @@ -202,27 +202,11 @@ impl SessionHandler { for window_id in mux.iter_windows().into_iter() { let window = mux.get_window(window_id).unwrap(); for tab in window.iter() { - if let Some(pane) = tab.get_active_pane() { - let dims = pane.renderer().get_dimensions(); - let working_dir = pane.get_current_working_dir(); - tabs.push(WindowAndTabEntry { - window_id, - tab_id: tab.tab_id(), - pane_id: pane.pane_id(), - title: pane.get_title(), - size: PtySize { - cols: dims.cols as u16, - rows: dims.viewport_rows as u16, - pixel_height: 0, - pixel_width: 0, - }, - working_dir: working_dir.map(Into::into), - }); - } + tabs.push(tab.codec_pane_tree()); } } - log::error!("ListTabs {:#?}", tabs); - Ok(Pdu::ListTabsResponse(ListTabsResponse { tabs })) + log::error!("ListPanes {:#?}", tabs); + Ok(Pdu::ListPanesResponse(ListPanesResponse { tabs })) }, send_response, ) @@ -288,7 +272,35 @@ impl SessionHandler { }); } - Pdu::Resize(Resize { pane_id, size }) => { + Pdu::SetPaneZoomed(SetPaneZoomed { + containing_tab_id, + pane_id, + zoomed, + }) => { + spawn_into_main_thread(async move { + catch( + move || { + let mux = Mux::get().unwrap(); + let pane = mux + .get_pane(pane_id) + .ok_or_else(|| anyhow!("no such pane {}", pane_id))?; + let tab = mux + .get_tab(containing_tab_id) + .ok_or_else(|| anyhow!("no such tab {}", containing_tab_id))?; + tab.set_active_pane(&pane); + tab.set_zoomed(zoomed); + Ok(Pdu::UnitResponse(UnitResponse {})) + }, + send_response, + ) + }); + } + + Pdu::Resize(Resize { + containing_tab_id, + pane_id, + size, + }) => { spawn_into_main_thread(async move { catch( move || { @@ -297,6 +309,10 @@ impl SessionHandler { .get_pane(pane_id) .ok_or_else(|| anyhow!("no such pane {}", pane_id))?; pane.resize(size)?; + let tab = mux + .get_tab(containing_tab_id) + .ok_or_else(|| anyhow!("no such tab {}", containing_tab_id))?; + tab.rebuild_splits_sizes_from_contained_panes(); Ok(Pdu::UnitResponse(UnitResponse {})) }, send_response, @@ -442,7 +458,7 @@ impl SessionHandler { Pdu::Invalid { .. } => send_response(Err(anyhow!("invalid PDU {:?}", decoded.pdu))), Pdu::Pong { .. } - | Pdu::ListTabsResponse { .. } + | Pdu::ListPanesResponse { .. } | Pdu::SetClipboard { .. } | Pdu::SpawnResponse { .. } | Pdu::GetPaneRenderChangesResponse { .. } @@ -498,22 +514,41 @@ async fn domain_spawn(spawn: Spawn, sender: PollableSender) -> anyho .get_domain(spawn.domain_id) .ok_or_else(|| anyhow!("domain {} not found on this server", spawn.domain_id))?; - let window_id = if let Some(window_id) = spawn.window_id { - mux.get_window_mut(window_id) - .ok_or_else(|| anyhow!("window_id {} not found on this server", window_id))?; - window_id + let (pane, tab_id, window_id, size) = if let Some((tab_id, pane_id, direction)) = spawn.split { + let pane = domain + .split_pane(spawn.command, spawn.command_dir, tab_id, pane_id, direction) + .await?; + let window_id = mux + .window_containing_tab(tab_id) + .ok_or_else(|| anyhow!("no window contains tab {}", tab_id))?; + let dims = pane.renderer().get_dimensions(); + let size = PtySize { + cols: dims.cols as u16, + rows: dims.viewport_rows as u16, + pixel_height: 0, + pixel_width: 0, + }; + (pane, tab_id, window_id, size) } else { - mux.new_empty_window() + let window_id = if let Some(window_id) = spawn.window_id { + mux.get_window_mut(window_id) + .ok_or_else(|| anyhow!("window_id {} not found on this server", window_id))?; + window_id + } else { + mux.new_empty_window() + }; + + let tab = domain + .spawn(spawn.size, spawn.command, spawn.command_dir, window_id) + .await?; + + let pane = tab + .get_active_pane() + .ok_or_else(|| anyhow!("missing active pane on tab!?"))?; + + (pane, tab.tab_id(), window_id, tab.get_size()) }; - let tab = domain - .spawn(spawn.size, spawn.command, spawn.command_dir, window_id) - .await?; - - let pane = tab - .get_active_pane() - .ok_or_else(|| anyhow!("missing active pane on tab!?"))?; - let clip: Arc = Arc::new(RemoteClipboard { pane_id: pane.pane_id(), sender, @@ -522,7 +557,8 @@ async fn domain_spawn(spawn: Spawn, sender: PollableSender) -> anyho Ok::(Pdu::SpawnResponse(SpawnResponse { pane_id: pane.pane_id(), - tab_id: tab.tab_id(), + tab_id: tab_id, window_id, + size, })) } diff --git a/src/server/tab/clienttab.rs b/src/server/tab/clienttab.rs index b8a922da3..e254e3d6d 100644 --- a/src/server/tab/clienttab.rs +++ b/src/server/tab/clienttab.rs @@ -1,7 +1,7 @@ use crate::config::configuration; use crate::mux::domain::DomainId; use crate::mux::renderable::{Renderable, RenderableDimensions}; -use crate::mux::tab::{alloc_pane_id, Pane, Pattern, SearchResult, TabId}; +use crate::mux::tab::{alloc_pane_id, Pane, PaneId, Pattern, SearchResult, TabId}; use crate::ratelim::RateLimiter; use crate::server::codec::*; use crate::server::domain::ClientInner; @@ -23,8 +23,9 @@ use wezterm_term::{Clipboard, KeyCode, KeyModifiers, MouseEvent}; pub struct ClientPane { client: Arc, - local_pane_id: TabId, - remote_pane_id: TabId, + local_pane_id: PaneId, + pub remote_pane_id: PaneId, + pub remote_tab_id: TabId, pub renderable: RefCell, writer: RefCell, reader: Pipe, @@ -36,7 +37,8 @@ pub struct ClientPane { impl ClientPane { pub fn new( client: &Arc, - remote_pane_id: TabId, + remote_tab_id: TabId, + remote_pane_id: PaneId, size: PtySize, title: &str, ) -> Self { @@ -78,6 +80,7 @@ impl ClientPane { mouse, remote_pane_id, local_pane_id, + remote_tab_id, renderable: RefCell::new(render), writer: RefCell::new(writer), reader, @@ -171,6 +174,27 @@ impl Pane for ClientPane { self.writer.borrow_mut() } + fn set_zoomed(&self, zoomed: bool) { + let render = self.renderable.borrow(); + let mut inner = render.inner.borrow_mut(); + let client = Arc::clone(&self.client); + let remote_pane_id = self.remote_pane_id; + let remote_tab_id = self.remote_tab_id; + // Invalidate any cached rows on a resize + inner.make_all_stale(); + promise::spawn::spawn(async move { + client + .client + .set_zoomed(SetPaneZoomed { + containing_tab_id: remote_tab_id, + pane_id: remote_pane_id, + zoomed, + }) + .await + }); + inner.update_last_send(); + } + fn resize(&self, size: PtySize) -> anyhow::Result<()> { let render = self.renderable.borrow(); let mut inner = render.inner.borrow_mut(); @@ -187,10 +211,12 @@ impl Pane for ClientPane { let client = Arc::clone(&self.client); let remote_pane_id = self.remote_pane_id; + let remote_tab_id = self.remote_tab_id; promise::spawn::spawn(async move { client .client .resize(Resize { + containing_tab_id: remote_tab_id, pane_id: remote_pane_id, size, }) diff --git a/src/ssh.rs b/src/ssh.rs index 06fe22c94..da1e2b6fe 100644 --- a/src/ssh.rs +++ b/src/ssh.rs @@ -1,7 +1,7 @@ use crate::connui::ConnectionUI; use crate::localtab::LocalPane; use crate::mux::domain::{alloc_domain_id, Domain, DomainId, DomainState}; -use crate::mux::tab::{Pane, SplitDirection, Tab, TabId}; +use crate::mux::tab::{Pane, PaneId, SplitDirection, Tab, TabId}; use crate::mux::window::WindowId; use crate::mux::Mux; use anyhow::{anyhow, bail, Context, Error}; @@ -268,7 +268,7 @@ impl Domain for RemoteSshDomain { let tab = Rc::new(Tab::new(&size)); tab.assign_pane(&pane); - mux.add_tab(&tab)?; + mux.add_tab_and_active_pane(&tab)?; mux.add_tab_to_window(&tab, window)?; Ok(tab) @@ -279,7 +279,7 @@ impl Domain for RemoteSshDomain { _command: Option, _command_dir: Option, _tab: TabId, - _pane_index: usize, + _pane_id: PaneId, _split_direction: SplitDirection, ) -> anyhow::Result> { bail!("spawn_pane not implemented for RemoteSshDomain"); diff --git a/src/termwiztermtab.rs b/src/termwiztermtab.rs index 35c170460..8a3a1f57d 100644 --- a/src/termwiztermtab.rs +++ b/src/termwiztermtab.rs @@ -59,7 +59,7 @@ impl Domain for TermWizTerminalDomain { _command: Option, _command_dir: Option, _tab: TabId, - _pane_index: usize, + _pane_id: PaneId, _split_direction: SplitDirection, ) -> anyhow::Result> { bail!("cannot spawn panes in a TermWizTerminalPane"); @@ -467,7 +467,7 @@ pub async fn run< })); tab.assign_pane(&pane); - mux.add_tab(&tab)?; + mux.add_tab_and_active_pane(&tab)?; mux.add_tab_to_window(&tab, window_id)?; let fontconfig = Rc::new(FontConfiguration::new());