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