Files
ghostty-rs/crates/ghostty-termio/src/wakeup.rs
T
ddidderr bab49ee596 feat(macos): port Ghostty's macOS code paths (Metal, CoreText, Darwin)
Ports the macOS-specific Zig code behind cfg(target_os = "macos"):
- renderer: a GraphicsApi trait with generic::Renderer<G>; Metal backend
  (all renderer/metal/* files, shaders.metal verbatim, runtime library
  compile, IOSurface layer, CVDisplayLink), shadertoy -> MSL via naga;
  OpenGL remains the backend elsewhere.
- font: CoreText face, shaper and discovery with build.rs backend
  selection (coretext default; coretext-freetype / coretext-harfbuzz /
  coretext-noshape features), no fontconfig/freetype/harfbuzz on Apple.
- input: KeymapDarwin via UCKeyTranslate, option-as-alt, mac keycodes.
- os: macos, mach, cf_release_thread, NSProcessInfo args and macOS
  branches; config: macOS defaults, keybinds, Application Support paths.
- termio/core: login(1) wrapping, openpty/execvpe, Darwin child exit
  handling, os_log logging.

Compile-checked for aarch64/x86_64-apple-darwin (clippy -D warnings
clean) using the cross setup in docs/rewrite/notes/macos-M1.md; cannot
run here. The embedded runtime/C API (embedded.zig) is the next step.

Also includes the cross-platform integration edits shared by the crash,
verification, Windows and macOS work (Cargo target-gating, thread
crash-context hooks, apprt-gtk surface/IME refactor, termio/os cfg
gates), a cfg fix so ghostty-config builds on wasm32, and an allow for
the intentional recursion in the crash overflow test.

Test Plan:
- cargo test --workspace (3224 passed)
- cargo clippy --workspace --all-targets -- -D warnings
- cargo check --target aarch64-apple-darwin -p ghostty-renderer (with
  the documented cross env)
2026-10-12 06:02:39 +02:00

158 lines
4.5 KiB
Rust

//! A tiny cross-thread wakeup primitive (replaces `xev.Async`).
//!
//! Backed by a non-blocking `eventfd` (a non-blocking pipe on Darwin, which
//! has no eventfd; libxev uses kqueue there), so it can be included in a
//! `poll(2)` set next to a pty fd or a pidfd. [`Wakeup::notify`] may be called from any
//! thread, any number of times; the waiter calls [`Wakeup::drain`] after
//! `poll` reports the fd readable.
use std::{
io,
os::fd::{AsFd, BorrowedFd, OwnedFd},
sync::Arc,
};
/// The fds backing a wakeup: a single eventfd (read == write) on Linux, the
/// two ends of a pipe on Darwin.
struct Fds {
read: OwnedFd,
write: Option<OwnedFd>,
}
impl Fds {
#[cfg(not(target_vendor = "apple"))]
fn new() -> io::Result<Fds> {
use rustix::event::{EventfdFlags, eventfd};
Ok(Fds {
read: eventfd(0, EventfdFlags::CLOEXEC | EventfdFlags::NONBLOCK)?,
write: None,
})
}
#[cfg(target_vendor = "apple")]
fn new() -> io::Result<Fds> {
use rustix::{
fs::{OFlags, fcntl_getfl, fcntl_setfl},
io::{FdFlags, fcntl_setfd},
};
let (read, write) = rustix::pipe::pipe()?;
for fd in [&read, &write] {
fcntl_setfd(fd, FdFlags::CLOEXEC)?;
fcntl_setfl(fd, fcntl_getfl(fd)? | OFlags::NONBLOCK)?;
}
Ok(Fds {
read,
write: Some(write),
})
}
fn write_fd(&self) -> &OwnedFd {
self.write.as_ref().unwrap_or(&self.read)
}
}
/// See the module docs. Cloning shares the same underlying fds.
#[derive(Clone)]
pub struct Wakeup(Arc<Fds>, Option<Arc<dyn Fn() + Send + Sync>>);
impl std::fmt::Debug for Wakeup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Wakeup").field(&self.0.read).finish()
}
}
impl Wakeup {
pub fn new() -> io::Result<Wakeup> {
Ok(Wakeup(Arc::new(Fds::new()?), None))
}
/// A wakeup that calls `hook` instead of signalling an eventfd. Used to
/// bridge into waiters that are not `poll(2)`-based (the renderer
/// thread's channel). `as_fd`/`drain` are meaningless for these.
pub fn with_hook(hook: Arc<dyn Fn() + Send + Sync>) -> io::Result<Wakeup> {
Ok(Wakeup(Arc::new(Fds::new()?), Some(hook)))
}
/// Wake up the waiter. Multiple notifications coalesce.
pub fn notify(&self) -> io::Result<()> {
if let Some(hook) = &self.1 {
hook();
return Ok(());
}
loop {
match rustix::io::write(self.0.write_fd(), &1u64.to_ne_bytes()) {
Ok(_) => return Ok(()),
Err(rustix::io::Errno::INTR) => {}
// Counter would overflow: the waiter is already guaranteed
// to wake up.
Err(rustix::io::Errno::AGAIN) => return Ok(()),
Err(e) => return Err(e.into()),
}
}
}
/// Reset the notification state. Returns true if a notification was
/// pending.
pub fn drain(&self) -> bool {
let mut buf = [0u8; 64];
// An eventfd resets with one read; a pipe is read until empty.
let mut any = false;
loop {
match rustix::io::read(&self.0.read, &mut buf) {
Ok(_) if self.0.write.is_none() => return true,
Ok(0) => return any,
Ok(_) => any = true,
Err(rustix::io::Errno::INTR) => {}
Err(_) => return any,
}
}
}
/// The fd to poll for `POLLIN`.
pub fn as_fd(&self) -> BorrowedFd<'_> {
self.0.read.as_fd()
}
}
#[cfg(test)]
mod tests {
use rustix::event::{PollFd, PollFlags, poll};
use super::*;
fn readable(w: &Wakeup) -> bool {
let mut fds = [PollFd::from_borrowed_fd(w.as_fd(), PollFlags::IN)];
poll(
&mut fds,
Some(&rustix::time::Timespec {
tv_sec: 0,
tv_nsec: 0,
}),
)
.unwrap()
> 0
}
#[test]
fn notify_coalesces_and_drains() {
let w = Wakeup::new().unwrap();
assert!(!readable(&w));
w.notify().unwrap();
w.notify().unwrap();
assert!(readable(&w));
assert!(w.drain());
assert!(!readable(&w));
assert!(!w.drain());
}
#[test]
fn notify_from_other_thread() {
let w = Wakeup::new().unwrap();
let w2 = w.clone();
std::thread::spawn(move || w2.notify().unwrap())
.join()
.unwrap();
assert!(readable(&w));
}
}