diff --git a/wezterm-gui/src/overlay/copy.rs b/wezterm-gui/src/overlay/copy.rs index a8e1a0d32..e63fa32b3 100644 --- a/wezterm-gui/src/overlay/copy.rs +++ b/wezterm-gui/src/overlay/copy.rs @@ -1,5 +1,5 @@ use crate::selection::{SelectionCoordinate, SelectionRange}; -use crate::termwindow::TermWindow; +use crate::termwindow::{TermWindow, TermWindowNotif}; use config::keyassignment::ScrollbackEraseMode; use mux::domain::DomainId; use mux::pane::{Pane, PaneId}; @@ -101,15 +101,14 @@ impl CopyRenderable { fn adjust_selection(&self, start: SelectionCoordinate, range: SelectionRange) { let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, window| { - if let Some(term_window) = term_window.downcast_mut::() { + let window = self.window.clone(); + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { let mut selection = term_window.selection(pane_id); selection.start = Some(start); selection.range = Some(range); window.invalidate(); - } - Ok(()) - }); + }))); self.adjust_viewport_for_cursor_position(); } @@ -154,12 +153,10 @@ impl CopyRenderable { fn set_viewport(&self, row: Option) { let dims = self.delegate.get_dimensions(); let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { term_window.set_viewport(pane_id, row, dims); - } - Ok(()) - }); + }))); } fn close(&self) { diff --git a/wezterm-gui/src/overlay/quickselect.rs b/wezterm-gui/src/overlay/quickselect.rs index 6d52da85c..e13c11b2e 100644 --- a/wezterm-gui/src/overlay/quickselect.rs +++ b/wezterm-gui/src/overlay/quickselect.rs @@ -1,5 +1,5 @@ use crate::selection::{SelectionCoordinate, SelectionRange}; -use crate::termwindow::TermWindow; +use crate::termwindow::{TermWindow, TermWindowNotif}; use config::keyassignment::{ClipboardCopyDestination, ScrollbackEraseMode}; use config::ConfigHandle; use mux::domain::DomainId; @@ -489,12 +489,10 @@ impl QuickSelectRenderable { fn set_viewport(&self, row: Option) { let dims = self.delegate.get_dimensions(); let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { term_window.set_viewport(pane_id, row, dims); - } - Ok(()) - }); + }))); } fn check_for_resize(&mut self) { @@ -579,10 +577,7 @@ impl QuickSelectRenderable { let pane_id = pane.pane_id(); let mut results = Some(results); - window.apply(move |term_window, _window| { - let term_window = term_window - .downcast_mut::() - .expect("to be TermWindow"); + window.notify(TermWindowNotif::Apply(Box::new(move |term_window| { let state = term_window.pane_state(pane_id); if let Some(overlay) = state.overlay.as_ref() { if let Some(search_overlay) = overlay.downcast_ref::() { @@ -599,8 +594,7 @@ impl QuickSelectRenderable { } } } - Ok(()) - }); + }))); anyhow::Result::<()>::Ok(()) }) .detach(); @@ -612,22 +606,20 @@ impl QuickSelectRenderable { fn clear_selection(&mut self) { let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { let mut selection = term_window.selection(pane_id); selection.start.take(); selection.range.take(); - } - Ok(()) - }); + }))); } fn select_and_copy_match_number(&mut self, n: usize, paste: bool) { let result = self.results[n].clone(); let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { { let mut selection = term_window.selection(pane_id); let start = SelectionCoordinate { @@ -659,9 +651,7 @@ impl QuickSelectRenderable { ); } } - } - Ok(()) - }); + }))); } fn activate_match_number(&mut self, n: usize) { diff --git a/wezterm-gui/src/overlay/search.rs b/wezterm-gui/src/overlay/search.rs index f935972f3..807aab497 100644 --- a/wezterm-gui/src/overlay/search.rs +++ b/wezterm-gui/src/overlay/search.rs @@ -1,5 +1,5 @@ use crate::selection::{SelectionCoordinate, SelectionRange}; -use crate::termwindow::TermWindow; +use crate::termwindow::{TermWindow, TermWindowNotif}; use config::keyassignment::ScrollbackEraseMode; use mux::domain::DomainId; use mux::pane::{Pane, PaneId, Pattern, SearchResult}; @@ -362,12 +362,10 @@ impl SearchRenderable { fn set_viewport(&self, row: Option) { let dims = self.delegate.get_dimensions(); let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { term_window.set_viewport(pane_id, row, dims); - } - Ok(()) - }); + }))); } fn check_for_resize(&mut self) { @@ -439,10 +437,7 @@ impl SearchRenderable { let pane_id = pane.pane_id(); let mut results = Some(results); - window.apply(move |term_window, _window| { - let term_window = term_window - .downcast_mut::() - .expect("to be TermWindow"); + window.notify(TermWindowNotif::Apply(Box::new(move |term_window| { let state = term_window.pane_state(pane_id); if let Some(overlay) = state.overlay.as_ref() { if let Some(search_overlay) = overlay.downcast_ref::() { @@ -459,8 +454,7 @@ impl SearchRenderable { } } } - Ok(()) - }); + }))); anyhow::Result::<()>::Ok(()) }) .detach(); @@ -472,14 +466,12 @@ impl SearchRenderable { fn clear_selection(&mut self) { let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { let mut selection = term_window.selection(pane_id); selection.start.take(); selection.range.take(); - } - Ok(()) - }); + }))); } fn activate_match_number(&mut self, n: usize) { @@ -487,8 +479,8 @@ impl SearchRenderable { let result = self.results[n].clone(); let pane_id = self.delegate.pane_id(); - self.window.apply(move |term_window, _window| { - if let Some(term_window) = term_window.downcast_mut::() { + self.window + .notify(TermWindowNotif::Apply(Box::new(move |term_window| { let mut selection = term_window.selection(pane_id); let start = SelectionCoordinate { x: result.start_x, @@ -504,9 +496,7 @@ impl SearchRenderable { y: result.end_y, }, }); - } - Ok(()) - }); + }))); self.set_viewport(Some(result.start_y)); } diff --git a/wezterm-gui/src/scripting/guiwin.rs b/wezterm-gui/src/scripting/guiwin.rs index 77fb28330..de31b3df4 100644 --- a/wezterm-gui/src/scripting/guiwin.rs +++ b/wezterm-gui/src/scripting/guiwin.rs @@ -1,8 +1,8 @@ //! GuiWin represents a Gui TermWindow (as opposed to a Mux window) in lua code use super::luaerr; use super::pane::PaneObject; +use crate::termwindow::TermWindowNotif; use crate::TermWindow; -use anyhow::anyhow; use config::keyassignment::KeyAssignment; use luahelper::*; use mlua::{UserData, UserDataMethods}; @@ -14,7 +14,7 @@ use window::WindowOps; #[derive(Clone)] pub struct GuiWin { mux_window_id: MuxWindowId, - window: ::window::Window, + pub window: ::window::Window, } impl GuiWin { @@ -26,24 +26,6 @@ impl GuiWin { mux_window_id, } } - - pub async fn with_term_window(&self, mut f: F) -> mlua::Result - where - F: FnMut(&mut TermWindow, &dyn WindowOps) -> anyhow::Result, - F: Send + 'static, - T: Send + 'static, - { - self.window - .apply(move |tw, ops| { - if let Some(term_window) = tw.downcast_mut::() { - f(term_window, ops) - } else { - Err(anyhow!("Window is not TermWindow!?")) - } - }) - .await - .map_err(luaerr) - } } impl UserData for GuiWin { @@ -61,76 +43,90 @@ impl UserData for GuiWin { Ok(()) }, ); - methods.add_async_method("set_right_status", |_, this, status: String| async move { - this.with_term_window(move |term_window, _ops| { - if status != term_window.right_status { - term_window.right_status = status.clone(); - term_window.update_title_post_status(); - } - Ok(()) - }) - .await + methods.add_method("set_right_status", |_, this, status: String| { + this.window.notify(TermWindowNotif::SetRightStatus(status)); + Ok(()) }); methods.add_async_method("get_dimensions", |_, this, _: ()| async move { - this.with_term_window(move |term_window, _ops| { - #[derive(Serialize, Deserialize)] - struct Dims { - pixel_width: usize, - pixel_height: usize, - dpi: usize, - is_full_screen: bool, - } - impl_lua_conversion!(Dims); + let (tx, rx) = smol::channel::bounded(1); + this.window.notify(TermWindowNotif::GetDimensions(tx)); + let (dims, is_full_screen) = rx + .recv() + .await + .map_err(|e| anyhow::anyhow!("{:#}", e)) + .map_err(luaerr)?; - let dims = Dims { - pixel_width: term_window.dimensions.pixel_width, - pixel_height: term_window.dimensions.pixel_height, - dpi: term_window.dimensions.dpi, - is_full_screen: term_window.is_full_screen, - }; - Ok(dims) - }) - .await + #[derive(Serialize, Deserialize)] + struct Dims { + pixel_width: usize, + pixel_height: usize, + dpi: usize, + is_full_screen: bool, + } + impl_lua_conversion!(Dims); + + let dims = Dims { + pixel_width: dims.pixel_width, + pixel_height: dims.pixel_height, + dpi: dims.dpi, + is_full_screen, + }; + Ok(dims) }); methods.add_async_method( "get_selection_text_for_pane", |_, this, pane: PaneObject| async move { - this.with_term_window(move |term_window, _ops| { - Ok(term_window.selection_text(&pane.pane()?)) - }) - .await + let (tx, rx) = smol::channel::bounded(1); + this.window.notify(TermWindowNotif::GetSelectionForPane { + pane_id: pane.pane, + tx, + }); + let text = rx + .recv() + .await + .map_err(|e| anyhow::anyhow!("{:#}", e)) + .map_err(luaerr)?; + + Ok(text) }, ); - methods.add_async_method( + methods.add_method( "perform_action", - |_, this, (assignment, pane): (KeyAssignment, PaneObject)| async move { - this.with_term_window(move |term_window, _ops| { - term_window.perform_key_assignment(&pane.pane()?, &assignment) - }) - .await + |_, this, (assignment, pane): (KeyAssignment, PaneObject)| { + this.window.notify(TermWindowNotif::PerformAssignment { + pane_id: pane.pane, + assignment, + }); + Ok(()) }, ); methods.add_async_method("effective_config", |_, this, _: ()| async move { - this.with_term_window(move |term_window, _ops| Ok((*term_window.config).clone())) + let (tx, rx) = smol::channel::bounded(1); + this.window.notify(TermWindowNotif::GetEffectiveConfig(tx)); + let config = rx + .recv() .await + .map_err(|e| anyhow::anyhow!("{:#}", e)) + .map_err(luaerr)?; + + Ok((*config).clone()) }); methods.add_async_method("get_config_overrides", |_, this, _: ()| async move { - this.with_term_window(move |term_window, _ops| { - let wrap = JsonLua(term_window.config_overrides.clone()); - Ok(wrap) - }) - .await - }); - methods.add_async_method( - "set_config_overrides", - |_, this, value: JsonLua| async move { - this.with_term_window(move |term_window, _ops| { - term_window.config_overrides = value.0.clone(); - term_window.config_was_reloaded(); - Ok(()) - }) + let (tx, rx) = smol::channel::bounded(1); + this.window.notify(TermWindowNotif::GetConfigOverrides(tx)); + let overrides = rx + .recv() .await - }, - ); + .map_err(|e| anyhow::anyhow!("{:#}", e)) + .map_err(luaerr)?; + + let wrap = JsonLua(overrides); + Ok(wrap) + }); + methods.add_method("set_config_overrides", |_, this, value: JsonLua| { + this.window + .notify(TermWindowNotif::SetConfigOverrides(value.0)); + Ok(()) + }); } } diff --git a/wezterm-gui/src/scripting/pane.rs b/wezterm-gui/src/scripting/pane.rs index 57c5d187c..bbc955073 100644 --- a/wezterm-gui/src/scripting/pane.rs +++ b/wezterm-gui/src/scripting/pane.rs @@ -8,7 +8,7 @@ use std::rc::Rc; #[derive(Clone)] pub struct PaneObject { - pane: PaneId, + pub pane: PaneId, } impl PaneObject { diff --git a/wezterm-gui/src/termwindow/clipboard.rs b/wezterm-gui/src/termwindow/clipboard.rs index 3c7e91ec9..46aff7f36 100644 --- a/wezterm-gui/src/termwindow/clipboard.rs +++ b/wezterm-gui/src/termwindow/clipboard.rs @@ -88,7 +88,11 @@ impl TermWindow { } } - pub fn paste_from_clipboard(&mut self, pane: &Rc, clipboard: ClipboardPasteSource) { + pub async fn paste_from_clipboard( + &mut self, + pane: &Rc, + clipboard: ClipboardPasteSource, + ) { let pane_id = pane.pane_id(); let window = self.window.as_ref().unwrap().clone(); let clipboard = match clipboard { @@ -97,27 +101,13 @@ impl TermWindow { }; let future = window.get_clipboard(clipboard); - promise::spawn::spawn(async move { - if let Ok(clip) = future.await { - window - .apply(move |term_window, _window| { - let clip = clip.clone(); - if let Some(term_window) = term_window.downcast_mut::() { - if let Some(pane) = - term_window.pane_state(pane_id).overlay.clone().or_else(|| { - let mux = Mux::get().unwrap(); - mux.get_pane(pane_id) - }) - { - pane.trickle_paste(clip).ok(); - } - } - Ok(()) - }) - .await?; - }; - Ok::<(), anyhow::Error>(()) - }) - .detach(); + if let Ok(clip) = future.await { + if let Some(pane) = self.pane_state(pane_id).overlay.clone().or_else(|| { + let mux = Mux::get().unwrap(); + mux.get_pane(pane_id) + }) { + pane.trickle_paste(clip).ok(); + } + } } } diff --git a/wezterm-gui/src/termwindow/keyevent.rs b/wezterm-gui/src/termwindow/keyevent.rs index 3da1e39bf..7427e708d 100644 --- a/wezterm-gui/src/termwindow/keyevent.rs +++ b/wezterm-gui/src/termwindow/keyevent.rs @@ -34,7 +34,7 @@ pub enum Key { } impl super::TermWindow { - pub fn key_event_impl(&mut self, window_key: &KeyEvent, context: &dyn WindowOps) -> bool { + pub async fn key_event_impl(&mut self, window_key: KeyEvent, context: &dyn WindowOps) -> bool { if !window_key.key_is_down { return false; } @@ -95,7 +95,7 @@ impl super::TermWindow { .input_map .lookup_key(&raw_code_key, window_key.raw_modifiers | leader_mod) { - self.perform_key_assignment(&pane, &assignment).ok(); + self.perform_key_assignment(&pane, &assignment).await.ok(); context.invalidate(); if leader_active { @@ -124,7 +124,7 @@ impl super::TermWindow { .input_map .lookup_key(key, window_key.raw_modifiers | leader_mod) { - self.perform_key_assignment(&pane, &assignment).ok(); + self.perform_key_assignment(&pane, &assignment).await.ok(); context.invalidate(); if leader_active { @@ -189,7 +189,7 @@ impl super::TermWindow { .input_map .lookup_key(&window_key.key, window_key.modifiers | leader_mod) { - self.perform_key_assignment(&pane, &assignment).ok(); + self.perform_key_assignment(&pane, &assignment).await.ok(); context.invalidate(); if leader_active { // A successful leader key-lookup cancels the leader diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index ae4bf4523..c1596c286 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -24,7 +24,6 @@ use config::{configuration, ConfigHandle, WindowCloseConfirmation}; use lru::LruCache; use luahelper::impl_lua_conversion; use mlua::FromLua; -use mux::activity::Activity; use mux::domain::{DomainId, DomainState}; use mux::pane::{Pane, PaneId}; use mux::renderable::RenderableDimensions; @@ -33,7 +32,7 @@ use mux::window::WindowId as MuxWindowId; use mux::{Mux, MuxNotification}; use portable_pty::PtySize; use serde::*; -use std::any::Any; +use smol::channel::Sender; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::ops::Add; @@ -72,6 +71,38 @@ pub fn set_window_class(cls: &str) { *WINDOW_CLASS.lock().unwrap() = cls.to_owned(); } +/// Type used together with Window::notify to do something in the +/// context of the window-specific event loop +pub enum TermWindowNotif { + InvalidateShapeCache, + PerformAssignment { + pane_id: PaneId, + assignment: KeyAssignment, + }, + SetRightStatus(String), + GetDimensions(Sender<(Dimensions, bool)>), + GetSelectionForPane { + pane_id: PaneId, + tx: Sender, + }, + GetEffectiveConfig(Sender), + FinishWindowEvent { + name: String, + again: bool, + }, + GetConfigOverrides(Sender), + SetConfigOverrides(serde_json::Value), + CancelOverlayForPane(PaneId), + CancelOverlayForTab { + tab_id: TabId, + pane_id: Option, + }, + MuxNotification(MuxNotification), + Periodic, + EmitStatusUpdate, + Apply(Box), +} + #[derive(Default, Clone)] pub struct PaneState { /// If is_some(), the top row of the visible screen. @@ -196,19 +227,23 @@ pub struct TermWindow { has_animation: RefCell>, } -impl WindowCallbacks for TermWindow { - fn can_close(&mut self) -> bool { +impl TermWindow { + fn close_requested(&mut self, window: &Window) { let mux = Mux::get().unwrap(); match self.config.window_close_confirmation { WindowCloseConfirmation::NeverPrompt => { // Immediately kill the tabs and allow the window to close mux.kill_window(self.mux_window_id); - true + window.close(); } WindowCloseConfirmation::AlwaysPrompt => { let tab = match mux.get_active_tab_for_window(self.mux_window_id) { Some(tab) => tab, - None => return true, + None => { + mux.kill_window(self.mux_window_id); + window.close(); + return; + } }; let mux_window_id = self.mux_window_id; @@ -218,7 +253,8 @@ impl WindowCallbacks for TermWindow { .map_or(false, |w| w.can_close_without_prompting()); if can_close { mux.kill_window(self.mux_window_id); - return true; + window.close(); + return; } let window = self.window.clone().unwrap(); let (overlay, future) = start_overlay(self, &tab, move |tab_id, term| { @@ -229,16 +265,11 @@ impl WindowCallbacks for TermWindow { // Don't close right now; let the close happen from // the confirmation overlay - false } } } - fn as_any(&mut self) -> &mut dyn Any { - self - } - - fn focus_change(&mut self, focused: bool) { + fn focus_changed(&mut self, focused: bool) { log::trace!("Setting focus to {:?}", focused); self.focused = if focused { Some(Instant::now()) } else { None }; @@ -258,10 +289,6 @@ impl WindowCallbacks for TermWindow { } } - fn mouse_event(&mut self, event: &MouseEvent, context: &dyn WindowOps) { - self.mouse_event_impl(event, context) - } - fn resize(&mut self, dimensions: Dimensions, is_full_screen: bool) { log::trace!( "resize event, current cells: {:?}, new dims: {:?} is_full_screen:{}", @@ -283,88 +310,6 @@ impl WindowCallbacks for TermWindow { self.emit_window_event("window-resized"); } - fn key_event(&mut self, window_key: &KeyEvent, context: &dyn WindowOps) -> bool { - self.key_event_impl(window_key, context) - } - - fn opengl_context_lost(&mut self, prior_window: &dyn WindowOps) -> anyhow::Result<()> { - log::error!("context was lost, set up a new window"); - let activity = Activity::new(); - - let render_state = None; - - let clipboard_contents = Arc::clone(&self.clipboard_contents); - let dimensions = self.dimensions.clone(); - let mux_window_id = self.mux_window_id; - let config = self.config.clone(); - - let guts = Box::new(Self { - window: None, - config: self.config.clone(), - config_overrides: self.config_overrides.clone(), - window_background: self.window_background.clone(), - palette: None, - focused: None, - mux_window_id, - fonts: Rc::clone(&self.fonts), - render_metrics: self.render_metrics.clone(), - dimensions, - is_full_screen: self.is_full_screen, - terminal_size: self.terminal_size.clone(), - render_state, - input_map: InputMap::new(&config), - leader_is_down: None, - show_tab_bar: self.show_tab_bar, - show_scroll_bar: self.show_scroll_bar, - tab_bar: self.tab_bar.clone(), - right_status: self.right_status.clone(), - last_mouse_coords: self.last_mouse_coords.clone(), - last_mouse_terminal_coords: self.last_mouse_terminal_coords.clone(), - scroll_drag_start: self.scroll_drag_start.clone(), - split_drag_start: self.split_drag_start.clone(), - window_drag_position: None, - current_mouse_event: None, - prev_cursor: self.prev_cursor.clone(), - last_scroll_info: self.last_scroll_info.clone(), - clipboard_contents: Arc::clone(&clipboard_contents), - tab_state: RefCell::new(self.tab_state.borrow().clone()), - pane_state: RefCell::new(self.pane_state.borrow().clone()), - current_mouse_button: self.current_mouse_button.clone(), - last_mouse_click: self.last_mouse_click.clone(), - current_highlight: self.current_highlight.clone(), - shape_cache: RefCell::new(LruCache::new(65536)), - last_blink_paint: Instant::now(), - last_status_call: Instant::now(), - event_states: HashMap::new(), - has_animation: RefCell::new(None), - }); - prior_window.close(); - - promise::spawn::spawn(async move { - smol::Timer::after(Duration::from_millis(300)).await; - log::error!("now try making that new window"); - let window = Window::new_window( - &*WINDOW_CLASS.lock().unwrap(), - "wezterm", - dimensions.pixel_width, - dimensions.pixel_height, - guts, - Some(&config), - ) - .await?; - - Self::apply_icon(&window)?; - Self::start_periodic_maintenance(window.clone()); - Self::setup_clipboard(&window, mux_window_id, clipboard_contents); - - drop(activity); // Keep the activity outstanding until we get here - Ok::<(), anyhow::Error>(()) - }) - .detach(); - - Ok(()) - } - fn created( &mut self, window: &Window, @@ -412,10 +357,6 @@ impl WindowCallbacks for TermWindow { Ok(()) } - - fn paint(&mut self, frame: &mut glium::Frame) { - self.paint_impl(frame) - } } fn load_background_image(config: &ConfigHandle) -> Option> { @@ -521,51 +462,52 @@ impl TermWindow { let clipboard_contents = Arc::new(Mutex::new(None)); - let window = Window::new_window( + let mut myself = Self { + window: None, + window_background, + config: config.clone(), + config_overrides: serde_json::Value::default(), + palette: None, + focused: None, + mux_window_id, + fonts: fontconfig, + render_metrics, + dimensions, + is_full_screen: false, + terminal_size, + render_state, + input_map: InputMap::new(&config), + leader_is_down: None, + show_tab_bar, + show_scroll_bar: config.enable_scroll_bar, + tab_bar: TabBarState::default(), + right_status: String::new(), + last_mouse_coords: (0, -1), + last_mouse_terminal_coords: (0, 0), + scroll_drag_start: None, + split_drag_start: None, + window_drag_position: None, + current_mouse_event: None, + prev_cursor: PrevCursorPos::new(), + last_scroll_info: RenderableDimensions::default(), + clipboard_contents: Arc::clone(&clipboard_contents), + tab_state: RefCell::new(HashMap::new()), + pane_state: RefCell::new(HashMap::new()), + current_mouse_button: None, + last_mouse_click: None, + current_highlight: None, + shape_cache: RefCell::new(LruCache::new(65536)), + last_blink_paint: Instant::now(), + last_status_call: Instant::now(), + event_states: HashMap::new(), + has_animation: RefCell::new(None), + }; + + let (window, events) = Window::new_window( &*WINDOW_CLASS.lock().unwrap(), "wezterm", dimensions.pixel_width, dimensions.pixel_height, - Box::new(Self { - window: None, - window_background, - config: config.clone(), - config_overrides: serde_json::Value::default(), - palette: None, - focused: None, - mux_window_id, - fonts: fontconfig, - render_metrics, - dimensions, - is_full_screen: false, - terminal_size, - render_state, - input_map: InputMap::new(&config), - leader_is_down: None, - show_tab_bar, - show_scroll_bar: config.enable_scroll_bar, - tab_bar: TabBarState::default(), - right_status: String::new(), - last_mouse_coords: (0, -1), - last_mouse_terminal_coords: (0, 0), - scroll_drag_start: None, - split_drag_start: None, - window_drag_position: None, - current_mouse_event: None, - prev_cursor: PrevCursorPos::new(), - last_scroll_info: RenderableDimensions::default(), - clipboard_contents: Arc::clone(&clipboard_contents), - tab_state: RefCell::new(HashMap::new()), - pane_state: RefCell::new(HashMap::new()), - current_mouse_button: None, - last_mouse_click: None, - current_highlight: None, - shape_cache: RefCell::new(LruCache::new(65536)), - last_blink_paint: Instant::now(), - last_status_call: Instant::now(), - event_states: HashMap::new(), - has_animation: RefCell::new(None), - }), Some(&config), ) .await?; @@ -573,10 +515,149 @@ impl TermWindow { Self::apply_icon(&window)?; Self::setup_clipboard(&window, mux_window_id, clipboard_contents); + promise::spawn::spawn(async move { + let gl = window.enable_opengl().await?; + myself.created(&window, Rc::clone(&gl))?; + myself.subscribe_to_pane_updates(); + myself.emit_status_event(); + + while let Ok(event) = events.recv().await { + match event { + WindowEvent::Destroyed => { + break; + } + WindowEvent::CloseRequested => { + myself.close_requested(&window); + } + WindowEvent::FocusChanged(focused) => { + myself.focus_changed(focused); + } + WindowEvent::MouseEvent(event) => { + myself.mouse_event_impl(event, &window).await; + } + WindowEvent::Resized { + dimensions, + is_full_screen, + } => { + myself.resize(dimensions, is_full_screen); + } + WindowEvent::KeyEvent(event) => { + myself.key_event_impl(event, &window).await; + } + WindowEvent::NeedRepaint => { + if gl.is_context_lost() { + eprintln!("opengl context was lost; should reinit"); + break; + } + + let mut frame = glium::Frame::new( + Rc::clone(&gl), + ( + myself.dimensions.pixel_width as u32, + myself.dimensions.pixel_height as u32, + ), + ); + + myself.paint_impl(&mut frame); + window.finish_frame(frame)?; + } + WindowEvent::Notification(item) => { + if let Ok(notif) = item.downcast::() { + myself.dispatch_notif(*notif, &window).await?; + } + } + } + } + anyhow::Result::<()>::Ok(()) + }) + .detach(); + crate::update::start_update_checker(); Ok(()) } + async fn dispatch_notif( + &mut self, + notif: TermWindowNotif, + window: &Window, + ) -> anyhow::Result<()> { + match notif { + TermWindowNotif::InvalidateShapeCache => { + self.shape_cache.borrow_mut().clear(); + window.invalidate(); + } + TermWindowNotif::PerformAssignment { + pane_id, + assignment, + } => { + let mux = Mux::get().unwrap(); + let pane = mux + .get_pane(pane_id) + .ok_or_else(|| anyhow!("pane id {} is not valid", pane_id))?; + self.perform_key_assignment(&pane, &assignment).await?; + } + TermWindowNotif::SetRightStatus(status) => { + if status != self.right_status { + self.right_status = status; + self.update_title_post_status(); + } + } + TermWindowNotif::GetDimensions(tx) => { + tx.send((self.dimensions, self.is_full_screen)).await?; + } + TermWindowNotif::GetEffectiveConfig(tx) => { + tx.send(self.config.clone()).await?; + } + TermWindowNotif::FinishWindowEvent { name, again } => { + self.finish_window_event(&name, again); + } + TermWindowNotif::GetConfigOverrides(tx) => { + tx.send(self.config_overrides.clone()).await?; + } + TermWindowNotif::SetConfigOverrides(value) => { + self.config_overrides = value; + self.config_was_reloaded(); + } + TermWindowNotif::CancelOverlayForPane(pane_id) => { + self.cancel_overlay_for_pane(pane_id); + } + TermWindowNotif::CancelOverlayForTab { tab_id, pane_id } => { + self.cancel_overlay_for_tab(tab_id, pane_id); + } + TermWindowNotif::MuxNotification(n) => match n { + MuxNotification::Alert { + alert: Alert::TitleMaybeChanged, + .. + } => { + self.update_title(); + } + MuxNotification::PaneOutput(pane_id) => { + self.mux_pane_output_event(pane_id); + } + _ => {} + }, + TermWindowNotif::Periodic => { + self.periodic_window_maintenance(window)?; + } + TermWindowNotif::EmitStatusUpdate => { + self.emit_status_event(); + } + TermWindowNotif::GetSelectionForPane { pane_id, tx } => { + let mux = Mux::get().unwrap(); + let pane = mux + .get_pane(pane_id) + .ok_or_else(|| anyhow!("pane id {} is not valid", pane_id))?; + + tx.send(self.selection_text(&pane)).await?; + } + TermWindowNotif::Apply(func) => { + func(self); + } + } + + Ok(()) + } + fn apply_icon(window: &Window) -> anyhow::Result<()> { let icon_image = image::load_from_memory(ICON_DATA)?; let image = icon_image.to_bgra8(); @@ -591,52 +672,17 @@ impl TermWindow { fn schedule_status_update(&self) { if let Some(window) = self.window.as_ref() { - let window = window.clone(); - promise::spawn::spawn(async move { - window - .apply(move |tw, _ops| { - if let Some(term_window) = tw.downcast_mut::() { - term_window.emit_status_event(); - } - Ok(()) - }) - .await - }) - .detach(); + window.notify(TermWindowNotif::EmitStatusUpdate); } } fn start_periodic_maintenance(window: Window) { - Connection::get() - .unwrap() - .schedule_timer(std::time::Duration::from_millis(35), { - let window = window.clone(); - move || { - window.apply(move |myself, window| { - if let Some(myself) = myself.downcast_mut::() { - myself.periodic_window_maintenance(window)?; - } - Ok(()) - }); - } - }); - - // Trigger an initial status update - { - let window = window.clone(); - promise::spawn::spawn(async move { - window - .apply(move |tw, _ops| { - if let Some(term_window) = tw.downcast_mut::() { - term_window.subscribe_to_pane_updates(); - term_window.emit_status_event(); - } - Ok(()) - }) - .await - }) - .detach(); - } + Connection::get().unwrap().schedule_timer( + std::time::Duration::from_millis(35), + move || { + window.notify(TermWindowNotif::Periodic); + }, + ); } fn mux_pane_output_event(&mut self, pane_id: PaneId) { @@ -693,27 +739,7 @@ impl TermWindow { _ => return true, } - let dead = Arc::clone(dead); - window.apply(move |myself, _window| { - if let Some(myself) = myself.downcast_mut::() { - match n { - MuxNotification::Alert { - alert: Alert::TitleMaybeChanged, - .. - } => { - myself.update_title(); - } - MuxNotification::PaneOutput(pane_id) => { - myself.mux_pane_output_event(pane_id); - } - _ => {} - } - } else { - // Something inconsistent: cancel subscription - dead.store(true, Ordering::Relaxed); - } - Ok(()) - }); + window.notify(TermWindowNotif::MuxNotification(n)); true } @@ -758,17 +784,9 @@ impl TermWindow { false }; - let name_copy = name.clone(); - - if let Err(err) = window - .with_term_window(move |myself, _| { - myself.finish_window_event(&name, again); - Ok(()) - }) - .await - { - log::error!("while finishing {} event: {:#}", name_copy, err); - } + window + .window + .notify(TermWindowNotif::FinishWindowEvent { name, again }); Ok(()) } @@ -1478,7 +1496,7 @@ impl TermWindow { self.move_tab(tab) } - pub fn perform_key_assignment( + pub async fn perform_key_assignment( &mut self, pane: &Rc, assignment: &KeyAssignment, @@ -1520,13 +1538,15 @@ impl TermWindow { self.copy_to_clipboard(*dest, text); } Paste => { - self.paste_from_clipboard(pane, ClipboardPasteSource::Clipboard); + self.paste_from_clipboard(pane, ClipboardPasteSource::Clipboard) + .await; } PastePrimarySelection => { - self.paste_from_clipboard(pane, ClipboardPasteSource::PrimarySelection); + self.paste_from_clipboard(pane, ClipboardPasteSource::PrimarySelection) + .await; } PasteFrom(source) => { - self.paste_from_clipboard(pane, *source); + self.paste_from_clipboard(pane, *source).await; } ActivateTabRelative(n) => { self.activate_tab_relative(*n)?; @@ -1598,49 +1618,7 @@ impl TermWindow { self.window_drag_position = self.current_mouse_event.clone(); } OpenLinkAtMouseCursor => { - // They clicked on a link, so let's open it! - // We need to ensure that we spawn the `open` call outside of the context - // of our window loop; on Windows it can cause a panic due to - // triggering our WndProc recursively. - // We get that assurance for free as part of the async dispatch that we - // perform below; here we allow the user to define an `open-uri` event - // handler that can bypass the normal `open::that` functionality. - if let Some(link) = self.current_highlight.as_ref().cloned() { - let window = GuiWin::new(self); - let pane = PaneObject::new(pane); - - async fn open_uri( - lua: Option>, - window: GuiWin, - pane: PaneObject, - link: String, - ) -> anyhow::Result<()> { - let default_click = match lua { - Some(lua) => { - let args = lua.pack_multi((window, pane, link.clone()))?; - config::lua::emit_event(&lua, ("open-uri".to_string(), args)) - .await - .map_err(|e| { - log::error!("while processing open-uri event: {:#}", e); - e - })? - } - None => true, - }; - if default_click { - log::info!("clicking {}", link); - if let Err(err) = open::that(&link) { - log::error!("failed to open {}: {:?}", link, err); - } - } - Ok(()) - } - - promise::spawn::spawn(config::with_lua_config_on_main_thread(move |lua| { - open_uri(lua, window, pane, link.uri().to_string()) - })) - .detach(); - } + self.do_open_link_at_mouse_cursor(pane); } EmitEvent(name) => { self.emit_window_event(name); @@ -1652,8 +1630,7 @@ impl TermWindow { let window = self.window.as_ref().unwrap(); window.invalidate(); } else { - return self - .perform_key_assignment(pane, &KeyAssignment::OpenLinkAtMouseCursor); + self.do_open_link_at_mouse_cursor(pane); } } CompleteSelection(dest) => { @@ -1725,6 +1702,51 @@ impl TermWindow { Ok(()) } + fn do_open_link_at_mouse_cursor(&self, pane: &Rc) { + // They clicked on a link, so let's open it! + // We need to ensure that we spawn the `open` call outside of the context + // of our window loop; on Windows it can cause a panic due to + // triggering our WndProc recursively. + // We get that assurance for free as part of the async dispatch that we + // perform below; here we allow the user to define an `open-uri` event + // handler that can bypass the normal `open::that` functionality. + if let Some(link) = self.current_highlight.as_ref().cloned() { + let window = GuiWin::new(self); + let pane = PaneObject::new(pane); + + async fn open_uri( + lua: Option>, + window: GuiWin, + pane: PaneObject, + link: String, + ) -> anyhow::Result<()> { + let default_click = match lua { + Some(lua) => { + let args = lua.pack_multi((window, pane, link.clone()))?; + config::lua::emit_event(&lua, ("open-uri".to_string(), args)) + .await + .map_err(|e| { + log::error!("while processing open-uri event: {:#}", e); + e + })? + } + None => true, + }; + if default_click { + log::info!("clicking {}", link); + if let Err(err) = open::that(&link) { + log::error!("failed to open {}: {:?}", link, err); + } + } + Ok(()) + } + + promise::spawn::spawn(config::with_lua_config_on_main_thread(move |lua| { + open_uri(lua, window, pane, link.uri().to_string()) + })) + .detach(); + } + } fn close_current_pane(&mut self, confirm: bool) { let mux_window_id = self.mux_window_id; let mux = Mux::get().unwrap(); @@ -2003,12 +2025,7 @@ impl TermWindow { } pub fn schedule_cancel_overlay(window: Window, tab_id: TabId, pane_id: Option) { - window.apply(move |myself, _| { - if let Some(myself) = myself.downcast_mut::() { - myself.cancel_overlay_for_tab(tab_id, pane_id); - } - Ok(()) - }); + window.notify(TermWindowNotif::CancelOverlayForTab { tab_id, pane_id }); } fn cancel_overlay_for_pane(&self, pane_id: PaneId) { @@ -2027,12 +2044,7 @@ impl TermWindow { } pub fn schedule_cancel_overlay_for_pane(window: Window, pane_id: PaneId) { - window.apply(move |myself, _| { - if let Some(myself) = myself.downcast_mut::() { - myself.cancel_overlay_for_pane(pane_id); - } - Ok(()) - }); + window.notify(TermWindowNotif::CancelOverlayForPane(pane_id)); } pub fn assign_overlay_for_pane(&mut self, pane_id: PaneId, overlay: Rc) { diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs index 3a82d6343..345fc96ab 100644 --- a/wezterm-gui/src/termwindow/mouseevent.rs +++ b/wezterm-gui/src/termwindow/mouseevent.rs @@ -18,7 +18,7 @@ use wezterm_term::input::MouseEventKind as TMEK; use wezterm_term::{LastMouseClick, StableRowIndex}; impl super::TermWindow { - pub fn mouse_event_impl(&mut self, event: &MouseEvent, context: &dyn WindowOps) { + pub async fn mouse_event_impl(&mut self, event: MouseEvent, context: &dyn WindowOps) { let pane = match self.get_active_pane_or_overlay() { Some(pane) => pane, None => return, @@ -209,11 +209,12 @@ impl super::TermWindow { } else if in_scroll_bar { self.mouse_event_scroll_bar(pane, event, context); } else { - self.mouse_event_terminal(pane, x, term_y, event, context); + self.mouse_event_terminal(pane, x, term_y, event, context) + .await; } } - pub fn mouse_event_tab_bar(&mut self, x: usize, event: &MouseEvent, context: &dyn WindowOps) { + pub fn mouse_event_tab_bar(&mut self, x: usize, event: MouseEvent, context: &dyn WindowOps) { match event.kind { WMEK::Press(MousePress::Left) => match self.tab_bar.hit_test(x) { TabBarItem::Tab(tab_idx) => { @@ -251,7 +252,7 @@ impl super::TermWindow { pub fn mouse_event_scroll_bar( &mut self, pane: Rc, - event: &MouseEvent, + event: MouseEvent, context: &dyn WindowOps, ) { if let WMEK::Press(MousePress::Left) = event.kind { @@ -302,12 +303,12 @@ impl super::TermWindow { context.set_cursor(Some(MouseCursor::Arrow)); } - pub fn mouse_event_terminal( + pub async fn mouse_event_terminal( &mut self, mut pane: Rc, mut x: usize, mut y: i64, - event: &MouseEvent, + event: MouseEvent, context: &dyn WindowOps, ) { let mut on_split = None; @@ -499,7 +500,7 @@ impl super::TermWindow { .input_map .lookup_mouse(event_trigger_type.clone(), modifiers) { - self.perform_key_assignment(&pane, &action).ok(); + self.perform_key_assignment(&pane, &action).await.ok(); return; } } diff --git a/wezterm-gui/src/termwindow/render.rs b/wezterm-gui/src/termwindow/render.rs index eced0b0ee..2f519ac98 100644 --- a/wezterm-gui/src/termwindow/render.rs +++ b/wezterm-gui/src/termwindow/render.rs @@ -1,7 +1,9 @@ use crate::glium::texture::SrgbTexture2d; use crate::glyphcache::{BlockKey, CachedGlyph, GlyphCache}; use crate::shapecache::*; -use crate::termwindow::{BorrowedShapeCacheKey, MappedQuads, RenderState, ScrollHit, ShapedInfo}; +use crate::termwindow::{ + BorrowedShapeCacheKey, MappedQuads, RenderState, ScrollHit, ShapedInfo, TermWindowNotif, +}; use ::window::bitmaps::atlas::OutOfTextureSpace; use ::window::bitmaps::{TextureCoord, TextureRect, TextureSize}; use ::window::glium; @@ -546,7 +548,9 @@ impl super::TermWindow { None => { let font = self.fonts.resolve_font(style)?; let window = self.window.as_ref().unwrap().clone(); - match font.shape(text, || Self::invalidate_post_font_resolve(window)) { + match font.shape(text, move || { + window.notify(TermWindowNotif::InvalidateShapeCache) + }) { Ok(info) => { let line = Line::from_text(&text, &CellAttributes::default()); let clusters = line.cluster(); @@ -661,21 +665,6 @@ impl super::TermWindow { Ok(()) } - fn invalidate_post_font_resolve(window: ::window::Window) { - promise::spawn::spawn_into_main_thread(async move { - window - .apply(move |tw, _| { - if let Some(tw) = tw.downcast_mut::() { - tw.shape_cache.borrow_mut().clear(); - tw.window.as_ref().unwrap().invalidate(); - } - Ok(()) - }) - .await - }) - .detach(); - } - /// "Render" a line of the terminal screen into the vertex buffer. /// This is nominally a matter of setting the fg/bg color and the /// texture coordinates for a given glyph. There's a little bit @@ -847,9 +836,9 @@ impl super::TermWindow { None => { let font = self.fonts.resolve_font(style)?; let window = self.window.as_ref().unwrap().clone(); - match font - .shape(&cluster.text, || Self::invalidate_post_font_resolve(window)) - { + match font.shape(&cluster.text, move || { + window.notify(TermWindowNotif::InvalidateShapeCache) + }) { Ok(info) => { let glyphs = self.glyph_infos_to_glyphs( cluster, diff --git a/window/src/lib.rs b/window/src/lib.rs index fff0f4c52..fbe632af6 100644 --- a/window/src/lib.rs +++ b/window/src/lib.rs @@ -1,5 +1,6 @@ use async_trait::async_trait; use promise::Future; +use std::any::Any; use std::rc::Rc; use thiserror::Error; pub mod bitmaps; @@ -61,7 +62,7 @@ pub enum MouseCursor { SizeLeftRight, } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug)] pub enum WindowEvent { /// Called when the window close button is clicked. /// The window closure is deferred and this event is @@ -94,6 +95,8 @@ pub enum WindowEvent { KeyEvent(KeyEvent), MouseEvent(MouseEvent), + + Notification(Box), } pub type WindowEventSender = async_channel::Sender; @@ -108,6 +111,10 @@ pub trait WindowOps { /// Show a hidden window fn show(&self) -> Future<()>; + fn notify(&self, t: T) + where + Self: Sized; + /// Setup opengl for rendering async fn enable_opengl(&self) -> anyhow::Result>; /// Advise the window that a frame is finished diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs index 8e0fc1cdd..657b0c261 100644 --- a/window/src/os/macos/window.rs +++ b/window/src/os/macos/window.rs @@ -30,6 +30,7 @@ use objc::rc::{StrongPtr, WeakPtr}; use objc::runtime::{Class, Object, Protocol, Sel}; use objc::*; use promise::Future; +use std::any::Any; use std::cell::RefCell; use std::ffi::c_void; use std::rc::Rc; @@ -495,6 +496,24 @@ impl WindowOps for Window { .await } + fn notify(&self, t: T) + where + Self: Sized, + { + let mut t = Some(t); + Connection::with_window_inner(self.0, move |inner| { + if let Some(window_view) = WindowView::get_this(unsafe { &**inner.view }) { + window_view + .inner + .borrow() + .events + .try_send(WindowEvent::Notification(Box::new(t.take().unwrap()))) + .ok(); + } + Ok(()) + }); + } + fn close(&self) -> Future<()> { Connection::with_window_inner(self.0, |inner| { inner.close();