Files
LLeMbas-TTY/wezterm/src/main.rs
T

337 lines
10 KiB
Rust

use anyhow::{anyhow, Context};
use clap::builder::ValueParser;
use clap::{Parser, ValueEnum, ValueHint};
use clap_complete::{generate as generate_completion, shells, Generator as CompletionGenerator};
use config::{wezterm_version, ConfigHandle};
use mux::Mux;
use std::ffi::OsString;
use std::io::Read;
use umask::UmaskSaver;
use wezterm_gui_subcommands::*;
mod asciicast;
mod cli;
// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";
#[derive(Debug, Parser)]
#[command(
about = "Wez's Terminal Emulator\nhttp://github.com/wez/wezterm",
version = wezterm_version()
)]
pub struct Opt {
/// Skip loading wezterm.lua
#[arg(long, short = 'n')]
skip_config: bool,
/// Specify the configuration file to use, overrides the normal
/// configuration file resolution
#[arg(
long,
value_parser,
conflicts_with = "skip_config",
value_hint=ValueHint::FilePath
)]
config_file: Option<OsString>,
/// Override specific configuration values
#[arg(
long = "config",
name = "name=value",
value_parser=ValueParser::new(name_equals_value),
number_of_values = 1)]
config_override: Vec<(String, String)>,
#[command(subcommand)]
cmd: Option<SubCommand>,
}
#[derive(Debug, Clone, ValueEnum)]
enum Shell {
Bash,
Elvish,
Fish,
PowerShell,
Zsh,
Fig,
}
impl CompletionGenerator for Shell {
fn file_name(&self, name: &str) -> String {
match self {
Shell::Bash => shells::Bash.file_name(name),
Shell::Elvish => shells::Elvish.file_name(name),
Shell::Fish => shells::Fish.file_name(name),
Shell::PowerShell => shells::PowerShell.file_name(name),
Shell::Zsh => shells::Zsh.file_name(name),
Shell::Fig => clap_complete_fig::Fig.file_name(name),
}
}
fn generate(&self, cmd: &clap::Command, buf: &mut dyn std::io::Write) {
match self {
Shell::Bash => shells::Bash.generate(cmd, buf),
Shell::Elvish => shells::Elvish.generate(cmd, buf),
Shell::Fish => shells::Fish.generate(cmd, buf),
Shell::PowerShell => shells::PowerShell.generate(cmd, buf),
Shell::Zsh => shells::Zsh.generate(cmd, buf),
Shell::Fig => clap_complete_fig::Fig.generate(cmd, buf),
}
}
}
#[derive(Debug, Parser, Clone)]
enum SubCommand {
#[command(
name = "start",
about = "Start the GUI, optionally running an alternative program"
)]
Start(StartCommand),
#[command(name = "ssh", about = "Establish an ssh session")]
Ssh(SshCommand),
#[command(name = "serial", about = "Open a serial port")]
Serial(SerialCommand),
#[command(name = "connect", about = "Connect to wezterm multiplexer")]
Connect(ConnectCommand),
#[command(name = "ls-fonts", about = "Display information about fonts")]
LsFonts(LsFontsCommand),
#[command(name = "show-keys", about = "Show key assignments")]
ShowKeys(ShowKeysCommand),
#[command(name = "cli", about = "Interact with experimental mux server")]
Cli(cli::CliCommand),
#[command(name = "imgcat", about = "Output an image to the terminal")]
ImageCat(ImgCatCommand),
#[command(
name = "set-working-directory",
about = "Advise the terminal of the current working directory by \
emitting an OSC 7 escape sequence"
)]
SetCwd(SetCwdCommand),
#[command(name = "record", about = "Record a terminal session as an asciicast")]
Record(asciicast::RecordCommand),
#[command(name = "replay", about = "Replay an asciicast terminal session")]
Replay(asciicast::PlayCommand),
/// Generate shell completion information
#[command(name = "shell-completion")]
ShellCompletion {
/// Which shell to generate for
#[arg(long, value_parser)]
shell: Shell,
},
}
use termwiz::escape::osc::{
ITermDimension, ITermFileData, ITermProprietary, OperatingSystemCommand,
};
#[derive(Debug, Parser, Clone)]
struct ImgCatCommand {
/// Specify the display width; defaults to "auto" which automatically selects
/// an appropriate size. You may also use an integer value `N` to specify the
/// number of cells, or `Npx` to specify the number of pixels, or `N%` to
/// size relative to the terminal width.
#[arg(long = "width")]
width: Option<ITermDimension>,
/// Specify the display height; defaults to "auto" which automatically selects
/// an appropriate size. You may also use an integer value `N` to specify the
/// number of cells, or `Npx` to specify the number of pixels, or `N%` to
/// size relative to the terminal height.
#[arg(long = "height")]
height: Option<ITermDimension>,
/// Do not respect the aspect ratio. The default is to respect the aspect
/// ratio
#[arg(long = "no-preserve-aspect-ratio")]
no_preserve_aspect_ratio: bool,
/// The name of the image file to be displayed.
/// If omitted, will attempt to read it from stdin.
#[arg(value_parser, value_hint=ValueHint::FilePath)]
file_name: Option<OsString>,
}
impl ImgCatCommand {
fn run(&self) -> anyhow::Result<()> {
let mut data = Vec::new();
if let Some(file_name) = self.file_name.as_ref() {
let mut f = std::fs::File::open(file_name)
.with_context(|| anyhow!("reading image file: {:?}", file_name))?;
f.read_to_end(&mut data)?;
} else {
let mut stdin = std::io::stdin();
stdin.read_to_end(&mut data)?;
}
let osc = OperatingSystemCommand::ITermProprietary(ITermProprietary::File(Box::new(
ITermFileData {
name: None,
size: Some(data.len()),
width: self.width.unwrap_or_default(),
height: self.height.unwrap_or_default(),
preserve_aspect_ratio: !self.no_preserve_aspect_ratio,
inline: true,
do_not_move_cursor: false,
data,
},
)));
println!("{}", osc);
Ok(())
}
}
#[derive(Debug, Parser, Clone)]
struct SetCwdCommand {
/// The directory to specify.
/// If omitted, will use the current directory of the process itself.
#[arg(value_parser, value_hint=ValueHint::DirPath)]
cwd: Option<OsString>,
/// The hostname to use in the constructed file:// URL.
/// If omitted, the system hostname will be used.
#[arg(value_parser, value_hint=ValueHint::Hostname)]
host: Option<OsString>,
}
impl SetCwdCommand {
fn run(&self) -> anyhow::Result<()> {
let mut cwd = std::env::current_dir()?;
if let Some(dir) = &self.cwd {
cwd.push(dir);
}
let mut url = url::Url::from_directory_path(&cwd)
.map_err(|_| anyhow::anyhow!("cwd {} is not an absolute path", cwd.display()))?;
let host = match self.host.as_ref() {
Some(h) => h.clone(),
None => hostname::get()?,
};
let host = host.to_str().unwrap_or("localhost");
url.set_host(Some(host))?;
let osc = OperatingSystemCommand::CurrentWorkingDirectory(url.into());
print!("{}", osc);
Ok(())
}
}
fn terminate_with_error_message(err: &str) -> ! {
log::error!("{}; terminating", err);
std::process::exit(1);
}
fn terminate_with_error(err: anyhow::Error) -> ! {
terminate_with_error_message(&format!("{:#}", err));
}
fn main() {
config::designate_this_as_the_main_thread();
config::assign_error_callback(mux::connui::show_configuration_error_message);
if let Err(e) = run() {
terminate_with_error(e);
}
Mux::shutdown();
}
fn init_config(opts: &Opt) -> anyhow::Result<ConfigHandle> {
config::common_init(
opts.config_file.as_ref(),
&opts.config_override,
opts.skip_config,
)
.context("config::common_init")?;
let config = config::configuration();
config.update_ulimit()?;
Ok(config)
}
fn run() -> anyhow::Result<()> {
env_bootstrap::bootstrap();
let saver = UmaskSaver::new();
let opts = Opt::parse();
match opts
.cmd
.as_ref()
.cloned()
.unwrap_or_else(|| SubCommand::Start(StartCommand::default()))
{
SubCommand::Start(_)
| SubCommand::LsFonts(_)
| SubCommand::ShowKeys(_)
| SubCommand::Ssh(_)
| SubCommand::Serial(_)
| SubCommand::Connect(_) => delegate_to_gui(saver),
SubCommand::ImageCat(cmd) => cmd.run(),
SubCommand::SetCwd(cmd) => cmd.run(),
SubCommand::Cli(cli) => cli::run_cli(&opts, cli),
SubCommand::Record(cmd) => cmd.run(init_config(&opts)?),
SubCommand::Replay(cmd) => cmd.run(),
SubCommand::ShellCompletion { shell } => {
use clap::CommandFactory;
let mut cmd = Opt::command();
let name = cmd.get_name().to_string();
generate_completion(shell, &mut cmd, name, &mut std::io::stdout());
Ok(())
}
}
}
fn delegate_to_gui(saver: UmaskSaver) -> anyhow::Result<()> {
use std::process::Command;
// Restore the original umask
drop(saver);
let exe_name = if cfg!(windows) {
"wezterm-gui.exe"
} else {
"wezterm-gui"
};
let exe = std::env::current_exe()?
.parent()
.ok_or_else(|| anyhow!("exe has no parent dir!?"))?
.join(exe_name);
let mut cmd = Command::new(exe);
if cfg!(windows) {
cmd.arg("--attach-parent-console");
}
cmd.args(std::env::args_os().skip(1));
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Clean up random fds, except when we're running in an AppImage.
// AppImage relies on child processes keeping alive an fd that
// references the mount point and if we close it as part of execing
// the gui binary, the appimage gets unmounted before we can exec.
if std::env::var_os("APPIMAGE").is_none() {
portable_pty::unix::close_random_fds();
}
let res = cmd.exec();
return Err(anyhow::anyhow!("failed to exec {cmd:?}: {res:?}"));
}
#[cfg(windows)]
{
let mut child = cmd.spawn()?;
let status = child.wait()?;
let code = status.code().unwrap_or(1);
std::process::exit(code);
}
}