fix: close remaining gaps found by the completeness audit

Addresses the partial ports listed in
docs/rewrite/notes/review-completeness-codex.md (details in
docs/rewrite/notes/gaps-X2.md):
- Flatpak: the exit watcher no longer consumes the host command; a
  shared FlatpakSignalHandle lets closing a surface still SIGHUP the
  host process group.
- Child environment is byte-preserving end to end (ghostty_os::EnvMap
  of OsStrings) and Snap paths are filtered like filterSnapPaths.
- argv handling no longer panics on non-UTF-8 arguments.
- URI percent-decoding keeps raw bytes; OSC 7 pwd is passed through
  without lossy conversion.
- Keybinding comparison/hashing uses full Unicode case folding from a
  table generated from CaseFolding.txt (Unicode 17.0.0).
- Link regexes set Oniguruma's whole-search retry limit through the new
  minimal ghostty-onig crate (one SAFETY-commented FFI call).
- OSC 9 NUL-capacity check ordering matches Zig.
- Wayland registry binds/clears globals advertised after startup.
- Custom shaders may pass sampler2D to helper functions (naga adapter).
- +list-themes preview renders OSC 8 links, styled underlines and
  follows color-scheme reports.

Also includes the inspector's integration edits in shared files
(renderer state hook, termio VT recording, core/apprt-gtk wiring), X1's
config/input/cli additions for completion generation, and a fix for a
race in the termio backpressure test (it wrote before `stty raw`
applied, so the cooked line discipline dropped bytes past MAX_CANON).

Test Plan:
- cargo test --workspace
- cargo clippy --workspace --all-targets -- -D warnings
This commit is contained in:
ddidderr committed 2026-10-12 04:39:24 +02:00
1 parent 90ad602969
commit f4c020101c
61 files changed
+4210 -298

No files matched your search

+35 -4
View File
@@ -13,7 +13,6 @@
//! async-signal-safe, like their Zig counterparts are expected to be).
use std::{
collections::HashMap,
ffi::{CString, NulError, c_char},
os::fd::OwnedFd,
panic::{AssertUnwindSafe, catch_unwind},
@@ -25,6 +24,7 @@ use rustix::{
process::{self, WaitOptions},
stdio,
};
use std::os::unix::ffi::OsStrExt;
/// Function executed /in the child process/ after the fork, but before
/// exec'ing the command. If the function returns `Some(code)`, the child
@@ -173,7 +173,7 @@ pub struct Command {
/// Environment variables for the child process. If this is `None`,
/// inherits the environment variables from this process. These are the
/// exact environment variables to set; these are /not/ merged.
pub env: Option<HashMap<String, String>>,
pub env: Option<ghostty_os::EnvMap>,
/// Working directory to change to in the child process. If not set, the
/// working directory of the calling process is preserved. Failure to
@@ -249,7 +249,12 @@ impl Command {
let envp = match &self.env {
Some(map) => map
.iter()
.map(|(k, v)| CString::new(format!("{k}={v}")))
.map(|(k, v)| {
let mut b = k.as_bytes().to_vec();
b.push(b'=');
b.extend_from_slice(v.as_bytes());
CString::new(b)
})
.collect::<Result<_, _>>()?,
// Inherit: snapshot our environment before the fork (nothing may
// allocate in the child).
@@ -738,13 +743,39 @@ mod tests {
let mut cmd = sh("echo $VALUE");
cmd.stdout = Some(stdout.try_clone().unwrap().into());
cmd.env = Some(HashMap::from([("VALUE".to_owned(), "hello".to_owned())]));
cmd.env = Some(ghostty_os::EnvMap::from_iter([("VALUE", "hello")]));
cmd.start().unwrap();
assert_eq!(cmd.wait(true).unwrap(), Exit::Exited(0));
assert_eq!("hello\n", read_all(stdout));
}
#[test]
fn non_utf8_env_value_is_preserved() {
use std::os::unix::ffi::OsStringExt;
let td = TempDir::init().unwrap();
let stdout = test_file(&td, "stdout.txt");
let mut cmd = sh("printf %s \"$VALUE\"");
cmd.stdout = Some(stdout.try_clone().unwrap().into());
let mut env = ghostty_os::EnvMap::new();
env.insert(
"VALUE",
std::ffi::OsString::from_vec(vec![b'a', 0xff, b'b']),
);
cmd.env = Some(env);
cmd.start().unwrap();
assert_eq!(cmd.wait(true).unwrap(), Exit::Exited(0));
let mut bytes = Vec::new();
std::io::Read::read_to_end(
&mut std::fs::File::open(td.path().join("stdout.txt")).unwrap(),
&mut bytes,
)
.unwrap();
assert_eq!(bytes, vec![b'a', 0xff, b'b']);
}
#[test]
fn custom_working_directory() {
let td = TempDir::init().unwrap();
+36 -27
View File
@@ -212,6 +212,9 @@ impl Exec {
let (tx, rx) = crossbeam_channel::bounded(1);
let wakeup = Wakeup::new()?;
if let Some(cmd) = fp.cmd.take() {
// Keep a signal handle so stop() can still SIGHUP the
// host process group after the watcher owns the command.
fp.signal = Some(cmd.signal_handle());
let w = wakeup.clone();
cmd.wait_callback(move |r| {
let _ = tx.send(r.map_err(|e| format!("{e}")));
@@ -724,10 +727,9 @@ enum Process {
struct FlatpakProcess {
pid: u32,
/// Taken by the exit watcher (`wait_callback` consumes the command).
/// TODO(integration): ghostty-os' `FlatpakHostCommand::wait_callback`
/// takes `self`, so after the watcher is installed we can no longer
/// `signal()` the command from `stop()`.
cmd: Option<ghostty_os::flatpak::FlatpakHostCommand>,
/// Signal handle that outlives the command's move into the watcher.
signal: Option<ghostty_os::flatpak::FlatpakSignalHandle>,
}
struct Subprocess {
@@ -756,7 +758,7 @@ impl Subprocess {
// If we have a resources dir then set our env var
if let Some(dir) = &cfg.resources_dir {
log::info!("found Ghostty resources dir: {dir}");
env.insert("GHOSTTY_RESOURCES_DIR".into(), dir.clone());
env.insert("GHOSTTY_RESOURCES_DIR", dir.clone());
}
// Set our TERM var. This is a bit complicated because we want to use
@@ -766,8 +768,8 @@ impl Subprocess {
// For now, we just look up a bundled dir but in the future we should
// also load the terminfo database and look for it.
if let Some(base) = &cfg.resources_dir {
env.insert("TERM".into(), cfg.term.clone());
env.insert("COLORTERM".into(), "truecolor".into());
env.insert("TERM", cfg.term.clone());
env.insert("COLORTERM", "truecolor");
// Assume that the resources directory is adjacent to the terminfo
// database
@@ -784,10 +786,10 @@ impl Subprocess {
.map_or_else(String::new, |p| p.to_string_lossy().into_owned());
format!("{parent}/terminfo")
};
env.insert("TERMINFO".into(), terminfo);
env.insert("TERMINFO", terminfo);
} else {
env.insert("TERM".into(), "xterm-256color".into());
env.insert("COLORTERM".into(), "truecolor".into());
env.insert("TERM", "xterm-256color");
env.insert("COLORTERM", "truecolor");
}
// Add our binary to the path if we can find it.
@@ -795,8 +797,8 @@ impl Subprocess {
// Set environment variables used by some programs (such as neovim) to detect
// which terminal emulator and version they're running under.
env.insert("TERM_PROGRAM".into(), "ghostty".into());
env.insert("TERM_PROGRAM_VERSION".into(), VERSION_STRING.into());
env.insert("TERM_PROGRAM", "ghostty");
env.insert("TERM_PROGRAM_VERSION", VERSION_STRING);
// VTE_VERSION is set by gnome-terminal and other VTE-based terminals.
// We don't want our child processes to think we're running under VTE.
@@ -858,7 +860,7 @@ impl Subprocess {
// Add the environment variables that override any others.
for (k, v) in cfg.env_override.iter() {
env.insert(k.to_owned(), v.to_owned());
env.insert(k, v);
}
// Build our args list
@@ -876,7 +878,7 @@ impl Subprocess {
// https://github.com/kovidgoyal/kitty/issues/1595
// https://github.com/ghostty-org/ghostty/discussions/7769
if let Some(pwd) = &cwd {
env.insert("PWD".into(), pwd.clone());
env.insert("PWD", pwd.clone());
}
Ok(Subprocess {
@@ -1014,6 +1016,7 @@ impl Subprocess {
);
self.process = Some(Process::Flatpak(FlatpakProcess {
pid,
signal: Some(cmd.signal_handle()),
cmd: Some(cmd),
}));
return Ok((pty.master.try_clone()?, pty.master.try_clone()?));
@@ -1086,15 +1089,16 @@ impl Subprocess {
}
}
Process::Flatpak(fp) => {
if let Some(cmd) = &fp.cmd {
if let Err(err) = cmd.signal(1 /* SIGHUP */, true) {
log::error!("error sending SIGHUP to command, may hang: {err}");
let res = match (&fp.cmd, &fp.signal) {
(Some(cmd), _) => cmd.signal(1 /* SIGHUP */, true),
(None, Some(h)) => h.signal(1 /* SIGHUP */, true),
(None, None) => {
log::warn!("no signal handle for flatpak host command pid={}", fp.pid);
Ok(())
}
} else {
log::warn!(
"cannot signal flatpak host command pid={} after the watcher took it",
fp.pid
);
};
if let Err(err) = res {
log::error!("error sending SIGHUP to command, may hang: {err}");
}
}
}
@@ -1147,22 +1151,27 @@ fn add_ghostty_path(env: &mut EnvMap) {
// We always set this so that if the shell overwrites the path
// scripts still have a way to find the Ghostty binary when
// running in Ghostty.
env.insert("GHOSTTY_BIN_DIR".into(), exe_dir.clone());
env.insert("GHOSTTY_BIN_DIR", exe_dir.clone());
// Append if we have a path. We want to append so that ghostty is
// the last priority in the path. If we don't have a path set
// then we just set it to the directory of the binary.
if let Some(path) = env.get("PATH").cloned() {
if let Some(path) = env.get("PATH").map(std::ffi::OsStr::to_owned) {
// Verify that our path doesn't already contain this entry
use std::os::unix::ffi::OsStrExt;
if path
.split(':')
.any(|entry| !entry.is_empty() && entry == exe_dir)
.as_bytes()
.split(|&b| b == b':')
.any(|entry| !entry.is_empty() && entry == exe_dir.as_bytes())
{
return;
}
env.insert("PATH".into(), ghostty_os::env::append_env(&path, &exe_dir));
env.insert(
"PATH",
ghostty_os::env::append_env_os(&path, std::ffi::OsStr::new(&exe_dir)),
);
} else {
env.insert("PATH".into(), exe_dir);
env.insert("PATH", exe_dir);
}
}
+126 -51
View File
@@ -3,12 +3,12 @@
//! The shell scripts live in `resources/shell-integration/` at the workspace
//! root (copied verbatim from `src/shell-integration/`).
use std::{collections::HashMap, path::Path};
use std::path::Path;
use ghostty_os::{env::prepend_env, homedir, shell::ShellCommandBuilder};
use ghostty_os::{env::prepend_env_os, homedir, shell::ShellCommandBuilder};
/// The environment passed to the child (Zig `std.process.EnvMap`).
pub type EnvMap = HashMap<String, String>;
pub type EnvMap = ghostty_os::EnvMap;
/// Shell types we support
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -144,7 +144,7 @@ pub fn setup_features(env: &mut EnvMap, features: ShellIntegrationFeatures, curs
}
if !buf.is_empty() {
env.insert("GHOSTTY_SHELL_FEATURES".to_owned(), buf);
env.insert("GHOSTTY_SHELL_FEATURES", buf);
}
}
@@ -218,15 +218,15 @@ fn setup_bash(
}
// Preserve an existing ENV value. We're about to overwrite it.
if let Some(v) = env.get("ENV").cloned() {
env.insert("GHOSTTY_BASH_ENV".to_owned(), v);
if let Some(v) = env.get("ENV").map(std::ffi::OsStr::to_owned) {
env.insert("GHOSTTY_BASH_ENV", v);
}
// Set our new ENV to point to our integration script.
let script_path = format!("{resource_dir}/shell-integration/bash/ghostty.bash");
match std::fs::File::open(&script_path) {
Ok(_) => {
env.insert("ENV".to_owned(), script_path);
env.insert("ENV", script_path);
}
Err(err) => {
log::warn!("unable to open {script_path}: {err}");
@@ -235,9 +235,9 @@ fn setup_bash(
}
}
env.insert("GHOSTTY_BASH_INJECT".to_owned(), inject);
env.insert("GHOSTTY_BASH_INJECT", inject);
if let Some(v) = rcfile {
env.insert("GHOSTTY_BASH_RCFILE".to_owned(), v);
env.insert("GHOSTTY_BASH_RCFILE", v);
}
// In POSIX mode, HISTFILE defaults to ~/.sh_history, so unless we're
@@ -245,8 +245,8 @@ fn setup_bash(
if !env.contains_key("HISTFILE")
&& let Some(home) = homedir::home()?
{
env.insert("HISTFILE".to_owned(), format!("{home}/.bash_history"));
env.insert("GHOSTTY_BASH_UNEXPORT_HISTFILE".to_owned(), "1".to_owned());
env.insert("HISTFILE", format!("{home}/.bash_history"));
env.insert("GHOSTTY_BASH_UNEXPORT_HISTFILE", "1");
}
// Return a copy of our modified command line to use as the shell command.
@@ -271,10 +271,7 @@ fn setup_xdg_data_dirs(resource_dir: &str, env: &mut EnvMap) -> bool {
// Set an env var so we can remove this from XDG_DATA_DIRS later.
// This happens in the shell integration config itself. We do this
// so that our modifications don't interfere with other commands.
env.insert(
"GHOSTTY_SHELL_INTEGRATION_XDG_DIR".to_owned(),
integ_path.clone(),
);
env.insert("GHOSTTY_SHELL_INTEGRATION_XDG_DIR", integ_path.clone());
// If no XDG_DATA_DIRS set use the default value as specified.
// This ensures that the default directories aren't lost by setting
@@ -283,9 +280,9 @@ fn setup_xdg_data_dirs(resource_dir: &str, env: &mut EnvMap) -> bool {
let key = "XDG_DATA_DIRS";
let current = env
.get(key)
.map_or("/usr/local/share:/usr/share", String::as_str);
let new = prepend_env(current, &integ_path);
env.insert(key.to_owned(), new);
.unwrap_or_else(|| std::ffi::OsStr::new("/usr/local/share:/usr/share"));
let new = prepend_env_os(current, std::ffi::OsStr::new(&integ_path));
env.insert(key, new);
true
}
@@ -356,8 +353,8 @@ fn setup_nushell(command: &Command, resource_dir: &str, env: &mut EnvMap) -> Opt
/// config then loads the true user config.
fn setup_zsh(command: &Command, resource_dir: &str, env: &mut EnvMap) -> Option<Command> {
// Preserve an existing ZDOTDIR value. We're about to overwrite it.
if let Some(old) = env.get("ZDOTDIR").cloned() {
env.insert("GHOSTTY_ZSH_ZDOTDIR".to_owned(), old);
if let Some(old) = env.get("ZDOTDIR").map(std::ffi::OsStr::to_owned) {
env.insert("GHOSTTY_ZSH_ZDOTDIR", old);
}
// Set our new ZDOTDIR to point to our shell resource directory.
@@ -367,7 +364,7 @@ fn setup_zsh(command: &Command, resource_dir: &str, env: &mut EnvMap) -> Option<
log::warn!("unable to open {integ_path}");
return None;
}
env.insert("ZDOTDIR".to_owned(), integ_path);
env.insert("ZDOTDIR", integ_path);
Some(command.clone())
}
@@ -494,7 +491,7 @@ mod tests {
);
assert_eq!(
"cursor:blink,path,ssh-env,ssh-terminfo,sudo,title",
env["GHOSTTY_SHELL_FEATURES"]
env.get("GHOSTTY_SHELL_FEATURES").unwrap().to_str().unwrap()
);
// all features disabled
@@ -513,7 +510,10 @@ mod tests {
},
true,
);
assert_eq!("ssh-env,sudo", env["GHOSTTY_SHELL_FEATURES"]);
assert_eq!(
"ssh-env,sudo",
env.get("GHOSTTY_SHELL_FEATURES").unwrap().to_str().unwrap()
);
// blinking cursor
let only_cursor = ShellIntegrationFeatures {
@@ -522,19 +522,28 @@ mod tests {
};
let mut env = EnvMap::new();
setup_features(&mut env, only_cursor, true);
assert_eq!("cursor:blink", env["GHOSTTY_SHELL_FEATURES"]);
assert_eq!(
"cursor:blink",
env.get("GHOSTTY_SHELL_FEATURES").unwrap().to_str().unwrap()
);
// steady cursor
let mut env = EnvMap::new();
setup_features(&mut env, only_cursor, false);
assert_eq!("cursor:steady", env["GHOSTTY_SHELL_FEATURES"]);
assert_eq!(
"cursor:steady",
env.get("GHOSTTY_SHELL_FEATURES").unwrap().to_str().unwrap()
);
}
#[test]
fn default_features() {
let mut env = EnvMap::new();
setup_features(&mut env, ShellIntegrationFeatures::default(), true);
assert_eq!("cursor:blink,path,title", env["GHOSTTY_SHELL_FEATURES"]);
assert_eq!(
"cursor:blink,path,title",
env.get("GHOSTTY_SHELL_FEATURES").unwrap().to_str().unwrap()
);
}
#[test]
@@ -544,8 +553,14 @@ mod tests {
let command = setup_bash(&sh("bash"), &res.path, &mut env).unwrap();
assert_eq!("bash --posix", shell_str(command.as_ref()));
assert_eq!("1", env["GHOSTTY_BASH_INJECT"]);
assert_eq!(format!("{}/ghostty.bash", res.shell_path), env["ENV"]);
assert_eq!(
"1",
env.get("GHOSTTY_BASH_INJECT").unwrap().to_str().unwrap()
);
assert_eq!(
format!("{}/ghostty.bash", res.shell_path),
env.get("ENV").unwrap().to_str().unwrap()
);
}
#[test]
@@ -575,12 +590,18 @@ mod tests {
let mut env = EnvMap::new();
let command = setup_bash(&sh("bash --norc"), &res.path, &mut env).unwrap();
assert_eq!("bash --posix", shell_str(command.as_ref()));
assert_eq!("1 --norc", env["GHOSTTY_BASH_INJECT"]);
assert_eq!(
"1 --norc",
env.get("GHOSTTY_BASH_INJECT").unwrap().to_str().unwrap()
);
let mut env = EnvMap::new();
let command = setup_bash(&sh("bash --noprofile"), &res.path, &mut env).unwrap();
assert_eq!("bash --posix", shell_str(command.as_ref()));
assert_eq!("1 --noprofile", env["GHOSTTY_BASH_INJECT"]);
assert_eq!(
"1 --noprofile",
env.get("GHOSTTY_BASH_INJECT").unwrap().to_str().unwrap()
);
}
#[test]
@@ -590,11 +611,17 @@ mod tests {
let command = setup_bash(&sh("bash --rcfile profile.sh"), &res.path, &mut env).unwrap();
assert_eq!("bash --posix", shell_str(command.as_ref()));
assert_eq!("profile.sh", env["GHOSTTY_BASH_RCFILE"]);
assert_eq!(
"profile.sh",
env.get("GHOSTTY_BASH_RCFILE").unwrap().to_str().unwrap()
);
let command = setup_bash(&sh("bash --init-file profile.sh"), &res.path, &mut env).unwrap();
assert_eq!("bash --posix", shell_str(command.as_ref()));
assert_eq!("profile.sh", env["GHOSTTY_BASH_RCFILE"]);
assert_eq!(
"profile.sh",
env.get("GHOSTTY_BASH_RCFILE").unwrap().to_str().unwrap()
);
}
#[test]
@@ -605,15 +632,27 @@ mod tests {
temp_env::with_var("HOME", Some("/home/test"), || {
let mut env = EnvMap::new();
setup_bash(&sh("bash"), &res.path, &mut env).unwrap();
assert!(env["HISTFILE"].ends_with(".bash_history"));
assert_eq!("1", env["GHOSTTY_BASH_UNEXPORT_HISTFILE"]);
assert!(
env.get("HISTFILE")
.unwrap()
.to_str()
.unwrap()
.ends_with(".bash_history")
);
assert_eq!(
"1",
env.get("GHOSTTY_BASH_UNEXPORT_HISTFILE")
.unwrap()
.to_str()
.unwrap()
);
});
// HISTFILE set
let mut env = EnvMap::new();
env.insert("HISTFILE".into(), "my_history".into());
env.insert("HISTFILE", "my_history");
setup_bash(&sh("bash"), &res.path, &mut env).unwrap();
assert_eq!("my_history", env["HISTFILE"]);
assert_eq!("my_history", env.get("HISTFILE").unwrap().to_str().unwrap());
assert!(!env.contains_key("GHOSTTY_BASH_UNEXPORT_HISTFILE"));
}
@@ -621,11 +660,17 @@ mod tests {
fn bash_env() {
let res = TmpResourcesDir::new(Shell::Bash);
let mut env = EnvMap::new();
env.insert("ENV".into(), "env.sh".into());
env.insert("ENV", "env.sh");
setup_bash(&sh("bash"), &res.path, &mut env).unwrap();
assert_eq!("env.sh", env["GHOSTTY_BASH_ENV"]);
assert_eq!(format!("{}/ghostty.bash", res.shell_path), env["ENV"]);
assert_eq!(
"env.sh",
env.get("GHOSTTY_BASH_ENV").unwrap().to_str().unwrap()
);
assert_eq!(
format!("{}/ghostty.bash", res.shell_path),
env.get("ENV").unwrap().to_str().unwrap()
);
}
#[test]
@@ -667,11 +712,14 @@ mod tests {
assert!(setup_xdg_data_dirs(&res.path, &mut env));
assert_eq!(
format!("{}/shell-integration", res.path),
env["GHOSTTY_SHELL_INTEGRATION_XDG_DIR"]
env.get("GHOSTTY_SHELL_INTEGRATION_XDG_DIR")
.unwrap()
.to_str()
.unwrap()
);
assert_eq!(
format!("{}/shell-integration:/usr/local/share:/usr/share", res.path),
env["XDG_DATA_DIRS"]
env.get("XDG_DATA_DIRS").unwrap().to_str().unwrap()
);
}
@@ -679,16 +727,19 @@ mod tests {
fn xdg_existing_xdg_data_dirs() {
let res = TmpResourcesDir::new(Shell::Fish);
let mut env = EnvMap::new();
env.insert("XDG_DATA_DIRS".into(), "/opt/share".into());
env.insert("XDG_DATA_DIRS", "/opt/share");
assert!(setup_xdg_data_dirs(&res.path, &mut env));
assert_eq!(
format!("{}/shell-integration", res.path),
env["GHOSTTY_SHELL_INTEGRATION_XDG_DIR"]
env.get("GHOSTTY_SHELL_INTEGRATION_XDG_DIR")
.unwrap()
.to_str()
.unwrap()
);
assert_eq!(
format!("{}/shell-integration:/opt/share", res.path),
env["XDG_DATA_DIRS"]
env.get("XDG_DATA_DIRS").unwrap().to_str().unwrap()
);
}
@@ -710,9 +761,18 @@ mod tests {
assert_eq!("nu --execute 'use ghostty *'", shell_str(command.as_ref()));
assert_eq!(
format!("{}/shell-integration", res.path),
env["GHOSTTY_SHELL_INTEGRATION_XDG_DIR"]
env.get("GHOSTTY_SHELL_INTEGRATION_XDG_DIR")
.unwrap()
.to_str()
.unwrap()
);
assert!(
env.get("XDG_DATA_DIRS")
.unwrap()
.to_str()
.unwrap()
.starts_with(&format!("{}/shell-integration", res.path))
);
assert!(env["XDG_DATA_DIRS"].starts_with(&format!("{}/shell-integration", res.path)));
}
#[test]
@@ -747,7 +807,10 @@ mod tests {
let command = setup_zsh(&sh("zsh"), &res.path, &mut env);
assert_eq!("zsh", shell_str(command.as_ref()));
assert_eq!(res.shell_path, env["ZDOTDIR"]);
assert_eq!(
res.shell_path,
env.get("ZDOTDIR").unwrap().to_str().unwrap()
);
assert!(!env.contains_key("GHOSTTY_ZSH_ZDOTDIR"));
}
@@ -755,12 +818,18 @@ mod tests {
fn zsh_zdotdir() {
let res = TmpResourcesDir::new(Shell::Zsh);
let mut env = EnvMap::new();
env.insert("ZDOTDIR".into(), "$HOME/.config/zsh".into());
env.insert("ZDOTDIR", "$HOME/.config/zsh");
let command = setup_zsh(&sh("zsh"), &res.path, &mut env);
assert_eq!("zsh", shell_str(command.as_ref()));
assert_eq!(res.shell_path, env["ZDOTDIR"]);
assert_eq!("$HOME/.config/zsh", env["GHOSTTY_ZSH_ZDOTDIR"]);
assert_eq!(
res.shell_path,
env.get("ZDOTDIR").unwrap().to_str().unwrap()
);
assert_eq!(
"$HOME/.config/zsh",
env.get("GHOSTTY_ZSH_ZDOTDIR").unwrap().to_str().unwrap()
);
}
#[test]
@@ -780,7 +849,13 @@ mod tests {
let mut env = EnvMap::new();
let r = setup(root, &sh("bash"), &mut env, None).unwrap().unwrap();
assert_eq!(r.shell, Shell::Bash);
assert!(env["ENV"].ends_with("shell-integration/bash/ghostty.bash"));
assert!(
env.get("ENV")
.unwrap()
.to_str()
.unwrap()
.ends_with("shell-integration/bash/ghostty.bash")
);
assert!(
Path::new(root)
.join("shell-integration/nushell/vendor/autoload/ghostty.nu")
+12 -16
View File
@@ -933,19 +933,15 @@ impl StreamHandler<'_> {
return Ok(());
}
let Ok(url_str) = std::str::from_utf8(url) else {
log::warn!("invalid url in OSC 7: not utf-8");
return Ok(());
};
// Attempt to parse this file-style URI using options appropriate
// for this OSC 7 context (e.g. kitty-shell-cwd expects the full,
// unencoded path).
let uri = match ghostty_os::uri::parse(
url_str,
// unencoded path). Parsing is byte based so non-UTF-8 path bytes
// survive percent-decoding.
let uri = match ghostty_os::uri::parse_bytes(
url,
ghostty_os::uri::ParseOptions {
mac_address: true,
raw_path: url_str.starts_with("kitty-shell-cwd://"),
raw_path: url.starts_with(b"kitty-shell-cwd://"),
},
) {
Ok(uri) => uri,
@@ -967,12 +963,11 @@ impl StreamHandler<'_> {
log::warn!("OSC 7 uri must contain a hostname: UriMissingHost");
return Ok(());
};
let host = host.to_raw();
// OSC 7 is a little sketchy because anyone can send any value from
// any host (such an SSH session). The best practice terminals follow
// is to valid the hostname to be local.
let host_valid = match ghostty_os::hostname::is_local(&host) {
let host_valid = match ghostty_os::hostname::is_local(host) {
Ok(v) => v,
Err(err) => {
log::warn!("failed to get hostname for OSC 7 validation: {err:?}");
@@ -985,17 +980,18 @@ impl StreamHandler<'_> {
}
// We need the raw path, which might require unescaping.
let path = uri.path.to_raw().into_owned();
let path = uri.path;
log::debug!("terminal pwd: {path}");
self.terminal.set_pwd(path.as_bytes())?;
log::debug!("terminal pwd: {}", String::from_utf8_lossy(&path));
self.terminal.set_pwd(&path)?;
// Report it to the surface.
self.surface_message_writer(SurfaceMessage::PwdChange(WriteReq::init(path.as_bytes())));
self.surface_message_writer(SurfaceMessage::PwdChange(WriteReq::init(&path)));
// If we haven't seen a title, use our pwd as the title.
if !self.st.seen_title {
self.window_title(&path);
// Titles are text; only the title is lossy.
self.window_title(&String::from_utf8_lossy(&path));
self.st.seen_title = false;
}
Ok(())
+24 -3
View File
@@ -34,6 +34,7 @@ use ghostty_config::types_b::{ClipboardAccess, GraphemeWidthMethod, OSCColorRepo
use ghostty_datastruct::blocking_queue::Timeout;
use ghostty_renderer::message::Message as RendererMessage;
use ghostty_renderer::size::Size;
use ghostty_renderer::state::InspectorHook;
use ghostty_terminal::kitty::graphics_storage::TerminalInfo;
use ghostty_terminal::point::{Coordinate, Point};
use ghostty_terminal::screen::Scroll;
@@ -221,8 +222,9 @@ impl Output {
// the lock to grab our read data.
let outbox = {
let mut term = self.state.lock_terminal();
let inspector = term.state().inspector.clone();
let mut inner = self.inner();
self.process_output_locked(&mut term, &mut inner, buf);
self.process_output_locked(&mut term, &mut inner, buf, inspector.as_deref());
// If our stream handling caused messages to be sent to the
// mailbox thread, then we need to wake it up so that it
@@ -241,7 +243,13 @@ impl Output {
}
/// Process output from the pty but the lock is already held.
fn process_output_locked(&self, term: &mut Terminal, inner: &mut OutputInner, buf: &[u8]) {
fn process_output_locked(
&self,
term: &mut Terminal,
inner: &mut OutputInner,
buf: &[u8],
inspector: Option<&dyn InspectorHook>,
) {
// Schedule a render. We can call this first because we have the lock.
inner.stream.state.queue_render();
@@ -260,7 +268,20 @@ impl Output {
.push(RendererMessage::ResetCursorBlink, Timeout::Instant);
}
if let Err(err) = inner.stream.process(term, buf) {
// If we have an inspector, we enter SLOW MODE because we need to
// process a byte at a time alternating between the inspector handler
// and the termio handler. This is very slow compared to our
// optimizations below but at least users only pay for it if they're
// using the inspector.
if let Some(insp) = inspector {
for &byte in buf {
insp.record_pty_read(term, &[byte]);
if let Err(err) = inner.stream.process_byte(term, byte) {
log::error!("error processing terminal data: {err:?}");
}
}
} else if let Err(err) = inner.stream.process(term, buf) {
log::error!("error processing terminal data: {err:?}");
}
}
@@ -287,9 +287,13 @@ fn large_write_with_backpressure_is_delivered_in_order() {
// queue (the pty buffer is far smaller) and the output reader at the
// same time (cat would otherwise block on a full pty).
let mut f = start(
sh("stty raw -echo; head -c 262144 | wc -c; echo done"),
sh("stty raw -echo; echo ready; head -c 262144 | wc -c; echo done"),
|_| {},
);
// Writing before `stty raw` applies would go through the cooked-mode
// line discipline, which silently drops bytes past MAX_CANON (4095)
// on a line without a newline.
f.wait_text("ready");
let chunk = vec![b'x'; 4096];
for _ in 0..64 {
f.write(&chunk);
@@ -555,7 +559,7 @@ fn change_config_message_updates_palette_and_colors() {
fn process_output_manual_api() {
// Termio can also be fed manually (no child involved).
let config = base_config();
let mut ecfg = exec::Config::new(std::collections::HashMap::new(), "xterm-256color");
let mut ecfg = exec::Config::new(ghostty_os::EnvMap::new(), "xterm-256color");
ecfg.command = Some(sh("true"));
let (tx, _rx) = unbounded();
let termio = Termio::init(Options {