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