Files
2026-04-12 00:09:18 -07:00

7.1 KiB
Raw Permalink Blame History

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 all and 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_ui prefs 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)

  1. 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).
  2. Emulation: libghostty parses VT sequences, maintains screen, scrollback, cursor, styles, etc.
  3. 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.
  4. 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_64 as 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 TextMeasurer or fixed metrics from FontFamily.Monospace);
    • column/row count derived from onSizeChanged / LayoutCoordinates and 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.
  • Draw using Canvas / drawContext.canvas.nativeCanvas or drawIntoCanvas:
    • 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 / TextMeasurer for 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 (or LayoutCoordinates) to call resize(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 withFrameNanos or LaunchedEffect + 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 Canvas drawing with a custom View (or SurfaceView + thread) using Canvas.drawText / drawRect for 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 Compose AndroidView wrapper) 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 terminalText string 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.