summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Addon.zig13
-rw-r--r--src/Core.zig44
-rw-r--r--src/Effect.zig2
-rw-r--r--src/Kind.zig48
-rw-r--r--src/TerminalImages.zig55
-rw-r--r--src/addon_test.zig2
-rw-r--r--src/builtins.zig2
-rw-r--r--src/config.zig3
-rw-r--r--src/gui/gui.zig16
-rw-r--r--src/host_io.zig4
-rw-r--r--src/image.zig558
-rw-r--r--src/keys.zig1
-rw-r--r--src/look.zig3
-rw-r--r--src/macos.zig19
-rw-r--r--src/ninep/ctl.zig40
-rw-r--r--src/panes.zig3
-rw-r--r--src/pardes.zig5
-rw-r--r--src/pdf_view.zig177
-rw-r--r--src/surface.zig73
-rw-r--r--src/tape.zig6
-rw-r--r--src/tui/tui.zig16
21 files changed, 371 insertions, 719 deletions
diff --git a/src/Addon.zig b/src/Addon.zig
index 4a387afa..6955741d 100644
--- a/src/Addon.zig
+++ b/src/Addon.zig
@@ -294,7 +294,7 @@ pub const Loaded = struct {
name: []const u8 = "",
version: u32 = 0,
abi: u32 = 0,
- /// The library file's BLAKE3; zero for a kind compiled in.
+ /// The library file's BLAKE3; zero for one never read.
hash: [32]u8 = @splat(0),
caps: Kind.Caps = .{},
path: []const u8 = "",
@@ -372,7 +372,7 @@ pub fn take(r: *Kind.Registry, l: Loaded, except: []const u8) ?[]const u8 {
r.n += 1;
return e.why.slice();
}
- e.why.set(if (e.compiledIn()) "static" else "loaded");
+ e.why.set("loaded");
r.ops[r.n] = if (tape.replaying()) null else @ptrFromInt(l.ops);
for (l.words) |w| {
r.words[r.nwords] = .{ .kind = r.n, .arg = w.arg, .opens = w.opens };
@@ -462,7 +462,7 @@ pub fn run(p: *Pardes, id: usize, arg: ?[]const u8) void {
if (a.len == 0) {
var w: std.Io.Writer = .fixed(&said);
w.writeAll("addons:") catch {};
- for (p.kinds.kinds[0..p.kinds.n]) |*e| if (!e.refused) w.print(" {s} {d}{s}", .{ e.nameOf(), e.version, if (e.compiledIn()) " (compiled in)" else "" }) catch {};
+ for (p.kinds.kinds[0..p.kinds.n]) |*e| if (!e.refused) w.print(" {s} {d}", .{ e.nameOf(), e.version }) catch {};
return p.setMessage(id, w.buffered());
}
const takes = "Addon takes load <path>, unload <name> or reload <name>";
@@ -478,7 +478,6 @@ pub fn run(p: *Pardes, id: usize, arg: ?[]const u8) void {
}
const k = p.kinds.byName(rest) orelse return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: no addon brought kind {s}", .{ op, rest }) catch takes);
const e = &p.kinds.kinds[k];
- if (e.compiledIn()) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon {t}: {s} is compiled in", .{ op, rest }) catch takes);
if (op == .reload) return p.emit(.{ .addon = .{ .op = .reload, .pane = @intCast(id), .arg = .from(e.path.slice()) } });
const n = openPanes(p, rest);
if (n > 0) return p.reportFailure(id, std.fmt.bufPrint(&said, "Addon unload: {d} {s} pane{s} open", .{ n, rest, if (n == 1) " is" else "s are" }) catch takes);
@@ -551,7 +550,7 @@ pub fn reopenWaiting(p: *Pardes, name: []const u8) usize {
/// generation (a job the old one asked for is dropped as it answers).
fn swap(p: *Pardes, l: Loaded, why: *Why) bool {
const k = for (p.kinds.kinds[0..p.kinds.n], 0..) |*e, i| {
- if (!e.refused and !e.compiledIn() and std.mem.eql(u8, e.path.slice(), l.path)) break @as(u8, @intCast(i));
+ if (!e.refused and std.mem.eql(u8, e.path.slice(), l.path)) break @as(u8, @intCast(i));
} else return fail(why, "no addon was loaded from it", .{});
const name = p.kinds.kinds[k].nameOf();
if (l.why.len > 0) return fail(why, "{s}", .{l.why});
@@ -612,12 +611,12 @@ fn fail(why: *Why, comptime fmt: []const u8, args: anytype) bool {
}
/// /addons: `<kind> <version> <abi> <panes open> <path> <blake3>
-/// static|loaded|refused: why` a line (`-` for no path, no hash).
+/// loaded|refused: why` a line (`-` for no path, no hash).
pub fn list(p: *const Pardes, out: *std.ArrayList(u8), gpa: std.mem.Allocator) !void {
for (p.kinds.kinds[0..p.kinds.n]) |*e| {
const name = if (e.nameOf().len > 0) e.nameOf() else std.fs.path.basename(e.path.slice());
try out.print(gpa, "{s} {d} {d}.{d} {d} {s} ", .{ name, e.version, e.abi >> 16, e.abi & 0xffff, if (e.refused) 0 else openPanes(p, name), if (e.path.len > 0) e.path.slice() else "-" });
- if (e.compiledIn()) try out.append(gpa, '-') else try out.print(gpa, "{x}", .{e.hash});
+ if (std.mem.allEqual(u8, &e.hash, 0)) try out.append(gpa, '-') else try out.print(gpa, "{x}", .{e.hash});
try out.print(gpa, " {s}\n", .{e.why.slice()});
}
}
diff --git a/src/Core.zig b/src/Core.zig
index 4584e395..b1195ac2 100644
--- a/src/Core.zig
+++ b/src/Core.zig
@@ -64,7 +64,6 @@ const font_picker = pardes.font_picker;
const fonts = pardes.fonts;
const frame_ns = pardes.frame_ns;
const host_io = pardes.host_io;
-const image = pardes.image;
const layout = pardes.layout;
const limits = memory.limits;
const locations = @import("locations.zig");
@@ -2499,7 +2498,7 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane"
try testing.expect(!first.tty_filter);
const doc_id = p.freeSlot().?;
- const doc = try pardes.Kind.open(p, doc_id, pardes.Kind.image, "/tmp/filter-inert.ppm", "");
+ const doc = try pardes.Kind.open(p, doc_id, pardes.Kind.test_kind.of(p), "/tmp/filter-inert.ppm", "");
try testing.expect(!doc.tty_filter);
try testing.expect(p.executeBuiltinLine(doc_id, "Filter"));
try testing.expect(!doc.tty_filter);
@@ -2669,7 +2668,7 @@ test "unknown Exec from a document runs as a command pane in its directory, type
// A terminal free at a prompt in the same directory is not borrowed.
p.setCwd(0, "/tmp/pardes-image-dir");
- const image_doc = try pardes.Kind.open(p, 1, pardes.Kind.image, "/tmp/pardes-image-dir/pic.ppm", null);
+ const image_doc = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pardes-image-dir/pic.ppm", null);
try std.testing.expectEqualStrings("/tmp/pardes-image-dir", Pardes.paneDir(image_doc));
const dst = exec.execute(p, 1, "echo image-fallback") orelse return error.ExecFoundNowhereToRun;
try std.testing.expect(dst != 0 and dst != 1);
@@ -2723,7 +2722,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 });
defer p.deinit();
while (p.nextEffect()) |_| {}
- _ = try pardes.Kind.open(p, 1, pardes.Kind.image, "/tmp/pic.ppm", null);
+ _ = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pic.ppm", null);
const two = "def greet(name):\n return name\n\nprint(greet(\"x\"))\n";
const dst = exec.execute(p, 1, two) orelse return error.NoCommandPane;
while (p.nextEffect()) |_| {}
@@ -3071,7 +3070,7 @@ test "a command pane shows how its command ended, and the next command there run
defer p.deinit();
while (p.nextEffect()) |_| {}
p.setCwd(0, "/tmp/pardes-cmd");
- _ = try pardes.Kind.open(p, 1, pardes.Kind.image, "/tmp/pardes-cmd/pic.ppm", null);
+ _ = try pardes.Kind.open(p, 1, pardes.Kind.test_kind.of(p), "/tmp/pardes-cmd/pic.ppm", null);
const dst = exec.execute(p, 1, "make -j8") orelse return error.NoCommandPane;
while (p.nextEffect()) |_| {}
@@ -3163,41 +3162,6 @@ test "a command pane shows how its command ended, and the next command there run
try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long));
}
-test "image dump restores source bytes renderer choices and exact custom tail" {
- const gpa = std.testing.allocator;
- const p = try Pardes.init(gpa, .{ .tty_only = true });
- defer p.deinit();
- try pardes.panes.deinitPane(p, p.panes[0].?);
- p.panes[0] = null;
-
- const source = "\x00embedded image bytes\xff";
- const pane = try pardes.Kind.open(p, 0, pardes.Kind.image, "/missing/restored-image.ppm", source);
- pane.addon.?.art = .{ .glyph = true, .palette = .terminal, .ascii = false };
- if (pane.tag.own) |own| p.gpa.free(own);
- pane.tag.own = try p.gpa.dupe(u8, " Keep Del");
- try dump.dumpState(p);
-
- const restored = try dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?);
- defer restored.deinit();
- const restored_pane = restored.panes[0].?;
- const art = restored_pane.addon.?.art;
- try std.testing.expect(art.glyph);
- try std.testing.expectEqual(image.PaletteMode.terminal, art.palette);
- try std.testing.expect(!art.ascii);
- try std.testing.expect(restored_pane.tag.own != null);
- try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane));
- var kept: [64]u8 = undefined;
- const slot = restored_pane.addon.?;
- try std.testing.expectEqualSlices(u8, source, kept[0..image.kind.dump.?(slot.st, &kept, kept.len)]);
-
- // And dumped again, its bytes still there.
- try dump.dumpState(restored);
- const again = try dump.load(gpa, .{ .tty_only = true }, restored.dump_out.?, null);
- defer again.deinit();
- // Loaded as a replica loads it: a placeholder holding the record.
- try std.testing.expectEqualSlices(u8, source, again.panes[0].?.addon.?.record.?);
-}
-
test "a terminal its program gave back takes command lines again" {
const gpa = std.testing.allocator;
const p = try Pardes.init(gpa, .{});
diff --git a/src/Effect.zig b/src/Effect.zig
index 31187751..f5ee7ff9 100644
--- a/src/Effect.zig
+++ b/src/Effect.zig
@@ -615,7 +615,7 @@ test "Save reaches every tagline with text behind it and no other" {
// An image's bytes on disk already are what they are: nothing of the
// pane's own is unwritten, so the word is absent and inert.
const img_id = p.freeSlot().?;
- const img = try pardes.Kind.open(p, img_id, pardes.Kind.image, "/tmp/pardes-tag.ppm", "");
+ const img = try pardes.Kind.open(p, img_id, pardes.Kind.test_kind.of(p), "/tmp/pardes-tag.ppm", "");
try std.testing.expectEqualStrings(" Term Collapse Del", tagline.curTail(img));
try std.testing.expect(p.executeBuiltinLine(img_id, "Save"));
try std.testing.expect(img.prompt != .save);
diff --git a/src/Kind.zig b/src/Kind.zig
index 241acf4b..60d86778 100644
--- a/src/Kind.zig
+++ b/src/Kind.zig
@@ -2,7 +2,7 @@
//! anything an addon (a library, Addon.zig) brings. Its records and
//! functions are the C ABI of src/kinds/pardes_addon.h (translated, the
//! one copy); this file is the core's side of it: the kinds a core has
-//! (`Registry`, compiled in or brought, with their words and extensions),
+//! (`Registry`, what libraries brought, with their words and extensions),
//! and a pane's `Slot`, the state the core keeps round the kind's own.
//!
//! The core is deterministic and a kind is only the authority's: a
@@ -47,8 +47,6 @@ comptime {
// ---- the kinds a core has ----
pub const max_kinds = 16;
-/// The kinds compiled in come first in every core: the image is kind 0.
-pub const image: u8 = 0;
/// Which of its functions a kind has: what both cores decide by.
pub const Caps = packed struct(u8) {
@@ -77,17 +75,13 @@ pub const Entry = struct {
pub fn nameOf(e: *const Entry) []const u8 {
return std.mem.sliceTo(&e.name, 0);
}
- pub fn compiledIn(e: *const Entry) bool {
- return std.mem.allEqual(u8, &e.hash, 0);
- }
};
pub const Word = struct { kind: u8, name: Buf(32) = .{}, leader: Buf(8) = .{}, arg: u8 = 0, opens: u8 = 0, doc: Buf(96) = .{} };
pub const Ext = struct { kind: u8, ext: Buf(16) = .{} };
-/// A core's kinds: the compiled-in ones every core starts with, then what
-/// libraries brought (Addon.zig), as data both cores hold alike; and each
-/// one's code here, which a replica has none of for a library's.
+/// A core's kinds: what libraries brought (Addon.zig), as data both cores
+/// hold alike; and each one's code here, which a replica has none of.
pub const Registry = struct {
pub const replica = .{
.local = .{"ops"},
@@ -101,17 +95,9 @@ pub const Registry = struct {
nexts: u8 = 0,
ops: [max_kinds]?*const Ops = @splat(null),
- /// The kinds compiled in.
- pub fn init() Registry {
- var r: Registry = .{};
- var words: [64]LoadedWord = undefined;
- _ = r.take(loadedOf(&@import("image.zig").kind, "", @splat(0), &words), "");
- return r;
- }
-
- /// The kinds compiled in and what the scan at start found.
+ /// What the scan at start found.
pub fn started(found: []const Loaded) Registry {
- var r: Registry = .init();
+ var r: Registry = .{};
for (found) |l| _ = r.take(l, "");
return r;
}
@@ -793,6 +779,25 @@ fn textPane(p: *Pardes, id: usize, slot: *const Slot, name: []const u8, text: []
@import("exec.zig").placeNew(p, id, id, free, .doc);
}
+/// A kind for tests of the core's side of a kind's pane, no library: a
+/// picture of one pixel over its body.
+pub const test_kind = struct {
+ const pixel = [4]u8{ 255, 0, 0, 255 };
+ fn picture(_: ?*anyopaque, win: [*c]const c.pa_window, out: [*c]c.pa_paint) callconv(.c) void {
+ out.*.placements[0] = std.mem.zeroInit(c.pa_placement, .{ .rgba = &pixel, .w = 1, .h = 1, .src = .{ .x = 0, .y = 0, .w = 1, .h = 1 }, .dst = .{ .x = 0, .y = 0, .w = win.*.cols, .h = win.*.rows } });
+ out.*.n = 1;
+ }
+ const ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .name = "test".* ++ @as([12]u8, @splat(0)), .version = 1 }), .paint = picture });
+
+ /// Its index in `p`'s kinds, taken in at the first ask.
+ pub fn of(p: *Pardes) u8 {
+ if (p.kinds.byName("test")) |k| return k;
+ var words: [64]LoadedWord = undefined;
+ _ = p.kinds.take(loadedOf(&ops, "", @splat(0), &words), "");
+ return p.kinds.n - 1;
+ }
+};
+
// ---- small things ----
pub fn Buf(comptime n: usize) type {
@@ -824,14 +829,13 @@ test "a kind's head is checked before a core takes it, and a core's kinds are it
};
var ops = std.mem.zeroInit(Ops, .{ .head = std.mem.zeroInit(c.pa_head, .{ .size = @sizeOf(c.pa_head), .abi = abi, .version = 3 }), .paint = Fake.paint });
@memcpy(ops.head.name[0..5], "zzzab");
- var a: Registry = .init();
- var b: Registry = .init();
+ var a: Registry = .{};
+ var b: Registry = .{};
var words: [64]LoadedWord = undefined;
try std.testing.expect(a.take(loadedOf(&ops, "", @splat(1), &words), "") == null);
try std.testing.expect(a.byName("zzzab") != null);
try std.testing.expect(b.byName("zzzab") == null);
try std.testing.expectEqualStrings("refused: kind zzzab is here already", a.take(loadedOf(&ops, "", @splat(1), &words), "").?);
- try std.testing.expectEqualStrings("refused: kind image is here already", b.take(loadedOf(&@import("image.zig").kind, "", @splat(1), &words), "").?);
a.drop(a.byName("zzzab").?);
try std.testing.expect(a.byName("zzzab") == null);
}
diff --git a/src/TerminalImages.zig b/src/TerminalImages.zig
index 0aee6b52..c352c2a4 100644
--- a/src/TerminalImages.zig
+++ b/src/TerminalImages.zig
@@ -10,11 +10,12 @@
const std = @import("std");
const ghostty_vt = @import("ghostty-vt");
const pardes = @import("pardes.zig");
-const image = @import("image.zig");
+const zstbi = @import("zstbi");
+const wuffs = @import("wuffs");
const TerminalImages = @This();
const gfx = ghostty_vt.kitty.graphics;
-const PixelRect = image.PixelRect;
+const PixelRect = @import("surface.zig").RectPx;
/// The bytes ghostty-vt may hold for one screen's images (it evicts the
/// oldest past this): a 4K picture in RGBA, with room for a second.
@@ -59,25 +60,25 @@ const PlaceholderRuns = struct {
continue;
}
var run: ?gfx.unicode.IncompletePlacement = null;
- var start: usize = 0;
+ var first: usize = 0;
const cells = row.cells(.all);
while (self.x < cells.len) : (self.x += 1) {
const cell = &cells[self.x];
if (cell.codepoint() != gfx.unicode.placeholder) {
- if (run) |done| return complete(row, start, done);
+ if (run) |done| return complete(row, first, done);
continue;
}
const style = row.style(cell);
const curr: gfx.unicode.IncompletePlacement = .init(&style, row.grapheme(cell) orelse &.{});
if (run) |*prev| {
- if (!prev.append(&curr)) return complete(row, start, prev.*);
+ if (!prev.append(&curr)) return complete(row, first, prev.*);
} else {
run = curr.start();
- start = self.x;
+ first = self.x;
}
}
self.advance();
- if (run) |done| return complete(row, start, done);
+ if (run) |done| return complete(row, first, done);
}
return null;
}
@@ -109,14 +110,48 @@ pub fn deinit(ti: *TerminalImages, gpa: std.mem.Allocator) void {
}
/// Accept PNG (`f=100`) as well as raw pixels: ghostty-vt built as a
-/// library decodes none itself. stb_image does it, as for image panes.
+/// library decodes none itself. wuffs does it (ghostty's, linked for it).
pub fn installPngDecoder() void {
ghostty_vt.sys.decode_png = &decodePng;
}
+/// The longest side a PNG is kept at: a pane is at most a screenful of
+/// cells, and a multi-thousand-pixel picture only costs its memory.
+const max_dim: u32 = 1280;
+
+/// stb_image_resize has its allocator (`start`): before, a PNG is refused.
+var started = false;
+
+/// Once at startup and exit, with what the resize allocates from.
+pub fn start(io: std.Io, gpa: std.mem.Allocator) void {
+ zstbi.init(io, gpa);
+ started = true;
+}
+pub fn stop() void {
+ started = false;
+ zstbi.deinit();
+}
+
fn decodePng(gpa: std.mem.Allocator, bytes: []const u8) ghostty_vt.sys.DecodeError!ghostty_vt.sys.Image {
- const decoded = image.decode(gpa, bytes) orelse return error.InvalidData;
- return .{ .width = @intCast(decoded.w), .height = @intCast(decoded.h), .data = decoded.rgba };
+ if (!started) return error.InvalidData;
+ // Bounded before decoding: a few KB of PNG can name gigapixels. The
+ // signature, then IHDR first: its length, type, width and height.
+ if (bytes.len < 24 or !std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n") or !std.mem.eql(u8, bytes[12..16], "IHDR")) return error.InvalidData;
+ const w = std.mem.readInt(u32, bytes[16..20], .big);
+ const h = std.mem.readInt(u32, bytes[20..24], .big);
+ if (@as(u64, w) * h > pardes.memory.limits.image_decode_pixels) return error.InvalidData;
+ const got = wuffs.png.decode(gpa, bytes) catch return error.InvalidData;
+ if (got.data.len != @as(usize, got.width) * got.height * 4) {
+ gpa.free(got.data);
+ return error.InvalidData;
+ }
+ const longest = @max(got.width, got.height);
+ if (longest <= max_dim) return .{ .width = got.width, .height = got.height, .data = got.data };
+ defer gpa.free(got.data);
+ const img: zstbi.Image = .{ .data = got.data, .width = got.width, .height = got.height, .num_components = 4, .bytes_per_component = 1, .bytes_per_row = got.width * 4, .is_hdr = false };
+ var scaled = img.resize(@intCast(@max(1, @as(u64, got.width) * max_dim / longest)), @intCast(@max(1, @as(u64, got.height) * max_dim / longest)));
+ defer scaled.deinit();
+ return .{ .width = scaled.width, .height = scaled.height, .data = gpa.dupe(u8, scaled.data) catch return error.InvalidData };
}
/// Draw the active screen's images. `rows_of[v]` is the body row the
diff --git a/src/addon_test.zig b/src/addon_test.zig
index 9acd319b..a4788109 100644
--- a/src/addon_test.zig
+++ b/src/addon_test.zig
@@ -45,8 +45,6 @@ fn run(io: std.Io, gpa: std.mem.Allocator, lib: []const u8, script_path: ?[]cons
// The regions and the C libraries' allocators a frontend sets up.
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
- pardes.image.start(io, allocs.image);
- defer pardes.image.stop();
pardes.syntax.start(allocs.tree_sitter);
defer pardes.syntax.stop();
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .image_allocator = allocs.image, .pdf_allocator = allocs.pdf, .tree_sitter_allocator = allocs.tree_sitter, .frame_allocator = allocs.frame });
diff --git a/src/builtins.zig b/src/builtins.zig
index 643fe5bb..68730166 100644
--- a/src/builtins.zig
+++ b/src/builtins.zig
@@ -1023,7 +1023,7 @@ pub const Palette = struct {
pub fn run(c: Ctx) void {
const art = &(c.pane.addon orelse return).art;
if (c.arg != null) {
- const want = stateArg(c, panes.Image.PaletteMode, "Palette", "commodore or terminal") orelse return;
+ const want = stateArg(c, pardes.Placement.Art.Palette, "Palette", "commodore or terminal") orelse return;
if (want == art.palette) return;
}
art.palette = if (art.palette == .commodore) .terminal else .commodore;
diff --git a/src/config.zig b/src/config.zig
index ae9b774a..f9fd336f 100644
--- a/src/config.zig
+++ b/src/config.zig
@@ -301,7 +301,6 @@ pub const dir_pane_builtins_str = "Get Term Collapse Del";
pub const tag_normal = " ";
pub const tag_insert = "^";
pub const tag_tty = "$";
-pub const tag_image = "img";
pub const command_line: []const Chord = &.{.{ .cp = ':' }};
@@ -468,8 +467,6 @@ pub const pane_addr = "@p";
pub const url_schemes = [_][]const u8{ "http://", "https://" };
-pub const image_exts = [_][]const u8{ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ppm", ".pgm", ".tga" };
-
// Match Helix's fallback for unknown languages and languages without line comments.
pub const comment_token_default = "#";
pub const comment_tokens: []const struct { exts: []const []const u8, token: []const u8 } = &.{
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index 0d8c53ca..1125ff03 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -2030,12 +2030,16 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_
const have: ?*replica.Have = if (far) &have_store else null;
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
- pardes.image.start(io, allocs.image);
- if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.pdf.start(allocs.pdf);
+ }
pardes.syntax.start(allocs.tree_sitter);
defer {
- pardes.image.stop();
- if (comptime pardes.pdf_enabled) pardes.pdf.stop();
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.stop();
+ pardes.pdf.stop();
+ }
pardes.syntax.stop();
}
var o = opts_in;
@@ -5028,11 +5032,11 @@ fn validImageBytes(place: pardes.Placement) ?u32 {
/// Where the placement's pixels go in its cells: where it says, or fitted
/// there (no larger than it is, at the top left).
-fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.image.NativeGeometry {
+fn nativePlaceGeometry(g: *const Gui, place: pardes.Placement) ?pardes.NativeGeometry {
if (place.at) |at| return .{ .src = place.src, .dst = at };
const bound_w = std.math.mul(u32, place.dst.w, g.cell_w) catch return null;
const bound_h = std.math.mul(u32, place.dst.h, g.cell_h) catch return null;
- const fit = pardes.image.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null;
+ const fit = pardes.containGeometry(place.src.w, place.src.h, bound_w, bound_h) orelse return null;
return .{ .src = place.src, .dst = fit.dst };
}
diff --git a/src/host_io.zig b/src/host_io.zig
index 2320077e..9cc34465 100644
--- a/src/host_io.zig
+++ b/src/host_io.zig
@@ -171,8 +171,8 @@ pub fn testClock() ?u64 {
/// on `allocs` (pardes.memory.init); PDF pages render on lanes off the
/// loop (pdf_view.workers). `stopWorkers` is its defer.
pub fn startWorkers(io: std.Io, allocs: pardes.memory.Allocators) void {
- pardes.image.start(io, allocs.image);
if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.start(io, allocs.image);
pardes.pdf.start(allocs.pdf);
pardes.panes.Pdf.workers = io;
}
@@ -180,8 +180,8 @@ pub fn startWorkers(io: std.Io, allocs: pardes.memory.Allocators) void {
}
pub fn stopWorkers() void {
- pardes.image.stop();
if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.stop();
pardes.panes.Pdf.dropKept();
pardes.pdf.stop();
}
diff --git a/src/image.zig b/src/image.zig
deleted file mode 100644
index b5efc5fd..00000000
--- a/src/image.zig
+++ /dev/null
@@ -1,558 +0,0 @@
-//! Image decoding, pixel placement, and the image pane.
-const std = @import("std");
-const builtin = @import("builtin");
-const zstbi = @import("zstbi");
-const pdf_enabled = @import("pardes_config").mupdf;
-const pardes = @import("pardes.zig");
-const Kind = @import("Kind.zig");
-const config = @import("config.zig");
-const filesystem = @import("fs.zig");
-/// cap the longest side before keeping/transmitting: a pane is at most a
-/// screenful of cells, multi-thousand-pixel photos waste decode/transmit time
-const MAX_DIM: u32 = 1280;
-
-pub const PaletteMode = pardes.Placement.Art.Palette;
-
-/// How a native pixel attachment is placed in its pane body. `contain` is the
-/// historical image-pane policy: shrink only when necessary and keep the
-/// image at the top left. The axis-specific modes may enlarge, letterbox the
-/// unconstrained axis, or crop it when it overflows.
-pub const NativeFit = if (pdf_enabled) enum { contain, width, height } else enum { contain };
-
-pub const PixelRect = struct {
- x: u32 = 0,
- y: u32 = 0,
- w: u32 = 0,
- h: u32 = 0,
-};
-
-pub const PixelPoint = struct { x: u32, y: u32 };
-
-/// Source pixels and their destination inside a pane body's pixel rectangle.
-/// Both rectangles are half-open. Rounding is always toward the inside, so a
-/// backend can draw this result without a backend-specific overflow clip.
-pub const NativeGeometry = struct {
- src: PixelRect,
- dst: PixelRect,
-
- /// Map a destination pixel back into the retained source crop. This is the
- /// same integer transform the texture rectangle describes; points in a
- /// letterbox return null.
- pub fn sourcePoint(self: NativeGeometry, x: u32, y: u32) ?PixelPoint {
- if (self.src.w == 0 or self.src.h == 0 or self.dst.w == 0 or self.dst.h == 0) return null;
- if (x < self.dst.x or y < self.dst.y) return null;
- const dx = x - self.dst.x;
- const dy = y - self.dst.y;
- if (dx >= self.dst.w or dy >= self.dst.h) return null;
- return .{
- .x = self.src.x + @as(u32, @intCast(@as(u64, dx) * self.src.w / self.dst.w)),
- .y = self.src.y + @as(u32, @intCast(@as(u64, dy) * self.src.h / self.dst.h)),
- };
- }
-};
-
-fn panOffset(overflow: u32, pan: u16) u32 {
- if (overflow == 0 or pan == 0) return 0;
- if (pan == std.math.maxInt(u16)) return overflow;
- // Round, rather than truncate, so the midpoint is the visual midpoint.
- return @intCast((@as(u64, overflow) * pan + std.math.maxInt(u16) / 2) / std.math.maxInt(u16));
-}
-
-fn fitWidth(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_y: u16) ?NativeGeometry {
- const scaled_h = @as(u64, src_h) * body_w;
- if (scaled_h <= @as(u64, body_h) * src_w) {
- const full_h: u32 = @intCast(@max(1, scaled_h / src_w));
- return .{
- .src = .{ .w = src_w, .h = src_h },
- .dst = .{ .y = (body_h - full_h) / 2, .w = body_w, .h = full_h },
- };
- }
-
- // Retain the largest whole source-pixel crop which cannot extend beyond
- // the body at this scale. The sub-pixel remainder becomes at most a small
- // centered letterbox instead of leaking into an adjacent cell in Kitty.
- const crop_h_wide = @as(u64, body_h) * src_w / body_w;
- if (crop_h_wide == 0) return null;
- const crop_h: u32 = @min(src_h, @as(u32, @intCast(crop_h_wide)));
- const dst_h: u32 = @min(body_h, @max(1, @as(u32, @intCast(@as(u64, crop_h) * body_w / src_w))));
- return .{
- .src = .{
- .y = panOffset(src_h - crop_h, pan_y),
- .w = src_w,
- .h = crop_h,
- },
- .dst = .{ .y = (body_h - dst_h) / 2, .w = body_w, .h = dst_h },
- };
-}
-
-fn fitHeight(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_x: u16) ?NativeGeometry {
- const scaled_w = @as(u64, src_w) * body_h;
- if (scaled_w <= @as(u64, body_w) * src_h) {
- const full_w: u32 = @intCast(@max(1, scaled_w / src_h));
- return .{
- .src = .{ .w = src_w, .h = src_h },
- .dst = .{ .x = (body_w - full_w) / 2, .w = full_w, .h = body_h },
- };
- }
-
- const crop_w_wide = @as(u64, body_w) * src_h / body_h;
- if (crop_w_wide == 0) return null;
- const crop_w: u32 = @min(src_w, @as(u32, @intCast(crop_w_wide)));
- const dst_w: u32 = @min(body_w, @max(1, @as(u32, @intCast(@as(u64, crop_w) * body_h / src_h))));
- return .{
- .src = .{
- .x = panOffset(src_w - crop_w, pan_x),
- .w = crop_w,
- .h = src_h,
- },
- .dst = .{ .x = (body_w - dst_w) / 2, .w = dst_w, .h = body_h },
- };
-}
-
-/// Compute native image placement without floating point. Source dimensions
-/// are limited to u32 because SDL's texture API and Kitty's crop parameters
-/// cannot describe anything larger. Kitty applies the stricter u16 check at
-/// its protocol boundary.
-pub fn nativeGeometry(
- iw: usize,
- ih: usize,
- body_pixel_w: u32,
- body_pixel_h: u32,
- fit: NativeFit,
- pan_x: u16,
- pan_y: u16,
-) ?NativeGeometry {
- if (comptime !pdf_enabled) {
- return containGeometry(iw, ih, body_pixel_w, body_pixel_h);
- }
- if (iw == 0 or ih == 0 or body_pixel_w == 0 or body_pixel_h == 0 or
- iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null;
-
- const src_w: u32 = @intCast(iw);
- const src_h: u32 = @intCast(ih);
- return switch (fit) {
- .width => fitWidth(src_w, src_h, body_pixel_w, body_pixel_h, pan_y),
- .height => fitHeight(src_w, src_h, body_pixel_w, body_pixel_h, pan_x),
- // Pan is not contain's: it keeps the top-left placement.
- .contain => containGeometry(iw, ih, body_pixel_w, body_pixel_h),
- };
-}
-
-/// The ordinary image-pane policy: shrunk only when it must be, at the top
-/// left. The scale ratios are compared without floating point: the tighter
-/// bound is exact, the other rounded inward.
-pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeometry {
- if (iw == 0 or ih == 0 or max_w == 0 or max_h == 0 or
- iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null;
-
- const src_w: u32 = @intCast(iw);
- const src_h: u32 = @intCast(ih);
- if (src_w <= max_w and src_h <= max_h) return .{
- .src = .{ .w = src_w, .h = src_h },
- .dst = .{ .w = src_w, .h = src_h },
- };
- const dst: PixelRect = if (@as(u64, max_w) * src_h <= @as(u64, max_h) * src_w)
- .{
- .w = max_w,
- .h = @intCast(@max(1, @as(u64, src_h) * max_w / src_w)),
- }
- else
- .{
- .w = @intCast(@max(1, @as(u64, src_w) * max_h / src_h)),
- .h = max_h,
- };
- return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst };
-}
-
-test "native image contain keeps aspect, bounds, top-left, and small-image size" {
- try std.testing.expectEqual(PixelRect{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst);
- try std.testing.expectEqual(PixelRect{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst);
- try std.testing.expectEqual(PixelRect{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst);
- try std.testing.expect(containGeometry(17, 9, 0, 40) == null);
-
- const odd = containGeometry(403, 211, 101, 47).?;
- try std.testing.expectEqual(PixelRect{ .w = 89, .h = 47 }, odd.dst);
- try std.testing.expectEqual(PixelRect{ .w = 403, .h = 211 }, odd.src);
-}
-
-test "native fit width handles portrait crop, pan extrema, and landscape letterbox" {
- if (comptime !pdf_enabled) return;
- const top = nativeGeometry(600, 1000, 800, 600, .width, 0, 0).?;
- try std.testing.expectEqual(PixelRect{ .w = 600, .h = 450 }, top.src);
- try std.testing.expectEqual(PixelRect{ .w = 800, .h = 600 }, top.dst);
-
- const middle = nativeGeometry(600, 1000, 800, 600, .width, 0, 32768).?;
- try std.testing.expectEqual(@as(u32, 275), middle.src.y);
- const bottom = nativeGeometry(600, 1000, 800, 600, .width, 65535, 65535).?;
- try std.testing.expectEqual(@as(u32, 550), bottom.src.y);
-
- const landscape = nativeGeometry(1000, 600, 800, 600, .width, 0, 65535).?;
- try std.testing.expectEqual(PixelRect{ .w = 1000, .h = 600 }, landscape.src);
- try std.testing.expectEqual(PixelRect{ .y = 60, .w = 800, .h = 480 }, landscape.dst);
-}
-
-test "native fit height handles portrait letterbox and landscape crop" {
- if (comptime !pdf_enabled) return;
- const portrait = nativeGeometry(600, 1000, 800, 600, .height, 65535, 0).?;
- try std.testing.expectEqual(PixelRect{ .w = 600, .h = 1000 }, portrait.src);
- try std.testing.expectEqual(PixelRect{ .x = 220, .w = 360, .h = 600 }, portrait.dst);
-
- const left = nativeGeometry(1000, 600, 800, 600, .height, 0, 0).?;
- try std.testing.expectEqual(PixelRect{ .w = 800, .h = 600 }, left.src);
- try std.testing.expectEqual(PixelRect{ .w = 800, .h = 600 }, left.dst);
- const right = nativeGeometry(1000, 600, 800, 600, .height, 65535, 0).?;
- try std.testing.expectEqual(@as(u32, 200), right.src.x);
-}
-
-test "native fit odd ratios round inward and map points through letterboxes and crops" {
- if (comptime !pdf_enabled) return;
- const width = nativeGeometry(403, 211, 101, 47, .width, 0, 32768).?;
- try std.testing.expectEqual(PixelRect{ .y = 12, .w = 403, .h = 187 }, width.src);
- try std.testing.expectEqual(PixelRect{ .w = 101, .h = 46 }, width.dst);
- const mapped = width.sourcePoint(100, 45).?;
- try std.testing.expect(mapped.x < width.src.x + width.src.w);
- try std.testing.expect(mapped.y < width.src.y + width.src.h);
- try std.testing.expect(width.sourcePoint(101, 46) == null);
-
- const height = nativeGeometry(403, 211, 101, 47, .height, 32768, 0).?;
- try std.testing.expectEqual(PixelRect{ .w = 403, .h = 211 }, height.src);
- try std.testing.expectEqual(PixelRect{ .x = 6, .w = 89, .h = 47 }, height.dst);
- try std.testing.expect(height.sourcePoint(5, 20) == null);
- try std.testing.expect(height.sourcePoint(6, 20) != null);
-}
-
-test "native geometry rejects dimensions which its backend contract cannot represent" {
- try std.testing.expect(containGeometry(0, 10, 20, 20) == null);
- if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null);
- if (comptime pdf_enabled) {
- try std.testing.expect(nativeGeometry(10, 10, 0, 20, .width, 0, 0) == null);
- if (@bitSizeOf(usize) > 32)
- try std.testing.expect(nativeGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20, .height, 0, 0) == null);
- }
-}
-
-test "native geometry is total at extreme accepted aspect ratios" {
- if (comptime !pdf_enabled) return;
- const largest = std.math.maxInt(u32);
- try std.testing.expect(nativeGeometry(1, largest, largest, 1, .width, 0, 65535) == null);
- try std.testing.expect(nativeGeometry(largest, 1, 1, largest, .height, 65535, 0) == null);
-
- const wide = nativeGeometry(largest, 1, largest, 1, .width, 0, 0).?;
- try std.testing.expectEqual(PixelRect{ .w = largest, .h = 1 }, wide.dst);
- const tall = nativeGeometry(1, largest, 1, largest, .height, 0, 0).?;
- try std.testing.expectEqual(PixelRect{ .w = 1, .h = largest }, tall.dst);
-}
-
-/// call once at startup / exit (stb_image's allocator shim)
-pub fn start(io: std.Io, gpa: std.mem.Allocator) void {
- zstbi.init(io, gpa);
- decode_gpa = gpa;
- started = true;
-}
-pub fn stop() void {
- started = false;
- decode_gpa = null;
- zstbi.deinit();
-}
-
-/// What a decode allocates from: the image region `start` was given.
-var decode_gpa: ?std.mem.Allocator = null;
-
-/// stb_image has its allocator (`start`): before, nothing of it may run.
-var started = false;
-
-extern fn stbi_info_from_memory(buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, comp: *c_int) c_int;
-
-/// stb_image's header reader.
-fn stbiInfo(bytes: []const u8, w: *c_int, h: *c_int, c: *c_int) bool {
- return stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), w, h, c) == 1;
-}
-
-/// PNG and JPEG are ghostty's decoders (wuffs, which ghostty-vt links for
-/// kitty graphics) wherever ghostty-vt is in the build; stb_image is then
-/// compiled without them, and without the inflate only its PNG used
-/// (build.zig, docs/shared-libs.md). Other formats, and builds without
-/// ghostty-vt, are stb_image's.
-const wuffs_images = @hasDecl(@import("pardes_config"), "wuffs_images") and @import("pardes_config").wuffs_images;
-const wuffs = if (wuffs_images) @import("wuffs") else struct {};
-
-const Format = enum { png, jpeg, other };
-
-fn format(bytes: []const u8) Format {
- if (std.mem.startsWith(u8, bytes, "\x89PNG\r\n\x1a\n")) return .png;
- if (bytes.len >= 3 and bytes[0] == 0xff and bytes[1] == 0xd8 and bytes[2] == 0xff) return .jpeg;
- return .other;
-}
-
-const Size = struct { w: usize, h: usize };
-
-/// An image's size from its header alone, before anything is decoded.
-fn headerSize(bytes: []const u8) ?Size {
- if (comptime wuffs_images) switch (format(bytes)) {
- .png => {
- // The signature, then IHDR first: length, type, width, height.
- if (bytes.len < 24 or !std.mem.eql(u8, bytes[12..16], "IHDR")) return null;
- return .{ .w = std.mem.readInt(u32, bytes[16..20], .big), .h = std.mem.readInt(u32, bytes[20..24], .big) };
- },
- .jpeg => return jpegSize(bytes),
- .other => {},
- };
- var iw: c_int = 0;
- var ih: c_int = 0;
- var ic: c_int = 0;
- if (!stbiInfo(bytes, &iw, &ih, &ic)) return null;
- return .{ .w = @intCast(@max(0, iw)), .h = @intCast(@max(0, ih)) };
-}
-
-/// A JPEG's size, from its first start-of-frame segment (any SOFn but the
-/// DHT, JPG and DAC markers that share their range).
-fn jpegSize(bytes: []const u8) ?Size {
- var at: usize = 2;
- while (at + 4 <= bytes.len) {
- if (bytes[at] != 0xff) return null;
- const marker = bytes[at + 1];
- // Fill bytes, and the markers that stand alone.
- if (marker == 0xff) {
- at += 1;
- continue;
- }
- if (marker == 0x01 or (marker >= 0xd0 and marker <= 0xd7)) {
- at += 2;
- continue;
- }
- const len = std.mem.readInt(u16, bytes[at + 2 ..][0..2], .big);
- if (len < 2) return null;
- const sof = marker >= 0xc0 and marker <= 0xcf and marker != 0xc4 and marker != 0xc8 and marker != 0xcc;
- if (sof) {
- if (at + 9 > bytes.len) return null;
- return .{ .w = std.mem.readInt(u16, bytes[at + 7 ..][0..2], .big), .h = std.mem.readInt(u16, bytes[at + 5 ..][0..2], .big) };
- }
- if (marker == 0xda) return null; // scan data before any frame
- at += 2 + len;
- }
- return null;
-}
-
-/// Whether `bytes` are an image `decode` can read, from its header alone.
-pub fn readable(bytes: []const u8) bool {
- if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return false;
- var w: c_int = 0;
- var h: c_int = 0;
- var c: c_int = 0;
- if (!started) return true; // ponytail: no stb_image yet (a unit test), so no judging
- if (comptime wuffs_images) if (format(bytes) != .other) return headerSize(bytes) != null;
- return stbiInfo(bytes, &w, &h, &c);
-}
-
-/// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the
-/// pane then simply shows a blank body.
-const Decoded = struct { rgba: []u8, w: usize, h: usize };
-
-pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?Decoded {
- // stb_image allocates through what `start` gave it: before that, a call
- // jumps through a null pointer (a terminal's PNG in a core no shell set up).
- if (!started) return null;
- if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null;
- // Bounded before decoding: a few KB of PNG can name gigapixels.
- const size = headerSize(bytes) orelse return null;
- const pixels = std.math.mul(usize, size.w, size.h) catch return null;
- if (pixels > @import("memory.zig").limits.image_decode_pixels) return null;
- if (comptime wuffs_images) switch (format(bytes)) {
- inline .png, .jpeg => |f| {
- const got = @field(wuffs, @tagName(f)).decode(gpa, bytes) catch return null;
- defer gpa.free(got.data);
- if (got.data.len != @as(usize, got.width) * got.height * 4) return null;
- return finish(gpa, .{
- .data = got.data,
- .width = got.width,
- .height = got.height,
- .num_components = 4,
- .bytes_per_component = 1,
- .bytes_per_row = got.width * 4,
- .is_hdr = false,
- });
- },
- .other => {},
- };
- var img = zstbi.Image.loadFromMemory(bytes, 4) catch return null; // 4 = RGBA
- defer img.deinit();
- return finish(gpa, img);
-}
-
-/// The decoded RGBA, scaled to MAX_DIM at most, in a gpa copy.
-fn finish(gpa: std.mem.Allocator, img: zstbi.Image) ?Decoded {
- var scaled: ?zstbi.Image = null;
- defer if (scaled) |*s| s.deinit();
- const longest = @max(img.width, img.height);
- const src: *const zstbi.Image = if (longest > MAX_DIM) blk: {
- const nw = @max(1, img.width * MAX_DIM / longest);
- const nh = @max(1, img.height * MAX_DIM / longest);
- scaled = img.resize(nw, nh);
- break :blk &scaled.?;
- } else &img;
- const rgba = gpa.dupe(u8, src.data) catch return null;
- return .{ .rgba = rgba, .w = src.width, .h = src.height };
-}
-
-test "PNG and JPEG decode through wuffs, sized from their headers first; other formats through stb_image" {
- const gpa = std.testing.allocator;
- start(std.testing.io, gpa);
- defer stop();
- const dec = std.base64.standard.Decoder;
- const Fixture = struct { b64: []const u8, w: usize, h: usize, rgb: [3]u8, tolerance: u8 };
- const fixtures = [_]Fixture{
- // 4x2, red left, blue right (a hand-built PNG).
- .{ .b64 = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAIAAADwyuo0AAAAE0lEQVR4nGP4z8AARGDiPwMyBwBnsgf5Q2OaZwAAAABJRU5ErkJggg==", .w = 4, .h = 2, .rgb = .{ 255, 0, 0 }, .tolerance = 0 },
- // 16x8 of (200,30,30), baseline and progressive (Pillow, quality 95).
- .{ .b64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAAIABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5Dooor8LP9VD/2Q==", .w = 16, .h = 8, .rgb = .{ 200, 30, 30 }, .tolerance = 6 },
- .{ .b64 = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wgARCAAIABADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAVAQEBAAAAAAAAAAAAAAAAAAAGCP/aAAwDAQACEAMQAAABkIC1V//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAQUCP//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Bf//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEABj8CP//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAT8hP//aAAwDAQACAAMAAAAQA//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Qf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Qf//EABQQAQAAAAAAAAAAAAAAAAAAABD/2gAIAQEAAT8QP//Z", .w = 16, .h = 8, .rgb = .{ 200, 30, 30 }, .tolerance = 6 },
- };
- for (fixtures) |f| {
- const bytes = try gpa.alloc(u8, try dec.calcSizeForSlice(f.b64));
- defer gpa.free(bytes);
- try dec.decode(bytes, f.b64);
- try std.testing.expect(readable(bytes));
- const size = headerSize(bytes).?;
- try std.testing.expectEqual(Size{ .w = f.w, .h = f.h }, size);
- const got = decode(gpa, bytes) orelse return error.NotDecoded;
- defer gpa.free(got.rgba);
- try std.testing.expectEqual(f.w, got.w);
- try std.testing.expectEqual(f.h, got.h);
- for (got.rgba[0..3], f.rgb) |have, want| try std.testing.expect(@max(have, want) - @min(have, want) <= f.tolerance);
- try std.testing.expectEqual(@as(u8, 255), got.rgba[3]);
- }
- // A PPM still goes through stb_image.
- const ppm = "P6\n2 1\n255\n\x0d\x4d\xe7\x0d\x4d\xe7";
- try std.testing.expectEqual(Format.other, format(ppm));
- const got = decode(gpa, ppm) orelse return error.NotDecoded;
- defer gpa.free(got.rgba);
- try std.testing.expectEqualSlices(u8, &.{ 0x0d, 0x4d, 0xe7, 255 }, got.rgba[0..4]);
- // Truncated headers are no image, never a read past the end.
- try std.testing.expect(headerSize("\x89PNG\r\n\x1a\n\x00\x00") == null);
- try std.testing.expect(headerSize("\xff\xd8\xff\xe0\x00\x10JFIF") == null);
- try std.testing.expect(decode(gpa, "\xff\xd8\xff\xe0\x00\x10JFIF") == null);
-}
-
-// ---- the image kind (kinds/pardes_addon.h), compiled in ----
-
-/// A picture: its file's bytes decoded on a job, shown as one placement
-/// over the body that a frontend fits (or draws as glyph art).
-pub const kind: Kind.Ops = std.mem.zeroInit(Kind.Ops, .{
- .head = std.mem.zeroInit(Kind.c.pa_head, .{
- .size = @sizeOf(Kind.c.pa_head),
- .abi = Kind.abi,
- .name = "image".* ++ @as([11]u8, @splat(0)),
- .version = 1,
- .exts = exts,
- }),
- .open = open,
- .paint = paint,
- .job_run = jobRun,
- .job_done = jobDone,
- .dump = dump,
- .load = load,
-});
-
-const exts = blk: {
- var all: []const u8 = "";
- for (config.image_exts, 0..) |e, i| all = all ++ (if (i == 0) "" else " ") ++ e;
- break :blk all ++ "";
-};
-
-const State = struct {
- path: []const u8,
- /// The file's bytes, as a dump keeps them.
- raw: []const u8 = &.{},
- rgba: []const u8 = &.{},
- w: u32 = 0,
- h: u32 = 0,
-};
-
-fn alloc(comptime T: type, n: usize) ?[]T {
- const mem = Kind.api.alloc.?(n * @sizeOf(T)) orelse return null;
- return @as([*]T, @ptrCast(@alignCast(mem)))[0..n];
-}
-
-fn open(path: [*c]const u8, bytes: [*c]const u8, len: u64) callconv(.c) ?*anyopaque {
- const st = &(alloc(State, 1) orelse return null)[0];
- const p = if (path == null) "" else std.mem.span(path);
- const kept = alloc(u8, p.len) orelse return null;
- @memcpy(kept, p);
- st.* = .{ .path = kept };
- if (bytes != null) {
- const raw = bytes[0..@intCast(len)];
- // One it cannot read (corrupt, truncated, not what its name says)
- // is refused, rather than shown as a blank pane.
- if (!readable(raw)) {
- const why = "not an image pardes can read";
- Kind.api.say.?(why, why.len, 1);
- return st;
- }
- keep(st, raw);
- }
- return st;
-}
-
-/// The file's bytes kept, and decoded on a job.
-fn keep(st: *State, raw: []const u8) void {
- const copy = alloc(u8, raw.len) orelse return;
- @memcpy(copy, raw);
- st.raw = copy;
- if (raw.len > 0) _ = Kind.api.job.?(copy.ptr, @intCast(copy.len));
-}
-
-fn paint(ctx: ?*anyopaque, win: [*c]const Kind.c.pa_window, out: [*c]Kind.c.pa_paint) callconv(.c) void {
- const st: *const State = @ptrCast(@alignCast(ctx orelse return));
- const w = win.*;
- const o = &out.*;
- // `img`, which the core follows with its art words and the path.
- @memcpy(o.prefix[0..config.tag_image.len], config.tag_image);
- o.prefix_len = config.tag_image.len;
- if (st.rgba.len == 0 or o.cap == 0) return;
- o.placements[0] = std.mem.zeroInit(Kind.c.pa_placement, .{
- .rgba = st.rgba.ptr,
- .w = st.w,
- .h = st.h,
- .src = .{ .x = 0, .y = 0, .w = st.w, .h = st.h },
- .dst = .{ .x = 0, .y = 0, .w = w.cols, .h = w.rows },
- });
- o.n = 1;
-}
-
-/// Off the loop (80 ms in ReleaseSafe, 290 in Debug, for the docs'
-/// screenshot): width and height, then the RGBA.
-fn jobRun(in: [*c]const u8, n: u32, out: [*c]Kind.c.pa_out) callconv(.c) u32 {
- const got = decode(decode_gpa orelse return 0, in[0..n]) orelse return 0;
- defer decode_gpa.?.free(got.rgba);
- const len = 8 + got.rgba.len;
- const buf: [*]u8 = @ptrCast(out.*.alloc.?(out, len) orelse return 0);
- std.mem.writeInt(u32, buf[0..4], @intCast(got.w), .little);
- std.mem.writeInt(u32, buf[4..8], @intCast(got.h), .little);
- @memcpy(buf[8..len], got.rgba);
- return @intCast(len);
-}
-
-fn jobDone(ctx: ?*anyopaque, _: u32, out: [*c]const u8, n: u32) callconv(.c) void {
- const st: *State = @ptrCast(@alignCast(ctx orelse return));
- if (n < 8) return;
- const w = std.mem.readInt(u32, out[0..4], .little);
- const h = std.mem.readInt(u32, out[4..8], .little);
- if (@as(u64, w) * h * 4 != n - 8) return;
- const rgba = alloc(u8, n - 8) orelse return;
- @memcpy(rgba, out[8..n]);
- st.rgba = rgba;
- st.w = w;
- st.h = h;
-}
-
-fn dump(ctx: ?*anyopaque, buf: [*c]u8, n: u32) callconv(.c) u32 {
- const st: *const State = @ptrCast(@alignCast(ctx orelse return 0));
- if (st.raw.len <= n) @memcpy(buf[0..st.raw.len], st.raw);
- return @intCast(st.raw.len);
-}
-
-fn load(ctx: ?*anyopaque, buf: [*c]const u8, n: u32, _: u32) callconv(.c) c_int {
- const st: *State = @ptrCast(@alignCast(ctx orelse return 1));
- keep(st, buf[0..n]);
- return 0;
-}
diff --git a/src/keys.zig b/src/keys.zig
index 06566714..ee14a48a 100644
--- a/src/keys.zig
+++ b/src/keys.zig
@@ -14,7 +14,6 @@ const layout = @import("layout.zig");
const tagline = @import("tagline.zig");
const mouse = @import("mouse.zig");
const builtins = @import("builtins.zig");
-const image = @import("image.zig");
const ctlfs = @import("ninep/tree.zig");
const Macro = @import("Macro.zig");
const Pipe = @import("Pipe.zig");
diff --git a/src/look.zig b/src/look.zig
index b2fb5ae9..42ed0fb1 100644
--- a/src/look.zig
+++ b/src/look.zig
@@ -371,8 +371,7 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu
.at = pl.at,
.kind = .pdf,
} };
- var compiled_in: Kind.Registry = if (p == null) .init() else .{};
- if ((if (p) |pp| &pp.kinds else &compiled_in).forPath(found.path)) |k| return .{ .kind = .{ .path = found.path, .kind = k } };
+ if (p) |pp| if (pp.kinds.forPath(found.path)) |k| return .{ .kind = .{ .path = found.path, .kind = k } };
return .{ .file = .{ .path = found.path, .at = pl.at } };
}
diff --git a/src/macos.zig b/src/macos.zig
index 3ba5f52a..685e9d2f 100644
--- a/src/macos.zig
+++ b/src/macos.zig
@@ -14,7 +14,6 @@ const message = pardes.Messages.Message;
const layout = @import("layout.zig");
const animation = @import("animation.zig");
const file_watch = @import("file_watch.zig");
-const image = if (pardes.pdf_enabled) @import("image.zig") else struct {};
const host_io = @import("host_io.zig");
const fonts = @import("fonts.zig"); // the shared fallback preference order
const tracy = @import("tracy.zig"); // no-op unless -Dtracy names a checkout
@@ -511,10 +510,14 @@ fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void {
if (found.dir) |d| crash.setDir(d);
}
- pardes.image.start(io, allocs.image);
- errdefer pardes.image.stop();
- if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
- errdefer if (comptime pardes.pdf_enabled) pardes.pdf.stop();
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.pdf.start(allocs.pdf);
+ }
+ errdefer if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.stop();
+ pardes.pdf.stop();
+ };
pardes.syntax.start(allocs.tree_sitter);
errdefer pardes.syntax.stop();
@@ -604,8 +607,10 @@ export fn pardes_deinit() void {
if (st.changed_cells.len > 0) st.gpa.free(st.changed_cells);
if (st.images.len > 0) st.gpa.free(st.images);
st.core.deinit();
- pardes.image.stop();
- if (comptime pardes.pdf_enabled) pardes.pdf.stop();
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.stop();
+ pardes.pdf.stop();
+ }
pardes.syntax.stop();
st.config_arena.deinit();
st.prompt_rcs.deinit();
diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig
index 9b87d9aa..42d9f3bd 100644
--- a/src/ninep/ctl.zig
+++ b/src/ninep/ctl.zig
@@ -1539,7 +1539,7 @@ test "an address looked at in an image pane names the image, never an empty subj
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
const id = p.freeSlot().?;
- const doc = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/pardes-pic.ppm", null);
+ const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
_ = wr(p, Node.of(doc.serial, .look), ":/x/\n");
try testing.expect(th.logHas(p, "look: /tmp/pardes-pic.ppm is no text to address"));
}
@@ -1548,7 +1548,7 @@ test "Save and Save path on an image pane are refused with why, never a silent s
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
const id = p.freeSlot().?;
- const doc = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/pardes-pic.ppm", null);
+ const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
for ([_][]const u8{ "Save\n", "Save /tmp/pardes-copy.ppm\n" }) |line| {
const r = wr(p, Node.of(doc.serial, .ctl), line);
try testing.expectEqual(Status.err, r.reply.status);
@@ -1579,9 +1579,7 @@ test "a builtin for one kind of pane is refused on another, and still acts on it
};
const id = p.freeSlot().?;
// A picture shown: the core's art words follow the kind's prefix.
- pardes.image.start(testing.io, testing.allocator);
- defer pardes.image.stop();
- const doc = try pardes.Kind.open(p, id, pardes.Kind.image, "/tmp/pardes-pic.ppm", "P6\n1 1\n255\n\x01\x02\x03");
+ const doc = try pardes.Kind.open(p, id, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", "P6\n1 1\n255\n\x01\x02\x03");
while (p.nextEffect()) |e| p.perform(e);
pardes.exec.placeNew(p, 0, 0, id, .doc);
_ = try p.render(p.scratch.allocator());
@@ -2158,32 +2156,10 @@ test "a language server question that finds nothing, cannot be answered, or is a
try testing.expectEqual(@as(u16, 0), p.fs.late_failure_len);
// An image's body takes no write.
const slot = p.freeSlot().?;
- const img = try pardes.Kind.open(p, slot, pardes.Kind.image, "/tmp/pardes-no-such.png", "not a png");
+ const img = try pardes.Kind.open(p, slot, pardes.Kind.test_kind.of(p), "/tmp/pardes-no-such.png", "not a png");
try testing.expectEqual(E.INVAL, wr(p, Node.of(img.serial, .body), "text\n").errno());
}
-test "a corrupt image fails its look with an err, and no pane is made" {
- pardes.image.start(testing.io, testing.allocator);
- defer pardes.image.stop();
- const p = try withFile(testing.allocator, "x\n");
- defer p.deinit();
- var tmp = testing.tmpDir(.{});
- defer tmp.cleanup();
- try tmp.dir.writeFile(testing.io, .{ .sub_path = "bad.png", .data = "\x89PNG not really" });
- var dir_buf: [4096]u8 = undefined;
- const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)];
- var line: [4200]u8 = undefined;
- var count: usize = 0;
- for (p.panes) |slot| count += @intFromBool(slot != null);
- const r = wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/bad.png\n", .{dir}));
- try testing.expectEqual(E.IO, r.errno());
- try testing.expect(std.mem.endsWith(u8, r.reply.ename, "bad.png: not an image pardes can read"));
- p.sync();
- var after: usize = 0;
- for (p.panes) |slot| after += @intFromBool(slot != null);
- try testing.expectEqual(count, after);
-}
-
test "a truncated PDF fails its look with its path and why" {
if (comptime !pardes.pdf_enabled) return;
const p = try withFile(testing.allocator, "x\n");
@@ -2800,7 +2776,7 @@ test "a Save whose directory is missing because one above refuses says permissio
test "a body write to an image pane says its body takes none, not that terminals have no text" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
- const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.image, "/tmp/pardes-pic.ppm", null);
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
try testing.expectEqualStrings(pane_files.e_no_body, wr(p, Node.of(doc.serial, .body), "x").reply.ename);
}
@@ -2830,7 +2806,7 @@ test "a Rename that reaches other files previews them, says so, and is the pane
test "Edit on an image pane is refused as a data write there is, EINVAL, before it runs" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
- const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.image, "/tmp/pardes-pic.ppm", null);
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
const edit = wr(p, Node.of(doc.serial, .ctl), "Edit ,d\n");
const data = wr(p, Node.of(doc.serial, .data), "x");
try testing.expectEqual(E.INVAL, edit.errno());
@@ -2841,7 +2817,7 @@ test "Edit on an image pane is refused as a data write there is, EINVAL, before
test "Petscii, Palette and Ascii take the state their tag word names, set rather than flipped" {
const p = try withFile(testing.allocator, "x\n");
defer p.deinit();
- const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.image, "/tmp/pardes-pic.ppm", null);
+ const doc = try pardes.Kind.open(p, p.freeSlot().?, pardes.Kind.test_kind.of(p), "/tmp/pardes-pic.ppm", null);
const ctl_node = Node.of(doc.serial, .ctl);
for ([_][]const u8{ "Petscii on\n", "Petscii on\n" }) |line| {
try testing.expectEqual(Status.ok, wr(p, ctl_node, line).reply.status);
@@ -2851,7 +2827,7 @@ test "Petscii, Palette and Ascii take the state their tag word names, set rather
try testing.expect(!doc.addon.?.art.glyph);
_ = wr(p, ctl_node, "Palette terminal\n");
_ = wr(p, ctl_node, "Palette terminal\n");
- try testing.expectEqual(pardes.panes.Image.PaletteMode.terminal, doc.addon.?.art.palette);
+ try testing.expectEqual(pardes.Placement.Art.Palette.terminal, doc.addon.?.art.palette);
_ = wr(p, ctl_node, "Ascii off\n");
_ = wr(p, ctl_node, "Ascii off\n");
try testing.expect(!doc.addon.?.art.ascii);
diff --git a/src/panes.zig b/src/panes.zig
index e4872468..cfe09f33 100644
--- a/src/panes.zig
+++ b/src/panes.zig
@@ -723,8 +723,6 @@ pub const Dir = @import("Dir.zig");
pub const mini = @import("mini.zig");
-pub const Image = @import("image.zig");
-
pub const Pdf = @import("pdf_view.zig");
pub const terminal = @import("terminal.zig");
@@ -736,7 +734,6 @@ test {
_ = Output;
_ = Dir;
_ = mini;
- _ = Image;
_ = @import("Kind.zig");
_ = Pdf;
_ = terminal;
diff --git a/src/pardes.zig b/src/pardes.zig
index 35cccf26..58f8fa17 100644
--- a/src/pardes.zig
+++ b/src/pardes.zig
@@ -42,6 +42,8 @@ pub const Cell = @import("surface.zig").Cell;
pub const Placement = @import("surface.zig").Placement;
pub const Raster = @import("surface.zig").Raster;
pub const RectPx = @import("surface.zig").RectPx;
+pub const NativeGeometry = @import("surface.zig").NativeGeometry;
+pub const containGeometry = @import("surface.zig").containGeometry;
pub const RectCell = @import("surface.zig").RectCell;
pub const Surface = @import("surface.zig").Surface;
pub const Region = @import("surface.zig").Region;
@@ -77,8 +79,9 @@ pub const views = @import("views.zig");
pub const rollback = @import("rollback.zig");
pub const replica = @import("replica.zig");
pub const echo = @import("echo.zig");
-pub const image = @import("image.zig");
pub const Kind = @import("Kind.zig");
+/// A terminal's kitty pictures; its PNG resize is started with the shell.
+pub const TerminalImages = panes.terminal.TerminalImages;
pub const Addon = @import("Addon.zig");
pub const dump = @import("dump.zig");
pub const lsp = @import("lsp/lsp.zig");
diff --git a/src/pdf_view.zig b/src/pdf_view.zig
index 8edb4902..93390b57 100644
--- a/src/pdf_view.zig
+++ b/src/pdf_view.zig
@@ -9,7 +9,7 @@ const config = @import("config.zig");
const modal = @import("modal.zig");
const filesystem = @import("fs.zig");
const tracy = @import("tracy.zig");
-const image = @import("image.zig");
+const surface = @import("surface.zig");
const look = @import("look.zig");
const tagline = @import("tagline.zig");
const File = panes.File;
@@ -1147,8 +1147,163 @@ pub const PanResult = enum { moved, edge, unavailable };
pub const ScrollResult = struct { active_page: usize };
pub const CellPixels = struct { w: u16, h: u16 };
+/// How a native pixel attachment is placed in its pane body. `contain` is the
+/// historical image-pane policy: shrink only when necessary and keep the
+/// image at the top left. The axis-specific modes may enlarge, letterbox the
+/// unconstrained axis, or crop it when it overflows.
+pub const NativeFit = if (enabled) enum { contain, width, height } else enum { contain };
+
+fn panOffset(overflow: u32, pan: u16) u32 {
+ if (overflow == 0 or pan == 0) return 0;
+ if (pan == std.math.maxInt(u16)) return overflow;
+ // Round, rather than truncate, so the midpoint is the visual midpoint.
+ return @intCast((@as(u64, overflow) * pan + std.math.maxInt(u16) / 2) / std.math.maxInt(u16));
+}
+
+fn fitWidth(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_y: u16) ?surface.NativeGeometry {
+ const scaled_h = @as(u64, src_h) * body_w;
+ if (scaled_h <= @as(u64, body_h) * src_w) {
+ const full_h: u32 = @intCast(@max(1, scaled_h / src_w));
+ return .{
+ .src = .{ .w = src_w, .h = src_h },
+ .dst = .{ .y = (body_h - full_h) / 2, .w = body_w, .h = full_h },
+ };
+ }
+
+ // Retain the largest whole source-pixel crop which cannot extend beyond
+ // the body at this scale. The sub-pixel remainder becomes at most a small
+ // centered letterbox instead of leaking into an adjacent cell in Kitty.
+ const crop_h_wide = @as(u64, body_h) * src_w / body_w;
+ if (crop_h_wide == 0) return null;
+ const crop_h: u32 = @min(src_h, @as(u32, @intCast(crop_h_wide)));
+ const dst_h: u32 = @min(body_h, @max(1, @as(u32, @intCast(@as(u64, crop_h) * body_w / src_w))));
+ return .{
+ .src = .{
+ .y = panOffset(src_h - crop_h, pan_y),
+ .w = src_w,
+ .h = crop_h,
+ },
+ .dst = .{ .y = (body_h - dst_h) / 2, .w = body_w, .h = dst_h },
+ };
+}
+
+fn fitHeight(src_w: u32, src_h: u32, body_w: u32, body_h: u32, pan_x: u16) ?surface.NativeGeometry {
+ const scaled_w = @as(u64, src_w) * body_h;
+ if (scaled_w <= @as(u64, body_w) * src_h) {
+ const full_w: u32 = @intCast(@max(1, scaled_w / src_h));
+ return .{
+ .src = .{ .w = src_w, .h = src_h },
+ .dst = .{ .x = (body_w - full_w) / 2, .w = full_w, .h = body_h },
+ };
+ }
+
+ const crop_w_wide = @as(u64, body_w) * src_h / body_h;
+ if (crop_w_wide == 0) return null;
+ const crop_w: u32 = @min(src_w, @as(u32, @intCast(crop_w_wide)));
+ const dst_w: u32 = @min(body_w, @max(1, @as(u32, @intCast(@as(u64, crop_w) * body_h / src_h))));
+ return .{
+ .src = .{
+ .x = panOffset(src_w - crop_w, pan_x),
+ .w = crop_w,
+ .h = src_h,
+ },
+ .dst = .{ .x = (body_w - dst_w) / 2, .w = dst_w, .h = body_h },
+ };
+}
+
+/// Compute native image placement without floating point. Source dimensions
+/// are limited to u32 because SDL's texture API and Kitty's crop parameters
+/// cannot describe anything larger. Kitty applies the stricter u16 check at
+/// its protocol boundary.
+pub fn nativeGeometry(
+ iw: usize,
+ ih: usize,
+ body_pixel_w: u32,
+ body_pixel_h: u32,
+ fit: NativeFit,
+ pan_x: u16,
+ pan_y: u16,
+) ?surface.NativeGeometry {
+ if (comptime !enabled) {
+ return surface.containGeometry(iw, ih, body_pixel_w, body_pixel_h);
+ }
+ if (iw == 0 or ih == 0 or body_pixel_w == 0 or body_pixel_h == 0 or
+ iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null;
+
+ const src_w: u32 = @intCast(iw);
+ const src_h: u32 = @intCast(ih);
+ return switch (fit) {
+ .width => fitWidth(src_w, src_h, body_pixel_w, body_pixel_h, pan_y),
+ .height => fitHeight(src_w, src_h, body_pixel_w, body_pixel_h, pan_x),
+ // Pan is not contain's: it keeps the top-left placement.
+ .contain => surface.containGeometry(iw, ih, body_pixel_w, body_pixel_h),
+ };
+}
+
+test "native fit width handles portrait crop, pan extrema, and landscape letterbox" {
+ if (comptime !enabled) return;
+ const top = nativeGeometry(600, 1000, 800, 600, .width, 0, 0).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = 600, .h = 450 }, top.src);
+ try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, top.dst);
+
+ const middle = nativeGeometry(600, 1000, 800, 600, .width, 0, 32768).?;
+ try std.testing.expectEqual(@as(u32, 275), middle.src.y);
+ const bottom = nativeGeometry(600, 1000, 800, 600, .width, 65535, 65535).?;
+ try std.testing.expectEqual(@as(u32, 550), bottom.src.y);
+
+ const landscape = nativeGeometry(1000, 600, 800, 600, .width, 0, 65535).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = 1000, .h = 600 }, landscape.src);
+ try std.testing.expectEqual(surface.RectPx{ .y = 60, .w = 800, .h = 480 }, landscape.dst);
+}
+
+test "native fit height handles portrait letterbox and landscape crop" {
+ if (comptime !enabled) return;
+ const portrait = nativeGeometry(600, 1000, 800, 600, .height, 65535, 0).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = 600, .h = 1000 }, portrait.src);
+ try std.testing.expectEqual(surface.RectPx{ .x = 220, .w = 360, .h = 600 }, portrait.dst);
+
+ const left = nativeGeometry(1000, 600, 800, 600, .height, 0, 0).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, left.src);
+ try std.testing.expectEqual(surface.RectPx{ .w = 800, .h = 600 }, left.dst);
+ const right = nativeGeometry(1000, 600, 800, 600, .height, 65535, 0).?;
+ try std.testing.expectEqual(@as(u32, 200), right.src.x);
+}
+
+test "native fit odd ratios round inward and map points through letterboxes and crops" {
+ if (comptime !enabled) return;
+ const width = nativeGeometry(403, 211, 101, 47, .width, 0, 32768).?;
+ try std.testing.expectEqual(surface.RectPx{ .y = 12, .w = 403, .h = 187 }, width.src);
+ try std.testing.expectEqual(surface.RectPx{ .w = 101, .h = 46 }, width.dst);
+ const mapped = width.sourcePoint(100, 45).?;
+ try std.testing.expect(mapped.x < width.src.x + width.src.w);
+ try std.testing.expect(mapped.y < width.src.y + width.src.h);
+ try std.testing.expect(width.sourcePoint(101, 46) == null);
+
+ const height = nativeGeometry(403, 211, 101, 47, .height, 32768, 0).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = 403, .h = 211 }, height.src);
+ try std.testing.expectEqual(surface.RectPx{ .x = 6, .w = 89, .h = 47 }, height.dst);
+ try std.testing.expect(height.sourcePoint(5, 20) == null);
+ try std.testing.expect(height.sourcePoint(6, 20) != null);
+}
+
+test "native fit modes reject what the backend contract cannot represent and are total at extreme aspect ratios" {
+ if (comptime !enabled) return;
+ try std.testing.expect(nativeGeometry(10, 10, 0, 20, .width, 0, 0) == null);
+ if (@bitSizeOf(usize) > 32)
+ try std.testing.expect(nativeGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20, .height, 0, 0) == null);
+
+ const largest = std.math.maxInt(u32);
+ try std.testing.expect(nativeGeometry(1, largest, largest, 1, .width, 0, 65535) == null);
+ try std.testing.expect(nativeGeometry(largest, 1, 1, largest, .height, 65535, 0) == null);
+
+ const wide = nativeGeometry(largest, 1, largest, 1, .width, 0, 0).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = largest, .h = 1 }, wide.dst);
+ const tall = nativeGeometry(1, largest, 1, largest, .height, 0, 0).?;
+ try std.testing.expectEqual(surface.RectPx{ .w = 1, .h = largest }, tall.dst);
+}
+
const PlacedGeometry = struct {
- geometry: image.NativeGeometry,
+ geometry: surface.NativeGeometry,
pixel_offset_y: f32,
};
@@ -1157,7 +1312,7 @@ pub const PlacedRaster = if (enabled) struct {
revision: u32,
fit: FitMode,
pan_x: u16,
- geometry: image.NativeGeometry,
+ geometry: surface.NativeGeometry,
pixel_offset_y: f32,
rgba: []const u8,
width: usize,
@@ -1165,7 +1320,7 @@ pub const PlacedRaster = if (enabled) struct {
} else void;
const VisibleRows = struct {
- base: image.NativeGeometry,
+ base: surface.NativeGeometry,
y0: u32,
y1: u32,
dst_y: u32,
@@ -1269,7 +1424,7 @@ fn visibleRows(
) ?VisibleRows {
if (comptime !enabled) return null;
const page_h = state.page_heights[page];
- const base = image.nativeGeometry(
+ const base = nativeGeometry(
iw,
ih,
viewport.pixel_w,
@@ -1367,7 +1522,7 @@ pub fn placedRaster(state: *const State, viewport: Viewport, page: usize) ?Place
};
}
-pub fn activeGeometry(state: *const State, viewport: Viewport) ?image.NativeGeometry {
+pub fn activeGeometry(state: *const State, viewport: Viewport) ?surface.NativeGeometry {
if (comptime !enabled) return null;
const raster = rasterForPageConst(state, state.page) orelse return null;
const placed = placedGeometry(state, raster, viewport, state.page) orelse return null;
@@ -2131,7 +2286,7 @@ pub fn scrollDocument(state: *State, viewport: Viewport, delta_pixels: f64) ?Scr
pub fn panPixels(
state: *State,
- geometry: image.NativeGeometry,
+ geometry: surface.NativeGeometry,
axis: PanAxis,
direction: i8,
display_pixels: u32,
@@ -2185,7 +2340,7 @@ pub fn panPixels(
return .moved;
}
-fn setHorizontalEdge(state: *State, geometry: image.NativeGeometry, end: bool) void {
+fn setHorizontalEdge(state: *State, geometry: surface.NativeGeometry, end: bool) void {
if (comptime !enabled) return;
const raster = rasterForPage(state, state.page) orelse return;
if (raster.iw <= geometry.src.w) return;
@@ -2205,7 +2360,7 @@ fn rearmSearchReveal(state: *State, viewport: Viewport) void {
pub fn revealSearch(
state: *State,
viewport: Viewport,
- geometry: ?image.NativeGeometry,
+ geometry: ?surface.NativeGeometry,
) void {
if (comptime !enabled) return;
if (!state.search_reveal_pending) return;
@@ -2529,7 +2684,7 @@ pub fn probeWord(
}
pub fn pointAtGeometry(
- geometry: image.NativeGeometry,
+ geometry: surface.NativeGeometry,
pixel_offset_y: f32,
full_width: usize,
full_height: usize,
@@ -2958,7 +3113,7 @@ pub fn tintColors(core: *const pardes.Pardes) TintColors {
};
}
-pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?image.NativeGeometry {
+pub fn paneGeometry(core: *const pardes.Pardes, pane: *const pardes.Pane) ?surface.NativeGeometry {
if (comptime !enabled) return null;
const state = if (pane.pdf) |view| view else return null;
const view = paneViewport(core, pane) orelse return null;
diff --git a/src/surface.zig b/src/surface.zig
index df9abac1..c058e101 100644
--- a/src/surface.zig
+++ b/src/surface.zig
@@ -7,7 +7,6 @@ const uucode = @import("uucode");
const vaxis = @import("vaxis");
const panes = @import("panes.zig");
const config = @import("config.zig");
-const image = @import("image.zig");
const MAX_PANES = pardes.MAX_PANES;
const Layer = @import("Layer.zig");
const MAX_TAG_LAYERS = pardes.MAX_TAG_LAYERS;
@@ -71,7 +70,77 @@ test "cell visual equality ignores dead grapheme tail bytes" {
}
/// A rectangle in pixels.
-pub const RectPx = image.PixelRect;
+pub const RectPx = struct {
+ x: u32 = 0,
+ y: u32 = 0,
+ w: u32 = 0,
+ h: u32 = 0,
+};
+
+pub const PixelPoint = struct { x: u32, y: u32 };
+
+/// Source pixels and their destination inside a pane body's pixel rectangle.
+/// Both rectangles are half-open. Rounding is always toward the inside, so a
+/// backend can draw this result without a backend-specific overflow clip.
+pub const NativeGeometry = struct {
+ src: RectPx,
+ dst: RectPx,
+
+ /// Map a destination pixel back into the retained source crop. This is the
+ /// same integer transform the texture rectangle describes; points in a
+ /// letterbox return null.
+ pub fn sourcePoint(self: NativeGeometry, x: u32, y: u32) ?PixelPoint {
+ if (self.src.w == 0 or self.src.h == 0 or self.dst.w == 0 or self.dst.h == 0) return null;
+ if (x < self.dst.x or y < self.dst.y) return null;
+ const dx = x - self.dst.x;
+ const dy = y - self.dst.y;
+ if (dx >= self.dst.w or dy >= self.dst.h) return null;
+ return .{
+ .x = self.src.x + @as(u32, @intCast(@as(u64, dx) * self.src.w / self.dst.w)),
+ .y = self.src.y + @as(u32, @intCast(@as(u64, dy) * self.src.h / self.dst.h)),
+ };
+ }
+};
+
+/// Where a fitted placement (`at` null) goes: shrunk only when it must be,
+/// at the top left. The scale ratios are compared without floating point:
+/// the tighter bound is exact, the other rounded inward.
+pub fn containGeometry(iw: usize, ih: usize, max_w: u32, max_h: u32) ?NativeGeometry {
+ if (iw == 0 or ih == 0 or max_w == 0 or max_h == 0 or
+ iw > std.math.maxInt(u32) or ih > std.math.maxInt(u32)) return null;
+
+ const src_w: u32 = @intCast(iw);
+ const src_h: u32 = @intCast(ih);
+ if (src_w <= max_w and src_h <= max_h) return .{
+ .src = .{ .w = src_w, .h = src_h },
+ .dst = .{ .w = src_w, .h = src_h },
+ };
+ const dst: RectPx = if (@as(u64, max_w) * src_h <= @as(u64, max_h) * src_w)
+ .{
+ .w = max_w,
+ .h = @intCast(@max(1, @as(u64, src_h) * max_w / src_w)),
+ }
+ else
+ .{
+ .w = @intCast(@max(1, @as(u64, src_w) * max_h / src_h)),
+ .h = max_h,
+ };
+ return .{ .src = .{ .w = src_w, .h = src_h }, .dst = dst };
+}
+
+test "native image contain keeps aspect, bounds, top-left, and small-image size" {
+ try std.testing.expectEqual(RectPx{ .w = 40, .h = 20 }, containGeometry(400, 200, 40, 40).?.dst);
+ try std.testing.expectEqual(RectPx{ .w = 20, .h = 40 }, containGeometry(200, 400, 40, 40).?.dst);
+ try std.testing.expectEqual(RectPx{ .w = 17, .h = 9 }, containGeometry(17, 9, 40, 40).?.dst);
+ try std.testing.expect(containGeometry(17, 9, 0, 40) == null);
+
+ const odd = containGeometry(403, 211, 101, 47).?;
+ try std.testing.expectEqual(RectPx{ .w = 89, .h = 47 }, odd.dst);
+ try std.testing.expectEqual(RectPx{ .w = 403, .h = 211 }, odd.src);
+ // Nothing its backend contract cannot represent.
+ try std.testing.expect(containGeometry(0, 10, 20, 20) == null);
+ if (@bitSizeOf(usize) > 32) try std.testing.expect(containGeometry(@as(usize, std.math.maxInt(u32)) + 1, 10, 20, 20) == null);
+}
/// A rectangle in the frame's cells.
pub const RectCell = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 };
diff --git a/src/tape.zig b/src/tape.zig
index d3e5558a..cd777f96 100644
--- a/src/tape.zig
+++ b/src/tape.zig
@@ -1242,8 +1242,10 @@ pub fn startFromEnv() void {
pub fn replayMain(io: std.Io, path: []const u8) u8 {
const gpa = std.heap.c_allocator;
// What a shell starts before its core (tui.zig's localSession).
- pardes.image.start(io, gpa);
- if (comptime pardes.pdf_enabled) pardes.pdf.start(gpa);
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.start(io, gpa);
+ pardes.pdf.start(gpa);
+ }
pardes.syntax.start(gpa);
const bytes = std.Io.Dir.cwd().readFileAlloc(std.Io.Threaded.global_single_threaded.io(), path, gpa, .unlimited) catch |err| {
std.debug.print("replay: cannot read {s}: {t}\n", .{ path, err });
diff --git a/src/tui/tui.zig b/src/tui/tui.zig
index 0c74cbaa..fd47cb67 100644
--- a/src/tui/tui.zig
+++ b/src/tui/tui.zig
@@ -766,7 +766,7 @@ fn exactKittyPlacement(
screen_pixel_w: u16,
screen_pixel_h: u16,
) ?KittyPlacement {
- const g: pardes.image.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null };
+ const g: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null };
const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8);
const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16);
if (g.dst.w == 0 or g.dst.h == 0 or g.src.w == 0 or g.src.h == 0) return null;
@@ -823,7 +823,7 @@ fn kittyPlacement(
) ?KittyPlacement {
const cell_w = terminalCellPixels(screen_pixel_w, screen_cols, 8);
const cell_h = terminalCellPixels(screen_pixel_h, screen_rows, 16);
- const geometry: pardes.image.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null };
+ const geometry: pardes.NativeGeometry = .{ .src = place.src, .dst = place.at orelse return null };
const fit: enum { width, height } = if (geometry.dst.w >= @as(u32, place.dst.w) * cell_w) .width else .height;
const safe_rows_u32 = geometry.dst.h / cell_h;
@@ -1221,12 +1221,16 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se
const have: ?*replica.Have = if (far) &have_store else null;
const allocs = pardes.memory.init(gpa);
defer pardes.memory.deinit();
- pardes.image.start(io, allocs.image);
- if (comptime pardes.pdf_enabled) pardes.pdf.start(allocs.pdf);
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.start(io, allocs.image);
+ pardes.pdf.start(allocs.pdf);
+ }
pardes.syntax.start(allocs.tree_sitter);
defer {
- pardes.image.stop();
- if (comptime pardes.pdf_enabled) pardes.pdf.stop();
+ if (comptime pardes.pdf_enabled) {
+ pardes.TerminalImages.stop();
+ pardes.pdf.stop();
+ }
pardes.syntax.stop();
}
var o = opts;