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