Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,41 @@ jobs:
timeout 900 sh tests/elf-tls.sh
sh tests/static-vulkan.sh

pixel-macos:
# The pixel harness of the macOS look (issue 1072): the renders of
# AppKit from native-ref, and each control of aqua-macos.css against
# its render. The report goes to the summary of the job, and the
# pictures of each case (AppKit at the left, ztk at the right) to an
# artifact.
name: Pixels (macOS look)
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: macos-latest
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2
with:
version: ${{ env.ZIG_VERSION }}
- name: Render the AppKit controls
run: |
sw_vers
mkdir -p "$RUNNER_TEMP/native-ref"
zig build native-ref -- "$RUNNER_TEMP/native-ref"
- name: Compare ztk with AppKit
run: ZTK_NATIVE_REF="$RUNNER_TEMP/native-ref" zig build test -Dtest-filter="pixel harness"
- name: Report
if: always()
run: |
{ echo "## The macOS look against AppKit ($(sw_vers -productVersion))"; echo; cat "$RUNNER_TEMP/native-ref/report.md"; } >> "$GITHUB_STEP_SUMMARY" || true
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
name: pixel-macos
path: |
${{ runner.temp }}/native-ref/report.md
${{ runner.temp }}/native-ref/compare/
if-no-files-found: ignore

test-ios:
# The UIKit backend: the ztk program for the iOS Simulator, an app
# with tests/ios/main.tcl, and a screenshot of its first window.
Expand Down
2 changes: 1 addition & 1 deletion docs/dev/native-look.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ The target is an app that AppKit draws on macOS 13 and later: Finder, System Set
2. The reference tool: AppKit controls rendered offscreen in light and dark, with their measures as JSON.
3. The Core Text backend of `text/system.zig`, with a test that compares glyph images with the images of Core Text.
4. `aqua-macos.css` with the system colors as variables, control by control, from the measures of step 2, and `nativeLook` = `macos`.
5. The pixel harness in CI against the renders of step 2.
5. The pixel harness in CI against the renders of step 2. `src/tests/aqua_pixels.zig` with `ZTK_NATIVE_REF=DIR` (the output folder of `zig build native-ref`) compares each control in each state with its render, and the job `pixel-macos` of CI runs it and keeps the report and the pictures. A case fails above its limit; a change that brings a control closer lowers its limit.
6. Vibrancy and the title bar styles.
7. Scrolling with momentum and overlay scrollers, and the motion timings.
8. The text bindings of Cocoa, the Services, spell check, and the context menu of text.
Expand Down
252 changes: 252 additions & 0 deletions src/tests/aqua_pixels.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
//! The pixel harness of the macOS look (ztk#1072, step 5 of the macOS part
//! of docs/dev/native-look.md): each control of `aqua-macos.css` against
//! the render of the same AppKit control by `zig build native-ref`.
//!
//! zig build native-ref -- REFDIR
//! ZTK_NATIVE_REF=REFDIR zig build test -Dtest-filter="pixel harness"
//!
//! For each case of `cases` (a control in a state, in the regular size of
//! the key window) and for light and dark, the test reads the frame of
//! the control from REFDIR/measures.json and the scale from its
//! `pixels_wide`, makes the same widget with ztk on the headless backend
//! with Core Text, places it at that frame, and crops it. The AppKit
//! render has no background, so it goes over the window color of ztk.
//! AppKit and ztk may put a control a few pixels apart, so the compare
//! tries each shift of up to `max_shift` pixels and keeps the best. A
//! pixel differs when one of its channels differs by more than
//! `level`; the score is the fraction of pixels that differ. A case fails
//! when its score is above its limit: a change that moves ztk further
//! from AppKit fails, and a change that brings it closer lowers the limit
//! in the same PR. The test writes REFDIR/report.md (one row for each
//! case) and REFDIR/compare/NAME.png (AppKit at the left, ztk at the
//! right), which CI keeps as an artifact. Without ZTK_NATIVE_REF the test
//! is skipped.
//! SPDX-License-Identifier: BSD-2-Clause

const std = @import("std");
const builtin = @import("builtin");
const t = std.testing;
const Harness = @import("../testing.zig").Harness;
const png = @import("../base/png.zig");
const Image = @import("../render/renderer.zig").Image;

const level: u8 = 40;
const max_shift: i32 = 4;

const Case = struct {
/// The kind and the state of native-ref: `KIND-regular-STATE`.
kind: []const u8,
state: []const u8,
/// The Tcl that makes the widget `.c`.
script: []const u8,
/// The highest score for light and for dark.
limit: [2]f32,
};

/// The controls with a ttk widget. native-ref also renders a stepper and
/// a spinner, which have no ttk widget of their own, and a legacy
/// scroller, which AppKit draws empty with no window on the screen (the
/// scrollers are step 7). The limits are the scores on macOS 27 plus
/// 0.05; the large ones are the differences that the next steps fix: the
/// size of the switch, and the size and the text of the default button.
const cases = [_]Case{
.{ .kind = "push", .state = "rest", .script = "ttk::button .c -text Button", .limit = .{ 0.08, 0.10 } },
.{ .kind = "push", .state = "disabled", .script = "ttk::button .c -text Button; .c state disabled", .limit = .{ 0.05, 0.05 } },
.{ .kind = "push", .state = "default", .script = "ttk::button .c -text Button -default active", .limit = .{ 0.39, 0.39 } },
.{ .kind = "check", .state = "rest", .script = "ttk::checkbutton .c -text {Check box} -variable v; set v 0", .limit = .{ 0.10, 0.13 } },
.{ .kind = "check", .state = "on", .script = "ttk::checkbutton .c -text {Check box} -variable v; set v 1", .limit = .{ 0.14, 0.17 } },
.{ .kind = "check", .state = "disabled", .script = "ttk::checkbutton .c -text {Check box} -variable v; set v 0; .c state disabled", .limit = .{ 0.05, 0.06 } },
.{ .kind = "radio", .state = "rest", .script = "ttk::radiobutton .c -text Radio -value 1 -variable v; set v 0", .limit = .{ 0.09, 0.13 } },
.{ .kind = "radio", .state = "on", .script = "ttk::radiobutton .c -text Radio -value 1 -variable v; set v 1", .limit = .{ 0.16, 0.19 } },
.{ .kind = "radio", .state = "disabled", .script = "ttk::radiobutton .c -text Radio -value 1 -variable v; set v 0; .c state disabled", .limit = .{ 0.05, 0.06 } },
.{ .kind = "toggle", .state = "rest", .script = "ttk::checkbutton .c -variable v; ztk::class .c add switch; set v 0", .limit = .{ 0.07, 0.41 } },
.{ .kind = "toggle", .state = "on", .script = "ttk::checkbutton .c -variable v; ztk::class .c add switch; set v 1", .limit = .{ 0.55, 0.77 } },
.{ .kind = "toggle", .state = "disabled", .script = "ttk::checkbutton .c -variable v; ztk::class .c add switch; set v 0; .c state disabled", .limit = .{ 0.07, 0.49 } },
.{ .kind = "slider", .state = "rest", .script = "ttk::scale .c -from 0 -to 1 -value 0.5", .limit = .{ 0.11, 0.12 } },
.{ .kind = "slider", .state = "on", .script = "ttk::scale .c -from 0 -to 1 -value 0.75", .limit = .{ 0.12, 0.14 } },
.{ .kind = "slider", .state = "disabled", .script = "ttk::scale .c -from 0 -to 1 -value 0.5; .c state disabled", .limit = .{ 0.11, 0.13 } },
.{ .kind = "popup", .state = "rest", .script = "ttk::menubutton .c -text Pop-up", .limit = .{ 0.17, 0.17 } },
.{ .kind = "popup", .state = "disabled", .script = "ttk::menubutton .c -text Pop-up; .c state disabled", .limit = .{ 0.13, 0.12 } },
.{ .kind = "pulldown", .state = "rest", .script = "ttk::menubutton .c -text Pull-down", .limit = .{ 0.16, 0.17 } },
.{ .kind = "pulldown", .state = "disabled", .script = "ttk::menubutton .c -text Pull-down; .c state disabled", .limit = .{ 0.13, 0.12 } },
.{ .kind = "field", .state = "rest", .script = "ttk::entry .c; .c insert 0 Text", .limit = .{ 0.07, 0.07 } },
.{ .kind = "field", .state = "disabled", .script = "ttk::entry .c; .c insert 0 Text; .c state disabled", .limit = .{ 0.06, 0.06 } },
.{ .kind = "combo", .state = "rest", .script = "ttk::combobox .c; .c set Combo", .limit = .{ 0.09, 0.10 } },
.{ .kind = "combo", .state = "disabled", .script = "ttk::combobox .c; .c set Combo; .c state disabled", .limit = .{ 0.06, 0.07 } },
.{ .kind = "segmented", .state = "rest", .script = segmented ++ "set v 0", .limit = .{ 0.09, 0.10 } },
.{ .kind = "segmented", .state = "on", .script = segmented ++ "set v 1", .limit = .{ 0.09, 0.10 } },
.{ .kind = "segmented", .state = "disabled", .script = segmented ++ "set v 0; foreach b [winfo children .c] { $b state disabled }", .limit = .{ 0.40, 0.40 } },
.{ .kind = "progress", .state = "rest", .script = "ttk::progressbar .c -value 40", .limit = .{ 0.09, 0.09 } },
.{ .kind = "tabview", .state = "rest", .script = notebook, .limit = .{ 0.07, 0.10 } },
.{ .kind = "tabview", .state = "disabled", .script = notebook ++ "; .c state disabled", .limit = .{ 0.07, 0.10 } },
.{ .kind = "box", .state = "rest", .script = "ttk::labelframe .c -text Group", .limit = .{ 0.06, 0.06 } },
};

const segmented =
\\ttk::frame .c; ztk::class .c add segmented
\\foreach {i l} {0 One 1 Two 2 Three} {
\\ ttk::radiobutton .c.$i -text $l -value $i -variable v
\\ ztk::class .c.$i add segmented
\\ pack .c.$i -side left -fill both -expand 1
\\}
\\
;
const notebook = "ttk::notebook .c; .c add [ttk::frame .c.a] -text Account; .c add [ttk::frame .c.s] -text Server";

const Frame = struct { w: f64, h: f64, scale: f64 };

/// The frame of `name` in measures.json, and the scale of its render.
fn frameOf(measures: std.json.Value, name: []const u8) ?Frame {
const m = measures.object.get(name) orelse return null;
const fr = m.object.get("frame").?.array.items;
const w = num(fr[0]);
const pw: f64 = num(m.object.get("pixels_wide").?);
if (w <= 0 or pw <= 0) return null;
return .{ .w = w, .h = num(fr[1]), .scale = @round(pw / w) };
}

fn num(v: std.json.Value) f64 {
return switch (v) {
.integer => |i| @floatFromInt(i),
.float => |f| f,
else => 0,
};
}

const Score = struct { fraction: f32, dx: i32, dy: i32 };

/// The fraction of the pixels of `ref` (over `bg`) that differ from `img`
/// at the best shift.
fn compare(ref: Image, img: Image, x0: i32, y0: i32) Score {
var best: Score = .{ .fraction = 1, .dx = 0, .dy = 0 };
var dy: i32 = -max_shift;
while (dy <= max_shift) : (dy += 1) {
var dx: i32 = -max_shift;
while (dx <= max_shift) : (dx += 1) {
var diff: usize = 0;
var total: usize = 0;
for (0..ref.height) |ry| for (0..ref.width) |rx| {
const ix = x0 + dx + @as(i32, @intCast(rx));
const iy = y0 + dy + @as(i32, @intCast(ry));
if (ix < 0 or iy < 0 or ix >= img.width or iy >= img.height) continue;
const bgp = pixel(img, 0, 0);
const r = pixel(ref, rx, ry);
const z = pixel(img, @intCast(ix), @intCast(iy));
const a: u32 = r[3];
total += 1;
for (0..3) |k| {
const over: u32 = (@as(u32, r[k]) * a + @as(u32, bgp[k]) * (255 - a)) / 255;
if (@abs(@as(i32, @intCast(over)) - @as(i32, z[k])) > level) {
diff += 1;
break;
}
}
};
if (total == 0) continue;
const f: f32 = @as(f32, @floatFromInt(diff)) / @as(f32, @floatFromInt(total));
if (f < best.fraction) best = .{ .fraction = f, .dx = dx, .dy = dy };
}
}
return best;
}

fn pixel(img: Image, x: usize, y: usize) [4]u8 {
const i = (y * img.width + x) * 4;
return img.pixels[i..][0..4].*;
}

/// AppKit at the left, the same area of ztk at the right.
fn sideBySide(a: std.mem.Allocator, ref: Image, img: Image, x0: i32, y0: i32) !Image {
const w = ref.width * 2 + 8;
const out: Image = .{ .width = w, .height = ref.height, .pixels = try a.alloc(u8, w * ref.height * 4) };
@memset(out.pixels, 128);
const bgp = pixel(img, 0, 0);
for (0..ref.height) |y| for (0..ref.width) |x| {
const r = pixel(ref, x, y);
const o = (y * w + x) * 4;
for (0..3) |k| out.pixels[o + k] = @intCast((@as(u32, r[k]) * r[3] + @as(u32, bgp[k]) * (255 - r[3])) / 255);
out.pixels[o + 3] = 255;
const ix = x0 + @as(i32, @intCast(x));
const iy = y0 + @as(i32, @intCast(y));
if (ix < 0 or iy < 0 or ix >= img.width or iy >= img.height) continue;
const z = pixel(img, @intCast(ix), @intCast(iy));
const o2 = (y * w + ref.width + 8 + x) * 4;
out.pixels[o2..][0..4].* = .{ z[0], z[1], z[2], 255 };
};
return out;
}

test "pixel harness: the controls of the macOS look against AppKit" {
if (comptime builtin.os.tag != .macos or !@import("build_options").appkit) return error.SkipZigTest;
const gpa = t.allocator;
const dir_z = t.environ.getAlloc(gpa, "ZTK_NATIVE_REF") catch return error.SkipZigTest;
defer gpa.free(dir_z);
const dir = std.Io.Dir.cwd();
const mpath = try std.fmt.allocPrint(gpa, "{s}/measures.json", .{dir_z});
defer gpa.free(mpath);
const mbytes = try dir.readFileAlloc(t.io, mpath, gpa, .limited(16 << 20));
defer gpa.free(mbytes);
const parsed = try std.json.parseFromSlice(std.json.Value, gpa, mbytes, .{});
defer parsed.deinit();
const cmp_dir = try std.fmt.allocPrint(gpa, "{s}/compare", .{dir_z});
defer gpa.free(cmp_dir);
try dir.createDirPath(t.io, cmp_dir);

const ct = @import("../platform/macos/coretext.zig");
const c = ct.CoreText.init(gpa) orelse return error.SkipZigTest;
defer c.deinit();

var report: std.ArrayList(u8) = .empty;
defer report.deinit(gpa);
try report.appendSlice(gpa, "| Control | State | Appearance | Score | Limit | Shift |\n|---|---|---|---|---|---|\n");
var failures: usize = 0;
for ([_]bool{ false, true }, 0..) |dark, ai| {
const ap = if (dark) "dark" else "light";
for (cases) |cs| {
const name = try std.fmt.allocPrint(gpa, "{s}-regular-{s}-{s}", .{ cs.kind, cs.state, ap });
defer gpa.free(name);
const fr = frameOf(parsed.value, name) orelse continue;
const rpath = try std.fmt.allocPrint(gpa, "{s}/{s}.png", .{ dir_z, name });
defer gpa.free(rpath);
const rbytes = try dir.readFileAlloc(t.io, rpath, gpa, .limited(16 << 20));
defer gpa.free(rbytes);
const ref = try png.decode(gpa, rbytes);
defer gpa.free(ref.pixels);

var h: Harness = undefined;
h.render_mode = .inline_draw;
h.animations = false;
h.dark = dark;
try h.initFull(null, "macos", c.backend());
defer h.deinit();
h.head.setScale(h.win, @floatCast(fr.scale));
_ = try h.eval("wm geometry . 300x160");
_ = try h.eval(cs.script);
const place = try std.fmt.allocPrint(gpa, "place .c -x 20 -y 20 -width {d} -height {d}", .{ @round(fr.w), @round(fr.h) });
defer gpa.free(place);
_ = try h.eval(place);
try h.update();
const img = h.head.image(h.win).?;
const x0: i32 = @intFromFloat(20 * fr.scale);
const sc = compare(ref, img, x0, x0);
const limit = cs.limit[ai];
const fail = sc.fraction > limit;
if (fail) failures += 1;
try report.print(gpa, "| {s} | {s} | {s} | {d:.3} | {d:.3} | {d},{d} |{s}\n", .{ cs.kind, cs.state, ap, sc.fraction, limit, sc.dx, sc.dy, if (fail) " FAIL" else "" });
const side = try sideBySide(gpa, ref, img, x0 + sc.dx, x0 + sc.dy);
defer gpa.free(side.pixels);
const bytes = try png.encode(gpa, side);
defer gpa.free(bytes);
const cpath = try std.fmt.allocPrint(gpa, "{s}/{s}.png", .{ cmp_dir, name });
defer gpa.free(cpath);
try dir.writeFile(t.io, .{ .sub_path = cpath, .data = bytes });
}
}
const rp = try std.fmt.allocPrint(gpa, "{s}/report.md", .{dir_z});
defer gpa.free(rp);
try dir.writeFile(t.io, .{ .sub_path = rp, .data = report.items });
if (failures > 0) {
std.debug.print("pixel harness: {d} cases above their limit; see {s}\n{s}", .{ failures, rp, report.items });
return error.TestUnexpectedResult;
}
}
1 change: 1 addition & 0 deletions src/ztk.zig
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ test {
_ = @import("tests/tray.zig");
_ = @import("tests/dnd.zig");
_ = @import("tests/aqua_look.zig");
_ = @import("tests/aqua_pixels.zig");
_ = @import("tests/density.zig");
_ = @import("tests/native_choice.zig");
_ = @import("tests/svgphoto.zig");
Expand Down
13 changes: 11 additions & 2 deletions tools/native-ref/macos/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
//! AppKit draws some parts only on the screen (the tabs of a tab view, the
//! glass of a window): `controls.swift` in this folder shows the Login
//! dialog and the other controls in a real window, for `screencapture -l`.
//! The renders are in sRGB, as ztk draws: a capture of the screen is in
//! the color space of the display, where the accent #007aff of AppKit
//! reads as another blue, so convert one with `sips -m` and the sRGB
//! profile before a compare.
//! The renders are references for the pixel harness and the measures are
//! the sources of `aqua-macos.css`; neither goes into the repository. The
//! accent is the accent of the machine (blue on a CI runner).
Expand Down Expand Up @@ -292,8 +296,13 @@ pub fn main(init: std.process.Init) !void {
defer gpa.free(name);
// The render of AppKit, as a PNG of NSBitmapImageRep.
const rep = objc.call(fn (Id, Sel, NSRect) callconv(.c) ?Id, c, "bitmapImageRepForCachingDisplayInRect:", .{bounds});
if (rep) |r| {
objc.call(fn (Id, Sel, NSRect, Id) callconv(.c) void, c, "cacheDisplayInRect:toBitmapImageRep:", .{ bounds, r });
if (rep) |r0| {
objc.call(fn (Id, Sel, NSRect, Id) callconv(.c) void, c, "cacheDisplayInRect:toBitmapImageRep:", .{ bounds, r0 });
// The render is in the color space of the screen; ztk
// draws in sRGB, so the PNG is converted to sRGB
// (NSColorRenderingIntentDefault 0).
const srgb = objc.call(fn (Class, Sel) callconv(.c) Id, cls("NSColorSpace"), "sRGBColorSpace", .{});
const r = objc.call(fn (Id, Sel, Id, isize) callconv(.c) ?Id, r0, "bitmapImageRepByConvertingToColorSpace:renderingIntent:", .{ srgb, @as(isize, 0) }) orelse r0;
const dict = objc.call(fn (Class, Sel) callconv(.c) Id, cls("NSDictionary"), "dictionary", .{});
// NSBitmapImageFileTypePNG 4.
if (objc.call(fn (Id, Sel, usize, Id) callconv(.c) ?Id, r, "representationUsingType:properties:", .{ @as(usize, 4), dict })) |data| {
Expand Down
Loading