╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const xitui = xit.xitui; 5 const term = xitui.terminal; 6 const wgt = xitui.widget; 7 const layout = xitui.layout; 8 const inp = xitui.input; 9 const Grid = xitui.grid.Grid; 10 const Focus = xitui.focus.Focus; 11 const evt = @import("./event.zig"); 12 13 pub const Home = @import("./ui/Home.zig"); 14 pub const User = @import("./ui/User.zig"); 15 pub const Repo = @import("./ui/Repo.zig"); 16 pub const Title = @import("./ui/Title.zig"); 17 pub const Quit = @import("./ui/Quit.zig"); 18 19 pub const PageKind = enum { 20 home, 21 user, 22 repo, 23 }; 24 25 pub const Page = union(PageKind) { 26 home: Home, 27 user: User, 28 repo: Repo, 29 30 pub fn init(arena: *std.heap.ArenaAllocator, session: *Session, route: RoutablePage) !Page { 31 const haxy_moment = session.haxy_moment orelse return error.NoMoment; 32 return switch (route.parent()) { 33 .home => .{ .home = try Home.init(arena, haxy_moment) }, 34 .user => switch (route) { 35 .user, .user_settings, .user_auth => |name| .{ .user = try User.init(arena, haxy_moment, name) }, 36 else => return error.UnexpectedRoute, 37 }, 38 .repo => switch (route) { 39 .repo, .repo_commits, .repo_settings, .repo_auth => .{ .repo = try Repo.init(arena, session, route) }, 40 else => return error.UnexpectedRoute, 41 }, 42 }; 43 } 44 }; 45 46 // what the server hands to the client (and what main_wasm parses on _start). 47 // keeps Page free of any per-request session state. 48 pub const Snapshot = struct { 49 page: Page, 50 session: Session.Data = .{}, 51 }; 52 53 // a top-level "page" the user can navigate to. the user_* variants are the 54 // tabs of a user page; they each carry the user's name and all map to the 55 // .user parent page, so switching between them stays on that page (and just 56 // updates the url) rather than navigating away. 57 pub const RoutablePage = union(enum) { 58 home_users, 59 home_repos, 60 home_settings, 61 home_auth, 62 user: Array(evt.User.name_max_len), 63 user_settings: Array(evt.User.name_max_len), 64 user_auth: Array(evt.User.name_max_len), 65 repo: Array(repo_route_max_len), 66 repo_commits: struct { name: Array(repo_route_max_len), after: usize = 0 }, 67 repo_settings: Array(repo_route_max_len), 68 repo_auth: Array(repo_route_max_len), 69 70 pub const default: RoutablePage = .home_users; 71 72 const user_segment = "/user/"; 73 const repo_segment = "/repo/"; 74 const files_seg = "files"; 75 const commits_seg = "commits"; 76 77 // a repo route is "username/reponame", optionally followed by 78 // "/files/<dir>" for a directory in the files tab 79 pub const repo_route_max_len = 1024; 80 81 // the parts of a `.repo` files route. owner/name/dir are slices into the 82 // route's stored string; dir is "" at the repo root. 83 pub const RepoFiles = struct { 84 identity: []const u8, // "owner/name" 85 owner: []const u8, 86 name: []const u8, 87 dir: []const u8, 88 89 // parse a `.repo` route's stored string ("owner/name" or 90 // "owner/name/files/<dir>"). 91 pub fn parse(s: []const u8) ?RepoFiles { 92 const s1 = std.mem.indexOfScalar(u8, s, '/') orelse return null; 93 const owner = s[0..s1]; 94 const after = s[s1 + 1 ..]; 95 const s2 = std.mem.indexOfScalar(u8, after, '/'); 96 const name = if (s2) |i| after[0..i] else after; 97 if (owner.len == 0 or name.len == 0) return null; 98 const dir = if (s2) |i| blk: { 99 const tail = after[i + 1 ..]; // "files" or "files/<dir>" 100 break :blk if (std.mem.startsWith(u8, tail, files_seg ++ "/")) tail[files_seg.len + 1 ..] else ""; 101 } else ""; 102 return .{ .identity = s[0 .. s1 + 1 + name.len], .owner = owner, .name = name, .dir = dir }; 103 } 104 }; 105 106 // build a `.repo` files route for "owner/name" (identity) at `dir` ("" = 107 // root), or null if the result doesn't fit the inline name. 108 pub fn repoFilesRoute(identity: []const u8, dir: []const u8) ?RoutablePage { 109 if (dir.len == 0) return .{ .repo = Array(repo_route_max_len).from(identity) orelse return null }; 110 var buf: [repo_route_max_len]u8 = undefined; 111 const s = std.fmt.bufPrint(&buf, "{s}/" ++ files_seg ++ "/{s}", .{ identity, dir }) catch return null; 112 return .{ .repo = Array(repo_route_max_len).from(s) orelse return null }; 113 } 114 115 // the start oid of a `.repo_commits` route's stored string ("" = page 1, 116 // which the commits tab walks from HEAD). 117 pub fn repoCommitsStart(s: []const u8) []const u8 { 118 const marker = "/" ++ commits_seg ++ "/"; 119 const i = std.mem.indexOf(u8, s, marker) orelse return ""; 120 return s[i + marker.len ..]; 121 } 122 123 // build a `.repo_commits` route for "owner/name" (identity) at `start_oid` 124 // ("" = the first page). always carries the `commits` marker so page 1 125 // ("owner/name/commits") doesn't collide with the files root. 126 pub fn repoCommitsRoute(identity: []const u8, start_oid: []const u8, after: usize) ?RoutablePage { 127 var buf: [repo_route_max_len]u8 = undefined; 128 const s = if (start_oid.len == 0) 129 std.fmt.bufPrint(&buf, "{s}/" ++ commits_seg, .{identity}) catch return null 130 else 131 std.fmt.bufPrint(&buf, "{s}/" ++ commits_seg ++ "/{s}", .{ identity, start_oid }) catch return null; 132 return .{ .repo_commits = .{ .name = Array(repo_route_max_len).from(s) orelse return null, .after = after } }; 133 } 134 135 // an inline, owned array of data. keeping it in the route (rather than a 136 // borrowed slice) makes RoutablePage a plain value: it can be copied, stored 137 // in history, and serialized without any arena tracking. 138 pub fn Array(comptime max_len: usize) type { 139 return struct { 140 bytes: [max_len]u8 = undefined, 141 len: u16 = 0, 142 143 pub fn from(s: []const u8) ?Array(max_len) { 144 if (s.len > max_len) return null; 145 var name = Array(max_len){ .len = @intCast(s.len) }; 146 @memcpy(name.bytes[0..s.len], s); 147 return name; 148 } 149 150 pub fn slice(self: *const Array(max_len)) []const u8 { 151 return self.bytes[0..self.len]; 152 } 153 }; 154 } 155 156 pub fn url(comptime self: RoutablePage) []const u8 { 157 return switch (self) { 158 .home_users => "/users", 159 .home_repos => "/repos", 160 .home_settings => "/settings", 161 .home_auth => "/auth", 162 .user, .user_settings, .user_auth => @compileError("user routes are dynamic; use urlAlloc"), 163 .repo, .repo_commits, .repo_settings, .repo_auth => @compileError("repo routes are dynamic; use urlAlloc"), 164 }; 165 } 166 167 pub fn urlAlloc(self: RoutablePage, arena: *std.heap.ArenaAllocator) ![]const u8 { 168 return switch (self) { 169 .user => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}", .{name.slice()}), 170 .user_settings => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/settings", .{name.slice()}), 171 .user_auth => |name| try std.fmt.allocPrint(arena.allocator(), user_segment ++ "{s}/auth", .{name.slice()}), 172 .repo => |name| try std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{name.slice()}), 173 .repo_commits => |c| if (c.after == 0) 174 try std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}", .{c.name.slice()}) 175 else 176 try std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}?after={d}", .{ c.name.slice(), c.after }), 177 .repo_settings => |name| try std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}/settings", .{name.slice()}), 178 .repo_auth => |name| try std.fmt.allocPrint(arena.allocator(), repo_segment ++ "{s}/auth", .{name.slice()}), 179 inline else => |_, tag| url(tag), 180 }; 181 } 182 183 pub fn parent(self: RoutablePage) PageKind { 184 return switch (self) { 185 .home_users, .home_repos, .home_settings, .home_auth => .home, 186 .user, .user_settings, .user_auth => .user, 187 .repo, .repo_commits, .repo_settings, .repo_auth => .repo, 188 }; 189 } 190 191 // parse a path plus its raw query string 192 pub fn fromUrl(path: []const u8, query: ?[]const u8) ?RoutablePage { 193 const after = uintParam(query, "after") orelse 0; 194 if (std.mem.eql(u8, path, "/")) return default; 195 if (std.mem.eql(u8, path, "/users")) return .home_users; 196 if (std.mem.eql(u8, path, "/repos")) return .home_repos; 197 if (std.mem.eql(u8, path, "/settings")) return .home_settings; 198 if (std.mem.eql(u8, path, "/auth")) return .home_auth; 199 // /user/<name>[/settings|/auth] 200 if (std.mem.startsWith(u8, path, user_segment)) { 201 const rest = path[user_segment.len..]; 202 const slash = std.mem.indexOfScalar(u8, rest, '/'); 203 const name = if (slash) |s| rest[0..s] else rest; 204 if (name.len == 0) return null; 205 const parsed = Array(evt.User.name_max_len).from(name) orelse return null; // name too long 206 if (slash) |s| { 207 const sub = rest[s + 1 ..]; 208 if (std.mem.eql(u8, sub, "settings")) return .{ .user_settings = parsed }; 209 if (std.mem.eql(u8, sub, "auth")) return .{ .user_auth = parsed }; 210 return null; // unknown sub-path 211 } 212 return .{ .user = parsed }; 213 } 214 // /repo/<username>/<reponame> (files root), then optionally /settings, 215 // /auth, or /files/<dir> for a directory in the files tab. the `repo` 216 // variant stores "username/reponame" (root) or 217 // "username/reponame/files/<dir>"; settings/auth store just the pair. 218 if (std.mem.startsWith(u8, path, repo_segment)) { 219 const rest = path[repo_segment.len..]; 220 const user_slash = std.mem.indexOfScalar(u8, rest, '/') orelse return null; 221 const after_user = rest[user_slash + 1 ..]; 222 const repo_slash = std.mem.indexOfScalar(u8, after_user, '/'); 223 const repo_name = if (repo_slash) |s| after_user[0..s] else after_user; 224 // reject an empty username or reponame 225 if (user_slash == 0 or repo_name.len == 0) return null; 226 const pair = rest[0 .. user_slash + 1 + repo_name.len]; // "username/reponame" 227 if (repo_slash) |s| { 228 const sub = after_user[s + 1 ..]; 229 if (std.mem.eql(u8, sub, "settings")) return .{ .repo_settings = Array(repo_route_max_len).from(pair) orelse return null }; 230 if (std.mem.eql(u8, sub, "auth")) return .{ .repo_auth = Array(repo_route_max_len).from(pair) orelse return null }; 231 if (std.mem.eql(u8, sub, files_seg)) return repoFilesRoute(pair, ""); // trailing /files == root 232 if (std.mem.startsWith(u8, sub, files_seg ++ "/")) return repoFilesRoute(pair, sub[files_seg.len + 1 ..]); 233 if (std.mem.eql(u8, sub, commits_seg)) return repoCommitsRoute(pair, "", after); // trailing /commits == page 1 234 if (std.mem.startsWith(u8, sub, commits_seg ++ "/")) return repoCommitsRoute(pair, sub[commits_seg.len + 1 ..], after); 235 return null; // unknown sub-path 236 } 237 return repoFilesRoute(pair, ""); 238 } 239 return null; 240 } 241 242 // read a "key=<uint>" value from a raw "a=1&b=2" query string. 243 fn uintParam(query: ?[]const u8, key: []const u8) ?usize { 244 const qs = query orelse return null; 245 var it = std.mem.splitScalar(u8, qs, '&'); 246 while (it.next()) |pair| { 247 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 248 if (std.mem.eql(u8, pair[0..eq], key)) 249 return std.fmt.parseInt(usize, pair[eq + 1 ..], 10) catch null; 250 } 251 return null; 252 } 253 254 pub fn eql(a: RoutablePage, b: RoutablePage) bool { 255 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 256 return switch (a) { 257 .user => |a_name| std.mem.eql(u8, a_name.slice(), b.user.slice()), 258 .user_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.user_settings.slice()), 259 .user_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.user_auth.slice()), 260 .repo => |a_name| std.mem.eql(u8, a_name.slice(), b.repo.slice()), 261 .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, 262 .repo_settings => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_settings.slice()), 263 .repo_auth => |a_name| std.mem.eql(u8, a_name.slice(), b.repo_auth.slice()), 264 else => true, 265 }; 266 } 267 268 // the content a repo route renders: which repo, plus the files directory and 269 // commits page. tab switches keep this fixed (the page already holds every 270 // tab's data); a files-directory or commits-page change alters it. 271 const RepoContent = struct { identity: []const u8, files_dir: []const u8, commits_start: []const u8, commits_after: usize }; 272 273 fn repoContent(r: RoutablePage) ?RepoContent { 274 const name = switch (r) { 275 .repo, .repo_settings, .repo_auth => |n| n.slice(), 276 .repo_commits => |c| c.name.slice(), 277 else => return null, 278 }; 279 const rf = RepoFiles.parse(name) orelse return null; 280 return .{ 281 .identity = rf.identity, 282 .files_dir = if (std.meta.activeTag(r) == .repo) rf.dir else "", 283 .commits_start = if (std.meta.activeTag(r) == .repo_commits) repoCommitsStart(name) else "", 284 .commits_after = switch (r) { 285 .repo_commits => |c| c.after, 286 else => 0, 287 }, 288 }; 289 } 290 291 // true when `a` and `b` are both repo routes that render different content 292 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 293 const ca = repoContent(a) orelse return false; 294 const cb = repoContent(b) orelse return false; 295 return !std.mem.eql(u8, ca.identity, cb.identity) or 296 !std.mem.eql(u8, ca.files_dir, cb.files_dir) or 297 !std.mem.eql(u8, ca.commits_start, cb.commits_start) or 298 ca.commits_after != cb.commits_after; 299 } 300 301 // serialize as { "kind": <tag>, "name"?: <name>, "after"?: <n> }. the default 302 // union(enum) codec doesn't round-trip here: Stringify emits a void 303 // variant as a bare tag string, but the parser expects an object — so the 304 // server->wasm Snapshot JSON would fail to parse. 305 pub fn jsonStringify(self: RoutablePage, jw: anytype) !void { 306 try jw.beginObject(); 307 try jw.objectField("kind"); 308 try jw.write(@tagName(self)); 309 switch (self) { 310 .user, .user_settings, .user_auth => |name| { 311 try jw.objectField("name"); 312 try jw.write(name.slice()); 313 }, 314 .repo, .repo_settings, .repo_auth => |name| { 315 try jw.objectField("name"); 316 try jw.write(name.slice()); 317 }, 318 .repo_commits => |c| { 319 try jw.objectField("name"); 320 try jw.write(c.name.slice()); 321 try jw.objectField("after"); 322 try jw.write(c.after); 323 }, 324 else => {}, 325 } 326 try jw.endObject(); 327 } 328 329 pub fn jsonParse(allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions) !RoutablePage { 330 const Helper = struct { kind: std.meta.Tag(RoutablePage), name: ?[]const u8 = null, after: usize = 0 }; 331 const helper = try std.json.innerParse(Helper, allocator, source, options); 332 const parseName = struct { 333 // errors must stay within std.json's ParseError set; ValueTooLong 334 // is its member for an over-long field. 335 fn f(comptime max_len: usize, maybe: ?[]const u8) !Array(max_len) { 336 return Array(max_len).from(maybe orelse return error.MissingField) orelse error.ValueTooLong; 337 } 338 }.f; 339 return switch (helper.kind) { 340 .home_users => .home_users, 341 .home_repos => .home_repos, 342 .home_settings => .home_settings, 343 .home_auth => .home_auth, 344 .user => .{ .user = try parseName(evt.User.name_max_len, helper.name) }, 345 .user_settings => .{ .user_settings = try parseName(evt.User.name_max_len, helper.name) }, 346 .user_auth => .{ .user_auth = try parseName(evt.User.name_max_len, helper.name) }, 347 .repo => .{ .repo = try parseName(repo_route_max_len, helper.name) }, 348 .repo_commits => .{ .repo_commits = .{ .name = try parseName(repo_route_max_len, helper.name), .after = helper.after } }, 349 .repo_settings => .{ .repo_settings = try parseName(repo_route_max_len, helper.name) }, 350 .repo_auth => .{ .repo_auth = try parseName(repo_route_max_len, helper.name) }, 351 }; 352 } 353 }; 354 355 // per-connection mutable state. each SSH session / web session / local TUI 356 // run gets its own. 357 pub const Session = struct { 358 data: Data = .{}, 359 // session-lifetime allocations: login/user_id, persisted prefs, queued 360 // actions. lives as long as the connection. 361 arena: *std.heap.ArenaAllocator, 362 // current page's allocations: page data and the page-scoped strings widgets 363 // build (form actions, links). owned by Nav, swapped on each navigation, so 364 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 365 // where a render is one-shot, this points at the same arena as `arena`. 366 page_arena: *std.heap.ArenaAllocator, 367 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 368 // filesystem io and the path to <server>/repos, for opening on-disk repos 369 // during page construction. both null on wasm, which has no filesystem and 370 // rebuilds pages from the serialized snapshot rather than from disk. 371 io: ?std.Io = null, 372 repos_dir: ?[]const u8 = null, 373 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 374 // focus id -> the live TextInput, refreshed each frame by the views that own 375 // inputs. web/wasm form handling looks widgets up here by focus id. 376 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 377 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 378 // a requested forward navigation. set this (via navigate) to move to a new 379 // page; Nav.sync builds it and then copies it into current_page, clearing 380 // this back to null. setting current_page directly only updates the url and 381 // does not navigate. 382 next_page: ?RoutablePage = null, 383 is_terminal: bool = false, // true on remote SSH and local TUI 384 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 385 // url. null on the web itself (no footer there). 386 web_port: ?u16 = null, 387 quit_requested: bool = false, 388 389 const Self = @This(); 390 391 // serializable data sent down to web client 392 pub const Data = struct { 393 user_id: ?[]const u8 = null, 394 // a transient outcome to surface from the last /login POST attempt 395 login_failure: ?Home.Auth.Login.Failure = null, 396 current_page: RoutablePage = .default, 397 // whether to render the ANSI art backdrop 398 enable_ansi: bool = false, 399 }; 400 401 // a user-initiated state change. widgets enqueue these on the session during 402 // input instead of mutating state or touching the DB themselves; the host 403 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 404 // side effects out of the widget tree and gives every render path one place to 405 // turn a UI action into a state change + event. 406 pub const Action = union(enum) { 407 toggle_ansi, 408 }; 409 410 pub fn init( 411 arena: *std.heap.ArenaAllocator, 412 repo: *rp.Repo(.xit, evt.admin_repo_opts), 413 data: Data, 414 ) !Self { 415 var session = Self{ 416 .data = data, 417 .arena = arena, 418 // until a host swaps in a page-scoped arena (Nav does this), page 419 // allocations land in the session arena. on the web path that's the 420 // intended behavior, since the whole arena is per-request. 421 .page_arena = arena, 422 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 423 }; 424 try session.loadUserPrefs(); 425 return session; 426 } 427 428 // load the logged-in user's persisted preferences from the db 429 pub fn loadUserPrefs(self: *Self) !void { 430 const user_id = self.data.user_id orelse return; 431 const moment = self.haxy_moment orelse return; 432 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 433 self.data.enable_ansi = user.enable_ansi; 434 } 435 } 436 437 // queue an action for the host to drain this frame. 438 pub fn push(self: *Self, action: Action) !void { 439 try self.pending.append(self.arena.allocator(), action); 440 } 441 442 // apply a single action's in-memory effect only (no persistence). 443 fn apply(self: *Self, action: Action) void { 444 switch (action) { 445 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 446 } 447 } 448 449 // drain the session's queued actions by applying them to the session. 450 // used on the wasm path, which has no repo to persist to. 451 pub fn applyPending(self: *Self) void { 452 for (self.pending.items) |action| self.apply(action); 453 self.pending.clearRetainingCapacity(); 454 } 455 456 // drain the session's queued actions by applying them to the session and 457 // writing them to the db 458 pub fn applyAndWritePending( 459 self: *Self, 460 io: std.Io, 461 allocator: std.mem.Allocator, 462 repo: *rp.Repo(.xit, evt.admin_repo_opts), 463 ) !void { 464 defer self.pending.clearRetainingCapacity(); 465 for (self.pending.items) |action| { 466 self.apply(action); 467 switch (action) { 468 .toggle_ansi => if (self.data.user_id) |user_id| { 469 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 470 }, 471 } 472 } 473 } 474 475 // request a forward navigation to `route`; Nav.sync builds it next 476 fn navigate(self: *Session, route: RoutablePage) !void { 477 self.next_page = route; 478 } 479 }; 480 481 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session) !void { 482 var nav = try Nav.init(allocator, session); 483 defer nav.deinit(allocator); 484 485 var terminal = try term.Terminal.init(io, allocator); 486 defer terminal.deinit(io); 487 488 // set term as active so it will be properly cooked 489 // when a panic/segfault happens 490 term.setActive(&terminal); 491 defer term.setActive(null); 492 493 var last_size = layout.Size{ .width = 0, .height = 0 }; 494 var last_grid = try Grid.init(allocator, last_size); 495 defer last_grid.deinit(); 496 497 while (!terminal.shouldQuit()) { 498 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 499 500 // process any inputs. 501 // 502 // if the grid didn't change, then first do a blocking 503 // read, so the thread will sleep until further input. 504 // after that, all remaining reads are non-blocking so 505 // we can process the rest of the queued inputs. 506 // 507 // if the grid *did* change, then only do non-blocking 508 // reads. we do not want to sleep the thread because 509 // there may be an animation that requires more looping. 510 var blocking = !grid_changed; 511 while (try terminal.readKey(io, blocking)) |key| { 512 blocking = false; 513 try inputKey(allocator, &nav.root, key, session); 514 } 515 516 // local run has no repo to persist to, so just apply in-memory 517 session.applyPending(); 518 519 // reconcile navigation: forward to a new page, or back on escape. 520 try nav.sync(allocator, session); 521 522 // the quit button (on the quit tab) asks the host to tear down. 523 if (session.quit_requested) terminal.requestQuit(); 524 525 try nav.root.build(allocator, .{ 526 .min_size = .{ .width = null, .height = null }, 527 .max_size = .{ .width = last_size.width, .height = last_size.height }, 528 }, nav.root.getFocus()); 529 } 530 } 531 532 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: inp.Key, session: *Session) !void { 533 switch (key) { 534 // request a navigation pop; the host's Nav.sync goes back a page, or 535 // quits when there's no history left. 536 .escape => session.nav_back = true, 537 .enter => { 538 const root_focus = root.getFocus(); 539 if (root_focus.grandchild_id) |gid| { 540 // follow a cross-page link 541 if (crossPageLink(root_focus, gid, session.data.current_page)) |route| { 542 return session.navigate(route); 543 } 544 } 545 try root.input(allocator, key, root_focus); 546 }, 547 .mouse => |mouse| { 548 if (mouse.action == .press and mouse.action.press == .left) { 549 const root_focus = root.getFocus(); 550 var clicked: ?usize = null; 551 var iter = root_focus.children.iterator(); 552 while (iter.next()) |entry| { 553 const child = entry.value_ptr.*; 554 if (!child.focus.focusable) continue; 555 const r = child.rect; 556 if (mouse.x >= r.x and mouse.y >= r.y and 557 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 558 { 559 clicked = entry.key_ptr.*; 560 break; 561 } 562 } 563 if (clicked) |focus_id| { 564 // follow a cross-page link 565 if (crossPageLink(root_focus, focus_id, session.data.current_page)) |route| { 566 return session.navigate(route); 567 } 568 try root_focus.setFocus(focus_id); 569 } 570 // forward the press into the widget tree so buttons (and any 571 // future click-aware widgets) can react. widgets that don't 572 // care about presses ignore it. 573 try root.input(allocator, key, root.getFocus()); 574 } else { 575 try root.input(allocator, key, root.getFocus()); 576 } 577 }, 578 else => try root.input(allocator, key, root.getFocus()), 579 } 580 } 581 582 // if the focus target at focus_id is an `a:` link that should navigate (a 583 // different parent page, or a different files directory within the repo page), 584 // return its route; otherwise null. lets a host turn a click / enter on such a 585 // link into a navigation rather than a focus change. 586 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, current: RoutablePage) ?RoutablePage { 587 const child = root_focus.children.get(focus_id) orelse return null; 588 const custom = switch (child.focus.kind) { 589 .custom => |c| c, 590 else => return null, 591 }; 592 const a_prefix = "a:"; 593 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 594 const url = custom[a_prefix.len..]; 595 const q = std.mem.indexOfScalar(u8, url, '?'); 596 const route = RoutablePage.fromUrl(if (q) |i| url[0..i] else url, if (q) |i| url[i + 1 ..] else null) orelse return null; 597 // a link to a different parent page always navigates; within the repo page, 598 // a files-directory link navigates while settings/auth tab links stay 599 // in-page (header-handled). 600 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current)) return route; 601 return null; 602 } 603 604 // native-TUI navigation 605 pub const Nav = struct { 606 root: Widget, 607 route: RoutablePage, 608 // backs the current page (its Page data and the page-scoped strings its 609 // widgets build). owned here, swapped on each navigation. session.page_arena 610 // tracks whichever of these is current so widgets allocate into it. 611 arena: *std.heap.ArenaAllocator, 612 history: std.ArrayList(Entry), 613 614 // each retained page keeps its own arena, freed when the page leaves the 615 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 616 // long-lived session from accumulating every page it ever visited. 617 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 618 619 // cap on retained back-history so the chain can't grow memory without bound 620 const max_history: usize = 16; 621 622 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 623 const arena = try allocator.create(std.heap.ArenaAllocator); 624 arena.* = std.heap.ArenaAllocator.init(allocator); 625 errdefer { 626 arena.deinit(); 627 allocator.destroy(arena); 628 } 629 630 session.page_arena = arena; 631 const route = session.data.current_page; 632 633 const page = try arena.allocator().create(Page); 634 page.* = try Page.init(arena, session, route); 635 return .{ 636 .root = try initRoot(allocator, page, session), 637 .route = route, 638 .arena = arena, 639 .history = .empty, 640 }; 641 } 642 643 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 644 self.root.deinit(allocator); 645 freeArena(allocator, self.arena); 646 for (self.history.items) |*entry| { 647 entry.root.deinit(allocator); 648 freeArena(allocator, entry.arena); 649 } 650 self.history.deinit(allocator); 651 } 652 653 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 654 arena.deinit(); 655 allocator.destroy(arena); 656 } 657 658 // reconcile the displayed root with the session's navigation state. a 659 // forward nav (current_page moved to a different parent page) pushes the 660 // current root and builds the new page in a fresh arena; a back request 661 // frees the current page and restores the previous one. when escape is 662 // pressed with no history left we switch to the quit tab instead of quitting. 663 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 664 if (session.nav_back) { 665 session.nav_back = false; 666 if (self.history.pop()) |entry| { 667 self.root.deinit(allocator); 668 freeArena(allocator, self.arena); 669 self.root = entry.root; 670 self.route = entry.route; 671 self.arena = entry.arena; 672 session.page_arena = entry.arena; 673 session.data.current_page = entry.route; 674 return; 675 } 676 // nothing to go back to; switch to the quit confirmation 677 const root_focus = self.root.getFocus(); 678 var iter = root_focus.children.iterator(); 679 while (iter.next()) |entry| { 680 switch (entry.value_ptr.focus.kind) { 681 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 682 try root_focus.setFocus(entry.key_ptr.*); 683 // a Stack only builds its selected child, so the quit 684 // button isn't in the focus tree until a build runs with 685 // the quit tab selected. build once, then send a 686 // synthetic arrow_down to drop focus from the tab onto 687 // the button so it's ready to confirm. 688 try self.root.build(allocator, .{ 689 .min_size = .{ .width = null, .height = 40 }, 690 .max_size = .{ .width = 80, .height = null }, 691 }, root_focus); 692 try self.root.input(allocator, .arrow_down, root_focus); 693 break; 694 }, 695 else => {}, 696 } 697 } 698 return; 699 } 700 701 // forward navigation: navigate() set next_page to the page to move to (a 702 // cross-page link or tab change crossing pages) 703 if (session.next_page) |route| { 704 session.next_page = null; 705 if (session.haxy_moment == null) return; 706 // the page we navigated to becomes the current page 707 session.data.current_page = route; 708 709 const arena = try allocator.create(std.heap.ArenaAllocator); 710 arena.* = std.heap.ArenaAllocator.init(allocator); 711 errdefer freeArena(allocator, arena); 712 713 session.page_arena = arena; 714 715 const page = try arena.allocator().create(Page); 716 page.* = try Page.init(arena, session, route); 717 const new_root = try initRoot(allocator, page, session); 718 719 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 720 // drop the oldest entry (freeing its widget tree and arena) once over cap 721 if (self.history.items.len > max_history) { 722 var oldest = self.history.orderedRemove(0); 723 oldest.root.deinit(allocator); 724 freeArena(allocator, oldest.arena); 725 } 726 self.root = new_root; 727 self.route = route; 728 self.arena = arena; 729 } 730 } 731 }; 732 733 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 734 const page_widget: Widget = switch (page.*) { 735 .home => |*p| .{ .home = try .init(allocator, p, session) }, 736 .user => |*p| .{ .user = try .init(allocator, p, session) }, 737 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 738 }; 739 740 const demon_art = @embedFile("embed/demon.ans"); 741 742 // on the TUI/SSH, the page sits above a one-row footer showing the url 743 var root = if (session.is_terminal) blk: { 744 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 745 errdefer box.deinit(allocator); 746 const bg_id = bg_blk: { 747 var background = try AnsiBackground.init(allocator, page_widget, demon_art, session); 748 errdefer background.deinit(allocator); 749 const id = background.getFocus().id; 750 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 751 break :bg_blk id; 752 }; 753 { 754 var footer = try Footer.init(allocator, session); 755 errdefer footer.deinit(allocator); 756 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 757 } 758 box.getFocus().child_id = bg_id; 759 break :blk Widget{ .box = box }; 760 } else Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 761 errdefer root.deinit(allocator); 762 763 // input-owning views build their TextInputs in init — so reset the 764 // focus-id -> *TextInput map here 765 session.text_inputs.clearRetainingCapacity(); 766 767 try root.build(allocator, .{ 768 .min_size = .{ .width = null, .height = 40 }, 769 .max_size = .{ .width = 80, .height = null }, 770 }, root.getFocus()); 771 if (root.getFocus().child_id) |child_id| { 772 try root.getFocus().setFocus(child_id); 773 } 774 775 return root; 776 } 777 778 pub const Widget = union(enum) { 779 text: wgt.Text(Widget), 780 box: wgt.Box(Widget), 781 text_box: wgt.TextBox(Widget), 782 text_input: wgt.TextInput(Widget), 783 scroll: wgt.Scroll(Widget), 784 stack: wgt.Stack(Widget), 785 flow_box: FlowBox, 786 flow_box_scroll: FlowBox.Scroll, 787 spacer: Spacer, 788 center: Center, 789 ansi_art: AnsiArt, 790 background: AnsiBackground, 791 home: Home.View, 792 user: User.View, 793 repo: Repo.View, 794 quit: Quit.View, 795 title: Title.View, 796 home_header: Home.Header.View, 797 user_header: User.Header.View, 798 repo_header: Repo.Header.View, 799 repo_files: Repo.Files.View, 800 repo_commits: Repo.Commits.View, 801 home_users: Home.Users.View, 802 home_repos: Home.Repos.View, 803 auth_tab: Home.Header.AuthTab.View, 804 home_settings: Home.Settings.View, 805 home_auth: Home.Auth.View, 806 footer: Footer, 807 808 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 809 switch (self.*) { 810 inline else => |*case| case.deinit(allocator), 811 } 812 } 813 814 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 815 switch (self.*) { 816 inline else => |*case| try case.build(allocator, constraint, root_focus), 817 } 818 } 819 820 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) anyerror!void { 821 switch (self.*) { 822 inline else => |*case| try case.input(allocator, key, root_focus), 823 } 824 } 825 826 pub fn clearGrid(self: *Widget) void { 827 switch (self.*) { 828 inline else => |*case| case.clearGrid(), 829 } 830 } 831 832 pub fn getGrid(self: Widget) ?Grid { 833 switch (self) { 834 inline else => |*case| return case.getGrid(), 835 } 836 } 837 838 pub fn getFocus(self: *Widget) *Focus { 839 switch (self.*) { 840 inline else => |*case| return case.getFocus(), 841 } 842 } 843 }; 844 845 pub const FlowBox = struct { 846 focus: *Focus, 847 grid: ?Grid, 848 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 849 // backs the per-item strings the text boxes borrow: each box's `content` 850 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 851 // wholesale on each setItems so there's no per-string ownership to track. 852 arena: std.heap.ArenaAllocator, 853 // column count from the last build — FlowBox.Scroll.input uses it so arrow 854 // up/down can step by a row's worth of items. 855 last_cols: usize, 856 options: Options, 857 858 const border_rows: usize = 2; 859 860 pub const Options = struct { 861 cell_width: usize = 40, 862 cell_height: usize = 3, 863 }; 864 865 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 866 return .{ 867 .focus = try Focus.create(allocator, .container), 868 .grid = null, 869 .text_boxes = .empty, 870 .arena = std.heap.ArenaAllocator.init(allocator), 871 .last_cols = 1, 872 .options = options, 873 }; 874 } 875 876 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 877 self.focus.destroy(allocator); 878 if (self.grid) |*grid| { 879 grid.deinit(); 880 self.grid = null; 881 } 882 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 883 self.text_boxes.deinit(allocator); 884 self.arena.deinit(); 885 } 886 887 // `links`, when given, is parallel to `items`: a non-empty entry sets that 888 // item's focus kind to `.{ .custom = link }` (e.g. "a:/user/foo"), which the 889 // web renderer turns into an anchor. pass null when items aren't links. 890 // both the item text and the link are copied into the arena, so the caller's 891 // slices needn't outlive this call. 892 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const []const u8, links: ?[]const []const u8) !void { 893 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 894 self.text_boxes.clearAndFree(allocator); 895 896 // the old text boxes (and their borrowed content/links) are gone now, so 897 // the arena that backed those strings can be reclaimed. 898 _ = self.arena.reset(.retain_capacity); 899 const aa = self.arena.allocator(); 900 901 self.focus.clear(); 902 self.focus.child_id = null; 903 904 for (items, 0..) |item, i| { 905 const line = try aa.dupe(u8, item); 906 907 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 908 errdefer text_box.deinit(allocator); 909 text_box.getFocus().focusable = true; 910 911 if (links) |link_items| { 912 if (i < link_items.len and link_items[i].len > 0) { 913 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, link_items[i]) }; 914 } 915 } 916 917 try self.text_boxes.append(allocator, text_box); 918 } 919 920 if (self.text_boxes.items.len > 0) { 921 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 922 } 923 } 924 925 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 926 self.clearGrid(); 927 self.focus.clear(); 928 929 const cell_width = self.options.cell_width; 930 const max_width = constraint.max_size.width orelse cell_width; 931 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 932 self.last_cols = cols; 933 934 const count = self.text_boxes.items.len; 935 if (count == 0) return; 936 const slot_height = self.options.cell_height + border_rows; 937 if (slot_height == 0) return; 938 939 // build at the slot size so every text box fits a single grid cell 940 for (self.text_boxes.items) |*tb| { 941 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 942 try tb.build(allocator, .{ 943 .min_size = .{ .width = cell_width, .height = null }, 944 .max_size = .{ .width = cell_width, .height = slot_height }, 945 }, root_focus); 946 } 947 948 const rows = (count + cols - 1) / cols; 949 const content_height = rows * slot_height; 950 const total_width = cols * cell_width; 951 if (total_width == 0 or content_height == 0) return; 952 953 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 954 errdefer grid.deinit(); 955 956 for (self.text_boxes.items, 0..) |*tb, i| { 957 const tb_grid = tb.getGrid() orelse continue; 958 const col = i % cols; 959 const row = i / cols; 960 const cell_x = col * cell_width; 961 const cell_y = row * slot_height; 962 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 963 try grid.drawGrid(tb_grid, cell_x, cell_y); 964 } 965 966 self.grid = grid; 967 } 968 969 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 970 _ = self; 971 _ = allocator; 972 _ = key; 973 _ = root_focus; 974 } 975 976 pub fn clearGrid(self: *FlowBox) void { 977 if (self.grid) |*grid| { 978 grid.deinit(); 979 self.grid = null; 980 } 981 for (self.text_boxes.items) |*tb| tb.clearGrid(); 982 } 983 984 pub fn getGrid(self: FlowBox) ?Grid { 985 return self.grid; 986 } 987 988 pub fn getFocus(self: *FlowBox) *Focus { 989 return self.focus; 990 } 991 992 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 993 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 994 const slot_height = self.options.cell_height + border_rows; 995 const col = index % self.last_cols; 996 const row = index / self.last_cols; 997 return .{ 998 .x = @intCast(col * self.options.cell_width), 999 .y = @intCast(row * slot_height), 1000 .size = .{ .width = self.options.cell_width, .height = slot_height }, 1001 }; 1002 } 1003 1004 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 1005 for (self.text_boxes.items, 0..) |tb, i| { 1006 if (tb.box.focus.id == focus_id) return i; 1007 } 1008 return null; 1009 } 1010 1011 pub const Scroll = struct { 1012 scroll: wgt.Scroll(Widget), 1013 1014 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options) !Scroll { 1015 var layout_inner = try FlowBox.init(allocator, options); 1016 errdefer layout_inner.deinit(allocator); 1017 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert }); 1018 errdefer scroll.deinit(allocator); 1019 return .{ .scroll = scroll }; 1020 } 1021 1022 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 1023 self.scroll.deinit(allocator); 1024 } 1025 1026 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const []const u8, links: ?[]const []const u8) !void { 1027 self.scroll.x = 0; 1028 self.scroll.y = 0; 1029 try self.inner().setItems(allocator, items, links); 1030 } 1031 1032 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1033 try self.scroll.build(allocator, constraint, root_focus); 1034 } 1035 1036 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1037 _ = allocator; 1038 const in = self.inner(); 1039 const child_id = in.focus.child_id orelse return; 1040 const current_index = in.indexOfFocusId(child_id) orelse return; 1041 const count = in.text_boxes.items.len; 1042 if (count == 0) return; 1043 const cols = in.last_cols; 1044 const slot_height = in.options.cell_height + FlowBox.border_rows; 1045 1046 var index = current_index; 1047 switch (key) { 1048 .arrow_up => index -|= cols, 1049 .arrow_down => if (index + cols < count) { 1050 index += cols; 1051 }, 1052 .arrow_left => index -|= 1, 1053 .arrow_right => if (index + 1 < count) { 1054 index += 1; 1055 }, 1056 .home => index = 0, 1057 .end => index = count - 1, 1058 .page_up => { 1059 if (self.scroll.grid) |grid| if (slot_height > 0) { 1060 const rows_per_page = grid.size.height / slot_height; 1061 index -|= rows_per_page * cols; 1062 }; 1063 }, 1064 .page_down => { 1065 if (self.scroll.grid) |grid| if (slot_height > 0) { 1066 const rows_per_page = grid.size.height / slot_height; 1067 index = @min(index + rows_per_page * cols, count - 1); 1068 }; 1069 }, 1070 // scroll wheel moves the focused cell by a full row so the 1071 // viewport (via scrollToRect) follows in row-sized steps, 1072 // matching how a scroll wheel feels in a grid view. 1073 .mouse => |mouse| switch (mouse.action) { 1074 .scroll => |dir| switch (dir) { 1075 .up => index -|= cols, 1076 .down => if (index + cols < count) { 1077 index += cols; 1078 }, 1079 }, 1080 else => {}, 1081 }, 1082 else => {}, 1083 } 1084 1085 if (index != current_index) { 1086 try root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 1087 if (in.cellRect(index)) |rect| { 1088 self.scroll.scrollToRect(rect); 1089 } 1090 } 1091 } 1092 1093 pub fn clearGrid(self: *Scroll) void { 1094 self.scroll.clearGrid(); 1095 } 1096 1097 pub fn getGrid(self: Scroll) ?Grid { 1098 return self.scroll.getGrid(); 1099 } 1100 1101 pub fn getFocus(self: *Scroll) *Focus { 1102 return self.scroll.getFocus(); 1103 } 1104 1105 pub fn getSelectedIndex(self: Scroll) ?usize { 1106 const in = self.scroll.child.flow_box; 1107 const child_id = in.focus.child_id orelse return null; 1108 return in.indexOfFocusId(child_id); 1109 } 1110 1111 fn inner(self: *Scroll) *FlowBox { 1112 return &self.scroll.child.flow_box; 1113 } 1114 }; 1115 }; 1116 1117 // an invisible widget that fills the horizontal space granted by its parent. 1118 // used inside Box(horiz) with a min_size so the box reserves space for the 1119 // children that follow, pushing them to the right. 1120 pub const Spacer = struct { 1121 focus: *Focus, 1122 grid: ?Grid, 1123 1124 pub fn init(allocator: std.mem.Allocator) !Spacer { 1125 return .{ 1126 .focus = try Focus.create(allocator, .container), 1127 .grid = null, 1128 }; 1129 } 1130 1131 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 1132 self.focus.destroy(allocator); 1133 if (self.grid) |*grid| { 1134 grid.deinit(); 1135 self.grid = null; 1136 } 1137 } 1138 1139 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1140 _ = root_focus; 1141 self.clearGrid(); 1142 const width = constraint.max_size.width orelse return; 1143 if (width == 0) return; 1144 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1145 } 1146 1147 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1148 _ = self; 1149 _ = allocator; 1150 _ = key; 1151 _ = root_focus; 1152 } 1153 1154 pub fn clearGrid(self: *Spacer) void { 1155 if (self.grid) |*grid| { 1156 grid.deinit(); 1157 self.grid = null; 1158 } 1159 } 1160 1161 pub fn getGrid(self: Spacer) ?Grid { 1162 return self.grid; 1163 } 1164 1165 pub fn getFocus(self: *Spacer) *Focus { 1166 return self.focus; 1167 } 1168 }; 1169 1170 // a one-row, non-focusable status bar showing the current page's url 1171 pub const Footer = struct { 1172 focus: *Focus, 1173 grid: ?Grid, 1174 session: *Session, 1175 arena: std.heap.ArenaAllocator, 1176 1177 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 1178 return .{ 1179 .focus = try Focus.create(allocator, .container), 1180 .grid = null, 1181 .session = session, 1182 .arena = std.heap.ArenaAllocator.init(allocator), 1183 }; 1184 } 1185 1186 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 1187 self.focus.destroy(allocator); 1188 if (self.grid) |*grid| grid.deinit(); 1189 self.arena.deinit(); 1190 } 1191 1192 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1193 _ = root_focus; 1194 self.clearGrid(); 1195 const width = constraint.max_size.width orelse return; 1196 if (width == 0) return; 1197 1198 _ = self.arena.reset(.retain_capacity); 1199 const aa = self.arena.allocator(); 1200 const path = self.session.data.current_page.urlAlloc(&self.arena) catch return; 1201 const text = if (self.session.web_port) |port| 1202 std.fmt.allocPrint(aa, "http://localhost:{d}{s}", .{ port, path }) catch return 1203 else 1204 path; 1205 1206 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1207 errdefer grid.deinit(); 1208 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 1209 var i: usize = 0; 1210 while (utf8.nextCodepointSlice()) |ch| { 1211 if (i == width) break; 1212 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 1213 i += 1; 1214 } 1215 self.grid = grid; 1216 } 1217 1218 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1219 _ = self; 1220 _ = allocator; 1221 _ = key; 1222 _ = root_focus; 1223 } 1224 1225 pub fn clearGrid(self: *Footer) void { 1226 if (self.grid) |*grid| { 1227 grid.deinit(); 1228 self.grid = null; 1229 } 1230 } 1231 1232 pub fn getGrid(self: Footer) ?Grid { 1233 return self.grid; 1234 } 1235 1236 pub fn getFocus(self: *Footer) *Focus { 1237 return self.focus; 1238 } 1239 }; 1240 1241 // a single-child wrapper that builds the child at its natural size and 1242 // positions its grid in the middle of the area granted by the parent 1243 pub const Center = struct { 1244 focus: *Focus, 1245 grid: ?Grid, 1246 child: *Widget, 1247 direction: Direction, 1248 1249 pub const Direction = enum { both, horiz, vert }; 1250 1251 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, direction: Direction) !Center { 1252 const child = try allocator.create(Widget); 1253 errdefer allocator.destroy(child); 1254 child.* = child_widget; 1255 return .{ 1256 .focus = try Focus.create(allocator, .container), 1257 .grid = null, 1258 .child = child, 1259 .direction = direction, 1260 }; 1261 } 1262 1263 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 1264 self.focus.destroy(allocator); 1265 if (self.grid) |*grid| { 1266 grid.deinit(); 1267 self.grid = null; 1268 } 1269 self.child.deinit(allocator); 1270 allocator.destroy(self.child); 1271 } 1272 1273 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1274 self.clearGrid(); 1275 self.getFocus().clear(); 1276 1277 // build the child without forcing it to fill min_size; it sizes 1278 // itself to its content within the available max. 1279 try self.child.build(allocator, .{ 1280 .min_size = .{ .width = null, .height = null }, 1281 .max_size = constraint.max_size, 1282 }, root_focus); 1283 1284 const child_grid = self.child.getGrid() orelse return; 1285 1286 // prefer max when given; otherwise grow to max(min, child) so that 1287 // when only a min is set (e.g. the wasm path passes viewport rows 1288 // as min_height with no max), we can still vertically center while 1289 // letting taller content extend past the min. 1290 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; 1291 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; 1292 if (width == 0 or height == 0) return; 1293 1294 const offset_x: usize = if (self.direction == .horiz or self.direction == .both) 1295 (width -| child_grid.size.width) / 2 1296 else 1297 0; 1298 const offset_y: usize = if (self.direction == .vert or self.direction == .both) 1299 (height -| child_grid.size.height) / 2 1300 else 1301 0; 1302 1303 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 1304 errdefer grid.deinit(); 1305 try grid.drawGrid(child_grid, offset_x, offset_y); 1306 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 1307 self.getFocus().child_id = self.child.getFocus().id; 1308 1309 self.grid = grid; 1310 } 1311 1312 pub fn input(self: *Center, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1313 try self.child.input(allocator, key, root_focus); 1314 } 1315 1316 pub fn clearGrid(self: *Center) void { 1317 if (self.grid) |*grid| { 1318 grid.deinit(); 1319 self.grid = null; 1320 } 1321 self.child.clearGrid(); 1322 } 1323 1324 pub fn getGrid(self: Center) ?Grid { 1325 return self.grid; 1326 } 1327 1328 pub fn getFocus(self: *Center) *Focus { 1329 return self.focus; 1330 } 1331 }; 1332 1333 // renders truecolor ANSI art 1334 pub const AnsiArt = struct { 1335 focus: *Focus, 1336 grid: ?Grid, 1337 content: []const u8, 1338 1339 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 1340 return .{ 1341 .focus = try Focus.create(allocator, .container), 1342 .grid = null, 1343 .content = content, 1344 }; 1345 } 1346 1347 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 1348 self.focus.destroy(allocator); 1349 if (self.grid) |*grid| { 1350 grid.deinit(); 1351 self.grid = null; 1352 } 1353 } 1354 1355 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1356 _ = root_focus; 1357 self.clearGrid(); 1358 1359 // parse into rows of cells, then copy into a rectangular grid 1360 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 1361 defer { 1362 for (rows.items) |*row| row.deinit(allocator); 1363 rows.deinit(allocator); 1364 } 1365 var row: std.ArrayList(Grid.Cell) = .empty; 1366 errdefer row.deinit(allocator); 1367 1368 var style: Grid.Style = .{}; 1369 var width: usize = 0; 1370 const content = self.content; 1371 var i: usize = 0; 1372 while (i < content.len) { 1373 const byte = content[i]; 1374 if (byte == '\n') { 1375 width = @max(width, row.items.len); 1376 try rows.append(allocator, row); 1377 row = .empty; 1378 i += 1; 1379 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 1380 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 1381 var j = i + 2; 1382 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 1383 if (j >= content.len) { 1384 i = content.len; // malformed trailing escape; stop 1385 } else { 1386 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 1387 i = j + 1; 1388 } 1389 } else { 1390 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 1391 const end = @min(content.len, i + len); 1392 const rune = content[i..end]; 1393 const transparent = end - i == 1 and rune[0] == ' ' and 1394 style.fg == null and style.bg == null and !style.inverted; 1395 try row.append(allocator, .{ 1396 .rune = if (transparent) null else rune, 1397 .style = style, 1398 }); 1399 i = end; 1400 } 1401 } 1402 // a trailing row with content but no closing newline 1403 if (row.items.len > 0) { 1404 width = @max(width, row.items.len); 1405 try rows.append(allocator, row); 1406 } else { 1407 row.deinit(allocator); 1408 } 1409 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1410 1411 const height = rows.items.len; 1412 if (width == 0 or height == 0) return; 1413 1414 const clamped_w = @min(width, constraint.max_size.width orelse width); 1415 const clamped_h = @min(height, constraint.max_size.height orelse height); 1416 1417 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1418 errdefer grid.deinit(); 1419 for (rows.items[0..clamped_h], 0..) |r, y| { 1420 const n = @min(r.items.len, clamped_w); 1421 for (r.items[0..n], 0..) |cell, x| { 1422 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1423 } 1424 } 1425 self.grid = grid; 1426 } 1427 1428 pub fn input(self: *AnsiArt, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1429 _ = self; 1430 _ = allocator; 1431 _ = key; 1432 _ = root_focus; 1433 } 1434 1435 pub fn clearGrid(self: *AnsiArt) void { 1436 if (self.grid) |*grid| { 1437 grid.deinit(); 1438 self.grid = null; 1439 } 1440 } 1441 1442 pub fn getGrid(self: AnsiArt) ?Grid { 1443 return self.grid; 1444 } 1445 1446 pub fn getFocus(self: *AnsiArt) *Focus { 1447 return self.focus; 1448 } 1449 1450 fn applySgr(style: *Grid.Style, params: []const u8) void { 1451 var nums: [16]u32 = undefined; 1452 var n: usize = 0; 1453 var it = std.mem.splitScalar(u8, params, ';'); 1454 while (it.next()) |tok| { 1455 if (n >= nums.len) break; 1456 // an empty parameter (e.g. bare "\x1b[m") means 0 1457 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 1458 n += 1; 1459 } 1460 if (n == 0) { 1461 style.* = .{}; 1462 return; 1463 } 1464 var i: usize = 0; 1465 while (i < n) : (i += 1) { 1466 switch (nums[i]) { 1467 0 => style.* = .{}, 1468 7 => style.inverted = true, 1469 27 => style.inverted = false, 1470 39 => style.fg = null, 1471 49 => style.bg = null, 1472 38, 48 => { 1473 // truecolor form: 38;2;r;g;b — anything else is ignored 1474 if (i + 4 < n and nums[i + 1] == 2) { 1475 const c = Grid.Color{ 1476 .r = @truncate(nums[i + 2]), 1477 .g = @truncate(nums[i + 3]), 1478 .b = @truncate(nums[i + 4]), 1479 }; 1480 if (nums[i] == 38) style.fg = c else style.bg = c; 1481 i += 4; 1482 } 1483 }, 1484 else => {}, 1485 } 1486 } 1487 } 1488 }; 1489 1490 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 1491 pub const AnsiBackground = struct { 1492 grid: ?Grid, 1493 child: *Widget, 1494 art: AnsiArt, 1495 session: *Session, 1496 1497 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 1498 var cw = child_widget; 1499 const child = allocator.create(Widget) catch |e| { 1500 cw.deinit(allocator); 1501 return e; 1502 }; 1503 child.* = cw; 1504 errdefer { 1505 child.deinit(allocator); 1506 allocator.destroy(child); 1507 } 1508 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 1509 } 1510 1511 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 1512 if (self.grid) |*grid| grid.deinit(); 1513 self.art.deinit(allocator); 1514 self.child.deinit(allocator); 1515 allocator.destroy(self.child); 1516 } 1517 1518 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1519 self.clearGrid(); 1520 1521 // make the wrapped page fill the whole available area 1522 try self.child.build(allocator, .{ 1523 .min_size = .{ 1524 .width = constraint.max_size.width orelse constraint.min_size.width, 1525 .height = constraint.max_size.height orelse constraint.min_size.height, 1526 }, 1527 .max_size = constraint.max_size, 1528 }, root_focus); 1529 1530 if (self.session.data.enable_ansi) { 1531 if (self.child.getGrid()) |fg| { 1532 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 1533 } 1534 } 1535 } 1536 1537 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1538 try self.child.input(allocator, key, root_focus); 1539 } 1540 1541 pub fn clearGrid(self: *AnsiBackground) void { 1542 if (self.grid) |*grid| { 1543 grid.deinit(); 1544 self.grid = null; 1545 } 1546 self.child.clearGrid(); 1547 self.art.clearGrid(); 1548 } 1549 1550 pub fn getGrid(self: AnsiBackground) ?Grid { 1551 return self.grid orelse self.child.getGrid(); 1552 } 1553 1554 pub fn getFocus(self: *AnsiBackground) *Focus { 1555 return self.child.getFocus(); 1556 } 1557 1558 // which top corner the art hugs. 1559 const ArtAnchor = enum { top_left, top_right }; 1560 1561 // a foreground cell counts as blank if it's empty or a bare space without styling 1562 fn cellIsBlank(cell: Grid.Cell) bool { 1563 if (cell.rune) |rune| { 1564 return std.mem.eql(u8, rune, " ") and 1565 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 1566 } 1567 return true; 1568 } 1569 1570 // a single representative color for an art cell 1571 fn artCellColor(style: Grid.Style) ?Grid.Color { 1572 const f = style.fg orelse return style.bg; 1573 const b = style.bg orelse return f; 1574 return .{ 1575 .r = @intCast((@as(u16, f.r) + b.r) / 2), 1576 .g = @intCast((@as(u16, f.g) + b.g) / 2), 1577 .b = @intCast((@as(u16, f.b) + b.b) / 2), 1578 }; 1579 } 1580 1581 // behind a visible glyph the art color is dimmed to this fraction of its 1582 // brightness so light terminal text stays legible on top of it 1583 const glyph_bg_brightness = 45; // percent 1584 1585 // a glyph sitting over the art also gets its foreground pinned to this color 1586 // (unless it set its own), so the text stays legible 1587 const glyph_fg_over_art = Grid.Color{ .r = 235, .g = 235, .b = 235 }; 1588 1589 fn dimColor(color: ?Grid.Color) ?Grid.Color { 1590 const c = color orelse return null; 1591 return .{ 1592 .r = @intCast(@as(u16, c.r) * glyph_bg_brightness / 100), 1593 .g = @intCast(@as(u16, c.g) * glyph_bg_brightness / 100), 1594 .b = @intCast(@as(u16, c.b) * glyph_bg_brightness / 100), 1595 }; 1596 } 1597 1598 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 1599 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 1600 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 1601 // snap such channels clear of that range so the backdrop doesn't blink or 1602 // hide text there; the ≤9/255 shift is imperceptible on terminals that 1603 // actually render truecolor. 1604 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 1605 const c = color orelse return null; 1606 const snap = struct { 1607 fn f(v: u8) u8 { 1608 return if (v >= 1 and v <= 9) 10 else v; 1609 } 1610 }.f; 1611 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 1612 } 1613 1614 // composites ANSI art behind a foreground grid 1615 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 1616 art.clearGrid(); 1617 try art.build(allocator, .{ 1618 .min_size = .{ .width = null, .height = null }, 1619 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 1620 }, root_focus); 1621 1622 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 1623 errdefer out.deinit(); 1624 1625 if (art.getGrid()) |art_grid| { 1626 const anchor_x = switch (anchor) { 1627 .top_left => 0, 1628 .top_right => foreground.size.width -| art_grid.size.width, 1629 }; 1630 for (0..art_grid.size.height) |y| { 1631 for (0..art_grid.size.width) |x| { 1632 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 1633 if (src.rune == null) continue; 1634 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 1635 const dst = &out.cells.items[idx]; 1636 if (cellIsBlank(dst.*)) { 1637 dst.* = src; 1638 dst.style.fg = sgrSafe(dst.style.fg); 1639 dst.style.bg = sgrSafe(dst.style.bg); 1640 } else if (dst.style.bg == null) { 1641 dst.style.bg = sgrSafe(dimColor(artCellColor(src.style))); 1642 if (dst.style.fg == null) dst.style.fg = glyph_fg_over_art; 1643 } 1644 } 1645 } 1646 } 1647 return out; 1648 } 1649 }; 1650