Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions crates/zet-gpu/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,70 @@ impl Renderer {
}
}

pub fn draw_ghostty_frame(&mut self, frame: &GhosttyFrame, vp: Viewport) {
self.quads.clear();
self.ui_quads.clear();
let (cw, ch) = self.cell_px();
let origin_x = vp.x.saturating_mul(cw);
let origin_y = vp.y.saturating_mul(ch);
// Background fill.
if let Some(slot) = self.bg_slot {
for vy in 0..vp.rows {
for vx in 0..vp.cols {
if let Some((cx, cy)) = viewport_cell_origin(vp, vx, vy) {
self.quads.extend(cell_quad(
cx,
cy,
cw as f32,
ch as f32,
(slot.x, slot.y),
self.atlas_size,
Rgba::rgb(0.05, 0.05, 0.08),
));
}
}
}
}
for y in 0..frame.rows.min(vp.rows as usize) {
for x in 0..frame.cols.min(vp.cols as usize) {
let cell = &frame.cells[y * frame.cols + x];
let bg = if cell.inverse {
cell.fg
} else {
cell.bg.unwrap_or(Rgba::rgb(0.05, 0.05, 0.08))
};
if cell.bg.is_some() || cell.inverse {
if let Some((cx, cy)) = viewport_cell_origin(vp, x as u32, y as u32) {
if let Some(slot) = self.bg_slot {
self.quads.extend(cell_quad(
cx,
cy,
cw as f32,
ch as f32,
(slot.x, slot.y),
self.atlas_size,
bg,
));
}
}
}
if cell.ch != ' ' {
let ink = if cell.inverse {
Rgba::rgb(0.05, 0.05, 0.08)
} else {
cell.fg
};
self.draw_text_row(vp, y as u32, x as u32, &cell.ch.to_string(), ink);
}
}
}
if frame.cursor_visible {
let cx = origin_x + frame.cursor_x as u32 * cw;
let cy = origin_y + frame.cursor_y as u32 * ch;
self.draw_rect_px(cx, cy, cw, ch, Rgba::rgb(0.8, 0.8, 0.8));
}
}

/// Tab bar on row 0: equal segments, active lifted + white ink,
/// inactive dim. Labels pre-truncated by the caller; overlong text
/// clips at the grid edge.
Expand Down Expand Up @@ -2596,3 +2660,22 @@ mod viewport_tests {
}
}
}

#[derive(Clone, Copy)]
pub struct GhosttyCell {
pub ch: char,
pub fg: Rgba,
pub bg: Option<Rgba>,
pub bold: bool,
pub inverse: bool,
}

#[derive(Clone)]
pub struct GhosttyFrame {
pub cols: usize,
pub rows: usize,
pub cells: Vec<GhosttyCell>,
pub cursor_x: usize,
pub cursor_y: usize,
pub cursor_visible: bool,
}
34 changes: 34 additions & 0 deletions crates/zet-pty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,36 @@ pub struct Session {
}

impl Session {
/// Spawn a shell in the process's current directory.
///
/// `portable_pty` does not inherit the caller's working directory by
/// default; leaving it unset starts the shell in `$HOME`. Resolve the
/// directory explicitly so ZET behaves like an ordinary terminal. If the
/// inherited directory is invalid (for example, deleted after launch),
/// fall back to the platform default instead of failing to start.
pub fn spawn(program: &str, args: &[&str], cols: u16, rows: u16) -> std::io::Result<Self> {
Self::spawn_with_cwd(
program,
args,
cols,
rows,
std::env::current_dir().ok().as_deref(),
)
}

/// Spawn a shell with an explicit working directory.
///
/// A missing or inaccessible directory falls back to `portable_pty`'s
/// default startup directory (`$HOME`). Passing `None` also uses that
/// default. This keeps callers from having to special-case deleted
/// launch directories while preserving explicit, testable cwd handling.
pub fn spawn_with_cwd(
program: &str,
args: &[&str],
cols: u16,
rows: u16,
cwd: Option<&std::path::Path>,
) -> std::io::Result<Self> {
let pty_system = native_pty_system();
let pair = pty_system
.openpty(PtySize {
Expand All @@ -57,6 +86,11 @@ impl Session {
.map_err(std::io::Error::other)?;
let mut cmd = CommandBuilder::new(program);
cmd.args(args);
if let Some(cwd) = cwd {
if cwd.is_dir() {
cmd.cwd(cwd);
}
}
let child = pair
.slave
.spawn_command(cmd)
Expand Down
128 changes: 128 additions & 0 deletions crates/zet-pty/tests/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,131 @@ fn shutdown_reaps_the_child() {
"process {pid} lingers"
);
}

fn unique_temp_dir(prefix: &str) -> std::path::PathBuf {
for attempt in 0..1000 {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let path = std::env::temp_dir().join(format!(
"zet-cwd-{prefix}-{}-{nanos}-{attempt}",
std::process::id()
));
match std::fs::create_dir(&path) {
Ok(()) => return path,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => panic!("could not create isolated test directory {path:?}: {e}"),
}
}
panic!("could not allocate a unique temporary directory");
}

#[test]
fn spawn_with_cwd_starts_shell_in_requested_directory() {
let dir = unique_temp_dir("project");
std::fs::write(
dir.join("Cargo.toml"),
"[package]\nname = \"x\"\nversion = \"0.1.0\"\n",
)
.unwrap();

let mut s = Session::spawn_with_cwd("sh", &["-c", "pwd"], 80, 24, Some(&dir)).unwrap();
let mut out = Vec::new();
let code = s.wait_with_output(&mut out).unwrap();
assert_eq!(code, 0);

let text = String::from_utf8_lossy(&out);
let actual = text
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or_default();
let actual = std::fs::canonicalize(actual).unwrap_or_else(|_| std::path::PathBuf::from(actual));
let expected = std::fs::canonicalize(&dir).unwrap();
assert_eq!(actual, expected, "pwd was {text:?}");

let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn spawn_with_cwd_falls_back_when_directory_is_invalid() {
let missing = std::env::temp_dir().join(format!(
"zet-cwd-missing-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
assert!(
!missing.exists(),
"test fixture unexpectedly exists: {missing:?}"
);

let mut s = Session::spawn_with_cwd("sh", &["-c", "pwd"], 80, 24, Some(&missing)).unwrap();
let mut out = Vec::new();
let code = s.wait_with_output(&mut out).unwrap();
assert_eq!(code, 0);

let text = String::from_utf8_lossy(&out);
let actual = text
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or_default();
assert!(
!actual.is_empty(),
"shell did not report a working directory"
);
assert!(
!actual.contains("zet-cwd-missing"),
"invalid directory leaked into shell: {text:?}"
);
}

#[test]
fn spawn_inherits_process_current_directory() {
if std::env::var_os("ZET_PTY_INHERIT_CWD_CHILD").is_some() {
let mut s = Session::spawn("sh", &["-c", "pwd"], 80, 24).unwrap();
let mut out = Vec::new();
let code = s.wait_with_output(&mut out).unwrap();
assert_eq!(code, 0);
let text = String::from_utf8_lossy(&out);
let actual = text
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or_default();
println!("ZET_CWD_RESULT={actual}");
return;
}

let dir = unique_temp_dir("inherit");
let expected = std::fs::canonicalize(&dir).unwrap();
let exe = std::env::current_exe().unwrap();
let output = std::process::Command::new(&exe)
.arg("spawn_inherits_process_current_directory")
.arg("--exact")
.arg("--nocapture")
.env("ZET_PTY_INHERIT_CWD_CHILD", "1")
.current_dir(&dir)
.output()
.unwrap();
assert!(
output.status.success(),
"child test failed: {}",
String::from_utf8_lossy(&output.stderr)
);

let stdout = String::from_utf8_lossy(&output.stdout);
let result = stdout
.lines()
.find_map(|line| line.strip_prefix("ZET_CWD_RESULT="))
.unwrap_or_default()
.trim();
let actual = std::fs::canonicalize(result).unwrap_or_else(|_| std::path::PathBuf::from(result));
assert_eq!(actual, expected, "child pwd was {stdout:?}");

let _ = std::fs::remove_dir_all(&dir);
}
4 changes: 4 additions & 0 deletions crates/zet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ path = "src/lib.rs"
name = "zet"
path = "src/main.rs"

[features]
default = []
ghostty-vt = []

[dependencies]
zet-agent = { path = "../zet-agent" }
zet-agent-observe = { path = "../zet-agent-observe" }
Expand Down
12 changes: 12 additions & 0 deletions crates/zet/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
fn main() {
#[cfg(feature = "ghostty-vt")]
{
let lib_dir = std::env::var("GHOSTTY_VT_LIB_DIR").unwrap_or_else(|_| {
"/home/bandit/zet-ghostty-a2/ghostty-0fa3d577a5614150ff8e2c152de5fb9d5c6d2dec/zig-out/lib"
.to_string()
});
println!("cargo:rustc-link-search=native={lib_dir}");
println!("cargo:rustc-link-lib=dylib=ghostty-vt");
println!("cargo:rustc-link-arg=-Wl,-rpath,{lib_dir}");
}
}
Loading
Loading