╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
192 // returned value slices into `s`. 193 pub const CommitsRef = struct { ref_or_oid: ?RefOrOid, value: []const u8 }; 194 pub fn repoCommitsRef(s: []const u8) CommitsRef { 195 const bare = CommitsRef{ .ref_or_oid = null, .value = "" }; 196 if (s.len == 0) return bare; 197 var segments = std.mem.splitScalar(u8, s, '/'); 198 if (identityElided(s)) { 199 _ = segments.next(); // the empty segment before the tail 200 } else { 201 _ = segments.next(); // owner 202 _ = segments.next(); // name 203 } 204 if (!std.mem.eql(u8, segments.next() orelse "", commits_seg)) return bare; 205 const kind = RefOrOid.fromSeg(segments.next() orelse "") orelse return bare; 206 const value = segments.rest(); 207 if (value.len == 0) return bare; 208 return .{ .ref_or_oid = kind, .value = value }; 209 } 210 211 // build a `.repo_commits` route for "owner/name" (identity), walking from 212 // `ref_or_oid`/`value` (a null ref_or_oid yields the bare default-branch 213 // route). always carries the `commits` marker so the bare route 214 // ("owner/name/commits") doesn't collide with the files root. 215 pub fn repoCommitsRoute(identity: []const u8, ref_or_oid: ?RefOrOid, value: []const u8, after: usize) ?RoutablePage { 216 var buf: [repo_route_max_len]u8 = undefined; 217 const s = if (ref_or_oid) |kind| 218 std.fmt.bufPrint(&buf, "{s}/" ++ commits_seg ++ "/{s}/{s}", .{ identity, @tagName(kind), value }) catch return null 219 else 220 std.fmt.bufPrint(&buf, "{s}/" ++ commits_seg, .{identity}) catch return null; 221 return .{ .repo_commits = .{ .name = Array(repo_route_max_len).from(s) orelse return null, .after = after } }; 222 } 223 224 // build a `.repo_refs` route for "owner/name" (identity) paginating `kind`'s 225 // column to `after` (0 = the first window, the other column always at 0). 226 pub fn repoRefsRoute(identity: []const u8, kind: RefKind, after: usize) ?RoutablePage { 227 return .{ .repo_refs = .{ .name = Array(repo_route_max_len).from(identity) orelse return null, .kind = kind, .after = after } }; 228 } 229 230 // build a `.repo_issues` route for "owner/name" (identity) filtered to the 231 // url-encoded `tag` ("" = unfiltered) and rooted at the issue with hex 232 // event id `selected` ("" = the first window). 233 pub fn repoIssuesRoute(identity: []const u8, tag: []const u8, selected: []const u8) ?RoutablePage { 234 return .{ .repo_issues = .{ 235 .name = Array(repo_route_max_len).from(identity) orelse return null, 236 .tag = Array(issue_tag_route_max_len).from(tag) orelse return null, 237 .selected = Array(evt.event_id_size * 2).from(selected) orelse return null, 238 } }; 239 } 240 241 // an inline, owned array of data. keeping it in the route (rather than a 242 // borrowed slice) makes RoutablePage a plain value: it can be copied, stored 243 // in history, and serialized without any arena tracking. 244 pub fn Array(comptime max_len: usize) type { 245 return struct { 246 bytes: [max_len]u8 = undefined, 247 len: u16 = 0, 248 249 pub fn from(s: []const u8) ?Array(max_len) { 250 if (s.len > max_len) return null; 251 var name = Array(max_len){ .len = @intCast(s.len) }; 252 @memcpy(name.bytes[0..s.len], s); 253 return name; 254 } 255 256 pub fn slice(self: *const Array(max_len)) []const u8 { 257 return self.bytes[0..self.len]; 258 } 259 }; 260 } 261 262 pub fn urlAlloc(self: RoutablePage, arena: *std.heap.ArenaAllocator) ![]const u8 { 263 return switch (self) { 264 .home_users => |after| if (after == 0) @as([]const u8, "/users") else try std.fmt.allocPrint(arena.allocator(), "/users?after={d}", .{after}), 265 .home_repos => |after| if (after == 0) @as([]const u8, "/repos") else try std.fmt.allocPrint(arena.allocator(), "/repos?after={d}", .{after}), 266 .home_settings => "/settings", 267 .home_auth => "/auth", 268 .user_repos => |u| if (u.after == 0) 269 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/repos", .{u.name.slice()}) 270 else 271 try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/repos?after={d}", .{ u.name.slice(), u.after }), 272 .user_settings => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/settings", .{name.slice()}), 273 .user_auth => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/auth", .{name.slice()}), 274 .repo_files => |f| blk: { 275 const path = try repoUrlPath(arena, f.name.slice()); 276 break :blk if (f.after == 0) path else try std.fmt.allocPrint(arena.allocator(), "{s}?after={d}", .{ path, f.after }); 277 }, 278 .repo_commits => |c| blk: { 279 const path = try repoUrlPath(arena, c.name.slice()); 280 break :blk if (c.after == 0) path else try std.fmt.allocPrint(arena.allocator(), "{s}?after={d}", .{ path, c.after }); 281 }, 282 .repo_refs => |r| blk: { 283 const prefix = try repoUrlPrefix(arena, r.name.slice()); 284 break :blk if (r.after == 0) 285 try std.fmt.allocPrint(arena.allocator(), "{s}/refs", .{prefix}) 286 else 287 try std.fmt.allocPrint(arena.allocator(), "{s}/refs?kind={s}&after={d}", .{ prefix, @tagName(r.kind), r.after }); 288 }, 289 .repo_issues => |i| blk: { 290 const prefix = try repoUrlPrefix(arena, i.name.slice()); 291 break :blk if (i.tag.len == 0) 292 (if (i.selected.len == 0) 293 try std.fmt.allocPrint(arena.allocator(), "{s}/issues", .{prefix}) 294 else 295 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/{s}", .{ prefix, i.selected.slice() })) 296 else if (i.selected.len == 0) 297 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/tag/{s}", .{ prefix, i.tag.slice() }) 298 else 299 try std.fmt.allocPrint(arena.allocator(), "{s}/issues/tag/{s}/{s}", .{ prefix, i.tag.slice(), i.selected.slice() }); 300 }, 301 .repo_settings => |name| try std.fmt.allocPrint(arena.allocator(), "{s}/settings", .{try repoUrlPrefix(arena, name.slice())}), 302 .repo_auth => |name| try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{try repoUrlPrefix(arena, name.slice())}), 303 }; 304 } 305 306 // the url path a files/commits route's stored string (identity + tail) maps 307 // to: "/repo/<string>", or the tail itself when the identity is elided 308 // ("/" at the bare root). 309 fn repoUrlPath(arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 310 if (identityElided(name)) return if (name.len == 0) "/" else name; 311 return std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{name}); 312 } 313 314 // the url prefix for a repo route's identity: "/repo/<identity>", or "" 315 // when the identity is elided. 316 fn repoUrlPrefix(arena: *std.heap.ArenaAllocator, identity: []const u8) ![]const u8 { 317 if (identity.len == 0) return ""; 318 return std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{identity}); 319 } 320 321 pub fn parent(self: RoutablePage) PageKind { 322 return switch (self) { 323 .home_users, .home_repos, .home_settings, .home_auth => .home, 324 .user_repos, .user_settings, .user_auth => .user, 325 .repo_files, .repo_commits, .repo_refs, .repo_issues, .repo_settings, .repo_auth => .repo, 326 }; 327 } 328 329 // parse a path plus its raw query string 330 pub fn fromUrl(path: []const u8, query: ?[]const u8) ?RoutablePage { 331 const after = uintParam(query, "after") orelse 0; 332 if (std.mem.eql(u8, path, "/")) return default; 333 if (std.mem.eql(u8, path, "/users")) return .{ .home_users = after }; 334 if (std.mem.eql(u8, path, "/repos")) return .{ .home_repos = after }; 335 if (std.mem.eql(u8, path, "/settings")) return .home_settings; 336 if (std.mem.eql(u8, path, "/auth")) return .home_auth; 337 // /user/<name>[/repos|/settings|/auth] 338 if (std.mem.startsWith(u8, path, user_segment)) { 339 const rest = path[user_segment.len..]; 340 var segments = std.mem.splitScalar(u8, rest, '/'); 341 const name = segments.next() orelse return null; 342 if (name.len == 0) return null; 343 const parsed = Array(evt.User.name_max_len).from(name) orelse return null; // name too long 344 if (segments.peek() != null) { 345 const sub = segments.rest(); 346 if (std.mem.eql(u8, sub, "repos")) return .{ .user_repos = .{ .name = parsed, .after = after } }; 347 if (std.mem.eql(u8, sub, "settings")) return .{ .user_settings = parsed }; 348 if (std.mem.eql(u8, sub, "auth")) return .{ .user_auth = parsed }; 349 return null; // unknown sub-path 350 } 351 return .{ .user_repos = .{ .name = parsed, .after = after } }; 352 } 353 // /repo/<username>/<reponame> (files root), then optionally /settings, 354 // /auth, or /files/<dir> for a directory in the files tab. the `repo` 355 // variant stores "username/reponame" (root) or 356 // "username/reponame/files/<dir>"; settings/auth store just the pair. 357 if (std.mem.startsWith(u8, path, repo_segment)) { 358 const rest = path[repo_segment.len..]; 359 var rest_segments = std.mem.splitScalar(u8, rest, '/'); 360 const owner = rest_segments.next() orelse return null; 361 const repo_name = rest_segments.next() orelse return null; 362 // reject an empty username or reponame 363 if (owner.len == 0 or repo_name.len == 0) return null; 364 const pair = rest[0 .. owner.len + 1 + repo_name.len]; // "username/reponame" 365 if (rest_segments.peek() != null) { 366 return repoSubRoute(pair, rest_segments.rest(), query); 367 } 368 return repoFilesRoute(pair, null, "", "", after); 369 } 370 return null; 371 } 372 373 // parse a local-mode url, which elides the "/repo/<owner>/<name>" prefix: 374 // "/" is the files root and the sub-paths follow directly. 375 pub fn fromUrlLocal(path: []const u8, query: ?[]const u8) ?RoutablePage { 376 if (std.mem.eql(u8, path, "/")) return repoFilesRoute("", null, "", "", uintParam(query, "after") orelse 0); 377 if (path.len < 2 or path[0] != '/') return null; 378 return repoSubRoute("", path[1..], query); 379 } 380 381 // parse the sub-path after a repo route's identity into a route whose 382 // stored string carries `pair` as its identity ("" for a local route). 383 fn repoSubRoute(pair: []const u8, sub: []const u8, query: ?[]const u8) ?RoutablePage { 384 const after = uintParam(query, "after") orelse 0; 385 if (std.mem.eql(u8, sub, "refs")) return .{ .repo_refs = .{ 386 .name = Array(repo_route_max_len).from(pair) orelse return null, 387 .kind = refsKind(query), 388 .after = after, 389 } }; 390 if (std.mem.eql(u8, sub, "issues") or std.mem.startsWith(u8, sub, "issues/")) { 391 // "issues[/tag/<tag>][/<issue event id>]" 392 var segments = std.mem.splitScalar(u8, sub, '/'); 393 _ = segments.next(); // "issues" 394 var tag_value: []const u8 = ""; 395 var id: []const u8 = ""; 396 if (segments.next()) |segment| { 397 if (std.mem.eql(u8, segment, "tag")) { 398 tag_value = segments.next() orelse return null; 399 if (tag_value.len == 0) return null; 400 id = segments.next() orelse ""; 401 } else { 402 if (segment.len == 0) return null; 403 id = segment; 404 } 405 } 406 if (segments.next() != null) return null; 407 return repoIssuesRoute(pair, tag_value, id); 408 } 409 if (std.mem.eql(u8, sub, "settings")) return .{ .repo_settings = Array(repo_route_max_len).from(pair) orelse return null }; 410 if (std.mem.eql(u8, sub, "auth")) return .{ .repo_auth = Array(repo_route_max_len).from(pair) orelse return null }; 411 if (std.mem.eql(u8, sub, files_seg) or std.mem.startsWith(u8, sub, files_seg ++ "/")) { 412 // "files[/<refkind>/<refvalue>[/<dir>]]" (bare = default-branch root) 413 var segments = std.mem.splitScalar(u8, sub, '/'); 414 _ = segments.next(); // "files" 415 const kind_segment = segments.next() orelse return repoFilesRoute(pair, null, "", "", after); 416 const kind = RefOrOid.fromSeg(kind_segment) orelse return null; 417 const value = segments.next() orelse return null; 418 if (value.len == 0) return null; 419 return repoFilesRoute(pair, kind, value, segments.rest(), after); 420 } 421 if (std.mem.eql(u8, sub, commits_seg) or std.mem.startsWith(u8, sub, commits_seg ++ "/")) { 422 // "commits[/<refkind>/<refvalue>]" (bare = default branch) 423 var segments = std.mem.splitScalar(u8, sub, '/'); 424 _ = segments.next(); // "commits" 425 const kind_segment = segments.next() orelse return repoCommitsRoute(pair, null, "", after); 426 const kind = RefOrOid.fromSeg(kind_segment) orelse return null; 427 const value = segments.rest(); 428 if (value.len == 0) return null; 429 return repoCommitsRoute(pair, kind, value, after); 430 } 431 return null; // unknown sub-path 432 } 433 434 // the refs column a "kind=" query param names; absent or unrecognized reads 435 // as the branches column. 436 fn refsKind(query: ?[]const u8) RefKind { 437 const qs = query orelse return .branch; 438 var it = std.mem.splitScalar(u8, qs, '&'); 439 while (it.next()) |pair| { 440 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 441 if (std.mem.eql(u8, pair[0..eq], "kind") and std.mem.eql(u8, pair[eq + 1 ..], "tag")) return .tag; 442 } 443 return .branch; 444 } 445 446 // read a "key=<uint>" value from a raw "a=1&b=2" query string. 447 fn uintParam(query: ?[]const u8, key: []const u8) ?usize { 448 const qs = query orelse return null; 449 var it = std.mem.splitScalar(u8, qs, '&'); 450 while (it.next()) |pair| { 451 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 452 if (std.mem.eql(u8, pair[0..eq], key)) 453 return std.fmt.parseInt(usize, pair[eq + 1 ..], 10) catch null; 454 } 455 return null; 456 } 457 458 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 459 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 460 return switch (a) { 461 .home_users => |a_after| a_after == b.home_users, 462 .home_repos => |a_after| a_after == b.home_repos, 463 .user_repos => |a_u| std.mem.eql(u8, a_u.name.slice(), b.user_repos.name.slice()) and a_u.after == b.user_repos.after, 464 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 465 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 466 .repo_files => |a_f| std.mem.eql(u8, a_f.name.slice(), b.repo_files.name.slice()) and a_f.after == b.repo_files.after, 467 .repo_commits => |a_c| std.mem.eql(u8, a_c.name.slice(), b.repo_commits.name.slice()) and a_c.after == b.repo_commits.after, 468 .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 a_r.after == b.repo_refs.after, 469 .repo_issues => |a_i| std.mem.eql(u8, a_i.name.slice(), b.repo_issues.name.slice()) and 470 std.mem.eql(u8, a_i.tag.slice(), b.repo_issues.tag.slice()) and 471 std.mem.eql(u8, a_i.selected.slice(), b.repo_issues.selected.slice()), 472 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 473 .repo_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_auth.slice()), 474 else => true, 475 }; 476 } 477 478 // true when following a link from `b` to `a` (both repo routes) should reload 479 // rather than stay in page 480 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 481 if (a.parent() != .repo or b.parent() != .repo) return false; 482 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 483 a.repo_refs.after == 0 and b.repo_refs.after == 0) 484 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 485 return !a.eql(b); 486 } 487 488 // true when `a` and `b` are the same user paginated to a different repos 489 // window. switching between a user's tabs is in-page (header-handled), so 490 // only a changed `after` on the repos list navigates. 491 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 492 return switch (a) { 493 .user_repos => |aa| switch (b) { 494 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.after != bb.after, 495 else => false, 496 }, 497 else => false, 498 }; 499 } 500 501 // true when `a` and `b` are the same home list tab paginated to a different 502 // window. switching between the users/repos tabs is in-page (the home page 503 // holds both lists), so only a changed `after` on the same tab navigates. 504 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 505 return switch (a) { 506 .home_users => |aa| switch (b) { 507 .home_users => |bb| aa != bb, 508 else => false, 509 }, 510 .home_repos => |aa| switch (b) { 511 .home_repos => |bb| aa != bb, 512 else => false, 513 }, 514 else => false, 515 }; 516 } 517 518 // serialize as { "kind": <tag>, "name"?: <name>, "after"?: <n> }. the default 519 // union(enum) codec doesn't round-trip here: Stringify emits a void 520 // variant as a bare tag string, but the parser expects an object — so the 521 // server->wasm Snapshot JSON would fail to parse. 522 pub fn jsonStringify(self: RoutablePage, jw: anytype) !void { 523 try jw.beginObject(); 524 try jw.objectField("kind"); 525 try jw.write(@tagName(self)); 526 switch (self) { 527 .user_repos => |u| { 528 try jw.objectField("name"); 529 try jw.write(u.name.slice()); 530 try jw.objectField("after"); 531 try jw.write(u.after); 532 }, 533 .user_settings, .user_auth => |name| { 534 try jw.objectField("name"); 535 try jw.write(name.slice()); 536 }, 537 .repo_settings, .repo_auth => |name| { 538 try jw.objectField("name"); 539 try jw.write(name.slice()); 540 }, 541 .repo_issues => |i| { 542 try jw.objectField("name"); 543 try jw.write(i.name.slice()); 544 try jw.objectField("tag"); 545 try jw.write(i.tag.slice()); 546 try jw.objectField("selected"); 547 try jw.write(i.selected.slice()); 548 }, 549 .repo_files => |f| { 550 try jw.objectField("name"); 551 try jw.write(f.name.slice()); 552 try jw.objectField("after"); 553 try jw.write(f.after); 554 }, 555 .repo_commits => |c| { 556 try jw.objectField("name"); 557 try jw.write(c.name.slice()); 558 try jw.objectField("after"); 559 try jw.write(c.after); 560 }, 561 .repo_refs => |r| { 562 try jw.objectField("name"); 563 try jw.write(r.name.slice()); 564 // "kind" already holds the union tag, so the paginated column 565 // travels under a distinct field. 566 try jw.objectField("ref_kind"); 567 try jw.write(@tagName(r.kind)); 568 try jw.objectField("after"); 569 try jw.write(r.after); 570 }, 571 .home_users, .home_repos => |after| { 572 try jw.objectField("after"); 573 try jw.write(after); 574 }, 575 else => {}, 576 } 577 try jw.endObject(); 578 } 579 580 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !RoutablePage { 581 const Helper = struct { kind: std.meta.Tag(RoutablePage), name: ?[]const u8 = null, after: usize = 0, ref_kind: ?[]const u8 = null, tag: ?[]const u8 = null, selected: ?[]const u8 = null }; 582 const helper = try std.json.innerParse(Helper, allocator, source, options); 583 const parseName = struct { 584 // errors must stay within std.json's ParseError set; ValueTooLong 585 // is its member for an over-long field. 586 fn f(comptime max_len: usize, maybe: ?[]const u8) !Array(max_len) { 587 return Array(max_len).from(maybe orelse return error.MissingField) orelse error.ValueTooLong; 588 } 589 }.f; 590 return switch (helper.kind) { 591 .home_users => .{ .home_users = helper.after }, 592 .home_repos => .{ .home_repos = helper.after }, 593 .home_settings => .home_settings, 594 .home_auth => .home_auth, 595 .user_repos => .{ .user_repos = .{ .name = try parseName(evt.User.name_max_len, helper.name), .after = helper.after } }, 596 .user_settings => .{ .user_settings = try parseName(evt.User.name_max_len, helper.name) }, 597 .user_auth => .{ .user_auth = try parseName(evt.User.name_max_len, helper.name) }, 598 .repo_files => .{ .repo_files = .{ .name = try parseName(repo_route_max_len, helper.name), .after = helper.after } }, 599 .repo_commits => .{ .repo_commits = .{ .name = try parseName(repo_route_max_len, helper.name), .after = helper.after } }, 600 .repo_refs => .{ .repo_refs = .{ 601 .name = try parseName(repo_route_max_len, helper.name), 602 .kind = if (helper.ref_kind) |k| (if (std.mem.eql(u8, k, "tag")) .tag else .branch) else .branch, 603 .after = helper.after, 604 } }, 605 .repo_issues => .{ .repo_issues = .{ 606 .name = try parseName(repo_route_max_len, helper.name), 607 .tag = Array(issue_tag_route_max_len).from(helper.tag orelse "") orelse return error.ValueTooLong, 608 .selected = Array(evt.event_id_size * 2).from(helper.selected orelse "") orelse return error.ValueTooLong, 609 } }, 610 .repo_settings => .{ .repo_settings = try parseName(repo_route_max_len, helper.name) }, 611 .repo_auth => .{ .repo_auth = try parseName(repo_route_max_len, helper.name) }, 612 }; 613 } 614 }; 615 616 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 617 fn isUnreserved(c: u8) bool { 618 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 619 } 620 621 // percent-encode a ref name for use as a single url path segment. 622 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 623 var out: std.Io.Writer.Allocating = .init(aa); 624 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 625 return out.written(); 626 } 627 628 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 629 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 630 return struct { 631 pub const hex_len = hash.hexLen(repo_opts.hash); 632 633 // the concrete ref/oid (a null request resolves to the default branch) 634 ref_or_oid: RoutablePage.RefOrOid, 635 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 636 // the route layer — which splits on '/' — stores them encoded). duped 637 // into `aa`. 638 value: []const u8, 639 // the commit oid it points at 640 oid: [hex_len]u8, 641 642 const Self = @This(); 643 644 // resolve a requested ref/oid (null = the repo's default branch) to a 645 // concrete ref/oid plus the commit oid it points at. `requested_value` is 646 // the url-encoded form (as it appears in the route). null when it doesn't 647 // resolve (an unknown branch/tag, or a malformed/unknown oid). 648 pub fn init( 649 repo: *rp.Repo(repo_kind, repo_opts), 650 io: std.Io, 651 aa: std.mem.Allocator, 652 requested_ref_or_oid: ?RoutablePage.RefOrOid, 653 requested_value: []const u8, 654 ) !?Self { 655 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 656 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 657 var value: []const u8 = if (requested_ref_or_oid == null) 658 requested_value 659 else 660 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 661 // no ref named: fall back to HEAD's branch (or its oid when detached). 662 if (requested_ref_or_oid == null) { 663 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 664 if (repo.head(io, &head_buf)) |head| switch (head) { 665 .ref => |r| { 666 ref_or_oid = .branch; 667 value = r.name; 668 }, 669 .oid => |o| { 670 ref_or_oid = .object; 671 value = o; 672 }, 673 } else |_| {} 674 } 675 676 var oid: [hex_len]u8 = undefined; 677 switch (ref_or_oid) { 678 .object => { 679 if (value.len != hex_len) return null; 680 @memcpy(&oid, value); 681 }, 682 .branch, .tag => { 683 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 684 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 685 }, 686 } 687 // store url-encoded so the route layer can hold the value verbatim. 688 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 689 } 690 }; 691 } 692 693 // where a repo page reads its on-disk repo from 694 pub const RepoSource = struct { 695 path: []const u8, 696 repo_kind: rp.RepoKind, 697 }; 698 699 // per-connection mutable state. each SSH session / web session / local TUI 700 // run gets its own. 701 pub const Session = struct { 702 data: Data = .{}, 703 // session-lifetime allocations: login/user_id, persisted prefs, queued 704 // actions. lives as long as the connection. 705 arena: *std.heap.ArenaAllocator, 706 // current page's allocations: page data and the page-scoped strings widgets 707 // build (form actions, links). owned by Nav, swapped on each navigation, so 708 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 709 // where a render is one-shot, this points at the same arena as `arena`. 710 page_arena: *std.heap.ArenaAllocator, 711 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 712 // filesystem io and the path to <server>/repos, for opening on-disk repos 713 // during page construction. both null on wasm, which has no filesystem and 714 // rebuilds pages from the serialized snapshot rather than from disk. 715 io: ?std.Io = null, 716 repos_dir: ?[]const u8 = null, 717 // the single on-disk repo this session views, when running in local mode 718 // (haxy invoked with no arguments inside a repo). null on the server paths, 719 // which resolve repos from the admin db instead. 720 local: ?RepoSource = null, 721 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 722 // focus id -> the live TextInput, refreshed each frame by the views that own 723 // inputs. web/wasm form handling looks widgets up here by focus id. 724 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 725 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 726 refresh_requested: bool = false, // set by input (ctrl+r) 727 // a requested forward navigation. set this (via navigate) to move to a new 728 // page; Nav.sync builds it and then copies it into current_page, clearing 729 // this back to null. setting current_page directly only updates the url and 730 // does not navigate. 731 next_page: ?RoutablePage = null, 732 is_terminal: bool = false, // true on remote SSH and local TUI 733 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 734 // url. null on the web itself (no footer there). 735 web_port: ?u16 = null, 736 quit_requested: bool = false, 737 738 const Self = @This(); 739 740 // serializable data sent down to web client 741 pub const Data = struct { 742 user_id: ?[]const u8 = null, 743 // a transient outcome to surface from the last /login POST attempt 744 login_failure: ?Home.Auth.Login.Failure = null, 745 current_page: RoutablePage = .default, 746 // whether to render the ANSI art backdrop 747 enable_ansi: bool = true, 748 // true when this session views a single local repo. unlike `local` 749 // (the host-side filesystem source) this travels in the snapshot, so 750 // the wasm side also parses elided link urls and hides the multi-user 751 // chrome. 752 is_local: bool = false, 753 }; 754 755 // a user-initiated state change. widgets enqueue these on the session during 756 // input instead of mutating state or touching the DB themselves; the host 757 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 758 // side effects out of the widget tree and gives every render path one place to 759 // turn a UI action into a state change + event. 760 pub const Action = union(enum) { 761 toggle_ansi, 762 }; 763 764 pub fn init( 765 arena: *std.heap.ArenaAllocator, 766 repo: *rp.Repo(.xit, evt.admin_repo_opts), 767 data: Data, 768 ) !Self { 769 var session = Self{ 770 .data = data, 771 .arena = arena, 772 // until a host swaps in a page-scoped arena (Nav does this), page 773 // allocations land in the session arena. on the web path that's the 774 // intended behavior, since the whole arena is per-request. 775 .page_arena = arena, 776 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 777 }; 778 try session.loadUserPrefs(); 779 return session; 780 } 781 782 // load the logged-in user's persisted preferences from the db 783 pub fn loadUserPrefs(self: *Self) !void { 784 const user_id = self.data.user_id orelse return; 785 const moment = self.haxy_moment orelse return; 786 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 787 self.data.enable_ansi = user.enable_ansi; 788 } 789 } 790 791 // queue an action for the host to drain this frame. 792 pub fn push(self: *Self, action: Action) !void { 793 try self.pending.append(self.arena.allocator(), action); 794 } 795 796 // apply a single action's in-memory effect only (no persistence). 797 fn apply(self: *Self, action: Action) void { 798 switch (action) { 799 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 800 } 801 } 802 803 // drain the session's queued actions by applying them to the session. 804 // used on the wasm path, which has no repo to persist to. 805 pub fn applyPending(self: *Self) void { 806 for (self.pending.items) |action| self.apply(action); 807 self.pending.clearRetainingCapacity(); 808 } 809 810 // drain the session's queued actions by applying them to the session and 811 // writing them to the db 812 pub fn applyAndWritePending( 813 self: *Self, 814 io: std.Io, 815 allocator: std.mem.Allocator, 816 repo: *rp.Repo(.xit, evt.admin_repo_opts), 817 ) !void { 818 defer self.pending.clearRetainingCapacity(); 819 for (self.pending.items) |action| { 820 self.apply(action); 821 switch (action) { 822 .toggle_ansi => if (self.data.user_id) |user_id| { 823 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 824 }, 825 } 826 } 827 } 828 829 // reload the moment from the admin repo 830 pub fn reloadMoment(self: *Self, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 831 self.haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo); 832 } 833 834 // request a forward navigation to `route`; the host consumes next_page 835 // (Nav.sync on the terminal, the wasm tick on the web). 836 pub fn navigate(self: *Session, route: RoutablePage) !void { 837 self.next_page = route; 838 } 839 }; 840 841 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 842 var nav = try Nav.init(allocator, session); 843 defer nav.deinit(allocator); 844 845 var terminal = try term.Terminal.init(io, allocator); 846 defer terminal.deinit(io); 847 848 // set term as active so it will be properly cooked 849 // when a panic/segfault happens 850 term.setActive(&terminal); 851 defer term.setActive(null); 852 853 var last_size = layout.Size{ .width = 0, .height = 0 }; 854 var last_grid = try Grid.init(allocator, last_size); 855 defer last_grid.deinit(); 856 857 while (!terminal.shouldQuit()) { 858 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 859 860 // process any inputs. 861 // 862 // if the grid didn't change, then first do a blocking 863 // read, so the thread will sleep until further input. 864 // after that, all remaining reads are non-blocking so 865 // we can process the rest of the queued inputs. 866 // 867 // if the grid *did* change, then only do non-blocking 868 // reads. we do not want to sleep the thread because 869 // there may be an animation that requires more looping. 870 var blocking = !grid_changed; 871 while (try terminal.readKey(io, blocking)) |key| { 872 blocking = false; 873 try inputKey(allocator, &nav.root, key, session); 874 } 875 876 // local run has no repo to persist to, so just apply in-memory 877 session.applyPending(); 878 879 // pick up data written by other handles so the next navigation 880 // builds its page from a current moment (local mode has no admin repo) 881 if (repo_maybe) |repo| try session.reloadMoment(repo); 882 883 // reconcile navigation: forward to a new page, or back on escape. 884 try nav.sync(allocator, session); 885 886 // the quit button (on the quit tab) asks the host to tear down. 887 if (session.quit_requested) terminal.requestQuit(); 888 889 try nav.root.build(allocator, .{ 890 .min_size = .{ .width = null, .height = null }, 891 .max_size = .{ .width = last_size.width, .height = last_size.height }, 892 }, nav.root.getFocus()); 893 } 894 } 895 896 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 897 switch (key) { 898 // request a navigation pop; the host's Nav.sync goes back a page, or 899 // quits when there's no history left. 900 .escape => session.nav_back = true, 901 .ctrl => |letter| switch (letter) { 902 'r' => session.refresh_requested = true, 903 else => try root.input(allocator, key, root.getFocus()), 904 }, 905 .enter => { 906 const root_focus = root.getFocus(); 907 if (root_focus.grandchild_id) |gid| { 908 // follow a cross-page link 909 if (crossPageLink(root_focus, gid, session.data)) |route| { 910 return session.navigate(route); 911 } 912 } 913 try root.input(allocator, key, root_focus); 914 }, 915 .mouse => |mouse| { 916 if (mouse.action == .press and mouse.action.press == .left) { 917 const root_focus = root.getFocus(); 918 var clicked: ?usize = null; 919 var iter = root_focus.children.iterator(); 920 while (iter.next()) |entry| { 921 const child = entry.value_ptr.*; 922 if (!child.focus.focusable) continue; 923 const r = child.rect; 924 if (mouse.x >= r.x and mouse.y >= r.y and 925 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 926 { 927 clicked = entry.key_ptr.*; 928 break; 929 } 930 } 931 if (clicked) |focus_id| { 932 // follow a cross-page link 933 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 934 return session.navigate(route); 935 } 936 root_focus.setFocus(focus_id); 937 } 938 // forward the press into the widget tree so buttons (and any 939 // future click-aware widgets) can react. widgets that don't 940 // care about presses ignore it. 941 try root.input(allocator, key, root.getFocus()); 942 } else { 943 try root.input(allocator, key, root.getFocus()); 944 } 945 }, 946 else => try root.input(allocator, key, root.getFocus()), 947 } 948 } 949 950 // if the focus target at focus_id is an `a:` link that should navigate (a 951 // different parent page, or a different files directory within the repo page), 952 // return its route; otherwise null. lets a host turn a click / enter on such a 953 // link into a navigation rather than a focus change. 954 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 955 const current = data.current_page; 956 const child = root_focus.children.get(focus_id) orelse return null; 957 const custom = switch (child.focus.kind) { 958 .custom => |c| c, 959 else => return null, 960 }; 961 const a_prefix = "a:"; 962 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 963 const url = custom[a_prefix.len..]; 964 const q = std.mem.indexOfScalar(u8, url, '?'); 965 const path = if (q) |i| url[0..i] else url; 966 const query = if (q) |i| url[i + 1 ..] else null; 967 // local sessions build (and parse) links with the repo identity elided 968 const route = (if (data.is_local) RoutablePage.fromUrlLocal(path, query) else RoutablePage.fromUrl(path, query)) orelse return null; 969 // a link to a different parent page always navigates; within a page, a 970 // files-directory / commits-page / list-window change navigates while tab 971 // links stay in-page (header-handled). 972 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 973 return null; 974 } 975 976 // native-TUI navigation 977 pub const Nav = struct { 978 root: Widget, 979 route: RoutablePage, 980 // backs the current page (its Page data and the page-scoped strings its 981 // widgets build). owned here, swapped on each navigation. session.page_arena 982 // tracks whichever of these is current so widgets allocate into it. 983 arena: *std.heap.ArenaAllocator, 984 history: std.ArrayList(Entry), 985 986 // each retained page keeps its own arena, freed when the page leaves the 987 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 988 // long-lived session from accumulating every page it ever visited. 989 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 990 991 // cap on retained back-history so the chain can't grow memory without bound 992 const max_history: usize = 16; 993 994 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 995 const arena = try allocator.create(std.heap.ArenaAllocator); 996 arena.* = std.heap.ArenaAllocator.init(allocator); 997 errdefer { 998 arena.deinit(); 999 allocator.destroy(arena); 1000 } 1001 1002 session.page_arena = arena; 1003 const route = session.data.current_page; 1004 1005 const page = try arena.allocator().create(Page); 1006 page.* = try Page.init(arena, session, route); 1007 return .{ 1008 .root = try initRoot(allocator, page, session), 1009 .route = route, 1010 .arena = arena, 1011 .history = .empty, 1012 }; 1013 } 1014 1015 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 1016 self.root.deinit(allocator); 1017 freeArena(allocator, self.arena); 1018 for (self.history.items) |*entry| { 1019 entry.root.deinit(allocator); 1020 freeArena(allocator, entry.arena); 1021 } 1022 self.history.deinit(allocator); 1023 } 1024 1025 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 1026 arena.deinit(); 1027 allocator.destroy(arena); 1028 } 1029 1030 // reconcile the displayed root with the session's navigation state. a 1031 // forward nav (current_page moved to a different parent page) pushes the 1032 // current root and builds the new page in a fresh arena; a back request 1033 // frees the current page and restores the previous one. when escape is 1034 // pressed with no history left we switch to the quit tab instead of quitting. 1035 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 1036 // refresh: rebuild the current page in place from a current moment 1037 if (session.refresh_requested) { 1038 session.refresh_requested = false; 1039 if (session.haxy_moment != null or session.local != null) { 1040 const arena = try allocator.create(std.heap.ArenaAllocator); 1041 arena.* = std.heap.ArenaAllocator.init(allocator); 1042 errdefer freeArena(allocator, arena); 1043 1044 session.page_arena = arena; 1045 1046 const page = try arena.allocator().create(Page); 1047 page.* = try Page.init(arena, session, self.route); 1048 const new_root = try initRoot(allocator, page, session); 1049 1050 self.root.deinit(allocator); 1051 freeArena(allocator, self.arena); 1052 self.root = new_root; 1053 self.arena = arena; 1054 } 1055 return; 1056 } 1057 1058 if (session.nav_back) { 1059 session.nav_back = false; 1060 if (self.history.pop()) |entry| { 1061 self.root.deinit(allocator); 1062 freeArena(allocator, self.arena); 1063 self.root = entry.root; 1064 self.route = entry.route; 1065 self.arena = entry.arena; 1066 session.page_arena = entry.arena; 1067 session.data.current_page = entry.route; 1068 return; 1069 } 1070 // nothing to go back to; switch to the quit confirmation 1071 const root_focus = self.root.getFocus(); 1072 var iter = root_focus.children.iterator(); 1073 while (iter.next()) |entry| { 1074 switch (entry.value_ptr.focus.kind) { 1075 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 1076 root_focus.setFocus(entry.key_ptr.*); 1077 // a Stack only builds its selected child, so the quit 1078 // button isn't in the focus tree until a build runs with 1079 // the quit tab selected. build once, then send a 1080 // synthetic arrow_down to drop focus from the tab onto 1081 // the button so it's ready to confirm. 1082 try self.root.build(allocator, .{ 1083 .min_size = .{ .width = null, .height = 40 }, 1084 .max_size = .{ .width = 80, .height = null }, 1085 }, root_focus); 1086 try self.root.input(allocator, .arrow_down, root_focus); 1087 break; 1088 }, 1089 else => {}, 1090 } 1091 } 1092 return; 1093 } 1094 1095 // forward navigation: navigate() set next_page to the page to move to (a 1096 // cross-page link or tab change crossing pages) 1097 if (session.next_page) |route| { 1098 session.next_page = null; 1099 if (session.haxy_moment == null and session.local == null) return; 1100 // the page we navigated to becomes the current page 1101 session.data.current_page = route; 1102 1103 const arena = try allocator.create(std.heap.ArenaAllocator); 1104 arena.* = std.heap.ArenaAllocator.init(allocator); 1105 errdefer freeArena(allocator, arena); 1106 1107 session.page_arena = arena; 1108 1109 const page = try arena.allocator().create(Page); 1110 page.* = try Page.init(arena, session, route); 1111 const new_root = try initRoot(allocator, page, session); 1112 1113 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 1114 // drop the oldest entry (freeing its widget tree and arena) once over cap 1115 if (self.history.items.len > max_history) { 1116 var oldest = self.history.orderedRemove(0); 1117 oldest.root.deinit(allocator); 1118 freeArena(allocator, oldest.arena); 1119 } 1120 self.root = new_root; 1121 self.route = route; 1122 self.arena = arena; 1123 } 1124 } 1125 }; 1126 1127 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 1128 const page_widget: Widget = switch (page.*) { 1129 .home => |*p| .{ .home = try .init(allocator, p, session) }, 1130 .user => |*p| .{ .user = try .init(allocator, p, session) }, 1131 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 1132 }; 1133 1134 const demon_art = @embedFile("embed/demon.ans"); 1135 1136 // on the TUI/SSH, the page sits above a one-row footer showing the url 1137 var root = if (session.is_terminal) blk: { 1138 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 1139 errdefer box.deinit(allocator); 1140 const bg_id = bg_blk: { 1141 var background = try AnsiBackground.init(allocator, page_widget, demon_art, session); 1142 errdefer background.deinit(allocator); 1143 const id = background.getFocus().id; 1144 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 1145 break :bg_blk id; 1146 }; 1147 { 1148 var footer = try Footer.init(allocator, session); 1149 errdefer footer.deinit(allocator); 1150 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 1151 } 1152 box.getFocus().child_id = bg_id; 1153 break :blk Widget{ .box = box }; 1154 } else Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 1155 errdefer root.deinit(allocator); 1156 1157 // input-owning views build their TextInputs in init — so reset the 1158 // focus-id -> *TextInput map here 1159 session.text_inputs.clearRetainingCapacity(); 1160 1161 try root.build(allocator, .{ 1162 .min_size = .{ .width = null, .height = 40 }, 1163 .max_size = .{ .width = 100, .height = null }, 1164 }, root.getFocus()); 1165 1166 return root; 1167 } 1168 1169 pub const Widget = union(enum) { 1170 text: wgt.Text(Widget), 1171 box: wgt.Box(Widget), 1172 text_box: wgt.TextBox(Widget), 1173 text_input: wgt.TextInput(Widget), 1174 scroll: wgt.Scroll(Widget), 1175 stack: wgt.Stack(Widget), 1176 flow_box: FlowBox, 1177 flow_box_scroll: FlowBox.Scroll, 1178 tag_flow: TagFlow, 1179 spacer: Spacer, 1180 center: Center, 1181 background: AnsiBackground, 1182 home: Home.View, 1183 user: User.View, 1184 repo: Repo.View, 1185 quit: Quit.View, 1186 title: Title.View, 1187 sub_title: SubTitle.View, 1188 home_header: Home.Header.View, 1189 user_header: User.Header.View, 1190 repo_header: Repo.Header.View, 1191 repo_sub_header: Repo.SubHeader.View, 1192 repo_files: Repo.Files.View, 1193 repo_commits: Repo.Commits.View, 1194 repo_refs: Repo.Refs.View, 1195 repo_issues: Repo.Issues.View, 1196 home_users: Home.Users.View, 1197 home_repos: Home.Repos.View, 1198 auth_tab: Home.Header.AuthTab.View, 1199 home_settings: Home.Settings.View, 1200 home_auth: Home.Auth.View, 1201 footer: Footer, 1202 1203 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 1204 switch (self.*) { 1205 inline else => |*case| case.deinit(allocator), 1206 } 1207 } 1208 1209 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 1210 switch (self.*) { 1211 inline else => |*case| try case.build(allocator, constraint, root_focus), 1212 } 1213 } 1214 1215 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) anyerror!void { 1216 switch (self.*) { 1217 inline else => |*case| try case.input(allocator, key, root_focus), 1218 } 1219 } 1220 1221 pub fn clearGrid(self: *Widget) void { 1222 switch (self.*) { 1223 inline else => |*case| case.clearGrid(), 1224 } 1225 } 1226 1227 pub fn getGrid(self: Widget) ?Grid { 1228 switch (self) { 1229 inline else => |*case| return case.getGrid(), 1230 } 1231 } 1232 1233 pub fn getFocus(self: *Widget) *Focus { 1234 switch (self.*) { 1235 inline else => |*case| return case.getFocus(), 1236 } 1237 } 1238 }; 1239 1240 // move the focused row in `box` by `delta`, clamped to the ends, scrolling 1241 // `scroll` to keep it visible. 1242 pub fn moveRowFocus(box: *wgt.Box(Widget), scroll: *wgt.Scroll(Widget), root_focus: *Focus, delta: isize) void { 1243 const keys = box.children.keys(); 1244 if (keys.len == 0) return; 1245 const cur_id = box.getFocus().child_id orelse return; 1246 const cur: isize = @intCast(box.children.getIndex(cur_id) orelse return); 1247 const last: isize = @intCast(keys.len - 1); 1248 const next: usize = @intCast(std.math.clamp(cur + delta, 0, last)); 1249 if (next == @as(usize, @intCast(cur))) return; 1250 root_focus.setFocus(keys[next]); 1251 if (box.children.values()[next].rect) |rect| scroll.scrollToRect(rect); 1252 } 1253 1254 pub const FlowBox = struct { 1255 focus: *Focus, 1256 grid: ?Grid, 1257 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1258 // backs the per-item strings the text boxes borrow: each box's `content` 1259 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 1260 // wholesale on each setItems so there's no per-string ownership to track. 1261 arena: std.heap.ArenaAllocator, 1262 // column count from the last build — FlowBox.Scroll.input uses it so arrow 1263 // up/down can step by a row's worth of items. 1264 last_cols: usize, 1265 options: Options, 1266 1267 const border_rows: usize = 2; 1268 1269 pub const Options = struct { 1270 cell_width: usize = 40, 1271 cell_height: usize = 3, 1272 }; 1273 1274 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 1275 return .{ 1276 .focus = try Focus.create(allocator, .container), 1277 .grid = null, 1278 .text_boxes = .empty, 1279 .arena = std.heap.ArenaAllocator.init(allocator), 1280 .last_cols = 1, 1281 .options = options, 1282 }; 1283 } 1284 1285 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 1286 self.focus.destroy(allocator); 1287 if (self.grid) |*grid| { 1288 grid.deinit(); 1289 self.grid = null; 1290 } 1291 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1292 self.text_boxes.deinit(allocator); 1293 self.arena.deinit(); 1294 } 1295 1296 // one flow item: its display text plus an optional link. a non-empty `link` 1297 // sets the item's focus kind such as `.{ .custom = "a:/user/foo" }`, which 1298 // the web renderer turns into an anchor. 1299 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1300 1301 // both the item text and the link are copied into the arena, so the caller's 1302 // slices needn't outlive this call. 1303 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const Item) !void { 1304 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1305 self.text_boxes.clearAndFree(allocator); 1306 1307 // the old text boxes (and their borrowed content/links) are gone now, so 1308 // the arena that backed those strings can be reclaimed. 1309 _ = self.arena.reset(.retain_capacity); 1310 const aa = self.arena.allocator(); 1311 1312 self.focus.clear(); 1313 self.focus.child_id = null; 1314 1315 for (items) |item| { 1316 const line = try aa.dupe(u8, item.text); 1317 1318 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 1319 errdefer text_box.deinit(allocator); 1320 text_box.getFocus().focusable = true; 1321 1322 if (item.link.len > 0) { 1323 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1324 } 1325 1326 try self.text_boxes.append(allocator, text_box); 1327 } 1328 1329 if (self.text_boxes.items.len > 0) { 1330 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1331 } 1332 } 1333 1334 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1335 self.clearGrid(); 1336 self.focus.clear(); 1337 1338 const cell_width = self.options.cell_width; 1339 const max_width = constraint.max_size.width orelse cell_width; 1340 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 1341 self.last_cols = cols; 1342 1343 const count = self.text_boxes.items.len; 1344 if (count == 0) return; 1345 const slot_height = self.options.cell_height + border_rows; 1346 if (slot_height == 0) return; 1347 1348 // build at the slot size so every text box fits a single grid cell 1349 for (self.text_boxes.items) |*tb| { 1350 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 1351 try tb.build(allocator, .{ 1352 .min_size = .{ .width = cell_width, .height = null }, 1353 .max_size = .{ .width = cell_width, .height = slot_height }, 1354 }, root_focus); 1355 } 1356 1357 const rows = (count + cols - 1) / cols; 1358 const content_height = rows * slot_height; 1359 const total_width = cols * cell_width; 1360 if (total_width == 0 or content_height == 0) return; 1361 1362 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 1363 errdefer grid.deinit(); 1364 1365 for (self.text_boxes.items, 0..) |*tb, i| { 1366 const tb_grid = tb.getGrid() orelse continue; 1367 const col = i % cols; 1368 const row = i / cols; 1369 const cell_x = col * cell_width; 1370 const cell_y = row * slot_height; 1371 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 1372 try grid.drawGrid(tb_grid, cell_x, cell_y); 1373 } 1374 1375 self.grid = grid; 1376 } 1377 1378 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1379 _ = self; 1380 _ = allocator; 1381 _ = key; 1382 _ = root_focus; 1383 } 1384 1385 pub fn clearGrid(self: *FlowBox) void { 1386 if (self.grid) |*grid| { 1387 grid.deinit(); 1388 self.grid = null; 1389 } 1390 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1391 } 1392 1393 pub fn getGrid(self: FlowBox) ?Grid { 1394 return self.grid; 1395 } 1396 1397 pub fn getFocus(self: *FlowBox) *Focus { 1398 return self.focus; 1399 } 1400 1401 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 1402 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 1403 const slot_height = self.options.cell_height + border_rows; 1404 const col = index % self.last_cols; 1405 const row = index / self.last_cols; 1406 return .{ 1407 .x = @intCast(col * self.options.cell_width), 1408 .y = @intCast(row * slot_height), 1409 .size = .{ .width = self.options.cell_width, .height = slot_height }, 1410 }; 1411 } 1412 1413 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 1414 for (self.text_boxes.items, 0..) |tb, i| { 1415 if (tb.box.focus.id == focus_id) return i; 1416 } 1417 return null; 1418 } 1419 1420 pub const Scroll = struct { 1421 scroll: wgt.Scroll(Widget), 1422 1423 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options, web_native: bool) !Scroll { 1424 var layout_inner = try FlowBox.init(allocator, options); 1425 errdefer layout_inner.deinit(allocator); 1426 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert, .web_native = web_native }); 1427 errdefer scroll.deinit(allocator); 1428 return .{ .scroll = scroll }; 1429 } 1430 1431 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 1432 self.scroll.deinit(allocator); 1433 } 1434 1435 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const Item) !void { 1436 self.scroll.x = 0; 1437 self.scroll.y = 0; 1438 try self.inner().setItems(allocator, items); 1439 } 1440 1441 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1442 try self.scroll.build(allocator, constraint, root_focus); 1443 } 1444 1445 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1446 _ = allocator; 1447 const in = self.inner(); 1448 const child_id = in.focus.child_id orelse return; 1449 const current_index = in.indexOfFocusId(child_id) orelse return; 1450 const count = in.text_boxes.items.len; 1451 if (count == 0) return; 1452 const cols = in.last_cols; 1453 const slot_height = in.options.cell_height + FlowBox.border_rows; 1454 1455 var index = current_index; 1456 switch (key) { 1457 .arrow_up => index -|= cols, 1458 .arrow_down => if (index + cols < count) { 1459 index += cols; 1460 }, 1461 .arrow_left => index -|= 1, 1462 .arrow_right => if (index + 1 < count) { 1463 index += 1; 1464 }, 1465 .home => index = 0, 1466 .end => index = count - 1, 1467 .page_up => { 1468 if (self.scroll.grid) |grid| if (slot_height > 0) { 1469 const rows_per_page = grid.size.height / slot_height; 1470 index -|= rows_per_page * cols; 1471 }; 1472 }, 1473 .page_down => { 1474 if (self.scroll.grid) |grid| if (slot_height > 0) { 1475 const rows_per_page = grid.size.height / slot_height; 1476 index = @min(index + rows_per_page * cols, count - 1); 1477 }; 1478 }, 1479 // scroll wheel moves the focused cell by a full row so the 1480 // viewport (via scrollToRect) follows in row-sized steps, 1481 // matching how a scroll wheel feels in a grid view. 1482 .mouse => |mouse| switch (mouse.action) { 1483 .scroll => |dir| switch (dir) { 1484 .up => index -|= cols, 1485 .down => if (index + cols < count) { 1486 index += cols; 1487 }, 1488 }, 1489 else => {}, 1490 }, 1491 else => {}, 1492 } 1493 1494 if (index != current_index) { 1495 root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 1496 if (in.cellRect(index)) |rect| { 1497 self.scroll.scrollToRect(rect); 1498 } 1499 } 1500 } 1501 1502 pub fn clearGrid(self: *Scroll) void { 1503 self.scroll.clearGrid(); 1504 } 1505 1506 pub fn getGrid(self: Scroll) ?Grid { 1507 return self.scroll.getGrid(); 1508 } 1509 1510 pub fn getFocus(self: *Scroll) *Focus { 1511 return self.scroll.getFocus(); 1512 } 1513 1514 pub fn getSelectedIndex(self: Scroll) ?usize { 1515 const in = self.scroll.child.flow_box; 1516 const child_id = in.focus.child_id orelse return null; 1517 return in.indexOfFocusId(child_id); 1518 } 1519 1520 fn inner(self: *Scroll) *FlowBox { 1521 return &self.scroll.child.flow_box; 1522 } 1523 }; 1524 }; 1525 1526 // a left-to-right flow of variable-width focusable items that wraps at the 1527 // available width, like words in a paragraph. unlike FlowBox there is no cell 1528 // grid: each item is as wide as its text. selection movement is driven by the 1529 // owning view via indexOfFocusId/verticalNeighbor. 1530 pub const TagFlow = struct { 1531 focus: *Focus, 1532 grid: ?Grid, 1533 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1534 // last build's item rects (content space), for vertical navigation and 1535 // scroll-into-view. 1536 rects: std.ArrayList(layout.IRect), 1537 // backs the per-item strings the text boxes borrow. 1538 arena: std.heap.ArenaAllocator, 1539 1540 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1541 1542 pub fn init(allocator: std.mem.Allocator) !TagFlow { 1543 return .{ 1544 .focus = try Focus.create(allocator, .container), 1545 .grid = null, 1546 .text_boxes = .empty, 1547 .rects = .empty, 1548 .arena = std.heap.ArenaAllocator.init(allocator), 1549 }; 1550 } 1551 1552 pub fn deinit(self: *TagFlow, allocator: std.mem.Allocator) void { 1553 self.focus.destroy(allocator); 1554 if (self.grid) |*grid| { 1555 grid.deinit(); 1556 self.grid = null; 1557 } 1558 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1559 self.text_boxes.deinit(allocator); 1560 self.rects.deinit(allocator); 1561 self.arena.deinit(); 1562 } 1563 1564 // both the item text and the link are copied into the arena, so the caller's 1565 // slices needn't outlive this call. 1566 pub fn setItems(self: *TagFlow, allocator: std.mem.Allocator, items: []const Item) !void { 1567 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1568 self.text_boxes.clearAndFree(allocator); 1569 1570 _ = self.arena.reset(.retain_capacity); 1571 const aa = self.arena.allocator(); 1572 1573 self.focus.clear(); 1574 self.focus.child_id = null; 1575 1576 for (items) |item| { 1577 const line = try aa.dupe(u8, item.text); 1578 1579 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none }); 1580 errdefer text_box.deinit(allocator); 1581 text_box.getFocus().focusable = true; 1582 1583 if (item.link.len > 0) { 1584 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1585 } 1586 1587 try self.text_boxes.append(allocator, text_box); 1588 } 1589 1590 if (self.text_boxes.items.len > 0) { 1591 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1592 } 1593 } 1594 1595 pub fn build(self: *TagFlow, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1596 self.clearGrid(); 1597 self.focus.clear(); 1598 1599 if (self.text_boxes.items.len == 0) return; 1600 const max_width = constraint.max_size.width orelse 80; 1601 if (max_width == 0) return; 1602 1603 // lay the items out left to right, wrapping to a new row when the next 1604 // one wouldn't fit. 1605 self.rects.clearRetainingCapacity(); 1606 var x: usize = 0; 1607 var y: usize = 0; 1608 var row_height: usize = 0; 1609 var total_width: usize = 0; 1610 for (self.text_boxes.items) |*tb| { 1611 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 1612 try tb.build(allocator, .{ 1613 .min_size = .{ .width = null, .height = null }, 1614 .max_size = .{ .width = max_width, .height = null }, 1615 }, root_focus); 1616 const tb_grid_maybe = tb.getGrid(); 1617 const w: usize = if (tb_grid_maybe) |g| g.size.width else 0; 1618 const h: usize = if (tb_grid_maybe) |g| g.size.height else 0; 1619 if (x > 0 and x + w > max_width) { 1620 x = 0; 1621 y += row_height; 1622 row_height = 0; 1623 } 1624 try self.rects.append(allocator, .{ .x = @intCast(x), .y = @intCast(y), .size = .{ .width = w, .height = h } }); 1625 if (h > row_height) row_height = h; 1626 x += w; 1627 if (x > total_width) total_width = x; 1628 } 1629 1630 const total_height = y + row_height; 1631 if (total_width == 0 or total_height == 0) return; 1632 1633 var grid = try Grid.init(allocator, .{ .width = total_width, .height = total_height }); 1634 errdefer grid.deinit(); 1635 1636 for (self.text_boxes.items, self.rects.items) |*tb, rect| { 1637 const tb_grid = tb.getGrid() orelse continue; 1638 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, @intCast(rect.x), @intCast(rect.y)); 1639 try grid.drawGrid(tb_grid, @intCast(rect.x), @intCast(rect.y)); 1640 } 1641 1642 self.grid = grid; 1643 } 1644 1645 pub fn input(self: *TagFlow, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1646 _ = self; 1647 _ = allocator; 1648 _ = key; 1649 _ = root_focus; 1650 } 1651 1652 pub fn clearGrid(self: *TagFlow) void { 1653 if (self.grid) |*grid| { 1654 grid.deinit(); 1655 self.grid = null; 1656 } 1657 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1658 } 1659 1660 pub fn getGrid(self: TagFlow) ?Grid { 1661 return self.grid; 1662 } 1663 1664 pub fn getFocus(self: *TagFlow) *Focus { 1665 return self.focus; 1666 } 1667 1668 pub fn indexOfFocusId(self: TagFlow, focus_id: usize) ?usize { 1669 for (self.text_boxes.items, 0..) |tb, i| { 1670 if (tb.box.focus.id == focus_id) return i; 1671 } 1672 return null; 1673 } 1674 1675 // the first item of the row below (when `downward`) or above, or null at 1676 // the flow's edge. items are laid out in order, so y is nondecreasing. 1677 pub fn rowStep(self: TagFlow, index: usize, downward: bool) ?usize { 1678 const rects = self.rects.items; 1679 if (index >= rects.len) return null; 1680 const cur_y = rects[index].y; 1681 if (downward) { 1682 for (rects[index + 1 ..], index + 1..) |r, i| { 1683 if (r.y > cur_y) return i; 1684 } 1685 return null; 1686 } 1687 // walk the earlier rows; the last one visited is the row above. 1688 var prev_first: ?usize = null; 1689 var i: usize = 0; 1690 while (i < rects.len and rects[i].y < cur_y) { 1691 prev_first = i; 1692 const y = rects[i].y; 1693 while (i < rects.len and rects[i].y == y) i += 1; 1694 } 1695 return prev_first; 1696 } 1697 }; 1698 1699 // an invisible widget that fills the horizontal space granted by its parent. 1700 // used inside Box(horiz) with a min_size so the box reserves space for the 1701 // children that follow, pushing them to the right. 1702 pub const Spacer = struct { 1703 focus: *Focus, 1704 grid: ?Grid, 1705 1706 pub fn init(allocator: std.mem.Allocator) !Spacer { 1707 return .{ 1708 .focus = try Focus.create(allocator, .container), 1709 .grid = null, 1710 }; 1711 } 1712 1713 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 1714 self.focus.destroy(allocator); 1715 if (self.grid) |*grid| { 1716 grid.deinit(); 1717 self.grid = null; 1718 } 1719 } 1720 1721 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1722 _ = root_focus; 1723 self.clearGrid(); 1724 const width = constraint.max_size.width orelse return; 1725 if (width == 0) return; 1726 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1727 } 1728 1729 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1730 _ = self; 1731 _ = allocator; 1732 _ = key; 1733 _ = root_focus; 1734 } 1735 1736 pub fn clearGrid(self: *Spacer) void { 1737 if (self.grid) |*grid| { 1738 grid.deinit(); 1739 self.grid = null; 1740 } 1741 } 1742 1743 pub fn getGrid(self: Spacer) ?Grid { 1744 return self.grid; 1745 } 1746 1747 pub fn getFocus(self: *Spacer) *Focus { 1748 return self.focus; 1749 } 1750 }; 1751 1752 // a one-row, non-focusable status bar showing the current page's url 1753 pub const Footer = struct { 1754 focus: *Focus, 1755 grid: ?Grid, 1756 session: *Session, 1757 arena: std.heap.ArenaAllocator, 1758 1759 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 1760 return .{ 1761 .focus = try Focus.create(allocator, .container), 1762 .grid = null, 1763 .session = session, 1764 .arena = std.heap.ArenaAllocator.init(allocator), 1765 }; 1766 } 1767 1768 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 1769 self.focus.destroy(allocator); 1770 if (self.grid) |*grid| grid.deinit(); 1771 self.arena.deinit(); 1772 } 1773 1774 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1775 _ = root_focus; 1776 self.clearGrid(); 1777 const width = constraint.max_size.width orelse return; 1778 if (width == 0) return; 1779 1780 _ = self.arena.reset(.retain_capacity); 1781 const aa = self.arena.allocator(); 1782 const path = self.session.data.current_page.urlAlloc(&self.arena) catch return; 1783 const text = if (self.session.web_port) |port| 1784 std.fmt.allocPrint(aa, "http://localhost:{d}{s}", .{ port, path }) catch return 1785 else 1786 path; 1787 1788 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1789 errdefer grid.deinit(); 1790 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 1791 var i: usize = 0; 1792 while (utf8.nextCodepointSlice()) |ch| { 1793 if (i == width) break; 1794 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 1795 i += 1; 1796 } 1797 self.grid = grid; 1798 } 1799 1800 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1801 _ = self; 1802 _ = allocator; 1803 _ = key; 1804 _ = root_focus; 1805 } 1806 1807 pub fn clearGrid(self: *Footer) void { 1808 if (self.grid) |*grid| { 1809 grid.deinit(); 1810 self.grid = null; 1811 } 1812 } 1813 1814 pub fn getGrid(self: Footer) ?Grid { 1815 return self.grid; 1816 } 1817 1818 pub fn getFocus(self: *Footer) *Focus { 1819 return self.focus; 1820 } 1821 }; 1822 1823 // a single-child wrapper that builds the child at its natural size and 1824 // positions its grid in the middle of the area granted by the parent 1825 pub const Center = struct { 1826 focus: *Focus, 1827 grid: ?Grid, 1828 child: *Widget, 1829 1830 pub fn init(allocator: std.mem.Allocator, child_widget: Widget) !Center { 1831 const child = try allocator.create(Widget); 1832 errdefer allocator.destroy(child); 1833 child.* = child_widget; 1834 return .{ 1835 .focus = try Focus.create(allocator, .container), 1836 .grid = null, 1837 .child = child, 1838 }; 1839 } 1840 1841 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 1842 self.focus.destroy(allocator); 1843 if (self.grid) |*grid| { 1844 grid.deinit(); 1845 self.grid = null; 1846 } 1847 self.child.deinit(allocator); 1848 allocator.destroy(self.child); 1849 } 1850 1851 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1852 self.clearGrid(); 1853 self.getFocus().clear(); 1854 1855 // build the child without forcing it to fill min_size; it sizes 1856 // itself to its content within the available max. 1857 try self.child.build(allocator, .{ 1858 .min_size = .{ .width = null, .height = null }, 1859 .max_size = constraint.max_size, 1860 }, root_focus); 1861 1862 const child_grid = self.child.getGrid() orelse return; 1863 1864 // prefer max when given; otherwise grow to max(min, child) so that 1865 // when only a min is set (e.g. the wasm path passes viewport rows 1866 // as min_height with no max), we can still vertically center while 1867 // letting taller content extend past the min. 1868 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; 1869 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; 1870 if (width == 0 or height == 0) return; 1871 1872 const offset_x: usize = (width -| child_grid.size.width) / 2; 1873 const offset_y: usize = (height -| child_grid.size.height) / 2; 1874 1875 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 1876 errdefer grid.deinit(); 1877 try grid.drawGrid(child_grid, offset_x, offset_y); 1878 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 1879 self.getFocus().child_id = self.child.getFocus().id; 1880 1881 self.grid = grid; 1882 } 1883 1884 pub fn input(self: *Center, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 1885 try self.child.input(allocator, key, root_focus); 1886 } 1887 1888 pub fn clearGrid(self: *Center) void { 1889 if (self.grid) |*grid| { 1890 grid.deinit(); 1891 self.grid = null; 1892 } 1893 self.child.clearGrid(); 1894 } 1895 1896 pub fn getGrid(self: Center) ?Grid { 1897 return self.grid; 1898 } 1899 1900 pub fn getFocus(self: *Center) *Focus { 1901 return self.focus; 1902 } 1903 }; 1904 1905 // renders truecolor ANSI art 1906 pub const AnsiArt = struct { 1907 focus: *Focus, 1908 grid: ?Grid, 1909 content: []const u8, 1910 1911 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 1912 return .{ 1913 .focus = try Focus.create(allocator, .container), 1914 .grid = null, 1915 .content = content, 1916 }; 1917 } 1918 1919 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 1920 self.focus.destroy(allocator); 1921 if (self.grid) |*grid| { 1922 grid.deinit(); 1923 self.grid = null; 1924 } 1925 } 1926 1927 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1928 _ = root_focus; 1929 self.clearGrid(); 1930 1931 // parse into rows of cells, then copy into a rectangular grid 1932 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 1933 defer { 1934 for (rows.items) |*row| row.deinit(allocator); 1935 rows.deinit(allocator); 1936 } 1937 var row: std.ArrayList(Grid.Cell) = .empty; 1938 errdefer row.deinit(allocator); 1939 1940 var style: Grid.Style = .{}; 1941 var width: usize = 0; 1942 const content = self.content; 1943 var i: usize = 0; 1944 while (i < content.len) { 1945 const byte = content[i]; 1946 if (byte == '\n') { 1947 width = @max(width, row.items.len); 1948 try rows.append(allocator, row); 1949 row = .empty; 1950 i += 1; 1951 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 1952 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 1953 var j = i + 2; 1954 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 1955 if (j >= content.len) { 1956 i = content.len; // malformed trailing escape; stop 1957 } else { 1958 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 1959 i = j + 1; 1960 } 1961 } else { 1962 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 1963 const end = @min(content.len, i + len); 1964 const rune = content[i..end]; 1965 const transparent = end - i == 1 and rune[0] == ' ' and 1966 style.fg == null and style.bg == null and !style.inverted; 1967 try row.append(allocator, .{ 1968 .rune = if (transparent) null else rune, 1969 .style = style, 1970 }); 1971 i = end; 1972 } 1973 } 1974 // a trailing row with content but no closing newline 1975 if (row.items.len > 0) { 1976 width = @max(width, row.items.len); 1977 try rows.append(allocator, row); 1978 } else { 1979 row.deinit(allocator); 1980 } 1981 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1982 1983 const height = rows.items.len; 1984 if (width == 0 or height == 0) return; 1985 1986 const clamped_w = @min(width, constraint.max_size.width orelse width); 1987 const clamped_h = @min(height, constraint.max_size.height orelse height); 1988 1989 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1990 errdefer grid.deinit(); 1991 for (rows.items[0..clamped_h], 0..) |r, y| { 1992 const n = @min(r.items.len, clamped_w); 1993 for (r.items[0..n], 0..) |cell, x| { 1994 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1995 } 1996 } 1997 self.grid = grid; 1998 } 1999 2000 pub fn clearGrid(self: *AnsiArt) void { 2001 if (self.grid) |*grid| { 2002 grid.deinit(); 2003 self.grid = null; 2004 } 2005 } 2006 2007 pub fn getGrid(self: AnsiArt) ?Grid { 2008 return self.grid; 2009 } 2010 2011 pub fn getFocus(self: *AnsiArt) *Focus { 2012 return self.focus; 2013 } 2014 2015 fn applySgr(style: *Grid.Style, params: []const u8) void { 2016 var nums: [16]u32 = undefined; 2017 var n: usize = 0; 2018 var it = std.mem.splitScalar(u8, params, ';'); 2019 while (it.next()) |tok| { 2020 if (n >= nums.len) break; 2021 // an empty parameter (e.g. bare "\x1b[m") means 0 2022 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 2023 n += 1; 2024 } 2025 if (n == 0) { 2026 style.* = .{}; 2027 return; 2028 } 2029 var i: usize = 0; 2030 while (i < n) : (i += 1) { 2031 switch (nums[i]) { 2032 0 => style.* = .{}, 2033 7 => style.inverted = true, 2034 27 => style.inverted = false, 2035 39 => style.fg = null, 2036 49 => style.bg = null, 2037 38, 48 => { 2038 // truecolor form: 38;2;r;g;b — anything else is ignored 2039 if (i + 4 < n and nums[i + 1] == 2) { 2040 const c = Grid.Color{ 2041 .r = @truncate(nums[i + 2]), 2042 .g = @truncate(nums[i + 3]), 2043 .b = @truncate(nums[i + 4]), 2044 }; 2045 if (nums[i] == 38) style.fg = c else style.bg = c; 2046 i += 4; 2047 } 2048 }, 2049 else => {}, 2050 } 2051 } 2052 } 2053 }; 2054 2055 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 2056 pub const AnsiBackground = struct { 2057 grid: ?Grid, 2058 child: *Widget, 2059 art: AnsiArt, 2060 session: *Session, 2061 2062 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 2063 var cw = child_widget; 2064 const child = allocator.create(Widget) catch |e| { 2065 cw.deinit(allocator); 2066 return e; 2067 }; 2068 child.* = cw; 2069 errdefer { 2070 child.deinit(allocator); 2071 allocator.destroy(child); 2072 } 2073 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 2074 } 2075 2076 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 2077 if (self.grid) |*grid| grid.deinit(); 2078 self.art.deinit(allocator); 2079 self.child.deinit(allocator); 2080 allocator.destroy(self.child); 2081 } 2082 2083 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 2084 self.clearGrid(); 2085 2086 // make the wrapped page fill the whole available area 2087 try self.child.build(allocator, .{ 2088 .min_size = .{ 2089 .width = constraint.max_size.width orelse constraint.min_size.width, 2090 .height = constraint.max_size.height orelse constraint.min_size.height, 2091 }, 2092 .max_size = constraint.max_size, 2093 }, root_focus); 2094 2095 if (self.session.data.enable_ansi) { 2096 if (self.child.getGrid()) |fg| { 2097 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 2098 } 2099 } 2100 } 2101 2102 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 2103 try self.child.input(allocator, key, root_focus); 2104 } 2105 2106 pub fn clearGrid(self: *AnsiBackground) void { 2107 if (self.grid) |*grid| { 2108 grid.deinit(); 2109 self.grid = null; 2110 } 2111 self.child.clearGrid(); 2112 self.art.clearGrid(); 2113 } 2114 2115 pub fn getGrid(self: AnsiBackground) ?Grid { 2116 return self.grid orelse self.child.getGrid(); 2117 } 2118 2119 pub fn getFocus(self: *AnsiBackground) *Focus { 2120 return self.child.getFocus(); 2121 } 2122 2123 // which top corner the art hugs. 2124 const ArtAnchor = enum { top_left, top_right }; 2125 2126 // a foreground cell counts as blank if it's empty or a bare space without styling 2127 fn cellIsBlank(cell: Grid.Cell) bool { 2128 if (cell.rune) |rune| { 2129 return std.mem.eql(u8, rune, " ") and 2130 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 2131 } 2132 return true; 2133 } 2134 2135 // the art is dimmed to this fraction of its brightness so foreground text 2136 // stays legible over it 2137 const art_brightness = 45; // percent 2138 2139 fn dimColor(color: ?Grid.Color) ?Grid.Color { 2140 const c = color orelse return null; 2141 return .{ 2142 .r = @intCast(@as(u16, c.r) * art_brightness / 100), 2143 .g = @intCast(@as(u16, c.g) * art_brightness / 100), 2144 .b = @intCast(@as(u16, c.b) * art_brightness / 100), 2145 }; 2146 } 2147 2148 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 2149 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 2150 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 2151 // snap such channels clear of that range so the backdrop doesn't blink or 2152 // hide text there; the ≤9/255 shift is imperceptible on terminals that 2153 // actually render truecolor. 2154 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 2155 const c = color orelse return null; 2156 const snap = struct { 2157 fn f(v: u8) u8 { 2158 return if (v >= 1 and v <= 9) 10 else v; 2159 } 2160 }.f; 2161 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 2162 } 2163 2164 // composites ANSI art behind a foreground grid 2165 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 2166 art.clearGrid(); 2167 try art.build(allocator, .{ 2168 .min_size = .{ .width = null, .height = null }, 2169 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 2170 }, root_focus); 2171 2172 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 2173 errdefer out.deinit(); 2174 2175 if (art.getGrid()) |art_grid| { 2176 const anchor_x = switch (anchor) { 2177 .top_left => 0, 2178 .top_right => foreground.size.width -| art_grid.size.width, 2179 }; 2180 for (0..art_grid.size.height) |y| { 2181 for (0..art_grid.size.width) |x| { 2182 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 2183 if (src.rune == null) continue; 2184 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 2185 const dst = &out.cells.items[idx]; 2186 // composite the dimmed art behind every cell so it shows 2187 // through the whole UI: a blank cell becomes the art, while a 2188 // cell with a glyph keeps the glyph but takes the dimmed art as 2189 // its background (replacing whatever background it had, which 2190 // would otherwise obscure the art). 2191 if (cellIsBlank(dst.*)) { 2192 dst.* = src; 2193 dst.style.fg = sgrSafe(dimColor(dst.style.fg)); 2194 dst.style.bg = sgrSafe(dimColor(dst.style.bg)); 2195 } else { 2196 dst.style.bg = sgrSafe(dimColor(src.style.bg orelse src.style.fg)); 2197 } 2198 } 2199 } 2200 } 2201 return out; 2202 } 2203 }; 2204