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