-
-
Notifications
You must be signed in to change notification settings - Fork 797
/
domain.rs
720 lines (635 loc) · 23.3 KB
/
domain.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
//! A Domain represents an instance of a multiplexer.
//! For example, the gui frontend has its own domain,
//! and we can connect to a domain hosted by a mux server
//! that may be local, running "remotely" inside a WSL
//! container or actually remote, running on the other end
//! of an ssh session somewhere.
use crate::localpane::LocalPane;
use crate::pane::{alloc_pane_id, Pane, PaneId};
use crate::tab::{SplitRequest, Tab, TabId};
use crate::window::WindowId;
use crate::Mux;
use anyhow::{bail, Context, Error};
use async_trait::async_trait;
use config::keyassignment::{SpawnCommand, SpawnTabDomain};
use config::{configuration, ExecDomain, SerialDomain, ValueOrFunc, WslDomain};
use downcast_rs::{impl_downcast, Downcast};
use parking_lot::Mutex;
use portable_pty::{native_pty_system, CommandBuilder, ExitStatus, MasterPty, PtySize, PtySystem};
use std::collections::HashMap;
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use wezterm_term::TerminalSize;
static DOMAIN_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);
pub type DomainId = usize;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DomainState {
Detached,
Attached,
}
pub fn alloc_domain_id() -> DomainId {
DOMAIN_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)
}
#[derive(Debug, Clone, PartialEq)]
pub enum SplitSource {
Spawn {
command: Option<CommandBuilder>,
command_dir: Option<String>,
},
MovePane(PaneId),
}
#[async_trait(?Send)]
pub trait Domain: Downcast + Send + Sync {
/// Spawn a new command within this domain
async fn spawn(
&self,
size: TerminalSize,
command: Option<CommandBuilder>,
command_dir: Option<String>,
window: WindowId,
) -> anyhow::Result<Arc<Tab>> {
let pane = self
.spawn_pane(size, command, command_dir)
.await
.context("spawn")?;
let tab = Arc::new(Tab::new(&size));
tab.assign_pane(&pane);
let mux = Mux::get();
mux.add_tab_and_active_pane(&tab)?;
mux.add_tab_to_window(&tab, window)?;
Ok(tab)
}
async fn split_pane(
&self,
source: SplitSource,
tab: TabId,
pane_id: PaneId,
split_request: SplitRequest,
) -> anyhow::Result<Arc<dyn Pane>> {
let mux = Mux::get();
let tab = match mux.get_tab(tab) {
Some(t) => t,
None => anyhow::bail!("Invalid tab id {}", tab),
};
let pane_index = match tab
.iter_panes_ignoring_zoom()
.iter()
.find(|p| p.pane.pane_id() == pane_id)
{
Some(p) => p.index,
None => anyhow::bail!("invalid pane id {}", pane_id),
};
let split_size = match tab.compute_split_size(pane_index, split_request) {
Some(s) => s,
None => anyhow::bail!("invalid pane index {}", pane_index),
};
let pane = match source {
SplitSource::Spawn {
command,
command_dir,
} => {
self.spawn_pane(split_size.second, command, command_dir)
.await?
}
SplitSource::MovePane(src_pane_id) => {
let (_domain, _window, src_tab) = mux
.resolve_pane_id(src_pane_id)
.ok_or_else(|| anyhow::anyhow!("pane {} not found", src_pane_id))?;
let src_tab = match mux.get_tab(src_tab) {
Some(t) => t,
None => anyhow::bail!("Invalid tab id {}", src_tab),
};
let pane = src_tab.remove_pane(src_pane_id).ok_or_else(|| {
anyhow::anyhow!("pane {} not found in its containing tab!?", src_pane_id)
})?;
if src_tab.is_dead() {
mux.remove_tab(src_tab.tab_id());
}
pane
}
};
tab.split_and_insert(pane_index, split_request, Arc::clone(&pane))?;
Ok(pane)
}
async fn spawn_pane(
&self,
size: TerminalSize,
command: Option<CommandBuilder>,
command_dir: Option<String>,
) -> anyhow::Result<Arc<dyn Pane>>;
/// The mux will call this method on the domain of the pane that
/// is being moved to give the domain a chance to handle the movement.
/// If this method returns Ok(None), then the mux will handle the
/// movement itself by mutating its local Tabs and Windows.
async fn move_pane_to_new_tab(
&self,
_pane_id: PaneId,
_window_id: Option<WindowId>,
_workspace_for_new_window: Option<String>,
) -> anyhow::Result<Option<(Arc<Tab>, WindowId)>> {
Ok(None)
}
/// Returns false if the `spawn` method will never succeed.
/// There are some internal placeholder domains that are
/// pre-created with local UI that we do not want to allow
/// to show in the launcher/menu as launchable items.
fn spawnable(&self) -> bool {
true
}
/// Returns true if the `detach` method can be used
/// to detach the domain, preserving the associated
/// panes, or false if the `detach` method will never
/// succeed
fn detachable(&self) -> bool;
/// Returns the domain id, which is useful for obtaining
/// a handle on the domain later.
fn domain_id(&self) -> DomainId;
/// Returns the name of the domain.
/// Should be a short identifier.
fn domain_name(&self) -> &str;
/// Returns a label describing the domain.
async fn domain_label(&self) -> String {
self.domain_name().to_string()
}
/// Re-attach to any tabs that might be pre-existing in this domain
async fn attach(&self, window_id: Option<WindowId>) -> anyhow::Result<()>;
/// Detach all tabs
fn detach(&self) -> anyhow::Result<()>;
/// Indicates the state of the domain
fn state(&self) -> DomainState;
}
impl_downcast!(Domain);
pub struct LocalDomain {
pty_system: Mutex<Box<dyn PtySystem + Send>>,
id: DomainId,
name: String,
}
impl LocalDomain {
pub fn new(name: &str) -> Result<Self, Error> {
Ok(Self::with_pty_system(name, native_pty_system()))
}
fn resolve_exec_domain(&self) -> Option<ExecDomain> {
config::configuration()
.exec_domains
.iter()
.find(|ed| ed.name == self.name)
.cloned()
}
fn resolve_wsl_domain(&self) -> Option<WslDomain> {
config::configuration()
.wsl_domains()
.iter()
.find(|d| d.name == self.name)
.cloned()
}
pub fn with_pty_system(name: &str, pty_system: Box<dyn PtySystem + Send>) -> Self {
let id = alloc_domain_id();
Self {
pty_system: Mutex::new(pty_system),
id,
name: name.to_string(),
}
}
pub fn new_wsl(wsl: WslDomain) -> Result<Self, Error> {
Self::new(&wsl.name)
}
pub fn new_exec_domain(exec_domain: ExecDomain) -> anyhow::Result<Self> {
Self::new(&exec_domain.name)
}
pub fn new_serial_domain(serial_domain: SerialDomain) -> anyhow::Result<Self> {
let port = serial_domain.port.as_ref().unwrap_or(&serial_domain.name);
let mut serial = portable_pty::serial::SerialTty::new(&port);
if let Some(baud) = serial_domain.baud {
serial.set_baud_rate(serial::BaudRate::from_speed(baud));
}
let pty_system = Box::new(serial);
Ok(Self::with_pty_system(&serial_domain.name, pty_system))
}
#[cfg(unix)]
fn is_conpty(&self) -> bool {
false
}
#[cfg(windows)]
fn is_conpty(&self) -> bool {
let pty_system = self.pty_system.lock();
let pty_system: &dyn PtySystem = &**pty_system;
pty_system
.downcast_ref::<portable_pty::win::conpty::ConPtySystem>()
.is_some()
}
async fn fixup_command(&self, cmd: &mut CommandBuilder) -> anyhow::Result<()> {
if let Some(wsl) = self.resolve_wsl_domain() {
let mut args: Vec<OsString> = cmd.get_argv().clone();
if args.is_empty() {
if let Some(def_prog) = &wsl.default_prog {
for arg in def_prog {
args.push(arg.into());
}
}
}
let mut argv: Vec<OsString> = vec![
"wsl.exe".into(),
"--distribution".into(),
wsl.distribution
.as_deref()
.unwrap_or(wsl.name.as_str())
.into(),
];
if let Some(cwd) = cmd.get_cwd() {
argv.push("--cd".into());
argv.push(cwd.into());
}
if let Some(user) = &wsl.username {
argv.push("--user".into());
argv.push(user.into());
}
if !args.is_empty() {
argv.push("--exec".into());
for arg in args {
argv.push(arg);
}
}
// TODO: process env list and update WLSENV so that they
// get passed through
cmd.clear_cwd();
*cmd.get_argv_mut() = argv;
} else if let Some(ed) = self.resolve_exec_domain() {
let mut args = vec![];
let mut set_environment_variables = HashMap::new();
for arg in cmd.get_argv() {
args.push(
arg.to_str()
.ok_or_else(|| anyhow::anyhow!("command argument is not utf8"))?
.to_string(),
);
}
for (k, v) in cmd.iter_full_env_as_str() {
set_environment_variables.insert(k.to_string(), v.to_string());
}
let cwd = match cmd.get_cwd() {
Some(cwd) => Some(PathBuf::from(cwd)),
None => None,
};
let spawn_command = SpawnCommand {
label: None,
domain: SpawnTabDomain::DomainName(ed.name.clone()),
args: if args.is_empty() { None } else { Some(args) },
set_environment_variables,
cwd,
position: None,
};
let spawn_command = config::with_lua_config_on_main_thread(|lua| async {
let lua = lua.ok_or_else(|| anyhow::anyhow!("missing lua context"))?;
let value = config::lua::emit_async_callback(
&*lua,
(ed.fixup_command.clone(), (spawn_command.clone())),
)
.await?;
let cmd: SpawnCommand =
luahelper::from_lua_value_dynamic(value).with_context(|| {
format!(
"interpreting SpawnCommand result from ExecDomain {}",
ed.name
)
})?;
Ok(cmd)
})
.await
.with_context(|| format!("calling ExecDomain {} function", ed.name))?;
// Reinterpret the SpawnCommand into the builder
cmd.get_argv_mut().clear();
if let Some(args) = &spawn_command.args {
for arg in args {
cmd.get_argv_mut().push(arg.into());
}
}
cmd.env_clear();
for (k, v) in &spawn_command.set_environment_variables {
cmd.env(k, v);
}
cmd.clear_cwd();
if let Some(cwd) = &spawn_command.cwd {
cmd.cwd(cwd);
}
} else if Path::new("/.flatpak-info").exists() {
// We're running inside a flatpak sandbox.
// Run the command outside the sandbox via flatpak-spawn
let mut args = vec![
"flatpak-spawn".to_string(),
"--host".to_string(),
"--watch-bus".to_string(),
];
if let Some(cwd) = cmd.get_cwd() {
args.push(format!("--directory={}", Path::new(cwd).display()));
}
let is_default_prog = cmd.is_default_prog();
// Note: WEZTERM_UNIX_SOCKET, WEZTERM_CONFIG_(FILE|DIR) and other env
// vars are not included in this.
// We can't include them: their paths are only meaningful in the sandbox
// and cannot be reasonably accessed from outside it in the shell.
for (k, v) in cmd.iter_extra_env_as_str() {
args.push(format!("--env={k}={v}"));
}
for arg in cmd.get_argv() {
args.push(
arg.to_str()
.ok_or_else(|| anyhow::anyhow!("command argument is not utf8"))?
.to_string(),
);
}
if is_default_prog {
// We can't read $SHELL from inside the sandbox, so ask the host.
let output = std::process::Command::new("flatpak-spawn")
.args(["--host", "sh", "-c", "echo $SHELL"])
.output()?;
let shell = String::from_utf8_lossy(&output.stdout);
args.push(shell.trim().to_string());
// Assume we can pass `-l` for a login shell
args.push("-l".to_string());
}
// Avoid setting up the controlling tty as that is not compatible
// with flatpak:
// <https://github.com/flatpak/flatpak/issues/3697>
// <https://github.com/flatpak/flatpak/issues/3285>
cmd.set_controlling_tty(false);
// Re-apply to the builder
cmd.get_argv_mut().clear();
for arg in args {
cmd.get_argv_mut().push(arg.into());
}
cmd.clear_cwd();
log::trace!("made: {cmd:#?}");
} else if let Some(dir) = cmd.get_cwd() {
// I'm not normally a fan of existence checking, but not checking here
// can be painful; in the case where a tab is local but has connected
// to a remote system and that remote has used OSC 7 to set a path
// that doesn't exist on the local system, process spawning can fail.
// Another situation is `sudo -i` has the pane with set to a cwd
// that is not accessible to the user.
if let Err(err) = Path::new(&dir).read_dir() {
log::warn!(
"Directory {:?} is not readable and will not be \
used for the command we are spawning: {:#}",
dir,
err
);
cmd.clear_cwd();
}
}
Ok(())
}
async fn build_command(
&self,
command: Option<CommandBuilder>,
command_dir: Option<String>,
pane_id: PaneId,
) -> anyhow::Result<CommandBuilder> {
let config = configuration();
let mut cmd = match command {
Some(mut cmd) => {
config.apply_cmd_defaults(&mut cmd, config.default_cwd.as_ref());
cmd
}
None => {
let wsl = self.resolve_wsl_domain();
config.build_prog(
None,
wsl.as_ref()
.map(|wsl| wsl.default_prog.as_ref())
.unwrap_or(config.default_prog.as_ref()),
wsl.as_ref()
.map(|wsl| wsl.default_cwd.as_ref())
.unwrap_or(config.default_cwd.as_ref()),
)?
}
};
if let Some(dir) = command_dir {
cmd.cwd(dir);
}
if let Ok(sock) = std::env::var("WEZTERM_UNIX_SOCKET") {
cmd.env("WEZTERM_UNIX_SOCKET", sock);
}
cmd.env("WEZTERM_PANE", pane_id.to_string());
if let Some(agent) = Mux::get().agent.as_ref() {
cmd.env("SSH_AUTH_SOCK", agent.path());
}
self.fixup_command(&mut cmd).await?;
Ok(cmd)
}
}
/// Allows sharing the writer between the Pane and the Terminal.
/// This could potentially be eliminated in the future if we can
/// teach the Pane impl to reference the writer in the Termninal,
/// but the Pane trait returns a RefMut and that makes it a bit
/// awkward at the moment.
#[derive(Clone)]
pub(crate) struct WriterWrapper {
writer: Arc<Mutex<Box<dyn Write + Send>>>,
}
impl WriterWrapper {
pub fn new(writer: Box<dyn Write + Send>) -> Self {
Self {
writer: Arc::new(Mutex::new(writer)),
}
}
}
impl std::io::Write for WriterWrapper {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.writer.lock().write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.writer.lock().flush()
}
}
/// Wraps the underlying pty; we use this as a marker for when
/// the spawn attempt failed in order to hold the pane open
pub(crate) struct FailedSpawnPty {
inner: Mutex<Box<dyn MasterPty>>,
}
impl portable_pty::MasterPty for FailedSpawnPty {
fn resize(&self, new_size: PtySize) -> anyhow::Result<()> {
self.inner.lock().resize(new_size)
}
fn get_size(&self) -> anyhow::Result<PtySize> {
self.inner.lock().get_size()
}
fn try_clone_reader(&self) -> anyhow::Result<Box<(dyn std::io::Read + Send + 'static)>> {
self.inner.lock().try_clone_reader()
}
fn take_writer(&self) -> anyhow::Result<Box<(dyn std::io::Write + Send + 'static)>> {
self.inner.lock().take_writer()
}
#[cfg(unix)]
fn process_group_leader(&self) -> Option<i32> {
None
}
#[cfg(unix)]
fn as_raw_fd(&self) -> Option<std::os::fd::RawFd> {
None
}
#[cfg(unix)]
fn tty_name(&self) -> Option<std::path::PathBuf> {
None
}
}
/// A fake child process for the case where the spawn attempt
/// failed. It reports as immediately terminated.
#[derive(Debug)]
pub(crate) struct FailedProcessSpawn {}
impl portable_pty::Child for FailedProcessSpawn {
fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>> {
Ok(Some(ExitStatus::with_exit_code(1)))
}
fn wait(&mut self) -> std::io::Result<ExitStatus> {
Ok(ExitStatus::with_exit_code(1))
}
fn process_id(&self) -> Option<u32> {
None
}
#[cfg(windows)]
fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
None
}
}
impl portable_pty::ChildKiller for FailedProcessSpawn {
fn kill(&mut self) -> std::io::Result<()> {
Ok(())
}
fn clone_killer(&self) -> Box<dyn portable_pty::ChildKiller + Send + Sync> {
Box::new(FailedProcessSpawn {})
}
}
#[async_trait(?Send)]
impl Domain for LocalDomain {
async fn spawn_pane(
&self,
size: TerminalSize,
command: Option<CommandBuilder>,
command_dir: Option<String>,
) -> anyhow::Result<Arc<dyn Pane>> {
let pane_id = alloc_pane_id();
let cmd = self
.build_command(command, command_dir, pane_id)
.await
.context("build_command")?;
let pair = self
.pty_system
.lock()
.openpty(crate::terminal_size_to_pty_size(size)?)?;
let command_line = cmd
.as_unix_command_line()
.unwrap_or_else(|err| format!("error rendering command line: {:?}", err));
let command_description = format!(
"\"{}\" in domain \"{}\"",
if command_line.is_empty() {
cmd.get_shell()
} else {
command_line
},
self.name
);
let child_result = pair.slave.spawn_command(cmd);
let mut writer = WriterWrapper::new(pair.master.take_writer()?);
let mut terminal = wezterm_term::Terminal::new(
size,
std::sync::Arc::new(config::TermConfig::new()),
"WezTerm",
config::wezterm_version(),
Box::new(writer.clone()),
);
if self.is_conpty() {
terminal.enable_conpty_quirks();
}
let pane: Arc<dyn Pane> = match child_result {
Ok(child) => Arc::new(LocalPane::new(
pane_id,
terminal,
child,
pair.master,
Box::new(writer),
self.id,
command_description,
)),
Err(err) => {
// Show the error to the user in the new pane
write!(writer, "{err:#}").ok();
// and return a dummy pane that has exited
Arc::new(LocalPane::new(
pane_id,
terminal,
Box::new(FailedProcessSpawn {}),
Box::new(FailedSpawnPty {
inner: Mutex::new(pair.master),
}),
Box::new(writer),
self.id,
command_description,
))
}
};
let mux = Mux::get();
mux.add_pane(&pane)?;
Ok(pane)
}
fn domain_id(&self) -> DomainId {
self.id
}
fn domain_name(&self) -> &str {
&self.name
}
async fn domain_label(&self) -> String {
if let Some(ed) = self.resolve_exec_domain() {
match &ed.label {
Some(ValueOrFunc::Value(wezterm_dynamic::Value::String(s))) => s.to_string(),
Some(ValueOrFunc::Func(label_func)) => {
let label = config::with_lua_config_on_main_thread(|lua| async {
let lua = lua.ok_or_else(|| anyhow::anyhow!("missing lua context"))?;
let value = config::lua::emit_async_callback(
&*lua,
(label_func.clone(), (self.name.clone())),
)
.await?;
let label: String =
luahelper::from_lua_value_dynamic(value).with_context(|| {
format!(
"interpreting SpawnCommand result from ExecDomain {}",
ed.name
)
})?;
Ok(label)
})
.await;
match label {
Ok(label) => label,
Err(err) => {
log::error!(
"Error while calling label function for ExecDomain `{}`: {err:#}",
self.name
);
self.name.to_string()
}
}
}
_ => self.name.to_string(),
}
} else if let Some(wsl) = self.resolve_wsl_domain() {
wsl.distribution.unwrap_or_else(|| self.name.to_string())
} else {
self.name.to_string()
}
}
async fn attach(&self, _window_id: Option<WindowId>) -> anyhow::Result<()> {
Ok(())
}
fn detachable(&self) -> bool {
false
}
fn detach(&self) -> anyhow::Result<()> {
bail!("detach not implemented for LocalDomain");
}
fn state(&self) -> DomainState {
DomainState::Attached
}
}