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