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