Something went wrong. Try again.
Sans-I/O image codecs for z2d surfaces: BMP, PNG, JPEG, GIF, TGA, XBM, XPM, Netpbm, PCX, ICO and WebP, with an optional sandbox for decoders
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! ICO and CUR: containers of alternatives rather than images.//!//! The fixtures are written by Pillow and ImageMagick, which between them//! cover both shapes an entry can hold and the depths that matter: an//! embedded PNG, a thirty-two bit DIB whose alpha the bitmap format says is//! unused, and a four-bit DIB where the AND mask is the only transparency//! there is. See `tools/gen_ico_fixtures.py`.
const std = @import("std");const Io = std.Io;const mem = std.mem;const testing = std.testing;const Allocator = mem.Allocator;
const z2d = @import("z2d");const z2dimg = @import("z2dimg");
const fixtures = @import("ico_fixtures.zig");const Rgba8 = z2dimg.pixels.Rgba8;
fn decodeBytes(gpa: Allocator, bytes: []const u8) !z2d.Surface { var r: Io.Reader = .fixed(bytes); return z2dimg.decode(gpa, &r, .{});}
fn at(sfc: z2d.Surface, x: i32, y: i32) Rgba8 { return Rgba8.fromZ2d(sfc.getPixel(x, y).?);}
fn expectPixels(sfc: z2d.Surface, expected: []const Rgba8, side: usize) !void { try testing.expectEqual(@as(i32, @intCast(side)), sfc.getWidth()); for (expected, 0..) |want, i| { const x: i32 = @intCast(i % side); const y: i32 = @intCast(i / side); const got = at(sfc, x, y); // A z2d surface stores premultiplied alpha, so the colour behind a // fully transparent pixel is multiplied by zero and cannot come back. // Pillow keeps it and this cannot, which is a property of the surface // rather than of the decoder --- so where the file says a pixel is // invisible, only that is compared. if (want.a == 0) { testing.expectEqual(@as(u8, 0), got.a) catch |err| { std.debug.print("at ({d},{d}): want transparent, got {any}\n", .{ x, y, got }); return err; }; continue; } expectClose(want, got) catch |err| { std.debug.print("at ({d},{d}): want {any}, got {any}\n", .{ x, y, want, got }); return err; }; }}
/// How far a channel may be off, given the alpha it was stored behind.////// A z2d surface is premultiplied: a colour goes in multiplied by its alpha/// and comes back divided by it, both as integers. At full opacity nothing is/// lost and the comparison is exact. Below it the round trip cannot resolve/// more than the alpha allows --- at a quarter opacity a channel is kept in a/// quarter of the range, so one step of what comes back is four of what went/// in.////// The bound is exactly the size of that step, `ceil(255 / alpha)`, which was/// not reasoned to but measured: every alpha, against every channel value,/// under every rounding convention either half of the conversion might use./// It is not a tolerance chosen to make a test pass --- at full opacity it/// permits nothing at all, and that is where the fixtures mostly sit.fn tolerance(alpha: u8) u8 { if (alpha == 0 or alpha == 255) return 0; return @intCast((255 + @as(u32, alpha) - 1) / @as(u32, alpha));}
fn expectClose(want: Rgba8, got: Rgba8) !void { // The alpha itself is stored as it arrived and is never approximate. try testing.expectEqual(want.a, got.a); const slack = tolerance(want.a); inline for (.{ "r", "g", "b" }) |field| { const a: i32 = @field(want, field); const b: i32 = @field(got, field); if (@abs(a - b) > slack) return error.TestExpectedEqual; }}
test "both shapes an entry can hold decode to what Pillow says is in them" { const gpa = testing.allocator; const cases = [_]struct { []const u8, []const Rgba8, []const u8 }{ .{ &fixtures.png_entry, &fixtures.png_entry_pixels, "an embedded PNG" }, .{ &fixtures.dib32, &fixtures.dib32_pixels, "a thirty-two bit DIB" }, .{ &fixtures.dib4, &fixtures.dib4_pixels, "a four-bit DIB and its mask" }, }; for (cases) |case| { const bytes, const want, const what = case; var sfc = decodeBytes(gpa, bytes) catch |err| { std.debug.print("{s}: {t}\n", .{ what, err }); return err; }; defer sfc.deinit(gpa); expectPixels(sfc, want, fixtures.side) catch |err| { std.debug.print("in the case of {s}\n", .{what}); return err; }; }}
test "a thirty-two bit icon keeps the alpha a bitmap would have thrown away" { // The trap this format sets. A thirty-two bit BMP with a forty-byte // header has no alpha: the format says those eight bits are unused, and // this library's bitmap decoder reads them that way, which is correct for // a BMP. An icon means them as alpha, and the convention was never // written into the bitmap one. // // So the entry's header is rewritten as the fifty-six byte version that // says what the icon means, and this is the assertion that it worked: the // soft edge survives, which a one-bit AND mask could not have carried. const gpa = testing.allocator; var sfc = try decodeBytes(gpa, &fixtures.dib32); defer sfc.deinit(gpa);
var partial: usize = 0; for (0..fixtures.side) |y| for (0..fixtures.side) |x| { const a = at(sfc, @intCast(x), @intCast(y)).a; if (a != 0 and a != 255) partial += 1; }; try testing.expect(partial > 0);}
test "the largest entry is the one that comes back" { // A directory is conventionally ordered smallest first, so a decoder that // took the first would hand back a sixteen by sixteen from a file that // also holds a thirty-two. const gpa = testing.allocator; var sfc = try decodeBytes(gpa, &fixtures.multi); defer sfc.deinit(gpa); try testing.expectEqual(@as(i32, 32), sfc.getWidth()); try testing.expectEqual(@as(i32, 32), sfc.getHeight()); try expectPixels(sfc, &fixtures.multi_pixels, 32);
// And a probe says the same, without reading an image. var r: Io.Reader = .fixed(&fixtures.multi); const info = try z2dimg.probe(&r, .{}); try testing.expectEqual(@as(u32, 32), info.width); try testing.expectEqual(z2dimg.Format.ico, info.format);}
test "the directory is there for a caller who wants a particular size" { const gpa = testing.allocator; var r: Io.Reader = .fixed(&fixtures.multi); var decoder = try z2dimg.ico.Decoder.init(gpa, &r, .{}); defer decoder.deinit(gpa);
try testing.expectEqual(z2dimg.ico.Kind.icon, decoder.kind); try testing.expectEqual(@as(usize, 2), decoder.entries.len);
// Whichever order the writer used, both sizes are described. var saw_small = false; var saw_large = false; for (decoder.entries) |entry| { if (entry.width == 16) saw_small = true; if (entry.width == 32) saw_large = true; } try testing.expect(saw_small); try testing.expect(saw_large);
// The smaller one, by index --- which is the whole point of exposing it. const small = for (decoder.entries, 0..) |entry, i| { if (entry.width == 16) break i; } else unreachable; var sfc = try decoder.decodeEntry(gpa, &r, small, .{}); defer sfc.deinit(gpa); try testing.expectEqual(@as(i32, 16), sfc.getWidth());}
test "an entry already read past is refused rather than answered wrongly" { // A `*Io.Reader` does not go backwards, which is the whole sans-I/O // bargain. Saying so is better than seeking to an offset that is no // longer where it was. const gpa = testing.allocator; var r: Io.Reader = .fixed(&fixtures.multi); var decoder = try z2dimg.ico.Decoder.init(gpa, &r, .{}); defer decoder.deinit(gpa);
var last = try decoder.decodeEntry(gpa, &r, decoder.entries.len - 1, .{}); last.deinit(gpa); try testing.expectError(error.Unsupported, decoder.decodeEntry(gpa, &r, 0, .{}));}
test "a cursor is an icon with one field changed" { const gpa = testing.allocator; var sfc = try decodeBytes(gpa, &fixtures.cursor); defer sfc.deinit(gpa); try expectPixels(sfc, &fixtures.dib32_pixels, fixtures.side);
var r: Io.Reader = .fixed(&fixtures.cursor); var decoder = try z2dimg.ico.Decoder.init(gpa, &r, .{}); defer decoder.deinit(gpa); try testing.expectEqual(z2dimg.ico.Kind.cursor, decoder.kind);}
test "an icon is told apart from a TGA, which begins the same way" { // The collision this format's detection is shaped by. A TGA with no // identification field and no colour map begins with two zeroes, and its // image type of one or two then sits exactly where an icon's type does. // The two formats agree in every byte either of them offers as a // signature, so the first directory *entry* is read as well. const tga = [_]u8{ 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 0x18, 0, } ++ @as([32]u8, @splat(0)); try testing.expectEqual(@as(?z2dimg.Format, .tga), z2dimg.detect(&tga));
// And a real icon is still an icon. try testing.expectEqual(@as(?z2dimg.Format, .ico), z2dimg.detect(&fixtures.dib32)); try testing.expectEqual(@as(?z2dimg.Format, .ico), z2dimg.detect(&fixtures.cursor));
// Headers that are the right shape and describe nothing. for ([_][]const u8{ &([_]u8{ 0, 0, 1, 0, 0, 0 } ++ @as([32]u8, @splat(0))), // no images &([_]u8{ 0, 0, 3, 0, 1, 0 } ++ @as([32]u8, @splat(0))), // a type that is neither &([_]u8{ 1, 0, 1, 0, 1, 0 } ++ @as([32]u8, @splat(0))), // reserved is not reserved }) |bytes| { try testing.expectEqual(@as(?z2dimg.Format, null), z2dimg.detect(bytes)); }}
test "what is written comes back, one image and several" { const gpa = testing.allocator; var small: z2d.Surface = try .init(.image_surface_rgba, gpa, 8, 8); defer small.deinit(gpa); for (0..8) |y| for (0..8) |x| { z2dimg.pixels.writePixel(&small, @intCast(x), @intCast(y), .{ .r = @intCast(x * 30), .g = @intCast(y * 30), .b = 90, .a = 255, }); }; var large: z2d.Surface = try .init(.image_surface_rgba, gpa, 16, 16); defer large.deinit(gpa); for (0..16) |y| for (0..16) |x| { z2dimg.pixels.writePixel(&large, @intCast(x), @intCast(y), .{ .r = 200, .g = @intCast(x * 16), .b = @intCast(y * 16), .a = if (x == 0) 0 else 255, }); };
// One image, through the uniform entry point. { var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try z2dimg.encode(gpa, &large, &w.writer, .{ .ico = .{} }); try testing.expectEqual(@as(?z2dimg.Format, .ico), z2dimg.detect(w.written()));
var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 16), back.getWidth()); // The alpha survives, which is the thirty-two bit entry doing its job. try testing.expectEqual(@as(u8, 0), at(back, 0, 0).a); try testing.expectEqual(Rgba8{ .r = 200, .g = 16, .b = 0, .a = 255 }, at(back, 1, 0)); }
// Several, which is what an icon file is actually for. { var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList();
var enc: z2dimg.ico.Encoder = .init(.{}); defer enc.deinit(gpa); try enc.image(gpa, &small); try enc.image(gpa, &large); try enc.finish(&w.writer);
var r: Io.Reader = .fixed(w.written()); var decoder = try z2dimg.ico.Decoder.init(gpa, &r, .{}); defer decoder.deinit(gpa); try testing.expectEqual(@as(usize, 2), decoder.entries.len); try testing.expectEqual(@as(u32, 8), decoder.entries[0].width); try testing.expectEqual(@as(u32, 16), decoder.entries[1].width);
// And the larger is what a bare decode gives back. var back = try decodeBytes(gpa, w.written()); defer back.deinit(gpa); try testing.expectEqual(@as(i32, 16), back.getWidth()); }}
test "an icon cannot record a side it has no room for" { // The directory keeps each side in one byte, with zero meaning the // largest. There is nowhere to say anything bigger. const gpa = testing.allocator; var wide: z2d.Surface = try .init(.image_surface_rgb, gpa, 257, 4); defer wide.deinit(gpa);
var list: std.ArrayList(u8) = .empty; defer list.deinit(gpa); var w: Io.Writer.Allocating = .fromArrayList(gpa, &list); defer list = w.toArrayList(); try testing.expectError( error.Unsupported, z2dimg.encode(gpa, &wide, &w.writer, .{ .ico = .{} }), );}
test "a truncated icon fails cleanly" { const gpa = testing.allocator; var n: usize = 6; while (n < fixtures.dib32.len) : (n += 13) { var sfc = decodeBytes(gpa, fixtures.dib32[0..n]) catch |err| switch (err) { error.InvalidData, error.Unsupported, error.EndOfStream, error.UnknownFormat => continue, else => return err, }; sfc.deinit(gpa); }}