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