feat(core): port App/Surface and wire up the runnable ghostty binary

This is the integration step that turns the ported crates into a working
terminal: `cargo run` now opens a GTK window running the user's shell.

ghostty-core ports App.zig, Surface.zig (split into keyboard, mouse,
binding, clipboard and config submodules), surface_mouse.zig and
global.zig, and implements the runtime traits. perform_binding_action
handles every binding action.

Cross-crate integration:
- The core<->runtime traits (CoreApp, CoreSurface, RtApp, RtSurface,
  Waker) move from apprt-gtk into ghostty_apprt::runtime_api so the core
  stays runtime-agnostic; Scrollbar/RendererHealth stand-ins are replaced
  by the real terminal/renderer types.
- termio now uses ghostty_renderer::state::{State, SharedState}; the
  renderer calls kitty_update; image-storage-limit is applied at init
  and on config change.
- The search thread locks the terminal through a TerminalLock trait so
  it can share the render state mutex; termio's Wakeup gained a hook to
  wake the renderer thread.
- apprt-gtk: GL proc addresses are resolved through libepoxy's
  epoxy_glFoo pointer variables (plain glFoo symbols resolved to null),
  default DPI fixed to 96, libadwaita version read without GTK init so
  --version works headless.

The root binary dispatches +actions to ghostty-cli (list-fonts,
show-face and new-window are now wired) and otherwise runs the GTK app
with the real core.

Verified at runtime on Wayland and X11: shell prompt and colored output
render, child exit closes the window cleanly. Not yet verified: keyboard
and mouse input, clipboard, IME, tabs and splits (no key injection was
possible in this environment). GHOSTTY_DEBUG_SCREENSHOT=<png> dumps the
renderer's last frame for headless checks.

Test Plan:
- cargo test --workspace (2890 passed)
- cargo clippy --workspace --all-targets -- -D warnings
- GSETTINGS_BACKEND=memory GHOSTTY_RESOURCES_DIR=/usr/share/ghostty \
  cargo run
This commit is contained in:
ddidderr committed 2026-10-12 01:33:44 +02:00
1 parent 9c3eeeba50
commit 3266108c10
42 files changed
+9301 -179

No files matched your search

+2
View File
@@ -6,7 +6,9 @@ license.workspace = true
[dependencies]
flate2 = "1.1.10"
ghostty-apprt.workspace = true
ghostty-config.workspace = true
ghostty-font.workspace = true
ghostty-input.workspace = true
ghostty-os.workspace = true
log = "0.4.34"
+69 -5
View File
@@ -1,7 +1,4 @@
//! `+list-fonts` (ZIG/src/cli/list_fonts.zig).
//!
//! DEFERRED: needs the font crate (font discovery). Only the options and
//! help are ported; running the action reports that it is not available.
use ghostty_config::config_struct;
@@ -52,6 +49,73 @@ pub fn run(args: &[String]) -> Result<u8, Error> {
let mut opts = Options::default();
crate::parse_options(&mut opts, args)?;
// TODO(integration): port the discovery/listing once ghostty-font lands.
Err(Error::NotYetAvailable("list-fonts"))
use std::collections::HashMap;
use std::io::Write;
// We'll be putting our fonts into a list categorized by family
// so it is easier to read the output.
let mut families: Vec<String> = Vec::new();
let mut map: HashMap<String, Vec<String>> = HashMap::new();
// Look up all available fonts
let disco = ghostty_font::Discover::init();
let desc = ghostty_font::Descriptor {
monospace: opts.family.is_none(),
family: opts.family.clone(),
style: opts.style.clone(),
bold: opts.bold,
italic: opts.italic,
..ghostty_font::Descriptor::default()
};
let mut it = disco
.discover(&desc)
.map_err(|e| Error::Other(e.to_string()))?;
while let Some(face) = it.next().map_err(|e| Error::Other(e.to_string()))? {
let family = match face.family_name() {
Ok(v) => v,
Err(err) => {
log::error!("failed to get font family name: {err}");
continue;
}
};
let full_name = match face.name() {
Ok(v) => v,
Err(err) => {
log::error!("failed to get font name: {err}");
continue;
}
};
let list = map.entry(family.clone()).or_insert_with(|| {
families.push(family);
Vec::new()
});
list.push(full_name);
}
// Sort our keys.
if opts.family.is_none() {
families.sort_unstable();
}
// Output each
let mut stdout = std::io::BufWriter::new(std::io::stdout().lock());
for family in &families {
let Some(list) = map.get_mut(family) else {
continue;
};
if list.is_empty() {
continue;
}
if opts.family.is_none() {
list.sort_unstable();
}
writeln!(stdout, "{family}")?;
for item in list.iter() {
writeln!(stdout, " {item}")?;
}
writeln!(stdout)?;
}
stdout.flush()?;
Ok(0)
}
+71 -7
View File
@@ -1,13 +1,31 @@
//! `+new-window` (ZIG/src/cli/new_window.zig).
//!
//! DEFERRED: sending the IPC needs the GTK app (`apprt.App.performIpc`).
//! The option parsing (including the manual `+new-window` argument gathering
//! hook) is ported; running the action reports that it is not available.
//! Sending the IPC needs the app runtime (`apprt.App.performIpc`); the root
//! binary registers it with [`set_ipc_handler`] so this crate does not
//! depend on GTK.
use std::sync::OnceLock;
use ghostty_apprt::ipc;
use ghostty_config::cli_args::{ArgError, ArgIter, CliTarget};
use crate::error::Error;
/// The runtime's IPC entrypoint (`apprt.App.performIpc`). `Ok(true)` means
/// the action was performed; `Err` carries an error message (use
/// [`IPC_FAILED`] when the runtime already printed a specific message).
pub type IpcHandler = fn(&ipc::Target, &ipc::Action) -> Result<bool, String>;
/// Error string for `error.IPCFailed`: the runtime already reported it.
pub const IPC_FAILED: &str = "IPCFailed";
static IPC_HANDLER: OnceLock<IpcHandler> = OnceLock::new();
/// Register the runtime IPC handler. Only the first call has an effect.
pub fn set_ipc_handler(f: IpcHandler) {
let _ = IPC_HANDLER.set(f);
}
/// Options of `+new-window`.
#[derive(Debug, Clone, Default)]
pub struct Options {
@@ -178,10 +196,42 @@ pub fn run(args: &[String]) -> Result<u8, Error> {
.insert(0, format!("--working-directory={}", wd.to_string_lossy()));
}
// TODO(integration): send the `new_window` IPC (class: `opts.class` or
// auto-detected, arguments: `opts.arguments`) via the GTK apprt's
// `performIpc`.
Err(Error::NotYetAvailable("new-window"))
let target = match opts.class {
Some(class) => ipc::Target::Class(class),
None => ipc::Target::Detect,
};
let action = ipc::Action::NewWindow(ipc::NewWindow {
arguments: if opts.arguments.is_empty() {
None
} else {
Some(opts.arguments)
},
});
// Without a registered runtime this behaves like `apprt.none`, whose
// performIpc always returns false.
let performed = match IPC_HANDLER.get() {
Some(handler) => match handler(&target, &action) {
Ok(v) => v,
Err(e) if e == IPC_FAILED => {
// The apprt should have printed a more specific error message
// already.
return Ok(1);
}
Err(e) => {
eprint!("Sending the IPC failed: {e}");
return Ok(1);
}
},
None => false,
};
if performed {
return Ok(0);
}
// If we get here, the platform is not supported.
eprintln!("+new-window is not supported on this platform.");
Ok(1)
}
#[cfg(test)]
@@ -236,4 +286,18 @@ mod tests {
let o = parse_str("--help");
assert_eq!(vec!["--help"], o.arguments);
}
#[test]
fn ipc_handler_registration_is_once() {
#[allow(clippy::unnecessary_wraps)]
fn h(_: &ipc::Target, _: &ipc::Action) -> Result<bool, String> {
Ok(true)
}
set_ipc_handler(h);
let r = IPC_HANDLER.get().unwrap()(
&ipc::Target::Detect,
&ipc::Action::NewWindow(ipc::NewWindow { arguments: None }),
);
assert_eq!(r, Ok(true));
}
}
+150 -6
View File
@@ -1,10 +1,13 @@
//! `+show-face` (ZIG/src/cli/show_face.zig).
//!
//! DEFERRED: needs the font crate (collection / codepoint resolver). Only the
//! options and help are ported; running the action reports that it is not
//! available.
use ghostty_config::config::Config;
use ghostty_config::diagnostics::Location;
use ghostty_config::{config_enum, config_struct, diagnostics::DiagnosticList};
use ghostty_font::collection::EntryError;
use ghostty_font::collection::GetFaceError;
use ghostty_font::face::DesiredSize;
use ghostty_font::shared_grid_set::DerivedConfig;
use ghostty_font::{self as font, SharedGrid, SharedGridSet};
use crate::error::Error;
@@ -73,6 +76,147 @@ pub fn run(args: &[String]) -> Result<u8, Error> {
let mut opts = Options::default();
crate::parse_options(&mut opts, args)?;
// TODO(integration): port the face lookup once ghostty-font lands.
Err(Error::NotYetAvailable("show-face"))
run_args(&opts, &mut std::io::stdout(), &mut std::io::stdout())
}
fn run_args(
opts: &Options,
stdout: &mut dyn std::io::Write,
stderr: &mut dyn std::io::Write,
) -> Result<u8, Error> {
// Print out any diagnostics, unless it's likely that the diagnostic was
// generated trying to parse a "normal" configuration setting. Exit with an
// error code if any diagnostics were printed.
const FIELDS: [&str; 4] = ["cp", "string", "style", "presentation"];
let mut exit = false;
for d in opts.diagnostics.items() {
if !matches!(d.location, Location::Cli(_)) {
continue;
}
if FIELDS.contains(&d.key.as_str()) {
writeln!(stderr, "config error: {d}")?;
exit = true;
}
}
if exit {
return Ok(1);
}
if opts.cp.is_none() && opts.string.is_none() {
writeln!(
stderr,
"You must specify a codepoint with --cp or a string with --string"
)?;
return Ok(1);
}
let config = match Config::load() {
Ok(c) => c,
Err(err) => {
write!(stderr, "Unable to load config: {err}")?;
return Ok(1);
}
};
// Print out any diagnostics generated from parsing the config, unless
// the diagnostic might have been generated because it's actually an
// action-specific argument.
for d in config.diagnostics.items() {
if FIELDS.contains(&d.key.as_str())
&& matches!(d.location, Location::None | Location::Cli(_))
{
continue;
}
writeln!(stderr, "config error: {d}")?;
}
let font_grid_set = match SharedGridSet::new() {
Ok(v) => v,
Err(err) => {
write!(stderr, "Unable to initialize font grid set: {err}")?;
return Ok(1);
}
};
let font_size = DesiredSize {
points: config.font_size,
xdpi: 96,
ydpi: 96,
};
let font_config = DerivedConfig::new(&config);
let (key, grid) = match font_grid_set.ref_(&font_config, font_size) {
Ok(v) => v,
Err(err) => {
write!(stderr, "Unable to get font grid: {err}")?;
return Ok(1);
}
};
let style = match opts.style {
Style::Regular => font::Style::Regular,
Style::Bold => font::Style::Bold,
Style::Italic => font::Style::Italic,
Style::BoldItalic => font::Style::BoldItalic,
};
let presentation = opts.presentation.map(|p| match p {
Presentation::Text => font::Presentation::Text,
Presentation::Emoji => font::Presentation::Emoji,
});
let mut rc = None;
if let Some(cp) = opts.cp {
rc = lookup(stdout, stderr, &grid, style, presentation, cp)?;
}
if rc.is_none()
&& let Some(string) = &opts.string
{
for ch in string.chars() {
rc = lookup(stdout, stderr, &grid, style, presentation, ch as u32)?;
if rc.is_some() {
break;
}
}
}
drop(grid);
font_grid_set.deref(&key);
Ok(rc.unwrap_or(0))
}
fn lookup(
stdout: &mut dyn std::io::Write,
stderr: &mut dyn std::io::Write,
grid: &SharedGrid,
style: font::Style,
presentation: Option<font::Presentation>,
cp: u32,
) -> Result<Option<u8>, Error> {
let ch = char::from_u32(cp).unwrap_or('\u{FFFD}');
let Ok(Some(idx)) = grid.get_index(cp, style, presentation) else {
writeln!(stdout, "U+{cp:02X} \u{ab} {ch} \u{bb} not found.")?;
return Ok(None);
};
let mut st = grid.write();
let face = match st.resolver.collection.get_face(idx) {
Ok(f) => f,
Err(GetFaceError::Entry(EntryError::SpecialHasNoFace)) => {
writeln!(
stdout,
"U+{cp:02X} \u{ab} {ch} \u{bb} is handled by Ghostty's internal sprites."
)?;
return Ok(None);
}
Err(err) => {
write!(stderr, "Unable to get face: {err}")?;
return Ok(Some(1));
}
};
let name = face.name();
writeln!(
stdout,
"U+{cp:02X} \u{ab} {ch} \u{bb} found in face \u{201c}{name}\u{201d}."
)?;
Ok(None)
}