diff options
Diffstat (limited to 'src/image.zig')
| -rw-r--r-- | src/image.zig | 453 |
1 files changed, 443 insertions, 10 deletions
diff --git a/src/image.zig b/src/image.zig index 592230c8..e334965a 100644 --- a/src/image.zig +++ b/src/image.zig @@ -1,5 +1,6 @@ //! Image decoding, pixel placement, and glyph approximation. const std = @import("std"); +const builtin = @import("builtin"); const zstbi = @import("zstbi"); /// The 16-colour ANSI table below is the only thing this file ever wanted from /// the emulator, and a build without one still renders images — see @@ -7,6 +8,10 @@ const zstbi = @import("zstbi"); const terminal_panes = @import("pardes.zig").terminal_panes; const ghostty_vt = if (terminal_panes) @import("ghostty-vt") else struct {}; const pdf_enabled = @import("pardes_config").mupdf; +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const dump = @import("dump.zig"); // Glyph matching adapted from caioluders/petsciinator. pub const GlyphArt = struct { pub const commodore = [16][3]u8{ @@ -238,11 +243,11 @@ pub const GlyphArt = struct { const glyphs_ascii = glyphs ++ ascii_glyphs; fn matchCell(cell: *const [64][3]u8, pal: Palette, gset: []const Glyph) Cell { - var counts = [_]u16{0} ** 16; + var counts = @as([16]u16, @splat(0)); for (cell) |px| counts[nearest(px, pal)] += 1; var cand: [4]u4 = undefined; var ncand: usize = 0; - var used = [_]bool{false} ** 16; + var used = @as([16]bool, @splat(false)); while (ncand < 4) : (ncand += 1) { var best: ?usize = null; for (counts, 0..) |c, i| { @@ -301,7 +306,6 @@ pub const GlyphArt = struct { pub fn render(gpa: std.mem.Allocator, rgba: []const u8, iw: usize, ih: usize, max_cols: usize, max_rows: usize, pal: Palette, ascii: bool) !Grid { if (iw == 0 or ih == 0 or max_cols == 0 or max_rows == 0) return .{ .cells = try gpa.alloc(Cell, 0), .cols = 0, .rows = 0 }; - const gset: []const Glyph = if (ascii) &glyphs_ascii else &glyphs; // contain-fit; cells are ~twice as tall as wide, so a row spans 2 width-units. var cols = max_cols; var rows = (max_cols * ih) / (2 * iw); @@ -311,16 +315,28 @@ pub const GlyphArt = struct { } cols = std.math.clamp(cols, 1, max_cols); rows = std.math.clamp(rows, 1, max_rows); + return renderRect(gpa, rgba, iw, ih, .{ .w = @intCast(iw), .h = @intCast(ih) }, cols, rows, pal, ascii); + } + /// The pixels of `src` (a rectangle of the `iw` x `ih` image) laid + /// over exactly `cols` x `rows` cells, whatever their shape: a + /// terminal's image fragment is already the size its cells are. + pub fn renderRect(gpa: std.mem.Allocator, rgba: []const u8, iw: usize, ih: usize, src: PixelRect, cols: usize, rows: usize, pal: Palette, ascii: bool) !Grid { + const x0: usize = @min(src.x, iw); + const y0: usize = @min(src.y, ih); + const sw: usize = @min(src.w, iw - x0); + const sh: usize = @min(src.h, ih - y0); + if (sw == 0 or sh == 0 or cols == 0 or rows == 0) return .{ .cells = try gpa.alloc(Cell, 0), .cols = 0, .rows = 0 }; + const gset: []const Glyph = if (ascii) &glyphs_ascii else &glyphs; const cells = try gpa.alloc(Cell, cols * rows); var cy: usize = 0; while (cy < rows) : (cy += 1) { - const ry0 = cy * ih / rows; - const ry1 = @max(ry0 + 1, (cy + 1) * ih / rows); + const ry0 = y0 + cy * sh / rows; + const ry1 = @max(ry0 + 1, y0 + (cy + 1) * sh / rows); var cx: usize = 0; while (cx < cols) : (cx += 1) { - const rx0 = cx * iw / cols; - const rx1 = @max(rx0 + 1, (cx + 1) * iw / cols); + const rx0 = x0 + cx * sw / cols; + const rx1 = @max(rx0 + 1, x0 + (cx + 1) * sw / cols); var cell: [64][3]u8 = undefined; var sy: usize = 0; while (sy < 8) : (sy += 1) { @@ -417,7 +433,7 @@ pub const GlyphArt = struct { test "render: tiny image produces a grid within bounds" { const a = std.testing.allocator; // 2x2 checker, RGBA - var img = [_]u8{0} ** (2 * 2 * 4); + var img = @as([2 * 2 * 4]u8, @splat(0)); img[0] = 255; img[1] = 255; img[2] = 255; @@ -728,17 +744,131 @@ test "native geometry is total at extreme accepted aspect ratios" { /// 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); + started = true; } pub fn stop() void { + started = false; zstbi.deinit(); } +/// 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; + +/// 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 (stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &iw, &ih, &ic) != 1) 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 stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &w, &h, &c) == 1; +} + /// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the /// pane then simply shows a blank body. -pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w: usize, h: usize } { - if (bytes.len == 0) return null; +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); @@ -751,3 +881,306 @@ pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w 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 pane ---- + +const GridKey = struct { + cols: u16 = 0, + rows: u16 = 0, + palette: PaletteMode = .commodore, + ascii: bool = true, +}; + +pub const State = struct { + path: []u8, + glyph_art: bool = false, + pmode: PaletteMode = .commodore, + ascii: bool = true, + tried: bool = false, + rgba: []u8 = &.{}, + iw: usize = 0, + ih: usize = 0, + /// Dump-loaded bytes, decoded lazily by the same path as a disk image. + raw: []u8 = &.{}, + grid: GlyphArt.Grid = .{ .cells = &.{}, .cols = 0, .rows = 0 }, + grid_key: GridKey = .{}, + /// The decode under way off the loop (ensureDecoded), and its answer. + decoder: ?std.Thread = null, + decoded: std.atomic.Value(bool) = .init(false), + answer: ?Decoded = null, + + pub fn deinit(state: *State, gpa: std.mem.Allocator) void { + if (state.decoder) |t| t.join(); + if (state.answer) |a| gpa.free(a.rgba); + gpa.free(state.path); + if (state.rgba.len > 0) gpa.free(state.rgba); + if (state.raw.len > 0) gpa.free(state.raw); + if (state.grid.cells.len > 0) gpa.free(state.grid.cells); + state.* = undefined; + } +}; + +/// Construct an image pane from a path and optionally transferred dump bytes. +/// `raw` must be image_gpa-owned and ownership transfers only on success. +/// Without them the file is read here, not at the first draw: a draw +/// must not go out into the host (`pardes.turn`), and the path may be a +/// mount this editor serves. A file that cannot be read draws blank. +pub fn create(p: *pardes.Pardes, id: usize, path: []const u8, raw: []u8) !*pardes.Pane { + var bytes = raw; + var read_here = false; + if (bytes.len == 0) { + // The slot stays ours across the read: another request may + // make a pane meanwhile. + p.reserved_slots[id] = true; + defer p.reserved_slots[id] = false; + if (filesystem.read(p, path)) |from_disk| { + defer p.gpa.free(from_disk); + bytes = try p.image_gpa.dupe(u8, from_disk); + read_here = true; + } else |_| {} + } + errdefer if (read_here) p.image_gpa.free(bytes); + const path_copy = try p.image_gpa.dupe(u8, path); + errdefer p.image_gpa.free(path_copy); + const pane = try p.newDocPane(id); + pane.image = .{ .path = path_copy, .raw = bytes }; + return pane; +} + +/// Serialize the binary image record used by images and, for dump-schema +/// compatibility, PDFs. Common pane metadata is supplied by the core. +pub fn dumpPane( + p: *pardes.Pardes, + arena: std.mem.Allocator, + pane: *const pardes.Pane, + tag: []const u8, + body: []const u8, + scroll: usize, + path: []const u8, + raw: []const u8, +) !dump.Pane { + // A picture or PDF on disk is read from there at Restore, as a clean + // file's text is: the dump keeps only the bytes of one that is not + // (megabytes of a PDF per dump, and a stale copy, otherwise). + _ = p; + const on_disk = if (comptime !pardes.hosted) false else if (filesystem.localPath(path)) |local| @import("exec.zig").kindOf(local) == .file else false; + const bytes: []const u8 = if (on_disk) &.{} else raw; + return .{ + .kind = .image, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .image = .{ + .path = path, + .bytes_b64 = if (bytes.len > 0) try dump.encodeBytes(arena, bytes) else "", + .petscii = if (pane.image) |state| state.glyph_art else false, + .palette = if (pane.image) |state| switch (state.pmode) { + .commodore => .commodore, + .terminal => .terminal, + } else .commodore, + .ascii = if (pane.image) |state| state.ascii else true, + .pdf_fit = if (comptime pardes.pdf_enabled) (if (pane.pdf) |pv| @tagName(pv.fit) else "") else "", + .pdf_tint = if (comptime pardes.pdf_enabled) (if (pane.pdf) |pv| @tagName(pv.tint) else "") else "", + }, + }; +} + +pub fn restore(p: *pardes.Pardes, id: usize, src: dump.Pane) !*pardes.Pane { + const saved = src.image.?; + var raw: []u8 = if (saved.bytes_b64.len > 0) + try dump.decodeBytes(p.image_gpa, saved.bytes_b64) + else + &.{}; + errdefer if (raw.len > 0) p.image_gpa.free(raw); + const pane = try create(p, id, saved.path, raw); + raw = &.{}; + pane.image.?.glyph_art = saved.petscii; + pane.image.?.pmode = switch (saved.palette) { + .commodore => .commodore, + .terminal => .terminal, + }; + pane.image.?.ascii = saved.ascii; + pane.cols = @max(1, src.cols); + pane.rows = @max(1, src.rows); + return pane; +} + +pub fn toggleGlyphArt(state: *State) void { + state.glyph_art = !state.glyph_art; +} + +pub fn togglePalette(state: *State) void { + state.pmode = if (state.pmode == .commodore) .terminal else .commodore; +} + +pub fn toggleAscii(state: *State) void { + state.ascii = !state.ascii; +} + +/// Image renderer choices are pane-local, not global Config values. Keep them +/// queryable where they apply: the live tag beside the image's path. +/// `glyphs`: whether the picture is drawn as glyph art, which a terminal +/// with no graphics does whatever `glyph_art` says. +pub fn tagPrefix(arena: std.mem.Allocator, state: *const State, glyphs: bool) ![]u8 { + return std.fmt.allocPrint( + arena, + "{s} petscii:{s} palette:{s} ascii:{s} {s}", + .{ + config.tag_image, + if (glyphs) "on" else "off", + @tagName(state.pmode), + if (state.ascii) "on" else "off", + state.path, + }, + ); +} + +/// The picture decoded off the loop: the first draw starts a thread and +/// draws the pane without it (its tag and frame at once); the frames after +/// it look (Pardes.nextWake asks for them) and the picture lands on the +/// first one after the decode (80 ms in ReleaseSafe, 290 in Debug, for the +/// docs' screenshot: all of it once on the frame before). +/// ponytail: a thread a picture; a pool if many open at once. +fn ensureDecoded(p: *pardes.Pardes, state: *State) void { + if (state.decoder) |t| { + if (!state.decoded.load(.acquire)) return; + t.join(); + state.decoder = null; + } + if (state.answer) |decoded| { + state.answer = null; + state.rgba = decoded.rgba; + state.iw = decoded.w; + state.ih = decoded.h; + } + if (state.tried) return; + state.tried = true; + if (state.raw.len == 0) return; // nothing was readable at open + const Work = struct { + fn run(gpa: std.mem.Allocator, st: *State) void { + st.answer = decode(gpa, st.raw); + st.decoded.store(true, .release); + } + }; + if (comptime pardes.hosted and !builtin.is_test) { + if (std.Thread.spawn(.{}, Work.run, .{ p.image_gpa, state })) |t| { + state.decoder = t; + return; + } else |_| {} + } + Work.run(p.image_gpa, state); + ensureDecoded(p, state); +} + +fn ensureGrid(p: *pardes.Pardes, state: *State, cols: u16, rows: u16) void { + const wanted = GridKey{ .cols = cols, .rows = rows, .palette = state.pmode, .ascii = state.ascii }; + if (state.grid.cells.len > 0 and std.meta.eql(state.grid_key, wanted)) return; + if (state.grid.cells.len > 0) p.image_gpa.free(state.grid.cells); + const palette = switch (state.pmode) { + .commodore => GlyphArt.commodore, + .terminal => terminal_palette, + }; + state.grid = GlyphArt.render( + p.image_gpa, + state.rgba, + state.iw, + state.ih, + cols, + rows, + palette, + state.ascii, + ) catch .{ .cells = &.{}, .cols = 0, .rows = 0 }; + state.grid_key = wanted; +} + +pub fn draw( + p: *pardes.Pardes, + s: *pardes.Surface, + state: *State, + pane_id: u8, + serial: u32, + x: u16, + y: u16, + cols: u16, + rows: u16, +) void { + ensureDecoded(p, state); + if (state.rgba.len == 0 or cols == 0 or rows == 0) return; + if (!state.glyph_art and p.native_images) { + _ = p.appendImagePlace(.{ + .pane = pane_id, + .serial = serial, + .x = x, + .y = y, + .w = cols, + .h = rows, + .rgba = state.rgba, + .iw = state.iw, + .ih = state.ih, + }); + return; + } + + ensureGrid(p, state, cols, rows); + if (state.grid.cells.len == 0) return; + const offx = if (cols > state.grid.cols) (@as(usize, cols) - state.grid.cols) / 2 else 0; + const offy = if (rows > state.grid.rows) (@as(usize, rows) - state.grid.rows) / 2 else 0; + for (0..state.grid.rows) |cy| for (0..state.grid.cols) |cx| { + const cell = &state.grid.cells[cy * state.grid.cols + cx]; + const fg: pardes.Color = switch (state.pmode) { + .commodore => .{ .rgb = GlyphArt.commodore[cell.fg] }, + .terminal => .{ .index = cell.fg }, + }; + const bg: pardes.Color = switch (state.pmode) { + .commodore => .{ .rgb = GlyphArt.commodore[cell.bg] }, + .terminal => .{ .index = cell.bg }, + }; + const sx = x + @as(u16, @intCast(offx + cx)); + const sy = y + @as(u16, @intCast(offy + cy)); + if (sx < s.cols and sy < s.rows) + s.set(sx, sy, cell.glyph[0..cell.glyph_len], .{ .fg = fg, .bg = bg }); + }; +} |
