╭ Files.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const evt = @import("../../event.zig"); 3 const ui = @import("../../ui.zig"); 4 const xit = @import("xit"); 5 const rp = xit.repo; 6 const tr = xit.tree; 7 const df = xit.diff; 8 const xitui = xit.xitui; 9 const wgt = xitui.widget; 10 const layout = xitui.layout; 11 const Key = xitui.input.Key; 12 const Grid = xitui.grid.Grid; 13 const Focus = xitui.focus.Focus; 14 const inp = @import("../input.zig"); 15 const fnd = @import("../../find.zig"); 16 17 // how many lines of a file's content one window shows before a "next" link. 18 const file_page = 5000; 19 20 // budget for the total bytes of file content preloaded (windowed) per page, 21 // so selecting a preloaded file shows its contents without a reload. 22 const max_preloaded_bytes = 2 * 1024 * 1024; 23 24 // how many rows a listing holds, for a directory and for search results alike. 25 const max_list_entries = 1000; 26 27 // one entry in the directory currently being viewed. 28 pub const Entry = struct { 29 name: []const u8, 30 is_dir: bool, 31 // a file's content window split into lines (each without its trailing 32 // newline); empty for directories and for binary or empty files. 33 lines: []const []const u8 = &.{}, 34 // true when xit's line iterator flagged the file as binary, so the detail 35 // pane shows a placeholder rather than its bytes. 36 is_binary: bool = false, 37 // the line index this window starts at (0 = the first window). non-zero only 38 // for the route's selected file, paginated by the url's `line`. 39 window_start: usize = 0, 40 // whether more lines exist after this window. 41 has_more: bool = false, 42 // whether this file's content was read; unloaded files load via their 43 // "a:" link. 44 loaded: bool = false, 45 }; 46 47 // where links and clone commands for this repository are rooted. 48 location: ui.RoutablePage.RepoLocation, 49 // the resolved ref this listing is read at (the default branch when the route 50 // didn't name one), so the view's directory links stay pinned to it. 51 ref_or_oid: ui.RoutablePage.RefOrOid, 52 ref_or_oid_value: []const u8, 53 patchrev_id: ?[]const u8 = null, 54 // the directory being viewed, relative to the repo root ("" at the root). 55 dir: []const u8, 56 // a file within `dir` to start selected (so its contents show and the url 57 // carries it), or null to fall back to a README / the first row. set when the 58 // route's path named a file rather than a directory. 59 selected_file: ?[]const u8 = null, 60 entries: []const Entry, 61 // true when the listing stopped at max_list_entries. 62 capped: bool = false, 63 // the decoded search term this listing holds the results of, or null for a 64 // plain directory listing. 65 find: ?[]const u8 = null, 66 // whether the viewed tree has a file index, so the search box shows and a 67 // find: route resolves. travels in the page json for the wasm view. 68 find_available: bool = false, 69 70 const Self = @This(); 71 72 pub fn initPatchRev( 73 comptime repo_kind: rp.RepoKind, 74 comptime repo_opts: rp.RepoOpts(repo_kind), 75 arena: *std.heap.ArenaAllocator, 76 repo: *rp.Repo(repo_kind, repo_opts), 77 io: std.Io, 78 gpa: std.mem.Allocator, 79 location: ui.RoutablePage.RepoLocation, 80 id_hex: []const u8, 81 path: []const u8, 82 line: usize, 83 ) !Self { 84 const id = evt.parseEventId(id_hex) catch return error.NotFound; 85 const record = (try evt.readFromRepo(evt.PatchRev, repo_kind, repo_opts, io, gpa, arena, repo, &id)) orelse return error.NotFound; 86 if (record.removed) return error.NotFound; 87 var data = try init(repo_kind, repo_opts, arena, repo, io, gpa, location, .object, record.head_tree_oid, path, line, ""); 88 data.patchrev_id = try arena.allocator().dupe(u8, id_hex); 89 return data; 90 } 91 92 pub fn filesRoute(self: *const Self, path: []const u8, line: usize) ?ui.RoutablePage { 93 if (self.patchrev_id) |id| return switch (self.location) { 94 .repo => |identity| ui.RoutablePage.repoPatchRevFilesRoute(identity, id, path, line), 95 .fork => null, 96 }; 97 const route = self.location.filesRoute(self.ref_or_oid, self.ref_or_oid_value, path, line) orelse return null; 98 return route.withFind(self.find orelse return route); 99 } 100 101 // build the listing for an opened repo. generic over the repo's backend and 102 // hash kind so the tree/diff types it threads through match the repo's opts. 103 // reads with the arena's backing allocator (transient); the listing is built 104 // into the page arena so it outlives the repo handle. 105 pub fn init( 106 comptime repo_kind: rp.RepoKind, 107 comptime repo_opts: rp.RepoOpts(repo_kind), 108 arena: *std.heap.ArenaAllocator, 109 repo: *rp.Repo(repo_kind, repo_opts), 110 io: std.Io, 111 gpa: std.mem.Allocator, 112 location: ui.RoutablePage.RepoLocation, 113 requested_ref_or_oid: ?ui.RoutablePage.RefOrOid, 114 requested_value: []const u8, 115 path: []const u8, 116 line: usize, 117 find: []const u8, 118 ) !Self { 119 const aa = arena.allocator(); 120 const term: ?[]const u8 = if (find.len == 0) null else std.Uri.percentDecodeInPlace(try aa.dupe(u8, find)); 121 122 // resolve the requested ref (or the default branch) to the object oid whose 123 // tree we list. a ref the route named explicitly that doesn't resolve is a 124 // bad url (NotFound -> 404); the default-branch path falls through to empty. 125 const resolved = (try ui.ResolvedRefOrOid(repo_kind, repo_opts).init(repo, io, aa, requested_ref_or_oid, requested_value)) orelse { 126 if (requested_ref_or_oid != null or term != null) return error.NotFound; 127 return emptyResult(aa, location, .branch, requested_value, path); 128 }; 129 130 // read just the viewed directory of that tree or commit. building the 131 // read-only state mirrors what repo.status does internally, but for an 132 // arbitrary commit rather than HEAD. a path that doesn't exist in the tree 133 // is a bad url (404). 134 var moment = repo.core.latestMoment() catch return emptyResult(aa, location, resolved.ref_or_oid, resolved.value, path); 135 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 136 137 var entries: std.ArrayList(Entry) = .empty; 138 var capped = false; 139 var preloaded_bytes: usize = 0; 140 var find_available = false; 141 142 // the index covers branch tips only, so any other view gets no search box 143 // and refuses a find: url. 144 if (comptime repo_kind == .xit) index: { 145 if (resolved.ref_or_oid != .branch) break :index; 146 const branch = std.Uri.percentDecodeInPlace(try aa.dupe(u8, resolved.value)); 147 const files = (try fnd.lookup(repo_opts, moment, branch, &resolved.oid)) orelse break :index; 148 find_available = true; 149 const value = term orelse break :index; 150 // a result's name is its full path, so the listing has no directory and 151 // the selected row is named in full. 152 const selected: ?[]const u8 = if (path.len == 0) null else try aa.dupe(u8, path); 153 const results = try fnd.search(repo_opts, files, aa, value, max_list_entries); 154 capped = results.capped; 155 var found = false; 156 for (results.matches) |match| { 157 if (selected) |sf| found = found or std.mem.eql(u8, sf, match.path); 158 try entries.append(aa, try fileEntry(repo_kind, repo_opts, state, io, gpa, aa, "", match.path, &match.oid, null, selected, line, &preloaded_bytes)); 159 } 160 // the cap can cut off the row the url names, so bring it back 161 if (capped and !found) { 162 if (selected) |sf| if (try fnd.get(repo_opts, files, aa, sf)) |*oid| { 163 try entries.append(aa, try fileEntry(repo_kind, repo_opts, state, io, gpa, aa, "", sf, oid, null, selected, line, &preloaded_bytes)); 164 }; 165 } 166 return .{ 167 .location = try location.dupe(aa), 168 .ref_or_oid = resolved.ref_or_oid, 169 .ref_or_oid_value = resolved.value, 170 .dir = "", 171 .selected_file = selected, 172 .entries = entries.items, 173 .capped = capped, 174 .find = value, 175 .find_available = true, 176 }; 177 } 178 if (term != null) return error.NotFound; 179 180 var tree_dir = tr.TreeDir(repo_kind, repo_opts).init(state, io, gpa, &resolved.oid, path) catch |err| switch (err) { 181 error.TreeEntryNotFound => return error.NotFound, 182 else => return emptyResult(aa, location, resolved.ref_or_oid, resolved.value, path), 183 }; 184 defer tree_dir.deinit(); 185 186 // when `path` named a file, the listing is its parent directory with that 187 // file selected. 188 var dir = path; 189 var selected_file: ?[]const u8 = null; 190 if (tree_dir.file_name != null) { 191 const slash = std.mem.lastIndexOfScalar(u8, path, '/'); 192 selected_file = try aa.dupe(u8, if (slash) |s| path[s + 1 ..] else path); 193 dir = if (slash) |s| path[0..s] else ""; 194 } 195 196 // tree objects store their entries in name order, so the listing is 197 // already sorted. group directories before files, keeping that order 198 // within each group, and dupe into the page arena. file contents are read 199 // here (into the page arena) so the detail pane can show them without 200 // another lookup. 201 try entries.ensureTotalCapacity(aa, @min(tree_dir.entries.count(), max_list_entries)); 202 for ([_]bool{ true, false }) |want_dir| { 203 for (tree_dir.entries.keys(), tree_dir.entries.values()) |name, tree_entry| { 204 if (tree_entry.isTree() != want_dir) continue; 205 if (want_dir) { 206 if (entries.items.len >= max_list_entries) { 207 capped = true; 208 continue; 209 } 210 try entries.append(aa, .{ .name = try aa.dupe(u8, name), .is_dir = true }); 211 } else { 212 // the rows the route and the default selection need are exempt 213 // from the cap, so a url naming a file always gets its row. 214 const exempt = isReadme(name) or (if (selected_file) |sf| std.mem.eql(u8, sf, name) else false); 215 if (entries.items.len >= max_list_entries and !exempt) { 216 capped = true; 217 continue; 218 } 219 try entries.append(aa, try fileEntry(repo_kind, repo_opts, state, io, gpa, aa, dir, name, &tree_entry.oid, tree_entry.mode, selected_file, line, &preloaded_bytes)); 220 } 221 } 222 } 223 224 return .{ 225 .location = try location.dupe(aa), 226 .ref_or_oid = resolved.ref_or_oid, 227 .ref_or_oid_value = resolved.value, 228 .dir = try aa.dupe(u8, dir), 229 .selected_file = selected_file, 230 .entries = entries.items, 231 .capped = capped, 232 .find_available = find_available, 233 }; 234 } 235 236 // build one file's row, reading its content window when the preload budget (or 237 // the route) calls for it. only the route's selected file paginates; the rest 238 // show their first window, for the in-page detail when selected. 239 fn fileEntry( 240 comptime repo_kind: rp.RepoKind, 241 comptime repo_opts: rp.RepoOpts(repo_kind), 242 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 243 io: std.Io, 244 gpa: std.mem.Allocator, 245 aa: std.mem.Allocator, 246 dir: []const u8, 247 name: []const u8, 248 oid: *const [xit.hash.byteLen(repo_opts.hash)]u8, 249 // null for a search result, which the index only holds files for 250 mode: ?xit.fs.Mode, 251 selected_file: ?[]const u8, 252 line: usize, 253 preloaded_bytes: *usize, 254 ) !Entry { 255 var entry: Entry = .{ .name = try aa.dupe(u8, name), .is_dir = false }; 256 const is_selected = if (selected_file) |sf| std.mem.eql(u8, sf, name) else false; 257 // the README always loads because it's the default selection. 258 if (preloaded_bytes.* >= max_preloaded_bytes and !is_selected and !isReadme(name)) return entry; 259 const file_path = try childDir(aa, dir, name); 260 // the url's `line` is 1-based (0 = unset); the window index is 0-based. 261 const window_start = if (is_selected) line -| 1 else 0; 262 const content = readFileContent(repo_kind, repo_opts, state, io, gpa, aa, file_path, oid, mode, window_start) catch 263 FileContent{ .lines = &.{} }; 264 for (content.lines) |l| preloaded_bytes.* += l.len; 265 entry.lines = content.lines; 266 entry.is_binary = content.is_binary; 267 entry.window_start = window_start; 268 entry.has_more = content.has_more; 269 entry.loaded = true; 270 return entry; 271 } 272 273 const FileContent = struct { 274 lines: []const []const u8, 275 is_binary: bool = false, 276 has_more: bool = false, 277 }; 278 279 // read the window [start, start+file_page) of a committed file's contents at 280 // `oid` into `arena`-owned lines, flagging whether more follow. xit's 281 // line iterator flags binary files (its source becomes `.binary`), in which case 282 // we report no lines and let the view show a placeholder. 283 fn readFileContent( 284 comptime repo_kind: rp.RepoKind, 285 comptime repo_opts: rp.RepoOpts(repo_kind), 286 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 287 io: std.Io, 288 gpa: std.mem.Allocator, 289 arena: std.mem.Allocator, 290 path: []const u8, 291 oid: *const [xit.hash.byteLen(repo_opts.hash)]u8, 292 mode: ?xit.fs.Mode, 293 start: usize, 294 ) !FileContent { 295 var line_iter = try df.LineIterator(repo_kind, repo_opts).initFromOid(state, io, gpa, path, oid, mode); 296 defer line_iter.deinit(); 297 if (line_iter.source == .binary) return .{ .lines = &.{}, .is_binary = true }; 298 299 // init reads through the file to validate it (and buffer it in memory), so 300 // the line count is known and a window can be sliced out of the buffer. 301 const total = line_iter.count(); 302 const end = @min(start +| file_page, total); 303 304 var lines: std.ArrayList([]const u8) = .empty; 305 var i = start; 306 while (i < end) : (i += 1) { 307 const line = try line_iter.get(i); 308 try lines.append(arena, try arena.dupe(u8, line)); 309 } 310 return .{ 311 .lines = try lines.toOwnedSlice(arena), 312 .has_more = end < total, 313 }; 314 } 315 316 // an empty listing pinned to a ref, for the wasm / no-repo / unresolved paths. 317 pub fn emptyResult(aa: std.mem.Allocator, location: ui.RoutablePage.RepoLocation, ref_or_oid: ui.RoutablePage.RefOrOid, ref_or_oid_value: []const u8, dir: []const u8) !Self { 318 return .{ 319 .location = try location.dupe(aa), 320 .ref_or_oid = ref_or_oid, 321 .ref_or_oid_value = try aa.dupe(u8, ref_or_oid_value), 322 .dir = try aa.dupe(u8, dir), 323 .entries = &.{}, 324 }; 325 } 326 327 pub const View = struct { 328 // a vertical stack: the search box and clone url on top, then a horizontal 329 // split with the file/directory list on the left and a detail pane on the 330 // right showing the selected file's contents. 331 box: wgt.Box(ui.Widget), // vert: [header_index] = header row, [content_index] = split 332 data: *const Self, 333 session: *ui.Session, 334 // the list row whose contents the detail pane currently shows. 335 shown_index: ?usize, 336 337 // the sub-header leads the box where there is one; local mode has none 338 const header_index: usize = 0; 339 // indices within the content box (the horizontal split). 340 const list_index: usize = 0; 341 const detail_index: usize = 1; 342 // indices within the detail pane frame (nav box above the content scroll). 343 const detail_nav_index: usize = 0; 344 const detail_scroll_index: usize = 1; 345 const list_max_width: usize = 35; 346 const detail_min_width: usize = 40; 347 // a list row's height: one text line inside its (hidden) border. 348 const row_height: usize = 3; 349 350 pub fn init(allocator: std.mem.Allocator, data: *const Self, session: *ui.Session) !View { 351 var outer = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 352 errdefer outer.deinit(allocator); 353 354 // the search box and the clone url at the top. local mode has neither. 355 if (session.data.host_kind == .server) { 356 var header_view = try ui.widget.SearchHeader.init(allocator, session, data.location, " find file ", "find", data.find, data.find_available); 357 errdefer header_view.deinit(allocator); 358 try outer.children.put(allocator, header_view.getFocus().id, .{ .widget = .{ .search_header = header_view }, .rect = null, .min_size = .{ .width = null, .height = 3 } }); 359 } 360 361 var box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 362 errdefer box.deinit(allocator); 363 364 // the directory listing on the left (one focusable row each). 365 { 366 var list_scroll = blk: { 367 var list_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert, .stretch = true }); 368 errdefer list_box.deinit(allocator); 369 370 // link kinds are borrowed by the rows, so they live in the page 371 // arena (as long as this page's widget tree). row labels are 372 // copied by their text boxes. 373 const aa = session.page_arena.allocator(); 374 if (data.dir.len != 0) { 375 try addRow(allocator, &list_box, "..", "", try dirLink(session.page_arena, data, parentDir(data.dir))); 376 } 377 for (data.entries) |entry| { 378 const path = try childDir(aa, data.dir, entry.name); 379 // a search result shows its file name, with its directory 380 // in the bottom label. 381 const label = if (data.find != null) 382 std.fs.path.basenamePosix(entry.name) 383 else if (entry.is_dir) 384 try std.fmt.allocPrint(aa, "{s}/", .{entry.name}) 385 else 386 entry.name; 387 const bottom_label = if (data.find != null) try resultDirLabel(aa, entry.name) else ""; 388 const link = if (entry.is_dir) 389 try dirLink(session.page_arena, data, path) 390 else 391 try fileLink(session.page_arena, data, path, entry.loaded, lineNumber(entry.window_start)); 392 try addRow(allocator, &list_box, label, bottom_label, link); 393 } 394 if (data.capped) try addRow(allocator, &list_box, "(list truncated)", "", ""); 395 // select the file the route named, else prefer a README so its 396 // contents greet the visitor in the detail pane, else the first 397 // row. a non-root directory has a leading ".." row, so the entry 398 // index is offset by one there. search results have no README 399 // default: the term decides what matters. 400 var sel: usize = 0; 401 if (list_box.children.count() > 0) { 402 const base: usize = if (data.dir.len != 0) 1 else 0; 403 const entry_idx = selectedFileIndex(data) orelse if (data.find == null) readmeIndex(data.entries) else null; 404 sel = if (entry_idx) |i| i + base else 0; 405 list_box.getFocus().child_id = list_box.children.keys()[sel]; 406 } 407 var sc = try wgt.Scroll(ui.Widget).init(allocator, .{ .box = list_box }, .{ .direction = .vert, .web_native = !session.is_terminal, .fill = true }); 408 // start scrolled so the selected row begins at the top of the 409 // viewport. rows are a fixed height, so no layout pass is 410 // needed; a too-far offset near the end of the list is clamped 411 // in build (the browser clamps its own scrolling natively). 412 sc.y = @intCast(sel * row_height); 413 break :blk sc; 414 }; 415 errdefer list_scroll.deinit(allocator); 416 try box.children.put(allocator, list_scroll.getFocus().id, .{ .widget = .{ .scroll = list_scroll }, .rect = null, .min_size = .{ .width = list_max_width, .height = null }, .max_size = .{ .width = list_max_width, .height = null } }); 417 } 418 419 // the detail pane on the right — a "next" nav box above a scroll of the 420 // selected file's content window. both are repopulated per selection by 421 // populateDetail. 422 { 423 var detail_outer = blk: { 424 var frame = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 425 errdefer frame.deinit(allocator); 426 427 { 428 var nav_box = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .horiz }); 429 errdefer nav_box.deinit(allocator); 430 try frame.children.put(allocator, nav_box.getFocus().id, .{ .widget = .{ .box = nav_box }, .rect = null, .min_size = null }); 431 } 432 { 433 // the content scroll wrapped in a bordered box; build sets the 434 // border single normally and double when the content is focused 435 // (the content box itself is borderless). 436 var scroll_frame = blk2: { 437 var detail_scroll = blk3: { 438 var detail_inner = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 439 errdefer detail_inner.deinit(allocator); 440 break :blk3 try wgt.Scroll(ui.Widget).init(allocator, .{ .box = detail_inner }, .{ .direction = .both, .web_native = !session.is_terminal, .fill = true }); 441 }; 442 errdefer detail_scroll.deinit(allocator); 443 var sf = try wgt.Box(ui.Widget).init(allocator, .{ .border_style = .single, .rounded_corners = true, .direction = .vert }); 444 errdefer sf.deinit(allocator); 445 // the wrapper's selected child is its scroll, so the focus 446 // chain reaches the content box (populateDetail points the 447 // scroll's inner box at it). 448 sf.getFocus().child_id = detail_scroll.getFocus().id; 449 try sf.children.put(allocator, detail_scroll.getFocus().id, .{ .widget = .{ .scroll = detail_scroll }, .rect = null, .min_size = null }); 450 break :blk2 sf; 451 }; 452 errdefer scroll_frame.deinit(allocator); 453 // entering the detail pane lands on the content scroll (focus 454 // recovery descends the frame's selected child). the nav links 455 // above are reached by scrolling to the top, then up. 456 frame.getFocus().child_id = scroll_frame.getFocus().id; 457 // shrink, so the fill scroll yields the nav box's row 458 // instead of consuming the frame's whole height. 459 try frame.children.put(allocator, scroll_frame.getFocus().id, .{ .widget = .{ .box = scroll_frame }, .rect = null, .min_size = null, .flex = .shrink }); 460 } 461 break :blk frame; 462 }; 463 errdefer detail_outer.deinit(allocator); 464 detail_outer.getFocus().mode = .mouse; 465 try box.children.put(allocator, detail_outer.getFocus().id, .{ .widget = .{ .box = detail_outer }, .rect = null, .min_size = .{ .width = detail_min_width, .height = null } }); 466 } 467 468 box.getFocus().child_id = box.children.keys()[list_index]; 469 try outer.children.put(allocator, box.getFocus().id, .{ .widget = .{ .box = box }, .rect = null, .min_size = null }); 470 471 // focus lives in the split, except that search results start in the 472 // search box so the term can be refined right away. 473 outer.getFocus().child_id = outer.children.keys()[if (data.find != null) header_index else outer.children.count() - 1]; 474 return .{ .box = outer, .data = data, .session = session, .shown_index = null }; 475 } 476 477 fn addRow(allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, bottom_label: []const u8, link: []const u8) !void { 478 var row = try wgt.TextBox.init(allocator, label, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .none, .bottom_label = bottom_label }); 479 errdefer row.deinit(allocator); 480 row.getFocus().mode = .all; 481 if (link.len != 0) row.getFocus().kind = .{ .custom = link }; 482 try box.children.put(allocator, row.getFocus().id, .{ .widget = .{ .text_box = row }, .rect = null, .min_size = null }); 483 } 484 485 // the selected file's contents as a single focusable multi-line text box. 486 // it's borderless — the border lives on the surrounding scroll frame, which 487 // doubles when this content is focused. a non-empty `link` makes activating 488 // the box follow it, like addRow. 489 fn addContentBox(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), text: []const u8, link: []const u8) !void { 490 _ = self; 491 var tb = try wgt.TextBox.init(allocator, text, .{ .border_style = null, .wrap_kind = .none }); 492 errdefer tb.deinit(allocator); 493 tb.getFocus().mode = .all; 494 if (link.len != 0) tb.getFocus().kind = .{ .custom = link }; 495 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 496 } 497 498 pub fn deinit(self: *View, allocator: std.mem.Allocator) void { 499 self.box.deinit(allocator); 500 } 501 502 // the split is last, after the sub-header where there is one 503 fn contentIndex(self: *View) usize { 504 return self.box.children.count() - 1; 505 } 506 507 fn contentBox(self: *View) *wgt.Box(ui.Widget) { 508 return &self.box.children.values()[self.contentIndex()].widget.box; 509 } 510 511 fn header(self: *View) ?*ui.widget.SearchHeader { 512 switch (self.box.children.values()[header_index].widget) { 513 .search_header => |*header_view| return header_view, 514 else => return null, 515 } 516 } 517 518 fn headerActive(self: *View) bool { 519 const header_view = self.header() orelse return false; 520 return self.box.getFocus().child_id == header_view.getFocus().id; 521 } 522 523 fn listScroll(self: *View) *wgt.Scroll(ui.Widget) { 524 return &self.contentBox().children.values()[list_index].widget.scroll; 525 } 526 527 fn listBox(self: *View) *wgt.Box(ui.Widget) { 528 return &self.listScroll().child.box; 529 } 530 531 fn detailOuter(self: *View) *wgt.Box(ui.Widget) { 532 return &self.contentBox().children.values()[detail_index].widget.box; 533 } 534 535 fn navBox(self: *View) *wgt.Box(ui.Widget) { 536 return &self.detailOuter().children.values()[detail_nav_index].widget.box; 537 } 538 539 // the bordered box wrapping the content scroll (border toggles with focus). 540 fn detailScrollFrame(self: *View) *wgt.Box(ui.Widget) { 541 return &self.detailOuter().children.values()[detail_scroll_index].widget.box; 542 } 543 544 fn detailScroll(self: *View) *wgt.Scroll(ui.Widget) { 545 return &self.detailScrollFrame().children.values()[0].widget.scroll; 546 } 547 548 fn detailInner(self: *View) *wgt.Box(ui.Widget) { 549 return &self.detailScroll().child.box; 550 } 551 552 fn detailActive(self: *View) bool { 553 const content = self.contentBox(); 554 const cid = content.getFocus().child_id orelse return false; 555 return content.children.getIndex(cid) == detail_index; 556 } 557 558 // the selected list row's index, or null when nothing is focused. 559 fn selectedRowIndex(self: *View) ?usize { 560 const lb = self.listBox(); 561 const cid = lb.getFocus().child_id orelse return null; 562 return lb.children.getIndex(cid); 563 } 564 565 // the entry the selected row points at, or null for the ".." row (which 566 // isn't an entry). directory rows return their entry too, though they carry 567 // no contents. 568 fn selectedEntry(self: *View) ?Entry { 569 const idx = self.selectedRowIndex() orelse return null; 570 const base: usize = if (self.data.dir.len != 0) 1 else 0; // skip the ".." row 571 if (idx < base) return null; 572 const e = idx - base; 573 if (e >= self.data.entries.len) return null; 574 return self.data.entries[e]; 575 } 576 577 pub fn build(self: *View, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 578 self.clearGrid(); 579 580 // swap the detail pane to the selected entry when the selection changes. 581 try self.refreshDetail(allocator); 582 583 // the selected list row shows a border (the focused TextBox upgrades it 584 // to a double border itself); the rest stay borderless. 585 const lb = self.listBox(); 586 for (lb.children.keys(), lb.children.values()) |id, *child| { 587 switch (child.widget) { 588 .text_box => |*tb| ui.widget.markSelected(tb, lb.getFocus().child_id == id), 589 else => {}, 590 } 591 } 592 593 // the content scroll's border is single normally and double when the 594 // content is focused (the content box itself is borderless). 595 const has_content = self.detailInner().children.count() > 0; 596 const content_focused = if (root_focus.grandchild_id) |g| self.detailInner().children.contains(g) else false; 597 self.detailScrollFrame().options.border_style = if (!has_content) null else if (content_focused) .double else .single; 598 599 // cap the list at list_max_width only while the detail pane fits beside 600 // it. the box drops the detail pane when the width can't hold both 601 // minimums, so when it's that narrow we lift the cap and let the list 602 // fill the whole width. 603 const both_panes_fit = if (constraint.max_size.width) |w| w >= list_max_width + detail_min_width else true; 604 self.contentBox().children.values()[list_index].max_size = if (both_panes_fit) .{ .width = list_max_width, .height = null } else null; 605 606 // stretch the detail pane and its bordered scroll frame across the rest 607 // of the width so the pane fills the area rather than shrinking to its 608 // content, like the refs view's columns. the content scroll inside keeps 609 // its natural width: forcing it to the full inner width would make it one 610 // column too wide whenever the vertical scrollbar appears, leaving a 611 // phantom horizontal scroll. (height fills via the scroll clipping to the 612 // viewport.) 613 if (constraint.max_size.width) |w| { 614 const detail_w = if (both_panes_fit) w - list_max_width else w; 615 self.contentBox().children.values()[detail_index].min_size = .{ .width = detail_w, .height = null }; 616 self.detailOuter().children.values()[detail_scroll_index].min_size = .{ .width = detail_w, .height = null }; 617 } else { 618 self.contentBox().children.values()[detail_index].min_size = .{ .width = detail_min_width, .height = null }; 619 self.detailOuter().children.values()[detail_scroll_index].min_size = null; 620 } 621 622 // crossing panes only re-selects the content box's child (focusList / 623 // focusDetail); when the window is too narrow to show both, the pane that 624 // was holding focus is dropped here. the framework recovers focus after 625 // the top-level build by re-deriving it down the selected-child chain, so 626 // there's nothing to fix up afterward. 627 try self.box.build(allocator, constraint, root_focus); 628 629 // clamp the list's initial offset (a selected row near the end of the 630 // list) against this build's grids, for the next frame. initRoot's 631 // pre-sizing build is unbounded — its full-content "viewport" would 632 // clamp the offset to zero, so only a bounded build counts. 633 if (constraint.max_size.height != null) self.listScroll().clampToContent(); 634 } 635 636 fn refreshDetail(self: *View, allocator: std.mem.Allocator) !void { 637 const cur = self.selectedRowIndex(); 638 if (std.meta.eql(cur, self.shown_index)) return; 639 try self.populateDetail(allocator); 640 self.shown_index = cur; 641 } 642 643 fn populateDetail(self: *View, allocator: std.mem.Allocator) !void { 644 const nav_box = self.navBox(); 645 const inner = self.detailInner(); 646 647 for (nav_box.children.values()) |*child| child.widget.deinit(allocator); 648 nav_box.children.clearAndFree(allocator); 649 nav_box.getFocus().child_id = null; 650 for (inner.children.values()) |*child| child.widget.deinit(allocator); 651 inner.children.clearAndFree(allocator); 652 inner.getFocus().child_id = null; 653 654 // only files have contents to show; directories and the ".." row leave 655 // the pane empty. 656 if (self.selectedEntry()) |entry| { 657 if (!entry.is_dir) { 658 // the window links sit above the scroll, so they stay put 659 // while the content scrolls. 660 if (entry.window_start > 0) try self.addNavLink(allocator, nav_box, "scroll to top", entry, 0); 661 if (entry.has_more) try self.addNavLink(allocator, nav_box, "next lines →", entry, lineNumber(entry.window_start + file_page)); 662 if (!entry.loaded) { 663 // the placeholder carries the file's "a:" link, so enter 664 // (or a click) here loads the file like on its list row. 665 const path = try childDir(self.session.page_arena.allocator(), self.data.dir, entry.name); 666 const link = try fileLink(self.session.page_arena, self.data, path, false, 0); 667 try self.addContentBox(allocator, inner, "(press enter to load this file)", link); 668 } else if (entry.is_binary) { 669 try self.addContentBox(allocator, inner, "(binary file)", ""); 670 } else { 671 const text = try numberedContent(self.session.page_arena.allocator(), entry.lines, entry.window_start); 672 try self.addContentBox(allocator, inner, text, ""); 673 } 674 } 675 } 676 // point each box at its first child so focus can descend into it. 677 if (nav_box.children.count() > 0) nav_box.getFocus().child_id = nav_box.children.keys()[0]; 678 if (inner.children.count() > 0) inner.getFocus().child_id = inner.children.keys()[0]; 679 680 // reserve the nav row's height (the shrink scroll frame yields it). 681 self.detailOuter().children.values()[detail_nav_index].min_size = 682 if (nav_box.children.count() > 0) .{ .width = null, .height = row_height } else null; 683 684 // reset the scroll to the top for the newly-shown file: directly on the 685 // terminal (the wasm offset), and via a version bump on the web (so the 686 // renderer's scroll id changes and JS drops the preserved position). 687 const sc = self.detailScroll(); 688 sc.x = 0; 689 sc.y = 0; 690 sc.getFocus().version +%= 1; 691 } 692 693 // a focusable "next" link above the content. it's an `a:` link to the 694 // selected file at `target_start`, so activating it (the host follows the 695 // link) reloads the page on the next window. 696 fn addNavLink(self: *View, allocator: std.mem.Allocator, box: *wgt.Box(ui.Widget), label: []const u8, entry: Entry, target_start: usize) !void { 697 const page_arena = self.session.page_arena; 698 const path = try childDir(page_arena.allocator(), self.data.dir, entry.name); 699 const route = self.data.filesRoute(path, target_start) orelse return error.RouteTooLong; 700 const link = try std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{try route.toUrl(page_arena)}); 701 var tb = try wgt.TextBox.init(allocator, label, .{ .border_style = .single, .rounded_corners = true, .wrap_kind = .none }); 702 errdefer tb.deinit(allocator); 703 tb.getFocus().mode = .all; 704 tb.getFocus().kind = .{ .custom = link }; 705 try box.children.put(allocator, tb.getFocus().id, .{ .widget = .{ .text_box = tb }, .rect = null, .min_size = null }); 706 } 707 708 pub fn input(self: *View, allocator: std.mem.Allocator, key: Key, root_focus: *Focus) !void { 709 // scrolling crosses the sub header boundary the same way arrows do 710 const direction = inp.vertDirection(key); 711 if (self.headerActive()) { 712 // active means there is one 713 const header_view = self.header() orelse unreachable; 714 if (direction == .down) { 715 root_focus.setFocus(self.contentBox().getFocus().id); 716 return; 717 } 718 if (key == .enter) if (try header_view.submittedText(allocator)) |term| { 719 defer allocator.free(term); 720 return self.submit(term); 721 }; 722 return header_view.input(allocator, key, root_focus); 723 } 724 if (direction == .up and self.contentAtTop() and self.focusHeader(root_focus)) return; 725 if (self.detailActive()) { 726 try self.detailInput(key, root_focus); 727 } else { 728 try self.listInput(key, root_focus); 729 } 730 } 731 732 // navigate to the typed term's results, pinned to the listing's ref. an 733 // empty term leaves the results for the plain listing. 734 fn submit(self: *View, term: []const u8) !void { 735 if (term.len == 0 and self.data.find == null) return; 736 const route = self.data.filesRoute("", 0) orelse return; 737 try self.session.navigate(route.withFind(term) orelse return); 738 } 739 740 fn listInput(self: *View, key: Key, root_focus: *Focus) !void { 741 // up/down (and the scroll wheel) move the selection; page up/down jump a 742 // fixed amount. right/Enter cross into the detail pane. Enter/clicks on a 743 // directory (or "..") row are turned into navigation by the host 744 // (crossPageLink) before reaching here. 745 if (inp.rowDelta(key, @intCast(self.listBox().children.count()))) |delta| { 746 ui.widget.moveRowFocus(self.listBox(), self.listScroll(), root_focus, delta); 747 return; 748 } 749 switch (key) { 750 .enter, .arrow_right => try self.focusDetail(root_focus), 751 else => {}, 752 } 753 } 754 755 // whether focus is on the content box (vs. a "previous"/"next" nav link). 756 fn focusOnContent(self: *View, root_focus: *Focus) bool { 757 const g = root_focus.grandchild_id orelse return false; 758 return self.detailInner().children.contains(g); 759 } 760 761 fn detailInput(self: *View, key: Key, root_focus: *Focus) !void { 762 const sc = self.detailScroll(); 763 const on_content = self.focusOnContent(root_focus); 764 // the "next" link sits above the content scroll. on the link, left returns 765 // to the file list and down drops into the content. in the content, the 766 // terminal scrolls by offset and reaching the top then pressing up crosses 767 // back up to the link; on the web vertical scrolling is the browser's job 768 // so up just crosses to the link. 769 switch (key) { 770 .arrow_left => { 771 if (on_content) { 772 if (sc.x > 0) { 773 sc.x -= 1; 774 self.detailScroll().clampToContent(); 775 } else try self.focusList(root_focus); 776 } else if (!self.moveNav(root_focus, -1)) { 777 try self.focusList(root_focus); 778 } 779 }, 780 .arrow_right => { 781 if (on_content) { 782 sc.x += 1; 783 self.detailScroll().clampToContent(); 784 } else _ = self.moveNav(root_focus, 1); 785 }, 786 .arrow_up => { 787 if (on_content) { 788 if (self.session.is_terminal and sc.y > 0) { 789 sc.y -= 1; 790 self.detailScroll().clampToContent(); 791 } else self.focusNav(root_focus); // cross up to the links 792 } 793 }, 794 .arrow_down => { 795 if (on_content) { 796 if (self.session.is_terminal) { 797 sc.y += 1; 798 self.detailScroll().clampToContent(); 799 } 800 } else self.focusContent(root_focus); // links -> content 801 }, 802 .page_up => if (on_content and self.session.is_terminal) { 803 sc.y -= 10; 804 self.detailScroll().clampToContent(); 805 }, 806 .page_down => if (on_content and self.session.is_terminal) { 807 sc.y += 10; 808 self.detailScroll().clampToContent(); 809 }, 810 .home => if (on_content and self.session.is_terminal) { 811 sc.y = 0; 812 self.detailScroll().clampToContent(); 813 }, 814 .end => if (on_content and self.session.is_terminal) { 815 sc.y = std.math.maxInt(isize); 816 self.detailScroll().clampToContent(); 817 }, 818 .mouse => |mouse| switch (mouse.action) { 819 .scroll => |dir| if (on_content and self.session.is_terminal) { 820 sc.y += if (dir == .up) -5 else 5; 821 self.detailScroll().clampToContent(); 822 }, 823 else => {}, 824 }, 825 else => {}, 826 } 827 } 828 829 // focus the first (left-most) nav link; a no-op when there are none, leaving 830 // focus on the content. 831 fn focusNav(self: *View, root_focus: *Focus) void { 832 const nav_box = self.navBox(); 833 if (nav_box.children.count() == 0) return; 834 root_focus.setFocus(nav_box.children.keys()[0]); 835 } 836 837 fn focusContent(self: *View, root_focus: *Focus) void { 838 const inner = self.detailInner(); 839 const id = inner.getFocus().child_id orelse (if (inner.children.count() > 0) inner.children.keys()[0] else return); 840 root_focus.setFocus(id); 841 } 842 843 // move focus `delta` rows within the nav box; returns false (without moving) 844 // when that would step off either end. 845 fn moveNav(self: *View, root_focus: *Focus, delta: isize) bool { 846 const nav_box = self.navBox(); 847 const keys = nav_box.children.keys(); 848 const cur_id = nav_box.getFocus().child_id orelse return false; 849 const cur: isize = @intCast(nav_box.children.getIndex(cur_id) orelse return false); 850 const target = cur + delta; 851 if (target < 0 or target >= @as(isize, @intCast(keys.len))) return false; 852 root_focus.setFocus(keys[@intCast(target)]); 853 return true; 854 } 855 856 // enter the detail pane, landing on the "next" link when there is one (so 857 // right-arrow reaches it), else on the content. a directory or ".." row has 858 // neither, so there's nothing to enter. selecting the frame's child (then 859 // focusing the frame) also handles the too-narrow case where the pane isn't 860 // laid out yet — focus lands inside it after the next build. 861 fn focusDetail(self: *View, root_focus: *Focus) !void { 862 const frame = self.detailOuter(); 863 if (self.navBox().children.count() > 0) { 864 frame.getFocus().child_id = self.navBox().getFocus().id; 865 } else if (self.detailInner().children.count() > 0) { 866 frame.getFocus().child_id = self.detailScrollFrame().getFocus().id; 867 } else return; 868 root_focus.setFocus(frame.getFocus().id); 869 } 870 871 // return to the list. 872 fn focusList(self: *View, root_focus: *Focus) !void { 873 root_focus.setFocus(self.listScroll().getFocus().id); 874 } 875 876 pub fn clearGrid(self: *View) void { 877 self.box.clearGrid(); 878 } 879 880 pub fn getGrid(self: View) ?Grid { 881 return self.box.getGrid(); 882 } 883 884 pub fn getFocus(self: *View) *Focus { 885 return self.box.getFocus(); 886 } 887 888 fn contentAtTop(self: *View) bool { 889 if (self.detailActive()) { 890 if (self.detailOuter().getFocus().child_id == self.navBox().getFocus().id) return true; 891 return self.navBox().children.count() == 0 and 892 (!self.session.is_terminal or self.detailScroll().y == 0); 893 } 894 const lb = self.listBox(); 895 const cid = lb.getFocus().child_id orelse return true; 896 return lb.children.getIndex(cid) == 0; 897 } 898 899 // only the header's own row sits directly below the repository header. 900 pub fn atTop(self: *View) bool { 901 const focusable = if (self.header()) |header_view| header_view.hasFocusable() else false; 902 return self.headerActive() or (!focusable and self.contentAtTop()); 903 } 904 905 pub fn focusHeader(self: *View, root_focus: *Focus) bool { 906 const header_view = self.header() orelse return false; 907 return header_view.focusHeader(root_focus); 908 } 909 }; 910 911 // join `lines` into one string, each prefixed with its 1-based file line number 912 // (right-aligned in a column wide enough for the last number, then a space), 913 // like the diffs view. `start` is the window's 0-based first line, so numbers 914 // continue across paginated windows. 915 fn numberedContent(arena: std.mem.Allocator, lines: []const []const u8, start: usize) ![]const u8 { 916 if (lines.len == 0) return ""; 917 const width = std.fmt.count("{d}", .{start + lines.len}); 918 const indent = try arena.alloc(u8, width); 919 @memset(indent, ' '); 920 921 var out: std.ArrayList(u8) = .empty; 922 for (lines, 0..) |line, i| { 923 if (i != 0) try out.append(arena, '\n'); 924 const num_str = try std.fmt.allocPrint(arena, "{d}", .{start + i + 1}); 925 try out.appendSlice(arena, indent[0 .. width - num_str.len]); 926 try out.appendSlice(arena, num_str); 927 try out.append(arena, ' '); 928 try out.appendSlice(arena, line); 929 } 930 return out.toOwnedSlice(arena); 931 } 932 933 // the index of the "README"/"README.md" file entry (case-insensitive), or null 934 // if none. used to pick the default selection at the repo root. 935 fn readmeIndex(entries: []const Entry) ?usize { 936 for (entries, 0..) |entry, i| { 937 if (!entry.is_dir and isReadme(entry.name)) return i; 938 } 939 return null; 940 } 941 942 fn isReadme(name: []const u8) bool { 943 return std.ascii.eqlIgnoreCase(name, "README") or std.ascii.eqlIgnoreCase(name, "README.md"); 944 } 945 946 // the index of the entry the route named (data.selected_file), or null if none. 947 fn selectedFileIndex(data: *const Self) ?usize { 948 const name = data.selected_file orelse return null; 949 for (data.entries, 0..) |entry, i| { 950 if (!entry.is_dir and std.mem.eql(u8, entry.name, name)) return i; 951 } 952 return null; 953 } 954 955 // an "a:" link to the files route at `path`, pinned to the listing's ref, so 956 // following it navigates to that directory's listing. 957 fn dirLink(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8) ![]const u8 { 958 const route = data.filesRoute(path, 0) orelse return error.RouteTooLong; 959 return std.fmt.allocPrint(page_arena.allocator(), "a:{s}", .{try route.toUrl(page_arena)}); 960 } 961 962 // a link to the file's route. a preloaded file gets an "ai:" link 963 // (crossPageLink ignores it, so a click selects the row in place and shows its 964 // contents); an unloaded file gets an "a:" link, so activating it reloads the 965 // page with that file selected and its content read. 966 fn fileLink(page_arena: *std.heap.ArenaAllocator, data: *const Self, path: []const u8, loaded: bool, line: usize) ![]const u8 { 967 const route = data.filesRoute(path, line) orelse return error.RouteTooLong; 968 const prefix = if (loaded) "ai:" else "a:"; 969 return std.fmt.allocPrint(page_arena.allocator(), "{s}{s}", .{ prefix, try route.toUrl(page_arena) }); 970 } 971 972 // the url `line` value for a content window: its first line's 1-based number, 973 // except the first window, which serializes as unset (0). 974 fn lineNumber(window_start: usize) usize { 975 return if (window_start == 0) 0 else window_start + 1; 976 } 977 978 // `dir`/`name`, or just `name` at the root. 979 pub fn childDir(arena: std.mem.Allocator, dir: []const u8, name: []const u8) ![]const u8 { 980 return if (dir.len == 0) name else std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, name }); 981 } 982 983 // `dir` with its last segment removed ("" when `dir` has a single segment). 984 fn parentDir(dir: []const u8) []const u8 { 985 const slash = std.mem.lastIndexOfScalar(u8, dir, '/') orelse return ""; 986 return dir[0..slash]; 987 } 988 989 // a search result's bottom label: the directory it sits in, empty at the root. 990 // a directory too wide for the list column is clipped from the left. 991 fn resultDirLabel(aa: std.mem.Allocator, path: []const u8) ![]const u8 { 992 const slash = std.mem.lastIndexOfScalar(u8, path, '/') orelse return ""; 993 const dir = path[0..slash]; 994 // the row's border and the label's padding take two columns each 995 const max_width = View.list_max_width - 4; 996 var width = try xitui.width.displayWidth(dir); 997 if (width <= max_width) return std.fmt.allocPrint(aa, " {s} ", .{dir}); 998 999 const ellipsis = ".."; 1000 var iter = (try std.unicode.Utf8View.init(dir)).iterator(); 1001 var start: usize = 0; 1002 while (width > max_width - ellipsis.len) { 1003 const slice = iter.nextCodepointSlice() orelse break; 1004 width -= xitui.width.cellWidth(try std.unicode.utf8Decode(slice)); 1005 start += slice.len; 1006 } 1007 return std.fmt.allocPrint(aa, " " ++ ellipsis ++ "{s} ", .{dir[start..]}); 1008 } 1009