╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ ui.zig ───────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
540 // resolve a requested ref/oid (null = the repo's default branch) to a 541 // concrete ref/oid plus the commit oid it points at. `requested_value` is 542 // the url-encoded form (as it appears in the route). null when it doesn't 543 // resolve (an unknown branch/tag, or a malformed/unknown oid). 544 pub fn init( 545 repo: *rp.Repo(.xit, repo_opts), 546 io: std.Io, 547 aa: std.mem.Allocator, 548 requested_ref_or_oid: ?RoutablePage.RefOrOid, 549 requested_value: []const u8, 550 ) !?Self { 551 var ref_or_oid: RoutablePage.RefOrOid = requested_ref_or_oid orelse .branch; 552 // the decoded ref name / oid to look up. a named ref arrives url-encoded. 553 var value: []const u8 = if (requested_ref_or_oid == null) 554 requested_value 555 else 556 std.Uri.percentDecodeInPlace(try aa.dupe(u8, requested_value)); 557 // no ref named: fall back to HEAD's branch (or its oid when detached). 558 if (requested_ref_or_oid == null) { 559 var head_buf: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 560 if (repo.head(io, &head_buf)) |head| switch (head) { 561 .ref => |r| { 562 ref_or_oid = .branch; 563 value = r.name; 564 }, 565 .oid => |o| { 566 ref_or_oid = .object; 567 value = o; 568 }, 569 } else |_| {} 570 } 571 572 var oid: [hex_len]u8 = undefined; 573 switch (ref_or_oid) { 574 .object => { 575 if (value.len != hex_len) return null; 576 @memcpy(&oid, value); 577 }, 578 .branch, .tag => { 579 const ref_kind: rf.RefKind = if (ref_or_oid == .branch) .head else .tag; 580 oid = (repo.readRef(io, .{ .kind = ref_kind, .name = value }) catch null) orelse return null; 581 }, 582 } 583 // store url-encoded so the route layer can hold the value verbatim. 584 return .{ .ref_or_oid = ref_or_oid, .value = try urlEncodeRef(aa, value), .oid = oid }; 585 } 586 }; 587 } 588 589 // per-connection mutable state. each SSH session / web session / local TUI 590 // run gets its own. 591 pub const Session = struct { 592 data: Data = .{}, 593 // session-lifetime allocations: login/user_id, persisted prefs, queued 594 // actions. lives as long as the connection. 595 arena: *std.heap.ArenaAllocator, 596 // current page's allocations: page data and the page-scoped strings widgets 597 // build (form actions, links). owned by Nav, swapped on each navigation, so 598 // it doesn't accumulate over a long-lived session. on the web/wasm paths, 599 // where a render is one-shot, this points at the same arena as `arena`. 600 page_arena: *std.heap.ArenaAllocator, 601 haxy_moment: ?evt.AdminDB.HashMap(.read_only) = null, // db cursor (null on the wasm side) 602 // filesystem io and the path to <server>/repos, for opening on-disk repos 603 // during page construction. both null on wasm, which has no filesystem and 604 // rebuilds pages from the serialized snapshot rather than from disk. 605 io: ?std.Io = null, 606 repos_dir: ?[]const u8 = null, 607 pending: std.ArrayList(Action) = .empty, // actions queued by widgets this frame 608 // focus id -> the live TextInput, refreshed each frame by the views that own 609 // inputs. web/wasm form handling looks widgets up here by focus id. 610 text_inputs: std.AutoHashMapUnmanaged(usize, *wgt.TextInput(Widget)) = .empty, 611 nav_back: bool = false, // set by input (escape) to request the native TUI pop a page; see Nav 612 // a requested forward navigation. set this (via navigate) to move to a new 613 // page; Nav.sync builds it and then copies it into current_page, clearing 614 // this back to null. setting current_page directly only updates the url and 615 // does not navigate. 616 next_page: ?RoutablePage = null, 617 is_terminal: bool = false, // true on remote SSH and local TUI 618 // port the web UI is served on, for the TUI/SSH footer's "http://localhost:<port>..." 619 // url. null on the web itself (no footer there). 620 web_port: ?u16 = null, 621 quit_requested: bool = false, 622 623 const Self = @This(); 624 625 // serializable data sent down to web client 626 pub const Data = struct { 627 user_id: ?[]const u8 = null, 628 // a transient outcome to surface from the last /login POST attempt 629 login_failure: ?Home.Auth.Login.Failure = null, 630 current_page: RoutablePage = .default, 631 // whether to render the ANSI art backdrop 632 enable_ansi: bool = true, 633 }; 634 635 // a user-initiated state change. widgets enqueue these on the session during 636 // input instead of mutating state or touching the DB themselves; the host 637 // drains them each frame (see applyAndWritePending / applyPending). this keeps DB 638 // side effects out of the widget tree and gives every render path one place to 639 // turn a UI action into a state change + event. 640 pub const Action = union(enum) { 641 toggle_ansi, 642 }; 643 644 pub fn init( 645 arena: *std.heap.ArenaAllocator, 646 repo: *rp.Repo(.xit, evt.admin_repo_opts), 647 data: Data, 648 ) !Self { 649 var session = Self{ 650 .data = data, 651 .arena = arena, 652 // until a host swaps in a page-scoped arena (Nav does this), page 653 // allocations land in the session arena. on the web path that's the 654 // intended behavior, since the whole arena is per-request. 655 .page_arena = arena, 656 .haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo), 657 }; 658 try session.loadUserPrefs(); 659 return session; 660 } 661 662 // load the logged-in user's persisted preferences from the db 663 pub fn loadUserPrefs(self: *Self) !void { 664 const user_id = self.data.user_id orelse return; 665 const moment = self.haxy_moment orelse return; 666 if (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, self.arena, user_id)) |user| { 667 self.data.enable_ansi = user.enable_ansi; 668 } 669 } 670 671 // queue an action for the host to drain this frame. 672 pub fn push(self: *Self, action: Action) !void { 673 try self.pending.append(self.arena.allocator(), action); 674 } 675 676 // apply a single action's in-memory effect only (no persistence). 677 fn apply(self: *Self, action: Action) void { 678 switch (action) { 679 .toggle_ansi => self.data.enable_ansi = !self.data.enable_ansi, 680 } 681 } 682 683 // drain the session's queued actions by applying them to the session. 684 // used on the wasm path, which has no repo to persist to. 685 pub fn applyPending(self: *Self) void { 686 for (self.pending.items) |action| self.apply(action); 687 self.pending.clearRetainingCapacity(); 688 } 689 690 // drain the session's queued actions by applying them to the session and 691 // writing them to the db 692 pub fn applyAndWritePending( 693 self: *Self, 694 io: std.Io, 695 allocator: std.mem.Allocator, 696 repo: *rp.Repo(.xit, evt.admin_repo_opts), 697 ) !void { 698 defer self.pending.clearRetainingCapacity(); 699 for (self.pending.items) |action| { 700 self.apply(action); 701 switch (action) { 702 .toggle_ansi => if (self.data.user_id) |user_id| { 703 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, repo, user_id); 704 }, 705 } 706 } 707 } 708 709 // reload the moment from the admin repo 710 pub fn reloadMoment(self: *Self, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 711 self.haxy_moment = try evt.currentMoment(evt.admin_repo_opts, repo); 712 } 713 714 // request a forward navigation to `route`; the host consumes next_page 715 // (Nav.sync on the terminal, the wasm tick on the web). 716 pub fn navigate(self: *Session, route: RoutablePage) !void { 717 self.next_page = route; 718 } 719 }; 720 721 pub fn run(io: std.Io, allocator: std.mem.Allocator, session: *Session, repo: *rp.Repo(.xit, evt.admin_repo_opts)) !void { 722 var nav = try Nav.init(allocator, session); 723 defer nav.deinit(allocator); 724 725 var terminal = try term.Terminal.init(io, allocator); 726 defer terminal.deinit(io); 727 728 // set term as active so it will be properly cooked 729 // when a panic/segfault happens 730 term.setActive(&terminal); 731 defer term.setActive(null); 732 733 var last_size = layout.Size{ .width = 0, .height = 0 }; 734 var last_grid = try Grid.init(allocator, last_size); 735 defer last_grid.deinit(); 736 737 while (!terminal.shouldQuit()) { 738 const grid_changed = try terminal.render(&nav.root, &last_grid, &last_size); 739 740 // process any inputs. 741 // 742 // if the grid didn't change, then first do a blocking 743 // read, so the thread will sleep until further input. 744 // after that, all remaining reads are non-blocking so 745 // we can process the rest of the queued inputs. 746 // 747 // if the grid *did* change, then only do non-blocking 748 // reads. we do not want to sleep the thread because 749 // there may be an animation that requires more looping. 750 var blocking = !grid_changed; 751 while (try terminal.readKey(io, blocking)) |key| { 752 blocking = false; 753 try inputKey(allocator, &nav.root, key, session); 754 } 755 756 // local run has no repo to persist to, so just apply in-memory 757 session.applyPending(); 758 759 // pick up data written by other handles so the next navigation 760 // builds its page from a current moment 761 try session.reloadMoment(repo); 762 763 // reconcile navigation: forward to a new page, or back on escape. 764 try nav.sync(allocator, session); 765 766 // the quit button (on the quit tab) asks the host to tear down. 767 if (session.quit_requested) terminal.requestQuit(); 768 769 try nav.root.build(allocator, .{ 770 .min_size = .{ .width = null, .height = null }, 771 .max_size = .{ .width = last_size.width, .height = last_size.height }, 772 }, nav.root.getFocus()); 773 } 774 } 775 776 pub fn inputKey(allocator: std.mem.Allocator, root: *Widget, key: inp.Key, session: *Session) !void { 777 switch (key) { 778 // request a navigation pop; the host's Nav.sync goes back a page, or 779 // quits when there's no history left. 780 .escape => session.nav_back = true, 781 .enter => { 782 const root_focus = root.getFocus(); 783 if (root_focus.grandchild_id) |gid| { 784 // follow a cross-page link 785 if (crossPageLink(root_focus, gid, session.data.current_page)) |route| { 786 return session.navigate(route); 787 } 788 } 789 try root.input(allocator, key, root_focus); 790 }, 791 .mouse => |mouse| { 792 if (mouse.action == .press and mouse.action.press == .left) { 793 const root_focus = root.getFocus(); 794 var clicked: ?usize = null; 795 var iter = root_focus.children.iterator(); 796 while (iter.next()) |entry| { 797 const child = entry.value_ptr.*; 798 if (!child.focus.focusable) continue; 799 const r = child.rect; 800 if (mouse.x >= r.x and mouse.y >= r.y and 801 mouse.x < r.x + r.size.width and mouse.y < r.y + r.size.height) 802 { 803 clicked = entry.key_ptr.*; 804 break; 805 } 806 } 807 if (clicked) |focus_id| { 808 // follow a cross-page link 809 if (crossPageLink(root_focus, focus_id, session.data.current_page)) |route| { 810 return session.navigate(route); 811 } 812 root_focus.setFocus(focus_id); 813 } 814 // forward the press into the widget tree so buttons (and any 815 // future click-aware widgets) can react. widgets that don't 816 // care about presses ignore it. 817 try root.input(allocator, key, root.getFocus()); 818 } else { 819 try root.input(allocator, key, root.getFocus()); 820 } 821 }, 822 else => try root.input(allocator, key, root.getFocus()), 823 } 824 } 825 826 // if the focus target at focus_id is an `a:` link that should navigate (a 827 // different parent page, or a different files directory within the repo page), 828 // return its route; otherwise null. lets a host turn a click / enter on such a 829 // link into a navigation rather than a focus change. 830 pub fn crossPageLink(root_focus: *Focus, focus_id: usize, current: RoutablePage) ?RoutablePage { 831 const child = root_focus.children.get(focus_id) orelse return null; 832 const custom = switch (child.focus.kind) { 833 .custom => |c| c, 834 else => return null, 835 }; 836 const a_prefix = "a:"; 837 if (!std.mem.startsWith(u8, custom, a_prefix)) return null; 838 const url = custom[a_prefix.len..]; 839 const q = std.mem.indexOfScalar(u8, url, '?'); 840 const route = RoutablePage.fromUrl(if (q) |i| url[0..i] else url, if (q) |i| url[i + 1 ..] else null) orelse return null; 841 // a link to a different parent page always navigates; within a page, a 842 // files-directory / commits-page / list-window change navigates while tab 843 // links stay in-page (header-handled). 844 if (route.parent() != current.parent() or RoutablePage.repoPageChanged(route, current) or RoutablePage.homePageChanged(route, current) or RoutablePage.userPageChanged(route, current)) return route; 845 return null; 846 } 847 848 // native-TUI navigation 849 pub const Nav = struct { 850 root: Widget, 851 route: RoutablePage, 852 // backs the current page (its Page data and the page-scoped strings its 853 // widgets build). owned here, swapped on each navigation. session.page_arena 854 // tracks whichever of these is current so widgets allocate into it. 855 arena: *std.heap.ArenaAllocator, 856 history: std.ArrayList(Entry), 857 858 // each retained page keeps its own arena, freed when the page leaves the 859 // stack (popped on back, evicted at cap, or on deinit). this is what keeps a 860 // long-lived session from accumulating every page it ever visited. 861 const Entry = struct { root: Widget, route: RoutablePage, arena: *std.heap.ArenaAllocator }; 862 863 // cap on retained back-history so the chain can't grow memory without bound 864 const max_history: usize = 16; 865 866 pub fn init(allocator: std.mem.Allocator, session: *Session) !Nav { 867 const arena = try allocator.create(std.heap.ArenaAllocator); 868 arena.* = std.heap.ArenaAllocator.init(allocator); 869 errdefer { 870 arena.deinit(); 871 allocator.destroy(arena); 872 } 873 874 session.page_arena = arena; 875 const route = session.data.current_page; 876 877 const page = try arena.allocator().create(Page); 878 page.* = try Page.init(arena, session, route); 879 return .{ 880 .root = try initRoot(allocator, page, session), 881 .route = route, 882 .arena = arena, 883 .history = .empty, 884 }; 885 } 886 887 pub fn deinit(self: *Nav, allocator: std.mem.Allocator) void { 888 self.root.deinit(allocator); 889 freeArena(allocator, self.arena); 890 for (self.history.items) |*entry| { 891 entry.root.deinit(allocator); 892 freeArena(allocator, entry.arena); 893 } 894 self.history.deinit(allocator); 895 } 896 897 fn freeArena(allocator: std.mem.Allocator, arena: *std.heap.ArenaAllocator) void { 898 arena.deinit(); 899 allocator.destroy(arena); 900 } 901 902 // reconcile the displayed root with the session's navigation state. a 903 // forward nav (current_page moved to a different parent page) pushes the 904 // current root and builds the new page in a fresh arena; a back request 905 // frees the current page and restores the previous one. when escape is 906 // pressed with no history left we switch to the quit tab instead of quitting. 907 pub fn sync(self: *Nav, allocator: std.mem.Allocator, session: *Session) !void { 908 if (session.nav_back) { 909 session.nav_back = false; 910 if (self.history.pop()) |entry| { 911 self.root.deinit(allocator); 912 freeArena(allocator, self.arena); 913 self.root = entry.root; 914 self.route = entry.route; 915 self.arena = entry.arena; 916 session.page_arena = entry.arena; 917 session.data.current_page = entry.route; 918 return; 919 } 920 // nothing to go back to; switch to the quit confirmation 921 const root_focus = self.root.getFocus(); 922 var iter = root_focus.children.iterator(); 923 while (iter.next()) |entry| { 924 switch (entry.value_ptr.focus.kind) { 925 .custom => |custom| if (std.mem.eql(u8, custom, Quit.tab_kind)) { 926 root_focus.setFocus(entry.key_ptr.*); 927 // a Stack only builds its selected child, so the quit 928 // button isn't in the focus tree until a build runs with 929 // the quit tab selected. build once, then send a 930 // synthetic arrow_down to drop focus from the tab onto 931 // the button so it's ready to confirm. 932 try self.root.build(allocator, .{ 933 .min_size = .{ .width = null, .height = 40 }, 934 .max_size = .{ .width = 80, .height = null }, 935 }, root_focus); 936 try self.root.input(allocator, .arrow_down, root_focus); 937 break; 938 }, 939 else => {}, 940 } 941 } 942 return; 943 } 944 945 // forward navigation: navigate() set next_page to the page to move to (a 946 // cross-page link or tab change crossing pages) 947 if (session.next_page) |route| { 948 session.next_page = null; 949 if (session.haxy_moment == null) return; 950 // the page we navigated to becomes the current page 951 session.data.current_page = route; 952 953 const arena = try allocator.create(std.heap.ArenaAllocator); 954 arena.* = std.heap.ArenaAllocator.init(allocator); 955 errdefer freeArena(allocator, arena); 956 957 session.page_arena = arena; 958 959 const page = try arena.allocator().create(Page); 960 page.* = try Page.init(arena, session, route); 961 const new_root = try initRoot(allocator, page, session); 962 963 try self.history.append(allocator, .{ .root = self.root, .route = self.route, .arena = self.arena }); 964 // drop the oldest entry (freeing its widget tree and arena) once over cap 965 if (self.history.items.len > max_history) { 966 var oldest = self.history.orderedRemove(0); 967 oldest.root.deinit(allocator); 968 freeArena(allocator, oldest.arena); 969 } 970 self.root = new_root; 971 self.route = route; 972 self.arena = arena; 973 } 974 } 975 }; 976 977 pub fn initRoot(allocator: std.mem.Allocator, page: *const Page, session: *Session) !Widget { 978 const page_widget: Widget = switch (page.*) { 979 .home => |*p| .{ .home = try .init(allocator, p, session) }, 980 .user => |*p| .{ .user = try .init(allocator, p, session) }, 981 .repo => |*p| .{ .repo = try .init(allocator, p, session) }, 982 }; 983 984 const demon_art = @embedFile("embed/demon.ans"); 985 986 // on the TUI/SSH, the page sits above a one-row footer showing the url 987 var root = if (session.is_terminal) blk: { 988 var box = try wgt.Box(Widget).init(allocator, .{ .border_style = null, .direction = .vert }); 989 errdefer box.deinit(allocator); 990 const bg_id = bg_blk: { 991 var background = try AnsiBackground.init(allocator, page_widget, demon_art, session); 992 errdefer background.deinit(allocator); 993 const id = background.getFocus().id; 994 try box.children.put(allocator, id, .{ .widget = .{ .background = background }, .rect = null, .min_size = null }); 995 break :bg_blk id; 996 }; 997 { 998 var footer = try Footer.init(allocator, session); 999 errdefer footer.deinit(allocator); 1000 try box.children.put(allocator, footer.getFocus().id, .{ .widget = .{ .footer = footer }, .rect = null, .min_size = .{ .width = null, .height = 1 } }); 1001 } 1002 box.getFocus().child_id = bg_id; 1003 break :blk Widget{ .box = box }; 1004 } else Widget{ .background = try AnsiBackground.init(allocator, page_widget, demon_art, session) }; 1005 errdefer root.deinit(allocator); 1006 1007 // input-owning views build their TextInputs in init — so reset the 1008 // focus-id -> *TextInput map here 1009 session.text_inputs.clearRetainingCapacity(); 1010 1011 try root.build(allocator, .{ 1012 .min_size = .{ .width = null, .height = 40 }, 1013 .max_size = .{ .width = 100, .height = null }, 1014 }, root.getFocus()); 1015 1016 return root; 1017 } 1018 1019 pub const Widget = union(enum) { 1020 text: wgt.Text(Widget), 1021 box: wgt.Box(Widget), 1022 text_box: wgt.TextBox(Widget), 1023 text_input: wgt.TextInput(Widget), 1024 scroll: wgt.Scroll(Widget), 1025 stack: wgt.Stack(Widget), 1026 flow_box: FlowBox, 1027 flow_box_scroll: FlowBox.Scroll, 1028 spacer: Spacer, 1029 center: Center, 1030 background: AnsiBackground, 1031 home: Home.View, 1032 user: User.View, 1033 repo: Repo.View, 1034 quit: Quit.View, 1035 title: Title.View, 1036 sub_title: SubTitle.View, 1037 home_header: Home.Header.View, 1038 user_header: User.Header.View, 1039 repo_header: Repo.Header.View, 1040 repo_sub_header: Repo.SubHeader.View, 1041 repo_files: Repo.Files.View, 1042 repo_commits: Repo.Commits.View, 1043 repo_refs: Repo.Refs.View, 1044 home_users: Home.Users.View, 1045 home_repos: Home.Repos.View, 1046 auth_tab: Home.Header.AuthTab.View, 1047 home_settings: Home.Settings.View, 1048 home_auth: Home.Auth.View, 1049 footer: Footer, 1050 1051 pub fn deinit(self: *Widget, allocator: std.mem.Allocator) void { 1052 switch (self.*) { 1053 inline else => |*case| case.deinit(allocator), 1054 } 1055 } 1056 1057 pub fn build(self: *Widget, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) anyerror!void { 1058 switch (self.*) { 1059 inline else => |*case| try case.build(allocator, constraint, root_focus), 1060 } 1061 } 1062 1063 pub fn input(self: *Widget, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) anyerror!void { 1064 switch (self.*) { 1065 inline else => |*case| try case.input(allocator, key, root_focus), 1066 } 1067 } 1068 1069 pub fn clearGrid(self: *Widget) void { 1070 switch (self.*) { 1071 inline else => |*case| case.clearGrid(), 1072 } 1073 } 1074 1075 pub fn getGrid(self: Widget) ?Grid { 1076 switch (self) { 1077 inline else => |*case| return case.getGrid(), 1078 } 1079 } 1080 1081 pub fn getFocus(self: *Widget) *Focus { 1082 switch (self.*) { 1083 inline else => |*case| return case.getFocus(), 1084 } 1085 } 1086 }; 1087 1088 pub const FlowBox = struct { 1089 focus: *Focus, 1090 grid: ?Grid, 1091 text_boxes: std.ArrayList(wgt.TextBox(Widget)), 1092 // backs the per-item strings the text boxes borrow: each box's `content` 1093 // and, for link items, its `.custom` focus kind (e.g. "a:/user/foo"). reset 1094 // wholesale on each setItems so there's no per-string ownership to track. 1095 arena: std.heap.ArenaAllocator, 1096 // column count from the last build — FlowBox.Scroll.input uses it so arrow 1097 // up/down can step by a row's worth of items. 1098 last_cols: usize, 1099 options: Options, 1100 1101 const border_rows: usize = 2; 1102 1103 pub const Options = struct { 1104 cell_width: usize = 40, 1105 cell_height: usize = 3, 1106 }; 1107 1108 pub fn init(allocator: std.mem.Allocator, options: Options) !FlowBox { 1109 return .{ 1110 .focus = try Focus.create(allocator, .container), 1111 .grid = null, 1112 .text_boxes = .empty, 1113 .arena = std.heap.ArenaAllocator.init(allocator), 1114 .last_cols = 1, 1115 .options = options, 1116 }; 1117 } 1118 1119 pub fn deinit(self: *FlowBox, allocator: std.mem.Allocator) void { 1120 self.focus.destroy(allocator); 1121 if (self.grid) |*grid| { 1122 grid.deinit(); 1123 self.grid = null; 1124 } 1125 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1126 self.text_boxes.deinit(allocator); 1127 self.arena.deinit(); 1128 } 1129 1130 // one flow item: its display text plus an optional link. a non-empty `link` 1131 // sets the item's focus kind such as `.{ .custom = "a:/user/foo" }`, which 1132 // the web renderer turns into an anchor. 1133 pub const Item = struct { text: []const u8, link: []const u8 = "" }; 1134 1135 // both the item text and the link are copied into the arena, so the caller's 1136 // slices needn't outlive this call. 1137 pub fn setItems(self: *FlowBox, allocator: std.mem.Allocator, items: []const Item) !void { 1138 for (self.text_boxes.items) |*tb| tb.deinit(allocator); 1139 self.text_boxes.clearAndFree(allocator); 1140 1141 // the old text boxes (and their borrowed content/links) are gone now, so 1142 // the arena that backed those strings can be reclaimed. 1143 _ = self.arena.reset(.retain_capacity); 1144 const aa = self.arena.allocator(); 1145 1146 self.focus.clear(); 1147 self.focus.child_id = null; 1148 1149 for (items) |item| { 1150 const line = try aa.dupe(u8, item.text); 1151 1152 var text_box = try wgt.TextBox(Widget).init(allocator, line, .{ .border_style = .hidden, .rounded_corners = true, .wrap_kind = .word }); 1153 errdefer text_box.deinit(allocator); 1154 text_box.getFocus().focusable = true; 1155 1156 if (item.link.len > 0) { 1157 text_box.getFocus().kind = .{ .custom = try aa.dupe(u8, item.link) }; 1158 } 1159 1160 try self.text_boxes.append(allocator, text_box); 1161 } 1162 1163 if (self.text_boxes.items.len > 0) { 1164 self.focus.child_id = self.text_boxes.items[0].getFocus().id; 1165 } 1166 } 1167 1168 pub fn build(self: *FlowBox, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1169 self.clearGrid(); 1170 self.focus.clear(); 1171 1172 const cell_width = self.options.cell_width; 1173 const max_width = constraint.max_size.width orelse cell_width; 1174 const cols = if (cell_width == 0) 1 else @max(1, max_width / cell_width); 1175 self.last_cols = cols; 1176 1177 const count = self.text_boxes.items.len; 1178 if (count == 0) return; 1179 const slot_height = self.options.cell_height + border_rows; 1180 if (slot_height == 0) return; 1181 1182 // build at the slot size so every text box fits a single grid cell 1183 for (self.text_boxes.items) |*tb| { 1184 tb.options.border_style = if (self.focus.child_id == tb.getFocus().id) .single else .hidden; 1185 try tb.build(allocator, .{ 1186 .min_size = .{ .width = cell_width, .height = null }, 1187 .max_size = .{ .width = cell_width, .height = slot_height }, 1188 }, root_focus); 1189 } 1190 1191 const rows = (count + cols - 1) / cols; 1192 const content_height = rows * slot_height; 1193 const total_width = cols * cell_width; 1194 if (total_width == 0 or content_height == 0) return; 1195 1196 var grid = try Grid.init(allocator, .{ .width = total_width, .height = content_height }); 1197 errdefer grid.deinit(); 1198 1199 for (self.text_boxes.items, 0..) |*tb, i| { 1200 const tb_grid = tb.getGrid() orelse continue; 1201 const col = i % cols; 1202 const row = i / cols; 1203 const cell_x = col * cell_width; 1204 const cell_y = row * slot_height; 1205 try self.focus.addChild(allocator, tb.getFocus(), tb_grid.size, cell_x, cell_y); 1206 try grid.drawGrid(tb_grid, cell_x, cell_y); 1207 } 1208 1209 self.grid = grid; 1210 } 1211 1212 pub fn input(self: *FlowBox, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1213 _ = self; 1214 _ = allocator; 1215 _ = key; 1216 _ = root_focus; 1217 } 1218 1219 pub fn clearGrid(self: *FlowBox) void { 1220 if (self.grid) |*grid| { 1221 grid.deinit(); 1222 self.grid = null; 1223 } 1224 for (self.text_boxes.items) |*tb| tb.clearGrid(); 1225 } 1226 1227 pub fn getGrid(self: FlowBox) ?Grid { 1228 return self.grid; 1229 } 1230 1231 pub fn getFocus(self: *FlowBox) *Focus { 1232 return self.focus; 1233 } 1234 1235 pub fn cellRect(self: FlowBox, index: usize) ?layout.IRect { 1236 if (self.last_cols == 0 or index >= self.text_boxes.items.len) return null; 1237 const slot_height = self.options.cell_height + border_rows; 1238 const col = index % self.last_cols; 1239 const row = index / self.last_cols; 1240 return .{ 1241 .x = @intCast(col * self.options.cell_width), 1242 .y = @intCast(row * slot_height), 1243 .size = .{ .width = self.options.cell_width, .height = slot_height }, 1244 }; 1245 } 1246 1247 pub fn indexOfFocusId(self: FlowBox, focus_id: usize) ?usize { 1248 for (self.text_boxes.items, 0..) |tb, i| { 1249 if (tb.box.focus.id == focus_id) return i; 1250 } 1251 return null; 1252 } 1253 1254 pub const Scroll = struct { 1255 scroll: wgt.Scroll(Widget), 1256 1257 pub fn init(allocator: std.mem.Allocator, options: FlowBox.Options, web_native: bool) !Scroll { 1258 var layout_inner = try FlowBox.init(allocator, options); 1259 errdefer layout_inner.deinit(allocator); 1260 var scroll = try wgt.Scroll(Widget).init(allocator, .{ .flow_box = layout_inner }, .{ .direction = .vert, .web_native = web_native }); 1261 errdefer scroll.deinit(allocator); 1262 return .{ .scroll = scroll }; 1263 } 1264 1265 pub fn deinit(self: *Scroll, allocator: std.mem.Allocator) void { 1266 self.scroll.deinit(allocator); 1267 } 1268 1269 pub fn setItems(self: *Scroll, allocator: std.mem.Allocator, items: []const Item) !void { 1270 self.scroll.x = 0; 1271 self.scroll.y = 0; 1272 try self.inner().setItems(allocator, items); 1273 } 1274 1275 pub fn build(self: *Scroll, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1276 try self.scroll.build(allocator, constraint, root_focus); 1277 } 1278 1279 pub fn input(self: *Scroll, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1280 _ = allocator; 1281 const in = self.inner(); 1282 const child_id = in.focus.child_id orelse return; 1283 const current_index = in.indexOfFocusId(child_id) orelse return; 1284 const count = in.text_boxes.items.len; 1285 if (count == 0) return; 1286 const cols = in.last_cols; 1287 const slot_height = in.options.cell_height + FlowBox.border_rows; 1288 1289 var index = current_index; 1290 switch (key) { 1291 .arrow_up => index -|= cols, 1292 .arrow_down => if (index + cols < count) { 1293 index += cols; 1294 }, 1295 .arrow_left => index -|= 1, 1296 .arrow_right => if (index + 1 < count) { 1297 index += 1; 1298 }, 1299 .home => index = 0, 1300 .end => index = count - 1, 1301 .page_up => { 1302 if (self.scroll.grid) |grid| if (slot_height > 0) { 1303 const rows_per_page = grid.size.height / slot_height; 1304 index -|= rows_per_page * cols; 1305 }; 1306 }, 1307 .page_down => { 1308 if (self.scroll.grid) |grid| if (slot_height > 0) { 1309 const rows_per_page = grid.size.height / slot_height; 1310 index = @min(index + rows_per_page * cols, count - 1); 1311 }; 1312 }, 1313 // scroll wheel moves the focused cell by a full row so the 1314 // viewport (via scrollToRect) follows in row-sized steps, 1315 // matching how a scroll wheel feels in a grid view. 1316 .mouse => |mouse| switch (mouse.action) { 1317 .scroll => |dir| switch (dir) { 1318 .up => index -|= cols, 1319 .down => if (index + cols < count) { 1320 index += cols; 1321 }, 1322 }, 1323 else => {}, 1324 }, 1325 else => {}, 1326 } 1327 1328 if (index != current_index) { 1329 root_focus.setFocus(in.text_boxes.items[index].getFocus().id); 1330 if (in.cellRect(index)) |rect| { 1331 self.scroll.scrollToRect(rect); 1332 } 1333 } 1334 } 1335 1336 pub fn clearGrid(self: *Scroll) void { 1337 self.scroll.clearGrid(); 1338 } 1339 1340 pub fn getGrid(self: Scroll) ?Grid { 1341 return self.scroll.getGrid(); 1342 } 1343 1344 pub fn getFocus(self: *Scroll) *Focus { 1345 return self.scroll.getFocus(); 1346 } 1347 1348 pub fn getSelectedIndex(self: Scroll) ?usize { 1349 const in = self.scroll.child.flow_box; 1350 const child_id = in.focus.child_id orelse return null; 1351 return in.indexOfFocusId(child_id); 1352 } 1353 1354 fn inner(self: *Scroll) *FlowBox { 1355 return &self.scroll.child.flow_box; 1356 } 1357 }; 1358 }; 1359 1360 // an invisible widget that fills the horizontal space granted by its parent. 1361 // used inside Box(horiz) with a min_size so the box reserves space for the 1362 // children that follow, pushing them to the right. 1363 pub const Spacer = struct { 1364 focus: *Focus, 1365 grid: ?Grid, 1366 1367 pub fn init(allocator: std.mem.Allocator) !Spacer { 1368 return .{ 1369 .focus = try Focus.create(allocator, .container), 1370 .grid = null, 1371 }; 1372 } 1373 1374 pub fn deinit(self: *Spacer, allocator: std.mem.Allocator) void { 1375 self.focus.destroy(allocator); 1376 if (self.grid) |*grid| { 1377 grid.deinit(); 1378 self.grid = null; 1379 } 1380 } 1381 1382 pub fn build(self: *Spacer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1383 _ = root_focus; 1384 self.clearGrid(); 1385 const width = constraint.max_size.width orelse return; 1386 if (width == 0) return; 1387 self.grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1388 } 1389 1390 pub fn input(self: *Spacer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1391 _ = self; 1392 _ = allocator; 1393 _ = key; 1394 _ = root_focus; 1395 } 1396 1397 pub fn clearGrid(self: *Spacer) void { 1398 if (self.grid) |*grid| { 1399 grid.deinit(); 1400 self.grid = null; 1401 } 1402 } 1403 1404 pub fn getGrid(self: Spacer) ?Grid { 1405 return self.grid; 1406 } 1407 1408 pub fn getFocus(self: *Spacer) *Focus { 1409 return self.focus; 1410 } 1411 }; 1412 1413 // a one-row, non-focusable status bar showing the current page's url 1414 pub const Footer = struct { 1415 focus: *Focus, 1416 grid: ?Grid, 1417 session: *Session, 1418 arena: std.heap.ArenaAllocator, 1419 1420 pub fn init(allocator: std.mem.Allocator, session: *Session) !Footer { 1421 return .{ 1422 .focus = try Focus.create(allocator, .container), 1423 .grid = null, 1424 .session = session, 1425 .arena = std.heap.ArenaAllocator.init(allocator), 1426 }; 1427 } 1428 1429 pub fn deinit(self: *Footer, allocator: std.mem.Allocator) void { 1430 self.focus.destroy(allocator); 1431 if (self.grid) |*grid| grid.deinit(); 1432 self.arena.deinit(); 1433 } 1434 1435 pub fn build(self: *Footer, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1436 _ = root_focus; 1437 self.clearGrid(); 1438 const width = constraint.max_size.width orelse return; 1439 if (width == 0) return; 1440 1441 _ = self.arena.reset(.retain_capacity); 1442 const aa = self.arena.allocator(); 1443 const path = self.session.data.current_page.urlAlloc(&self.arena) catch return; 1444 const text = if (self.session.web_port) |port| 1445 std.fmt.allocPrint(aa, "http://localhost:{d}{s}", .{ port, path }) catch return 1446 else 1447 path; 1448 1449 var grid = try Grid.init(allocator, .{ .width = width, .height = 1 }); 1450 errdefer grid.deinit(); 1451 var utf8 = (std.unicode.Utf8View.init(text) catch return).iterator(); 1452 var i: usize = 0; 1453 while (utf8.nextCodepointSlice()) |ch| { 1454 if (i == width) break; 1455 grid.cells.items[try grid.cells.at(.{ 0, i })].rune = ch; 1456 i += 1; 1457 } 1458 self.grid = grid; 1459 } 1460 1461 pub fn input(self: *Footer, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1462 _ = self; 1463 _ = allocator; 1464 _ = key; 1465 _ = root_focus; 1466 } 1467 1468 pub fn clearGrid(self: *Footer) void { 1469 if (self.grid) |*grid| { 1470 grid.deinit(); 1471 self.grid = null; 1472 } 1473 } 1474 1475 pub fn getGrid(self: Footer) ?Grid { 1476 return self.grid; 1477 } 1478 1479 pub fn getFocus(self: *Footer) *Focus { 1480 return self.focus; 1481 } 1482 }; 1483 1484 // a single-child wrapper that builds the child at its natural size and 1485 // positions its grid in the middle of the area granted by the parent 1486 pub const Center = struct { 1487 focus: *Focus, 1488 grid: ?Grid, 1489 child: *Widget, 1490 1491 pub fn init(allocator: std.mem.Allocator, child_widget: Widget) !Center { 1492 const child = try allocator.create(Widget); 1493 errdefer allocator.destroy(child); 1494 child.* = child_widget; 1495 return .{ 1496 .focus = try Focus.create(allocator, .container), 1497 .grid = null, 1498 .child = child, 1499 }; 1500 } 1501 1502 pub fn deinit(self: *Center, allocator: std.mem.Allocator) void { 1503 self.focus.destroy(allocator); 1504 if (self.grid) |*grid| { 1505 grid.deinit(); 1506 self.grid = null; 1507 } 1508 self.child.deinit(allocator); 1509 allocator.destroy(self.child); 1510 } 1511 1512 pub fn build(self: *Center, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1513 self.clearGrid(); 1514 self.getFocus().clear(); 1515 1516 // build the child without forcing it to fill min_size; it sizes 1517 // itself to its content within the available max. 1518 try self.child.build(allocator, .{ 1519 .min_size = .{ .width = null, .height = null }, 1520 .max_size = constraint.max_size, 1521 }, root_focus); 1522 1523 const child_grid = self.child.getGrid() orelse return; 1524 1525 // prefer max when given; otherwise grow to max(min, child) so that 1526 // when only a min is set (e.g. the wasm path passes viewport rows 1527 // as min_height with no max), we can still vertically center while 1528 // letting taller content extend past the min. 1529 const width = if (constraint.max_size.width) |w| w else if (constraint.min_size.width) |min_w| @max(min_w, child_grid.size.width) else child_grid.size.width; 1530 const height = if (constraint.max_size.height) |h| h else if (constraint.min_size.height) |min_h| @max(min_h, child_grid.size.height) else child_grid.size.height; 1531 if (width == 0 or height == 0) return; 1532 1533 const offset_x: usize = (width -| child_grid.size.width) / 2; 1534 const offset_y: usize = (height -| child_grid.size.height) / 2; 1535 1536 var grid = try Grid.init(allocator, .{ .width = width, .height = height }); 1537 errdefer grid.deinit(); 1538 try grid.drawGrid(child_grid, offset_x, offset_y); 1539 try self.getFocus().addChild(allocator, self.child.getFocus(), child_grid.size, offset_x, offset_y); 1540 self.getFocus().child_id = self.child.getFocus().id; 1541 1542 self.grid = grid; 1543 } 1544 1545 pub fn input(self: *Center, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1546 try self.child.input(allocator, key, root_focus); 1547 } 1548 1549 pub fn clearGrid(self: *Center) void { 1550 if (self.grid) |*grid| { 1551 grid.deinit(); 1552 self.grid = null; 1553 } 1554 self.child.clearGrid(); 1555 } 1556 1557 pub fn getGrid(self: Center) ?Grid { 1558 return self.grid; 1559 } 1560 1561 pub fn getFocus(self: *Center) *Focus { 1562 return self.focus; 1563 } 1564 }; 1565 1566 // renders truecolor ANSI art 1567 pub const AnsiArt = struct { 1568 focus: *Focus, 1569 grid: ?Grid, 1570 content: []const u8, 1571 1572 pub fn init(allocator: std.mem.Allocator, content: []const u8) !AnsiArt { 1573 return .{ 1574 .focus = try Focus.create(allocator, .container), 1575 .grid = null, 1576 .content = content, 1577 }; 1578 } 1579 1580 pub fn deinit(self: *AnsiArt, allocator: std.mem.Allocator) void { 1581 self.focus.destroy(allocator); 1582 if (self.grid) |*grid| { 1583 grid.deinit(); 1584 self.grid = null; 1585 } 1586 } 1587 1588 pub fn build(self: *AnsiArt, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1589 _ = root_focus; 1590 self.clearGrid(); 1591 1592 // parse into rows of cells, then copy into a rectangular grid 1593 var rows: std.ArrayList(std.ArrayList(Grid.Cell)) = .empty; 1594 defer { 1595 for (rows.items) |*row| row.deinit(allocator); 1596 rows.deinit(allocator); 1597 } 1598 var row: std.ArrayList(Grid.Cell) = .empty; 1599 errdefer row.deinit(allocator); 1600 1601 var style: Grid.Style = .{}; 1602 var width: usize = 0; 1603 const content = self.content; 1604 var i: usize = 0; 1605 while (i < content.len) { 1606 const byte = content[i]; 1607 if (byte == '\n') { 1608 width = @max(width, row.items.len); 1609 try rows.append(allocator, row); 1610 row = .empty; 1611 i += 1; 1612 } else if (byte == 0x1B and i + 1 < content.len and content[i + 1] == '[') { 1613 // CSI: scan to the final byte (0x40..0x7E); apply it if it's 'm' 1614 var j = i + 2; 1615 while (j < content.len and !(content[j] >= 0x40 and content[j] <= 0x7E)) j += 1; 1616 if (j >= content.len) { 1617 i = content.len; // malformed trailing escape; stop 1618 } else { 1619 if (content[j] == 'm') applySgr(&style, content[i + 2 .. j]); 1620 i = j + 1; 1621 } 1622 } else { 1623 const len = std.unicode.utf8ByteSequenceLength(byte) catch 1; 1624 const end = @min(content.len, i + len); 1625 const rune = content[i..end]; 1626 const transparent = end - i == 1 and rune[0] == ' ' and 1627 style.fg == null and style.bg == null and !style.inverted; 1628 try row.append(allocator, .{ 1629 .rune = if (transparent) null else rune, 1630 .style = style, 1631 }); 1632 i = end; 1633 } 1634 } 1635 // a trailing row with content but no closing newline 1636 if (row.items.len > 0) { 1637 width = @max(width, row.items.len); 1638 try rows.append(allocator, row); 1639 } else { 1640 row.deinit(allocator); 1641 } 1642 row = .empty; // ownership moved into rows (or freed); keep errdefer safe 1643 1644 const height = rows.items.len; 1645 if (width == 0 or height == 0) return; 1646 1647 const clamped_w = @min(width, constraint.max_size.width orelse width); 1648 const clamped_h = @min(height, constraint.max_size.height orelse height); 1649 1650 var grid = try Grid.init(allocator, .{ .width = clamped_w, .height = clamped_h }); 1651 errdefer grid.deinit(); 1652 for (rows.items[0..clamped_h], 0..) |r, y| { 1653 const n = @min(r.items.len, clamped_w); 1654 for (r.items[0..n], 0..) |cell, x| { 1655 grid.cells.items[try grid.cells.at(.{ y, x })] = cell; 1656 } 1657 } 1658 self.grid = grid; 1659 } 1660 1661 pub fn clearGrid(self: *AnsiArt) void { 1662 if (self.grid) |*grid| { 1663 grid.deinit(); 1664 self.grid = null; 1665 } 1666 } 1667 1668 pub fn getGrid(self: AnsiArt) ?Grid { 1669 return self.grid; 1670 } 1671 1672 pub fn getFocus(self: *AnsiArt) *Focus { 1673 return self.focus; 1674 } 1675 1676 fn applySgr(style: *Grid.Style, params: []const u8) void { 1677 var nums: [16]u32 = undefined; 1678 var n: usize = 0; 1679 var it = std.mem.splitScalar(u8, params, ';'); 1680 while (it.next()) |tok| { 1681 if (n >= nums.len) break; 1682 // an empty parameter (e.g. bare "\x1b[m") means 0 1683 nums[n] = std.fmt.parseInt(u32, tok, 10) catch 0; 1684 n += 1; 1685 } 1686 if (n == 0) { 1687 style.* = .{}; 1688 return; 1689 } 1690 var i: usize = 0; 1691 while (i < n) : (i += 1) { 1692 switch (nums[i]) { 1693 0 => style.* = .{}, 1694 7 => style.inverted = true, 1695 27 => style.inverted = false, 1696 39 => style.fg = null, 1697 49 => style.bg = null, 1698 38, 48 => { 1699 // truecolor form: 38;2;r;g;b — anything else is ignored 1700 if (i + 4 < n and nums[i + 1] == 2) { 1701 const c = Grid.Color{ 1702 .r = @truncate(nums[i + 2]), 1703 .g = @truncate(nums[i + 3]), 1704 .b = @truncate(nums[i + 4]), 1705 }; 1706 if (nums[i] == 38) style.fg = c else style.bg = c; 1707 i += 4; 1708 } 1709 }, 1710 else => {}, 1711 } 1712 } 1713 } 1714 }; 1715 1716 // a full-screen wrapper that renders ANSI art behind whatever page it wraps 1717 pub const AnsiBackground = struct { 1718 grid: ?Grid, 1719 child: *Widget, 1720 art: AnsiArt, 1721 session: *Session, 1722 1723 pub fn init(allocator: std.mem.Allocator, child_widget: Widget, art_content: []const u8, session: *Session) !AnsiBackground { 1724 var cw = child_widget; 1725 const child = allocator.create(Widget) catch |e| { 1726 cw.deinit(allocator); 1727 return e; 1728 }; 1729 child.* = cw; 1730 errdefer { 1731 child.deinit(allocator); 1732 allocator.destroy(child); 1733 } 1734 return .{ .grid = null, .child = child, .art = try AnsiArt.init(allocator, art_content), .session = session }; 1735 } 1736 1737 pub fn deinit(self: *AnsiBackground, allocator: std.mem.Allocator) void { 1738 if (self.grid) |*grid| grid.deinit(); 1739 self.art.deinit(allocator); 1740 self.child.deinit(allocator); 1741 allocator.destroy(self.child); 1742 } 1743 1744 pub fn build(self: *AnsiBackground, allocator: std.mem.Allocator, constraint: layout.Constraint, root_focus: *Focus) !void { 1745 self.clearGrid(); 1746 1747 // make the wrapped page fill the whole available area 1748 try self.child.build(allocator, .{ 1749 .min_size = .{ 1750 .width = constraint.max_size.width orelse constraint.min_size.width, 1751 .height = constraint.max_size.height orelse constraint.min_size.height, 1752 }, 1753 .max_size = constraint.max_size, 1754 }, root_focus); 1755 1756 if (self.session.data.enable_ansi) { 1757 if (self.child.getGrid()) |fg| { 1758 self.grid = try artBehind(allocator, fg, &self.art, .top_right, root_focus); 1759 } 1760 } 1761 } 1762 1763 pub fn input(self: *AnsiBackground, allocator: std.mem.Allocator, key: inp.Key, root_focus: *Focus) !void { 1764 try self.child.input(allocator, key, root_focus); 1765 } 1766 1767 pub fn clearGrid(self: *AnsiBackground) void { 1768 if (self.grid) |*grid| { 1769 grid.deinit(); 1770 self.grid = null; 1771 } 1772 self.child.clearGrid(); 1773 self.art.clearGrid(); 1774 } 1775 1776 pub fn getGrid(self: AnsiBackground) ?Grid { 1777 return self.grid orelse self.child.getGrid(); 1778 } 1779 1780 pub fn getFocus(self: *AnsiBackground) *Focus { 1781 return self.child.getFocus(); 1782 } 1783 1784 // which top corner the art hugs. 1785 const ArtAnchor = enum { top_left, top_right }; 1786 1787 // a foreground cell counts as blank if it's empty or a bare space without styling 1788 fn cellIsBlank(cell: Grid.Cell) bool { 1789 if (cell.rune) |rune| { 1790 return std.mem.eql(u8, rune, " ") and 1791 cell.style.fg == null and cell.style.bg == null and !cell.style.inverted; 1792 } 1793 return true; 1794 } 1795 1796 // the art is dimmed to this fraction of its brightness so foreground text 1797 // stays legible over it 1798 const art_brightness = 45; // percent 1799 1800 fn dimColor(color: ?Grid.Color) ?Grid.Color { 1801 const c = color orelse return null; 1802 return .{ 1803 .r = @intCast(@as(u16, c.r) * art_brightness / 100), 1804 .g = @intCast(@as(u16, c.g) * art_brightness / 100), 1805 .b = @intCast(@as(u16, c.b) * art_brightness / 100), 1806 }; 1807 } 1808 1809 // terminals that don't support truecolor misparse a "38;2;r;g;b"/"48;2;…" 1810 // SGR as a list of plain SGR codes, so any channel value in 1..9 turns on 1811 // a text attribute (5/6 = blink, 7 = inverse, 8 = conceal, …). 1812 // snap such channels clear of that range so the backdrop doesn't blink or 1813 // hide text there; the ≤9/255 shift is imperceptible on terminals that 1814 // actually render truecolor. 1815 fn sgrSafe(color: ?Grid.Color) ?Grid.Color { 1816 const c = color orelse return null; 1817 const snap = struct { 1818 fn f(v: u8) u8 { 1819 return if (v >= 1 and v <= 9) 10 else v; 1820 } 1821 }.f; 1822 return .{ .r = snap(c.r), .g = snap(c.g), .b = snap(c.b) }; 1823 } 1824 1825 // composites ANSI art behind a foreground grid 1826 fn artBehind(allocator: std.mem.Allocator, foreground: Grid, art: *AnsiArt, anchor: ArtAnchor, root_focus: *Focus) !Grid { 1827 art.clearGrid(); 1828 try art.build(allocator, .{ 1829 .min_size = .{ .width = null, .height = null }, 1830 .max_size = .{ .width = foreground.size.width, .height = foreground.size.height }, 1831 }, root_focus); 1832 1833 var out = try Grid.initFromGrid(allocator, foreground, foreground.size, 0, 0); 1834 errdefer out.deinit(); 1835 1836 if (art.getGrid()) |art_grid| { 1837 const anchor_x = switch (anchor) { 1838 .top_left => 0, 1839 .top_right => foreground.size.width -| art_grid.size.width, 1840 }; 1841 for (0..art_grid.size.height) |y| { 1842 for (0..art_grid.size.width) |x| { 1843 const src = art_grid.cells.items[try art_grid.cells.at(.{ y, x })]; 1844 if (src.rune == null) continue; 1845 const idx = out.cells.at(.{ y, anchor_x + x }) catch continue; 1846 const dst = &out.cells.items[idx]; 1847 // composite the dimmed art behind every cell so it shows 1848 // through the whole UI: a blank cell becomes the art, while a 1849 // cell with a glyph keeps the glyph but takes the dimmed art as 1850 // its background (replacing whatever background it had, which 1851 // would otherwise obscure the art). 1852 if (cellIsBlank(dst.*)) { 1853 dst.* = src; 1854 dst.style.fg = sgrSafe(dimColor(dst.style.fg)); 1855 dst.style.bg = sgrSafe(dimColor(dst.style.bg)); 1856 } else { 1857 dst.style.bg = sgrSafe(dimColor(src.style.bg orelse src.style.fg)); 1858 } 1859 } 1860 } 1861 } 1862 return out; 1863 } 1864 }; 1865