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