From 21dbeb6f834b8b9984b6489ea5bbc007e1297370 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 24 Oct 2020 23:21:03 -0700 Subject: [PATCH] wezterm: fixup APPIMAGE environment consistently Need to apply the same logic in wezterm-gui as we do in the wezterm-cli. --- Cargo.lock | 17 ++++-- env-bootstrap/Cargo.toml | 17 ++++++ env-bootstrap/src/lib.rs | 109 +++++++++++++++++++++++++++++++++++++++ wezterm-gui/Cargo.toml | 1 + wezterm-gui/src/main.rs | 7 +++ wezterm/Cargo.toml | 7 +-- wezterm/src/main.rs | 107 ++------------------------------------ 7 files changed, 151 insertions(+), 114 deletions(-) create mode 100644 env-bootstrap/Cargo.toml create mode 100644 env-bootstrap/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index d3830d4bb..3e0ab2d59 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1005,6 +1005,17 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "env-bootstrap" +version = "0.1.0" +dependencies = [ + "cocoa", + "config", + "dirs 2.0.2", + "libc", + "objc", +] + [[package]] name = "env_logger" version = "0.7.1" @@ -4004,15 +4015,12 @@ name = "wezterm" version = "0.1.0" dependencies = [ "anyhow", - "cocoa", "codec", "config", - "dirs 2.0.2", + "env-bootstrap", "filedescriptor", - "libc", "log", "mux", - "objc", "portable-pty", "pretty_env_logger", "promise", @@ -4098,6 +4106,7 @@ dependencies = [ "dirs 2.0.2", "downcast-rs", "embed-resource", + "env-bootstrap", "euclid 0.20.14", "filedescriptor", "hdrhistogram", diff --git a/env-bootstrap/Cargo.toml b/env-bootstrap/Cargo.toml new file mode 100644 index 000000000..35b5d1e59 --- /dev/null +++ b/env-bootstrap/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "env-bootstrap" +version = "0.1.0" +authors = ["Wez Furlong "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +config = { path = "../config" } +dirs = "2.0" + +[target.'cfg(target_os = "macos")'.dependencies] +cocoa = "0.20" +libc = "0.2" +objc = "0.2" + diff --git a/env-bootstrap/src/lib.rs b/env-bootstrap/src/lib.rs new file mode 100644 index 000000000..b9603c4de --- /dev/null +++ b/env-bootstrap/src/lib.rs @@ -0,0 +1,109 @@ +use std::path::{Path, PathBuf}; + +pub fn set_wezterm_executable() { + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + std::env::set_var("WEZTERM_EXECUTABLE_DIR", dir); + } + std::env::set_var("WEZTERM_EXECUTABLE", exe); + } +} + +pub fn fixup_appimage() { + if let Some(appimage) = std::env::var_os("APPIMAGE") { + let appimage = std::path::PathBuf::from(appimage); + + // We were started via an AppImage, presumably ourselves. + // AppImage exports ARGV0 into the environment and that causes + // everything that was indirectly spawned by us to appear to + // be the AppImage. eg: if you `vim foo` it shows as + // `WezTerm.AppImage foo`, which is super confusing for everyone! + // Let's just unset that from the environment! + std::env::remove_var("ARGV0"); + + // This AppImage feature allows redirecting HOME and XDG_CONFIG_HOME + // to live alongside the executable for portable use: + // https://github.com/AppImage/AppImageKit/issues/368 + // When we spawn children, we don't want them to inherit this, + // but we do want to respect them for config loading. + // Let's force resolution and cleanup our environment now. + + /// Given "/some/path.AppImage" produce "/some/path.AppImageSUFFIX". + /// We only support this for "path.AppImage" that can be converted + /// to UTF-8. Otherwise, we return "/some/path.AppImage" unmodified. + fn append_extra_file_name_suffix(p: &Path, suffix: &str) -> PathBuf { + if let Some(name) = p.file_name().and_then(|o| o.to_str()) { + p.with_file_name(format!("{}{}", name, suffix)) + } else { + p.to_path_buf() + } + } + + /// Our config stuff exports these env vars to help portable apps locate + /// the correct environment when it is launched via wezterm. + /// However, if we are using the system wezterm to spawn a portable + /// AppImage then we want these to not take effect. + fn clean_wezterm_config_env() { + std::env::remove_var("WEZTERM_CONFIG_FILE"); + std::env::remove_var("WEZTERM_CONFIG_DIR"); + } + + if config::HOME_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".home")) { + // Fixup HOME to point to the user's actual home dir + std::env::remove_var("HOME"); + std::env::set_var("HOME", dirs::home_dir().expect("can't resolve HOME dir")); + clean_wezterm_config_env(); + } + + if config::CONFIG_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".config")) { + std::env::remove_var("XDG_CONFIG_HOME"); + clean_wezterm_config_env(); + } + } +} + +/// If LANG isn't set in the environment, make an attempt at setting +/// it to a UTF-8 version of the current locale known to NSLocale. +#[cfg(target_os = "macos")] +pub fn set_lang_from_locale() { + use cocoa::base::id; + use cocoa::foundation::NSString; + use objc::runtime::Object; + use objc::*; + + if std::env::var_os("LANG").is_none() { + unsafe fn nsstring_to_str<'a>(ns: *mut Object) -> &'a str { + let data = NSString::UTF8String(ns as id) as *const u8; + let len = NSString::len(ns as id); + let bytes = std::slice::from_raw_parts(data, len); + std::str::from_utf8_unchecked(bytes) + } + + unsafe { + let locale: *mut Object = msg_send![class!(NSLocale), autoupdatingCurrentLocale]; + let lang_code_obj: *mut Object = msg_send![locale, languageCode]; + let country_code_obj: *mut Object = msg_send![locale, countryCode]; + + { + let lang_code = nsstring_to_str(lang_code_obj); + let country_code = nsstring_to_str(country_code_obj); + + let candidate = format!("{}_{}.UTF-8", lang_code, country_code); + let candidate_cstr = std::ffi::CString::new(candidate.as_bytes().clone()) + .expect("make cstr from str"); + + // If this looks like a working locale then export it to + // the environment so that our child processes inherit it. + let old = libc::setlocale(libc::LC_CTYPE, std::ptr::null()); + if !libc::setlocale(libc::LC_CTYPE, candidate_cstr.as_ptr()).is_null() { + std::env::set_var("LANG", &candidate); + } + libc::setlocale(libc::LC_CTYPE, old); + } + + let _: () = msg_send![lang_code_obj, release]; + let _: () = msg_send![country_code_obj, release]; + let _: () = msg_send![locale, release]; + } + } +} diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml index 5f94fc069..05fd6280f 100644 --- a/wezterm-gui/Cargo.toml +++ b/wezterm-gui/Cargo.toml @@ -22,6 +22,7 @@ codec = { path = "../codec" } config = { path = "../config" } dirs = "2.0" downcast-rs = "1.0" +env-bootstrap = { path = "../env-bootstrap" } euclid = "0.20" filedescriptor = { version="0.7", path = "../filedescriptor" } hdrhistogram = "7.1" diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs index 05fce60bb..660a6eb1c 100644 --- a/wezterm-gui/src/main.rs +++ b/wezterm-gui/src/main.rs @@ -404,6 +404,13 @@ fn run() -> anyhow::Result<()> { } }; + env_bootstrap::set_wezterm_executable(); + + #[cfg(target_os = "macos")] + env_bootstrap::set_lang_from_locale(); + + env_bootstrap::fixup_appimage(); + pretty_env_logger::init_timed(); stats::Stats::init()?; let _saver = umask::UmaskSaver::new(); diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.toml index 4d622c11b..5c7a5e1b4 100644 --- a/wezterm/Cargo.toml +++ b/wezterm/Cargo.toml @@ -13,7 +13,7 @@ anyhow = "1.0" anyhow = "1.0" codec = { path = "../codec" } config = { path = "../config" } -dirs = "2.0" +env-bootstrap = { path = "../env-bootstrap" } filedescriptor = { version="0.7", path = "../filedescriptor" } log = "0.4" mux = { path = "../mux" } @@ -29,8 +29,3 @@ wezterm-client = { path = "../wezterm-client" } wezterm-gui-subcommands = { path = "../wezterm-gui-subcommands" } wezterm-term = { path = "../term" } -[target.'cfg(target_os = "macos")'.dependencies] -cocoa = "0.20" -libc = "0.2" -objc = "0.2" - diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs index 957c63d8e..61304c089 100644 --- a/wezterm/src/main.rs +++ b/wezterm/src/main.rs @@ -7,7 +7,6 @@ use mux::Mux; use portable_pty::cmdbuilder::CommandBuilder; use std::ffi::OsString; use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; use std::rc::Rc; use structopt::StructOpt; use tabout::{tabulate_output, Alignment, Column}; @@ -179,113 +178,13 @@ fn main() { Mux::shutdown(); } -/// If LANG isn't set in the environment, make an attempt at setting -/// it to a UTF-8 version of the current locale known to NSLocale. -#[cfg(target_os = "macos")] -fn set_lang_from_locale() { - use cocoa::base::id; - use cocoa::foundation::NSString; - use objc::runtime::Object; - use objc::*; - - if std::env::var_os("LANG").is_none() { - unsafe fn nsstring_to_str<'a>(ns: *mut Object) -> &'a str { - let data = NSString::UTF8String(ns as id) as *const u8; - let len = NSString::len(ns as id); - let bytes = std::slice::from_raw_parts(data, len); - std::str::from_utf8_unchecked(bytes) - } - - unsafe { - let locale: *mut Object = msg_send![class!(NSLocale), autoupdatingCurrentLocale]; - let lang_code_obj: *mut Object = msg_send![locale, languageCode]; - let country_code_obj: *mut Object = msg_send![locale, countryCode]; - - { - let lang_code = nsstring_to_str(lang_code_obj); - let country_code = nsstring_to_str(country_code_obj); - - let candidate = format!("{}_{}.UTF-8", lang_code, country_code); - let candidate_cstr = std::ffi::CString::new(candidate.as_bytes().clone()) - .expect("make cstr from str"); - - // If this looks like a working locale then export it to - // the environment so that our child processes inherit it. - let old = libc::setlocale(libc::LC_CTYPE, std::ptr::null()); - if !libc::setlocale(libc::LC_CTYPE, candidate_cstr.as_ptr()).is_null() { - std::env::set_var("LANG", &candidate); - } - libc::setlocale(libc::LC_CTYPE, old); - } - - let _: () = msg_send![lang_code_obj, release]; - let _: () = msg_send![country_code_obj, release]; - let _: () = msg_send![locale, release]; - } - } -} - fn run() -> anyhow::Result<()> { - if let Ok(exe) = std::env::current_exe() { - if let Some(dir) = exe.parent() { - std::env::set_var("WEZTERM_EXECUTABLE_DIR", dir); - } - std::env::set_var("WEZTERM_EXECUTABLE", exe); - } + env_bootstrap::set_wezterm_executable(); #[cfg(target_os = "macos")] - set_lang_from_locale(); + env_bootstrap::set_lang_from_locale(); - if let Some(appimage) = std::env::var_os("APPIMAGE") { - let appimage = std::path::PathBuf::from(appimage); - - // We were started via an AppImage, presumably ourselves. - // AppImage exports ARGV0 into the environment and that causes - // everything that was indirectly spawned by us to appear to - // be the AppImage. eg: if you `vim foo` it shows as - // `WezTerm.AppImage foo`, which is super confusing for everyone! - // Let's just unset that from the environment! - std::env::remove_var("ARGV0"); - - // This AppImage feature allows redirecting HOME and XDG_CONFIG_HOME - // to live alongside the executable for portable use: - // https://github.com/AppImage/AppImageKit/issues/368 - // When we spawn children, we don't want them to inherit this, - // but we do want to respect them for config loading. - // Let's force resolution and cleanup our environment now. - - /// Given "/some/path.AppImage" produce "/some/path.AppImageSUFFIX". - /// We only support this for "path.AppImage" that can be converted - /// to UTF-8. Otherwise, we return "/some/path.AppImage" unmodified. - fn append_extra_file_name_suffix(p: &Path, suffix: &str) -> PathBuf { - if let Some(name) = p.file_name().and_then(|o| o.to_str()) { - p.with_file_name(format!("{}{}", name, suffix)) - } else { - p.to_path_buf() - } - } - - /// Our config stuff exports these env vars to help portable apps locate - /// the correct environment when it is launched via wezterm. - /// However, if we are using the system wezterm to spawn a portable - /// AppImage then we want these to not take effect. - fn clean_wezterm_config_env() { - std::env::remove_var("WEZTERM_CONFIG_FILE"); - std::env::remove_var("WEZTERM_CONFIG_DIR"); - } - - if config::HOME_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".home")) { - // Fixup HOME to point to the user's actual home dir - std::env::remove_var("HOME"); - std::env::set_var("HOME", dirs::home_dir().expect("can't resolve HOME dir")); - clean_wezterm_config_env(); - } - - if config::CONFIG_DIR.starts_with(append_extra_file_name_suffix(&appimage, ".config")) { - std::env::remove_var("XDG_CONFIG_HOME"); - clean_wezterm_config_env(); - } - } + env_bootstrap::fixup_appimage(); pretty_env_logger::init_timed(); let _saver = umask::UmaskSaver::new();