test(core): add headless end-to-end tests and fix bugs they found

Adds crates/ghostty-core/tests/e2e_*.rs: 81 tests that drive the real
core Surface, termio, pty and child processes through a fake runtime
(recording apprt actions, in-memory clipboard) with a headless renderer
(ghostty-renderer/src/headless.rs). They cover keys (legacy, DECCKM,
kitty, modifyOtherKeys), keybinding actions and sequences, mouse
selection/reporting/scrolling/links, clipboard incl. OSC 52 and paste
safety, resize, focus, titles/pwd/bell/notifications/progress, child
exit, and IME preedit.

Fixes for issues found by the tests and by the Codex audit
(docs/rewrite/notes/review-core-codex.md, all 9 items):
- replacing a selection with copy-on-select panicked (stale tracked
  handles); global new_window no longer inherits a parent; the child
  environment uses the runtime's env wholesale so GTK's removals stick;
  Flatpak host resources path; locale recovery (ensureLocale) in
  apprt-gtk before GTK init and for CLI actions; failed screen-file
  opens propagate errors; OSC 52 base64 rules, CSI/ESC binding length
  limits and GHOSTTY_LOG parsing match Zig.
- Also includes V2's termio cleanups (tmux viewer wiring in the stream
  handler, Pty slave semantics docs, shared cgroup wait loop).

apprt-gtk gains a debug input replay hook (GHOSTTY_DEBUG_INPUT_SCRIPT)
exercising the real GTK key path. With it, the real app was verified on
Wayland: typing and output, new tab, splits, select-all/copy/paste and
font size all work (docs/rewrite/notes/verification-V1.md). Not yet
exercised at GTK level: mouse, real IM-context IME, clipboard dialogs.

Test Plan:
- cargo test --workspace (2983 passed)
- cargo test -p ghostty-core --tests (81 e2e tests)
This commit is contained in:
ddidderr committed 2026-10-12 03:58:19 +02:00
1 parent d650e5171b
commit be6d706ba5
33 files changed
+3016 -222

No files matched your search

@@ -192,16 +192,63 @@ fn set_gtk_env(config: &CoreConfig) {
set_env("GDK_DISABLE", &gdk_disable);
}
/// Call `setlocale(LC_ALL, "")` like Ghostty's `global.zig` does at startup
/// (see docs/rewrite/INTEGRATION_TODO.md). Idempotent.
/// Port of Ghostty's `os/locale.zig` `ensureLocale` (called from
/// `global.zig` at startup): set the process locale from the environment and,
/// if that fails (usually an invalid `LANG`), retry with `LANG` unset, then fall
/// back to `en_US.UTF-8` (updating `LANG` on success). Idempotent. This must
/// run before GTK initializes and before the child environment is captured.
#[allow(unsafe_code)]
pub fn init_locale() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
// SAFETY: called with a valid NUL-terminated empty string at startup
// before other threads depend on the locale.
// SAFETY: all strings are valid NUL-terminated C strings; this runs at
// startup before other threads read the environment or locale.
unsafe {
libc::setlocale(libc::LC_ALL, c"".as_ptr());
fn show(p: *const libc::c_char) -> String {
// SAFETY: setlocale returns a valid C string when non-null.
unsafe { std::ffi::CStr::from_ptr(p) }
.to_string_lossy()
.into_owned()
}
// Set the locale to whatever is set in env vars.
let r = libc::setlocale(libc::LC_ALL, c"".as_ptr());
if !r.is_null() {
log::info!("setlocale from env result={}", show(r));
return;
}
// setlocale failed, probably because LANG is invalid. Try again
// without LANG to use the system default.
if std::env::var_os("LANG").is_some_and(|v| !v.is_empty()) {
// Both so that LANG is either empty or unset completely.
libc::setenv(c"LANG".as_ptr(), c"".as_ptr(), 1);
libc::unsetenv(c"LANG".as_ptr());
let r = libc::setlocale(libc::LC_ALL, c"".as_ptr());
if !r.is_null() {
let v = show(r);
log::info!("setlocale after unset lang result={v}");
// An unsupported locale yields the "C" fallback; we
// prefer moving on to en_US.UTF-8 in that case.
if v != "C" {
return;
}
}
}
// Failure again... fallback to en_US.UTF-8
log::warn!(
"setlocale failed with LANG and system default. Falling back to en_US.UTF-8"
);
let r = libc::setlocale(libc::LC_ALL, c"en_US.UTF-8".as_ptr());
if r.is_null() {
log::warn!("setlocale failed even with the fallback, uncertain results");
} else {
libc::setenv(c"LANG".as_ptr(), c"en_US.UTF-8".as_ptr(), 1);
log::info!("setlocale default result={}", show(r));
}
}
});
}
@@ -605,6 +652,9 @@ impl Application {
// Tell systemd that we are ready.
ghostty_os::systemd::notify::ready();
// Developer aid: replay synthesized input (GHOSTTY_DEBUG_INPUT_SCRIPT).
crate::debug_input::start(self);
log::debug!("entering runloop");
let imp = self.imp();
imp.running.set(true);
@@ -128,13 +128,16 @@ mod imp {
}
#[template_callback]
fn reveal_clicked(&self, _button: &gtk::Button) {
self.set_blurred(false, false, true);
fn reveal_clicked(_button: &gtk::Button, this: &super::ClipboardConfirmationDialog) {
// The signal emitter is the button, so the dialog arrives as the
// trailing user-data argument (a `&self` receiver would be
// matched against the button and panic).
this.imp().set_blurred(false, false, true);
}
#[template_callback]
fn hide_clicked(&self, _button: &gtk::Button) {
self.set_blurred(true, true, false);
fn hide_clicked(_button: &gtk::Button, this: &super::ClipboardConfirmationDialog) {
this.imp().set_blurred(true, true, false);
}
}
@@ -940,18 +940,36 @@ mod split_imp {
#[gtk::template_callbacks]
impl SplitTreeSplit {
#[template_callback]
fn notify_max_position(&self, _pspec: glib::ParamSpec) {
self.obj().refresh();
fn notify_max_position(
_paned: &gtk::Paned,
_pspec: glib::ParamSpec,
this: &super::SplitTreeSplit,
) {
// The emitter is the child `Paned`; the template instance is the
// trailing user-data argument.
this.refresh();
}
#[template_callback]
fn notify_min_position(&self, _pspec: glib::ParamSpec) {
self.obj().refresh();
fn notify_min_position(
_paned: &gtk::Paned,
_pspec: glib::ParamSpec,
this: &super::SplitTreeSplit,
) {
// The emitter is the child `Paned`; the template instance is the
// trailing user-data argument.
this.refresh();
}
#[template_callback]
fn notify_position(&self, _pspec: glib::ParamSpec) {
self.obj().refresh();
fn notify_position(
_paned: &gtk::Paned,
_pspec: glib::ParamSpec,
this: &super::SplitTreeSplit,
) {
// The emitter is the child `Paned`; the template instance is the
// trailing user-data argument.
this.refresh();
}
}
+122 -11
View File
@@ -32,6 +32,7 @@ use ghostty_input::{Action as KeyAction, Key, KeyEvent, Mods, MouseButton, Mouse
use ghostty_vt::mouse_shape::MouseShape;
use ghostty_vt::osc::{ProgressReport, ProgressState};
use gtk::glib::subclass::Signal;
use gtk::glib::translate::{FromGlib, IntoGlib};
use gtk::{gdk, gio, glib};
use crate::class::application::Application;
@@ -650,16 +651,88 @@ impl Surface {
// scenario we reach this point with im_len > 0 and that's if we
// received a commit event from the input method. We don't want to
// keep that state around since we've handled it here.
let result = self.key_event_encode(action, &event, &key_event, keyval, keycode, gtk_mods);
let result = self.key_event_encode(
action,
&KeySource::Event {
event: &event,
key_event: &key_event,
},
keyval,
keycode,
gtk_mods,
);
imp.im_buf.borrow_mut().clear();
result
}
/// Debug input replay (`GHOSTTY_DEBUG_INPUT_SCRIPT`): feed a synthesized
/// key event through the same encoding path as [`Surface::key_event`]
/// (physical key lookup, keyval translation, modifier translation, then
/// `key_callback`). The only part skipped is the input method filter
/// (it needs a real `GdkEvent`); text is committed through
/// [`Surface::debug_commit_text`] instead.
///
/// `keyval`/`keycode`/`state` are what GTK's key controller would pass.
pub fn debug_key_event(
&self,
action: KeyAction,
keyval: u32,
keycode: u32,
state: gdk::ModifierType,
) -> bool {
let display = self.imp().gl_area.display();
// What `GdkKeyEvent::keyval()/consumed_modifiers()/layout()` would
// report for this keycode+state (group 0).
let (translated, consumed) = display.translate_key(keycode, state, 0).map_or(
(
{
// SAFETY: GdkKey wraps a plain keyval integer.
#[allow(unsafe_code)]
unsafe {
gdk::Key::from_glib(keyval)
}
},
gdk::ModifierType::empty(),
),
|t| (t.0, t.3),
);
let result = self.key_event_encode(
action,
&KeySource::Synthetic {
translated,
layout: 0,
consumed,
},
translated.into_glib(),
keycode,
state,
);
self.imp().im_buf.borrow_mut().clear();
result
}
/// Debug input replay: write the renderer's last frame to `path` (PNG).
pub fn debug_screenshot(&self, path: &str) {
let Some(core) = self.core() else { return };
// The renderer reads back from the GL context.
self.imp().gl_area.make_current();
self.imp().gl_area.queue_render();
match core.write_screenshot(path) {
Ok(()) => log::warn!("debug input: wrote screenshot {path}"),
Err(err) => log::error!("debug input: screenshot failed: {err}"),
}
}
/// Debug input replay: commit text as the input method would (the
/// `commit` signal of the IM context), outside of any key event.
pub fn debug_commit_text(&self, text: &str) {
self.imp().im_context.emit_by_name::<()>("commit", &[&text]);
}
fn key_event_encode(
&self,
action: KeyAction,
event: &gdk::Event,
key_event: &gdk::KeyEvent,
src: &KeySource<'_>,
keyval: u32,
keycode: u32,
gtk_mods: gdk::ModifierType,
@@ -667,9 +740,18 @@ impl Surface {
let imp = self.imp();
// Get the keyvals for this event.
let keyval_unicode: Option<char> = key_event.keyval().to_unicode();
let keyval_unicode_unshifted =
gtk_key::keyval_unicode_unshifted(&*imp.gl_area, key_event, keycode);
let keyval_unicode: Option<char> = match src {
KeySource::Event { key_event, .. } => key_event.keyval().to_unicode(),
KeySource::Synthetic { translated, .. } => translated.to_unicode(),
};
let keyval_unicode_unshifted = match src {
KeySource::Event { key_event, .. } => {
gtk_key::keyval_unicode_unshifted(&*imp.gl_area, key_event, keycode)
}
KeySource::Synthetic { layout, .. } => {
gtk_key::keyval_unicode_unshifted_for_layout(&*imp.gl_area, *layout, keycode)
}
};
// We want to get the physical unmapped key to process physical
// keybinds. (These are keybinds explicitly marked as requesting
@@ -699,13 +781,28 @@ impl Surface {
// Get our modifier for the event
let application = app();
let mods: Mods = gtk_key::event_mods(event, physical_key, gtk_mods, action, |dev, m| {
application.winproto().event_mods(dev, m)
});
let device = match src {
KeySource::Event { event, .. } => event.device(),
KeySource::Synthetic { .. } => imp
.gl_area
.display()
.default_seat()
.and_then(|s| s.keyboard()),
};
let mods: Mods = gtk_key::event_mods_for_device(
device.as_ref(),
physical_key,
gtk_mods,
action,
|dev, m| application.winproto().event_mods(dev, m),
);
// Get our consumed modifiers
let consumed_mods: Mods =
gtk_key::translate_mods(key_event.consumed_modifiers() & gdk::MODIFIER_MASK);
let consumed = match src {
KeySource::Event { key_event, .. } => key_event.consumed_modifiers(),
KeySource::Synthetic { consumed, .. } => *consumed,
};
let consumed_mods: Mods = gtk_key::translate_mods(consumed & gdk::MODIFIER_MASK);
// If we have no UTF-8 text, we try to convert our keyval to
// a text value. We have to do this because GTK will not process
@@ -1758,6 +1855,20 @@ fn compute_fraction(progress: u8) -> f64 {
f64::from(progress.min(100)) / 100.0
}
/// Where the data for the key encoding path comes from: a real GDK key event
/// or a synthesized one (debug input replay).
enum KeySource<'a> {
Event {
event: &'a gdk::Event,
key_event: &'a gdk::KeyEvent,
},
Synthetic {
translated: gdk::Key,
layout: u32,
consumed: gdk::ModifierType,
},
}
// ---------------------------------------------------------------------
// Apprt Surface (Surface.zig)