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:
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: >k::Button) {
|
||||
self.set_blurred(false, false, true);
|
||||
fn reveal_clicked(_button: >k::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: >k::Button) {
|
||||
self.set_blurred(true, true, false);
|
||||
fn hide_clicked(_button: >k::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: >k::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: >k::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: >k::Paned,
|
||||
_pspec: glib::ParamSpec,
|
||||
this: &super::SplitTreeSplit,
|
||||
) {
|
||||
// The emitter is the child `Paned`; the template instance is the
|
||||
// trailing user-data argument.
|
||||
this.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Debug-only input replay (`GHOSTTY_DEBUG_INPUT_SCRIPT=<file>`).
|
||||
//!
|
||||
//! Compositors under test (niri) do not let us inject keys into a window, so
|
||||
//! this hook synthesizes the events inside the process, at the same entry
|
||||
//! points the GTK handlers use: key events go through
|
||||
//! `Surface::debug_key_event` (the keyval/keycode/state translation of
|
||||
//! `Surface::key_event`, i.e. `gtk/key.rs`, then `key_callback`) and text goes
|
||||
//! through the IM context's `commit` signal (`im_commit`).
|
||||
//!
|
||||
//! Script format, one command per line (`#` starts a comment):
|
||||
//!
|
||||
//! ```text
|
||||
//! key ctrl+shift+t # press+release; mods: ctrl shift alt super
|
||||
//! text hello world # IM commit of the rest of the line
|
||||
//! wait 200 # milliseconds
|
||||
//! screenshot /abs/out.png # dump the renderer's last frame (PNG)
|
||||
//! quit # quit the application
|
||||
//! ```
|
||||
//!
|
||||
//! Key names are GDK keysym names (`t`, `Return`, `Tab`, `equal`, `Up`, `F5`)
|
||||
//! with a few lowercase aliases (`enter`, `esc`, `up`, ...). Commands act on
|
||||
//! the active surface of the active window at the time they run.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use gtk::glib::translate::IntoGlib;
|
||||
use gtk::prelude::*;
|
||||
use gtk::{gdk, glib};
|
||||
|
||||
use crate::class::application::Application;
|
||||
use crate::class::surface::Surface;
|
||||
use crate::class::window::Window;
|
||||
|
||||
/// One parsed command.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Step {
|
||||
Key(String),
|
||||
Text(String),
|
||||
Wait(u64),
|
||||
Screenshot(String),
|
||||
Quit,
|
||||
}
|
||||
|
||||
/// Parse a script. Errors carry the 1-based line number.
|
||||
pub fn parse(script: &str) -> Result<Vec<Step>, String> {
|
||||
let mut steps = Vec::new();
|
||||
for (i, raw) in script.lines().enumerate() {
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let (cmd, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
|
||||
let rest = rest.trim_start();
|
||||
let err = |m: &str| format!("line {}: {m}", i + 1);
|
||||
steps.push(match cmd {
|
||||
"key" if !rest.is_empty() => Step::Key(rest.to_owned()),
|
||||
"text" if !rest.is_empty() => Step::Text(rest.to_owned()),
|
||||
"wait" => Step::Wait(rest.parse().map_err(|_| err("wait needs milliseconds"))?),
|
||||
"screenshot" if !rest.is_empty() => Step::Screenshot(rest.to_owned()),
|
||||
"quit" => Step::Quit,
|
||||
_ => return Err(err(&format!("bad command {line:?}"))),
|
||||
});
|
||||
}
|
||||
Ok(steps)
|
||||
}
|
||||
|
||||
/// Parse `ctrl+shift+t` into (keyval, state).
|
||||
pub fn parse_key(spec: &str) -> Result<(gdk::Key, gdk::ModifierType), String> {
|
||||
let mut state = gdk::ModifierType::empty();
|
||||
let parts: Vec<&str> = spec.split('+').collect();
|
||||
let (name, mods) = parts.split_last().ok_or("empty key")?;
|
||||
// "ctrl++" style: the key itself is "+"
|
||||
let (name, mods) = if name.is_empty() {
|
||||
("plus", &mods[..mods.len().saturating_sub(1)])
|
||||
} else {
|
||||
(*name, mods)
|
||||
};
|
||||
for m in mods {
|
||||
state |= match m.to_ascii_lowercase().as_str() {
|
||||
"ctrl" | "control" => gdk::ModifierType::CONTROL_MASK,
|
||||
"shift" => gdk::ModifierType::SHIFT_MASK,
|
||||
"alt" => gdk::ModifierType::ALT_MASK,
|
||||
"super" | "meta" => gdk::ModifierType::SUPER_MASK,
|
||||
other => return Err(format!("unknown modifier {other:?}")),
|
||||
};
|
||||
}
|
||||
let alias = match name.to_ascii_lowercase().as_str() {
|
||||
"enter" | "return" => "Return",
|
||||
"esc" | "escape" => "Escape",
|
||||
"tab" => "Tab",
|
||||
"space" => "space",
|
||||
"backspace" => "BackSpace",
|
||||
"delete" => "Delete",
|
||||
"up" => "Up",
|
||||
"down" => "Down",
|
||||
"left" => "Left",
|
||||
"right" => "Right",
|
||||
"home" => "Home",
|
||||
"end" => "End",
|
||||
"pageup" | "page_up" => "Page_Up",
|
||||
"pagedown" | "page_down" => "Page_Down",
|
||||
"insert" => "Insert",
|
||||
_ => name,
|
||||
};
|
||||
let key = gdk::Key::from_name(alias)
|
||||
.or_else(|| gdk::Key::from_name(name))
|
||||
.ok_or_else(|| format!("unknown key {name:?}"))?;
|
||||
Ok((key, state))
|
||||
}
|
||||
|
||||
/// Start the replay if `GHOSTTY_DEBUG_INPUT_SCRIPT` is set.
|
||||
pub fn start(app: &Application) {
|
||||
let Some(path) = std::env::var_os("GHOSTTY_DEBUG_INPUT_SCRIPT") else {
|
||||
return;
|
||||
};
|
||||
let script = match std::fs::read_to_string(&path) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
log::error!("debug input: cannot read {}: {err}", path.to_string_lossy());
|
||||
return;
|
||||
}
|
||||
};
|
||||
let steps = match parse(&script) {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
log::error!("debug input: {err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
log::warn!("debug input: replaying {} steps", steps.len());
|
||||
let runner = Rc::new(Runner {
|
||||
app: app.clone(),
|
||||
steps,
|
||||
next: RefCell::new(0),
|
||||
});
|
||||
// Wait for the first surface to be ready (realized, core initialized).
|
||||
glib::timeout_add_local(Duration::from_millis(100), move || {
|
||||
if runner.active_surface().is_some_and(|s| s.core().is_some()) {
|
||||
runner.run();
|
||||
glib::ControlFlow::Break
|
||||
} else {
|
||||
glib::ControlFlow::Continue
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
struct Runner {
|
||||
app: Application,
|
||||
steps: Vec<Step>,
|
||||
next: RefCell<usize>,
|
||||
}
|
||||
|
||||
impl Runner {
|
||||
fn active_surface(&self) -> Option<Surface> {
|
||||
self.app
|
||||
.active_window()?
|
||||
.downcast::<Window>()
|
||||
.ok()?
|
||||
.get_active_surface()
|
||||
}
|
||||
|
||||
/// Run steps until the next `wait`, which reschedules us.
|
||||
fn run(self: &Rc<Self>) {
|
||||
loop {
|
||||
let idx = *self.next.borrow();
|
||||
let Some(step) = self.steps.get(idx).cloned() else {
|
||||
log::warn!("debug input: script finished");
|
||||
return;
|
||||
};
|
||||
*self.next.borrow_mut() += 1;
|
||||
log::warn!("debug input: {step:?}");
|
||||
match step {
|
||||
Step::Wait(ms) => {
|
||||
let this = Rc::clone(self);
|
||||
glib::timeout_add_local_once(Duration::from_millis(ms), move || this.run());
|
||||
return;
|
||||
}
|
||||
Step::Quit => {
|
||||
self.app.quit();
|
||||
return;
|
||||
}
|
||||
Step::Key(spec) => self.key(&spec),
|
||||
Step::Text(text) => match self.active_surface() {
|
||||
Some(s) => s.debug_commit_text(&text),
|
||||
None => log::warn!("debug input: no active surface"),
|
||||
},
|
||||
Step::Screenshot(path) => match self.active_surface() {
|
||||
Some(s) => s.debug_screenshot(&path),
|
||||
None => log::warn!("debug input: no active surface"),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key(&self, spec: &str) {
|
||||
let Some(surface) = self.active_surface() else {
|
||||
log::warn!("debug input: no active surface");
|
||||
return;
|
||||
};
|
||||
let (key, state) = match parse_key(spec) {
|
||||
Ok(v) => v,
|
||||
Err(err) => {
|
||||
log::error!("debug input: {err}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let display = surface.display();
|
||||
let Some(keycode) = display
|
||||
.map_keyval(key)
|
||||
.and_then(|keys| keys.first().map(gdk::KeymapKey::keycode))
|
||||
else {
|
||||
log::error!("debug input: no keycode for {spec:?}");
|
||||
return;
|
||||
};
|
||||
// What GTK reports as `keyval` to the key controller is the
|
||||
// translated keyval; the encode path translates again from keycode.
|
||||
let keyval = key.into_glib();
|
||||
surface.debug_key_event(ghostty_input::key::Action::Press, keyval, keycode, state);
|
||||
surface.debug_key_event(ghostty_input::key::Action::Release, keyval, keycode, state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_script() {
|
||||
let s =
|
||||
"# c\n\nkey ctrl+shift+t\ntext hello world\nwait 200\nscreenshot /tmp/a.png\nquit\n";
|
||||
assert_eq!(
|
||||
parse(s).expect("valid script"),
|
||||
vec![
|
||||
Step::Key("ctrl+shift+t".into()),
|
||||
Step::Text("hello world".into()),
|
||||
Step::Wait(200),
|
||||
Step::Screenshot("/tmp/a.png".into()),
|
||||
Step::Quit
|
||||
]
|
||||
);
|
||||
assert!(parse("wait x").is_err());
|
||||
assert!(parse("bogus").is_err());
|
||||
}
|
||||
}
|
||||
@@ -101,11 +101,19 @@ pub fn keyval_unicode_unshifted(
|
||||
event: &gdk::KeyEvent,
|
||||
keycode: u32,
|
||||
) -> u32 {
|
||||
let display = widget.as_ref().display();
|
||||
|
||||
// We need the currently active keyboard layout so we know what group to
|
||||
// look at.
|
||||
let layout = event.layout();
|
||||
keyval_unicode_unshifted_for_layout(widget, event.layout(), keycode)
|
||||
}
|
||||
|
||||
/// Like [`keyval_unicode_unshifted`] with an explicit keyboard layout (group)
|
||||
/// instead of a `GdkKeyEvent`; used by the debug input replay.
|
||||
pub fn keyval_unicode_unshifted_for_layout(
|
||||
widget: &impl IsA<gtk::Widget>,
|
||||
layout: u32,
|
||||
keycode: u32,
|
||||
) -> u32 {
|
||||
let display = widget.as_ref().display();
|
||||
|
||||
// All possible keyboard mappings for this keycode (the physical key).
|
||||
let Some(entries) = display.map_keycode(keycode) else {
|
||||
@@ -132,10 +140,25 @@ pub fn event_mods(
|
||||
action: Action,
|
||||
winproto_event_mods: impl FnOnce(Option<&gdk::Device>, gdk::ModifierType) -> Mods,
|
||||
) -> Mods {
|
||||
let device = event.device();
|
||||
event_mods_for_device(
|
||||
event.device().as_ref(),
|
||||
physical_key,
|
||||
gtk_mods,
|
||||
action,
|
||||
winproto_event_mods,
|
||||
)
|
||||
}
|
||||
|
||||
let mut mods = winproto_event_mods(device.as_ref(), gtk_mods);
|
||||
mods.num_lock = device.as_ref().is_some_and(DeviceExt::is_num_locked);
|
||||
/// Like [`event_mods`] but with the (optional) device instead of the event.
|
||||
pub fn event_mods_for_device(
|
||||
device: Option<&gdk::Device>,
|
||||
physical_key: K,
|
||||
gtk_mods: gdk::ModifierType,
|
||||
action: Action,
|
||||
winproto_event_mods: impl FnOnce(Option<&gdk::Device>, gdk::ModifierType) -> Mods,
|
||||
) -> Mods {
|
||||
let mut mods = winproto_event_mods(device, gtk_mods);
|
||||
mods.num_lock = device.is_some_and(DeviceExt::is_num_locked);
|
||||
|
||||
// We use the physical key to determine sided modifiers. As far as I can
|
||||
// tell there's no other way to reliably determine this.
|
||||
|
||||
@@ -6,6 +6,7 @@ pub mod app;
|
||||
pub mod cgroup;
|
||||
pub mod class;
|
||||
pub mod css;
|
||||
pub mod debug_input;
|
||||
pub mod ext;
|
||||
pub mod flatpak;
|
||||
pub mod gl;
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
//! Parent post-fork hook creating the transient scope (port of
|
||||
//! `apprt/gtk/post_fork.zig`).
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use ghostty_config::config::Config;
|
||||
use ghostty_config::types_b::{GtkSingleInstance, LinuxCgroup};
|
||||
use gtk::gio;
|
||||
use gtk::prelude::*;
|
||||
|
||||
use crate::cgroup;
|
||||
use crate::pre_exec::current_scope_matches;
|
||||
|
||||
/// Allowable error from a post-fork hook; fails surface creation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
@@ -87,25 +84,16 @@ pub fn post_fork(info: &PostForkInfo, pid: Option<u32>) -> Result<(), PostForkEr
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if start.elapsed() > Duration::from_millis(250) {
|
||||
// Zig checks `rt_pre_exec_info.linux_cgroup_hard_fail` here;
|
||||
// both infos come from the same config so they're identical.
|
||||
if info.linux_cgroup_hard_fail {
|
||||
log::error!("transition to new transient systemd scope {expected} took too long");
|
||||
return Err(PostForkError);
|
||||
}
|
||||
log::warn!("transition to transient systemd scope {expected} took too long");
|
||||
break;
|
||||
if ghostty_os::cgroup::wait_for_scope(pid, &expected) {
|
||||
log::debug!("transition to transient systemd scope {expected} complete");
|
||||
} else {
|
||||
// Zig checks `rt_pre_exec_info.linux_cgroup_hard_fail` here;
|
||||
// both infos come from the same config so they're identical.
|
||||
if info.linux_cgroup_hard_fail {
|
||||
log::error!("transition to new transient systemd scope {expected} took too long");
|
||||
return Err(PostForkError);
|
||||
}
|
||||
|
||||
if current_scope_matches(pid, &expected) {
|
||||
log::debug!("transition to transient systemd scope {expected} complete");
|
||||
break;
|
||||
}
|
||||
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
log::warn!("transition to transient systemd scope {expected} took too long");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
//! Child pre-exec hook for cgroup transitions (port of `apprt/gtk/pre_exec.zig`).
|
||||
//!
|
||||
//! Runs in the child between fork and exec, so it only reads procfs and
|
||||
//! sleeps. The logic is also mirrored by `ghostty-termio`'s `Command`.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
//! sleeps. The wait loop is shared with `ghostty-termio` via
|
||||
//! `ghostty_os::cgroup::wait_for_scope`.
|
||||
|
||||
use ghostty_config::config::Config;
|
||||
use ghostty_config::types_b::{GtkSingleInstance, LinuxCgroup};
|
||||
@@ -46,36 +45,13 @@ pub fn pre_exec(info: &PreExecInfo) -> Option<u8> {
|
||||
|
||||
let pid = std::process::id();
|
||||
let expected = cgroup::fmt_scope(pid);
|
||||
let start = Instant::now();
|
||||
|
||||
loop {
|
||||
if start.elapsed() > Duration::from_millis(250) {
|
||||
if info.linux_cgroup_hard_fail {
|
||||
log::error!("transition to new transient systemd scope took too long");
|
||||
return Some(127);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if current_scope_matches(pid, &expected) {
|
||||
return None;
|
||||
}
|
||||
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
if !ghostty_os::cgroup::wait_for_scope(pid, &expected) && info.linux_cgroup_hard_fail {
|
||||
log::error!("transition to new transient systemd scope took too long");
|
||||
return Some(127);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// True if the final path component of `pid`'s cgroup equals `expected`.
|
||||
pub(crate) fn current_scope_matches(pid: u32, expected: &str) -> bool {
|
||||
let Some(raw) = ghostty_os::cgroup::current(pid) else {
|
||||
return false;
|
||||
};
|
||||
raw.rsplit_once('/')
|
||||
.is_some_and(|(_, last)| last == expected)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in new issue
Block a user