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