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