From 478cc59be3269376a2ff0ca48af9eb74ffbfdc01 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 24 Nov 2022 10:30:08 -0700 Subject: [PATCH] mux: Mux is now Send+Sync --- lua-api-crates/mux/src/lib.rs | 4 +- lua-api-crates/mux/src/pane.rs | 2 +- lua-api-crates/mux/src/tab.rs | 2 +- lua-api-crates/mux/src/window.rs | 7 +- mux/src/lib.rs | 30 ++---- mux/src/localpane.rs | 37 ++++---- wezterm-gui/src/frontend.rs | 150 +++++++++++++++--------------- wezterm-gui/src/main.rs | 8 +- wezterm-gui/src/termwindow/mod.rs | 8 +- wezterm-mux-server/src/main.rs | 2 +- wezterm/src/main.rs | 4 +- 11 files changed, 128 insertions(+), 126 deletions(-) diff --git a/lua-api-crates/mux/src/lib.rs b/lua-api-crates/mux/src/lib.rs index 1f74c99ec..a96ce298b 100644 --- a/lua-api-crates/mux/src/lib.rs +++ b/lua-api-crates/mux/src/lib.rs @@ -9,7 +9,7 @@ use mux::window::{Window, WindowId}; use mux::Mux; use portable_pty::CommandBuilder; use std::collections::HashMap; -use std::rc::Rc; +use std::sync::Arc; use wezterm_dynamic::{FromDynamic, ToDynamic}; use wezterm_term::TerminalSize; @@ -21,7 +21,7 @@ pub use pane::MuxPane; pub use tab::MuxTab; pub use window::MuxWindow; -fn get_mux() -> mlua::Result> { +fn get_mux() -> mlua::Result> { Mux::get() .ok_or_else(|| mlua::Error::external("cannot get Mux: not running on the mux thread?")) } diff --git a/lua-api-crates/mux/src/pane.rs b/lua-api-crates/mux/src/pane.rs index c878d5ca4..58b1f3e1e 100644 --- a/lua-api-crates/mux/src/pane.rs +++ b/lua-api-crates/mux/src/pane.rs @@ -6,7 +6,7 @@ use std::sync::Arc; pub struct MuxPane(pub PaneId); impl MuxPane { - pub fn resolve<'a>(&self, mux: &'a Rc) -> mlua::Result> { + pub fn resolve<'a>(&self, mux: &'a Arc) -> mlua::Result> { mux.get_pane(self.0) .ok_or_else(|| mlua::Error::external(format!("pane id {} not found in mux", self.0))) } diff --git a/lua-api-crates/mux/src/tab.rs b/lua-api-crates/mux/src/tab.rs index ae42b6a3d..2ba74aec0 100644 --- a/lua-api-crates/mux/src/tab.rs +++ b/lua-api-crates/mux/src/tab.rs @@ -5,7 +5,7 @@ use std::sync::Arc; pub struct MuxTab(pub TabId); impl MuxTab { - pub fn resolve<'a>(&self, mux: &'a Rc) -> mlua::Result> { + pub fn resolve<'a>(&self, mux: &'a Arc) -> mlua::Result> { mux.get_tab(self.0) .ok_or_else(|| mlua::Error::external(format!("tab id {} not found in mux", self.0))) } diff --git a/lua-api-crates/mux/src/window.rs b/lua-api-crates/mux/src/window.rs index 581e43704..29c399b91 100644 --- a/lua-api-crates/mux/src/window.rs +++ b/lua-api-crates/mux/src/window.rs @@ -5,14 +5,17 @@ use parking_lot::{MappedRwLockReadGuard, MappedRwLockWriteGuard}; pub struct MuxWindow(pub WindowId); impl MuxWindow { - pub fn resolve<'a>(&self, mux: &'a Rc) -> mlua::Result> { + pub fn resolve<'a>( + &self, + mux: &'a Arc, + ) -> mlua::Result> { mux.get_window(self.0) .ok_or_else(|| mlua::Error::external(format!("window id {} not found in mux", self.0))) } pub fn resolve_mut<'a>( &self, - mux: &'a Rc, + mux: &'a Arc, ) -> mlua::Result> { mux.get_window_mut(self.0) .ok_or_else(|| mlua::Error::external(format!("window id {} not found in mux", self.0))) diff --git a/mux/src/lib.rs b/mux/src/lib.rs index 066dd7924..2bb88ed8f 100644 --- a/mux/src/lib.rs +++ b/mux/src/lib.rs @@ -12,15 +12,13 @@ use libc::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF}; use log::error; use metrics::histogram; use parking_lot::{ - MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, + MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard, }; use percent_encoding::percent_decode_str; use portable_pty::{CommandBuilder, ExitStatus, PtySize}; -use std::cell::RefCell; use std::collections::HashMap; use std::convert::TryInto; use std::io::{Read, Write}; -use std::rc::Rc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; @@ -90,7 +88,7 @@ pub struct Mux { default_domain: RwLock>>, domains: RwLock>>, domains_by_name: RwLock>>, - subscribers: RwLock bool>>>, + subscribers: RwLock bool + Send + Sync>>>, banner: RwLock>, clients: RwLock>, identity: RwLock>>, @@ -312,8 +310,8 @@ fn read_from_pane_pty( dead.store(true, Ordering::Relaxed); } -thread_local! { - static MUX: RefCell>> = RefCell::new(None); +lazy_static::lazy_static! { + static ref MUX: Mutex>> = Mutex::new(None); } pub struct MuxWindowBuilder { @@ -543,7 +541,7 @@ impl Mux { pub fn subscribe(&self, subscriber: F) where - F: Fn(MuxNotification) -> bool + 'static, + F: Fn(MuxNotification) -> bool + 'static + Send + Sync, { let sub_id = SUB_ID.fetch_add(1, Ordering::Relaxed); self.subscribers @@ -597,24 +595,16 @@ impl Mux { .insert(domain.domain_name().to_string(), Arc::clone(domain)); } - pub fn set_mux(mux: &Rc) { - MUX.with(|m| { - *m.borrow_mut() = Some(Rc::clone(mux)); - }); + pub fn set_mux(mux: &Arc) { + MUX.lock().replace(Arc::clone(mux)); } pub fn shutdown() { - MUX.with(|m| drop(m.borrow_mut().take())); + MUX.lock().take(); } - pub fn get() -> Option> { - let mut res = None; - MUX.with(|m| { - if let Some(mux) = &*m.borrow() { - res = Some(Rc::clone(mux)); - } - }); - res + pub fn get() -> Option> { + MUX.lock().as_ref().map(Arc::clone) } pub fn get_pane(&self, pane_id: PaneId) -> Option> { diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs index 90f360644..dd34bf859 100644 --- a/mux/src/localpane.rs +++ b/mux/src/localpane.rs @@ -770,30 +770,31 @@ struct LocalPaneNotifHandler { impl AlertHandler for LocalPaneNotifHandler { fn alert(&mut self, alert: Alert) { - if let Some(mux) = Mux::get() { - match &alert { - Alert::WindowTitleChanged(title) => { - if let Some((_domain, window_id, _tab_id)) = mux.resolve_pane_id(self.pane_id) { - if let Some(mut window) = mux.get_window_mut(window_id) { - window.set_title(title); + let pane_id = self.pane_id; + promise::spawn::spawn_into_main_thread(async move { + if let Some(mux) = Mux::get() { + match &alert { + Alert::WindowTitleChanged(title) => { + if let Some((_domain, window_id, _tab_id)) = mux.resolve_pane_id(pane_id) { + if let Some(mut window) = mux.get_window_mut(window_id) { + window.set_title(title); + } } } - } - Alert::TabTitleChanged(title) => { - if let Some((_domain, _window_id, tab_id)) = mux.resolve_pane_id(self.pane_id) { - if let Some(tab) = mux.get_tab(tab_id) { - tab.set_title(title.as_deref().unwrap_or("")); + Alert::TabTitleChanged(title) => { + if let Some((_domain, _window_id, tab_id)) = mux.resolve_pane_id(pane_id) { + if let Some(tab) = mux.get_tab(tab_id) { + tab.set_title(title.as_deref().unwrap_or("")); + } } } + _ => {} } - _ => {} - } - mux.notify(MuxNotification::Alert { - pane_id: self.pane_id, - alert, - }); - } + mux.notify(MuxNotification::Alert { pane_id, alert }); + } + }) + .detach(); } } diff --git a/wezterm-gui/src/frontend.rs b/wezterm-gui/src/frontend.rs index 1b78f2c07..8d16df6ca 100644 --- a/wezterm-gui/src/frontend.rs +++ b/wezterm-gui/src/frontend.rs @@ -45,82 +45,85 @@ impl GuiFrontEnd { client_id: client_id.clone(), }); - let fe = Rc::downgrade(&front_end); mux.subscribe(move |n| { - if let Some(fe) = fe.upgrade() { - match n { - MuxNotification::WindowWorkspaceChanged(_) - | MuxNotification::ActiveWorkspaceChanged(_) - | MuxNotification::WindowCreated(_) - | MuxNotification::WindowRemoved(_) => { - promise::spawn::spawn(async move { - let fe = crate::frontend::front_end(); - if !fe.is_switching_workspace() { - fe.reconcile_workspace(); - } - }) - .detach(); - } - MuxNotification::TabAddedToWindow { .. } => {} - MuxNotification::PaneRemoved(_) => {} - MuxNotification::WindowInvalidated(_) => {} - MuxNotification::PaneOutput(_) => {} - MuxNotification::PaneAdded(_) => {} - MuxNotification::Alert { - pane_id: _, - alert: - Alert::ToastNotification { - title, - body, - focus: _, - }, - } => { - let message = if title.is_none() { "" } else { &body }; - let title = title.as_ref().unwrap_or(&body); - // FIXME: if notification.focus is true, we should do - // something here to arrange to focus pane_id when the - // notification is clicked - persistent_toast_notification(title, message); - } - MuxNotification::Alert { - pane_id: _, - alert: Alert::Bell, - } => { - // Handled via TermWindowNotif; NOP it here. - } - MuxNotification::Alert { - pane_id: _, - alert: - Alert::OutputSinceFocusLost - | Alert::PaletteChanged - | Alert::CurrentWorkingDirectoryChanged - | Alert::WindowTitleChanged(_) - | Alert::TabTitleChanged(_) - | Alert::IconTitleChanged(_) - | Alert::SetUserVar { .. }, - } => {} - MuxNotification::Empty => { + match n { + MuxNotification::WindowWorkspaceChanged(_) + | MuxNotification::ActiveWorkspaceChanged(_) + | MuxNotification::WindowCreated(_) + | MuxNotification::WindowRemoved(_) => { + promise::spawn::spawn_into_main_thread(async move { + let fe = crate::frontend::front_end(); + if !fe.is_switching_workspace() { + fe.reconcile_workspace(); + } + }) + .detach(); + } + MuxNotification::TabAddedToWindow { .. } => {} + MuxNotification::PaneRemoved(_) => {} + MuxNotification::WindowInvalidated(_) => {} + MuxNotification::PaneOutput(_) => {} + MuxNotification::PaneAdded(_) => {} + MuxNotification::Alert { + pane_id: _, + alert: + Alert::ToastNotification { + title, + body, + focus: _, + }, + } => { + let message = if title.is_none() { "" } else { &body }; + let title = title.as_ref().unwrap_or(&body); + // FIXME: if notification.focus is true, we should do + // something here to arrange to focus pane_id when the + // notification is clicked + persistent_toast_notification(title, message); + } + MuxNotification::Alert { + pane_id: _, + alert: Alert::Bell, + } => { + // Handled via TermWindowNotif; NOP it here. + } + MuxNotification::Alert { + pane_id: _, + alert: + Alert::OutputSinceFocusLost + | Alert::PaletteChanged + | Alert::CurrentWorkingDirectoryChanged + | Alert::WindowTitleChanged(_) + | Alert::TabTitleChanged(_) + | Alert::IconTitleChanged(_) + | Alert::SetUserVar { .. }, + } => {} + MuxNotification::Empty => { + promise::spawn::spawn_into_main_thread(async move { if mux::activity::Activity::count() == 0 { log::trace!("Mux is now empty, terminate gui"); Connection::get().unwrap().terminate_message_loop(); } - } - MuxNotification::SaveToDownloads { name, data } => { - if !config::configuration().allow_download_protocols { - log::error!( - "Ignoring download request for {:?}, \ + }) + .detach(); + } + MuxNotification::SaveToDownloads { name, data } => { + if !config::configuration().allow_download_protocols { + log::error!( + "Ignoring download request for {:?}, \ as allow_download_protocols=false", - name - ); - } else if let Err(err) = crate::download::save_to_downloads(name, &*data) { - log::error!("save_to_downloads: {:#}", err); - } + name + ); + } else if let Err(err) = crate::download::save_to_downloads(name, &*data) { + log::error!("save_to_downloads: {:#}", err); } - MuxNotification::AssignClipboard { - pane_id, - selection, - clipboard, - } => { + } + MuxNotification::AssignClipboard { + pane_id, + selection, + clipboard, + } => { + promise::spawn::spawn_into_main_thread(async move { + let fe = crate::frontend::front_end(); log::trace!( "set clipboard in pane {} {:?} {:?}", pane_id, @@ -139,13 +142,12 @@ impl GuiFrontEnd { ); } else { log::error!("Cannot assign clipboard as there are no windows"); - } - } + }; + }) + .detach(); } - true - } else { - false } + true }); // Re-evaluate the config so that folks that are using // `wezterm.gui.get_appearance()` can have that take effect diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs index d849702ee..84a02f8ad 100644 --- a/wezterm-gui/src/main.rs +++ b/wezterm-gui/src/main.rs @@ -491,7 +491,7 @@ enum Publish { } impl Publish { - pub fn resolve(mux: &Rc, config: &ConfigHandle, always_new_process: bool) -> Self { + pub fn resolve(mux: &Arc, config: &ConfigHandle, always_new_process: bool) -> Self { if mux.default_domain().domain_name() != config.default_domain.as_deref().unwrap_or("local") { return Self::NoConnectNoPublish; @@ -636,8 +636,8 @@ fn setup_mux( config: &ConfigHandle, default_domain_name: Option<&str>, default_workspace_name: Option<&str>, -) -> anyhow::Result> { - let mux = Rc::new(mux::Mux::new(Some(local_domain.clone()))); +) -> anyhow::Result> { + let mux = Arc::new(mux::Mux::new(Some(local_domain.clone()))); Mux::set_mux(&mux); let client_id = Arc::new(mux::client::ClientId::new()); mux.register_client(client_id.clone()); @@ -671,7 +671,7 @@ fn build_initial_mux( config: &ConfigHandle, default_domain_name: Option<&str>, default_workspace_name: Option<&str>, -) -> anyhow::Result> { +) -> anyhow::Result> { let domain: Arc = Arc::new(LocalDomain::new("local")?); setup_mux(domain, config, default_domain_name, default_workspace_name) } diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 5d3c9844c..656a6c345 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -1346,7 +1346,13 @@ impl TermWindow { let dead = Arc::new(AtomicBool::new(false)); mux.subscribe(move |n| { let mux_window_id = *mux_window_id.lock().unwrap(); - Self::mux_pane_output_event_callback(n, &window, mux_window_id, &dead) + let window = window.clone(); + let dead = dead.clone(); + promise::spawn::spawn_into_main_thread(async move { + Self::mux_pane_output_event_callback(n, &window, mux_window_id, &dead) + }) + .detach(); + true }); } diff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rs index 179f5c4e5..d298d3946 100644 --- a/wezterm-mux-server/src/main.rs +++ b/wezterm-mux-server/src/main.rs @@ -176,7 +176,7 @@ fn run() -> anyhow::Result<()> { }; let domain: Arc = Arc::new(LocalDomain::new("local")?); - let mux = Rc::new(mux::Mux::new(Some(domain.clone()))); + let mux = Arc::new(mux::Mux::new(Some(domain.clone()))); Mux::set_mux(&mux); let executor = promise::spawn::SimpleExecutor::new(); diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs index 84ba2a91c..320c03bfb 100644 --- a/wezterm/src/main.rs +++ b/wezterm/src/main.rs @@ -14,7 +14,7 @@ use portable_pty::cmdbuilder::CommandBuilder; use serde::Serializer as _; use std::ffi::OsString; use std::io::{Read, Write}; -use std::rc::Rc; +use std::sync::Arc; use tabout::{tabulate_output, Alignment, Column}; use umask::UmaskSaver; use wezterm_client::client::{unix_connect_with_retry, Client}; @@ -1152,7 +1152,7 @@ async fn run_cli_async(config: config::ConfigHandle, cli: CliCommand) -> anyhow: // ourselves into basically netcat. drop(client); - let mux = Rc::new(mux::Mux::new(None)); + let mux = Arc::new(mux::Mux::new(None)); Mux::set_mux(&mux); let unix_dom = config.unix_domains.first().unwrap(); let target = unix_dom.target();