╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
1970 std.mem.eql(u8, a_f.oid.slice(), b.fork_files.oid.slice()) and 1971 std.mem.eql(u8, a_f.find.slice(), b.fork_files.find.slice()) and 1972 std.mem.eql(u8, a_f.path.slice(), b.fork_files.path.slice()) and 1973 a_f.line == b.fork_files.line, 1974 .fork_commits => |a_c| std.mem.eql(u8, a_c.fork.name.slice(), b.fork_commits.fork.name.slice()) and 1975 std.mem.eql(u8, a_c.fork.id.slice(), b.fork_commits.fork.id.slice()) and 1976 std.mem.eql(u8, a_c.oid.slice(), b.fork_commits.oid.slice()) and 1977 a_c.message == b.fork_commits.message, 1978 .fork_delete => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_delete.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_delete.id.slice()), 1979 .fork_repo_new => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_repo_new.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_repo_new.id.slice()), 1980 .fork_user_new => |a_f| std.mem.eql(u8, a_f.name.slice(), b.fork_user_new.name.slice()) and std.mem.eql(u8, a_f.id.slice(), b.fork_user_new.id.slice()), 1981 .fork_user => |a_u| std.mem.eql(u8, a_u.fork.name.slice(), b.fork_user.fork.name.slice()) and 1982 std.mem.eql(u8, a_u.fork.id.slice(), b.fork_user.fork.id.slice()) and 1983 a_u.tab.eql(b.fork_user.tab), 1984 else => true, 1985 }; 1986 } 1987 1988 // true when following a link from `b` to `a` (both repo routes) should reload 1989 // rather than stay in page 1990 pub fn repoPageChanged(a: RoutablePage, b: RoutablePage) bool { 1991 if (a.parent() != .repo or b.parent() != .repo) return false; 1992 if (std.meta.activeTag(a) == .repo_refs and std.meta.activeTag(b) == .repo_refs and 1993 a.repo_refs.from.len == 0 and b.repo_refs.from.len == 0) 1994 return !std.mem.eql(u8, a.repo_refs.name.slice(), b.repo_refs.name.slice()); 1995 return !a.eql(b); 1996 } 1997 1998 pub fn forkPageChanged(a: RoutablePage, b: RoutablePage) bool { 1999 return a.parent() == .fork and b.parent() == .fork and !a.eql(b); 2000 } 2001 2002 // true when `a` and `b` are the same user paginated to a different repos 2003 // window or search. switching between a user's tabs is in-page, so only a 2004 // changed `start` or search on the same list navigates. 2005 pub fn userPageChanged(a: RoutablePage, b: RoutablePage) bool { 2006 return switch (a) { 2007 .user_repos => |aa| switch (b) { 2008 .user_repos => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and !a.eql(b), 2009 else => false, 2010 }, 2011 .user_forks => |aa| switch (b) { 2012 .user_forks => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and aa.start != bb.start, 2013 else => false, 2014 }, 2015 .user_user => |aa| switch (b) { 2016 .user_user => |bb| std.mem.eql(u8, aa.name.slice(), bb.name.slice()) and !a.eql(b), 2017 else => false, 2018 }, 2019 else => false, 2020 }; 2021 } 2022 2023 // true when `a` and `b` are the same home list tab paginated to a different 2024 // window or search. switching tabs is in-page, so only a changed `start` or 2025 // search on the same tab navigates. 2026 pub fn homePageChanged(a: RoutablePage, b: RoutablePage) bool { 2027 return switch (a) { 2028 .home_users => switch (b) { 2029 .home_users => !a.eql(b), 2030 else => false, 2031 }, 2032 .home_user => switch (b) { 2033 .home_user => !a.eql(b), 2034 else => false, 2035 }, 2036 else => false, 2037 }; 2038 } 2039 }; 2040 2041 // a `RefOrOid` resolved against an on-disk repo to the commit oid it points at 2042 fn isUnreserved(c: u8) bool { 2043 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 2044 } 2045 2046 // percent-encode a ref name for use as a single url path segment. 2047 pub fn urlEncodeRef(aa: std.mem.Allocator, raw: []const u8) ![]const u8 { 2048 var out: std.Io.Writer.Allocating = .init(aa); 2049 try std.Uri.Component.percentEncode(&out.writer, raw, isUnreserved); 2050 return out.written(); 2051 } 2052 2053 // a resolved ref/oid for a repo opened with `repo_kind`/`repo_opts` 2054 pub fn ResolvedRefOrOid(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2055 return struct { 2056 pub const hex_len = hash.hexLen(repo_opts.hash); 2057 2058 // the concrete ref/oid (a null request resolves to the default branch) 2059 ref_or_oid: RoutablePage.RefOrOid, 2060 // its branch/tag name or oid, url-encoded (ref names may contain '/', so 2061 // the route layer — which splits on '/' — stores them encoded). duped 2062 // into `aa`. 2063 value: []const u8, 2064 // the commit oid it points at 2065 oid: [hex_len]u8, 2066 2067 const Self = @This(); 2068 2069 // resolve a requested ref/oid (null = the repo's default branch) to a 2070 // concrete ref/oid plus the commit oid it points at. `requested_value` is 2071 // the url-encoded form (as it appears in the route). null when it doesn't 2072 // resolve (an unknown branch/tag, or a malformed/unknown oid). 2073 pub fn init( 2074 repo: *rp.Repo(repo_kind, repo_opts), 2075 io: std.Io, 2076 aa: std.mem.Allocator, 2077 requested_ref_or_oid: ?RoutablePage.RefOrOid, 2078 requested_value: []const u8, 2079 ) !?Self { 2080 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 2081 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 2082 var value: []const u8 = if (requested_ref_or_oid == null) 2083 requested_value 2084 else 2085 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 2086 // no ref named: fall back to HEAD's branch (or its oid when detached). 2087 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 2088 if (requested_ref_or_oid == null) { 2089 if (repo.head(io, &head_buf)) |head| switch (head) { 2090 .ref => |r| { 2091 ref_or_oid = .branch; 2092 value = r.name; 2093 }, 2094 .oid => |o| { 2095 ref_or_oid = .object; 2096 value = o; 2097 }, 2098 } else |_| {} 2099 } 2100 2101 var oid: [hex_len]u8 = undefined; 2102 switch (ref_or_oid) { 2103 .object => { 2104 if (value.len != hex_len) return null; 2105 @memcpy(&oid, value); 2106 }, 2107 .branch, .tag => { 2108 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 2109 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 2110 }, 2111 } 2112 // store url-encoded so the route layer can hold the value verbatim. 2113 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 2114 } 2115 }; 2116 } 2117 2118 // who a repo page is built for, which picks the actions it shows 2119 pub const Viewer = struct { 2120 role: evt.Repo.Role, 2121 email: []const u8, 2122 2123 // the session's viewer of a repo it holds `role` in, or null when logged 2124 // out. local mode owns everything. 2125 pub fn init(session: *Session, arena: *std.heap.ArenaAllocator, role: evt.Repo.Role) !?Viewer { 2126 if (session.data.host_kind == .local) return .{ .role = .owner, .email = "" }; 2127 const user_id = session.userId() orelse return null; 2128 const moment = session.haxy_moment orelse unreachable; 2129 const user = (try activeUser(moment, arena, user_id)) orelse return null; 2130 return .{ .role = role, .email = user.event.email }; 2131 } 2132 }; 2133 2134 // a repo a page shows, and what its viewer may do there 2135 pub const RepoHandle = struct { 2136 location: RoutablePage.RepoLocation, 2137 viewer: ?Viewer = null, 2138 // only a public repo can be cloned over http 2139 read_access: evt.Repo.Access = .private, 2140 2141 pub fn dupe(self: RepoHandle, allocator: std.mem.Allocator) !RepoHandle { 2142 var copy = self; 2143 copy.location = try self.location.dupe(allocator); 2144 return copy; 2145 } 2146 2147 // pushing, and seeing the events and undo tabs. local mode is always owner. 2148 pub fn canWrite(self: RepoHandle) bool { 2149 const viewer = self.viewer orelse return false; 2150 return viewer.role.atLeast(.write); 2151 } 2152 2153 pub fn canUndo(self: RepoHandle) bool { 2154 const viewer = self.viewer orelse return false; 2155 return viewer.role == .owner; 2156 } 2157 }; 2158 2159 // where a repo page reads its on-disk repo from 2160 pub const RepoSource = struct { 2161 path: []const u8, 2162 repo_kind: rp.RepoKind, 2163 // the user's global git config, so local mode picks up their identity and 2164 // their signing and ssh settings. null on the server paths, which must not 2165 // read whoever runs the server. 2166 global_config_path: ?[]const u8 = null, 2167 2168 pub fn localInitOpts(self: RepoSource) rp.InitOpts { 2169 return .{ .path = self.path, .global_config_path = self.global_config_path }; 2170 } 2171 2172 pub fn hasBranch(self: RepoSource, io: std.Io, allocator: std.mem.Allocator, branch: []const u8) !bool { 2173 if (!xit.ref.validateName(branch)) return false; 2174 return switch (self.repo_kind) { 2175 inline else => |repo_kind| blk: { 2176 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2177 defer any_repo.deinit(io, allocator); 2178 break :blk switch (any_repo) { 2179 inline else => |*repo| (try repo.readRef(io, .{ .kind = .head, .name = branch })) != null, 2180 }; 2181 }, 2182 }; 2183 } 2184 2185 // whether the actor may change the event `id` names 2186 pub fn canModify( 2187 self: RepoSource, 2188 io: std.Io, 2189 allocator: std.mem.Allocator, 2190 actor: Actor, 2191 kind: evt.EventKind, 2192 id: *const [evt.event_id_size]u8, 2193 ) !bool { 2194 // a role that may change an event with no author needs no read 2195 if (actor.role.canModify(actor.author.email, null)) return true; 2196 2197 var arena = std.heap.ArenaAllocator.init(allocator); 2198 defer arena.deinit(); 2199 return switch (self.repo_kind) { 2200 inline else => |repo_kind| blk: { 2201 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, self.localInitOpts()); 2202 defer any_repo.deinit(io, allocator); 2203 break :blk switch (any_repo) { 2204 inline else => |*repo| actor.role.canModify(actor.author.email, try evt.readAuthorEmail(repo_kind, repo.self_repo_opts, io, allocator, &arena, repo, kind, id)), 2205 }; 2206 }, 2207 }; 2208 } 2209 }; 2210 2211 // who a write acts as and the role they hold in its repo 2212 // the thread button that changes the viewer's notifications, named by its label 2213 pub const NotifyAction = enum { subscribe, mute }; 2214 2215 pub const Actor = struct { 2216 author: evt.CommitAuthor, 2217 // local mode has no accounts, so it has no user id 2218 user_id: ?[evt.event_id_size]u8 = null, 2219 role: evt.Repo.Role, 2220 // the repo owner's id, which local mode lacks 2221 repo_user_id: ?[evt.event_id_size]u8 = null, 2222 }; 2223 2224 pub const Authorization = union(enum) { 2225 actor: Actor, 2226 login_required, 2227 repo_not_found, 2228 forbidden, 2229 }; 2230 2231 // the account `user_id` names, or null once it has been removed. a user id is 2232 // checked here wherever one enters, so the role lookups can trust theirs. 2233 pub fn activeUser( 2234 moment: evt.AdminDB.HashMap(.read_only), 2235 arena: *std.heap.ArenaAllocator, 2236 user_id: [evt.event_id_size]u8, 2237 ) !?evt.User.Record { 2238 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 2239 return if (user.removed) null else user; 2240 } 2241 2242 // what the typed assignee resolves to 2243 pub const AssigneeLookup = union(enum) { 2244 email: []const u8, 2245 failure: Session.FormFeedback.AssignmentFailure, 2246 }; 2247 2248 // the email `text` assigns: itself when it holds an @, else the email of the 2249 // user it names. a null moment is local mode, which has no users to look up. 2250 pub fn assigneeEmail(moment_maybe: ?evt.AdminDB.HashMap(.read_only), arena: *std.heap.ArenaAllocator, text: []const u8) !AssigneeLookup { 2251 const trimmed = std.mem.trim(u8, text, " \t\r\n"); 2252 if (std.mem.indexOfScalar(u8, trimmed, '@') != null) return .{ .email = trimmed }; 2253 const moment = moment_maybe orelse return .{ .failure = .not_an_email }; 2254 const user_id = (try evt.User.readIdByName(evt.AdminDB, evt.admin_repo_opts.hash, moment, trimmed)) orelse return .{ .failure = .not_found }; 2255 const user = (try activeUser(moment, arena, user_id)) orelse return .{ .failure = .not_found }; 2256 return .{ .email = user.event.email }; 2257 } 2258 2259 // whether the user may write to the repo `identity` names with at least 2260 // `min_role`, and to the `thread_kind` tab when there is one 2261 pub fn authorizeUser( 2262 io: std.Io, 2263 moment: evt.AdminDB.HashMap(.read_only), 2264 arena: *std.heap.ArenaAllocator, 2265 users_dir: []const u8, 2266 user_id: [evt.event_id_size]u8, 2267 identity: []const u8, 2268 min_role: evt.Repo.Role, 2269 thread_kind: ?evt.EventKind, 2270 ) !Authorization { 2271 const user = (try activeUser(moment, arena, user_id)) orelse return .login_required; 2272 2273 const owner_repo = evt.parseOwnerRepoPath(identity) orelse return .repo_not_found; 2274 const repo = (try evt.readRepoByOwnerAndName(io, arena.child_allocator, arena, moment, users_dir, owner_repo.owner, owner_repo.name, user_id)) orelse return .repo_not_found; 2275 // a repo the user can't read doesn't exist to them 2276 const role = repo.role orelse return .repo_not_found; 2277 if (!role.atLeast(min_role)) return .forbidden; 2278 if (thread_kind) |kind| { 2279 // a tab that is off doesn't exist 2280 const tab_role = repo.repo.event.threadRole(kind) orelse return .repo_not_found; 2281 if (!role.atLeast(tab_role)) return .forbidden; 2282 } 2283 return .{ .actor = .{ 2284 .author = .{ .name = user.event.name, .email = user.event.email }, 2285 .user_id = user_id, 2286 .role = role, 2287 .repo_user_id = try evt.parseEventId(&repo.repo.event.user_id), 2288 } }; 2289 } 2290 2291 // events created in local mode have no account behind them, so the commit 2292 // author comes from the repo's config, which the global config feeds into. 2293 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 2294 2295 pub fn localAuthor( 2296 src: RepoSource, 2297 io: std.Io, 2298 allocator: std.mem.Allocator, 2299 arena: *std.heap.ArenaAllocator, 2300 ) !evt.CommitAuthor { 2301 switch (src.repo_kind) { 2302 inline else => |repo_kind| { 2303 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 2304 defer any_repo.deinit(io, allocator); 2305 2306 switch (any_repo) { 2307 inline else => |*repo| { 2308 var config = try repo.listConfig(io, allocator); 2309 defer config.deinit(); 2310 2311 const user = config.sections.get("user") orelse return local_author_fallback; 2312 const name = user.get("name") orelse return local_author_fallback; 2313 const email = user.get("email") orelse return local_author_fallback; 2314 return .{ 2315 .name = try arena.allocator().dupe(u8, name), 2316 .email = try arena.allocator().dupe(u8, email), 2317 }; 2318 }, 2319 } 2320 }, 2321 } 2322 } 2323 2324 // per-connection mutable state. each SSH session / web session / local TUI 2325 // run gets its own. 2326 pub const Session = struct { 2327 data: Data = .{}, 2328 // session-lifetime allocations: login/user_id, persisted prefs, queued 2329 // actions. lives as long as the connection. 2330 arena: *std.heap.ArenaAllocator, 2331 // current page's allocations: page data and the page-scoped strings widgets 2332 // build (form actions, links). owned by Nav, swapped on each navigation, so 2333 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 2334 // where a render is one-shot, this points at the same arena as `arena`. 2335 page_arena: *std.heap.ArenaAllocator, 2336 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 2337 // filesystem io and the path to <server>/repos, for opening on-disk repos 2338 // during page construction. both null on wasm, which has no filesystem and 2339 // rebuilds pages from the serialized snapshot rather than from disk. 2340 io: ?std.Io = null, 2341 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 2342 users_dir: ?[]const u8 = null, 2343 // the single on-disk repo this session views, when running in local mode 2344 // (haxy invoked with no arguments inside a repo). null on the server paths, 2345 // which resolve repos from the admin db instead. 2346 local: ?RepoSource = null, 2347 // focus id -> the live TextInput, refreshed each frame by the views that own 2348 // inputs. web/wasm form handling looks widgets up here by focus id. 2349 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 2350 back: enum { unavailable, available, requested } = .unavailable, 2351 refresh_requested: bool = false, // set by input (ctrl+r) 2352 // a requested forward navigation. set this (via navigate) to move to a new 2353 // page; Nav.sync builds it and then copies it into current_page, clearing 2354 // this back to null. setting current_page directly only updates the url and 2355 // does not navigate. 2356 next_page: ?RoutablePage = null, 2357 is_terminal: bool = false, // true on remote SSH and local TUI 2358 color: bool = true, // false when NO_COLOR is set, which also hides the art 2359 // the terminal's reported default background, which the art blends toward 2360 terminal_background: ?Grid.Color.Rgb = null, 2361 // the web UI's url, for the TUI/SSH footer. null on the web itself (no 2362 // footer there). 2363 web_url: ?[]const u8 = null, 2364 // the authorized_keys line of the key an ssh session connected with 2365 ssh_key: ?[]const u8 = null, 2366 // a host operation requested by a widget 2367 host_request: ?HostRequest = null, 2368 quit_requested: bool = false, 2369 2370 pub const HostRequest = union(enum) { 2371 show_copyable_text: []const u8, 2372 sync_events, 2373 undo: RoutablePage.RepoUndoRoute, 2374 }; 2375 2376 pub const FormFeedback = union(enum) { 2377 pub const LoginFailure = enum { unknown_user, wrong_password }; 2378 pub const ThreadFailure = enum { required_title }; 2379 pub const PatchFailure = enum { 2380 required_title, 2381 invalid_target_branch, 2382 invalid_source_branch, 2383 same_branch, 2384 unrelated_branches, 2385 2386 pub fn fromError(err: anyerror) ?PatchFailure { 2387 return switch (err) { 2388 error.InvalidTargetBranch => .invalid_target_branch, 2389 error.InvalidSourceBranch => .invalid_source_branch, 2390 error.SameBranch => .same_branch, 2391 error.UnrelatedBranches => .unrelated_branches, 2392 else => null, 2393 }; 2394 } 2395 }; 2396 2397 pub const RepoFailure = enum { 2398 required_name, 2399 invalid_name, 2400 name_taken, 2401 2402 pub fn fromError(err: anyerror) ?RepoFailure { 2403 return switch (err) { 2404 error.NameEmpty => .required_name, 2405 error.NameTooLong, error.InvalidName => .invalid_name, 2406 error.NameTaken => .name_taken, 2407 else => null, 2408 }; 2409 } 2410 }; 2411 2412 pub const MembersFailure = enum { not_found, already_added }; 2413 2414 pub const BranchesFailure = enum { 2415 not_found, 2416 already_added, 2417 too_many, 2418 too_long, 2419 2420 pub fn fromError(err: anyerror) ?BranchesFailure { 2421 return switch (err) { 2422 error.BranchProtected => .already_added, 2423 error.TooManyProtectedBranches => .too_many, 2424 else => null, 2425 }; 2426 } 2427 }; 2428 2429 pub const AssignmentFailure = enum { not_found, not_an_email, already_assigned }; 2430 2431 pub const DeleteFailure = enum { wrong_confirm, wrong_password }; 2432 2433 pub const KeyFailure = enum { 2434 invalid, 2435 unsupported, 2436 already_added, 2437 too_many, 2438 2439 pub fn fromError(err: anyerror) ?KeyFailure { 2440 return switch (err) { 2441 error.InvalidKey => .invalid, 2442 error.UnsupportedKey => .unsupported, 2443 error.KeyAdded => .already_added, 2444 error.TooManyKeys => .too_many, 2445 else => null, 2446 }; 2447 } 2448 }; 2449 2450 pub const UserFailure = enum { 2451 required_name, 2452 invalid_name, 2453 name_taken, 2454 required_email, 2455 email_taken, 2456 required_password, 2457 password_mismatch, 2458 wrong_password, 2459 2460 pub fn fromError(err: anyerror) ?UserFailure { 2461 return switch (err) { 2462 error.NameEmpty => .required_name, 2463 error.NameTooShort, error.NameTooLong, error.InvalidName => .invalid_name, 2464 error.NameTaken => .name_taken, 2465 error.EmailEmpty => .required_email, 2466 error.EmailTaken => .email_taken, 2467 error.PasswordEmpty => .required_password, 2468 error.PasswordMismatch => .password_mismatch, 2469 error.WrongPassword => .wrong_password, 2470 else => null, 2471 }; 2472 } 2473 }; 2474 2475 login: struct { 2476 failure: LoginFailure, 2477 username: []const u8, 2478 }, 2479 user: struct { 2480 failure: UserFailure, 2481 // passwords are never retained 2482 fields: struct { 2483 name: []const u8, 2484 email: []const u8, 2485 }, 2486 }, 2487 user_settings: struct { 2488 failure: UserFailure, 2489 // passwords are never retained 2490 fields: struct { email: []const u8 }, 2491 }, 2492 user_keys: struct { 2493 failure: KeyFailure, 2494 key: []const u8, 2495 }, 2496 repo: struct { 2497 failure: RepoFailure, 2498 fields: struct { 2499 name: []const u8, 2500 description: []const u8, 2501 hash: hash.HashKind, 2502 access: evt.Repo.Access, 2503 }, 2504 }, 2505 repo_settings: struct { 2506 failure: RepoFailure, 2507 fields: struct { 2508 name: []const u8, 2509 description: []const u8, 2510 access: evt.Repo.Access, 2511 discuss_role: ?evt.Repo.Role, 2512 issue_role: ?evt.Repo.Role, 2513 patch_role: ?evt.Repo.Role, 2514 }, 2515 }, 2516 repo_members: struct { 2517 failure: MembersFailure, 2518 name: []const u8, 2519 }, 2520 repo_branches: struct { 2521 failure: BranchesFailure, 2522 name: []const u8, 2523 }, 2524 assignment: struct { 2525 failure: AssignmentFailure, 2526 text: []const u8, 2527 }, 2528 delete: struct { 2529 failure: DeleteFailure, 2530 // a page can hold two delete forms, so this names the failed one 2531 target: std.meta.Tag(Delete.Target), 2532 // the password is never retained 2533 confirm: []const u8, 2534 }, 2535 issue: struct { 2536 failure: ThreadFailure, 2537 fields: ?struct { 2538 title: []const u8, 2539 labels: []const u8, 2540 description: []const u8, 2541 } = null, 2542 }, 2543 patch: struct { 2544 failure: PatchFailure, 2545 fields: ?struct { 2546 title: []const u8, 2547 labels: []const u8, 2548 description: []const u8, 2549 target_branch: []const u8, 2550 source_branch: []const u8 = "", 2551 source_kind: Repo.Patches.Source.Kind = .fork, 2552 } = null, 2553 }, 2554 discussion: struct { 2555 failure: ThreadFailure, 2556 fields: ?struct { 2557 title: []const u8, 2558 labels: []const u8, 2559 description: []const u8, 2560 } = null, 2561 }, 2562 }; 2563 2564 const Self = @This(); 2565 2566 // serializable data sent down to web client 2567 pub const Data = struct { 2568 // the server's reference time for relative timestamps on this page. 2569 now: i64 = 0, 2570 user_id: ?[]const u8 = null, 2571 // the logged-in user's name and email, for the views that show them 2572 user_name: ?[]const u8 = null, 2573 user_email: ?[]const u8 = null, 2574 // the logged-in user's unread notifications, refreshed on each page build 2575 unread_notifs: u64 = 0, 2576 // a failed form retained long enough to render it for correction 2577 form_feedback: ?FormFeedback = null, 2578 // a transient local event-sync error 2579 sync_failure: ?[]const u8 = null, 2580 // a failed terminal undo retained on the current tab 2581 undo_failure: ?[]const u8 = null, 2582 current_page: RoutablePage = .default, 2583 // the selected ANSI art. the server serializes one image for WASM so 2584 // the browser does not need the whole build-generated collection. 2585 ansi_art: []const u8 = "", 2586 // where git clones and pushes go. absent in local mode, where remote 2587 // urls are not shown. 2588 git_http_url: ?[]const u8 = null, 2589 git_ssh_url: ?[]const u8 = null, 2590 git_ssh_prefix: []const u8 = "", 2591 // whether this session views a local repo or the server. unlike `local` 2592 // (the host-side filesystem source) this travels in the snapshot, so 2593 // the wasm side also parses elided link urls and hides the multi-user 2594 // chrome. 2595 host_kind: evt.HostKind = .server, 2596 }; 2597 2598 pub fn init( 2599 arena: *std.heap.ArenaAllocator, 2600 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2601 data: Data, 2602 ) !Self { 2603 var session = Self{ 2604 .data = data, 2605 .arena = arena, 2606 // until a host swaps in a page-scoped arena (Nav does this), page 2607 // allocations land in the session arena. on the web path that's the 2608 // intended behavior, since the whole arena is per-request. 2609 .page_arena = arena, 2610 .admin_repo = repo, 2611 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2612 }; 2613 try session.loadUser(); 2614 return session; 2615 } 2616 2617 // web views share the page's reference time; terminals use the live clock. 2618 pub fn nowSeconds(self: *const Self) !i64 { 2619 if (builtin.target.cpu.arch == .wasm32 or !self.is_terminal) return self.data.now; 2620 const io = self.io orelse return error.NoClock; 2621 return std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse error.TimestampOutOfRange; 2622 } 2623 2624 // load the logged-in user's name and persisted preferences from the db 2625 pub fn loadUser(self: *Self) !void { 2626 const user_id = self.userId() orelse return; 2627 const moment = self.haxy_moment orelse return; 2628 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2629 self.data.user_name = user.event.name; 2630 self.data.user_email = user.event.email; 2631 } 2632 2633 // forget the logged-in user, on a logout or once their account is removed 2634 pub fn logOut(self: *Self) void { 2635 self.data.user_id = null; 2636 self.data.user_name = null; 2637 self.data.user_email = null; 2638 } 2639 2640 // log in as the account the session's ssh key last logged into with a 2641 // password, while that account still holds the key 2642 pub fn logInWithSshKey(self: *Self) !void { 2643 const key = self.ssh_key orelse return; 2644 const admin_repo = self.admin_repo orelse return; 2645 const moment = self.haxy_moment orelse return; 2646 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2647 const user_id = (try evt.readLoginKeyUser(try admin_repo.core.latestMoment(), &fingerprint)) orelse return; 2648 if (!try evt.User.holdsKey(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, &user_id, &fingerprint)) return; 2649 self.data.user_id = try self.arena.allocator().dupe(u8, &user_id); 2650 try self.loadUser(); 2651 } 2652 2653 // add the session's ssh key to the user who just logged in with a 2654 // password, which proves they hold it, and let it log them in from now on 2655 pub fn rememberSshKey(self: *Self) !void { 2656 if (builtin.target.cpu.arch == .wasm32) return; 2657 const key = self.ssh_key orelse return; 2658 const io = self.io orelse return; 2659 const users_dir = self.users_dir orelse return; 2660 const admin_repo = self.admin_repo orelse return; 2661 const user_id = self.userId() orelse return; 2662 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2663 const allocator = self.arena.child_allocator; 2664 2665 const day = (std.time.epoch.EpochSeconds{ .secs = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()) }).getEpochDay().calculateYearDay(); 2666 const month = day.calculateMonthDay(); 2667 const line = try std.fmt.allocPrint(allocator, "{s} added {d:0>4}-{d:0>2}-{d:0>2} via login", .{ key, day.year, month.month.numeric(), month.day_index + 1 }); 2668 defer allocator.free(line); 2669 evt.addUserKey(io, allocator, users_dir, admin_repo, &user_id, line) catch |err| switch (err) { 2670 // it's already there, or there's no room for it 2671 error.KeyAdded, error.TooManyKeys => {}, 2672 else => return err, 2673 }; 2674 try evt.setLoginKey(io, admin_repo, &fingerprint, &user_id, .trust); 2675 self.haxy_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2676 } 2677 2678 // stop the session's ssh key logging the user in, on a logout 2679 pub fn forgetSshKey(self: *Self) !void { 2680 if (builtin.target.cpu.arch == .wasm32) return; 2681 const key = self.ssh_key orelse return; 2682 const io = self.io orelse return; 2683 const admin_repo = self.admin_repo orelse return; 2684 const user_id = self.userId() orelse return; 2685 const fingerprint = evt.User.fingerprintOfKey(key) orelse return; 2686 try evt.setLoginKey(io, admin_repo, &fingerprint, &user_id, .forget); 2687 } 2688 2689 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2690 const bytes = self.data.user_id orelse return null; 2691 if (bytes.len != evt.event_id_size) return null; 2692 var id: [evt.event_id_size]u8 = undefined; 2693 @memcpy(&id, bytes); 2694 return id; 2695 } 2696 2697 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2698 const feedback = self.data.form_feedback orelse return null; 2699 if (std.meta.activeTag(feedback) != tag) return null; 2700 return @field(feedback, @tagName(tag)); 2701 } 2702 2703 pub fn clearFormFeedback(self: *Self) void { 2704 self.data.form_feedback = null; 2705 } 2706 2707 // the actor for a write to the repo `identity` names, or null when the 2708 // session may not write there with at least `min_role` or in the 2709 // `thread_kind` tab. local mode always writes. 2710 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role, thread_kind: ?evt.EventKind) !?Actor { 2711 if (self.data.host_kind == .local) { 2712 const author = blk: { 2713 const src = self.local orelse break :blk local_author_fallback; 2714 const io = self.io orelse break :blk local_author_fallback; 2715 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2716 }; 2717 return .{ .author = author, .role = .owner }; 2718 } 2719 const user_id = self.userId() orelse return null; 2720 // the session's moment predates this input, so read the roles afresh 2721 const admin_repo = self.admin_repo orelse return null; 2722 const io = self.io orelse return null; 2723 const users_dir = self.users_dir orelse return null; 2724 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2725 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role, thread_kind)) { 2726 .actor => |actor| actor, 2727 .login_required, .repo_not_found, .forbidden => null, 2728 }; 2729 } 2730 2731 // where this session's event writes go. a server session always has a users dir and an admin repo 2732 pub fn eventHost(self: *const Self) evt.Host { 2733 return switch (self.data.host_kind) { 2734 .local => .local, 2735 .server => .{ .server = .{ 2736 .users_dir = self.users_dir orelse unreachable, 2737 .admin_repo_path = (self.admin_repo orelse unreachable).core.work_path, 2738 } }, 2739 }; 2740 } 2741 2742 // reload the moment from the admin repo and log out a removed user 2743 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2744 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2745 self.haxy_moment = moment; 2746 2747 const user_id = self.userId() orelse return; 2748 var arena = std.heap.ArenaAllocator.init(allocator); 2749 defer arena.deinit(); 2750 if (try activeUser(moment, &arena, user_id) == null) self.logOut(); 2751 } 2752 2753 // request a forward navigation to `route`; the host consumes next_page 2754 // (Nav.sync on the terminal, the wasm tick on the web). 2755 pub fn navigate(self: *Session, route: RoutablePage) !void { 2756 self.clearFormFeedback(); 2757 self.next_page = route; 2758 } 2759 }; 2760 2761 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2762 var nav = try Nav.init(allocator, session); 2763 defer nav.deinit(allocator); 2764 2765 var terminal = try term.Terminal.init(io, allocator); 2766 terminal.render_state.no_color = !session.color; 2767 var terminal_live = true; 2768 defer if (terminal_live) terminal.deinit(io); 2769 2770 // set term as active so it will be properly cooked 2771 // when a panic/segfault happens 2772 term.setActive(&terminal); 2773 defer term.setActive(null); 2774 2775 try terminal.queryBackground(); 2776 2777 while (!terminal.shouldQuit()) { 2778 const grid_changed = try terminal.render(&nav.root); 2779 2780 // process any inputs. 2781 // 2782 // if the grid didn't change, then first do a blocking 2783 // read, so the thread will sleep until further input. 2784 // after that, all remaining reads are non-blocking so 2785 // we can process the rest of the queued inputs. 2786 // 2787 // if the grid *did* change, then only do non-blocking 2788 // reads. we do not want to sleep the thread because 2789 // there may be an animation that requires more looping. 2790 var blocking = !grid_changed; 2791 while (try terminal.readKey(io, blocking)) |key| { 2792 blocking = false; 2793 try inputKey(allocator, &nav.root, key, session); 2794 } 2795 2796 if (session.host_request) |request| { 2797 session.host_request = null; 2798 switch (request) { 2799 .show_copyable_text => |copyable_text| { 2800 term.setActive(null); 2801 terminal.deinit(io); 2802 terminal_live = false; 2803 showCopyableText(io, copyable_text) catch |show_err| { 2804 terminal = try term.Terminal.init(io, allocator); 2805 terminal_live = true; 2806 term.setActive(&terminal); 2807 return show_err; 2808 }; 2809 terminal = try term.Terminal.init(io, allocator); 2810 terminal.render_state.no_color = !session.color; 2811 terminal_live = true; 2812 term.setActive(&terminal); 2813 }, 2814 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2815 .sync_events => { 2816 try nav.root.build(allocator, .{ 2817 .min_size = .{ .width = null, .height = null }, 2818 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2819 }, nav.root.getFocus()); 2820 _ = try terminal.render(&nav.root); 2821 try Repo.Events.performSync(allocator, session); 2822 }, 2823 } 2824 } 2825 2826 // reload so the next navigation builds its page from the current moment 2827 if (repo_maybe) |repo| try session.reloadMoment(allocator, repo); 2828 2829 // reconcile navigation: forward to a new page, or back on escape. 2830 // the terminal background can change at any time, so recheck it on each page 2831 if (try nav.sync(allocator, session)) try terminal.queryBackground(); 2832 2833 // the quit button (on the quit tab) asks the host to tear down. 2834 if (session.quit_requested) terminal.requestQuit(); 2835 2836 try nav.root.build(allocator, .{ 2837 .min_size = .{ .width = null, .height = null }, 2838 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2839 }, nav.root.getFocus()); 2840 } 2841 } 2842 2843 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2844 const tty: ?std.Io.File = if (builtin.target.os.tag == .windows) 2845 null 2846 else 2847 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2848 defer if (tty) |file| file.close(io); 2849 2850 const input = if (tty) |file| file else std.Io.File.stdin(); 2851 const output = if (tty) |file| file else std.Io.File.stdout(); 2852 2853 var write_buf: [1024]u8 = undefined; 2854 var writer = output.writer(io, &write_buf); 2855 try writer.interface.print("\x1b[2J\x1b[Hcopy the following text and then press enter to go back:\r\n\r\n{s}\r\n", .{copyable_text}); 2856 try writer.interface.flush(); 2857 2858 var read_buf: [1]u8 = undefined; 2859 var reader = input.reader(io, &read_buf); 2860 while (true) { 2861 const byte = try reader.interface.takeByte(); 2862 if (byte == '\r' or byte == '\n') return; 2863 } 2864 } 2865 2866 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2867 const root_focus = root.getFocus(); 2868 const focused_before = root_focus.grandchild_id; 2869 var activate_in_page_link = false; 2870 switch (key) { 2871 // request a navigation pop; the host's Nav.sync goes back a page, or 2872 // quits when there's no history left. 2873 .escape => { 2874 session.back = .requested; 2875 return; 2876 }, 2877 .ctrl => |letter| switch (letter) { 2878 'r' => { 2879 session.refresh_requested = true; 2880 return; 2881 }, 2882 else => try root.input(allocator, key, root_focus), 2883 }, 2884 .enter => { 2885 if (root_focus.grandchild_id) |gid| { 2886 // follow a cross-page link 2887 if (crossPageLink(root_focus, gid, session.data)) |route| { 2888 return session.navigate(route); 2889 } 2890 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2891 } 2892 activate_in_page_link = true; 2893 try root.input(allocator, key, root_focus); 2894 }, 2895 .mouse => |mouse| { 2896 if (mouse.button == .left) { 2897 if (cellPageLink(root, mouse.x, mouse.y, session.data)) |route| return session.navigate(route); 2898 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2899 const focus_id = hit.id; 2900 if (hit.kind == .background) { 2901 root_focus.setFocus(focus_id); 2902 return; 2903 } 2904 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2905 if (session.back == .available) session.back = .requested; 2906 return; 2907 } 2908 // follow a cross-page link 2909 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2910 return session.navigate(route); 2911 } 2912 if (currentPageLink(root_focus, focus_id, session.data)) return; 2913 if (rawLink(root_focus, focus_id)) |url| { 2914 if (!mouse.ctrl) try requestRawLink(session, url); 2915 return; 2916 } 2917 root_focus.setFocus(focus_id); 2918 activate_in_page_link = true; 2919 } 2920 // forward the press into the widget tree so buttons (and any 2921 // future click-aware widgets) can react. widgets that don't 2922 // care about presses ignore it. 2923 try root.input(allocator, key, root_focus); 2924 } else { 2925 try root.input(allocator, key, root_focus); 2926 } 2927 }, 2928 .event => |event| switch (event) { 2929 .background => |rgb| session.terminal_background = rgb, 2930 .resize => try root.input(allocator, key, root_focus), 2931 }, 2932 // a scroll tick goes to the pane under the pointer, focusing it first. 2933 // from outside any pane (the tabs, a sub-header) or from a text input 2934 // it moves like the arrows instead, so scrolling up from a search box 2935 // reaches the header and stops there. 2936 .scroll_up, .scroll_down => |position| { 2937 if (focusedPane(root_focus)) |pane| if (scrollUnder(root_focus, position)) |under| { 2938 if (under != pane) root_focus.setFocus(under); 2939 }; 2940 try root.input(allocator, key, root_focus); 2941 }, 2942 else => try root.input(allocator, key, root_focus), 2943 } 2944 2945 const focused_after = root_focus.grandchild_id; 2946 if (!activate_in_page_link and focused_before == focused_after) return; 2947 const focus_id = focused_after orelse return; 2948 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2949 } 2950 2951 // the innermost vertically scrolling widget laid out under `position` 2952 fn scrollUnder(root_focus: *const Focus, position: xitui.input.Position) ?usize { 2953 var found: ?usize = null; 2954 var found_area: usize = std.math.maxInt(usize); 2955 var iter = root_focus.children.iterator(); 2956 while (iter.next()) |entry| { 2957 const info = entry.value_ptr.focus.scroll orelse continue; 2958 if (info.direction == .horiz) continue; 2959 const r = entry.value_ptr.rect; 2960 if (position.x < r.x or position.y < r.y or position.x >= r.x + r.size.width or position.y >= r.y + r.size.height) continue; 2961 // a nested scroll lies within its parent, so the smallest is innermost 2962 const area = r.size.width * r.size.height; 2963 if (area < found_area) { 2964 found = entry.key_ptr.*; 2965 found_area = area; 2966 } 2967 } 2968 return found; 2969 } 2970 2971 // the innermost vertically scrolling widget the focus lies in, unless the 2972 // focused widget is a text input 2973 fn focusedPane(root_focus: *const Focus) ?usize { 2974 var current = root_focus.grandchild_id orelse return null; 2975 switch ((root_focus.children.get(current) orelse return null).focus.kind) { 2976 .text_input, .text_input_password, .text_area => return null, 2977 else => {}, 2978 } 2979 while (root_focus.children.get(current)) |child| { 2980 if (child.focus.scroll) |info| if (info.direction != .horiz) return current; 2981 current = child.parent_id; 2982 } 2983 return null; 2984 } 2985 2986 // a link to bytes the server serves directly rather than to a page route, so 2987 // it never resolves to a RoutablePage 2988 pub const raw_link_prefix = "ax:"; 2989 2990 // a route already loaded into the current page; focusing it changes the url 2991 // without rebuilding the page 2992 pub const in_page_link_prefix = "ai:"; 2993 2994 // an in-page tab's base route, or the exact current route when it is selected 2995 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2996 const target = if (selected) session.data.current_page else route; 2997 return session.page_arena.allocator().print("{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2998 } 2999 3000 // a button the web renderer covers with a file picker that posts the chosen 3001 // file to the url after the prefix 3002 pub const file_input_prefix = "file:"; 3003 3004 // a submit button that overrides its enclosing form's action 3005 pub const submit_action_prefix = "submit:"; 3006 3007 // one option of a radio field, as `radio:<name>=<value>` 3008 pub const radio_prefix = "radio:"; 3009 3010 // the url an `ax:` link points at, or null for anything else. a host that 3011 // suppresses the anchor's own navigation needs this to follow the link. 3012 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 3013 const child = root_focus.children.get(focus_id) orelse return null; 3014 const custom = switch (child.focus.kind) { 3015 .custom => |c| c, 3016 else => return null, 3017 }; 3018 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 3019 return custom[raw_link_prefix.len..]; 3020 } 3021 3022 fn requestRawLink(session: *Session, url: []const u8) !void { 3023 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 3024 } 3025 3026 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 3027 // an absolute url is already complete 3028 if (!std.mem.startsWith(u8, path, "/")) return path; 3029 return if (session.web_url) |web_url| 3030 try allocator.print("{s}{s}", .{ web_url, path }) 3031 else 3032 path; 3033 } 3034 3035 // if the focus target at focus_id is an `a:` link that should navigate (a 3036 // different parent page, or a different files directory within the repo page), 3037 // return its route; otherwise null. lets a host turn a click / enter on such a 3038 // link into a navigation rather than a focus change. 3039 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 3040 const current = data.current_page; 3041 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 3042 // a link to a different parent page always navigates; within a page, a 3043 // files-directory / commits-page / list-window change navigates while tab 3044 // links stay in-page. 3045 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.forkPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 3046 return null; 3047 } 3048 3049 // the page the clicked cell links to, from a link inside a text box's content 3050 fn cellPageLink(root: *Widget, x: usize, y: usize, data: Session.Data) ?RoutablePage { 3051 const grid = root.getGrid() orelse return null; 3052 const cell = grid.cell(x, y) catch return null; 3053 const link = cell.link orelse return null; 3054 if (link.len == 0 or link[0] != '/') return null; 3055 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(link) else RoutablePage.fromUrl(link); 3056 } 3057 3058 // whether the `a:` focus target links to the page already shown, which a click 3059 // leaves alone rather than focusing 3060 pub fn currentPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) bool { 3061 const route = pageLink(root_focus, focus_id, data, "a:") orelse return false; 3062 return route.eql(data.current_page); 3063 } 3064 3065 // the route carried by an `ai:` focus target, or null for any other target 3066 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 3067 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 3068 } 3069 3070 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 3071 const child = root_focus.children.get(focus_id) orelse return null; 3072 const custom = switch (child.focus.kind) { 3073 .custom => |c| c, 3074 else => return null, 3075 }; 3076 if (!std.mem.startsWith(u8, custom, prefix)) return null; 3077 const path = custom[prefix.len..]; 3078 // local sessions build (and parse) links with the repo identity elided 3079 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 3080 } 3081 3082 // an assignee as the detail view shows it: the stored email, and the name of 3083 // the user holding it on this instance when there is one 3084 pub const Assignee = struct { 3085 email: []const u8, 3086 name: ?[]const u8 = null, 3087 3088 pub fn display(self: Assignee) []const u8 { 3089 return self.name orelse self.email; 3090 } 3091 }; 3092 3093 // a display author, resolved against the admin db at read time 3094 pub const Author = union(enum) { 3095 unknown, 3096 email: []const u8, // an email no user matches 3097 user_name: []const u8, 3098 3099 // the commit author line's email, resolved like initFromEmail 3100 pub fn init( 3101 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 3102 arena: *std.heap.ArenaAllocator, 3103 author_line: []const u8, 3104 ) !Author { 3105 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 3106 } 3107 3108 // from a record's stored author email: it resolves to the user currently 3109 // holding it, else stays the email. the result is allocated in `arena`, 3110 // so the email may borrow transient memory. 3111 pub fn initFromEmail( 3112 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 3113 arena: *std.heap.ArenaAllocator, 3114 author_email: ?[]const u8, 3115 ) !Author { 3116 const email = author_email orelse return .unknown; 3117 if (haxy_moment) |moment| { 3118 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 3119 return .{ .user_name = user.name }; 3120 } 3121 } 3122 return .{ .email = try arena.allocator().dupe(u8, email) }; 3123 } 3124 }; 3125 3126 // the "a:" link to user `name`'s page. 3127 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 3128 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 3129 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 3130 return page_arena.allocator().print("a:{s}", .{url}); 3131 } 3132 3133 // a focusable " author " box showing `author`, linking to their user page 3134 // when it is a known user 3135 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 3136 const text = switch (author) { 3137 .unknown => "", 3138 .email, .user_name => |t| t, 3139 }; 3140 var tb = try wgt.TextBox.init(allocator, text, .{ .border = .single, .round_corners = true, .wrap_kind = .none, .top_label = .{ .text = " author " } }); 3141 errdefer tb.deinit(allocator); 3142 tb.getFocus().mode = .all; 3143 switch (author) { 3144 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 3145 else => {}, 3146 } 3147 return tb; 3148 } 3149 3150 // native-TUI navigation 3151 pub const Nav = struct { 3152 root: Widget, 3153 // backs the current page (its Page data and the page-scoped strings its 3154 // widgets build). owned here, swapped on each navigation. session.page_arena 3155 // tracks whichever of these is current so widgets allocate into it. 3156 arena: *std.heap.ArenaAllocator, 3157 // the login the current root was built for 3158 user_id: ?[evt.event_id_size]u8, 3159 history: std.ArrayList(Entry), 3160 3161 // each retained page keeps its own arena, freed when the page leaves the 3162 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 3163 // long-lived session from accumulating every page it ever visited. 3164 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator, user_id: ?[evt.event_id_size]u8 }; 3165 3166 // cap on retained back-history so the chain can't grow memory without bound 3167 const max_history: usize = 16; 3168 3169 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 3170 session.back = .unavailable; 3171 const arena = try allocator.create(std.heap.ArenaAllocator); 3172 arena.* = std.heap.ArenaAllocator.init(allocator); 3173 errdefer { 3174 arena.deinit(); 3175 allocator.destroy(arena); 3176 } 3177 3178 return .{ 3179 .root = try initCurrentRoot(allocator, arena, session), 3180 .arena = arena, 3181 .user_id = session.userId(), 3182 .history = .empty, 3183 }; 3184 } 3185 3186 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 3187 self.root.deinit(allocator); 3188 freeArena(allocator, self.arena); 3189 for (self.history.items) |*entry| { 3190 entry.root.deinit(allocator); 3191 freeArena(allocator, entry.arena); 3192 } 3193 self.history.deinit(allocator); 3194 } 3195 3196 // rebuild the current page in place from a current moment 3197 fn rebuild(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 3198 if (session.haxy_moment == null and session.local == null) return; 3199 const arena = try allocator.create(std.heap.ArenaAllocator); 3200 arena.* = std.heap.ArenaAllocator.init(allocator); 3201 errdefer freeArena(allocator, arena); 3202 3203 const new_root = try initCurrentRoot(allocator, arena, session); 3204 3205 self.root.deinit(allocator); 3206 freeArena(allocator, self.arena); 3207 self.root = new_root; 3208 self.arena = arena; 3209 self.user_id = session.userId(); 3210 } 3211 3212 // build the current page's root in `arena`, or the not-found page's when 3213 // the route names nothing 3214 fn initCurrentRoot(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator, session: *Session) !Widget { 3215 session.page_arena = arena; 3216 const page = try arena.allocator().create(Page); 3217 page.* = Page.init(arena, session, session.data.current_page) catch |err| switch (err) { 3218 error.NotFound => blk: { 3219 session.data.current_page = .not_found; 3220 break :blk .not_found; 3221 }, 3222 else => |e| return e, 3223 }; 3224 return initRoot(allocator, page, session); 3225 } 3226 3227 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 3228 arena.deinit(); 3229 allocator.destroy(arena); 3230 } 3231 3232 // reconcile the displayed root with the session's navigation state. a 3233 // forward nav (current_page moved to a different parent page) pushes the 3234 // current root and builds the new page in a fresh arena; a back request 3235 // frees the current page and restores the previous one. when escape is 3236 // pressed with no history left we switch to the quit tab instead of quitting. 3237 // returns whether the root was replaced. 3238 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !bool { 3239 // refresh: rebuild the current page in place from a current moment 3240 if (session.refresh_requested) { 3241 session.refresh_requested = false; 3242 try self.rebuild(allocator, session); 3243 return true; 3244 } 3245 3246 if (session.back == .requested) { 3247 if (self.history.pop()) |entry| { 3248 session.back = if (self.history.items.len == 0) .unavailable else .available; 3249 self.root.deinit(allocator); 3250 freeArena(allocator, self.arena); 3251 self.root = entry.root; 3252 self.arena = entry.arena; 3253 self.user_id = entry.user_id; 3254 session.page_arena = entry.arena; 3255 session.data.current_page = entry.route; 3256 // a page built under another login is rebuilt rather than restored 3257 if (!std.meta.eql(entry.user_id, session.userId())) { 3258 try self.rebuild(allocator, session); 3259 return true; 3260 } 3261 chooseAnsiArtForNavigation(session); 3262 return true; 3263 } 3264 session.back = .unavailable; 3265 // nothing to go back to; switch to the quit confirmation 3266 const root_focus = self.root.getFocus(); 3267 var iter = root_focus.children.iterator(); 3268 while (iter.next()) |entry| { 3269 switch (entry.value_ptr.focus.kind) { 3270 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 3271 root_focus.setFocus(entry.key_ptr.*); 3272 // a Stack only builds its selected child, so the quit 3273 // button isn't in the focus tree until a build runs with 3274 // the quit tab selected. build once, then send a 3275 // synthetic arrow_down to drop focus from the tab onto 3276 // the button so it's ready to confirm. 3277 try self.root.build(allocator, .{ 3278 .min_size = .{ .width = null, .height = 40 }, 3279 .max_size = .{ .width = 80, .height = null }, 3280 }, root_focus); 3281 try self.root.input(allocator, .arrow_down, root_focus); 3282 break; 3283 }, 3284 else => {}, 3285 } 3286 } 3287 return false; 3288 } 3289 3290 // forward navigation: navigate() set next_page to the page to move to (a 3291 // cross-page link or tab change crossing pages) 3292 if (session.next_page) |route| { 3293 session.next_page = null; 3294 if (session.haxy_moment == null and session.local == null) return false; 3295 const previous_route = session.data.current_page; 3296 // the page we navigated to becomes the current page 3297 session.data.current_page = route; 3298 session.back = .available; 3299 3300 const arena = try allocator.create(std.heap.ArenaAllocator); 3301 arena.* = std.heap.ArenaAllocator.init(allocator); 3302 errdefer freeArena(allocator, arena); 3303 3304 const new_root = try initCurrentRoot(allocator, arena, session); 3305 3306 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena, .user_id = self.user_id }); 3307 // drop the oldest entry (freeing its widget tree and arena) once over cap 3308 if (self.history.items.len > max_history) { 3309 var oldest = self.history.orderedRemove(0); 3310 oldest.root.deinit(allocator); 3311 freeArena(allocator, oldest.arena); 3312 } 3313 self.root = new_root; 3314 self.arena = arena; 3315 self.user_id = session.userId(); 3316 return true; 3317 } 3318 return false; 3319 } 3320 }; 3321 3322 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 3323 const page_widget: Widget = switch (page.*) { 3324 .home => |*p| .{ .home = try .init(allocator, p, session) }, 3325 .user => |*p| .{ .user = try .init(allocator, p, session) }, 3326 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 3327 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 3328 .not_found => .{ .not_found = try .init(allocator, session) }, 3329 }; 3330 3331 chooseAnsiArtForNavigation(session); 3332 3333 // on the TUI/SSH, the page sits above a one-row footer showing its web 3334 // url, when there's a web UI to point at 3335 var root = if (session.is_terminal) blk: { 3336 var box = try wgt.Box(Widget).init(allocator, .{ .border = null, .direction = .vert }); 3337 errdefer box.deinit(allocator); 3338 const bg_id = bg_blk: { 3339 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 3340 errdefer background.deinit(allocator); 3341 const id = background.getFocus().id; 3342 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 3343 break :bg_blk id; 3344 }; 3345 if (session.web_url != null) { 3346 var footer = try widget.Footer.init(allocator, session); 3347 errdefer footer.deinit(allocator); 3348 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 3349 } 3350 box.getFocus().child_id = bg_id; 3351 break :blk Widget{ .box = box }; 3352 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 3353 errdefer root.deinit(allocator); 3354 3355 // input-owning views build their TextInputs in init, so reset their 3356 // registrations here 3357 session.text_inputs.clearRetainingCapacity(); 3358 3359 try root.build(allocator, .{ 3360 .min_size = .{ .width = null, .height = 40 }, 3361 .max_size = .{ .width = 100, .height = null }, 3362 }, root.getFocus()); 3363 3364 return root; 3365 } 3366 3367 // native and server-side sessions choose from the embedded collection. WASM 3368 // keeps the art serialized by the server instead. 3369 fn chooseAnsiArtForNavigation(session: *Session) void { 3370 if (comptime ansi_art.art.len == 0) return; 3371 if (session.data.current_page == .not_found) { 3372 session.data.ansi_art = ansi_art.not_found; 3373 return; 3374 } 3375 const io = session.io orelse return; 3376 var random: usize = undefined; 3377 io.random(std.mem.asBytes(&random)); 3378 session.data.ansi_art = ansi_art.art[random % ansi_art.art.len]; 3379 } 3380