From 4007ccbcd20807b309ec40587f70e67666b07c7e Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 18 Mar 2022 18:14:53 -0700 Subject: [PATCH] track focused pane in the client info wezterm cli spawn, and wezterm cli split-pane can use this information to pick a default for the pane id when invoked from outside of wezterm. refs: https://github.com/wez/wezterm/issues/1531 --- codec/src/lib.rs | 8 ++- mux/src/client.rs | 8 +++ mux/src/lib.rs | 12 ++++ mux/src/pane.rs | 5 ++ wezterm-client/src/client.rs | 1 + wezterm-client/src/domain.rs | 2 + wezterm-client/src/pane/clientpane.rs | 18 +++++ wezterm-gui/src/termwindow/render.rs | 4 ++ wezterm-mux-server-impl/src/sessionhandler.rs | 10 +++ wezterm/src/main.rs | 72 ++++++++++--------- 10 files changed, 105 insertions(+), 35 deletions(-) diff --git a/codec/src/lib.rs b/codec/src/lib.rs index e23efd279..e90cc17f9 100644 --- a/codec/src/lib.rs +++ b/codec/src/lib.rs @@ -405,7 +405,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 = 18; +pub const CODEC_VERSION: usize = 19; // Defines the Pdu enum. // Each struct has an explicit identifying number. @@ -448,6 +448,7 @@ pdu! { GetClientListResponse: 42, SetWindowWorkspace: 43, WindowWorkspaceChanged: 44, + SetFocusedPane: 45, } impl Pdu { @@ -708,6 +709,11 @@ pub struct SetClientId { pub client_id: ClientId, } +#[derive(Deserialize, Serialize, PartialEq, Debug)] +pub struct SetFocusedPane { + pub pane_id: PaneId, +} + #[derive(Deserialize, Serialize, PartialEq, Debug)] pub struct GetClientList; diff --git a/mux/src/client.rs b/mux/src/client.rs index 2f73a8f56..364854915 100644 --- a/mux/src/client.rs +++ b/mux/src/client.rs @@ -1,3 +1,4 @@ +use crate::PaneId; use chrono::serde::ts_seconds; use chrono::{DateTime, Utc}; use serde::*; @@ -47,6 +48,8 @@ pub struct ClientInfo { /// The last time we received input from this client #[serde(with = "ts_seconds")] pub last_input: DateTime, + /// The currently-focused pane + pub focused_pane_id: Option, } impl ClientInfo { @@ -56,10 +59,15 @@ impl ClientInfo { connected_at: Utc::now(), active_workspace: None, last_input: Utc::now(), + focused_pane_id: None, } } pub fn update_last_input(&mut self) { self.last_input = Utc::now(); } + + pub fn update_focused_pane(&mut self, pane_id: PaneId) { + self.focused_pane_id.replace(pane_id); + } } diff --git a/mux/src/lib.rs b/mux/src/lib.rs index 93eb84e55..1a4485d1f 100644 --- a/mux/src/lib.rs +++ b/mux/src/lib.rs @@ -359,6 +359,18 @@ impl Mux { } } + pub fn record_focus_for_current_identity(&self, pane_id: PaneId) { + if let Some(ident) = self.identity.borrow().as_ref() { + self.record_focus_for_client(ident, pane_id); + } + } + + pub fn record_focus_for_client(&self, client_id: &ClientId, pane_id: PaneId) { + if let Some(info) = self.clients.borrow_mut().get_mut(client_id) { + info.update_focused_pane(pane_id); + } + } + pub fn register_client(&self, client_id: Arc) { self.clients .borrow_mut() diff --git a/mux/src/pane.rs b/mux/src/pane.rs index df389e50b..eb296bd2a 100644 --- a/mux/src/pane.rs +++ b/mux/src/pane.rs @@ -343,6 +343,11 @@ pub trait Pane: Downcast { /// Called to advise on whether this tab has focus fn focus_changed(&self, _focused: bool) {} + + /// Called to advise remote mux that this is the active tab + /// for the current identity + fn advise_focus(&self) {} + fn has_unseen_output(&self) -> bool { false } diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs index 2c5ab7df7..80461de3d 100644 --- a/wezterm-client/src/client.rs +++ b/wezterm-client/src/client.rs @@ -1173,4 +1173,5 @@ impl Client { rpc!(set_client_id, SetClientId, UnitResponse); rpc!(list_clients, GetClientList, GetClientListResponse); rpc!(set_window_workspace, SetWindowWorkspace, UnitResponse); + rpc!(set_focused_pane_id, SetFocusedPane, UnitResponse); } diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs index 4ea0c0eb4..73c6eb967 100644 --- a/wezterm-client/src/domain.rs +++ b/wezterm-client/src/domain.rs @@ -26,6 +26,7 @@ pub struct ClientInner { remote_to_local_window: Mutex>, remote_to_local_tab: Mutex>, remote_to_local_pane: Mutex>, + pub focused_remote_pane_id: Mutex>, } impl ClientInner { @@ -179,6 +180,7 @@ impl ClientInner { remote_to_local_window: Mutex::new(HashMap::new()), remote_to_local_tab: Mutex::new(HashMap::new()), remote_to_local_pane: Mutex::new(HashMap::new()), + focused_remote_pane_id: Mutex::new(None), } } } diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs index b5495573b..2e6b97a8b 100644 --- a/wezterm-client/src/pane/clientpane.rs +++ b/wezterm-client/src/pane/clientpane.rs @@ -415,6 +415,24 @@ impl Pane for ClientPane { self.renderable.borrow().inner.borrow().working_dir.clone() } + fn advise_focus(&self) { + let mut focused_pane = self.client.focused_remote_pane_id.lock().unwrap(); + if *focused_pane != Some(self.remote_pane_id) { + focused_pane.replace(self.remote_pane_id); + let client = Arc::clone(&self.client); + let remote_pane_id = self.remote_pane_id; + promise::spawn::spawn(async move { + client + .client + .set_focused_pane_id(SetFocusedPane { + pane_id: remote_pane_id, + }) + .await + }) + .detach(); + } + } + fn can_close_without_prompting(&self, reason: CloseReason) -> bool { match reason { CloseReason::Window => true, diff --git a/wezterm-gui/src/termwindow/render.rs b/wezterm-gui/src/termwindow/render.rs index 3d331fdc3..499642d40 100644 --- a/wezterm-gui/src/termwindow/render.rs +++ b/wezterm-gui/src/termwindow/render.rs @@ -1538,6 +1538,10 @@ impl super::TermWindow { for pos in panes { if pos.is_active { self.update_text_cursor(&pos.pane); + pos.pane.advise_focus(); + mux::Mux::get() + .expect("called on mux thread") + .record_focus_for_current_identity(pos.pane.pane_id()); } self.paint_pane_opengl(&pos, num_panes)?; } diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs index cb9e34d0c..8fea3c2dc 100644 --- a/wezterm-mux-server-impl/src/sessionhandler.rs +++ b/wezterm-mux-server-impl/src/sessionhandler.rs @@ -303,6 +303,16 @@ impl SessionHandler { .detach(); send_response(Ok(Pdu::UnitResponse(UnitResponse {}))) } + Pdu::SetFocusedPane(SetFocusedPane { pane_id }) => { + let client_id = self.client_id.clone(); + spawn_into_main_thread(async move { + let mux = Mux::get().unwrap(); + let _identity = mux.with_identity(client_id); + mux.record_focus_for_current_identity(pane_id); + }) + .detach(); + send_response(Ok(Pdu::UnitResponse(UnitResponse {}))) + } Pdu::GetClientList(GetClientList) => { spawn_into_main_thread(async move { catch( diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs index f3127ccb6..6dde30d54 100644 --- a/wezterm/src/main.rs +++ b/wezterm/src/main.rs @@ -409,6 +409,33 @@ fn delegate_to_gui(saver: UmaskSaver) -> anyhow::Result<()> { } } +async fn resolve_pane_id(client: &Client, pane_id: Option) -> anyhow::Result { + let pane_id: PaneId = match pane_id { + Some(p) => p, + None => { + if let Ok(pane) = std::env::var("WEZTERM_PANE") { + pane.parse()? + } else { + let mut clients = client.list_clients(codec::GetClientList).await?.clients; + clients.retain(|client| client.focused_pane_id.is_some()); + clients.sort_by(|a, b| b.last_input.cmp(&a.last_input)); + if clients.is_empty() { + anyhow::bail!( + "--pane-id was not specified and $WEZTERM_PANE + is not set in the environment, and I couldn't + determine which pane was currently focused" + ); + } + + clients[0] + .focused_pane_id + .expect("to have filtered out above") + } + } + }; + Ok(pane_id) +} + async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow::Result<()> { let mut ui = mux::connui::ConnectionUI::new_headless(); let initial = true; @@ -450,6 +477,10 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: name: "WORKSPACE".to_string(), alignment: Alignment::Left, }, + Column { + name: "FOCUS".to_string(), + alignment: Alignment::Right, + }, ]; let mut data = vec![]; let clients = client.list_clients(codec::GetClientList).await?; @@ -473,6 +504,9 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: duration_string(connected), duration_string(idle), info.active_workspace.as_deref().unwrap_or("").to_string(), + info.focused_pane_id + .map(|id| id.to_string()) + .unwrap_or_else(String::new), ]); } @@ -547,17 +581,7 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: prog, horizontal, } => { - let pane_id: PaneId = match pane_id { - Some(p) => p, - None => std::env::var("WEZTERM_PANE") - .map_err(|_| { - anyhow!( - "--pane-id was not specified and $WEZTERM_PANE - is not set in the environment" - ) - })? - .parse()?, - }; + let pane_id = resolve_pane_id(&client, pane_id).await?; let spawned = client .split_pane(codec::SplitPane { @@ -582,17 +606,8 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: println!("{}", spawned.pane_id); } CliSubCommand::SendText { pane_id, text } => { - let pane_id: PaneId = match pane_id { - Some(p) => p, - None => std::env::var("WEZTERM_PANE") - .map_err(|_| { - anyhow!( - "--pane-id was not specified and $WEZTERM_PANE \ - is not set in the environment." - ) - })? - .parse()?, - }; + let pane_id = resolve_pane_id(&client, pane_id).await?; + let data = match text { Some(text) => text, None => { @@ -623,18 +638,7 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: match window_id { Some(w) => Some(w), None => { - let pane_id: PaneId = match pane_id { - Some(p) => p, - None => std::env::var("WEZTERM_PANE") - .map_err(|_| { - anyhow!( - "--pane-id was not specified and $WEZTERM_PANE \ - is not set in the environment. \ - Consider using --new-window?" - ) - })? - .parse()?, - }; + let pane_id = resolve_pane_id(&client, pane_id).await?; let panes = client.list_panes().await?; let mut window_id = None;