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