-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
lib.rs
1451 lines (1284 loc) · 47.4 KB
/
lib.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
use crate::client::{ClientId, ClientInfo};
use crate::pane::{CachePolicy, Pane, PaneId};
use crate::ssh_agent::AgentProxy;
use crate::tab::{SplitRequest, Tab, TabId};
use crate::window::{Window, WindowId};
use anyhow::{anyhow, Context, Error};
use config::keyassignment::SpawnTabDomain;
use config::{configuration, ExitBehavior, GuiPosition};
use domain::{Domain, DomainId, DomainState, SplitSource};
use filedescriptor::{poll, pollfd, socketpair, AsRawSocketDescriptor, FileDescriptor, POLLIN};
#[cfg(unix)]
use libc::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};
use log::error;
use metrics::histogram;
use parking_lot::{
MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard,
};
use percent_encoding::percent_decode_str;
use portable_pty::{CommandBuilder, ExitStatus, PtySize};
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Weak};
use std::thread;
use std::time::{Duration, Instant};
use termwiz::escape::csi::{DecPrivateMode, DecPrivateModeCode, Device, Mode};
use termwiz::escape::{Action, CSI};
use thiserror::*;
use wezterm_term::{Clipboard, ClipboardSelection, DownloadHandler, TerminalSize};
#[cfg(windows)]
use winapi::um::winsock2::{SOL_SOCKET, SO_RCVBUF, SO_SNDBUF};
pub mod activity;
pub mod client;
pub mod connui;
pub mod domain;
pub mod localpane;
pub mod pane;
pub mod renderable;
pub mod ssh;
pub mod ssh_agent;
pub mod tab;
pub mod termwiztermtab;
pub mod tmux;
pub mod tmux_commands;
mod tmux_pty;
pub mod window;
use crate::activity::Activity;
pub const DEFAULT_WORKSPACE: &str = "default";
#[derive(Clone, Debug)]
pub enum MuxNotification {
PaneOutput(PaneId),
PaneAdded(PaneId),
PaneRemoved(PaneId),
WindowCreated(WindowId),
WindowRemoved(WindowId),
WindowInvalidated(WindowId),
WindowWorkspaceChanged(WindowId),
ActiveWorkspaceChanged(Arc<ClientId>),
Alert {
pane_id: PaneId,
alert: wezterm_term::Alert,
},
Empty,
AssignClipboard {
pane_id: PaneId,
selection: ClipboardSelection,
clipboard: Option<String>,
},
SaveToDownloads {
name: Option<String>,
data: Arc<Vec<u8>>,
},
TabAddedToWindow {
tab_id: TabId,
window_id: WindowId,
},
PaneFocused(PaneId),
TabResized(TabId),
TabTitleChanged {
tab_id: TabId,
title: String,
},
WindowTitleChanged {
window_id: WindowId,
title: String,
},
WorkspaceRenamed {
old_workspace: String,
new_workspace: String,
},
}
static SUB_ID: AtomicUsize = AtomicUsize::new(0);
pub struct Mux {
tabs: RwLock<HashMap<TabId, Arc<Tab>>>,
panes: RwLock<HashMap<PaneId, Arc<dyn Pane>>>,
windows: RwLock<HashMap<WindowId, Window>>,
default_domain: RwLock<Option<Arc<dyn Domain>>>,
domains: RwLock<HashMap<DomainId, Arc<dyn Domain>>>,
domains_by_name: RwLock<HashMap<String, Arc<dyn Domain>>>,
subscribers: RwLock<HashMap<usize, Box<dyn Fn(MuxNotification) -> bool + Send + Sync>>>,
banner: RwLock<Option<String>>,
clients: RwLock<HashMap<ClientId, ClientInfo>>,
identity: RwLock<Option<Arc<ClientId>>>,
num_panes_by_workspace: RwLock<HashMap<String, usize>>,
main_thread_id: std::thread::ThreadId,
agent: Option<AgentProxy>,
}
const BUFSIZE: usize = 1024 * 1024;
/// This function applies parsed actions to the pane and notifies any
/// mux subscribers about the output event
fn send_actions_to_mux(pane: &Weak<dyn Pane>, dead: &Arc<AtomicBool>, actions: Vec<Action>) {
let start = Instant::now();
match pane.upgrade() {
Some(pane) => {
pane.perform_actions(actions);
histogram!("send_actions_to_mux.perform_actions.latency").record(start.elapsed());
Mux::notify_from_any_thread(MuxNotification::PaneOutput(pane.pane_id()));
}
None => {
// Something else removed the pane from
// the mux, so signal that we should stop
// trying to process it in read_from_pane_pty.
dead.store(true, Ordering::Relaxed);
}
}
histogram!("send_actions_to_mux.rate").record(1.);
}
fn parse_buffered_data(pane: Weak<dyn Pane>, dead: &Arc<AtomicBool>, mut rx: FileDescriptor) {
let mut buf = vec![0; configuration().mux_output_parser_buffer_size];
let mut parser = termwiz::escape::parser::Parser::new();
let mut actions = vec![];
let mut hold = false;
let mut action_size = 0;
let mut delay = Duration::from_millis(configuration().mux_output_parser_coalesce_delay_ms);
let mut deadline = None;
loop {
match rx.read(&mut buf) {
Ok(size) if size == 0 => {
dead.store(true, Ordering::Relaxed);
break;
}
Err(_) => {
dead.store(true, Ordering::Relaxed);
break;
}
Ok(size) => {
parser.parse(&buf[0..size], |action| {
let mut flush = false;
match &action {
Action::CSI(CSI::Mode(Mode::SetDecPrivateMode(DecPrivateMode::Code(
DecPrivateModeCode::SynchronizedOutput,
)))) => {
hold = true;
// Flush prior actions
if !actions.is_empty() {
send_actions_to_mux(&pane, &dead, std::mem::take(&mut actions));
action_size = 0;
}
}
Action::CSI(CSI::Mode(Mode::ResetDecPrivateMode(
DecPrivateMode::Code(DecPrivateModeCode::SynchronizedOutput),
))) => {
hold = false;
flush = true;
}
Action::CSI(CSI::Device(dev)) if matches!(**dev, Device::SoftReset) => {
hold = false;
flush = true;
}
_ => {}
};
action.append_to(&mut actions);
if flush && !actions.is_empty() {
send_actions_to_mux(&pane, &dead, std::mem::take(&mut actions));
action_size = 0;
}
});
action_size += size;
if !actions.is_empty() && !hold {
// If we haven't accumulated too much data,
// pause for a short while to increase the chances
// that we coalesce a full "frame" from an unoptimized
// TUI program
if action_size < buf.len() {
let poll_delay = match deadline {
None => {
deadline.replace(Instant::now() + delay);
Some(delay)
}
Some(target) => target.checked_duration_since(Instant::now()),
};
if poll_delay.is_some() {
let mut pfd = [pollfd {
fd: rx.as_socket_descriptor(),
events: POLLIN,
revents: 0,
}];
if let Ok(1) = poll(&mut pfd, poll_delay) {
// We can read now without blocking, so accumulate
// more data into actions
continue;
}
// Not readable in time: let the data we have flow into
// the terminal model
}
}
send_actions_to_mux(&pane, &dead, std::mem::take(&mut actions));
deadline = None;
action_size = 0;
}
let config = configuration();
buf.resize(config.mux_output_parser_buffer_size, 0);
delay = Duration::from_millis(config.mux_output_parser_coalesce_delay_ms);
}
}
}
// Don't forget to send anything that we might have buffered
// to be displayed before we return from here; this is important
// for very short lived commands so that we don't forget to
// display what they displayed.
if !actions.is_empty() {
send_actions_to_mux(&pane, &dead, std::mem::take(&mut actions));
}
}
fn set_socket_buffer(fd: &mut FileDescriptor, option: i32, size: usize) -> anyhow::Result<()> {
let socklen = std::mem::size_of_val(&size);
unsafe {
let res = libc::setsockopt(
fd.as_socket_descriptor(),
SOL_SOCKET,
option,
&size as *const usize as *const _,
socklen as _,
);
if res == 0 {
Ok(())
} else {
Err(std::io::Error::last_os_error()).context("setsockopt")
}
}
}
fn allocate_socketpair() -> anyhow::Result<(FileDescriptor, FileDescriptor)> {
let (mut tx, mut rx) = socketpair().context("socketpair")?;
set_socket_buffer(&mut tx, SO_SNDBUF, BUFSIZE).context("SO_SNDBUF")?;
set_socket_buffer(&mut rx, SO_RCVBUF, BUFSIZE).context("SO_RCVBUF")?;
Ok((tx, rx))
}
/// This function is run in a separate thread; its purpose is to perform
/// blocking reads from the pty (non-blocking reads are not portable to
/// all platforms and pty/tty types), parse the escape sequences and
/// relay the actions to the mux thread to apply them to the pane.
fn read_from_pane_pty(
pane: Weak<dyn Pane>,
banner: Option<String>,
mut reader: Box<dyn std::io::Read>,
) {
let mut buf = vec![0; BUFSIZE];
// This is used to signal that an error occurred either in this thread,
// or in the main mux thread. If `true`, this thread will terminate.
let dead = Arc::new(AtomicBool::new(false));
let (pane_id, exit_behavior) = match pane.upgrade() {
Some(pane) => (pane.pane_id(), pane.exit_behavior()),
None => return,
};
let (mut tx, rx) = match allocate_socketpair() {
Ok(pair) => pair,
Err(err) => {
log::error!("read_from_pane_pty: Unable to allocate a socketpair: {err:#}");
localpane::emit_output_for_pane(
pane_id,
&format!(
"⚠️ wezterm: read_from_pane_pty: \
Unable to allocate a socketpair: {err:#}"
),
);
return;
}
};
std::thread::spawn({
let dead = Arc::clone(&dead);
move || parse_buffered_data(pane, &dead, rx)
});
if let Some(banner) = banner {
tx.write_all(banner.as_bytes()).ok();
}
while !dead.load(Ordering::Relaxed) {
match reader.read(&mut buf) {
Ok(size) if size == 0 => {
log::trace!("read_pty EOF: pane_id {}", pane_id);
break;
}
Err(err) => {
error!("read_pty failed: pane {} {:?}", pane_id, err);
break;
}
Ok(size) => {
histogram!("read_from_pane_pty.bytes.rate").record(size as f64);
log::trace!("read_pty pane {pane_id} read {size} bytes");
if let Err(err) = tx.write_all(&buf[..size]) {
error!(
"read_pty failed to write to parser: pane {} {:?}",
pane_id, err
);
break;
}
}
}
}
match exit_behavior.unwrap_or_else(|| configuration().exit_behavior) {
ExitBehavior::Hold | ExitBehavior::CloseOnCleanExit => {
// We don't know if we can unilaterally close
// this pane right now, so don't!
promise::spawn::spawn_into_main_thread(async move {
let mux = Mux::get();
log::trace!("checking for dead windows after EOF on pane {}", pane_id);
mux.prune_dead_windows();
})
.detach();
}
ExitBehavior::Close => {
promise::spawn::spawn_into_main_thread(async move {
let mux = Mux::get();
mux.remove_pane(pane_id);
})
.detach();
}
}
dead.store(true, Ordering::Relaxed);
}
lazy_static::lazy_static! {
static ref MUX: Mutex<Option<Arc<Mux>>> = Mutex::new(None);
}
pub struct MuxWindowBuilder {
window_id: WindowId,
activity: Option<Activity>,
notified: bool,
}
impl MuxWindowBuilder {
fn notify(&mut self) {
if self.notified {
return;
}
self.notified = true;
let activity = self.activity.take().unwrap();
let window_id = self.window_id;
let mux = Mux::get();
if mux.is_main_thread() {
// If we're already on the mux thread, just send the notification
// immediately.
// This is super important for Wayland; if we push it to the
// spawn queue below then the extra milliseconds of delay
// causes it to get confused and shutdown the connection!?
mux.notify(MuxNotification::WindowCreated(window_id));
} else {
promise::spawn::spawn_into_main_thread(async move {
if let Some(mux) = Mux::try_get() {
mux.notify(MuxNotification::WindowCreated(window_id));
drop(activity);
}
})
.detach();
}
}
}
impl Drop for MuxWindowBuilder {
fn drop(&mut self) {
self.notify();
}
}
impl std::ops::Deref for MuxWindowBuilder {
type Target = WindowId;
fn deref(&self) -> &WindowId {
&self.window_id
}
}
impl Mux {
pub fn new(default_domain: Option<Arc<dyn Domain>>) -> Self {
let mut domains = HashMap::new();
let mut domains_by_name = HashMap::new();
if let Some(default_domain) = default_domain.as_ref() {
domains.insert(default_domain.domain_id(), Arc::clone(default_domain));
domains_by_name.insert(
default_domain.domain_name().to_string(),
Arc::clone(default_domain),
);
}
let agent = if config::configuration().mux_enable_ssh_agent {
Some(AgentProxy::new())
} else {
None
};
Self {
tabs: RwLock::new(HashMap::new()),
panes: RwLock::new(HashMap::new()),
windows: RwLock::new(HashMap::new()),
default_domain: RwLock::new(default_domain),
domains_by_name: RwLock::new(domains_by_name),
domains: RwLock::new(domains),
subscribers: RwLock::new(HashMap::new()),
banner: RwLock::new(None),
clients: RwLock::new(HashMap::new()),
identity: RwLock::new(None),
num_panes_by_workspace: RwLock::new(HashMap::new()),
main_thread_id: std::thread::current().id(),
agent,
}
}
fn get_default_workspace(&self) -> String {
let config = configuration();
config
.default_workspace
.as_deref()
.unwrap_or(DEFAULT_WORKSPACE)
.to_string()
}
pub fn is_main_thread(&self) -> bool {
std::thread::current().id() == self.main_thread_id
}
fn recompute_pane_count(&self) {
let mut count = HashMap::new();
for window in self.windows.read().values() {
let workspace = window.get_workspace();
for tab in window.iter() {
*count.entry(workspace.to_string()).or_insert(0) += match tab.count_panes() {
Some(n) => n,
None => {
// Busy: abort this and we'll retry later
return;
}
};
}
}
*self.num_panes_by_workspace.write() = count;
}
pub fn client_had_input(&self, client_id: &ClientId) {
if let Some(info) = self.clients.write().get_mut(client_id) {
info.update_last_input();
}
if let Some(agent) = &self.agent {
agent.update_target();
}
}
pub fn record_input_for_current_identity(&self) {
if let Some(ident) = self.identity.read().as_ref() {
self.client_had_input(ident);
}
}
pub fn record_focus_for_current_identity(&self, pane_id: PaneId) {
if let Some(ident) = self.identity.read().as_ref() {
self.record_focus_for_client(ident, pane_id);
}
}
pub fn resolve_focused_pane(
&self,
client_id: &ClientId,
) -> Option<(DomainId, WindowId, TabId, PaneId)> {
let pane_id = self.clients.read().get(client_id)?.focused_pane_id?;
let (domain, window, tab) = self.resolve_pane_id(pane_id)?;
Some((domain, window, tab, pane_id))
}
pub fn record_focus_for_client(&self, client_id: &ClientId, pane_id: PaneId) {
let mut prior = None;
if let Some(info) = self.clients.write().get_mut(client_id) {
prior = info.focused_pane_id;
info.update_focused_pane(pane_id);
}
if prior == Some(pane_id) {
return;
}
// Synthesize focus events
if let Some(prior_id) = prior {
if let Some(pane) = self.get_pane(prior_id) {
pane.focus_changed(false);
}
}
if let Some(pane) = self.get_pane(pane_id) {
pane.focus_changed(true);
}
}
/// Called by PaneFocused event handlers to reconcile a remote
/// pane focus event and apply its effects locally
pub fn focus_pane_and_containing_tab(&self, pane_id: PaneId) -> anyhow::Result<()> {
let pane = self
.get_pane(pane_id)
.ok_or_else(|| anyhow::anyhow!("pane {pane_id} not found"))?;
let (_domain, window_id, tab_id) = self
.resolve_pane_id(pane_id)
.ok_or_else(|| anyhow::anyhow!("can't find {pane_id} in the mux"))?;
// Focus/activate the containing tab within its window
{
let mut win = self
.get_window_mut(window_id)
.ok_or_else(|| anyhow::anyhow!("window_id {window_id} not found"))?;
let tab_idx = win
.idx_by_id(tab_id)
.ok_or_else(|| anyhow::anyhow!("tab {tab_id} not in {window_id}"))?;
win.save_and_then_set_active(tab_idx);
}
// Focus/activate the pane locally
let tab = self
.get_tab(tab_id)
.ok_or_else(|| anyhow::anyhow!("tab {tab_id} not found"))?;
tab.set_active_pane(&pane);
Ok(())
}
pub fn register_client(&self, client_id: Arc<ClientId>) {
self.clients
.write()
.insert((*client_id).clone(), ClientInfo::new(client_id));
}
pub fn iter_clients(&self) -> Vec<ClientInfo> {
self.clients
.read()
.values()
.map(|info| info.clone())
.collect()
}
/// Returns a list of the unique workspace names known to the mux.
/// This is taken from all known windows.
pub fn iter_workspaces(&self) -> Vec<String> {
let mut names: Vec<String> = self
.windows
.read()
.values()
.map(|w| w.get_workspace().to_string())
.collect();
names.sort();
names.dedup();
names
}
/// Generate a new unique workspace name
pub fn generate_workspace_name(&self) -> String {
let used = self.iter_workspaces();
for candidate in names::Generator::default() {
if !used.contains(&candidate) {
return candidate;
}
}
unreachable!();
}
/// Returns the effective active workspace name
pub fn active_workspace(&self) -> String {
self.identity
.read()
.as_ref()
.and_then(|ident| {
self.clients
.read()
.get(&ident)
.and_then(|info| info.active_workspace.clone())
})
.unwrap_or_else(|| self.get_default_workspace())
}
/// Returns the effective active workspace name for a given client
pub fn active_workspace_for_client(&self, ident: &Arc<ClientId>) -> String {
self.clients
.read()
.get(&ident)
.and_then(|info| info.active_workspace.clone())
.unwrap_or_else(|| self.get_default_workspace())
}
pub fn set_active_workspace_for_client(&self, ident: &Arc<ClientId>, workspace: &str) {
let mut clients = self.clients.write();
if let Some(info) = clients.get_mut(&ident) {
info.active_workspace.replace(workspace.to_string());
self.notify(MuxNotification::ActiveWorkspaceChanged(ident.clone()));
}
}
/// Assigns the active workspace name for the current identity
pub fn set_active_workspace(&self, workspace: &str) {
if let Some(ident) = self.identity.read().clone() {
self.set_active_workspace_for_client(&ident, workspace);
}
}
pub fn rename_workspace(&self, old_workspace: &str, new_workspace: &str) {
if old_workspace == new_workspace {
return;
}
self.notify(MuxNotification::WorkspaceRenamed {
old_workspace: old_workspace.to_string(),
new_workspace: new_workspace.to_string(),
});
for window in self.windows.write().values_mut() {
if window.get_workspace() == old_workspace {
window.set_workspace(new_workspace);
}
}
self.recompute_pane_count();
for client in self.clients.write().values_mut() {
if client.active_workspace.as_deref() == Some(old_workspace) {
client.active_workspace.replace(new_workspace.to_string());
self.notify(MuxNotification::ActiveWorkspaceChanged(
client.client_id.clone(),
));
}
}
}
/// Overrides the current client identity.
/// Returns `IdentityHolder` which will restore the prior identity
/// when it is dropped.
/// This can be used to change the identity for the duration of a block.
pub fn with_identity(&self, id: Option<Arc<ClientId>>) -> IdentityHolder {
let prior = self.replace_identity(id);
IdentityHolder { prior }
}
/// Replace the identity, returning the prior identity
pub fn replace_identity(&self, id: Option<Arc<ClientId>>) -> Option<Arc<ClientId>> {
std::mem::replace(&mut *self.identity.write(), id)
}
/// Returns the active identity
pub fn active_identity(&self) -> Option<Arc<ClientId>> {
self.identity.read().clone()
}
pub fn unregister_client(&self, client_id: &ClientId) {
self.clients.write().remove(client_id);
}
pub fn subscribe<F>(&self, subscriber: F)
where
F: Fn(MuxNotification) -> bool + 'static + Send + Sync,
{
let sub_id = SUB_ID.fetch_add(1, Ordering::Relaxed);
self.subscribers
.write()
.insert(sub_id, Box::new(subscriber));
}
pub fn notify(&self, notification: MuxNotification) {
let mut subscribers = self.subscribers.write();
subscribers.retain(|_, notify| notify(notification.clone()));
}
pub fn notify_from_any_thread(notification: MuxNotification) {
if let Some(mux) = Mux::try_get() {
if mux.is_main_thread() {
mux.notify(notification);
return;
}
}
promise::spawn::spawn_into_main_thread(async {
if let Some(mux) = Mux::try_get() {
mux.notify(notification);
}
})
.detach();
}
pub fn default_domain(&self) -> Arc<dyn Domain> {
self.default_domain.read().as_ref().map(Arc::clone).unwrap()
}
pub fn set_default_domain(&self, domain: &Arc<dyn Domain>) {
*self.default_domain.write() = Some(Arc::clone(domain));
}
pub fn get_domain(&self, id: DomainId) -> Option<Arc<dyn Domain>> {
self.domains.read().get(&id).cloned()
}
pub fn get_domain_by_name(&self, name: &str) -> Option<Arc<dyn Domain>> {
self.domains_by_name.read().get(name).cloned()
}
pub fn add_domain(&self, domain: &Arc<dyn Domain>) {
if self.default_domain.read().is_none() {
*self.default_domain.write() = Some(Arc::clone(domain));
}
self.domains
.write()
.insert(domain.domain_id(), Arc::clone(domain));
self.domains_by_name
.write()
.insert(domain.domain_name().to_string(), Arc::clone(domain));
}
pub fn set_mux(mux: &Arc<Mux>) {
MUX.lock().replace(Arc::clone(mux));
}
pub fn shutdown() {
MUX.lock().take();
}
pub fn get() -> Arc<Mux> {
Self::try_get().unwrap()
}
pub fn try_get() -> Option<Arc<Mux>> {
MUX.lock().as_ref().map(Arc::clone)
}
pub fn get_pane(&self, pane_id: PaneId) -> Option<Arc<dyn Pane>> {
self.panes.read().get(&pane_id).map(Arc::clone)
}
pub fn get_tab(&self, tab_id: TabId) -> Option<Arc<Tab>> {
self.tabs.read().get(&tab_id).map(Arc::clone)
}
pub fn add_pane(&self, pane: &Arc<dyn Pane>) -> Result<(), Error> {
if self.panes.read().contains_key(&pane.pane_id()) {
return Ok(());
}
let clipboard: Arc<dyn Clipboard> = Arc::new(MuxClipboard {
pane_id: pane.pane_id(),
});
pane.set_clipboard(&clipboard);
let downloader: Arc<dyn DownloadHandler> = Arc::new(MuxDownloader {});
pane.set_download_handler(&downloader);
self.panes.write().insert(pane.pane_id(), Arc::clone(pane));
let pane_id = pane.pane_id();
if let Some(reader) = pane.reader()? {
let banner = self.banner.read().clone();
let pane = Arc::downgrade(pane);
thread::spawn(move || read_from_pane_pty(pane, banner, reader));
}
self.recompute_pane_count();
self.notify(MuxNotification::PaneAdded(pane_id));
Ok(())
}
pub fn add_tab_no_panes(&self, tab: &Arc<Tab>) {
self.tabs.write().insert(tab.tab_id(), Arc::clone(tab));
self.recompute_pane_count();
}
pub fn add_tab_and_active_pane(&self, tab: &Arc<Tab>) -> Result<(), Error> {
self.tabs.write().insert(tab.tab_id(), Arc::clone(tab));
let pane = tab
.get_active_pane()
.ok_or_else(|| anyhow!("tab MUST have an active pane"))?;
self.add_pane(&pane)
}
fn remove_pane_internal(&self, pane_id: PaneId) {
log::debug!("removing pane {}", pane_id);
if let Some(pane) = self.panes.write().remove(&pane_id).clone() {
log::debug!("killing pane {}", pane_id);
pane.kill();
self.recompute_pane_count();
self.notify(MuxNotification::PaneRemoved(pane_id));
}
}
fn remove_tab_internal(&self, tab_id: TabId) -> Option<Arc<Tab>> {
log::debug!("remove_tab_internal tab {}", tab_id);
let tab = self.tabs.write().remove(&tab_id)?;
if let Some(mut windows) = self.windows.try_write() {
for w in windows.values_mut() {
w.remove_by_id(tab_id);
}
}
let mut pane_ids = vec![];
for pos in tab.iter_panes_ignoring_zoom() {
pane_ids.push(pos.pane.pane_id());
}
log::debug!("panes to remove: {pane_ids:?}");
for pane_id in pane_ids {
self.remove_pane_internal(pane_id);
}
self.recompute_pane_count();
Some(tab)
}
fn remove_window_internal(&self, window_id: WindowId) {
log::debug!("remove_window_internal {}", window_id);
let window = self.windows.write().remove(&window_id);
if let Some(window) = window {
// Gather all the domains referenced by this window
let mut domains_of_window = HashSet::new();
for tab in window.iter() {
for pane in tab.iter_panes_ignoring_zoom() {
domains_of_window.insert(pane.pane.domain_id());
}
}
for domain_id in domains_of_window {
if let Some(domain) = self.get_domain(domain_id) {
if domain.detachable() {
log::info!("detaching domain");
if let Err(err) = domain.detach() {
log::error!(
"while detaching domain {domain_id} {}: {err:#}",
domain.domain_name()
);
}
}
}
}
for tab in window.iter() {
self.remove_tab_internal(tab.tab_id());
}
self.notify(MuxNotification::WindowRemoved(window_id));
}
self.recompute_pane_count();
}
pub fn remove_pane(&self, pane_id: PaneId) {
self.remove_pane_internal(pane_id);
self.prune_dead_windows();
}
pub fn remove_tab(&self, tab_id: TabId) -> Option<Arc<Tab>> {
let tab = self.remove_tab_internal(tab_id);
self.prune_dead_windows();
tab
}
pub fn prune_dead_windows(&self) {
if Activity::count() > 0 {
log::trace!("prune_dead_windows: Activity::count={}", Activity::count());
return;
}
let live_tab_ids: Vec<TabId> = self.tabs.read().keys().cloned().collect();
let mut dead_windows = vec![];
let dead_tab_ids: Vec<TabId>;
{
let mut windows = match self.windows.try_write() {
Some(w) => w,
None => {
// It's ok if our caller already locked it; we can prune later.
log::trace!("prune_dead_windows: self.windows already borrowed");
return;
}
};
for (window_id, win) in windows.iter_mut() {
win.prune_dead_tabs(&live_tab_ids);
if win.is_empty() {
log::trace!("prune_dead_windows: window is now empty");
dead_windows.push(*window_id);
}
}
dead_tab_ids = self
.tabs
.read()
.iter()
.filter_map(|(&id, tab)| if tab.is_dead() { Some(id) } else { None })
.collect();
}
for tab_id in dead_tab_ids {
log::trace!("tab {} is dead", tab_id);
self.remove_tab_internal(tab_id);
}
for window_id in dead_windows {
log::trace!("window {} is dead", window_id);
self.remove_window_internal(window_id);
}
if self.is_empty() {
log::trace!("prune_dead_windows: is_empty, send MuxNotification::Empty");
self.notify(MuxNotification::Empty);
} else {
log::trace!("prune_dead_windows: not empty");
}
}
pub fn kill_window(&self, window_id: WindowId) {
self.remove_window_internal(window_id);
self.prune_dead_windows();
}
pub fn get_window(&self, window_id: WindowId) -> Option<MappedRwLockReadGuard<Window>> {
if !self.windows.read().contains_key(&window_id) {
return None;
}
Some(RwLockReadGuard::map(self.windows.read(), |windows| {
windows.get(&window_id).unwrap()
}))
}
pub fn get_window_mut(&self, window_id: WindowId) -> Option<MappedRwLockWriteGuard<Window>> {
if !self.windows.read().contains_key(&window_id) {
return None;
}
Some(RwLockWriteGuard::map(self.windows.write(), |windows| {
windows.get_mut(&window_id).unwrap()
}))
}
pub fn get_active_tab_for_window(&self, window_id: WindowId) -> Option<Arc<Tab>> {
let window = self.get_window(window_id)?;
window.get_active().map(Arc::clone)
}
pub fn new_empty_window(
&self,
workspace: Option<String>,
position: Option<GuiPosition>,
) -> MuxWindowBuilder {
let window = Window::new(workspace, position);
let window_id = window.window_id();
self.windows.write().insert(window_id, window);
MuxWindowBuilder {
window_id,
activity: Some(Activity::new()),
notified: false,
}
}
pub fn add_tab_to_window(&self, tab: &Arc<Tab>, window_id: WindowId) -> anyhow::Result<()> {
let tab_id = tab.tab_id();
{
let mut window = self
.get_window_mut(window_id)
.ok_or_else(|| anyhow!("add_tab_to_window: no such window_id {}", window_id))?;
window.push(tab);
}
self.recompute_pane_count();
self.notify(MuxNotification::TabAddedToWindow { tab_id, window_id });
Ok(())
}
pub fn window_containing_tab(&self, tab_id: TabId) -> Option<WindowId> {
for w in self.windows.read().values() {
for t in w.iter() {
if t.tab_id() == tab_id {
return Some(w.window_id());
}
}
}