From 8f44dc46d9e9b0f0c7b75e31df6bc2da2e4db5a0 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 8 Jul 2022 18:44:19 -0700 Subject: [PATCH] exec_domains: allow async callbacks. can now also set label for launcher The fixup callback can now by async, which makes it possible to use other async functions in the callback. There is an additional parameter to wezterm.exec_domain that allows setting the label that is shown in the launcher menu. It accepts either a string value or an async callback function that can be used to compute the label dynamically. --- config/src/exec_domain.rs | 14 +++++-- config/src/lua.rs | 57 ++++++++++++++++++++++++++--- mux/src/domain.rs | 55 ++++++++++++++++++++++------ wezterm-client/src/domain.rs | 4 +- wezterm-gui/src/overlay/launcher.rs | 37 +++++++++---------- wezterm-gui/src/termwindow/mod.rs | 46 +++++++++++++++-------- 6 files changed, 156 insertions(+), 57 deletions(-) diff --git a/config/src/exec_domain.rs b/config/src/exec_domain.rs index 2092a2c6a..081b17581 100644 --- a/config/src/exec_domain.rs +++ b/config/src/exec_domain.rs @@ -1,9 +1,17 @@ use luahelper::impl_lua_conversion_dynamic; -use wezterm_dynamic::{FromDynamic, ToDynamic}; +use wezterm_dynamic::{FromDynamic, ToDynamic, Value}; -#[derive(Default, Debug, Clone, FromDynamic, ToDynamic)] +#[derive(Debug, Clone, FromDynamic, ToDynamic)] +pub enum ValueOrFunc { + Value(Value), + Func(String), +} +impl_lua_conversion_dynamic!(ValueOrFunc); + +#[derive(Debug, Clone, FromDynamic, ToDynamic)] pub struct ExecDomain { pub name: String, - pub event_name: String, + pub fixup_command: String, + pub label: Option, } impl_lua_conversion_dynamic!(ExecDomain); diff --git a/config/src/lua.rs b/config/src/lua.rs index 0626733c2..7f7bfd2be 100644 --- a/config/src/lua.rs +++ b/config/src/lua.rs @@ -1,11 +1,11 @@ -use crate::exec_domain::ExecDomain; +use crate::exec_domain::{ExecDomain, ValueOrFunc}; use crate::keyassignment::KeyAssignment; use crate::{ FontAttributes, FontStretch, FontStyle, FontWeight, FreeTypeLoadTarget, Gradient, RgbaColor, TextStyle, }; use anyhow::anyhow; -use luahelper::from_lua_value_dynamic; +use luahelper::{from_lua_value_dynamic, lua_value_to_dynamic}; use mlua::{FromLua, Lua, Table, ToLuaMulti, Value, Variadic}; use ordered_float::NotNan; use std::convert::TryFrom; @@ -481,11 +481,35 @@ fn action_callback<'lua>(lua: &'lua Lua, callback: mlua::Function) -> mlua::Resu fn exec_domain<'lua>( lua: &'lua Lua, - (name, callback): (String, mlua::Function), + (name, fixup_command, label): (String, mlua::Function, Option), ) -> mlua::Result { - let event_name = format!("exec-domain-{name}"); - register_event(lua, (event_name.clone(), callback))?; - Ok(ExecDomain { name, event_name }) + let fixup_command = { + let event_name = format!("exec-domain-{name}"); + register_event(lua, (event_name.clone(), fixup_command))?; + event_name + }; + + let label = match label { + Some(Value::Function(callback)) => { + let event_name = format!("exec-domain-{name}-label"); + register_event(lua, (event_name.clone(), callback))?; + Some(ValueOrFunc::Func(event_name)) + } + Some(Value::String(value)) => Some(ValueOrFunc::Value(lua_value_to_dynamic( + Value::String(value), + )?)), + Some(_) => { + return Err(mlua::Error::external( + "label function parameter must be either a string or a lua function", + )) + } + None => None, + }; + Ok(ExecDomain { + name, + fixup_command, + label, + }) } fn split_by_newlines<'lua>(_: &'lua Lua, text: String) -> mlua::Result> { @@ -605,6 +629,27 @@ where } } +pub async fn emit_async_callback<'lua, A>( + lua: &'lua Lua, + (name, args): (String, A), +) -> mlua::Result> +where + A: ToLuaMulti<'lua>, +{ + let decorated_name = format!("wezterm-event-{}", name); + let tbl: mlua::Value = lua.named_registry_value(&decorated_name)?; + match tbl { + mlua::Value::Table(tbl) => { + for func in tbl.sequence_values::() { + let func = func?; + return func.call_async(args).await; + } + Ok(mlua::Value::Nil) + } + _ => Ok(mlua::Value::Nil), + } +} + /// Ungh: https://github.com/microsoft/WSL/issues/4456 fn utf16_to_utf8<'lua>(_: &'lua Lua, text: mlua::String) -> mlua::Result { let bytes = text.as_bytes(); diff --git a/mux/src/domain.rs b/mux/src/domain.rs index a092127c3..52109205a 100644 --- a/mux/src/domain.rs +++ b/mux/src/domain.rs @@ -13,7 +13,7 @@ use crate::Mux; use anyhow::{bail, Context, Error}; use async_trait::async_trait; use config::keyassignment::{SpawnCommand, SpawnTabDomain}; -use config::{configuration, ExecDomain, WslDomain}; +use config::{configuration, ExecDomain, ValueOrFunc, WslDomain}; use downcast_rs::{impl_downcast, Downcast}; use portable_pty::{native_pty_system, CommandBuilder, PtySystem}; use std::collections::HashMap; @@ -150,8 +150,8 @@ pub trait Domain: Downcast { fn domain_name(&self) -> &str; /// Returns a label describing the domain. - fn domain_label(&self) -> &str { - self.domain_name() + async fn domain_label(&self) -> String { + self.domain_name().to_string() } /// Re-attach to any tabs that might be pre-existing in this domain @@ -218,7 +218,7 @@ impl LocalDomain { .is_some() } - fn fixup_command(&self, cmd: &mut CommandBuilder) -> anyhow::Result<()> { + async fn fixup_command(&self, cmd: &mut CommandBuilder) -> anyhow::Result<()> { if let Some(wsl) = &self.wsl { let mut args: Vec = cmd.get_argv().clone(); @@ -286,12 +286,13 @@ impl LocalDomain { cwd, }; - let spawn_command = config::run_immediate_with_lua_config(|lua| { + let spawn_command = config::with_lua_config_on_main_thread(|lua| async { let lua = lua.ok_or_else(|| anyhow::anyhow!("missing lua context"))?; - let value = config::lua::emit_sync_callback( + let value = config::lua::emit_async_callback( &*lua, - (ed.event_name.clone(), (spawn_command.clone())), - )?; + (ed.fixup_command.clone(), (spawn_command.clone())), + ) + .await?; let cmd: SpawnCommand = luahelper::from_lua_value_dynamic(value).with_context(|| { format!( @@ -301,6 +302,7 @@ impl LocalDomain { })?; Ok(cmd) }) + .await .with_context(|| format!("calling ExecDomain {} function", ed.name))?; // Reinterpret the SpawnCommand into the builder @@ -339,7 +341,7 @@ impl LocalDomain { Ok(()) } - fn build_command( + async fn build_command( &self, command: Option, command_dir: Option, @@ -365,7 +367,7 @@ impl LocalDomain { if let Some(dir) = command_dir { cmd.cwd(dir); } - self.fixup_command(&mut cmd)?; + self.fixup_command(&mut cmd).await?; Ok(cmd) } } @@ -378,7 +380,7 @@ impl Domain for LocalDomain { command: Option, command_dir: Option, ) -> anyhow::Result> { - let mut cmd = self.build_command(command, command_dir)?; + let mut cmd = self.build_command(command, command_dir).await?; let pair = self .pty_system .openpty(crate::terminal_size_to_pty_size(size)?)?; @@ -436,6 +438,37 @@ impl Domain for LocalDomain { &self.name } + async fn domain_label(&self) -> String { + if let Some(ed) = &self.exec_domain { + match &ed.label { + Some(ValueOrFunc::Value(wezterm_dynamic::Value::String(s))) => s.to_string(), + Some(ValueOrFunc::Func(label_func)) => { + let label = config::with_lua_config_on_main_thread(|lua| async { + let lua = lua.ok_or_else(|| anyhow::anyhow!("missing lua context"))?; + let value = config::lua::emit_async_callback( + &*lua, + (label_func.clone(), (self.name.clone())), + ) + .await?; + let label: String = + luahelper::from_lua_value_dynamic(value).with_context(|| { + format!( + "interpreting SpawnCommand result from ExecDomain {}", + ed.name + ) + })?; + Ok(label) + }) + .await; + label.unwrap_or_else(|_| self.name.to_string()) + } + _ => self.name.to_string(), + } + } else { + self.name.to_string() + } + } + async fn attach(&self, _window_id: Option) -> anyhow::Result<()> { Ok(()) } diff --git a/wezterm-client/src/domain.rs b/wezterm-client/src/domain.rs index 8945d8a28..a72881ef6 100644 --- a/wezterm-client/src/domain.rs +++ b/wezterm-client/src/domain.rs @@ -477,8 +477,8 @@ impl Domain for ClientDomain { self.config.name() } - fn domain_label(&self) -> &str { - &self.label + async fn domain_label(&self) -> String { + self.label.to_string() } async fn spawn_pane( diff --git a/wezterm-gui/src/overlay/launcher.rs b/wezterm-gui/src/overlay/launcher.rs index a7b3007ea..eb5800880 100644 --- a/wezterm-gui/src/overlay/launcher.rs +++ b/wezterm-gui/src/overlay/launcher.rs @@ -62,7 +62,7 @@ pub struct LauncherArgs { impl LauncherArgs { /// Must be called on the Mux thread! - pub fn new( + pub async fn new( title: &str, flags: LauncherFlags, mux_window_id: WindowId, @@ -120,24 +120,23 @@ impl LauncherArgs { a.domain_id().cmp(&b.domain_id()) }); domains.retain(|dom| dom.spawnable()); - domains - .iter() - .map(|dom| { - let name = dom.domain_name(); - let label = dom.domain_label(); - let label = if name == label || label == "" { - format!("domain `{}`", name) - } else { - format!("domain `{}` - {}", name, label) - }; - LauncherDomainEntry { - domain_id: dom.domain_id(), - name: name.to_string(), - state: dom.state(), - label, - } - }) - .collect() + let mut d = vec![]; + for dom in domains.into_iter() { + let name = dom.domain_name(); + let label = dom.domain_label().await; + let label = if name == label || label == "" { + format!("domain `{}`", name) + } else { + format!("domain `{}` - {}", name, label) + }; + d.push(LauncherDomainEntry { + domain_id: dom.domain_id(), + name: name.to_string(), + state: dom.state(), + label, + }); + } + d } else { vec![] }; diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index b035781e5..61c5e6ab4 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -1802,6 +1802,9 @@ impl TermWindow { } fn show_launcher_impl(&mut self, title: &str, flags: LauncherFlags) { + let mux_window_id = self.mux_window_id; + let window = self.window.as_ref().unwrap().clone(); + let mux = Mux::get().unwrap(); let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, @@ -1813,29 +1816,40 @@ impl TermWindow { None => return, }; - let mux_window_id = self.mux_window_id; - - let window = self.window.as_ref().unwrap().clone(); - let domain_id_of_current_pane = tab .get_active_pane() .expect("tab has no panes!") .domain_id(); let pane_id = pane.pane_id(); + let tab_id = tab.tab_id(); + let title = title.to_string(); - let args = LauncherArgs::new( - title, - flags, - mux_window_id, - pane_id, - domain_id_of_current_pane, - ); + promise::spawn::spawn(async move { + let args = LauncherArgs::new( + &title, + flags, + mux_window_id, + pane_id, + domain_id_of_current_pane, + ) + .await; - let (overlay, future) = start_overlay(self, &tab, move |_tab_id, term| { - launcher(args, term, window) - }); - self.assign_overlay(tab.tab_id(), overlay); - promise::spawn::spawn(future).detach(); + let win = window.clone(); + win.notify(TermWindowNotif::Apply(Box::new(move |term_window| { + let mux = Mux::get().unwrap(); + if let Some(tab) = mux.get_tab(tab_id) { + let window = window.clone(); + let (overlay, future) = + start_overlay(term_window, &tab, move |_tab_id, term| { + launcher(args, term, window) + }); + + term_window.assign_overlay(tab_id, overlay); + promise::spawn::spawn(future).detach(); + } + }))); + }) + .detach(); } /// Returns the Prompt semantic zones