7.1 KiB
7.1 KiB
libghostty-vt integration (Android + SSH)
This document tracks how to embed libghostty-vt (terminal emulation via the Ghostty VT core, Zig with a C FFI) into this app, and how to render it on Android.
General maintenance
- Run
./gradlew :app:compileDebugKotlin --warning-mode alland remove any remaining deprecated API usage.
SSH identities / sessions
- Prevent deleting a saved SSH key from the vault while at least one active SSH session is still configured to authenticate with that key (referenced by id). Today the connection UI stores a key id per session in
ssh_connection_uiprefs and loads material from the vault at connect time; deletion can strand sessions or cause confusing errors.
References
- Ghostling — minimal demo: libghostty C API + a 2D renderer (Raylib). The important idea: libghostty owns VT state and exposes a render-state API; the app owns drawing.
- Upstream docs and build instructions for libghostty / libghostty-vt should be followed for ABI, API versioning, and threading guarantees.
Architecture (unchanged from desktop)
- Input path: SSH PTY bytes (already available from the shell session) → feed into libghostty’s byte/input API on a background thread (same thread as today’s SSH read loop, or a dedicated native pump).
- Emulation: libghostty parses VT sequences, maintains screen, scrollback, cursor, styles, etc.
- Output path: After each meaningful update, the library exposes what to draw (cells, attributes, damage regions). The Android layer maps that to pixels or text draws.
- Resize: When the terminal view size or font metrics change, compute columns × rows and notify libghostty (terminal resize), then redraw.
Phase 1 — Native bridge (NDK + JNI)
- Add NDK / CMake to the app module; build per-ABI shared libraries (
arm64-v8a,armeabi-v7a,x86_64as needed). - Integrate libghostty-vt (or the published C API artifact) into the CMake graph; confirm Zig/toolchain requirements for cross-compilation to Android ABIs.
- Define a thin JNI surface: create/destroy session,
feed(bytes, len),resize(cols, rows), query render state (cell grid, colors, cursor), and optionally scrollback accessors per API. - Threading contract: document whether libghostty calls must be serialized (likely yes); use a single worker queue for all native VT + feed operations; only copy immutable snapshots or lock briefly when handing state to the UI thread for drawing.
- Batching: avoid per-byte JNI; buffer PTY data and feed in chunks from the existing SSH reader.
Phase 2 — First renderer: Jetpack Compose Canvas
Goal: Ship a correct, maintainable terminal UI without GL complexity. Accept that very large / fast streams may need Phase 3.
- Add a dedicated composable (e.g.
TerminalSurface) that owns:- monospace font size and cell width/height (measure via
TextMeasureror fixed metrics fromFontFamily.Monospace); - column/row count derived from
onSizeChanged/LayoutCoordinatesand padding; - a snapshot of the terminal state to draw (grid of codepoints + foreground/background + attributes), produced from JNI or a Kotlin-friendly DTO filled on the worker thread.
- monospace font size and cell width/height (measure via
- Draw using
Canvas/drawContext.canvas.nativeCanvasordrawIntoCanvas:- For each damaged region (or full screen if simpler at first), fill background rects, then draw glyph runs per line or per cell batch.
- Prefer
drawText/TextMeasurerfor Unicode correctness over hand-placing every code unit unless profiling says otherwise.
- Damage tracking: start with full redraw each frame if needed for simplicity; then restrict to invalid rectangles from libghostty when exposed by the API.
- Scrolling: map touch/pointer to scrollback if the C API exposes it; otherwise defer.
- Input: wire the existing shell stdin path to emit bytes for key events (Enter, arrows if supported by your bridge), and add modifier keys (Ctrl/Alt) as a follow-up.
Compose-specific notes
- Use
Modifier.onSizeChanged(orLayoutCoordinates) to callresize(cols, rows)in native when the drawable size changes. - Keep heavy work off the main thread: JNI feed on IO; build a read-only frame buffer for the next draw on main.
- If frame preparation is expensive, use
withFrameNanosorLaunchedEffect+ snapshot throttling (e.g. coalesce updates at 60 Hz).
Phase 3 — Optional: performance upgrades
Switch only if profiling shows UI jank or high CPU from Compose drawing (large grids, truecolor, rapid output).
Option A — android.graphics.Canvas on a dedicated View / SurfaceView
- Replace Compose
Canvasdrawing with a customView(orSurfaceView+ thread) usingCanvas.drawText/drawRectfor cells or batched runs. - Often lower overhead than Compose for all-canvas scenes; still CPU rasterization.
- Can keep the same JNI snapshot model as Phase 2; only the painter changes.
Option B — OpenGL ES (closest to “game-style” terminal renderers)
- Add
GLSurfaceView/TextureView(or ComposeAndroidViewwrapper) with a Renderer that:- maintains a glyph atlas (monospace font baked to texture);
- draws quads per cell or batched instancing;
- applies 24-bit color in fragment shader.
- Best for sustained high throughput and large scrollback if you also texture scroll regions (more work).
- Higher implementation cost: atlas, blending, DPI, and resize handling.
Decision rule: profile Phase 2 on a mid-range device with realistic cat/htop output. If frame time stays within budget, stay on Compose Canvas until a concrete need appears.
SSH integration touchpoints (this repo)
- Replace or augment raw
terminalTextstring in the ViewModel with a PTY byte stream into libghostty (keep a plain-text fallback behind a flag during bring-up). - Ensure disconnect tears down the native session and clears render state to avoid use-after-free from JNI.
Checklist before calling it “done”
- Correct Unicode / wide characters (as supported by libghostty) — verify CJK width if you target those locales.
- Resize behavior matches expectations (reflow vs fixed grid per libghostty semantics).
- Memory: cap scrollback / buffer sizes if the API allows.
- Security: host key verification and secrets handling remain independent of VT (unchanged policy from SSH layer).
Summary
| Stage | Renderer | When |
|---|---|---|
| MVP | Jetpack Compose Canvas + measured monospace grid | First shipping integration |
| Tune | android.graphics.Canvas in custom View |
CPU-bound drawing, simpler than GL |
| Scale | OpenGL ES | Heavy sustained output, full-GPU path |
The libghostty integration work is mostly NDK + JNI + resize/feed; rendering is pluggable. Start with Compose Canvas, measure, then optionally swap only the paint layer.