forked from wez/wezterm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
3420 lines (3125 loc) · 124 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg_attr(feature = "cargo-clippy", allow(clippy::range_plus_one))]
use super::renderstate::*;
use super::utilsprites::RenderMetrics;
use crate::colorease::ColorEase;
use crate::frontend::{front_end, try_front_end};
use crate::inputmap::InputMap;
use crate::overlay::{
confirm_close_pane, confirm_close_tab, confirm_close_window, confirm_quit_program, launcher,
start_overlay, start_overlay_pane, CopyModeParams, CopyOverlay, LauncherArgs, LauncherFlags,
QuickSelectOverlay,
};
use crate::scripting::guiwin::GuiWin;
use crate::scrollbar::*;
use crate::selection::Selection;
use crate::shapecache::*;
use crate::tabbar::{TabBarItem, TabBarState};
use crate::termwindow::background::{
load_background_image, reload_background_image, LoadedBackgroundLayer,
};
use crate::termwindow::keyevent::{KeyTableArgs, KeyTableState};
use crate::termwindow::modal::Modal;
use crate::termwindow::render::paint::AllowImage;
use crate::termwindow::render::{
CachedLineState, LineQuadCacheKey, LineQuadCacheValue, LineToEleShapeCacheKey,
LineToElementShapeItem,
};
use crate::termwindow::webgpu::WebGpuState;
use ::wezterm_term::input::{ClickPosition, MouseButton as TMB};
use ::window::*;
use anyhow::{anyhow, ensure, Context};
use config::keyassignment::{
KeyAssignment, PaneDirection, Pattern, PromptInputLine, QuickSelectArguments,
RotationDirection, SpawnCommand, SplitSize,
};
use config::{
configuration, AudibleBell, ConfigHandle, Dimension, DimensionContext, FrontEndSelection,
GeometryOrigin, GuiPosition, TermConfig, WindowCloseConfirmation,
};
use lfucache::*;
use mlua::{FromLua, UserData, UserDataFields};
use mux::pane::{CloseReason, Pane, PaneId, Pattern as MuxPattern, PerformAssignmentResult};
use mux::renderable::RenderableDimensions;
use mux::tab::{
PositionedPane, PositionedSplit, SplitDirection, SplitRequest, SplitSize as MuxSplitSize, Tab,
TabId,
};
use mux::window::WindowId as MuxWindowId;
use mux::{Mux, MuxNotification};
use mux_lua::MuxPane;
use smol::channel::Sender;
use smol::Timer;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::ops::Add;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use termwiz::hyperlink::Hyperlink;
use termwiz::surface::SequenceNo;
use wezterm_dynamic::Value;
use wezterm_font::FontConfiguration;
use wezterm_term::color::ColorPalette;
use wezterm_term::input::LastMouseClick;
use wezterm_term::{Alert, StableRowIndex, TerminalConfiguration, TerminalSize};
pub mod background;
pub mod box_model;
pub mod charselect;
pub mod clipboard;
pub mod keyevent;
pub mod modal;
mod mouseevent;
pub mod palette;
pub mod paneselect;
mod prevcursor;
pub mod render;
pub mod resize;
mod selection;
pub mod spawn;
pub mod webgpu;
use crate::spawn::SpawnWhere;
use prevcursor::PrevCursorPos;
const ATLAS_SIZE: usize = 128;
lazy_static::lazy_static! {
static ref WINDOW_CLASS: Mutex<String> = Mutex::new(wezterm_gui_subcommands::DEFAULT_WINDOW_CLASS.to_owned());
static ref POSITION: Mutex<Option<GuiPosition>> = Mutex::new(None);
}
pub const ICON_DATA: &'static [u8] = include_bytes!("../../../assets/icon/terminal.png");
pub fn set_window_position(pos: GuiPosition) {
POSITION.lock().unwrap().replace(pos);
}
pub fn set_window_class(cls: &str) {
*WINDOW_CLASS.lock().unwrap() = cls.to_owned();
}
pub fn get_window_class() -> String {
WINDOW_CLASS.lock().unwrap().clone()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MouseCapture {
UI,
TerminalPane(PaneId),
}
/// 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,
tx: Option<Sender<anyhow::Result<()>>>,
},
SetLeftStatus(String),
SetRightStatus(String),
GetDimensions(Sender<(Dimensions, WindowState)>),
GetSelectionForPane {
pane_id: PaneId,
tx: Sender<String>,
},
GetEffectiveConfig(Sender<ConfigHandle>),
FinishWindowEvent {
name: String,
again: bool,
},
GetConfigOverrides(Sender<wezterm_dynamic::Value>),
SetConfigOverrides(wezterm_dynamic::Value),
CancelOverlayForPane(PaneId),
CancelOverlayForTab {
tab_id: TabId,
pane_id: Option<PaneId>,
},
MuxNotification(MuxNotification),
EmitStatusUpdate,
Apply(Box<dyn FnOnce(&mut TermWindow) + Send + Sync>),
SwitchToMuxWindow(MuxWindowId),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum UIItemType {
TabBar(TabBarItem),
CloseTab(usize),
AboveScrollThumb,
ScrollThumb,
BelowScrollThumb,
Split(PositionedSplit),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UIItem {
pub x: usize,
pub y: usize,
pub width: usize,
pub height: usize,
pub item_type: UIItemType,
}
impl UIItem {
pub fn hit_test(&self, x: isize, y: isize) -> bool {
x >= self.x as isize
&& x <= (self.x + self.width) as isize
&& y >= self.y as isize
&& y <= (self.y + self.height) as isize
}
}
#[derive(Clone, Default)]
pub struct SemanticZoneCache {
seqno: SequenceNo,
zones: Vec<StableRowIndex>,
}
pub struct OverlayState {
pub pane: Arc<dyn Pane>,
pub key_table_state: KeyTableState,
}
#[derive(Default)]
pub struct PaneState {
/// If is_some(), the top row of the visible screen.
/// Otherwise, the viewport is at the bottom of the
/// scrollback.
viewport: Option<StableRowIndex>,
selection: Selection,
/// If is_some(), rather than display the actual tab
/// contents, we're overlaying a little internal application
/// tab. We'll also route input to it.
pub overlay: Option<OverlayState>,
bell_start: Option<Instant>,
pub mouse_terminal_coords: Option<(ClickPosition, StableRowIndex)>,
}
/// Data used when synchronously formatting pane and window titles
#[derive(Debug, Clone)]
pub struct TabInformation {
pub tab_id: TabId,
pub tab_index: usize,
pub is_active: bool,
pub active_pane: Option<PaneInformation>,
pub window_id: MuxWindowId,
pub tab_title: String,
}
impl UserData for TabInformation {
fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_field_method_get("tab_id", |_, this| Ok(this.tab_id));
fields.add_field_method_get("tab_index", |_, this| Ok(this.tab_index));
fields.add_field_method_get("is_active", |_, this| Ok(this.is_active));
fields.add_field_method_get("active_pane", |_, this| {
if let Some(pane) = &this.active_pane {
Ok(Some(pane.clone()))
} else {
Ok(None)
}
});
fields.add_field_method_get("panes", |_, this| {
let mux = Mux::get();
let mut panes = vec![];
if let Some(tab) = mux.get_tab(this.tab_id) {
panes = tab
.iter_panes()
.iter()
.map(TermWindow::pos_pane_to_pane_info)
.collect();
}
Ok(panes)
});
fields.add_field_method_get("window_id", |_, this| Ok(this.window_id));
fields.add_field_method_get("tab_title", |_, this| Ok(this.tab_title.clone()));
fields.add_field_method_get("window_title", |_, this| {
let mux = Mux::get();
let window = mux.get_window(this.window_id).ok_or_else(|| {
mlua::Error::external(format!("window {} not found", this.window_id))
})?;
Ok(window.get_title().to_string())
});
}
}
/// Data used when synchronously formatting pane and window titles
#[derive(Debug, Clone)]
pub struct PaneInformation {
pub pane_id: PaneId,
pub pane_index: usize,
pub is_active: bool,
pub is_zoomed: bool,
pub has_unseen_output: bool,
pub left: usize,
pub top: usize,
pub width: usize,
pub height: usize,
pub pixel_width: usize,
pub pixel_height: usize,
pub title: String,
pub user_vars: HashMap<String, String>,
}
impl UserData for PaneInformation {
fn add_fields<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_field_method_get("pane_id", |_, this| Ok(this.pane_id));
fields.add_field_method_get("pane_index", |_, this| Ok(this.pane_index));
fields.add_field_method_get("is_active", |_, this| Ok(this.is_active));
fields.add_field_method_get("is_zoomed", |_, this| Ok(this.is_zoomed));
fields.add_field_method_get("has_unseen_output", |_, this| Ok(this.has_unseen_output));
fields.add_field_method_get("left", |_, this| Ok(this.left));
fields.add_field_method_get("top", |_, this| Ok(this.top));
fields.add_field_method_get("width", |_, this| Ok(this.width));
fields.add_field_method_get("height", |_, this| Ok(this.height));
fields.add_field_method_get("pixel_width", |_, this| Ok(this.pixel_width));
fields.add_field_method_get("pixel_height", |_, this| Ok(this.pixel_width));
fields.add_field_method_get("title", |_, this| Ok(this.title.clone()));
fields.add_field_method_get("user_vars", |_, this| Ok(this.user_vars.clone()));
fields.add_field_method_get("foreground_process_name", |_, this| {
let mut name = None;
if let Some(mux) = Mux::try_get() {
if let Some(pane) = mux.get_pane(this.pane_id) {
name = pane.get_foreground_process_name();
}
}
match name {
Some(name) => Ok(name),
None => Ok("".to_string()),
}
});
fields.add_field_method_get("tty_name", |_, this| {
let mut name = None;
if let Some(mux) = Mux::try_get() {
if let Some(pane) = mux.get_pane(this.pane_id) {
name = pane.tty_name();
}
}
Ok(name)
});
fields.add_field_method_get("current_working_dir", |_, this| {
if let Some(mux) = Mux::try_get() {
if let Some(pane) = mux.get_pane(this.pane_id) {
return Ok(pane
.get_current_working_dir()
.map(|url| url_funcs::Url { url }));
}
}
Ok(None)
});
fields.add_field_method_get("domain_name", |_, this| {
let mut name = None;
if let Some(mux) = Mux::try_get() {
if let Some(pane) = mux.get_pane(this.pane_id) {
let domain_id = pane.domain_id();
name = mux
.get_domain(domain_id)
.map(|dom| dom.domain_name().to_string());
}
}
match name {
Some(name) => Ok(name),
None => Ok("".to_string()),
}
});
}
}
#[derive(Default)]
pub struct TabState {
/// If is_some(), rather than display the actual tab
/// contents, we're overlaying a little internal application
/// tab. We'll also route input to it.
pub overlay: Option<OverlayState>,
}
/// Manages the state/queue of lua based event handlers.
/// We don't want to queue more than 1 event at a time,
/// so we use this enum to allow for at most 1 executing
/// and 1 pending event.
#[derive(Copy, Clone, Debug)]
enum EventState {
/// The event is not running
None,
/// The event is running
InProgress,
/// The event is running, and we have another one ready to
/// run once it completes
InProgressWithQueued(Option<PaneId>),
}
pub struct TermWindow {
pub window: Option<Window>,
pub config: ConfigHandle,
pub config_overrides: wezterm_dynamic::Value,
os_parameters: Option<parameters::Parameters>,
/// When we most recently received keyboard focus
pub focused: Option<Instant>,
fonts: Rc<FontConfiguration>,
/// Window dimensions and dpi
pub dimensions: Dimensions,
pub window_state: WindowState,
/// Terminal dimensions
terminal_size: TerminalSize,
pub mux_window_id: MuxWindowId,
pub mux_window_id_for_subscriptions: Arc<Mutex<MuxWindowId>>,
pub render_metrics: RenderMetrics,
render_state: Option<RenderState>,
input_map: InputMap,
/// If is_some, the LEADER modifier is active until the specified instant.
leader_is_down: Option<std::time::Instant>,
dead_key_status: DeadKeyStatus,
key_table_state: KeyTableState,
show_tab_bar: bool,
show_scroll_bar: bool,
tab_bar: TabBarState,
fancy_tab_bar: Option<box_model::ComputedElement>,
pub right_status: String,
pub left_status: String,
last_ui_item: Option<UIItem>,
/// Tracks whether the current mouse-down event is part of click-focus.
/// If so, we ignore mouse events until released
is_click_to_focus_window: bool,
last_mouse_coords: (usize, i64),
window_drag_position: Option<MouseEvent>,
current_mouse_event: Option<MouseEvent>,
prev_cursor: PrevCursorPos,
last_scroll_info: RenderableDimensions,
tab_state: RefCell<HashMap<TabId, TabState>>,
pane_state: RefCell<HashMap<PaneId, PaneState>>,
semantic_zones: HashMap<PaneId, SemanticZoneCache>,
window_background: Vec<LoadedBackgroundLayer>,
current_modifier_and_leds: (Modifiers, KeyboardLedStatus),
current_mouse_buttons: Vec<MousePress>,
current_mouse_capture: Option<MouseCapture>,
opengl_info: Option<String>,
/// Keeps track of double and triple clicks
last_mouse_click: Option<LastMouseClick>,
/// The URL over which we are currently hovering
current_highlight: Option<Arc<Hyperlink>>,
quad_generation: usize,
shape_generation: usize,
shape_cache: RefCell<LfuCache<ShapeCacheKey, anyhow::Result<Rc<Vec<ShapedInfo>>>>>,
line_to_ele_shape_cache: RefCell<LfuCache<LineToEleShapeCacheKey, LineToElementShapeItem>>,
line_state_cache: RefCell<LfuCacheU64<Arc<CachedLineState>>>,
next_line_state_id: u64,
line_quad_cache: RefCell<LfuCache<LineQuadCacheKey, LineQuadCacheValue>>,
last_status_call: Instant,
cursor_blink_state: RefCell<ColorEase>,
blink_state: RefCell<ColorEase>,
rapid_blink_state: RefCell<ColorEase>,
palette: Option<ColorPalette>,
ui_items: Vec<UIItem>,
dragging: Option<(UIItem, MouseEvent)>,
modal: RefCell<Option<Rc<dyn Modal>>>,
event_states: HashMap<String, EventState>,
pub current_event: Option<Value>,
has_animation: RefCell<Option<Instant>>,
/// We use this to attempt to do something reasonable
/// if we run out of texture space
allow_images: AllowImage,
scheduled_animation: RefCell<Option<Instant>>,
created: Instant,
pub last_frame_duration: Duration,
last_fps_check_time: Instant,
num_frames: usize,
pub fps: f32,
connection_name: String,
gl: Option<Rc<glium::backend::Context>>,
webgpu: Option<Rc<WebGpuState>>,
config_subscription: Option<config::ConfigSubscription>,
}
impl TermWindow {
fn load_os_parameters(&mut self) {
if let Some(ref window) = self.window {
self.os_parameters = match window.get_os_parameters(&self.config, self.window_state) {
Ok(os_parameters) => os_parameters,
Err(err) => {
log::warn!("Error while getting OS parameters: {:#}", err);
None
}
};
}
}
fn close_requested(&mut self, window: &Window) {
let mux = Mux::get();
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);
window.close();
front_end().forget_known_window(window);
}
WindowCloseConfirmation::AlwaysPrompt => {
let tab = match mux.get_active_tab_for_window(self.mux_window_id) {
Some(tab) => tab,
None => {
mux.kill_window(self.mux_window_id);
window.close();
front_end().forget_known_window(window);
return;
}
};
let mux_window_id = self.mux_window_id;
let can_close = mux
.get_window(mux_window_id)
.map_or(false, |w| w.can_close_without_prompting());
if can_close {
mux.kill_window(self.mux_window_id);
window.close();
front_end().forget_known_window(window);
return;
}
let window = self.window.clone().unwrap();
let (overlay, future) = start_overlay(self, &tab, move |tab_id, term| {
confirm_close_window(term, mux_window_id, window, tab_id)
});
self.assign_overlay(tab.tab_id(), overlay);
promise::spawn::spawn(future).detach();
// Don't close right now; let the close happen from
// the confirmation overlay
}
}
}
fn focus_changed(&mut self, focused: bool, window: &Window) {
log::trace!("Setting focus to {:?}", focused);
self.focused = if focused { Some(Instant::now()) } else { None };
self.quad_generation += 1;
self.load_os_parameters();
if self.focused.is_none() {
self.last_mouse_click = None;
self.current_mouse_buttons.clear();
self.current_mouse_capture = None;
self.is_click_to_focus_window = false;
for state in self.pane_state.borrow_mut().values_mut() {
state.mouse_terminal_coords.take();
}
}
// Reset the cursor blink phase
self.prev_cursor.bump();
// force cursor to be repainted
window.invalidate();
if let Some(pane) = self.get_active_pane_or_overlay() {
pane.focus_changed(focused);
}
self.update_title();
self.emit_window_event("window-focus-changed", None);
}
fn created(&mut self, ctx: RenderContext) -> anyhow::Result<()> {
self.render_state = None;
let render_info = ctx.renderer_info();
self.opengl_info.replace(render_info.clone());
match RenderState::new(ctx, &self.fonts, &self.render_metrics, ATLAS_SIZE) {
Ok(render_state) => {
log::debug!(
"OpenGL initialized! {} wezterm version: {}",
render_info,
config::wezterm_version(),
);
self.render_state.replace(render_state);
}
Err(err) => {
log::error!("failed to create RenderState: {}", err);
}
}
if self.render_state.is_none() {
panic!("No OpenGL");
}
Ok(())
}
}
impl TermWindow {
pub async fn new_window(mux_window_id: MuxWindowId) -> anyhow::Result<()> {
let config = configuration();
let dpi = config.dpi.unwrap_or_else(|| ::window::default_dpi()) as usize;
let fontconfig = Rc::new(FontConfiguration::new(Some(config.clone()), dpi)?);
let mux = Mux::get();
let size = match mux.get_active_tab_for_window(mux_window_id) {
Some(tab) => tab.get_size(),
None => {
log::debug!("new_window has no tabs... yet?");
Default::default()
}
};
let physical_rows = size.rows as usize;
let physical_cols = size.cols as usize;
let render_metrics = RenderMetrics::new(&fontconfig)?;
log::trace!("using render_metrics {:#?}", render_metrics);
// Initially we have only a single tab, so take that into account
// for the tab bar state.
let show_tab_bar = config.enable_tab_bar && !config.hide_tab_bar_if_only_one_tab;
let tab_bar_height = if show_tab_bar {
Self::tab_bar_pixel_height_impl(&config, &fontconfig, &render_metrics)? as usize
} else {
0
};
let terminal_size = TerminalSize {
rows: physical_rows,
cols: physical_cols,
pixel_width: (render_metrics.cell_size.width as usize * physical_cols),
pixel_height: (render_metrics.cell_size.height as usize * physical_rows),
dpi: dpi as u32,
};
if terminal_size != size {
// DPI is different from the default assumed DPI when the mux
// created the pty. We need to inform the kernel of the revised
// pixel geometry now
log::trace!(
"Initial geometry was {:?} but dpi-adjusted geometry \
is {:?}; update the kernel pixel geometry for the ptys!",
size,
terminal_size,
);
if let Some(window) = mux.get_window(mux_window_id) {
for tab in window.iter() {
tab.resize(terminal_size);
}
};
}
let h_context = DimensionContext {
dpi: dpi as f32,
pixel_max: terminal_size.pixel_width as f32,
pixel_cell: render_metrics.cell_size.width as f32,
};
let padding_left = config.window_padding.left.evaluate_as_pixels(h_context) as usize;
let padding_right = resize::effective_right_padding(&config, h_context) as usize;
let v_context = DimensionContext {
dpi: dpi as f32,
pixel_max: terminal_size.pixel_height as f32,
pixel_cell: render_metrics.cell_size.height as f32,
};
let padding_top = config.window_padding.top.evaluate_as_pixels(v_context) as usize;
let padding_bottom = config.window_padding.bottom.evaluate_as_pixels(v_context) as usize;
let mut dimensions = Dimensions {
pixel_width: (terminal_size.pixel_width + padding_left + padding_right) as usize,
pixel_height: ((terminal_size.rows * render_metrics.cell_size.height as usize)
+ padding_top
+ padding_bottom) as usize
+ tab_bar_height,
dpi,
};
let border = Self::get_os_border_impl(&None, &config, &dimensions, &render_metrics);
dimensions.pixel_height += (border.top + border.bottom).get() as usize;
dimensions.pixel_width += (border.left + border.right).get() as usize;
let window_background = load_background_image(&config, &dimensions, &render_metrics);
log::trace!(
"TermWindow::new_window called with mux_window_id {} {:?} {:?}",
mux_window_id,
terminal_size,
dimensions
);
let render_state = None;
let connection_name = Connection::get().unwrap().name();
let myself = Self {
created: Instant::now(),
connection_name,
last_fps_check_time: Instant::now(),
num_frames: 0,
last_frame_duration: Duration::ZERO,
fps: 0.,
config_subscription: None,
os_parameters: None,
gl: None,
webgpu: None,
window: None,
window_background,
config: config.clone(),
config_overrides: wezterm_dynamic::Value::default(),
palette: None,
focused: None,
mux_window_id,
mux_window_id_for_subscriptions: Arc::new(Mutex::new(mux_window_id)),
fonts: Rc::clone(&fontconfig),
render_metrics,
dimensions,
window_state: WindowState::default(),
terminal_size,
render_state,
input_map: InputMap::new(&config),
leader_is_down: None,
dead_key_status: DeadKeyStatus::None,
show_tab_bar,
show_scroll_bar: config.enable_scroll_bar,
tab_bar: TabBarState::default(),
fancy_tab_bar: None,
right_status: String::new(),
left_status: String::new(),
last_mouse_coords: (0, -1),
window_drag_position: None,
current_mouse_event: None,
current_modifier_and_leds: Default::default(),
prev_cursor: PrevCursorPos::new(),
last_scroll_info: RenderableDimensions::default(),
tab_state: RefCell::new(HashMap::new()),
pane_state: RefCell::new(HashMap::new()),
current_mouse_buttons: vec![],
current_mouse_capture: None,
last_mouse_click: None,
current_highlight: None,
quad_generation: 0,
shape_generation: 0,
shape_cache: RefCell::new(LfuCache::new(
"shape_cache.hit.rate",
"shape_cache.miss.rate",
|config| config.shape_cache_size,
&config,
)),
line_state_cache: RefCell::new(LfuCacheU64::new(
"line_state_cache.hit.rate",
"line_state_cache.miss.rate",
|config| config.line_state_cache_size,
&config,
)),
next_line_state_id: 0,
line_quad_cache: RefCell::new(LfuCache::new(
"line_quad_cache.hit.rate",
"line_quad_cache.miss.rate",
|config| config.line_quad_cache_size,
&config,
)),
line_to_ele_shape_cache: RefCell::new(LfuCache::new(
"line_to_ele_shape_cache.hit.rate",
"line_to_ele_shape_cache.miss.rate",
|config| config.line_to_ele_shape_cache_size,
&config,
)),
last_status_call: Instant::now(),
cursor_blink_state: RefCell::new(ColorEase::new(
config.cursor_blink_rate,
config.cursor_blink_ease_in,
config.cursor_blink_rate,
config.cursor_blink_ease_out,
None,
)),
blink_state: RefCell::new(ColorEase::new(
config.text_blink_rate,
config.text_blink_ease_in,
config.text_blink_rate,
config.text_blink_ease_out,
None,
)),
rapid_blink_state: RefCell::new(ColorEase::new(
config.text_blink_rate_rapid,
config.text_blink_rapid_ease_in,
config.text_blink_rate_rapid,
config.text_blink_rapid_ease_out,
None,
)),
event_states: HashMap::new(),
current_event: None,
has_animation: RefCell::new(None),
scheduled_animation: RefCell::new(None),
allow_images: AllowImage::Yes,
semantic_zones: HashMap::new(),
ui_items: vec![],
dragging: None,
last_ui_item: None,
is_click_to_focus_window: false,
key_table_state: KeyTableState::default(),
modal: RefCell::new(None),
opengl_info: None,
};
let tw = Rc::new(RefCell::new(myself));
let tw_event = Rc::clone(&tw);
let mut x = None;
let mut y = None;
let mut origin = GeometryOrigin::default();
if let Some(position) = mux
.get_window(mux_window_id)
.and_then(|window| window.get_initial_position().clone())
.or_else(|| POSITION.lock().unwrap().take())
{
x.replace(position.x);
y.replace(position.y);
origin = position.origin;
}
let geometry = RequestedWindowGeometry {
width: Dimension::Pixels(dimensions.pixel_width as f32),
height: Dimension::Pixels(dimensions.pixel_height as f32),
x,
y,
origin,
};
log::trace!("{:?}", geometry);
let window = Window::new_window(
&get_window_class(),
"wezterm",
geometry,
Some(&config),
Rc::clone(&fontconfig),
move |event, window| {
let mut tw = tw_event.borrow_mut();
if let Err(err) = tw.dispatch_window_event(event, window) {
log::error!("dispatch_window_event: {:#}", err);
}
},
)
.await?;
tw.borrow_mut().window.replace(window.clone());
Self::apply_icon(&window)?;
let config_subscription = config::subscribe_to_config_reload({
let window = window.clone();
move || {
window.notify(TermWindowNotif::Apply(Box::new(|tw| {
tw.config_was_reloaded()
})));
true
}
});
let gl = match config.front_end {
FrontEndSelection::WebGpu => None,
_ => Some(window.enable_opengl().await?),
};
{
let mut myself = tw.borrow_mut();
let webgpu = match config.front_end {
FrontEndSelection::WebGpu => Some(Rc::new(
WebGpuState::new(&window, dimensions, &config).await?,
)),
_ => None,
};
myself.config_subscription.replace(config_subscription);
if config.use_resize_increments {
window.set_resize_increments(
myself.render_metrics.cell_size.width as u16,
myself.render_metrics.cell_size.height as u16,
);
}
if let Some(gl) = gl {
myself.gl.replace(Rc::clone(&gl));
myself.created(RenderContext::Glium(Rc::clone(&gl)))?;
}
if let Some(webgpu) = webgpu {
myself.webgpu.replace(Rc::clone(&webgpu));
myself.created(RenderContext::WebGpu(Rc::clone(&webgpu)))?;
}
myself.load_os_parameters();
window.show();
myself.subscribe_to_pane_updates();
myself.emit_window_event("window-config-reloaded", None);
myself.emit_status_event();
}
crate::update::start_update_checker();
front_end().record_known_window(window, mux_window_id);
Ok(())
}
fn dispatch_window_event(
&mut self,
event: WindowEvent,
window: &Window,
) -> anyhow::Result<bool> {
log::debug!("{event:?}");
match event {
WindowEvent::Destroyed => {
// Ensure that we cancel any overlays we had running, so
// that the mux can empty out, otherwise the mux keeps
// the TermWindow alive via the frontend even though
// the window is gone and we'll linger forever.
// <https://github.com/wez/wezterm/issues/3522>
self.clear_all_overlays();
Ok(false)
}
WindowEvent::CloseRequested => {
self.close_requested(window);
Ok(true)
}
WindowEvent::AppearanceChanged(appearance) => {
log::debug!("Appearance is now {:?}", appearance);
// This is a bit fugly; we get per-window notifications
// for appearance changes which successfully updates the
// per-window config, but we need to explicitly tell the
// global config to reload, otherwise things that acces
// the config via config::configuration() will see the
// prior version of the config.
// What's fugly about this is that we'll reload the
// global config here once per window, which could
// be nasty for folks with a lot of windows.
// <https://github.com/wez/wezterm/issues/2295>
config::reload();
self.config_was_reloaded();
Ok(true)
}
WindowEvent::PerformKeyAssignment(action) => {
if let Some(pane) = self.get_active_pane_or_overlay() {
self.perform_key_assignment(&pane, &action)?;
window.invalidate();
}
Ok(true)
}
WindowEvent::FocusChanged(focused) => {
self.focus_changed(focused, window);
Ok(true)
}
WindowEvent::MouseEvent(event) => {
self.mouse_event_impl(event, window);
Ok(true)
}
WindowEvent::MouseLeave => {
self.mouse_leave_impl(window);
Ok(true)
}
WindowEvent::Resized {
dimensions,
window_state,
live_resizing,
} => {
self.resize(dimensions, window_state, window, live_resizing);
Ok(true)
}
WindowEvent::AdviseModifiersLedStatus(modifiers, leds) => {
self.current_modifier_and_leds = (modifiers, leds);
self.update_title();
window.invalidate();
Ok(true)
}
WindowEvent::RawKeyEvent(event) => {
self.raw_key_event_impl(event, window);
Ok(true)
}
WindowEvent::KeyEvent(event) => {
self.key_event_impl(event, window);
Ok(true)
}
WindowEvent::AdviseDeadKeyStatus(status) => {
log::trace!("DeadKeyStatus now: {:?}", status);
self.dead_key_status = status;
self.update_title();
// Ensure that we repaint so that any composing
// text is updated
window.invalidate();
Ok(true)
}
WindowEvent::NeedRepaint if self.webgpu.is_some() => self.do_paint_webgpu(),
WindowEvent::NeedRepaint => Ok(self.do_paint(window)),
WindowEvent::Notification(item) => {
if let Ok(notif) = item.downcast::<TermWindowNotif>() {
self.dispatch_notif(*notif, window)
.context("dispatch_notif")?;
}
Ok(true)
}
WindowEvent::DroppedFile(paths) => {
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return Ok(true),
};
let paths = paths
.iter()
.map(|path| {
self.config
.quote_dropped_files
.escape(&path.to_string_lossy())
})
.collect::<Vec<_>>()
.join(" ");
pane.send_paste(&paths)?;
Ok(true)
}
WindowEvent::DraggedFile(_) => Ok(true),
}
}
fn do_paint(&mut self, window: &Window) -> bool {
let gl = match self.gl.as_ref() {
Some(gl) => gl,
None => return false,
};
if gl.is_context_lost() {
log::error!("opengl context was lost; should reinit");
window.close();
front_end().forget_known_window(window);
return false;
}
let mut frame = glium::Frame::new(