╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const rf = xit.ref; 5 const hash = xit.hash; 6 const xitui = xit.xitui; 7 const term = xitui.terminal; 8 const wgt = xitui.widget; 9 const layout = xitui.layout; 10 const Key = xitui.input.Key; 11 const Grid = xitui.grid.Grid; 12 const Focus = xitui.focus.Focus; 13 const evt = @import("./event.zig"); 14 15 pub const Home = @import("./ui/Home.zig"); 16 pub const User = @import("./ui/User.zig"); 17 pub const Repo = @import("./ui/Repo.zig"); 18 pub const Title = @import("./ui/Title.zig"); 19 pub const SubTitle = @import("./ui/SubTitle.zig"); 20 pub const Quit = @import("./ui/Quit.zig"); 21 pub const Unauthorized = @import("./ui/Unauthorized.zig"); 22 23 pub const PageKind = enum { 24 home, 25 user, 26 repo, 27 }; 28 29 pub const Page = union(PageKind) { 30 home: Home, 31 user: User, 32 repo: Repo, 33 34 pub fn init(arena: *std.heap.ArenaAllocator, session: *Session, route: RoutablePage) !Page { 35 // the repo page can build without a moment in local mode; the home and 36 // user pages always read from the admin db. 37 return switch (route.parent()) { 38 .home => .{ .home = try Home.init(arena, session.haxy_moment orelse return error.NoMoment, switch (route) { 39 .home_users => |start| start, 40 else => 0, 41 }, switch (route) { 42 .home_repos => |start| start, 43 else => 0, 44 }) }, 45 .user => blk: { 46 const haxy_moment = session.haxy_moment orelse return error.NoMoment; 47 break :blk switch (route) { 48 .user_repos => |u| .{ .user = try User.init(arena, haxy_moment, u.name, u.start) }, 49 .user_settings, .user_auth => |name| .{ .user = try User.init(arena, haxy_moment, name, 0) }, 50 else => return error.UnexpectedRoute, 51 }; 52 }, 53 .repo => switch (route) { 54 .repo_files, .repo_commits, .repo_refs, .repo_issues, .repo_settings, .repo_auth => .{ .repo = try Repo.init(arena, session, route) }, 55 else => return error.UnexpectedRoute, 56 }, 57 }; 58 } 59 }; 60 61 // what the server hands to the client (and what main_wasm parses on _start). 62 // keeps Page free of any per-request session state. 63 pub const Snapshot = struct { 64 page: Page, 65 session: Session.Data = .{}, 66 }; 67 68 // a top-level "page" the user can navigate to. the user_* variants are the 69 // tabs of a user page; they each carry the user's name and all map to the 70 // .user parent page, so switching between them stays on that page (and just 71 // updates the url) rather than navigating away. 72 pub const RoutablePage = union(enum) { 73 home_users: usize, // 0 = first page 74 home_repos: usize, // 0 = first page 75 home_settings, 76 home_auth, 77 user_repos: struct { name: Array(evt.User.name_max_len), start: usize = 0 }, 78 user_settings: Array(evt.User.name_max_len), 79 user_auth: Array(evt.User.name_max_len), 80 repo_files: RepoFilesRoute, 81 repo_commits: RepoCommitsRoute, 82 repo_refs: struct { 83 name: Array(repo_route_max_len), 84 kind: RefKind = .branch, 85 // the url-encoded ref name `kind`'s column windows from ("" = the 86 // first window; the other column always shows its first window). 87 from: Array(ref_route_max_len) = .{}, 88 }, 89 repo_issues: struct { 90 name: Array(repo_route_max_len), 91 // the tag the list is filtered to, url-encoded ("" = unfiltered). 92 tag: Array(issue_tag_route_max_len) = .{}, 93 // the issue the route names: the list's window root, or the issue the 94 // edit/description/resolve view shows. 95 selected: Array(evt.event_id_size * 2) = .{}, 96 // the resolve view's comma-separated list of fields prefilled from 97 // their side of the conflict. 98 theirs: Array(theirs_route_max_len) = .{}, 99 // the view the url names; a route with `selected` derives its view 100 // from that issue's status instead. 101 view: IssuesView = .open, 102 }, 103 repo_settings: Array(repo_route_max_len), 104 repo_auth: Array(repo_route_max_len), 105 106 pub const default: RoutablePage = .{ .home_repos = 0 }; 107 108 pub const RefKind = enum { branch, tag }; 109 110 pub const IssuesView = enum { open, closed, tags, new, edit, description, conflicts, resolve }; 111 112 pub const RefOrOid = enum { 113 branch, 114 tag, 115 object, 116 }; 117 118 // the "key:value" segments of a url tail, collected in any order 119 const Params = struct { 120 const ParamKey = enum { start, line, branch, tag, object, theirs }; 121 122 // a branch:/tag:/object: param; the value stays url-encoded 123 const RefParam = struct { kind: RefOrOid, value: []const u8 }; 124 125 values: std.enums.EnumArray(ParamKey, ?[]const u8) = .initFill(null), 126 127 // consume the leading "key:value" segments, stopping at the first 128 // segment that isn't one 129 fn scanPairs(self: *Params, segments: *std.mem.SplitIterator(u8, .scalar)) error{BadUrl}!void { 130 while (segments.peek()) |seg| { 131 const colon = std.mem.indexOfScalar(u8, seg, ':') orelse return; 132 const key = std.meta.stringToEnum(ParamKey, seg[0..colon]) orelse return; 133 const value = seg[colon + 1 ..]; 134 if (value.len == 0) return error.BadUrl; 135 if (self.values.get(key) != null) return error.BadUrl; 136 self.values.set(key, value); 137 _ = segments.next(); 138 } 139 } 140 141 // consume every remaining segment: pairs plus at most one bare word, 142 // which is returned 143 fn scanTail(self: *Params, segments: *std.mem.SplitIterator(u8, .scalar)) error{BadUrl}!?[]const u8 { 144 var word: ?[]const u8 = null; 145 while (true) { 146 try self.scanPairs(segments); 147 const seg = segments.next() orelse return word; 148 if (seg.len == 0 or word != null) return error.BadUrl; 149 word = seg; 150 } 151 } 152 153 // true when every set param is one of `allowed` 154 fn only(self: Params, allowed: []const ParamKey) bool { 155 for (std.enums.values(ParamKey)) |key| { 156 if (self.values.get(key) == null) continue; 157 if (std.mem.indexOfScalar(ParamKey, allowed, key) == null) return false; 158 } 159 return true; 160 } 161 162 // the "start:<n>" window param (0 when absent), null when malformed 163 fn start(self: Params) ?usize { 164 const value = self.values.get(.start) orelse return 0; 165 return std.fmt.parseInt(usize, value, 10) catch null; 166 } 167 168 // the "line:<n>" first-line param (0 when absent), null when malformed 169 fn line(self: Params) ?usize { 170 const value = self.values.get(.line) orelse return 0; 171 return std.fmt.parseInt(usize, value, 10) catch null; 172 } 173 174 // the single branch:/tag:/object: param, null when none is set 175 fn ref(self: Params) error{BadUrl}!?RefParam { 176 var result: ?RefParam = null; 177 inline for (@typeInfo(RefOrOid).@"enum".fields) |field| { 178 if (self.values.get(@field(ParamKey, field.name))) |value| { 179 if (result != null) return error.BadUrl; 180 result = .{ .kind = @field(RefOrOid, field.name), .value = value }; 181 } 182 } 183 return result; 184 } 185 }; 186 187 const user_segment = "/user/"; 188 const repo_segment = "/repo/"; 189 const files_seg = "files"; 190 const commits_seg = "commits"; 191 // ends a commits route naming its commit's full message 192 const message_seg = "message"; 193 // the `Params` key spellings the url emitters use 194 const tag_filter_seg = @tagName(Params.ParamKey.tag) ++ ":"; 195 const start_seg = @tagName(Params.ParamKey.start) ++ ":"; 196 const line_seg = @tagName(Params.ParamKey.line) ++ ":"; 197 const theirs_seg = @tagName(Params.ParamKey.theirs) ++ ":"; 198 // marks a files or commits route's trailing path: the value is the raw 199 // remainder of the url, so it must come last 200 const path_seg = "path:"; 201 202 // a repo route is "username/reponame", optionally followed by the files 203 // tab's "/files/<refkind>:<refvalue>[/line:<n>][/path:<dir>]"; the bare 204 // pair means the default branch's files root. a local session's routes 205 // elide the identity: "" at the bare root, else starting at the tail's "/". 206 pub const repo_route_max_len = 1024; 207 pub const repo_identity_max_len = evt.User.name_max_len + 1 + evt.Repo.name_max_len; 208 209 // true when a repo route's stored string elides its identity (local mode). 210 // unambiguous because a full string always starts with its owner segment. 211 fn identityElided(s: []const u8) bool { 212 return s.len == 0 or s[0] == '/'; 213 } 214 215 // a url-encoded tag can grow to three bytes per source byte. 216 pub const issue_tag_route_max_len = evt.Issue.tag_max_len * 3; 217 218 // caps the resolve view's theirs: field list (a longer one doesn't route). 219 pub const theirs_route_max_len = 512; 220 221 // caps a url-encoded ref name in a route (a longer name doesn't route). 222 pub const ref_route_max_len = 512; 223 224 // the identity stored by every repo route. Local routes elide it. 225 pub const RepoIdentity = struct { 226 identity: []const u8, // "owner/name" 227 owner: []const u8, 228 name: []const u8, 229 230 pub fn parse(s: []const u8) ?RepoIdentity { 231 var result: RepoIdentity = .{ 232 .identity = "", 233 .owner = "", 234 .name = "", 235 }; 236 if (identityElided(s)) { 237 return result; 238 } else { 239 var id_segments = std.mem.splitScalar(u8, s, '/'); 240 const owner = id_segments.next() orelse return null; 241 const name = id_segments.next() orelse return null; 242 if (owner.len == 0 or name.len == 0) return null; 243 result.identity = s[0 .. owner.len + 1 + name.len]; 244 result.owner = owner; 245 result.name = name; 246 } 247 return result; 248 } 249 }; 250 251 pub const RepoFilesRoute = struct { 252 name: Array(repo_identity_max_len), 253 ref_kind: ?RefOrOid = null, 254 ref_value: Array(ref_route_max_len) = .{}, 255 path: Array(repo_route_max_len) = .{}, 256 // the selected file's first visible line (1-based; 0 = unset). 257 line: usize = 0, 258 }; 259 260 pub const RepoCommitsRoute = struct { 261 name: Array(repo_identity_max_len), 262 ref_or_oid: ?RefOrOid = null, 263 value: Array(ref_route_max_len) = .{}, 264 // what the pane shows for the commit the log walks from. 265 content: Content = .{ .diff = .{} }, 266 267 // a diff window and the message are alternatives, so the window's 268 // params can't be named alongside the message. 269 pub const Content = union(enum) { 270 diff: struct { 271 // the hunk index the window starts at. 272 start: usize = 0, 273 // the file the diff is filtered to ("" = every file). 274 path: Array(repo_route_max_len) = .{}, 275 }, 276 message, 277 }; 278 }; 279 280 // build a `.repo_files` route (a null ref_kind = the bare default-branch 281 // root). null if the result doesn't fit the inline name. 282 pub fn repoFilesRoute(identity: []const u8, ref_kind: ?RefOrOid, ref_value: []const u8, dir: []const u8, line: usize) ?RoutablePage { 283 if (ref_kind == null and (ref_value.len != 0 or dir.len != 0)) return null; 284 if (ref_kind != null and ref_value.len == 0 and dir.len != 0) return null; 285 return .{ .repo_files = .{ 286 .name = Array(repo_identity_max_len).from(identity) orelse return null, 287 .ref_kind = ref_kind, 288 .ref_value = Array(ref_route_max_len).from(ref_value) orelse return null, 289 .path = Array(repo_route_max_len).from(dir) orelse return null, 290 .line = line, 291 } }; 292 } 293 294 // build a `.repo_commits` route (a null ref_or_oid = the default branch). 295 // always carries the `commits` marker so the bare route doesn't collide 296 // with the files root. a non-empty `path` filters the diff pane to that 297 // file and requires a ref. 298 pub fn repoCommitsRoute(identity: []const u8, ref_or_oid: ?RefOrOid, value: []const u8, start: usize, path: []const u8) ?RoutablePage { 299 if (ref_or_oid == null and (value.len != 0 or path.len != 0)) return null; 300 return .{ .repo_commits = .{ 301 .name = Array(repo_identity_max_len).from(identity) orelse return null, 302 .ref_or_oid = ref_or_oid, 303 .value = Array(ref_route_max_len).from(value) orelse return null, 304 .content = .{ .diff = .{ 305 .start = start, 306 .path = Array(repo_route_max_len).from(path) orelse return null, 307 } }, 308 } }; 309 } 310 311 // build a `.repo_commits` route showing the ref/oid's commit message in 312 // full, which is the only content that page renders. 313 pub fn repoCommitMessageRoute(identity: []const u8, ref_or_oid: RefOrOid, value: []const u8) ?RoutablePage { 314 if (value.len == 0) return null; 315 return .{ .repo_commits = .{ 316 .name = Array(repo_identity_max_len).from(identity) orelse return null, 317 .ref_or_oid = ref_or_oid, 318 .value = Array(ref_route_max_len).from(value) orelse return null, 319 .content = .message, 320 } }; 321 } 322 323 // build a `.repo_refs` route windowing `kind`'s column from the 324 // url-encoded ref name `from` ("" = the first window). 325 pub fn repoRefsRoute(identity: []const u8, kind: RefKind, from: []const u8) ?RoutablePage { 326 return .{ .repo_refs = .{ 327 .name = Array(repo_route_max_len).from(identity) orelse return null, 328 .kind = kind, 329 .from = Array(ref_route_max_len).from(from) orelse return null, 330 } }; 331 } 332 333 // build a `.repo_issues` route for "owner/name" (identity) showing 334 // `status`'s list, filtered to the url-encoded `tag` ("" = unfiltered) and 335 // rooted at the issue with hex event id `selected` ("" = the first window). 336 pub fn repoIssuesRoute(identity: []const u8, status: evt.Issue.Status, tag: []const u8, selected: []const u8) ?RoutablePage { 337 return .{ .repo_issues = .{ 338 .name = Array(repo_route_max_len).from(identity) orelse return null, 339 .tag = Array(issue_tag_route_max_len).from(tag) orelse return null, 340 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 341 .view = switch (status) { 342 .open => .open, 343 .closed => .closed, 344 }, 345 } }; 346 } 347 348 // build a `.repo_issues` route showing tags view, keeping the url-encoded 349 // `tag` filter ("" = unfiltered). 350 pub fn repoIssuesTagsRoute(identity: []const u8, tag: []const u8) ?RoutablePage { 351 return .{ .repo_issues = .{ 352 .name = Array(repo_route_max_len).from(identity) orelse return null, 353 .tag = Array(issue_tag_route_max_len).from(tag) orelse return null, 354 .view = .tags, 355 } }; 356 } 357 358 // build a `.repo_issues` route showing new-issue form. 359 pub fn repoIssuesNewRoute(identity: []const u8) ?RoutablePage { 360 return .{ .repo_issues = .{ 361 .name = Array(repo_route_max_len).from(identity) orelse return null, 362 .view = .new, 363 } }; 364 } 365 366 // build a `.repo_issues` route showing the edit form for the issue with 367 // hex event id `selected`. 368 pub fn repoIssuesEditRoute(identity: []const u8, selected: []const u8) ?RoutablePage { 369 if (selected.len == 0) return null; 370 return .{ .repo_issues = .{ 371 .name = Array(repo_route_max_len).from(identity) orelse return null, 372 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 373 .view = .edit, 374 } }; 375 } 376 377 // build a `.repo_issues` route showing the whole description of the issue 378 // with hex event id `selected`. 379 pub fn repoIssuesDescriptionRoute(identity: []const u8, selected: []const u8) ?RoutablePage { 380 if (selected.len == 0) return null; 381 return .{ .repo_issues = .{ 382 .name = Array(repo_route_max_len).from(identity) orelse return null, 383 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 384 .view = .description, 385 } }; 386 } 387 388 // build a `.repo_issues` route showing the conflicts list, rooted at the 389 // issue with hex event id `start` ("" = the first window). 390 pub fn repoIssuesConflictsRoute(identity: []const u8, start: []const u8) ?RoutablePage { 391 return .{ .repo_issues = .{ 392 .name = Array(repo_route_max_len).from(identity) orelse return null, 393 .selected = Array(evt.event_id_size * 2).from(start) orelse return null, 394 .view = .conflicts, 395 } }; 396 } 397 398 // build a `.repo_issues` route showing the conflict resolve form for the 399 // issue with hex event id `selected`; `theirs` is the comma-separated list 400 // of fields prefilled from their side. 401 pub fn repoIssuesResolveRoute(identity: []const u8, selected: []const u8, theirs: []const u8) ?RoutablePage { 402 if (selected.len == 0) return null; 403 return .{ .repo_issues = .{ 404 .name = Array(repo_route_max_len).from(identity) orelse return null, 405 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 406 .theirs = Array(theirs_route_max_len).from(theirs) orelse return null, 407 .view = .resolve, 408 } }; 409 } 410 411 // an inline, owned array of data. keeping it in the route (rather than a 412 // borrowed slice) makes RoutablePage a plain value: it can be copied, stored 413 // in history, and serialized without any arena tracking. 414 pub fn Array(comptime max_len: usize) type { 415 return struct { 416 bytes: [max_len]u8 = undefined, 417 len: u16 = 0, 418 419 pub fn from(s: []const u8) ?Array(max_len) { 420 if (s.len > max_len) return null; 421 var name = Array(max_len){ .len = @intCast(s.len) }; 422 @memcpy(name.bytes[0..s.len], s); 423 return name; 424 } 425 426 pub fn slice(self: *const Array(max_len)) []const u8 { 427 return self.bytes[0..self.len]; 428 } 429 430 // round-trip as a json string instead of an array of numbers. 431 pub fn jsonStringify(self: *const Array(max_len), jw: anytype) !void { 432 try jw.write(self.slice()); 433 } 434 435 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !Array(max_len) { 436 const s = try std.json.innerParse([]const u8, allocator, source, options); 437 // ValueTooLong is std.json's error for an over-long field. 438 return from(s) orelse error.ValueTooLong; 439 } 440 }; 441 } 442 443 pub fn toUrl(self: RoutablePage, arena: *std.heap.ArenaAllocator) ![]const u8 { 444 return switch (self) { 445 .home_users => |start| if (start == 0) @as([]const u8, "/users") else try std.fmt.allocPrint(arena.allocator(), "/users/" ++ start_seg ++ "{d}", .{start}), 446 .home_repos => |start| if (start == 0) @as([]const u8, "/repos") else try std.fmt.allocPrint(arena.allocator(), "/repos/" ++ start_seg ++ "{d}", .{start}), 447 .home_settings => "/settings", 448 .home_auth => "/auth", 449 .user_repos => |u| if (u.start == 0) 450 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/repos", .{u.name.slice()}) 451 else 452 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/repos/" ++ start_seg ++ "{d}", .{ u.name.slice(), u.start }), 453 .user_settings => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/settings", .{name.slice()}), 454 .user_auth => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/auth", .{name.slice()}), 455 .repo_files => |f| blk: { 456 const prefix = try repoUrlPrefix(arena, f.name.slice()); 457 if (f.ref_kind == null and f.line == 0) break :blk if (prefix.len == 0) "/" else prefix; 458 var out: std.Io.Writer.Allocating = .init(arena.allocator()); 459 try out.writer.print("{s}/" ++ files_seg, .{prefix}); 460 if (f.ref_kind) |kind| if (f.ref_value.len != 0) try out.writer.print("/{s}:{s}", .{ @tagName(kind), f.ref_value.slice() }); 461 if (f.line != 0) try out.writer.print("/" ++ line_seg ++ "{d}", .{f.line}); 462 if (f.path.len != 0) try out.writer.print("/" ++ path_seg ++ "{s}", .{f.path.slice()}); 463 break :blk out.written(); 464 }, 465 .repo_commits => |c| blk: { 466 const prefix = try repoUrlPrefix(arena, c.name.slice()); 467 var out: std.Io.Writer.Allocating = .init(arena.allocator()); 468 try out.writer.print("{s}/" ++ commits_seg, .{prefix}); 469 if (c.ref_or_oid) |kind| if (c.value.len != 0) try out.writer.print("/{s}:{s}", .{ @tagName(kind), c.value.slice() }); 470 switch (c.content) { 471 .diff => |d| { 472 if (d.start != 0) try out.writer.print("/" ++ start_seg ++ "{d}", .{d.start}); 473 if (d.path.len != 0) try out.writer.print("/" ++ path_seg ++ "{s}", .{d.path.slice()}); 474 }, 475 .message => try out.writer.print("/" ++ message_seg, .{}), 476 } 477 break :blk out.written(); 478 }, 479 .repo_refs => |r| blk: { 480 const prefix = try repoUrlPrefix(arena, r.name.slice()); 481 break :blk if (r.from.len == 0) 482 try std.fmt.allocPrint(arena.allocator(), "{s}/refs", .{prefix}) 483 else 484 try std.fmt.allocPrint(arena.allocator(), "{s}/refs/{s}:{s}", .{ prefix, @tagName(r.kind), r.from.slice() }); 485 }, 486 .repo_issues => |i| blk: { 487 const prefix = try repoUrlPrefix(arena, i.name.slice()); 488 if (i.view == .edit) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}/edit", .{ prefix, i.selected.slice() }); 489 if (i.view == .description) break :blk try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}/description", .{ prefix, i.selected.slice() }); 490 if (i.view == .resolve) break :blk if (i.theirs.len == 0) 491 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}/resolve", .{ prefix, i.selected.slice() }) 492 else 493 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/" ++ theirs_seg ++ "{s}/{s}/resolve", .{ prefix, i.theirs.slice(), i.selected.slice() }); 494 if (i.view == .conflicts) break :blk if (i.selected.len == 0) 495 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/conflicts", .{prefix}) 496 else 497 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/" ++ start_seg ++ "{s}/conflicts", .{ prefix, i.selected.slice() }); 498 // a selected issue's url carries its id instead of a view 499 // name, so it survives status changes 500 const word = if (i.selected.len != 0) i.selected.slice() else @tagName(i.view); 501 break :blk if (i.tag.len == 0) 502 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}", .{ prefix, word }) 503 else 504 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}/" ++ tag_filter_seg ++ "{s}", .{ prefix, word, i.tag.slice() }); 505 }, 506 .repo_settings => |name| try std.fmt.allocPrint(arena.allocator(), "{s}/settings", .{try repoUrlPrefix(arena, name.slice())}), 507 .repo_auth => |name| try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{try repoUrlPrefix(arena, name.slice())}), 508 }; 509 } 510 511 pub fn fromUrl(path: []const u8) ?RoutablePage { 512 if (std.mem.eql(u8, path, "/")) return default; 513 if (path.len < 2 or path[0] != '/') return null; 514 var segments = std.mem.splitScalar(u8, path[1..], '/'); 515 const first = segments.next() orelse return null; 516 if (std.mem.eql(u8, first, "users")) return .{ .home_users = listStart(&segments) orelse return null }; 517 if (std.mem.eql(u8, first, "repos")) return .{ .home_repos = listStart(&segments) orelse return null }; 518 if (std.mem.eql(u8, first, "settings")) return if (segments.next() == null) .home_settings else null; 519 if (std.mem.eql(u8, first, "auth")) return if (segments.next() == null) .home_auth else null; 520 // "user/<name>[/repos[/start:<n>]|/settings|/auth]" 521 if (std.mem.eql(u8, first, "user")) { 522 const name = segments.next() orelse return null; 523 if (name.len == 0) return null; 524 const parsed = Array(evt.User.name_max_len).from(name) orelse return null; // name too long 525 const sub = segments.next() orelse return .{ .user_repos = .{ .name = parsed } }; 526 if (std.mem.eql(u8, sub, "repos")) return .{ .user_repos = .{ .name = parsed, .start = listStart(&segments) orelse return null } }; 527 if (std.mem.eql(u8, sub, "settings")) return if (segments.next() == null) .{ .user_settings = parsed } else null; 528 if (std.mem.eql(u8, sub, "auth")) return if (segments.next() == null) .{ .user_auth = parsed } else null; 529 return null; // unknown sub-path 530 } 531 // "repo/<username>/<reponame>[/<tab tail>]"; the bare pair is the 532 // files root 533 if (std.mem.eql(u8, first, "repo")) { 534 const rest = segments.rest(); // "username/reponame[/...]" 535 const owner = segments.next() orelse return null; 536 const repo_name = segments.next() orelse return null; 537 // reject an empty username or reponame 538 if (owner.len == 0 or repo_name.len == 0) return null; 539 const pair = rest[0 .. owner.len + 1 + repo_name.len]; // "username/reponame" 540 if (segments.peek() != null) { 541 return repoSubRoute(pair, segments.rest()); 542 } 543 return repoFilesRoute(pair, null, "", "", 0); 544 } 545 return null; 546 } 547 548 // parse a local-mode url, which elides the "/repo/<owner>/<name>" prefix: 549 // "/" is the files root and the sub-paths follow directly. 550 pub fn fromUrlLocal(path: []const u8) ?RoutablePage { 551 if (std.mem.eql(u8, path, "/")) return repoFilesRoute("", null, "", "", 0); 552 if (path.len < 2 or path[0] != '/') return null; 553 return repoSubRoute("", path[1..]); 554 } 555 556 // the url prefix for a repo route's identity: "/repo/<identity>", or "" 557 // when the identity is elided. 558 fn repoUrlPrefix(arena: *std.heap.ArenaAllocator, identity: []const u8) ![]const u8 { 559 if (identity.len == 0) return ""; 560 return std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{identity}); 561 } 562 563 // true when the page builds at its content height on the web, letting the 564 // browser scroll the whole page, rather than being pinned to the viewport 565 pub fn fullHeight(self: RoutablePage) bool { 566 return switch (self) { 567 .repo_issues => |i| i.view == .resolve, 568 else => false, 569 }; 570 } 571 572 // the "owner/name" a repo route carries, null for any other route. the 573 // result borrows the route, so it must outlive the slice. 574 pub fn repoIdentity(self: *const RoutablePage) ?[]const u8 { 575 return switch (self.*) { 576 .repo_files => |*f| f.name.slice(), 577 .repo_commits => |*c| c.name.slice(), 578 .repo_refs => |*r| r.name.slice(), 579 .repo_issues => |*i| i.name.slice(), 580 .repo_settings, .repo_auth => |*name| name.slice(), 581 else => null, 582 }; 583 } 584 585 // the route this route's page lands on, with no tab or params: the users 586 // list, a user's repos, or a repo's files root. 587 pub fn pageRoot(self: RoutablePage) RoutablePage { 588 return switch (self.parent()) { 589 .home => .default, 590 .user => switch (self) { 591 .user_repos => |u| .{ .user_repos = .{ .name = u.name } }, 592 .user_settings, .user_auth => |name| .{ .user_repos = .{ .name = name } }, 593 else => self, 594 }, 595 // every repo route stores the same identity, so it always fits 596 .repo => repoFilesRoute(self.repoIdentity() orelse return self, null, "", "", 0) orelse self, 597 }; 598 } 599 600 pub fn parent(self: RoutablePage) PageKind { 601 return switch (self) { 602 .home_users, .home_repos, .home_settings, .home_auth => .home, 603 .user_repos, .user_settings, .user_auth => .user, 604 .repo_files, .repo_commits, .repo_refs, .repo_issues, .repo_settings, .repo_auth => .repo, 605 }; 606 } 607 608 // the dir a trailing "path:<dir>" names: the raw remainder ("" when 609 // absent, null when malformed) 610 fn pathValue(rest: []const u8) ?[]const u8 { 611 if (rest.len == 0) return ""; 612 if (!std.mem.startsWith(u8, rest, path_seg)) return null; 613 const dir = rest[path_seg.len..]; 614 return if (dir.len == 0) null else dir; 615 } 616 617 // a list route's tail: at most a "start:<n>" param, null on anything else 618 fn listStart(segments: *std.mem.SplitIterator(u8, .scalar)) ?usize { 619 var params = Params{}; 620 const word = params.scanTail(segments) catch return null; 621 if (word != null or !params.only(&.{.start})) return null; 622 return params.start(); 623 } 624 625 // parse the sub-path after a repo route's identity ("" for a local 626 // route): a tab keyword followed by "key:value" params in any order, plus 627 // the files tab's trailing "path:<dir>". 628 fn repoSubRoute(pair: []const u8, sub: []const u8) ?RoutablePage { 629 var segments = std.mem.splitScalar(u8, sub, '/'); 630 const tab = segments.next() orelse return null; 631 var params = Params{}; 632 if (std.mem.eql(u8, tab, "settings")) return if (segments.next() == null) .{ .repo_settings = Array(repo_route_max_len).from(pair) orelse return null } else null; 633 if (std.mem.eql(u8, tab, "auth")) return if (segments.next() == null) .{ .repo_auth = Array(repo_route_max_len).from(pair) orelse return null } else null; 634 if (std.mem.eql(u8, tab, "refs")) { 635 const word = params.scanTail(&segments) catch return null; 636 if (word != null or !params.only(&.{ .branch, .tag })) return null; 637 const ref = (params.ref() catch return null) orelse return repoRefsRoute(pair, .branch, ""); 638 const kind = std.meta.stringToEnum(RefKind, @tagName(ref.kind)) orelse return null; 639 return repoRefsRoute(pair, kind, ref.value); 640 } 641 if (std.mem.eql(u8, tab, "issues")) { 642 // "<id>/edit" is the edit form for that issue, with no params; 643 // "<id>/description" is its whole-description page. 644 const after_tab = segments.rest(); 645 if (std.mem.endsWith(u8, after_tab, "/edit")) { 646 const id = after_tab[0 .. after_tab.len - "/edit".len]; 647 if (id.len == 0 or std.mem.indexOfScalar(u8, id, '/') != null) return null; 648 return repoIssuesEditRoute(pair, id); 649 } 650 if (std.mem.endsWith(u8, after_tab, "/description")) { 651 const id = after_tab[0 .. after_tab.len - "/description".len]; 652 if (id.len == 0 or std.mem.indexOfScalar(u8, id, '/') != null) return null; 653 return repoIssuesDescriptionRoute(pair, id); 654 } 655 // "[theirs:<list>/]<id>/resolve" is the conflict resolve form. 656 if (std.mem.endsWith(u8, after_tab, "/resolve")) { 657 var resolve_segments = std.mem.splitScalar(u8, after_tab[0 .. after_tab.len - "/resolve".len], '/'); 658 const id = (params.scanTail(&resolve_segments) catch return null) orelse return null; 659 if (!params.only(&.{.theirs})) return null; 660 return repoIssuesResolveRoute(pair, id, params.values.get(.theirs) orelse ""); 661 } 662 // the word is a view name or an issue event id (whose status 663 // picks the view); a filter with neither is never emitted. 664 const word = params.scanTail(&segments) catch return null; 665 const tag_value = params.values.get(.tag) orelse ""; 666 const w = word orelse return if (params.only(&.{})) repoIssuesRoute(pair, .open, "", "") else null; 667 // the conflicts list windows by an issue id, not a number, so it 668 // reads the start param raw 669 if (std.mem.eql(u8, w, "conflicts")) { 670 if (!params.only(&.{.start})) return null; 671 return repoIssuesConflictsRoute(pair, params.values.get(.start) orelse ""); 672 } 673 if (!params.only(&.{.tag})) return null; 674 if (std.meta.stringToEnum(evt.Issue.Status, w)) |status| return repoIssuesRoute(pair, status, tag_value, ""); 675 if (std.mem.eql(u8, w, "tags")) return repoIssuesTagsRoute(pair, tag_value); 676 if (std.mem.eql(u8, w, "new")) return if (tag_value.len == 0) repoIssuesNewRoute(pair) else null; 677 return repoIssuesRoute(pair, .open, tag_value, w); 678 } 679 if (std.mem.eql(u8, tab, files_seg)) { 680 params.scanPairs(&segments) catch return null; 681 if (!params.only(&.{ .line, .branch, .tag, .object })) return null; 682 const line = params.line() orelse return null; 683 const dir = pathValue(segments.rest()) orelse return null; 684 const ref = (params.ref() catch return null) orelse 685 return if (dir.len == 0) repoFilesRoute(pair, null, "", "", line) else null; 686 return repoFilesRoute(pair, ref.kind, ref.value, dir, line); 687 } 688 if (std.mem.eql(u8, tab, commits_seg)) { 689 params.scanPairs(&segments) catch return null; 690 if (!params.only(&.{ .start, .branch, .tag, .object })) return null; 691 const start = params.start() orelse return null; 692 const ref = (params.ref() catch return null) orelse { 693 const file = pathValue(segments.rest()) orelse return null; 694 return if (file.len == 0) repoCommitsRoute(pair, null, "", start, "") else null; 695 }; 696 // the message page names its commit and nothing else 697 if (std.mem.eql(u8, segments.rest(), message_seg)) 698 return if (start == 0) repoCommitMessageRoute(pair, ref.kind, ref.value) else null; 699 const file = pathValue(segments.rest()) orelse return null; 700 return repoCommitsRoute(pair, ref.kind, ref.value, start, file); 701 } 702 return null; // unknown sub-path 703 } 704 705 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 706 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 707 return switch (a) { 708 .home_users => |a_start| a_start == b.home_users, 709 .home_repos => |a_start| a_start == b.home_repos, 710 .user_repos => |a_u| std.mem.eql(u8, a_u.name.slice(), b.user_repos.name.slice()) and a_u.start == b.user_repos.start, 711 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 712 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 713 .repo_files => |a_f| std.mem.eql(u8, a_f.name.slice(), b.repo_files.name.slice()) and 714 a_f.ref_kind == b.repo_files.ref_kind and 715 std.mem.eql(u8, a_f.ref_value.slice(), b.repo_files.ref_value.slice()) and 716 std.mem.eql(u8, a_f.path.slice(), b.repo_files.path.slice()) and 717 a_f.line == b.repo_files.line, 718 .repo_commits => |a_c| std.mem.eql(u8, a_c.name.slice(), b.repo_commits.name.slice()) and 719 a_c.ref_or_oid == b.repo_commits.ref_or_oid and 720 std.mem.eql(u8, a_c.value.slice(), b.repo_commits.value.slice()) and 721 switch (a_c.content) { 722 .diff => |a_d| switch (b.repo_commits.content) { 723 .diff => |b_d| a_d.start == b_d.start and std.mem.eql(u8, a_d.path.slice(), b_d.path.slice()), 724 .message => false, 725 }, 726 .message => std.meta.activeTag(b.repo_commits.content) == .message, 727 }, 728 .repo_refs => |a_r| std.mem.eql(u8, a_r.name.slice(), b.repo_refs.name.slice()) and a_r.kind == b.repo_refs.kind and std.mem.eql(u8, a_r.from.slice(), b.repo_refs.from.slice()), 729 .repo_issues => |a_i| std.mem.eql(u8, a_i.name.slice(), b.repo_issues.name.slice()) and 730 std.mem.eql(u8, a_i.tag.slice(), b.repo_issues.tag.slice()) and 731 std.mem.eql(u8, a_i.selected.slice(), b.repo_issues.selected.slice()) and 732 std.mem.eql(u8, a_i.theirs.slice(), b.repo_issues.theirs.slice()) and 733 a_i.view == b.repo_issues.view, 734 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 735 .repo_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_auth.slice()), 736 else => true, 737 }; 738 } 739 740 // true when following a link from `b` to `a` (both repo routes) should reload 741 // rather than stay in page 742 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 743 if (a.parent() != .repo or b.parent() != .repo) return false; 744 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 745 a.repo_refs.from.len == 0 and b.repo_refs.from.len == 0) 746 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 747 return !a.eql(b); 748 } 749 750 // true when `a` and `b` are the same user paginated to a different repos 751 // window. switching between a user's tabs is in-page (header-handled), so 752 // only a changed `start` on the repos list navigates. 753 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 754 return switch (a) { 755 .user_repos => |aa| switch (b) { 756 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 757 else => false, 758 }, 759 else => false, 760 }; 761 } 762 763 // true when `a` and `b` are the same home list tab paginated to a different 764 // window. switching between the users/repos tabs is in-page (the home page 765 // holds both lists), so only a changed `after` on the same tab navigates. 766 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 767 return switch (a) { 768 .home_users => |aa| switch (b) { 769 .home_users => |bb| aa != bb, 770 else => false, 771 }, 772 .home_repos => |aa| switch (b) { 773 .home_repos => |bb| aa != bb, 774 else => false, 775 }, 776 else => false, 777 }; 778 } 779 }; 780 781 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 782 fn isUnreserved(c: u8) bool { 783 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 784 } 785 786 // percent-encode a ref name for use as a single url path segment. 787 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 788 var out: std.Io.Writer.Allocating = .init(aa); 789 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 790 return out.written(); 791 } 792 793 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 794 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 795 return struct { 796 pub const hex_len = hash.hexLen(repo_opts.hash); 797 798 // the concrete ref/oid (a null request resolves to the default branch) 799 ref_or_oid: RoutablePage.RefOrOid, 800 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 801 // the route layer — which splits on '/' — stores them encoded). duped 802 // into `aa`. 803 value: []const u8, 804 // the commit oid it points at 805 oid: [hex_len]u8, 806 807 const Self = @This(); 808 809 // resolve a requested ref/oid (null = the repo's default branch) to a 810 // concrete ref/oid plus the commit oid it points at. `requested_value` is 811 // the url-encoded form (as it appears in the route). null when it doesn't 812 // resolve (an unknown branch/tag, or a malformed/unknown oid). 813 pub fn init( 814 repo: *rp.Repo(repo_kind, repo_opts), 815 io: std.Io, 816 aa: std.mem.Allocator, 817 requested_ref_or_oid: ?RoutablePage.RefOrOid, 818 requested_value: []const u8, 819 ) !?Self { 820 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 821 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 822 var value: []const u8 = if (requested_ref_or_oid == null) 823 requested_value 824 else 825 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 826 // no ref named: fall back to HEAD's branch (or its oid when detached). 827 if (requested_ref_or_oid == null) { 828 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 829 if (repo.head(io, &head_buf)) |head| switch (head) { 830 .ref => |r| { 831 ref_or_oid = .branch; 832 value = r.name; 833 }, 834 .oid => |o| { 835 ref_or_oid = .object; 836 value = o; 837 }, 838 } else |_| {} 839 } 840 841 var oid: [hex_len]u8 = undefined; 842 switch (ref_or_oid) { 843 .object => { 844 if (value.len != hex_len) return null; 845 @memcpy(&oid, value); 846 }, 847 .branch, .tag => { 848 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 849 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 850 }, 851 } 852 // store url-encoded so the route layer can hold the value verbatim. 853 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 854 } 855 }; 856 } 857 858 // where a repo page reads its on-disk repo from 859 pub const RepoSource = struct { 860 path: []const u8, 861 repo_kind: rp.RepoKind, 862 }; 863 864 // per-connection mutable state. each SSH session / web session / local TUI 865 // run gets its own. 866 pub const Session = struct { 867 data: Data = .{}, 868 // session-lifetime allocations: login/user_id, persisted prefs, queued 869 // actions. lives as long as the connection. 870 arena: *std.heap.ArenaAllocator, 871 // current page's allocations: page data and the page-scoped strings widgets 872 // build (form actions, links). owned by Nav, swapped on each navigation, so 873 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 874 // where a render is one-shot, this points at the same arena as `arena`. 875 page_arena: *std.heap.ArenaAllocator, 876 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 877 // filesystem io and the path to <server>/repos, for opening on-disk repos 878 // during page construction. both null on wasm, which has no filesystem and 879 // rebuilds pages from the serialized snapshot rather than from disk. 880 io: ?std.Io = null, 881 repos_dir: ?[]const u8 = null, 882 // the single on-disk repo this session views, when running in local mode 883 // (haxy invoked with no arguments inside a repo). null on the server paths, 884 // which resolve repos from the admin db instead. 885 local: ?RepoSource = null, 886 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 887 // focus id -> the live TextInput, refreshed each frame by the views that own 888 // inputs. web/wasm form handling looks widgets up here by focus id. 889 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 890 // focus id -> the page-constant text the web overlay renders into an 891 // input initially, refreshed each frame alongside `text_inputs`. never 892 // the input's live content: the overlay html must not change as the 893 // user types, or the diff in _setOverlay would rebuild the element. 894 input_values: std.AutoHashMapUnmanaged(usize, []const u8) = .empty, 895 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 896 refresh_requested: bool = false, // set by input (ctrl+r) 897 // a requested forward navigation. set this (via navigate) to move to a new 898 // page; Nav.sync builds it and then copies it into current_page, clearing 899 // this back to null. setting current_page directly only updates the url and 900 // does not navigate. 901 next_page: ?RoutablePage = null, 902 is_terminal: bool = false, // true on remote SSH and local TUI 903 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 904 // url. null on the web itself (no footer there). 905 web_port: ?u16 = null, 906 quit_requested: bool = false, 907 908 const Self = @This(); 909 910 // serializable data sent down to web client 911 pub const Data = struct { 912 user_id: ?[]const u8 = null, 913 // the logged-in user's name, for the views that show it 914 user_name: ?[]const u8 = null, 915 // a transient outcome to surface from the last /login POST attempt 916 login_failure: ?Home.Auth.Login.Failure = null, 917 current_page: RoutablePage = .default, 918 // whether to render the ANSI art backdrop 919 enable_ansi: bool = true, 920 // true when this session views a single local repo. unlike `local` 921 // (the host-side filesystem source) this travels in the snapshot, so 922 // the wasm side also parses elided link urls and hides the multi-user 923 // chrome. 924 is_local: bool = false, 925 }; 926 927 // a user-initiated state change. widgets enqueue these on the session during 928 // input instead of mutating state or touching the DB themselves; the host 929 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 930 // side effects out of the widget tree and gives every render path one place to 931 // turn a UI action into a state change + event. 932 pub const Action = union(enum) { 933 toggle_ansi, 934 }; 935 936 pub fn init( 937 arena: *std.heap.ArenaAllocator, 938 repo: *rp.Repo(.xit, evt.admin_repo_opts), 939 data: Data, 940 ) !Self { 941 var session = Self{ 942 .data = data, 943 .arena = arena, 944 // until a host swaps in a page-scoped arena (Nav does this), page 945 // allocations land in the session arena. on the web path that's the 946 // intended behavior, since the whole arena is per-request. 947 .page_arena = arena, 948 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 949 }; 950 try session.loadUser(); 951 return session; 952 } 953 954 // load the logged-in user's name and persisted preferences from the db 955 pub fn loadUser(self: *Self) !void { 956 const user_id = self.data.user_id orelse return; 957 const moment = self.haxy_moment orelse return; 958 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 959 self.data.user_name = user.event.name; 960 self.data.enable_ansi = user.event.enable_ansi; 961 } 962 } 963 964 // the author for an event this session creates, or null when it may not 965 // create one. local mode has no accounts, so it authors anonymously. 966 pub fn eventAuthorEmail(self: *Self) !?[]const u8 { 967 if (self.data.is_local) return "user@haxy"; // TODO: try the repo's git config user.email first 968 const user_id = self.data.user_id orelse return null; 969 const moment = self.haxy_moment orelse return null; 970 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.page_arena, user_id)) orelse return null; 971 return user.event.email; 972 } 973 974 // queue an action for the host to drain this frame. 975 pub fn push(self: *Self, action: Action) !void { 976 try self.pending.append(self.arena.allocator(), action); 977 } 978 979 // apply a single action's in-memory effect only (no persistence). 980 fn apply(self: *Self, action: Action) void { 981 switch (action) { 982 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 983 } 984 } 985 986 // drain the session's queued actions by applying them to the session. 987 // used on the wasm path, which has no repo to persist to. 988 pub fn applyPending(self: *Self) void { 989 for (self.pending.items) |action| self.apply(action); 990 self.pending.clearRetainingCapacity(); 991 } 992 993 // drain the session's queued actions by applying them to the session and 994 // writing them to the db 995 pub fn applyAndWritePending( 996 self: *Self, 997 io: std.Io, 998 allocator: std.mem.Allocator, 999 repo: *rp.Repo(.xit, evt.admin_repo_opts), 1000 ) !void { 1001 defer self.pending.clearRetainingCapacity(); 1002 for (self.pending.items) |action| { 1003 self.apply(action); 1004 switch (action) { 1005 .toggle_ansi => if (self.data.user_id) |user_id| { 1006 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 1007 }, 1008 } 1009 } 1010 } 1011 1012 // reload the moment from the admin repo and re-read user preferences 1013 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 1014 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 1015 self.haxy_moment = moment; 1016 1017 const user_id = self.data.user_id orelse return; 1018 var arena = std.heap.ArenaAllocator.init(allocator); 1019 defer arena.deinit(); 1020 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &arena, user_id)) |user| { 1021 self.data.enable_ansi = user.event.enable_ansi; 1022 } 1023 } 1024 1025 // request a forward navigation to `route`; the host consumes next_page 1026 // (Nav.sync on the terminal, the wasm tick on the web). 1027 pub fn navigate(self: *Session, route: RoutablePage) !void { 1028 self.next_page = route; 1029 } 1030 }; 1031 1032 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 1033 var nav = try Nav.init(allocator, session); 1034 defer nav.deinit(allocator); 1035 1036 var terminal = try term.Terminal.init(io, allocator); 1037 defer terminal.deinit(io); 1038 1039 // set term as active so it will be properly cooked 1040 // when a panic/segfault happens 1041 term.setActive(&terminal); 1042 defer term.setActive(null); 1043 1044 var last_size = layout.Size{ .width = 0, .height = 0 }; 1045 var last_grid = try Grid.init(allocator, last_size); 1046 defer last_grid.deinit(); 1047 1048 while (!terminal.shouldQuit()) { 1049 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 1050 1051 // process any inputs. 1052 // 1053 // if the grid didn't change, then first do a blocking 1054 // read, so the thread will sleep until further input. 1055 // after that, all remaining reads are non-blocking so 1056 // we can process the rest of the queued inputs. 1057 // 1058 // if the grid *did* change, then only do non-blocking 1059 // reads. we do not want to sleep the thread because 1060 // there may be an animation that requires more looping. 1061 var blocking = !grid_changed; 1062 while (try terminal.readKey(io, blocking)) |key| { 1063 blocking = false; 1064 try inputKey(allocator, &nav.root, key, session); 1065 } 1066 1067 // persist queued actions when there's a repo; local mode has none, 1068 // so just apply in-memory 1069 if (repo_maybe) |repo| { 1070 try session.applyAndWritePending(io, allocator, repo); 1071 // reload so the next navigation builds its page from the current moment 1072 try session.reloadMoment(allocator, repo); 1073 } else { 1074 session.applyPending(); 1075 } 1076 1077 // reconcile navigation: forward to a new page, or back on escape. 1078 try nav.sync(allocator, session); 1079 1080 // the quit button (on the quit tab) asks the host to tear down. 1081 if (session.quit_requested) terminal.requestQuit(); 1082 1083 try nav.root.build(allocator, .{ 1084 .min_size = .{ .width = null, .height = null }, 1085 .max_size = .{ .width = last_size.width, .height = last_size.height }, 1086 }, nav.root.getFocus()); 1087 } 1088 } 1089 1090 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 1091 switch (key) { 1092 // request a navigation pop; the host's Nav.sync goes back a page, or 1093 // quits when there's no history left. 1094 .escape => session.nav_back = true, 1095 .ctrl => |letter| switch (letter) { 1096 'r' => session.refresh_requested = true, 1097 else => try root.input(allocator, key, root.getFocus()), 1098 }, 1099 .enter => { 1100 const root_focus = root.getFocus(); 1101 if (root_focus.grandchild_id) |gid| { 1102 // follow a cross-page link 1103 if (crossPageLink(root_focus, gid, session.data)) |route| { 1104 return session.navigate(route); 1105 } 1106 } 1107 try root.input(allocator, key, root_focus); 1108 }, 1109 .mouse => |mouse| { 1110 if (mouse.action == .press and mouse.action.press == .left) { 1111 const root_focus = root.getFocus(); 1112 var clicked: ?usize = null; 1113 var iter = root_focus.children.iterator(); 1114 while (iter.next()) |entry| { 1115 const child = entry.value_ptr.*; 1116 if (!child.focus.focusable) continue; 1117 const r = child.rect; 1118 if (mouse.x >= r.x and mouse.y >= r.y and 1119 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 1120 { 1121 clicked = entry.key_ptr.*; 1122 break; 1123 } 1124 } 1125 if (clicked) |focus_id| { 1126 // follow a cross-page link 1127 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 1128 return session.navigate(route); 1129 } 1130 root_focus.setFocus(focus_id); 1131 } 1132 // forward the press into the widget tree so buttons (and any 1133 // future click-aware widgets) can react. widgets that don't 1134 // care about presses ignore it. 1135 try root.input(allocator, key, root.getFocus()); 1136 } else { 1137 try root.input(allocator, key, root.getFocus()); 1138 } 1139 }, 1140 else => try root.input(allocator, key, root.getFocus()), 1141 } 1142 } 1143 1144 // if the focus target at focus_id is an `a:` link that should navigate (a 1145 // different parent page, or a different files directory within the repo page), 1146 // return its route; otherwise null. lets a host turn a click / enter on such a 1147 // link into a navigation rather than a focus change. 1148 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 1149 const current = data.current_page; 1150 const child = root_focus.children.get(focus_id) orelse return null; 1151 const custom = switch (child.focus.kind) { 1152 .custom => |c| c, 1153 else => return null, 1154 }; 1155 const a_prefix = "a:"; 1156 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 1157 const path = custom[a_prefix.len..]; 1158 // local sessions build (and parse) links with the repo identity elided 1159 const route = (if (data.is_local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path)) orelse return null; 1160 // a link to a different parent page always navigates; within a page, a 1161 // files-directory / commits-page / list-window change navigates while tab 1162 // links stay in-page (header-handled). 1163 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 1164 return null; 1165 } 1166 1167 // a display author, resolved against the admin db at read time 1168 pub const Author = union(enum) { 1169 unknown, 1170 email: []const u8, // an email no user matches 1171 user_name: []const u8, 1172 1173 // the commit author line's email, resolved like initFromEmail 1174 pub fn init( 1175 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1176 arena: *std.heap.ArenaAllocator, 1177 author_line: []const u8, 1178 ) !Author { 1179 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 1180 } 1181 1182 // from a record's stored author email: it resolves to the user currently 1183 // holding it, else stays the email. the result is allocated in `arena`, 1184 // so the email may borrow transient memory. 1185 pub fn initFromEmail( 1186 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 1187 arena: *std.heap.ArenaAllocator, 1188 author_email: ?[]const u8, 1189 ) !Author { 1190 const email = author_email orelse return .unknown; 1191 if (haxy_moment) |moment| { 1192 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 1193 return .{ .user_name = user.event.name }; 1194 } 1195 } 1196 return .{ .email = try arena.allocator().dupe(u8, email) }; 1197 } 1198 }; 1199 1200 // the "a:" link to user `name`'s page. 1201 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 1202 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 1203 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 1204 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 1205 } 1206 1207 // a focusable " author " box showing `author`, linking to their user page 1208 // when it is a known user 1209 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox(Widget) { 1210 const text = switch (author) { 1211 .unknown => "", 1212 .email, .user_name => |t| t, 1213 }; 1214 var tb = try wgt.TextBox(Widget).init(allocator, text, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none, .label = " author " }); 1215 errdefer tb.deinit(allocator); 1216 tb.getFocus().focusable = true; 1217 switch (author) { 1218 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 1219 else => {}, 1220 } 1221 return tb; 1222 } 1223 1224 // native-TUI navigation 1225 pub const Nav = struct { 1226 root: Widget, 1227 route: RoutablePage, 1228 // backs the current page (its Page data and the page-scoped strings its 1229 // widgets build). owned here, swapped on each navigation. session.page_arena 1230 // tracks whichever of these is current so widgets allocate into it. 1231 arena: *std.heap.ArenaAllocator, 1232 history: std.ArrayList(Entry), 1233 1234 // each retained page keeps its own arena, freed when the page leaves the 1235 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 1236 // long-lived session from accumulating every page it ever visited. 1237 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 1238 1239 // cap on retained back-history so the chain can't grow memory without bound 1240 const max_history: usize = 16; 1241 1242 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 1243 const arena = try allocator.create(std.heap.ArenaAllocator); 1244 arena.* = std.heap.ArenaAllocator.init(allocator); 1245 errdefer { 1246 arena.deinit(); 1247 allocator.destroy(arena); 1248 } 1249 1250 session.page_arena = arena; 1251 const route = session.data.current_page; 1252 1253 const page = try arena.allocator().create(Page); 1254 page.* = try Page.init(arena, session, route); 1255 return .{ 1256 .root = try initRoot(allocator, page, session), 1257 .route = route, 1258 .arena = arena, 1259 .history = .empty, 1260 }; 1261 } 1262 1263 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 1264 self.root.deinit(allocator); 1265 freeArena(allocator, self.arena); 1266 for (self.history.items) |*entry| { 1267 entry.root.deinit(allocator); 1268 freeArena(allocator, entry.arena); 1269 } 1270 self.history.deinit(allocator); 1271 } 1272 1273 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 1274 arena.deinit(); 1275 allocator.destroy(arena); 1276 } 1277 1278 // reconcile the displayed root with the session's navigation state. a 1279 // forward nav (current_page moved to a different parent page) pushes the 1280 // current root and builds the new page in a fresh arena; a back request 1281 // frees the current page and restores the previous one. when escape is 1282 // pressed with no history left we switch to the quit tab instead of quitting. 1283 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 1284 // refresh: rebuild the current page in place from a current moment 1285 if (session.refresh_requested) { 1286 session.refresh_requested = false; 1287 if (session.haxy_moment != null or session.local != null) { 1288 const arena = try allocator.create(std.heap.ArenaAllocator); 1289 arena.* = std.heap.ArenaAllocator.init(allocator); 1290 errdefer freeArena(allocator, arena); 1291 1292 session.page_arena = arena; 1293 1294 const page = try arena.allocator().create(Page); 1295 page.* = try Page.init(arena, session, self.route); 1296 const new_root = try initRoot(allocator, page, session); 1297 1298 self.root.deinit(allocator); 1299 freeArena(allocator, self.arena); 1300 self.root = new_root; 1301 self.arena = arena; 1302 } 1303 return; 1304 } 1305 1306 if (session.nav_back) { 1307 session.nav_back = false; 1308 if (self.history.pop()) |entry| { 1309 self.root.deinit(allocator); 1310 freeArena(allocator, self.arena); 1311 self.root = entry.root; 1312 self.route = entry.route; 1313 self.arena = entry.arena; 1314 session.page_arena = entry.arena; 1315 session.data.current_page = entry.route; 1316 return; 1317 } 1318 // nothing to go back to; switch to the quit confirmation 1319 const root_focus = self.root.getFocus(); 1320 var iter = root_focus.children.iterator(); 1321 while (iter.next()) |entry| { 1322 switch (entry.value_ptr.focus.kind) { 1323 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 1324 root_focus.setFocus(entry.key_ptr.*); 1325 // a Stack only builds its selected child, so the quit 1326 // button isn't in the focus tree until a build runs with 1327 // the quit tab selected. build once, then send a 1328 // synthetic arrow_down to drop focus from the tab onto 1329 // the button so it's ready to confirm. 1330 try self.root.build(allocator, .{ 1331 .min_size = .{ .width = null, .height = 40 }, 1332 .max_size = .{ .width = 80, .height = null }, 1333 }, root_focus); 1334 try self.root.input(allocator, .arrow_down, root_focus); 1335 break; 1336 }, 1337 else => {}, 1338 } 1339 } 1340 return; 1341 } 1342 1343 // forward navigation: navigate() set next_page to the page to move to (a 1344 // cross-page link or tab change crossing pages) 1345 if (session.next_page) |route| { 1346 session.next_page = null; 1347 if (session.haxy_moment == null and session.local == null) return; 1348 // the page we navigated to becomes the current page 1349 session.data.current_page = route; 1350 1351 const arena = try allocator.create(std.heap.ArenaAllocator); 1352 arena.* = std.heap.ArenaAllocator.init(allocator); 1353 errdefer freeArena(allocator, arena); 1354 1355 session.page_arena = arena; 1356 1357 const page = try arena.allocator().create(Page); 1358 page.* = try Page.init(arena, session, route); 1359 const new_root = try initRoot(allocator, page, session); 1360 1361 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 1362 // drop the oldest entry (freeing its widget tree and arena) once over cap 1363 if (self.history.items.len > max_history) { 1364 var oldest = self.history.orderedRemove(0); 1365 oldest.root.deinit(allocator); 1366 freeArena(allocator, oldest.arena); 1367 } 1368 self.root = new_root; 1369 self.route = route; 1370 self.arena = arena; 1371 } 1372 } 1373 }; 1374 1375 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 1376 const page_widget: Widget = switch (page.*) { 1377 .home => |*p| .{ .home = try .init(allocator, p, session) }, 1378 .user => |*p| .{ .user = try .init(allocator, p, session) }, 1379 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 1380 }; 1381 1382 const demon_art = @embedFile("embed/demon.ans"); 1383 1384 // on the TUI/SSH, the page sits above a one-row footer showing the url 1385 var root = if (session.is_terminal) blk: { 1386 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 1387 errdefer box.deinit(allocator); 1388 const bg_id = bg_blk: { 1389 var background = try AnsiBackground.init(allocator, page_widget, demon_art, session); 1390 errdefer background.deinit(allocator); 1391 const id = background.getFocus().id; 1392 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 1393 break :bg_blk id; 1394 }; 1395 { 1396 var footer = try Footer.init(allocator, session); 1397 errdefer footer.deinit(allocator); 1398 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 1399 } 1400 box.getFocus().child_id = bg_id; 1401 break :blk Widget{ .box = box }; 1402 } else Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 1403 errdefer root.deinit(allocator); 1404 1405 // input-owning views build their TextInputs in init — so reset the 1406 // focus-id -> *TextInput map here 1407 session.text_inputs.clearRetainingCapacity(); 1408 session.input_values.clearRetainingCapacity(); 1409 1410 try root.build(allocator, .{ 1411 .min_size = .{ .width = null, .height = 40 }, 1412 .max_size = .{ .width = 100, .height = null }, 1413 }, root.getFocus()); 1414 1415 return root; 1416 } 1417 1418 pub const Widget = union(enum) { 1419 text: wgt.Text(Widget), 1420 box: wgt.Box(Widget), 1421 text_box: wgt.TextBox(Widget), 1422 text_input: wgt.TextInput(Widget), 1423 scroll: wgt.Scroll(Widget), 1424 stack: wgt.Stack(Widget), 1425 flow_box: FlowBox, 1426 flow_box_scroll: FlowBox.Scroll, 1427 tag_flow: TagFlow, 1428 spacer: Spacer, 1429 center: Center, 1430 section_label: SectionLabel, 1431 submit_button: SubmitButton, 1432 background: AnsiBackground, 1433 home: Home.View, 1434 user: User.View, 1435 repo: Repo.View, 1436 quit: Quit.View, 1437 unauthorized: Unauthorized.View, 1438 title: Title.View, 1439 sub_title: SubTitle.View, 1440 home_header: Home.Header.View, 1441 user_header: User.Header.View, 1442 repo_header: Repo.Header.View, 1443 repo_files_header: Repo.Files.Header.View, 1444 repo_commits_header: Repo.Commits.Header.View, 1445 repo_issues_header: Repo.Issues.Header, 1446 repo_files: Repo.Files.View, 1447 repo_commits: Repo.Commits.View, 1448 repo_refs: Repo.Refs.View, 1449 repo_issues: Repo.Issues.View, 1450 home_users: Home.Users.View, 1451 home_repos: Home.Repos.View, 1452 auth_tab: Home.Header.AuthTab.View, 1453 home_settings: Home.Settings.View, 1454 home_auth: Home.Auth.View, 1455 footer: Footer, 1456 1457 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 1458 switch (self.*) { 1459 inline else => |*case| case.deinit(allocator), 1460 } 1461 } 1462 1463 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 1464 switch (self.*) { 1465 inline else => |*case| try case.build(allocator, constraint, root_focus), 1466 } 1467 } 1468 1469 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) anyerror!void { 1470 switch (self.*) { 1471 inline else => |*case| try case.input(allocator, key, root_focus), 1472 } 1473 } 1474 1475 pub fn clearGrid(self: *Widget) void { 1476 switch (self.*) { 1477 inline else => |*case| case.clearGrid(), 1478 } 1479 } 1480 1481 pub fn getGrid(self: Widget) ?Grid { 1482 switch (self) { 1483 inline else => |*case| return case.getGrid(), 1484 } 1485 } 1486 1487 pub fn getFocus(self: *Widget) *Focus { 1488 switch (self.*) { 1489 inline else => |*case| return case.getFocus(), 1490 } 1491 } 1492 }; 1493 1494 // move the focused row in `box` by `delta`, clamped to the ends, scrolling 1495 // `scroll` to keep it visible. 1496 pub fn moveRowFocus(box: *wgt.Box(Widget), scroll: *wgt.Scroll(Widget), root_focus: *Focus, delta: isize) void { 1497 const keys = box.children.keys(); 1498 if (keys.len == 0) return; 1499 const cur_id = box.getFocus().child_id orelse return; 1500 const cur: isize = @intCast(box.children.getIndex(cur_id) orelse return); 1501 const last: isize = @intCast(keys.len - 1); 1502 const next: usize = @intCast(std.math.clamp(cur + delta, 0, last)); 1503 if (next == @as(usize, @intCast(cur))) return; 1504 root_focus.setFocus(keys[next]); 1505 if (box.children.values()[next].rect) |rect| scroll.scrollToRect(rect); 1506 } 1507 1508 pub const FlowBox = struct { 1509 focus: *Focus, 1510 grid: ?Grid, 1511 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1512 // backs the per-item strings the text boxes borrow: each box's `content` 1513 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 1514 // wholesale on each setItems so there's no per-string ownership to track. 1515 arena: std.heap.ArenaAllocator, 1516 // column count from the last build — FlowBox.Scroll.input uses it so arrow 1517 // up/down can step by a row's worth of items. 1518 last_cols: usize, 1519 options: Options, 1520 1521 const border_rows: usize = 2; 1522 1523 pub const Options = struct { 1524 cell_width: usize = 40, 1525 cell_height: usize = 3, 1526 }; 1527 1528 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 1529 return .{ 1530 .focus = try Focus.create(allocator, .container), 1531 .grid = null, 1532 .text_boxes = .empty, 1533 .arena = std.heap.ArenaAllocator.init(allocator), 1534 .last_cols = 1, 1535 .options = options, 1536 }; 1537 } 1538 1539 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 1540 self.focus.destroy(allocator); 1541 if (self.grid) |*grid| { 1542 grid.deinit(); 1543 self.grid = null; 1544 } 1545 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1546 self.text_boxes.deinit(allocator); 1547 self.arena.deinit(); 1548 } 1549 1550 // one flow item: its display text plus an optional link. a non-empty `link` 1551 // sets the item's focus kind such as `.{ .custom = "a:/user/foo" }`, which 1552 // the web renderer turns into an anchor. 1553 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1554 1555 // both the item text and the link are copied into the arena, so the caller's 1556 // slices needn't outlive this call. 1557 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const Item) !void { 1558 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1559 self.text_boxes.clearAndFree(allocator); 1560 1561 // the old text boxes (and their borrowed content/links) are gone now, so 1562 // the arena that backed those strings can be reclaimed. 1563 _ = self.arena.reset(.retain_capacity); 1564 const aa = self.arena.allocator(); 1565 1566 self.focus.clear(); 1567 self.focus.child_id = null; 1568 1569 for (items) |item| { 1570 const line = try aa.dupe(u8, item.text); 1571 1572 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 1573 errdefer text_box.deinit(allocator); 1574 text_box.getFocus().focusable = true; 1575 1576 if (item.link.len > 0) { 1577 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1578 } 1579 1580 try self.text_boxes.append(allocator, text_box); 1581 } 1582 1583 if (self.text_boxes.items.len > 0) { 1584 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1585 } 1586 } 1587 1588 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1589 self.clearGrid(); 1590 self.focus.clear(); 1591 1592 const cell_width = self.options.cell_width; 1593 const max_width = constraint.max_size.width orelse cell_width; 1594 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 1595 self.last_cols = cols; 1596 1597 const count = self.text_boxes.items.len; 1598 if (count == 0) return; 1599 const slot_height = self.options.cell_height + border_rows; 1600 if (slot_height == 0) return; 1601 1602 // build at the slot size so every text box fits a single grid cell 1603 for (self.text_boxes.items) |*tb| { 1604 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 1605 try tb.build(allocator, .{ 1606 .min_size = .{ .width = cell_width, .height = null }, 1607 .max_size = .{ .width = cell_width, .height = slot_height }, 1608 }, root_focus); 1609 } 1610 1611 const rows = (count + cols - 1) / cols; 1612 const content_height = rows * slot_height; 1613 const total_width = cols * cell_width; 1614 if (total_width == 0 or content_height == 0) return; 1615 1616 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 1617 errdefer grid.deinit(); 1618 1619 for (self.text_boxes.items, 0..) |*tb, i| { 1620 const tb_grid = tb.getGrid() orelse continue; 1621 const col = i % cols; 1622 const row = i / cols; 1623 const cell_x = col * cell_width; 1624 const cell_y = row * slot_height; 1625 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 1626 try grid.drawGrid(tb_grid, cell_x, cell_y); 1627 } 1628 1629 self.grid = grid; 1630 } 1631 1632 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1633 _ = self; 1634 _ = allocator; 1635 _ = key; 1636 _ = root_focus; 1637 } 1638 1639 pub fn clearGrid(self: *FlowBox) void { 1640 if (self.grid) |*grid| { 1641 grid.deinit(); 1642 self.grid = null; 1643 } 1644 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1645 } 1646 1647 pub fn getGrid(self: FlowBox) ?Grid { 1648 return self.grid; 1649 } 1650 1651 pub fn getFocus(self: *FlowBox) *Focus { 1652 return self.focus; 1653 } 1654 1655 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 1656 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 1657 const slot_height = self.options.cell_height + border_rows; 1658 const col = index % self.last_cols; 1659 const row = index / self.last_cols; 1660 return .{ 1661 .x = @intCast(col * self.options.cell_width), 1662 .y = @intCast(row * slot_height), 1663 .size = .{ .width = self.options.cell_width, .height = slot_height }, 1664 }; 1665 } 1666 1667 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 1668 for (self.text_boxes.items, 0..) |tb, i| { 1669 if (tb.box.focus.id == focus_id) return i; 1670 } 1671 return null; 1672 } 1673 1674 pub const Scroll = struct { 1675 scroll: wgt.Scroll(Widget), 1676 1677 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options, web_native: bool) !Scroll { 1678 var layout_inner = try FlowBox.init(allocator, options); 1679 errdefer layout_inner.deinit(allocator); 1680 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert, .web_native = web_native }); 1681 errdefer scroll.deinit(allocator); 1682 return .{ .scroll = scroll }; 1683 } 1684 1685 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 1686 self.scroll.deinit(allocator); 1687 } 1688 1689 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const Item) !void { 1690 self.scroll.x = 0; 1691 self.scroll.y = 0; 1692 try self.inner().setItems(allocator, items); 1693 } 1694 1695 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1696 try self.scroll.build(allocator, constraint, root_focus); 1697 } 1698 1699 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1700 _ = allocator; 1701 const in = self.inner(); 1702 const child_id = in.focus.child_id orelse return; 1703 const current_index = in.indexOfFocusId(child_id) orelse return; 1704 const count = in.text_boxes.items.len; 1705 if (count == 0) return; 1706 const cols = in.last_cols; 1707 const slot_height = in.options.cell_height + FlowBox.border_rows; 1708 1709 var index = current_index; 1710 switch (key) { 1711 .arrow_up => index -|= cols, 1712 .arrow_down => if (index + cols < count) { 1713 index += cols; 1714 }, 1715 .arrow_left => index -|= 1, 1716 .arrow_right => if (index + 1 < count) { 1717 index += 1; 1718 }, 1719 .home => index = 0, 1720 .end => index = count - 1, 1721 .page_up => { 1722 if (self.scroll.grid) |grid| if (slot_height > 0) { 1723 const rows_per_page = grid.size.height / slot_height; 1724 index -|= rows_per_page * cols; 1725 }; 1726 }, 1727 .page_down => { 1728 if (self.scroll.grid) |grid| if (slot_height > 0) { 1729 const rows_per_page = grid.size.height / slot_height; 1730 index = @min(index + rows_per_page * cols, count - 1); 1731 }; 1732 }, 1733 // scroll wheel moves the focused cell by a full row so the 1734 // viewport (via scrollToRect) follows in row-sized steps, 1735 // matching how a scroll wheel feels in a grid view. 1736 .mouse => |mouse| switch (mouse.action) { 1737 .scroll => |dir| switch (dir) { 1738 .up => index -|= cols, 1739 .down => if (index + cols < count) { 1740 index += cols; 1741 }, 1742 }, 1743 else => {}, 1744 }, 1745 else => {}, 1746 } 1747 1748 if (index != current_index) { 1749 root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 1750 if (in.cellRect(index)) |rect| { 1751 self.scroll.scrollToRect(rect); 1752 } 1753 } 1754 } 1755 1756 pub fn clearGrid(self: *Scroll) void { 1757 self.scroll.clearGrid(); 1758 } 1759 1760 pub fn getGrid(self: Scroll) ?Grid { 1761 return self.scroll.getGrid(); 1762 } 1763 1764 pub fn getFocus(self: *Scroll) *Focus { 1765 return self.scroll.getFocus(); 1766 } 1767 1768 pub fn getSelectedIndex(self: Scroll) ?usize { 1769 const in = self.scroll.child.flow_box; 1770 const child_id = in.focus.child_id orelse return null; 1771 return in.indexOfFocusId(child_id); 1772 } 1773 1774 fn inner(self: *Scroll) *FlowBox { 1775 return &self.scroll.child.flow_box; 1776 } 1777 }; 1778 }; 1779 1780 // a left-to-right flow of variable-width focusable items that wraps at the 1781 // available width, like words in a paragraph. unlike FlowBox there is no cell 1782 // grid: each item is as wide as its text. selection movement is driven by the 1783 // owning view via indexOfFocusId/verticalNeighbor. 1784 pub const TagFlow = struct { 1785 focus: *Focus, 1786 grid: ?Grid, 1787 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1788 // last build's item rects (content space), for vertical navigation and 1789 // scroll-into-view. 1790 rects: std.ArrayList(layout.IRect), 1791 // backs the per-item strings the text boxes borrow. 1792 arena: std.heap.ArenaAllocator, 1793 1794 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1795 1796 pub fn init(allocator: std.mem.Allocator) !TagFlow { 1797 return .{ 1798 .focus = try Focus.create(allocator, .container), 1799 .grid = null, 1800 .text_boxes = .empty, 1801 .rects = .empty, 1802 .arena = std.heap.ArenaAllocator.init(allocator), 1803 }; 1804 } 1805 1806 pub fn deinit(self: *TagFlow, allocator: std.mem.Allocator) void { 1807 self.focus.destroy(allocator); 1808 if (self.grid) |*grid| { 1809 grid.deinit(); 1810 self.grid = null; 1811 } 1812 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1813 self.text_boxes.deinit(allocator); 1814 self.rects.deinit(allocator); 1815 self.arena.deinit(); 1816 } 1817 1818 // both the item text and the link are copied into the arena, so the caller's 1819 // slices needn't outlive this call. 1820 pub fn setItems(self: *TagFlow, allocator: std.mem.Allocator, items: []const Item) !void { 1821 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1822 self.text_boxes.clearAndFree(allocator); 1823 1824 _ = self.arena.reset(.retain_capacity); 1825 const aa = self.arena.allocator(); 1826 1827 self.focus.clear(); 1828 self.focus.child_id = null; 1829 1830 for (items) |item| { 1831 const line = try aa.dupe(u8, item.text); 1832 1833 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 1834 errdefer text_box.deinit(allocator); 1835 text_box.getFocus().focusable = true; 1836 1837 if (item.link.len > 0) { 1838 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1839 } 1840 1841 try self.text_boxes.append(allocator, text_box); 1842 } 1843 1844 if (self.text_boxes.items.len > 0) { 1845 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1846 } 1847 } 1848 1849 pub fn build(self: *TagFlow, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1850 self.clearGrid(); 1851 self.focus.clear(); 1852 1853 if (self.text_boxes.items.len == 0) return; 1854 const max_width = constraint.max_size.width orelse 80; 1855 if (max_width == 0) return; 1856 1857 // lay the items out left to right, wrapping to a new row when the next 1858 // one wouldn't fit. 1859 self.rects.clearRetainingCapacity(); 1860 var x: usize = 0; 1861 var y: usize = 0; 1862 var row_height: usize = 0; 1863 var total_width: usize = 0; 1864 for (self.text_boxes.items) |*tb| { 1865 try tb.build(allocator, .{ 1866 .min_size = .{ .width = null, .height = null }, 1867 .max_size = .{ .width = max_width, .height = null }, 1868 }, root_focus); 1869 const tb_grid_maybe = tb.getGrid(); 1870 const w: usize = if (tb_grid_maybe) |g| g.size.width else 0; 1871 const h: usize = if (tb_grid_maybe) |g| g.size.height else 0; 1872 if (x > 0 and x + w > max_width) { 1873 x = 0; 1874 y += row_height; 1875 row_height = 0; 1876 } 1877 try self.rects.append(allocator, .{ .x = @intCast(x), .y = @intCast(y), .size = .{ .width = w, .height = h } }); 1878 if (h > row_height) row_height = h; 1879 x += w; 1880 if (x > total_width) total_width = x; 1881 } 1882 1883 const total_height = y + row_height; 1884 if (total_width == 0 or total_height == 0) return; 1885 1886 var grid = try Grid.init(allocator, .{ .width = total_width, .height = total_height }); 1887 errdefer grid.deinit(); 1888 1889 for (self.text_boxes.items, self.rects.items) |*tb, rect| { 1890 const tb_grid = tb.getGrid() orelse continue; 1891 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, @intCast(rect.x), @intCast(rect.y)); 1892 try grid.drawGrid(tb_grid, @intCast(rect.x), @intCast(rect.y)); 1893 } 1894 1895 self.grid = grid; 1896 } 1897 1898 pub fn input(self: *TagFlow, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1899 _ = self; 1900 _ = allocator; 1901 _ = key; 1902 _ = root_focus; 1903 } 1904 1905 pub fn clearGrid(self: *TagFlow) void { 1906 if (self.grid) |*grid| { 1907 grid.deinit(); 1908 self.grid = null; 1909 } 1910 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1911 } 1912 1913 pub fn getGrid(self: TagFlow) ?Grid { 1914 return self.grid; 1915 } 1916 1917 pub fn getFocus(self: *TagFlow) *Focus { 1918 return self.focus; 1919 } 1920 1921 pub fn indexOfFocusId(self: TagFlow, focus_id: usize) ?usize { 1922 for (self.text_boxes.items, 0..) |tb, i| { 1923 if (tb.box.focus.id == focus_id) return i; 1924 } 1925 return null; 1926 } 1927 1928 // the first item of the row below (when `downward`) or above, or null at 1929 // the flow's edge. items are laid out in order, so y is nondecreasing. 1930 pub fn rowStep(self: TagFlow, index: usize, downward: bool) ?usize { 1931 const rects = self.rects.items; 1932 if (index >= rects.len) return null; 1933 const cur_y = rects[index].y; 1934 if (downward) { 1935 for (rects[index + 1 ..], index + 1..) |r, i| { 1936 if (r.y > cur_y) return i; 1937 } 1938 return null; 1939 } 1940 // walk the earlier rows; the last one visited is the row above. 1941 var prev_first: ?usize = null; 1942 var i: usize = 0; 1943 while (i < rects.len and rects[i].y < cur_y) { 1944 prev_first = i; 1945 const y = rects[i].y; 1946 while (i < rects.len and rects[i].y == y) i += 1; 1947 } 1948 return prev_first; 1949 } 1950 }; 1951 1952 // an invisible widget that fills the horizontal space granted by its parent. 1953 // used inside Box(horiz) with a min_size so the box reserves space for the 1954 // children that follow, pushing them to the right. 1955 pub const Spacer = struct { 1956 focus: *Focus, 1957 grid: ?Grid, 1958 1959 pub fn init(allocator: std.mem.Allocator) !Spacer { 1960 return .{ 1961 .focus = try Focus.create(allocator, .container), 1962 .grid = null, 1963 }; 1964 } 1965 1966 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 1967 self.focus.destroy(allocator); 1968 if (self.grid) |*grid| { 1969 grid.deinit(); 1970 self.grid = null; 1971 } 1972 } 1973 1974 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1975 _ = root_focus; 1976 self.clearGrid(); 1977 const width = constraint.max_size.width orelse return; 1978 if (width == 0) return; 1979 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1980 } 1981 1982 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1983 _ = self; 1984 _ = allocator; 1985 _ = key; 1986 _ = root_focus; 1987 } 1988 1989 pub fn clearGrid(self: *Spacer) void { 1990 if (self.grid) |*grid| { 1991 grid.deinit(); 1992 self.grid = null; 1993 } 1994 } 1995 1996 pub fn getGrid(self: Spacer) ?Grid { 1997 return self.grid; 1998 } 1999 2000 pub fn getFocus(self: *Spacer) *Focus { 2001 return self.focus; 2002 } 2003 }; 2004 2005 // a one-row, non-focusable status bar showing the current page's url 2006 pub const Footer = struct { 2007 focus: *Focus, 2008 grid: ?Grid, 2009 session: *Session, 2010 arena: std.heap.ArenaAllocator, 2011 2012 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 2013 return .{ 2014 .focus = try Focus.create(allocator, .container), 2015 .grid = null, 2016 .session = session, 2017 .arena = std.heap.ArenaAllocator.init(allocator), 2018 }; 2019 } 2020 2021 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 2022 self.focus.destroy(allocator); 2023 if (self.grid) |*grid| grid.deinit(); 2024 self.arena.deinit(); 2025 } 2026 2027 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2028 _ = root_focus; 2029 self.clearGrid(); 2030 const width = constraint.max_size.width orelse return; 2031 if (width == 0) return; 2032 2033 _ = self.arena.reset(.retain_capacity); 2034 const aa = self.arena.allocator(); 2035 const path = self.session.data.current_page.toUrl(&self.arena) catch return; 2036 const text = if (self.session.web_port) |port| 2037 std.fmt.allocPrint(aa, "http://localhost:{d}{s}", .{ port, path }) catch return 2038 else 2039 path; 2040 2041 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 2042 errdefer grid.deinit(); 2043 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 2044 var i: usize = 0; 2045 while (utf8.nextCodepointSlice()) |ch| { 2046 if (i == width) break; 2047 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 2048 i += 1; 2049 } 2050 self.grid = grid; 2051 } 2052 2053 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2054 _ = self; 2055 _ = allocator; 2056 _ = key; 2057 _ = root_focus; 2058 } 2059 2060 pub fn clearGrid(self: *Footer) void { 2061 if (self.grid) |*grid| { 2062 grid.deinit(); 2063 self.grid = null; 2064 } 2065 } 2066 2067 pub fn getGrid(self: Footer) ?Grid { 2068 return self.grid; 2069 } 2070 2071 pub fn getFocus(self: *Footer) *Focus { 2072 return self.focus; 2073 } 2074 }; 2075 2076 // a single-child wrapper that builds the child at its natural size and 2077 // positions its grid in the middle of the area granted by the parent 2078 // a bordered label, indented past the content it precedes 2079 pub const SectionLabel = struct { 2080 box: wgt.Box(Widget), 2081 2082 pub fn init(allocator: std.mem.Allocator, content: []const u8) !SectionLabel { 2083 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 2084 errdefer box.deinit(allocator); 2085 2086 { 2087 var gap = try wgt.Text(Widget).init(allocator, " "); 2088 errdefer gap.deinit(allocator); 2089 try box.children.put(allocator, gap.getFocus().id, .{ .widget = .{ .text = gap }, .rect = null, .min_size = null }); 2090 } 2091 2092 { 2093 var tb = try wgt.TextBox(Widget).init(allocator, content, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 2094 errdefer tb.deinit(allocator); 2095 tb.getFocus().focusable = true; 2096 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 2097 } 2098 2099 box.getFocus().child_id = box.children.keys()[1]; 2100 return .{ .box = box }; 2101 } 2102 2103 pub fn deinit(self: *SectionLabel, allocator: std.mem.Allocator) void { 2104 self.box.deinit(allocator); 2105 } 2106 2107 pub fn build(self: *SectionLabel, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2108 try self.box.build(allocator, constraint, root_focus); 2109 } 2110 2111 pub fn input(self: *SectionLabel, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2112 _ = self; 2113 _ = allocator; 2114 _ = key; 2115 _ = root_focus; 2116 } 2117 2118 pub fn clearGrid(self: *SectionLabel) void { 2119 self.box.clearGrid(); 2120 } 2121 2122 pub fn getGrid(self: SectionLabel) ?Grid { 2123 return self.box.getGrid(); 2124 } 2125 2126 pub fn getFocus(self: *SectionLabel) *Focus { 2127 return self.box.getFocus(); 2128 } 2129 }; 2130 2131 // a submit button, indented past its form's content. the web overlay POSTs 2132 // the button's form; terminal hosts detect presses through `buttonId`. 2133 pub const SubmitButton = struct { 2134 box: wgt.Box(Widget), 2135 2136 pub fn init(allocator: std.mem.Allocator) !SubmitButton { 2137 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 2138 errdefer box.deinit(allocator); 2139 2140 { 2141 var gap = try wgt.Text(Widget).init(allocator, " "); 2142 errdefer gap.deinit(allocator); 2143 try box.children.put(allocator, gap.getFocus().id, .{ .widget = .{ .text = gap }, .rect = null, .min_size = null }); 2144 } 2145 2146 { 2147 const label = "submit"; 2148 var button = try wgt.TextBox(Widget).init(allocator, label, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 2149 errdefer button.deinit(allocator); 2150 button.getFocus().focusable = true; 2151 // the renderer distinguishes plain clickables from buttons that 2152 // should POST to a server route by this kind. 2153 button.getFocus().kind = .{ .custom = "submit" }; 2154 try box.children.put(allocator, button.getFocus().id, .{ .widget = .{ .text_box = button }, .rect = null, .min_size = .{ .width = label.len + 2, .height = null } }); 2155 } 2156 2157 box.getFocus().child_id = box.children.keys()[1]; 2158 return .{ .box = box }; 2159 } 2160 2161 pub fn deinit(self: *SubmitButton, allocator: std.mem.Allocator) void { 2162 self.box.deinit(allocator); 2163 } 2164 2165 pub fn build(self: *SubmitButton, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2166 try self.box.build(allocator, constraint, root_focus); 2167 } 2168 2169 pub fn input(self: *SubmitButton, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2170 _ = self; 2171 _ = allocator; 2172 _ = key; 2173 _ = root_focus; 2174 } 2175 2176 pub fn clearGrid(self: *SubmitButton) void { 2177 self.box.clearGrid(); 2178 } 2179 2180 pub fn getGrid(self: SubmitButton) ?Grid { 2181 return self.box.getGrid(); 2182 } 2183 2184 pub fn getFocus(self: *SubmitButton) *Focus { 2185 return self.box.getFocus(); 2186 } 2187 2188 // the button's focus id, for click hit-testing 2189 pub fn buttonId(self: *const SubmitButton) usize { 2190 return self.box.children.keys()[1]; 2191 } 2192 }; 2193 2194 pub const Center = struct { 2195 focus: *Focus, 2196 grid: ?Grid, 2197 child: *Widget, 2198 2199 pub fn init(allocator: std.mem.Allocator, child_widget: Widget) !Center { 2200 const child = try allocator.create(Widget); 2201 errdefer allocator.destroy(child); 2202 child.* = child_widget; 2203 return .{ 2204 .focus = try Focus.create(allocator, .container), 2205 .grid = null, 2206 .child = child, 2207 }; 2208 } 2209 2210 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 2211 self.focus.destroy(allocator); 2212 if (self.grid) |*grid| { 2213 grid.deinit(); 2214 self.grid = null; 2215 } 2216 self.child.deinit(allocator); 2217 allocator.destroy(self.child); 2218 } 2219 2220 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2221 self.clearGrid(); 2222 self.getFocus().clear(); 2223 2224 // build the child without forcing it to fill min_size; it sizes 2225 // itself to its content within the available max. 2226 try self.child.build(allocator, .{ 2227 .min_size = .{ .width = null, .height = null }, 2228 .max_size = constraint.max_size, 2229 }, root_focus); 2230 2231 const child_grid = self.child.getGrid() orelse return; 2232 2233 // prefer max when given; otherwise grow to max(min, child) so that 2234 // when only a min is set (e.g. the wasm path passes viewport rows 2235 // as min_height with no max), we can still vertically center while 2236 // letting taller content extend past the min. 2237 const width = if (constraint.max_size.width) |w| w else if (constraint.min_size.width) |min_w| @max(min_w, child_grid.size.width) else child_grid.size.width; 2238 const height = if (constraint.max_size.height) |h| h else if (constraint.min_size.height) |min_h| @max(min_h, child_grid.size.height) else child_grid.size.height; 2239 if (width == 0 or height == 0) return; 2240 2241 const offset_x: usize = (width -| child_grid.size.width) / 2; 2242 const offset_y: usize = (height -| child_grid.size.height) / 2; 2243 2244 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 2245 errdefer grid.deinit(); 2246 try grid.drawGrid(child_grid, offset_x, offset_y); 2247 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 2248 self.getFocus().child_id = self.child.getFocus().id; 2249 2250 self.grid = grid; 2251 } 2252 2253 pub fn input(self: *Center, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2254 try self.child.input(allocator, key, root_focus); 2255 } 2256 2257 pub fn clearGrid(self: *Center) void { 2258 if (self.grid) |*grid| { 2259 grid.deinit(); 2260 self.grid = null; 2261 } 2262 self.child.clearGrid(); 2263 } 2264 2265 pub fn getGrid(self: Center) ?Grid { 2266 return self.grid; 2267 } 2268 2269 pub fn getFocus(self: *Center) *Focus { 2270 return self.focus; 2271 } 2272 }; 2273 2274 // renders truecolor ANSI art 2275 pub const AnsiArt = struct { 2276 focus: *Focus, 2277 grid: ?Grid, 2278 content: []const u8, 2279 2280 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 2281 return .{ 2282 .focus = try Focus.create(allocator, .container), 2283 .grid = null, 2284 .content = content, 2285 }; 2286 } 2287 2288 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 2289 self.focus.destroy(allocator); 2290 if (self.grid) |*grid| { 2291 grid.deinit(); 2292 self.grid = null; 2293 } 2294 } 2295 2296 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2297 _ = root_focus; 2298 self.clearGrid(); 2299 2300 // parse into rows of cells, then copy into a rectangular grid 2301 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 2302 defer { 2303 for (rows.items) |*row| row.deinit(allocator); 2304 rows.deinit(allocator); 2305 } 2306 var row: std.ArrayList(Grid.Cell) = .empty; 2307 errdefer row.deinit(allocator); 2308 2309 var style: Grid.Style = .{}; 2310 var width: usize = 0; 2311 const content = self.content; 2312 var i: usize = 0; 2313 while (i < content.len) { 2314 const byte = content[i]; 2315 if (byte == '\n') { 2316 width = @max(width, row.items.len); 2317 try rows.append(allocator, row); 2318 row = .empty; 2319 i += 1; 2320 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 2321 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 2322 var j = i + 2; 2323 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 2324 if (j >= content.len) { 2325 i = content.len; // malformed trailing escape; stop 2326 } else { 2327 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 2328 i = j + 1; 2329 } 2330 } else { 2331 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 2332 const end = @min(content.len, i + len); 2333 const rune = content[i..end]; 2334 const transparent = end - i == 1 and rune[0] == ' ' and 2335 style.fg == null and style.bg == null and !style.inverted; 2336 try row.append(allocator, .{ 2337 .rune = if (transparent) null else rune, 2338 .style = style, 2339 }); 2340 i = end; 2341 } 2342 } 2343 // a trailing row with content but no closing newline 2344 if (row.items.len > 0) { 2345 width = @max(width, row.items.len); 2346 try rows.append(allocator, row); 2347 } else { 2348 row.deinit(allocator); 2349 } 2350 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 2351 2352 const height = rows.items.len; 2353 if (width == 0 or height == 0) return; 2354 2355 const clamped_w = @min(width, constraint.max_size.width orelse width); 2356 const clamped_h = @min(height, constraint.max_size.height orelse height); 2357 2358 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 2359 errdefer grid.deinit(); 2360 for (rows.items[0..clamped_h], 0..) |r, y| { 2361 const n = @min(r.items.len, clamped_w); 2362 for (r.items[0..n], 0..) |cell, x| { 2363 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 2364 } 2365 } 2366 self.grid = grid; 2367 } 2368 2369 pub fn clearGrid(self: *AnsiArt) void { 2370 if (self.grid) |*grid| { 2371 grid.deinit(); 2372 self.grid = null; 2373 } 2374 } 2375 2376 pub fn getGrid(self: AnsiArt) ?Grid { 2377 return self.grid; 2378 } 2379 2380 pub fn getFocus(self: *AnsiArt) *Focus { 2381 return self.focus; 2382 } 2383 2384 fn applySgr(style: *Grid.Style, params: []const u8) void { 2385 var nums: [16]u32 = undefined; 2386 var n: usize = 0; 2387 var it = std.mem.splitScalar(u8, params, ';'); 2388 while (it.next()) |tok| { 2389 if (n >= nums.len) break; 2390 // an empty parameter (e.g. bare "\x1b[m") means 0 2391 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 2392 n += 1; 2393 } 2394 if (n == 0) { 2395 style.* = .{}; 2396 return; 2397 } 2398 var i: usize = 0; 2399 while (i < n) : (i += 1) { 2400 switch (nums[i]) { 2401 0 => style.* = .{}, 2402 7 => style.inverted = true, 2403 27 => style.inverted = false, 2404 39 => style.fg = null, 2405 49 => style.bg = null, 2406 38, 48 => { 2407 // truecolor form: 38;2;r;g;b — anything else is ignored 2408 if (i + 4 < n and nums[i + 1] == 2) { 2409 const c = Grid.Color{ 2410 .r = @truncate(nums[i + 2]), 2411 .g = @truncate(nums[i + 3]), 2412 .b = @truncate(nums[i + 4]), 2413 }; 2414 if (nums[i] == 38) style.fg = c else style.bg = c; 2415 i += 4; 2416 } 2417 }, 2418 else => {}, 2419 } 2420 } 2421 } 2422 }; 2423 2424 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 2425 pub const AnsiBackground = struct { 2426 grid: ?Grid, 2427 child: *Widget, 2428 art: AnsiArt, 2429 session: *Session, 2430 2431 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 2432 var cw = child_widget; 2433 const child = allocator.create(Widget) catch |e| { 2434 cw.deinit(allocator); 2435 return e; 2436 }; 2437 child.* = cw; 2438 errdefer { 2439 child.deinit(allocator); 2440 allocator.destroy(child); 2441 } 2442 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 2443 } 2444 2445 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 2446 if (self.grid) |*grid| grid.deinit(); 2447 self.art.deinit(allocator); 2448 self.child.deinit(allocator); 2449 allocator.destroy(self.child); 2450 } 2451 2452 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2453 self.clearGrid(); 2454 2455 // make the wrapped page fill the whole available area 2456 try self.child.build(allocator, .{ 2457 .min_size = .{ 2458 .width = constraint.max_size.width orelse constraint.min_size.width, 2459 .height = constraint.max_size.height orelse constraint.min_size.height, 2460 }, 2461 .max_size = constraint.max_size, 2462 }, root_focus); 2463 2464 if (self.session.data.enable_ansi) { 2465 if (self.child.getGrid()) |fg| { 2466 self.grid = try artBehind(allocator, fg, &self.art, .top_right, self.session.is_terminal, root_focus); 2467 } 2468 } 2469 } 2470 2471 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2472 try self.child.input(allocator, key, root_focus); 2473 } 2474 2475 pub fn clearGrid(self: *AnsiBackground) void { 2476 if (self.grid) |*grid| { 2477 grid.deinit(); 2478 self.grid = null; 2479 } 2480 self.child.clearGrid(); 2481 self.art.clearGrid(); 2482 } 2483 2484 pub fn getGrid(self: AnsiBackground) ?Grid { 2485 return self.grid orelse self.child.getGrid(); 2486 } 2487 2488 pub fn getFocus(self: *AnsiBackground) *Focus { 2489 return self.child.getFocus(); 2490 } 2491 2492 // which top corner the art hugs. 2493 const ArtAnchor = enum { top_left, top_right }; 2494 2495 // a foreground cell counts as blank if it's empty or a bare space without styling 2496 fn cellIsBlank(cell: Grid.Cell) bool { 2497 if (cell.rune) |rune| { 2498 return std.mem.eql(u8, rune, " ") and 2499 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 2500 } 2501 return true; 2502 } 2503 2504 // the art is dimmed to this fraction of its brightness so foreground text 2505 // stays legible over it 2506 const art_brightness = 45; // percent 2507 2508 fn dimColor(color: ?Grid.Color) ?Grid.Color { 2509 const c = color orelse return null; 2510 return .{ 2511 .r = @intCast(@as(u16, c.r) * art_brightness / 100), 2512 .g = @intCast(@as(u16, c.g) * art_brightness / 100), 2513 .b = @intCast(@as(u16, c.b) * art_brightness / 100), 2514 }; 2515 } 2516 2517 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 2518 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 2519 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 2520 // snap such channels clear of that range so the backdrop doesn't blink or 2521 // hide text there; the ≤9/255 shift is imperceptible on terminals that 2522 // actually render truecolor. 2523 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 2524 const c = color orelse return null; 2525 const snap = struct { 2526 fn f(v: u8) u8 { 2527 return if (v >= 1 and v <= 9) 10 else v; 2528 } 2529 }.f; 2530 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 2531 } 2532 2533 // composites ANSI art behind a foreground grid 2534 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, is_terminal: bool, root_focus: *Focus) !Grid { 2535 art.clearGrid(); 2536 try art.build(allocator, .{ 2537 .min_size = .{ .width = null, .height = null }, 2538 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 2539 }, root_focus); 2540 2541 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 2542 errdefer out.deinit(); 2543 2544 if (art.getGrid()) |art_grid| { 2545 const anchor_x = switch (anchor) { 2546 .top_left => 0, 2547 .top_right => foreground.size.width -| art_grid.size.width, 2548 }; 2549 for (0..art_grid.size.height) |y| { 2550 for (0..art_grid.size.width) |x| { 2551 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 2552 if (src.rune == null) continue; 2553 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 2554 const dst = &out.cells.items[idx]; 2555 // composite the dimmed art behind every cell so it shows 2556 // through the whole UI: a blank cell becomes the art, while a 2557 // cell with a glyph keeps the glyph but takes the dimmed art as 2558 // its background (replacing whatever background it had, which 2559 // would otherwise obscure the art). 2560 if (cellIsBlank(dst.*)) { 2561 dst.* = src; 2562 dst.style.fg = sgrSafe(dimColor(dst.style.fg)); 2563 dst.style.bg = sgrSafe(dimColor(dst.style.bg)); 2564 } else { 2565 const background_maybe = sgrSafe(dimColor(src.style.bg orelse src.style.fg)); 2566 dst.style.bg = background_maybe; 2567 // change the color of text overlaying ANSI art to ensure 2568 // it is readable. don't do this in the web UI, since we 2569 // have direct control of the theme there (also, inner 2570 // scroll panes allow text to move without a re-render 2571 // by the TUI, which would break this). also don't do this 2572 // if the text is explicitly styled. 2573 if (is_terminal and dst.style.fg == null) { 2574 if (background_maybe) |background| { 2575 // use near-black and near-white, which is easier on the eyes 2576 // while retaining high contrast 2577 const luminance = (@as(u32, background.r) * 299 + 2578 @as(u32, background.g) * 587 + 2579 @as(u32, background.b) * 114) / 1000; 2580 dst.style.fg = if (luminance >= 128) 2581 .{ .r = 16, .g = 16, .b = 16 } 2582 else 2583 .{ .r = 240, .g = 240, .b = 240 }; 2584 } 2585 } 2586 } 2587 } 2588 } 2589 } 2590 return out; 2591 } 2592 }; 2593