╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2008 moment: evt.AdminDB.HashMap(.read_only), 2009 arena: *std.heap.ArenaAllocator, 2010 user_id: [evt.event_id_size]u8, 2011 ) !?evt.User.Record { 2012 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 2013 return if (user.removed) null else user; 2014 } 2015 2016 // whether the user may write to the repo `identity` names with at least 2017 // `min_role` 2018 pub fn authorizeUser( 2019 io: std.Io, 2020 moment: evt.AdminDB.HashMap(.read_only), 2021 arena: *std.heap.ArenaAllocator, 2022 users_dir: []const u8, 2023 user_id: [evt.event_id_size]u8, 2024 identity: []const u8, 2025 min_role: evt.Repo.Role, 2026 ) !Authorization { 2027 const user = (try activeUser(moment, arena, user_id)) orelse return .login_required; 2028 2029 const owner_repo = evt.parseOwnerRepoPath(identity) orelse return .repo_not_found; 2030 const repo = (try evt.readRepoByOwnerAndName(io, arena.child_allocator, arena, moment, users_dir, owner_repo.owner, owner_repo.name)) orelse return .repo_not_found; 2031 const role = evt.Repo.roleOf(repo.repo, user_id); 2032 // a repo the user can't read doesn't exist to them 2033 if (role == .none) return .repo_not_found; 2034 if (!role.atLeast(min_role)) return .forbidden; 2035 return .{ .actor = .{ 2036 .author = .{ .name = user.event.name, .email = user.event.email }, 2037 .user_id = user_id, 2038 .role = role, 2039 .repo_user_id = repo.repo.event.user_id[0..evt.event_id_size].*, 2040 } }; 2041 } 2042 2043 // events created in local mode have no account behind them, so the commit 2044 // author comes from the repo's config, which the global config feeds into. 2045 pub const local_author_fallback = evt.CommitAuthor{ .name = "haxy", .email = "user@haxy" }; 2046 2047 pub fn localAuthor( 2048 src: RepoSource, 2049 io: std.Io, 2050 allocator: std.mem.Allocator, 2051 arena: *std.heap.ArenaAllocator, 2052 ) !evt.CommitAuthor { 2053 switch (src.repo_kind) { 2054 inline else => |repo_kind| { 2055 var any_repo = rp.AnyRepo(repo_kind, .{}).open(io, allocator, src.localInitOpts()) catch return local_author_fallback; 2056 defer any_repo.deinit(io, allocator); 2057 2058 switch (any_repo) { 2059 inline else => |*repo| { 2060 var config = try repo.listConfig(io, allocator); 2061 defer config.deinit(); 2062 2063 const user = config.sections.get("user") orelse return local_author_fallback; 2064 const name = user.get("name") orelse return local_author_fallback; 2065 const email = user.get("email") orelse return local_author_fallback; 2066 return .{ 2067 .name = try arena.allocator().dupe(u8, name), 2068 .email = try arena.allocator().dupe(u8, email), 2069 }; 2070 }, 2071 } 2072 }, 2073 } 2074 } 2075 2076 // per-connection mutable state. each SSH session / web session / local TUI 2077 // run gets its own. 2078 pub const Session = struct { 2079 data: Data = .{}, 2080 // session-lifetime allocations: login/user_id, persisted prefs, queued 2081 // actions. lives as long as the connection. 2082 arena: *std.heap.ArenaAllocator, 2083 // current page's allocations: page data and the page-scoped strings widgets 2084 // build (form actions, links). owned by Nav, swapped on each navigation, so 2085 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 2086 // where a render is one-shot, this points at the same arena as `arena`. 2087 page_arena: *std.heap.ArenaAllocator, 2088 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 2089 // filesystem io and the path to <server>/repos, for opening on-disk repos 2090 // during page construction. both null on wasm, which has no filesystem and 2091 // rebuilds pages from the serialized snapshot rather than from disk. 2092 io: ?std.Io = null, 2093 admin_repo: ?*rp.Repo(.xit, evt.admin_repo_opts) = null, 2094 users_dir: ?[]const u8 = null, 2095 // the single on-disk repo this session views, when running in local mode 2096 // (haxy invoked with no arguments inside a repo). null on the server paths, 2097 // which resolve repos from the admin db instead. 2098 local: ?RepoSource = null, 2099 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 2100 // focus id -> the live TextInput, refreshed each frame by the views that own 2101 // inputs. web/wasm form handling looks widgets up here by focus id. 2102 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput) = .empty, 2103 back: enum { unavailable, available, requested } = .unavailable, 2104 refresh_requested: bool = false, // set by input (ctrl+r) 2105 // a requested forward navigation. set this (via navigate) to move to a new 2106 // page; Nav.sync builds it and then copies it into current_page, clearing 2107 // this back to null. setting current_page directly only updates the url and 2108 // does not navigate. 2109 next_page: ?RoutablePage = null, 2110 is_terminal: bool = false, // true on remote SSH and local TUI 2111 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 2112 // url. null on the web itself (no footer there). 2113 web_port: ?u16 = null, 2114 // a host operation requested by a widget 2115 host_request: ?HostRequest = null, 2116 quit_requested: bool = false, 2117 2118 pub const HostRequest = union(enum) { 2119 show_copyable_text: []const u8, 2120 sync_events, 2121 undo: RoutablePage.RepoUndoRoute, 2122 }; 2123 2124 pub const FormFeedback = union(enum) { 2125 pub const LoginFailure = enum { unknown_user, wrong_password }; 2126 pub const ThreadFailure = enum { required_title }; 2127 pub const PatchFailure = enum { 2128 required_title, 2129 invalid_target_branch, 2130 invalid_source_branch, 2131 same_branch, 2132 unrelated_branches, 2133 2134 pub fn fromError(err: anyerror) ?PatchFailure { 2135 return switch (err) { 2136 error.InvalidTargetBranch => .invalid_target_branch, 2137 error.InvalidSourceBranch => .invalid_source_branch, 2138 error.SameBranch => .same_branch, 2139 error.UnrelatedBranches => .unrelated_branches, 2140 else => null, 2141 }; 2142 } 2143 }; 2144 2145 login: struct { 2146 failure: LoginFailure, 2147 username: []const u8, 2148 }, 2149 issue: struct { 2150 failure: ThreadFailure, 2151 fields: ?struct { 2152 title: []const u8, 2153 labels: []const u8, 2154 description: []const u8, 2155 } = null, 2156 }, 2157 patch: struct { 2158 failure: PatchFailure, 2159 fields: ?struct { 2160 title: []const u8, 2161 labels: []const u8, 2162 description: []const u8, 2163 target_branch: []const u8, 2164 source_branch: []const u8 = "", 2165 source_kind: Repo.Patches.Source.Kind = .fork, 2166 } = null, 2167 }, 2168 discussion: struct { 2169 failure: ThreadFailure, 2170 fields: ?struct { 2171 title: []const u8, 2172 labels: []const u8, 2173 description: []const u8, 2174 } = null, 2175 }, 2176 }; 2177 2178 const Self = @This(); 2179 2180 // serializable data sent down to web client 2181 pub const Data = struct { 2182 user_id: ?[]const u8 = null, 2183 // the logged-in user's name, for the views that show it 2184 user_name: ?[]const u8 = null, 2185 // a failed form retained long enough to render it for correction 2186 form_feedback: ?FormFeedback = null, 2187 // a transient local event-sync error 2188 sync_failure: ?[]const u8 = null, 2189 // a failed terminal undo retained on the current tab 2190 undo_failure: ?[]const u8 = null, 2191 current_page: RoutablePage = .default, 2192 // whether to render the ANSI art backdrop 2193 enable_ansi: bool = true, 2194 // the selected ANSI art. the server serializes one image for WASM so 2195 // the browser does not need the whole build-generated collection. 2196 ansi_art: []const u8 = "", 2197 // the bound git-service ports. absent in local mode, where remote urls 2198 // are not shown. 2199 git_http_port: ?u16 = null, 2200 git_ssh_port: ?u16 = null, 2201 git_ssh_prefix: []const u8 = "", 2202 // whether this session views a local repo or the server. unlike `local` 2203 // (the host-side filesystem source) this travels in the snapshot, so 2204 // the wasm side also parses elided link urls and hides the multi-user 2205 // chrome. 2206 host_kind: evt.HostKind = .server, 2207 }; 2208 2209 // a user-initiated state change. widgets enqueue these on the session during 2210 // input instead of mutating state or touching the DB themselves; the host 2211 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 2212 // side effects out of the widget tree and gives every render path one place to 2213 // turn a UI action into a state change + event. 2214 pub const Action = union(enum) { 2215 toggle_ansi, 2216 }; 2217 2218 pub fn init( 2219 arena: *std.heap.ArenaAllocator, 2220 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2221 data: Data, 2222 ) !Self { 2223 var session = Self{ 2224 .data = data, 2225 .arena = arena, 2226 // until a host swaps in a page-scoped arena (Nav does this), page 2227 // allocations land in the session arena. on the web path that's the 2228 // intended behavior, since the whole arena is per-request. 2229 .page_arena = arena, 2230 .admin_repo = repo, 2231 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 2232 }; 2233 try session.loadUser(); 2234 return session; 2235 } 2236 2237 // load the logged-in user's name and persisted preferences from the db 2238 pub fn loadUser(self: *Self) !void { 2239 const user_id = self.userId() orelse return; 2240 const moment = self.haxy_moment orelse return; 2241 const user = (try activeUser(moment, self.arena, user_id)) orelse return self.logOut(); 2242 self.data.user_name = user.event.name; 2243 self.data.enable_ansi = user.event.enable_ansi; 2244 } 2245 2246 // forget the logged-in user, on a logout or once their account is removed 2247 pub fn logOut(self: *Self) void { 2248 self.data.user_id = null; 2249 self.data.user_name = null; 2250 } 2251 2252 pub fn userId(self: *const Self) ?[evt.event_id_size]u8 { 2253 const bytes = self.data.user_id orelse return null; 2254 if (bytes.len != evt.event_id_size) return null; 2255 var id: [evt.event_id_size]u8 = undefined; 2256 @memcpy(&id, bytes); 2257 return id; 2258 } 2259 2260 pub fn formFeedback(self: *const Self, comptime tag: std.meta.Tag(FormFeedback)) ?@FieldType(FormFeedback, @tagName(tag)) { 2261 const feedback = self.data.form_feedback orelse return null; 2262 if (std.meta.activeTag(feedback) != tag) return null; 2263 return @field(feedback, @tagName(tag)); 2264 } 2265 2266 pub fn clearFormFeedback(self: *Self) void { 2267 self.data.form_feedback = null; 2268 } 2269 2270 // the actor for a write to the repo `identity` names, or null when the 2271 // session may not write there with at least `min_role`. local mode always 2272 // writes. 2273 pub fn authorize(self: *Self, identity: []const u8, min_role: evt.Repo.Role) !?Actor { 2274 if (self.data.host_kind == .local) { 2275 const author = blk: { 2276 const src = self.local orelse break :blk local_author_fallback; 2277 const io = self.io orelse break :blk local_author_fallback; 2278 break :blk try localAuthor(src, io, self.page_arena.child_allocator, self.page_arena); 2279 }; 2280 return .{ .author = author, .role = .owner }; 2281 } 2282 const user_id = self.userId() orelse return null; 2283 // the session's moment predates this input, so read the roles afresh 2284 const admin_repo = self.admin_repo orelse return null; 2285 const io = self.io orelse return null; 2286 const users_dir = self.users_dir orelse return null; 2287 const moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 2288 return switch (try authorizeUser(io, moment, self.page_arena, users_dir, user_id, identity, min_role)) { 2289 .actor => |actor| actor, 2290 .login_required, .repo_not_found, .forbidden => null, 2291 }; 2292 } 2293 2294 // where this session's event writes go. a server session always has a users dir 2295 pub fn eventHost(self: *const Self) evt.Host { 2296 return switch (self.data.host_kind) { 2297 .local => .local, 2298 .server => .{ .server = .{ .users_dir = self.users_dir orelse unreachable } }, 2299 }; 2300 } 2301 2302 // queue an action for the host to drain this frame. 2303 pub fn push(self: *Self, action: Action) !void { 2304 try self.pending.append(self.arena.allocator(), action); 2305 } 2306 2307 // apply a single action's in-memory effect only (no persistence). 2308 fn apply(self: *Self, action: Action) void { 2309 switch (action) { 2310 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 2311 } 2312 } 2313 2314 // drain the session's queued actions by applying them to the session. 2315 // used on the wasm path, which has no repo to persist to. 2316 pub fn applyPending(self: *Self) void { 2317 for (self.pending.items) |action| self.apply(action); 2318 self.pending.clearRetainingCapacity(); 2319 } 2320 2321 // drain the session's queued actions by applying them to the session and 2322 // writing them to the db 2323 pub fn applyAndWritePending( 2324 self: *Self, 2325 io: std.Io, 2326 allocator: std.mem.Allocator, 2327 repo: *rp.Repo(.xit, evt.admin_repo_opts), 2328 ) !void { 2329 defer self.pending.clearRetainingCapacity(); 2330 for (self.pending.items) |action| { 2331 self.apply(action); 2332 switch (action) { 2333 .toggle_ansi => if (self.data.user_id) |user_id| { 2334 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, self.users_dir orelse unreachable, user_id); 2335 }, 2336 } 2337 } 2338 } 2339 2340 // reload the moment from the admin repo and re-read user preferences 2341 pub fn reloadMoment(self: *Self, allocator: std.mem.Allocator, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 2342 const moment = try evt.currentMoment(evt.admin_repo_opts, repo); 2343 self.haxy_moment = moment; 2344 2345 const user_id = self.userId() orelse return; 2346 var arena = std.heap.ArenaAllocator.init(allocator); 2347 defer arena.deinit(); 2348 const user = (try activeUser(moment, &arena, user_id)) orelse return self.logOut(); 2349 self.data.enable_ansi = user.event.enable_ansi; 2350 } 2351 2352 // request a forward navigation to `route`; the host consumes next_page 2353 // (Nav.sync on the terminal, the wasm tick on the web). 2354 pub fn navigate(self: *Session, route: RoutablePage) !void { 2355 self.clearFormFeedback(); 2356 self.next_page = route; 2357 } 2358 }; 2359 2360 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo_maybe: ?*rp.Repo(.xit, evt.admin_repo_opts)) !void { 2361 var nav = try Nav.init(allocator, session); 2362 defer nav.deinit(allocator); 2363 2364 var terminal = try term.Terminal.init(io, allocator); 2365 var terminal_live = true; 2366 defer if (terminal_live) terminal.deinit(io); 2367 2368 // set term as active so it will be properly cooked 2369 // when a panic/segfault happens 2370 term.setActive(&terminal); 2371 defer term.setActive(null); 2372 2373 while (!terminal.shouldQuit()) { 2374 const grid_changed = try terminal.render(&nav.root); 2375 2376 // process any inputs. 2377 // 2378 // if the grid didn't change, then first do a blocking 2379 // read, so the thread will sleep until further input. 2380 // after that, all remaining reads are non-blocking so 2381 // we can process the rest of the queued inputs. 2382 // 2383 // if the grid *did* change, then only do non-blocking 2384 // reads. we do not want to sleep the thread because 2385 // there may be an animation that requires more looping. 2386 var blocking = !grid_changed; 2387 while (try terminal.readKey(io, blocking)) |key| { 2388 blocking = false; 2389 try inputKey(allocator, &nav.root, key, session); 2390 } 2391 2392 if (session.host_request) |request| { 2393 session.host_request = null; 2394 switch (request) { 2395 .show_copyable_text => |copyable_text| { 2396 term.setActive(null); 2397 terminal.deinit(io); 2398 terminal_live = false; 2399 showCopyableText(io, copyable_text) catch |show_err| { 2400 terminal = try term.Terminal.init(io, allocator); 2401 terminal_live = true; 2402 term.setActive(&terminal); 2403 return show_err; 2404 }; 2405 terminal = try term.Terminal.init(io, allocator); 2406 terminal_live = true; 2407 term.setActive(&terminal); 2408 }, 2409 .undo => |target| Repo.Undo.handleRequest(allocator, session, target), 2410 .sync_events => { 2411 try nav.root.build(allocator, .{ 2412 .min_size = .{ .width = null, .height = null }, 2413 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2414 }, nav.root.getFocus()); 2415 _ = try terminal.render(&nav.root); 2416 try Repo.Events.performSync(allocator, session); 2417 }, 2418 } 2419 } 2420 2421 // persist queued actions when there's a repo; local mode has none, 2422 // so just apply in-memory 2423 if (repo_maybe) |repo| { 2424 try session.applyAndWritePending(io, allocator, repo); 2425 // reload so the next navigation builds its page from the current moment 2426 try session.reloadMoment(allocator, repo); 2427 } else { 2428 session.applyPending(); 2429 } 2430 2431 // reconcile navigation: forward to a new page, or back on escape. 2432 try nav.sync(allocator, session); 2433 2434 // the quit button (on the quit tab) asks the host to tear down. 2435 if (session.quit_requested) terminal.requestQuit(); 2436 2437 try nav.root.build(allocator, .{ 2438 .min_size = .{ .width = null, .height = null }, 2439 .max_size = .{ .width = terminal.size.width, .height = terminal.size.height }, 2440 }, nav.root.getFocus()); 2441 } 2442 } 2443 2444 fn showCopyableText(io: std.Io, copyable_text: []const u8) !void { 2445 const tty: ?std.Io.File = if (builtin.os.tag == .windows) 2446 null 2447 else 2448 try std.Io.Dir.cwd().openFile(io, "/dev/tty", .{ .mode = .read_write }); 2449 defer if (tty) |file| file.close(io); 2450 2451 const input = if (tty) |file| file else std.Io.File.stdin(); 2452 const output = if (tty) |file| file else std.Io.File.stdout(); 2453 2454 var write_buf: [1024]u8 = undefined; 2455 var writer = output.writer(io, &write_buf); 2456 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}); 2457 try writer.interface.flush(); 2458 2459 var read_buf: [1]u8 = undefined; 2460 var reader = input.reader(io, &read_buf); 2461 while (true) { 2462 const byte = try reader.interface.takeByte(); 2463 if (byte == '\r' or byte == '\n') return; 2464 } 2465 } 2466 2467 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: Key, session: *Session) !void { 2468 const root_focus = root.getFocus(); 2469 const focused_before = root_focus.grandchild_id; 2470 var activate_in_page_link = false; 2471 switch (key) { 2472 // request a navigation pop; the host's Nav.sync goes back a page, or 2473 // quits when there's no history left. 2474 .escape => { 2475 session.back = .requested; 2476 return; 2477 }, 2478 .ctrl => |letter| switch (letter) { 2479 'r' => { 2480 session.refresh_requested = true; 2481 return; 2482 }, 2483 else => try root.input(allocator, key, root_focus), 2484 }, 2485 .enter => { 2486 if (root_focus.grandchild_id) |gid| { 2487 // follow a cross-page link 2488 if (crossPageLink(root_focus, gid, session.data)) |route| { 2489 return session.navigate(route); 2490 } 2491 if (rawLink(root_focus, gid)) |url| return requestRawLink(session, url); 2492 } 2493 activate_in_page_link = true; 2494 try root.input(allocator, key, root_focus); 2495 }, 2496 .mouse => |mouse| { 2497 if (mouse.action == .press and mouse.action.press == .left) { 2498 if (root_focus.hitTest(mouse.x, mouse.y)) |hit| { 2499 const focus_id = hit.id; 2500 if (hit.kind == .background) { 2501 root_focus.setFocus(focus_id); 2502 return; 2503 } 2504 if (widget.isBackButton((root_focus.children.get(focus_id) orelse return).focus)) { 2505 if (session.back == .available) session.back = .requested; 2506 return; 2507 } 2508 // follow a cross-page link 2509 if (crossPageLink(root_focus, focus_id, session.data)) |route| { 2510 return session.navigate(route); 2511 } 2512 if (rawLink(root_focus, focus_id)) |url| { 2513 if (!mouse.ctrl) try requestRawLink(session, url); 2514 return; 2515 } 2516 root_focus.setFocus(focus_id); 2517 activate_in_page_link = true; 2518 } 2519 // forward the press into the widget tree so buttons (and any 2520 // future click-aware widgets) can react. widgets that don't 2521 // care about presses ignore it. 2522 try root.input(allocator, key, root_focus); 2523 } else { 2524 try root.input(allocator, key, root_focus); 2525 } 2526 }, 2527 else => try root.input(allocator, key, root_focus), 2528 } 2529 2530 const focused_after = root_focus.grandchild_id; 2531 if (!activate_in_page_link and focused_before == focused_after) return; 2532 const focus_id = focused_after orelse return; 2533 if (inPageLink(root_focus, focus_id, session.data)) |route| session.data.current_page = route; 2534 } 2535 2536 // a link to bytes the server serves directly rather than to a page route, so 2537 // it never resolves to a RoutablePage 2538 pub const raw_link_prefix = "ax:"; 2539 2540 // a route already loaded into the current page; focusing it changes the url 2541 // without rebuilding the page 2542 pub const in_page_link_prefix = "ai:"; 2543 2544 // an in-page tab's base route, or the exact current route when it is selected 2545 pub fn inPageTabLink(session: *Session, route: RoutablePage, selected: bool) ![]const u8 { 2546 const target = if (selected) session.data.current_page else route; 2547 return std.fmt.allocPrint(session.page_arena.allocator(), "{s}{s}", .{ in_page_link_prefix, try target.toUrl(session.page_arena) }); 2548 } 2549 2550 // a button the web renderer covers with a file picker that posts the chosen 2551 // file to the url after the prefix 2552 pub const file_input_prefix = "file:"; 2553 2554 // a submit button that overrides its enclosing form's action 2555 pub const submit_action_prefix = "submit:"; 2556 2557 // the url an `ax:` link points at, or null for anything else. a host that 2558 // suppresses the anchor's own navigation needs this to follow the link. 2559 pub fn rawLink(root_focus: *Focus, focus_id: usize) ?[]const u8 { 2560 const child = root_focus.children.get(focus_id) orelse return null; 2561 const custom = switch (child.focus.kind) { 2562 .custom => |c| c, 2563 else => return null, 2564 }; 2565 if (!std.mem.startsWith(u8, custom, raw_link_prefix)) return null; 2566 return custom[raw_link_prefix.len..]; 2567 } 2568 2569 fn requestRawLink(session: *Session, url: []const u8) !void { 2570 session.host_request = .{ .show_copyable_text = try terminalWebUrl(session.page_arena.allocator(), session, url) }; 2571 } 2572 2573 pub fn terminalWebUrl(allocator: std.mem.Allocator, session: *const Session, path: []const u8) ![]const u8 { 2574 // an absolute url is already complete 2575 if (!std.mem.startsWith(u8, path, "/")) return path; 2576 return if (session.web_port) |port| 2577 try std.fmt.allocPrint(allocator, "http://localhost:{d}{s}", .{ port, path }) 2578 else 2579 path; 2580 } 2581 2582 // if the focus target at focus_id is an `a:` link that should navigate (a 2583 // different parent page, or a different files directory within the repo page), 2584 // return its route; otherwise null. lets a host turn a click / enter on such a 2585 // link into a navigation rather than a focus change. 2586 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2587 const current = data.current_page; 2588 const route = pageLink(root_focus, focus_id, data, "a:") orelse return null; 2589 // a link to a different parent page always navigates; within a page, a 2590 // files-directory / commits-page / list-window change navigates while tab 2591 // links stay in-page. 2592 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; 2593 return null; 2594 } 2595 2596 // the route carried by an `ai:` focus target, or null for any other target 2597 pub fn inPageLink(root_focus: *Focus, focus_id: usize, data: Session.Data) ?RoutablePage { 2598 return pageLink(root_focus, focus_id, data, in_page_link_prefix); 2599 } 2600 2601 fn pageLink(root_focus: *Focus, focus_id: usize, data: Session.Data, prefix: []const u8) ?RoutablePage { 2602 const child = root_focus.children.get(focus_id) orelse return null; 2603 const custom = switch (child.focus.kind) { 2604 .custom => |c| c, 2605 else => return null, 2606 }; 2607 if (!std.mem.startsWith(u8, custom, prefix)) return null; 2608 const path = custom[prefix.len..]; 2609 // local sessions build (and parse) links with the repo identity elided 2610 return if (data.host_kind == .local) RoutablePage.fromUrlLocal(path) else RoutablePage.fromUrl(path); 2611 } 2612 2613 // a display author, resolved against the admin db at read time 2614 pub const Author = union(enum) { 2615 unknown, 2616 email: []const u8, // an email no user matches 2617 user_name: []const u8, 2618 2619 // the commit author line's email, resolved like initFromEmail 2620 pub fn init( 2621 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2622 arena: *std.heap.ArenaAllocator, 2623 author_line: []const u8, 2624 ) !Author { 2625 return initFromEmail(haxy_moment, arena, evt.authorEmail(author_line)); 2626 } 2627 2628 // from a record's stored author email: it resolves to the user currently 2629 // holding it, else stays the email. the result is allocated in `arena`, 2630 // so the email may borrow transient memory. 2631 pub fn initFromEmail( 2632 haxy_moment: ?evt.AdminDB.HashMap(.read_only), 2633 arena: *std.heap.ArenaAllocator, 2634 author_email: ?[]const u8, 2635 ) !Author { 2636 const email = author_email orelse return .unknown; 2637 if (haxy_moment) |moment| { 2638 if (try evt.User.readByEmail(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, email)) |user| { 2639 return .{ .user_name = user.name }; 2640 } 2641 } 2642 return .{ .email = try arena.allocator().dupe(u8, email) }; 2643 } 2644 }; 2645 2646 // the "a:" link to user `name`'s page. 2647 pub fn userLink(page_arena: *std.heap.ArenaAllocator, name: []const u8) ![]const u8 { 2648 const parsed = RoutablePage.Array(evt.User.name_max_len).from(name) orelse return error.RouteTooLong; 2649 const url = try (RoutablePage{ .user_repos = .{ .name = parsed } }).toUrl(page_arena); 2650 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{url}); 2651 } 2652 2653 // a focusable " author " box showing `author`, linking to their user page 2654 // when it is a known user 2655 pub fn authorBox(allocator: std.mem.Allocator, page_arena: *std.heap.ArenaAllocator, author: Author) !wgt.TextBox { 2656 const text = switch (author) { 2657 .unknown => "", 2658 .email, .user_name => |t| t, 2659 }; 2660 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = .single, .round_corners = true, .wrap_kind = .none, .label = " author " }); 2661 errdefer tb.deinit(allocator); 2662 tb.getFocus().mode = .all; 2663 switch (author) { 2664 .user_name => |name| tb.getFocus().kind = .{ .custom = try userLink(page_arena, name) }, 2665 else => {}, 2666 } 2667 return tb; 2668 } 2669 2670 // native-TUI navigation 2671 pub const Nav = struct { 2672 root: Widget, 2673 // backs the current page (its Page data and the page-scoped strings its 2674 // widgets build). owned here, swapped on each navigation. session.page_arena 2675 // tracks whichever of these is current so widgets allocate into it. 2676 arena: *std.heap.ArenaAllocator, 2677 history: std.ArrayList(Entry), 2678 2679 // each retained page keeps its own arena, freed when the page leaves the 2680 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 2681 // long-lived session from accumulating every page it ever visited. 2682 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 2683 2684 // cap on retained back-history so the chain can't grow memory without bound 2685 const max_history: usize = 16; 2686 2687 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 2688 session.back = .unavailable; 2689 const arena = try allocator.create(std.heap.ArenaAllocator); 2690 arena.* = std.heap.ArenaAllocator.init(allocator); 2691 errdefer { 2692 arena.deinit(); 2693 allocator.destroy(arena); 2694 } 2695 2696 session.page_arena = arena; 2697 const route = session.data.current_page; 2698 2699 const page = try arena.allocator().create(Page); 2700 page.* = try Page.init(arena, session, route); 2701 return .{ 2702 .root = try initRoot(allocator, page, session), 2703 .arena = arena, 2704 .history = .empty, 2705 }; 2706 } 2707 2708 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 2709 self.root.deinit(allocator); 2710 freeArena(allocator, self.arena); 2711 for (self.history.items) |*entry| { 2712 entry.root.deinit(allocator); 2713 freeArena(allocator, entry.arena); 2714 } 2715 self.history.deinit(allocator); 2716 } 2717 2718 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 2719 arena.deinit(); 2720 allocator.destroy(arena); 2721 } 2722 2723 // reconcile the displayed root with the session's navigation state. a 2724 // forward nav (current_page moved to a different parent page) pushes the 2725 // current root and builds the new page in a fresh arena; a back request 2726 // frees the current page and restores the previous one. when escape is 2727 // pressed with no history left we switch to the quit tab instead of quitting. 2728 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 2729 // refresh: rebuild the current page in place from a current moment 2730 if (session.refresh_requested) { 2731 session.refresh_requested = false; 2732 if (session.haxy_moment != null or session.local != null) { 2733 const arena = try allocator.create(std.heap.ArenaAllocator); 2734 arena.* = std.heap.ArenaAllocator.init(allocator); 2735 errdefer freeArena(allocator, arena); 2736 2737 session.page_arena = arena; 2738 2739 const route = session.data.current_page; 2740 const page = try arena.allocator().create(Page); 2741 page.* = try Page.init(arena, session, route); 2742 const new_root = try initRoot(allocator, page, session); 2743 2744 self.root.deinit(allocator); 2745 freeArena(allocator, self.arena); 2746 self.root = new_root; 2747 self.arena = arena; 2748 } 2749 return; 2750 } 2751 2752 if (session.back == .requested) { 2753 if (self.history.pop()) |entry| { 2754 session.back = if (self.history.items.len == 0) .unavailable else .available; 2755 self.root.deinit(allocator); 2756 freeArena(allocator, self.arena); 2757 self.root = entry.root; 2758 self.arena = entry.arena; 2759 session.page_arena = entry.arena; 2760 session.data.current_page = entry.route; 2761 chooseAnsiArtForNavigation(session); 2762 return; 2763 } 2764 session.back = .unavailable; 2765 // nothing to go back to; switch to the quit confirmation 2766 const root_focus = self.root.getFocus(); 2767 var iter = root_focus.children.iterator(); 2768 while (iter.next()) |entry| { 2769 switch (entry.value_ptr.focus.kind) { 2770 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 2771 root_focus.setFocus(entry.key_ptr.*); 2772 // a Stack only builds its selected child, so the quit 2773 // button isn't in the focus tree until a build runs with 2774 // the quit tab selected. build once, then send a 2775 // synthetic arrow_down to drop focus from the tab onto 2776 // the button so it's ready to confirm. 2777 try self.root.build(allocator, .{ 2778 .min_size = .{ .width = null, .height = 40 }, 2779 .max_size = .{ .width = 80, .height = null }, 2780 }, root_focus); 2781 try self.root.input(allocator, .arrow_down, root_focus); 2782 break; 2783 }, 2784 else => {}, 2785 } 2786 } 2787 return; 2788 } 2789 2790 // forward navigation: navigate() set next_page to the page to move to (a 2791 // cross-page link or tab change crossing pages) 2792 if (session.next_page) |route| { 2793 session.next_page = null; 2794 if (session.haxy_moment == null and session.local == null) return; 2795 const previous_route = session.data.current_page; 2796 // the page we navigated to becomes the current page 2797 session.data.current_page = route; 2798 session.back = .available; 2799 2800 const arena = try allocator.create(std.heap.ArenaAllocator); 2801 arena.* = std.heap.ArenaAllocator.init(allocator); 2802 errdefer freeArena(allocator, arena); 2803 2804 session.page_arena = arena; 2805 2806 const page = try arena.allocator().create(Page); 2807 page.* = try Page.init(arena, session, route); 2808 const new_root = try initRoot(allocator, page, session); 2809 2810 try self.history.append(allocator, .{ .root = self.root, .route = previous_route, .arena = self.arena }); 2811 // drop the oldest entry (freeing its widget tree and arena) once over cap 2812 if (self.history.items.len > max_history) { 2813 var oldest = self.history.orderedRemove(0); 2814 oldest.root.deinit(allocator); 2815 freeArena(allocator, oldest.arena); 2816 } 2817 self.root = new_root; 2818 self.arena = arena; 2819 } 2820 } 2821 }; 2822 2823 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 2824 const page_widget: Widget = switch (page.*) { 2825 .home => |*p| .{ .home = try .init(allocator, p, session) }, 2826 .user => |*p| .{ .user = try .init(allocator, p, session) }, 2827 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 2828 .fork => |*p| .{ .fork = try .init(allocator, p, session) }, 2829 }; 2830 2831 chooseAnsiArtForNavigation(session); 2832 2833 // on the TUI/SSH, the page sits above a one-row footer showing its web 2834 // url, when there's a web UI to point at 2835 var root = if (session.is_terminal) blk: { 2836 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 2837 errdefer box.deinit(allocator); 2838 const bg_id = bg_blk: { 2839 var background = try widget.AnsiBackground.init(allocator, page_widget, session); 2840 errdefer background.deinit(allocator); 2841 const id = background.getFocus().id; 2842 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 2843 break :bg_blk id; 2844 }; 2845 if (session.web_port != null) { 2846 var footer = try widget.Footer.init(allocator, session); 2847 errdefer footer.deinit(allocator); 2848 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 2849 } 2850 box.getFocus().child_id = bg_id; 2851 break :blk Widget{ .box = box }; 2852 } else Widget{ .background = try widget.AnsiBackground.init(allocator, page_widget, session) }; 2853 errdefer root.deinit(allocator); 2854 2855 // input-owning views build their TextInputs in init, so reset their 2856 // registrations here 2857 session.text_inputs.clearRetainingCapacity(); 2858 2859 try root.build(allocator, .{ 2860 .min_size = .{ .width = null, .height = 40 }, 2861 .max_size = .{ .width = 100, .height = null }, 2862 }, root.getFocus()); 2863 2864 return root; 2865 } 2866 2867 // native and server-side sessions choose from the embedded collection. WASM 2868 // keeps the art serialized by the server instead. 2869 fn chooseAnsiArtForNavigation(session: *Session) void { 2870 if (comptime ansi_arts.len == 0) return; 2871 const io = session.io orelse return; 2872 var random: usize = undefined; 2873 io.random(std.mem.asBytes(&random)); 2874 session.data.ansi_art = ansi_arts[random % ansi_arts.len]; 2875 } 2876