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