/* ui_all.c —— **C 语言 UI 接口逐条验收**（画布 / 窗口 / 输入消息 / 存储 / 音频 / 传感器）。
 * ui_all.c - **per-interface acceptance for the C UI API** (canvas / window / input messages / store / audio / sensors).
 *
 * ## 这个程序要证明的那一件事
 * ## The one thing this program exists to prove
 *
 * **每一条接口都有一条「生效 / 没生效」分辨得出来的证据** —— 不是「调了不崩」。
 * **Every interface gets evidence that can tell "took effect" from "did not"** - not just "it did not crash".
 * 手法与 `Examples/c/3d/g3_all.c` 同一套：
 * Same techniques as `Examples/c/3d/g3_all.c`:
 *   ① **有返回值的**：把返回值打出来并按语义断言（合法 ≥1、越界/非法 <0、0 = 失败）；
 *     1) **Return values**: print them and assert the documented semantics (valid >= 1, out-of-range/invalid < 0, 0 = failure);
 *   ② **改变画面的**：用 `ui_2d_get_pixel` 读**同一个像素**调用前后的值，两个值必须不同；
 *     2) **Changing the image**: read the **same pixel** with `ui_2d_get_pixel` before and after; the two must differ;
 *   ③ **反证**（本文件里标 `REVERSE:` 的那些）：参数换成「应当无效果」的值，断言读数**不变**。
 *     3) **Reverse tests** (the ones marked `REVERSE:`): use a value that should have no effect and assert the reading is **unchanged**.
 *      例：`ui_layer_end(0)` 之后层里的东西必须**一点都没上来**；`ui_mask_clear()` 之后蒙版外必须又能画上。
 *      e.g. after `ui_layer_end(0)` nothing from the layer may have landed; after `ui_mask_clear()` drawing outside must work again.
 *      **只测「变了」不测「不该变时没变」的判据会被巧合骗过。**
 *      **A criterion that only tests "it changed" and never "it did not change when it should not" is fooled by coincidence.**
 *
 * ## 跑法
 * ## How to run
 *   桌面（无头，秒级闭环；`--screen` 就是 `ui_scr_get_w/h` 报的数）：
 *   Desktop (headless, seconds to finish; `--screen` is what `ui_scr_get_w/h` reports):
 *     dotnet scripts/vmlcli/bin/Release/net10.0/vmlcli.dll \
 *            third_party/vml/Examples/c/ui/ui_all.c --screen 480x640 --timeout 120
 *   手机：命令行页敲 `vml run examples/c/ui/ui_all.c`
 *   On a phone: type `vml run examples/c/ui/ui_all.c` in the command-line page.
 *
 * 机器判读：逐行 `PASS <名字> <观测A> <观测B>` / `FAIL …` / `UNIMPL …`，
 * Machine-readable: one `PASS <name> <obsA> <obsB>` / `FAIL ...` / `UNIMPL ...` line per assertion,
 * 最后一行 `OK=<通过> FAIL=<失败> UNIMPL=<本端没这个能力> NUMS=<碰到的接口号数>`。
 * ending with `OK=<pass> FAIL=<fail> UNIMPL=<capability absent on this host> NUMS=<number of interface numbers touched>`.
 *   `UNIMPL` **不是失败**：桌面没有传感器/GPS 是如实反映（`vml_ui.h` 写着"这一端没有"）。
 *   `UNIMPL` **is not a failure**: a desktop with no sensors/GPS is reporting the truth (`vml_ui.h` says "this end lacks it").
 *   ⚠ 但**能分辨**：`UNIMPL` 只在接口自己说了"没有"时记（返回 0 且 `is_available` 为 0），
 *   ⚠ But it is **distinguishable**: `UNIMPL` is recorded only when the interface itself says "absent" (returns 0 and `is_available` is 0),
 *     接口返回了错误值/错误语义时一律 `FAIL`。
 *     while a wrong return value or wrong semantics is always `FAIL`.
 *
 * ## 判据为什么这么挑（都是实测出来的）
 * ## Why the criteria look like this (all measured)
 *
 * · **颜色一律写 `VML_COLOR_*` / `ui_color_rgb`**：`-65536` 是红、`-16777216` 是黑 —— 手算负数
 *   · **Colours always go through `VML_COLOR_*` / `ui_color_rgb`**: `-65536` is red and `-16777216` is black. Hand-computing
 *   坑过本仓两轮（见 g3_all.c 的记录），所以开头先打一行颜色自证。
 *   negative constants cost this repo two rounds (see the record in g3_all.c), so the first lines print a colour self-check.
 * · `ui_2d_get_pixel` 回的是 **0xRRGGBB（没有 alpha）**；而 `ui_2d_flood_fill` 的边界色要 **0xAARRGGBB**
 *   · `ui_2d_get_pixel` returns **0xRRGGBB (no alpha)**, while `ui_2d_flood_fill`'s border colour wants **0xAARRGGBB**
 *   （BGI 的 `_bgi_rgb` 就 OR 了 `0xFF000000`）。**实测**：传 `0x008000` 边界**不生效、整屏被灌满**，
 *   (BGI's `_bgi_rgb` ORs in `0xFF000000`). **Measured**: passing `0x008000` makes the border **ineffective and the whole screen gets filled**,
 *   传 `0xFF008000` 才是 37 条游程、只填框内。本文件用后者。
 *   while `0xFF008000` gives 37 runs and fills only the inside. This file uses the latter.
 * · **透明度混合值不写死**：桌面 128/255 白叠黑实测 `0x808080`，但不同后端可能差 1～2 档 ⇒ 判「灰度且在 0x7E..0x82」。
 *   · **The blended value is not hard-coded**: on the desktop 128/255 white over black measured `0x808080`, but other backends may be 1-2 off
 *   => assert "grey and within 0x7E..0x82".
 * · **文字只判"有墨"**：字号/字体随平台不同，`>0` 才是跨端通用的判据。
 *   · **Text only asserts "there is ink"**: size and font vary per platform, so `>0` is the portable criterion.
 * · **音频/传感器按「有就验、没有就 UNIMPL」**：桌面可能没有声卡（`ui_tone_on` 返回 -1）或没有硬件。
 *   · **Audio/sensors are "verify if present, UNIMPL if absent"**: a desktop may lack a sound card (`ui_tone_on` returns -1) or the hardware.
 *
 * ## 已知偏差（2026-10-26 实测，**本文件没有把它们写成 FAIL**）
 * ## Known deviations (measured 2026-10-26; **not asserted as FAIL here**)
 *   ① `ui_brush_named("从没定义过的名字")` 返回**一个有效句柄**（实测 2），而 `vml_ui.h` 写的是「0 = 没有这个名字」；
 *     1) `ui_brush_named("a name never defined")` returns **a valid handle** (measured 2), while `vml_ui.h` says "0 = no such name";
 *   ② `ui_tone_on(-1, 999, 500)` 返回 **0（成功）**，而文档写「-1 = 参数非法」；
 *     2) `ui_tone_on(-1, 999, 500)` returns **0 (success)**, while the docs say "-1 = invalid argument";
 *   ③ `ui_2d_flood_fill` 的边界色要 ARGB、`ui_2d_get_pixel` 回 RGB —— 两者**不能直接串起来用**（见上）。
 *     3) `ui_2d_flood_fill` wants an ARGB border while `ui_2d_get_pixel` returns RGB - the two **cannot be chained directly** (see above).
 *   前两条等宿主与文档对齐之后再收成判据（那时候会先红）。
 *   The first two become criteria once the host and the docs agree (they will go red first).
 *
 * ## 输入/对话框不在本文件里
 * ## Input and dialogs are not in this file
 * 它们要脚本化事件（`vmlcli --input` / `--answer`）或真机手指，见同目录的 `ui_input.c`
 * They need scripted events (`vmlcli --input` / `--answer`) or real fingers; see `ui_input.c` in this directory
 * 与 `scripts/vml-ui-api-probe.sh`。
 * and `scripts/vml-ui-api-probe.sh`.
 */
#include <vml_ui.h>
#include <stdio.h>

/* ── 计数与输出 ───────────────────────────────────────────────── */
/* ── Counters and output ──────────────────────────────────────── */

int g_ok;
int g_fail;
int g_unimpl;
int g_used[128];          /* 碰到过的接口号（去重后 NUMS=几个） */
                                 /* interface numbers touched (deduplicated => NUMS) */
int g_nused;
char g_line[256];

/* 记一个碰到的接口号（NUMS 是**真的碰到几个**，不是清单里有多少号）。 */
/* Record an interface number (NUMS is how many were really touched, not how many exist). */
void touch(int n) {
    int i;
    for (i = 0; i < g_nused; i++) {
        if (g_used[i] == n) { return; }
    }
    if (g_nused < 128) {
        g_used[g_nused] = n;
        g_nused = g_nused + 1;
    }
}

void chk(int cond, char* name, int a, int b) {
    if (cond) {
        printf("PASS %s %d %d\n", name, a, b);
        g_ok = g_ok + 1;
    } else {
        printf("FAIL %s %d %d\n", name, a, b);
        g_fail = g_fail + 1;
    }
}

void unimpl(char* name, int obs) {
    printf("UNIMPL %s %d\n", name, obs);
    g_unimpl = g_unimpl + 1;
}

/* 字符串里有没有 needle（不用 strstr：不假设它一定在）。 */
/* Does hay contain needle (no strstr: do not assume it exists). */
int has(char* hay, char* needle) {
    int i;
    int j;
    i = 0;
    while (hay[i] != 0) {
        j = 0;
        while (needle[j] != 0 && hay[i + j] == needle[j]) { j = j + 1; }
        if (needle[j] == 0) { return 1; }
        i = i + 1;
    }
    return 0;
}

/* 忙等：桌面没有 sleep 也行（ui_time_get_ms 是宿主时钟）。 */
/* Busy wait: works without sleep (ui_time_get_ms is the host clock). */
void wait_ms(int ms) {
    int t0;
    t0 = ui_time_get_ms();
    while (ui_time_get_ms() - t0 < ms) { }
}

int main(void) {
    int msg[8];
    int i;
    int n;
    int r;
    int h;
    int w;
    int hh;
    int win;
    char buf[256];
    char buf2[256];
    int pts[8];

    g_ok = 0; g_fail = 0; g_unimpl = 0; g_nused = 0;

    /* ══════════════════════════════════════════════════════════
     * A. 颜色封装（纯库函数，不占号）
     * A. Colour packing (pure library functions, no syscall number)
     * ══════════════════════════════════════════════════════════ */
    printf("COLOR rgb(255,0,0)=%d rgb(0,0,0)=%d argb(128,255,0,0)=%d\n",
           ui_color_rgb(255, 0, 0), ui_color_rgb(0, 0, 0), ui_color_argb(128, 255, 0, 0));
    chk(ui_color_rgb(255, 0, 0) == VML_COLOR_RED, "COLOR_RED", ui_color_rgb(255, 0, 0), VML_COLOR_RED);
    chk(ui_color_rgb(0, 0, 0) == VML_COLOR_BLACK, "COLOR_BLACK", ui_color_rgb(0, 0, 0), VML_COLOR_BLACK);
    /* 分量夹到 0..255：-5 -> 0、300 -> 255、12 不动 */
    /* Components clamp to 0..255: -5 -> 0, 300 -> 255, 12 stays */
    chk(ui_color_rgb(-5, 300, 12) == (int)0xFF00FF0Cu, "COLOR_CLAMP", ui_color_rgb(-5, 300, 12), (int)0xFF00FF0Cu);
    /* alpha 0x80 必须真的进高位（不是被丢掉） */
    /* alpha 0x80 must really go into the high byte (not be dropped) */
    chk(ui_color_argb(128, 255, 0, 0) == (int)0x80FF0000u, "COLOR_ARGB", ui_color_argb(128, 255, 0, 0), (int)0x80FF0000u);

    /* ══════════════════════════════════════════════════════════
     * B. 屏幕与窗口
     * B. Screen and window
     * ══════════════════════════════════════════════════════════ */
    /* 方向**开窗前就能问**（别拿 w>h 推：那是绘图区形状）。 */
    /* Orientation is askable **before** opening (do not infer it from w>h: that is the drawing area's shape). */
    touch(569);
    r = ui_scr_get_orientation();
    chk(r == VML_ORIENT_PORTRAIT || r == VML_ORIENT_LANDSCAPE, "ORIENT_PRE", r, 0);
    touch(568);
    chk(ui_scr_get_language() == 0 || ui_scr_get_language() == 1, "LANG", ui_scr_get_language(), 0);

    /* 开窗：传 0 尺寸 = 交给宿主（E141：开窗**前**问尺寸必然偏）。 */
    /* Open: 0 size = let the host decide (E141: asking **before** opening is always off). */
    touch(520);
    win = ui_win_open("ui_all", 0, 0);
    chk(win >= 1, "WIN_OPEN", win, 0);
    touch(565);
    chk(ui_win_is_closed() == 0, "WIN_IS_CLOSED0", ui_win_is_closed(), 0);

    /* 开完再问：这一对才是真值。 */
    /* Ask after opening: that pair is the real value. */
    touch(566); touch(567);
    w = ui_scr_get_w();
    hh = ui_scr_get_h();
    chk(w > 0, "SCR_W", w, 0);
    chk(hh > 0, "SCR_H", hh, 0);
    printf("SCREEN %dx%d orient=%d lang=%d\n", w, hh, ui_scr_get_orientation(), ui_scr_get_language());

    /* 按声明的 chrome 问：0 = 手柄/键盘都不要（画布吃满整屏）⇒ 不会比"要手柄"小。 */
    /* Ask by declared chrome: 0 = no gamepad/keyboard (canvas fills the screen) => never smaller than "needs gamepad". */
    touch(571); touch(572);
    r = ui_scr_get_w_ex(VML_ORIENT_PORTRAIT, VML_CHROME_NONE);
    n = ui_scr_get_w_ex(VML_ORIENT_PORTRAIT, VML_CHROME_GAMEPAD);
    chk(r > 0 && r >= n, "SCR_W_EX", r, n);
    r = ui_scr_get_h_ex(VML_ORIENT_PORTRAIT, VML_CHROME_NONE);
    n = ui_scr_get_h_ex(VML_ORIENT_PORTRAIT, VML_CHROME_GAMEPAD);
    chk(r > 0 && r >= n, "SCR_H_EX", r, n);
    chk(ui_scr_get_w_ex(VML_ORIENT_LANDSCAPE, VML_CHROME_NONE) > 0, "SCR_W_EX_LAND",
        ui_scr_get_w_ex(VML_ORIENT_LANDSCAPE, VML_CHROME_NONE), 0);

    /* JSON 通道与 syscall 通道**必须同源**（同一台机器上两个答案是最难查的分叉）。 */
    /* The JSON channel and the syscall channel **must agree** (two answers on one machine is the hardest kind of fork to debug). */
    touch(573);
    buf[0] = 0;
    n = ui_call_json("screen", "{}", buf, 256);
    sprintf(buf2, "\"w\":%d", w);
    chk(n > 0 && has(buf, buf2), "JSON_SCREEN_W", n, w);
    sprintf(buf2, "\"h\":%d", hh);
    chk(has(buf, buf2), "JSON_SCREEN_H", hh, 0);

    /* ══════════════════════════════════════════════════════════
     * C. 2D 图元 + 像素读回
     * C. 2D primitives + pixel readback
     * ══════════════════════════════════════════════════════════ */
    touch(522);
    ui_2d_clear(VML_COLOR_BLACK);
    touch(587);
    chk(ui_2d_get_pixel(3, 3) == 0, "CLEAR_BLACK", ui_2d_get_pixel(3, 3), 0);
    touch(523);
    ui_2d_pixel(5, 7, VML_COLOR_RED);
    chk(ui_2d_get_pixel(5, 7) == 0x00FF0000, "PIXEL_RED", ui_2d_get_pixel(5, 7), 0x00FF0000);
    /* 越界读必须是 -1（不是 0、不是随机色） */
    /* An out-of-range read must be -1 (not 0, not a random colour) */
    chk(ui_2d_get_pixel(-1, -1) == -1, "PIXEL_OOB", ui_2d_get_pixel(-1, -1), -1);

    touch(524);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_line(20, 10, 80, 10, VML_COLOR_RED, 2);
    chk(ui_2d_get_pixel(50, 10) == 0x00FF0000, "LINE_ON", ui_2d_get_pixel(50, 10), 0);
    /* REVERSE：线外两格必须还是黑（线宽 2 只该盖住两行） */
    /* REVERSE: two rows away must still be black (a width-2 line covers two rows only) */
    chk(ui_2d_get_pixel(50, 14) == 0, "LINE_OFF", ui_2d_get_pixel(50, 14), 0);

    touch(525);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_rect(10, 20, 50, 50, VML_COLOR_GREEN, 1, 0, 0);
    chk(ui_2d_get_pixel(30, 40) == 0x00008000, "RECT_IN", ui_2d_get_pixel(30, 40), 0);
    chk(ui_2d_get_pixel(5, 5) == 0, "RECT_OUT", ui_2d_get_pixel(5, 5), 0);
    /* 空心的那一档：框内必须**留空** */
    /* The unfilled variant: the inside must stay **empty** */
    ui_2d_rect(100, 20, 50, 50, VML_COLOR_GREEN, 0, 4, 0);
    chk(ui_2d_get_pixel(125, 45) == 0, "RECT_HOLLOW", ui_2d_get_pixel(125, 45), 0);
    chk(ui_2d_get_pixel(100, 45) == 0x00008000, "RECT_STROKE", ui_2d_get_pixel(100, 45), 0);

    touch(526);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_circle(200, 60, 20, VML_COLOR_BLUE, 1, 0);
    chk(ui_2d_get_pixel(200, 60) == 0x000000FF, "CIRCLE_C", ui_2d_get_pixel(200, 60), 0);
    chk(ui_2d_get_pixel(200, 20) == 0, "CIRCLE_OUT", ui_2d_get_pixel(200, 20), 0);

    touch(527);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_ellipse(250, 60, 30, 10, VML_COLOR_YELLOW, 1, 0);
    chk(ui_2d_get_pixel(250, 60) == 0x00FFFF00, "ELLIPSE_C", ui_2d_get_pixel(250, 60), 0);
    chk(ui_2d_get_pixel(250, 40) == 0, "ELLIPSE_OUT", ui_2d_get_pixel(250, 40), 0);

    /* 画序：后画的盖住先画的（读回的是最后一笔） */
    /* Draw order: later primitives cover earlier ones (readback returns the last stroke) */
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_rect(0, 0, 60, 60, VML_COLOR_RED, 1, 0, 0);
    ui_2d_rect(30, 30, 60, 60, VML_COLOR_BLUE, 1, 0, 0);
    chk(ui_2d_get_pixel(45, 45) == 0x000000FF, "DRAW_ORDER", ui_2d_get_pixel(45, 45), 0);

    /* ══════════════════════════════════════════════════════════
     * D. 裁剪
     * D. Clipping
     * ══════════════════════════════════════════════════════════ */
    touch(595);
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_clip_push(10, 10, 20, 20) == 1, "CLIP_PUSH", 1, 0);
    ui_2d_rect(0, 0, 100, 100, VML_COLOR_RED, 1, 0, 0);
    chk(ui_2d_get_pixel(15, 15) == 0x00FF0000, "CLIP_IN", ui_2d_get_pixel(15, 15), 0);
    /* REVERSE：裁剪区外一个像素都不许落 */
    /* REVERSE: not a single pixel may land outside the clip rect */
    chk(ui_2d_get_pixel(50, 50) == 0, "CLIP_OUT", ui_2d_get_pixel(50, 50), 0);
    chk(ui_clip_pop() == 1, "CLIP_POP", 1, 0);
    ui_2d_rect(60, 60, 10, 10, VML_COLOR_GREEN, 1, 0, 0);
    chk(ui_2d_get_pixel(65, 65) == 0x00008000, "CLIP_RESTORED", ui_2d_get_pixel(65, 65), 0);
    chk(ui_clip_reset() == 1, "CLIP_RESET", 1, 0);

    /* ══════════════════════════════════════════════════════════
     * E. 全局透明度与图层
     * E. Global alpha and layers
     * ══════════════════════════════════════════════════════════ */
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_2d_set_alpha(128) == 1, "ALPHA_SET", 1, 0);
    ui_2d_rect(10, 10, 50, 50, VML_COLOR_WHITE, 1, 0, 0);
    r = ui_2d_get_pixel(20, 20);
    /* 半透明白叠黑：三个通道相等、落在 0x7E..0x82（不同后端可能差 1～2 档） */
    /* Half-transparent white over black: all three channels equal and within 0x7E..0x82 (backends may be 1-2 off) */
    n = (r >> 16) & 0xFF;
    chk(n >= 0x7E && n <= 0x82 && ((r >> 8) & 0xFF) == n && (r & 0xFF) == n, "ALPHA_BLEND", r, n);
    ui_2d_set_alpha(255);
    ui_2d_rect(70, 70, 20, 20, VML_COLOR_WHITE, 1, 0, 0);
    chk(ui_2d_get_pixel(75, 75) == 0x00FFFFFF, "ALPHA_255", ui_2d_get_pixel(75, 75), 0x00FFFFFF);

    /* 图层：录制期间**看不见**，layer_end(0) 之后也**看不见**（REVERSE），255 才合成上来 */
    /* Layers: **invisible** while recording, still **invisible** after layer_end(0) (REVERSE), only 255 composites */
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_layer_begin() == 1, "LAYER_BEGIN", 1, 0);
    ui_2d_rect(10, 10, 30, 30, VML_COLOR_RED, 1, 0, 0);
    chk(ui_2d_get_pixel(20, 20) == 0, "LAYER_RECORDING", ui_2d_get_pixel(20, 20), 0);
    chk(ui_layer_end(0) == 1, "LAYER_END0", 1, 0);
    chk(ui_2d_get_pixel(20, 20) == 0, "LAYER_ZERO", ui_2d_get_pixel(20, 20), 0);
    chk(ui_layer_begin() == 1, "LAYER_BEGIN2", 1, 0);
    ui_2d_rect(10, 10, 30, 30, VML_COLOR_RED, 1, 0, 0);
    chk(ui_layer_end(255) == 1, "LAYER_END255", 1, 0);
    chk(ui_2d_get_pixel(20, 20) == 0x00FF0000, "LAYER_FULL", ui_2d_get_pixel(20, 20), 0);

    /* ══════════════════════════════════════════════════════════
     * F. 蒙版（碰撞体 + 布尔运算 + 导出路径）
     * F. Masks (collision body + boolean ops + path export)
     * ══════════════════════════════════════════════════════════ */
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_mask_begin() == 1, "MASK_BEGIN", 1, 0);
    ui_2d_rect(10, 10, 40, 40, VML_COLOR_RED, 1, 0, 0);
    chk(ui_mask_end(1) == 1, "MASK_END", 1, 0);
    ui_2d_rect(0, 0, 200, 200, VML_COLOR_WHITE, 1, 0, 0);
    chk(ui_2d_get_pixel(20, 20) == 0x00FFFFFF, "MASK_IN", ui_2d_get_pixel(20, 20), 0);
    /* REVERSE：蒙版外一笔都画不上 */
    /* REVERSE: nothing can be drawn outside the mask */
    chk(ui_2d_get_pixel(100, 100) == 0, "MASK_OUT", ui_2d_get_pixel(100, 100), 0);
    chk(ui_mask_is_inside(20, 20) == 1, "MASK_IS_IN", 1, 0);
    chk(ui_mask_is_inside(100, 100) == 0, "MASK_IS_OUT", 0, 0);
    chk(ui_mask_get_seg_count() == 1, "MASK_SEGS", ui_mask_get_seg_count(), 0);
    chk(ui_mask_get_seg_op(0) == VML_MASK_REPLACE, "MASK_OP", ui_mask_get_seg_op(0), 0);
    chk(ui_mask_get_shape_count(0) == 1, "MASK_SHAPES", ui_mask_get_shape_count(0), 0);
    buf[0] = 0;
    n = ui_mask_path(0, 0, buf, 200);
    chk(n > 0 && has(buf, "M10 10") && has(buf, "L50 50"), "MASK_PATH", n, 0);
    printf("MASK_PATH_S=%s\n", buf);
    /* 反证：缓冲区放不下要 -1；越界索引也是 -1 / 0 */
    /* Reverse: a too-small buffer is -1; an out-of-range index is -1 / 0 */
    chk(ui_mask_path(0, 0, buf, 4) == -1, "MASK_PATH_SMALL", ui_mask_path(0, 0, buf, 4), -1);
    chk(ui_mask_get_seg_op(99) == -1, "MASK_OP_OOB", ui_mask_get_seg_op(99), -1);
    chk(ui_mask_get_shape_count(99) == 0, "MASK_SHAPES_OOB", ui_mask_get_shape_count(99), 0);

    /* 布尔运算：并集 = 两段，第二段 op = UNION；两块区域都在里面 */
    /* Boolean op: union = two segments, the second's op is UNION; both areas are inside */
    ui_mask_begin();
    ui_2d_rect(30, 30, 40, 40, VML_COLOR_RED, 1, 0, 0);
    chk(ui_mask_end_ex(VML_MASK_UNION) == 1, "MASK_UNION", 1, 0);
    chk(ui_mask_get_seg_count() == 2, "MASK_UNION_SEGS", ui_mask_get_seg_count(), 0);
    chk(ui_mask_get_seg_op(1) == VML_MASK_UNION, "MASK_UNION_OP", ui_mask_get_seg_op(1), 0);
    chk(ui_mask_is_inside(20, 20) == 1 && ui_mask_is_inside(60, 60) == 1, "MASK_UNION_IN", 1, 1);

    /* 差集：中间挖一个洞（REVERSE：洞里画不上、洞外照画） */
    /* Subtraction: dig a hole in the middle (REVERSE: nothing lands in the hole, outside still works) */
    ui_2d_clear(VML_COLOR_BLACK);
    ui_mask_begin();
    ui_2d_rect(30, 30, 10, 10, VML_COLOR_RED, 1, 0, 0);
    chk(ui_mask_end_ex(VML_MASK_SUBTRACT) == 1, "MASK_SUB", 1, 0);
    chk(ui_mask_is_inside(35, 35) == 0, "MASK_HOLE", ui_mask_is_inside(35, 35), 0);
    chk(ui_mask_is_inside(15, 15) == 1, "MASK_OUTER", ui_mask_is_inside(15, 15), 1);

    chk(ui_mask_clear() == 1, "MASK_CLEAR", 1, 0);
    chk(ui_mask_get_seg_count() == 0, "MASK_CLEARED", ui_mask_get_seg_count(), 0);
    ui_2d_rect(100, 100, 10, 10, VML_COLOR_WHITE, 1, 0, 0);
    chk(ui_2d_get_pixel(105, 105) == 0x00FFFFFF, "MASK_CLEAR_DRAW", ui_2d_get_pixel(105, 105), 0);

    /* ══════════════════════════════════════════════════════════
     * G. 画刷 / 渐变 / 形状
     * G. Brushes / gradients / shapes
     * ══════════════════════════════════════════════════════════ */
    ui_2d_clear(VML_COLOR_BLACK);
    touch(575);
    r = ui_brush_solid(VML_COLOR_RED);
    chk(r >= 1, "BRUSH_SOLID", r, 0);
    touch(576);
    chk(ui_brush_set_fill(r) == 1, "STYLE_FILL", 1, 0);
    touch(574);
    ui_2d_shape_rect(10, 10, 40, 40, 0);
    chk(ui_2d_get_pixel(20, 20) == 0x00FF0000, "SHAPE_RECT", ui_2d_get_pixel(20, 20), 0);

    /* 线性渐变：两端**必须不同**（相同就说明渐变没生效、只剩纯色） */
    /* Linear gradient: the two ends **must differ** (equal means the gradient did not take effect, leaving a solid colour) */
    ui_2d_clear(VML_COLOR_BLACK);
    r = ui_brush_linear(VML_COLOR_RED, VML_COLOR_BLUE, 0, 0, 1000, 0);
    chk(r >= 1, "BRUSH_LINEAR", r, 0);
    ui_brush_set_fill(r);
    ui_2d_shape_rect(0, 0, 100, 40, 0);
    w = ui_2d_get_pixel(3, 20);
    hh = ui_2d_get_pixel(96, 20);
    chk(w != hh && w != 0 && hh != 0, "GRAD_LINEAR", w, hh);

    /* 径向渐变：圆心与边缘必须不同（几何量是**千分比**，传 100 会退化成纯色） */
    /* Radial gradient: centre and edge must differ (geometry is in **thousandths**; passing 100 degenerates to a solid colour) */
    ui_2d_clear(VML_COLOR_BLACK);
    r = ui_brush_radial(VML_COLOR_WHITE, VML_COLOR_BLUE, 500, 500, 500);
    chk(r >= 1, "BRUSH_RADIAL", r, 0);
    ui_brush_set_fill(r);
    ui_2d_shape_circle(150, 150, 60, 0);
    w = ui_2d_get_pixel(150, 150);
    hh = ui_2d_get_pixel(200, 150);
    chk(w != hh && w != 0 && hh != 0, "GRAD_RADIAL", w, hh);

    /* 命名渐变：先 `ui_2d_gradient` 定义、再 `ui_brush_named` 引用 */
    /* Named gradient: define with `ui_2d_gradient`, then reference with `ui_brush_named` */
    touch(534);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_gradient("ui_all_g", 0, VML_COLOR_RED, VML_COLOR_BLUE, 0, 0, 1000, 0);
    r = ui_brush_named("ui_all_g");
    chk(r >= 1, "BRUSH_NAMED", r, 0);
    ui_brush_set_fill(r);
    ui_2d_shape_rect(0, 0, 100, 40, 0);
    w = ui_2d_get_pixel(3, 20);
    hh = ui_2d_get_pixel(96, 20);
    chk(w != hh && w != 0 && hh != 0, "GRAD_NAMED", w, hh);

    /* 直接给渐变名的那条老接口（#538） */
    /* The older "pass the gradient name directly" interface (#538) */
    touch(538);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_gradient("ui_all_g2", 0, VML_COLOR_RED, VML_COLOR_BLUE, 0, 0, 1000, 0);
    ui_2d_rect_grad(0, 0, 100, 40, "ui_all_g2", 0);
    w = ui_2d_get_pixel(3, 20);
    hh = ui_2d_get_pixel(96, 20);
    chk(w != hh && w != 0 && hh != 0, "GRAD_RECT", w, hh);

    chk(ui_brush_reset() == 1, "BRUSH_RESET", 1, 0);
    /* 重置后回到纯色路径：直接传颜色也是合法刷子 */
    /* After reset we are back to solid: passing a colour directly is a legal brush too */
    ui_brush_set_fill(VML_COLOR_GREEN);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_shape_circle(200, 60, 30, 0);
    chk(ui_2d_get_pixel(200, 60) == 0x00008000, "FILL_COLOR_DIRECT", ui_2d_get_pixel(200, 60), 0);

    /* 形状族：每个都在它的特征点上留墨 */
    /* Shape family: each leaves ink at its characteristic point */
    ui_2d_clear(VML_COLOR_BLACK);
    ui_brush_set_fill(VML_COLOR_RED);
    ui_2d_shape_star(250, 80, 40, 18, 5, 0);
    chk(ui_2d_get_pixel(250, 80) == 0x00FF0000, "SHAPE_STAR", ui_2d_get_pixel(250, 80), 0);
    ui_2d_shape_pie(80, 250, 30, 0, 90);
    chk(ui_2d_get_pixel(95, 250) == 0x00FF0000, "SHAPE_PIE", ui_2d_get_pixel(95, 250), 0);
    ui_2d_shape_heart(250, 250, 50);
    chk(ui_2d_get_pixel(250, 250) == 0x00FF0000, "SHAPE_HEART", ui_2d_get_pixel(250, 250), 0);
    pts[0] = 20;  pts[1] = 240;
    pts[2] = 120; pts[3] = 240;
    pts[4] = 120; pts[5] = 300;
    pts[6] = 20;  pts[7] = 300;
    ui_2d_shape_poly(pts, 4, 1);
    chk(ui_2d_get_pixel(60, 270) == 0x00FF0000, "SHAPE_POLY", ui_2d_get_pixel(60, 270), 0);
    ui_2d_shape_path("M200 240 L280 240 L280 300 L200 300 Z");
    chk(ui_2d_get_pixel(240, 270) == 0x00FF0000, "SHAPE_PATH", ui_2d_get_pixel(240, 270), 0);
    /* 圆环是**填充**刷子（实测）：带宽里有墨、中心洞留空 */
    /* The ring uses the **fill** brush (measured): ink in the band, hole in the middle */
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_shape_ring(250, 180, 50, 25);
    chk(ui_2d_get_pixel(250, 215) == 0x00FF0000, "SHAPE_RING_BAND", ui_2d_get_pixel(250, 215), 0);
    chk(ui_2d_get_pixel(250, 180) == 0, "SHAPE_RING_HOLE", ui_2d_get_pixel(250, 180), 0);
    /* 画笔刷子：描边色由 STYLE_PEN 决定（不是填充色） */
    /* Pen brush: the stroke colour comes from STYLE_PEN (not the fill colour) */
    r = ui_brush_solid(VML_COLOR_GREEN);
    ui_brush_set_pen(r, 6, 0, 0, 0);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_shape_line(20, 60, 200, 60);
    chk(ui_2d_get_pixel(100, 60) == 0x00008000, "SHAPE_LINE_PEN", ui_2d_get_pixel(100, 60), 0);
    /* REVERSE：形状外必须干净 */
    /* REVERSE: outside the shape must stay clean */
    chk(ui_2d_get_pixel(100, 90) == 0, "SHAPE_OUTSIDE", ui_2d_get_pixel(100, 90), 0);
    ui_brush_reset();

    /* ══════════════════════════════════════════════════════════
     * H. 文字
     * H. Text
     * ══════════════════════════════════════════════════════════ */
    touch(528);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_text(10, 10, "Hello", VML_COLOR_WHITE, 20, VML_ANCHOR_LEFT);
    n = 0;
    for (i = 0; i < 400; i++) {
        if (ui_2d_get_pixel(6 + (i % 100), 6 + (i / 100) * 8) != 0) { n = n + 1; }
    }
    chk(n > 0, "TEXT_INK", n, 0);
    /* REVERSE：清屏之后必须一点墨都没有（同一块区域） */
    /* REVERSE: after clearing there must be no ink at all (same area) */
    ui_2d_clear(VML_COLOR_BLACK);
    n = 0;
    for (i = 0; i < 400; i++) {
        if (ui_2d_get_pixel(6 + (i % 100), 6 + (i / 100) * 8) != 0) { n = n + 1; }
    }
    chk(n == 0, "TEXT_CLEARED", n, 0);

    ui_2d_text_styled(10, 10, "Bold", VML_COLOR_WHITE, 24, VML_ANCHOR_LEFT, VML_FONT_BOLD);
    n = 0;
    for (i = 0; i < 400; i++) {
        if (ui_2d_get_pixel(6 + (i % 100), 6 + (i / 100) * 10) != 0) { n = n + 1; }
    }
    chk(n > 0, "TEXT_STYLED", n, 0);

    /* 竖对齐：中档要把字放在 y 上下两侧（只看有没有墨） */
    /* Vertical alignment: the middle setting puts ink on both sides of y (only checking there is ink) */
    touch(581);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_text_v(200, 120, "Mid", VML_COLOR_WHITE, 24, VML_ANCHOR_CENTER, VML_VANCHOR_MIDDLE, 0);
    n = 0;
    for (i = 0; i < 600; i++) {
        if (ui_2d_get_pixel(150 + (i % 100), 90 + (i / 100) * 10) != 0) { n = n + 1; }
    }
    chk(n > 0, "TEXT_VALIGN", n, 0);

    /* 状态式：set_font + text_cur（#532 / #533） */
    /* Stateful: set_font + text_cur (#532 / #533) */
    touch(532); touch(533);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_text_set_font(20, 0, VML_COLOR_WHITE, VML_ANCHOR_LEFT);
    touch(586);
    ui_text_set_valign(VML_VANCHOR_TOP);
    ui_2d_text_cur(10, 10, "Cur");
    n = 0;
    for (i = 0; i < 300; i++) {
        if (ui_2d_get_pixel(6 + (i % 100), 6 + (i / 100) * 10) != 0) { n = n + 1; }
    }
    chk(n > 0, "TEXT_CUR", n, 0);

    /* ══════════════════════════════════════════════════════════
     * I. 图像 / 图块 / 填充 / 截图
     * I. Images / blocks / flood fill / screenshot
     * ══════════════════════════════════════════════════════════ */
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_rect(100, 100, 20, 20, VML_COLOR_RED, 1, 0, 0);
    touch(584);
    h = ui_2d_get_image(100, 100, 20, 20);
    chk(h >= 1, "IMG_GET", h, 0);
    /* 资源计数：图像是宿主级表（what=1），0 -> 1 -> 0 */
    /* Resource counts: images are a host-level table (what=1), 0 -> 1 -> 0 */
    chk(ui_res_get_count(1) == 1, "RES_IMAGES", ui_res_get_count(1), 1);
    chk(ui_res_get_count(999) == -1, "RES_UNKNOWN", ui_res_get_count(999), -1);
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_2d_get_pixel(105, 105) == 0, "IMG_CLEARED", ui_2d_get_pixel(105, 105), 0);
    touch(585);
    chk(ui_2d_put_image(100, 100, h, 0) == 1, "IMG_PUT", 1, 0);
    chk(ui_2d_get_pixel(105, 105) == 0x00FF0000, "IMG_RESTORED", ui_2d_get_pixel(105, 105), 0);
    touch(594);
    chk(ui_2d_free_image(h) == 1, "IMG_FREE", 1, 0);
    /* REVERSE：同一个句柄不能再释放一次 */
    /* REVERSE: the same handle cannot be freed twice */
    chk(ui_2d_free_image(h) == 0, "IMG_FREE_TWICE", ui_2d_free_image(h), 0);
    chk(ui_res_get_count(1) == 0, "RES_IMAGES_FREED", ui_res_get_count(1), 0);

    /* XOR 贴图：贴两次必须回到原样（异或的逆运算就是自己） */
    /* XOR blit: pasting twice must restore the original (xor is its own inverse) */
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_rect(50, 50, 20, 20, VML_COLOR_RED, 1, 0, 0);
    h = ui_2d_get_image(50, 50, 20, 20);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_put_image(50, 50, h, 1);
    chk(ui_2d_get_pixel(55, 55) == 0x00FF0000, "IMG_XOR_ON", ui_2d_get_pixel(55, 55), 0);
    ui_2d_put_image(50, 50, h, 1);
    chk(ui_2d_get_pixel(55, 55) == 0, "IMG_XOR_OFF", ui_2d_get_pixel(55, 55), 0);
    ui_2d_free_image(h);

    /* 矢量图块：录制 -> 贴（左上角）/ 贴（中心）-> 释放 */
    /* Vector blocks: record -> paste (top-left) / paste (centre) -> free */
    ui_2d_clear(VML_COLOR_BLACK);
    touch(589);
    r = ui_2d_create_block(20, 20, 0);
    chk(r >= 1, "BLOCK_CREATE", r, 0);
    ui_2d_rect(0, 0, 20, 20, VML_COLOR_GREEN, 1, 0, 0);
    h = ui_2d_end_block();
    chk(h >= 1, "BLOCK_END", h, 0);
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_2d_draw_block_at(h, 100, 100, 1000, 1000, 0) == 1, "BLOCK_DRAW_AT", 1, 0);
    chk(ui_2d_get_pixel(105, 105) == 0x00008000, "BLOCK_AT_PIXEL", ui_2d_get_pixel(105, 105), 0);
    ui_2d_clear(VML_COLOR_BLACK);
    chk(ui_2d_draw_block(h, 200, 200, 1000, 1000, 0) == 1, "BLOCK_DRAW_CENTER", 1, 0);
    chk(ui_2d_get_pixel(200, 200) == 0x00008000, "BLOCK_CENTER_PIXEL", ui_2d_get_pixel(200, 200), 0);
    chk(ui_2d_free_block(h) == 1, "BLOCK_FREE", 1, 0);
    /* REVERSE：释放之后贴不上去；再 end 一次也是 0 */
    /* REVERSE: after freeing it cannot be pasted; another end is 0 too */
    chk(ui_2d_draw_block_at(h, 100, 100, 1000, 1000, 0) == 0, "BLOCK_FREED", ui_2d_draw_block_at(h, 100, 100, 1000, 1000, 0), 0);
    chk(ui_2d_end_block() == 0, "BLOCK_END_IDLE", ui_2d_end_block(), 0);

    /* 洪水填充：边界色要 **0xAARRGGBB**（见文件头那一段实测） */
    /* Flood fill: the border colour must be **0xAARRGGBB** (see the measurement at the top of this file) */
    touch(583);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_rect(10, 10, 41, 41, VML_COLOR_GREEN, 0, 4, 0);
    n = ui_2d_flood_fill(30, 30, VML_COLOR_RED, 0xFF008000);
    chk(n > 0, "FLOOD_RUNS", n, 0);
    chk(ui_2d_get_pixel(30, 30) == 0x00FF0000, "FLOOD_IN", ui_2d_get_pixel(30, 30), 0);
    /* REVERSE：边界自己不能被覆盖、框外不能被灌 */
    /* REVERSE: the border itself must not be covered, and the outside must not be flooded */
    chk(ui_2d_get_pixel(200, 200) == 0, "FLOOD_OUT", ui_2d_get_pixel(200, 200), 0);
    chk(ui_2d_get_pixel(11, 30) == 0x00008000, "FLOOD_BORDER", ui_2d_get_pixel(11, 30), 0);

    /* QBasic 手打位图：8x1、平面 0 全 1 ⇒ 调色板索引 1；调色板要**带 alpha** 才画得出来 */
    /* QBasic hand-packed bitmap: 8x1, plane 0 all ones => palette index 1; the palette needs **alpha** to draw */
    {
        int qb[8];
        int pal[16];
        qb[0] = 8 | (1 << 16);
        qb[1] = -1;
        qb[2] = 0;
        qb[3] = 0;
        qb[4] = 0;
        pal[0] = (int)0xFF000000u;
        pal[1] = (int)0xFF00FF00u;
        ui_2d_clear(VML_COLOR_BLACK);
        ui_2d_put_qb_bitmap(10, 10, qb, pal, 1, 0);
        chk(ui_2d_get_pixel(12, 10) == 0x0000FF00, "QB_BITMAP", ui_2d_get_pixel(12, 10), 0);
    }

    /* 截屏：正常路径 > 0 字节；带 ".." 的路径必须 -1（沙箱边界） */
    /* Screenshot: a normal path > 0 bytes; a path with ".." must be -1 (sandbox boundary) */
    touch(588);
    n = ui_scr_screenshot("shot/ui_all.png");
    chk(n > 0, "SHOT", n, 0);
    chk(ui_scr_screenshot("../ui_all_evil.png") == -1, "SHOT_BAD_PATH", ui_scr_screenshot("../ui_all_evil.png"), -1);

    /* ══════════════════════════════════════════════════════════
     * J. 存储 / 剪贴板 / 错误槽 / 时间 / 随机 / 网格 / 棋子 / 参数
     * J. Store / clipboard / error slot / time / random / grid / pieces / args
     * ══════════════════════════════════════════════════════════ */
    touch(550);
    chk(ui_store_set("ui_all_k", "v1") == 0, "STORE_SET", 0, 0);
    buf[0] = 0;
    n = ui_store_get("ui_all_k", buf, 128);
    chk(n == 2 && has(buf, "v1"), "STORE_GET", n, 0);
    chk(ui_store_del("ui_all_k") == 0, "STORE_DEL", 0, 0);
    /* REVERSE：删掉之后读回来必须是 -1（不能还是上一次的值） */
    /* REVERSE: after deleting, reading back must be -1 (not the previous value) */
    chk(ui_store_get("ui_all_k", buf, 128) == -1, "STORE_GONE", ui_store_get("ui_all_k", buf, 128), -1);

    touch(542);
    n = ui_clipboard_set("hello");
    if (n == 1) {
        buf[0] = 0;
        r = ui_clipboard_get(buf, 128);
        chk(r == 5 && has(buf, "hello"), "CLIPBOARD", r, 0);
    } else {
        unimpl("CLIPBOARD", n);
    }

    touch(596); touch(597);
    chk(ui_error_get_code() == VML_E_OK, "ERROR_OK", ui_error_get_code(), 0);
    chk(ui_error_get_message(buf, 128) == 0, "ERROR_MSG_EMPTY", ui_error_get_message(buf, 128), 0);

    /* 失败之后错误槽必须真的有东西（读不到文件的音频 = VML_E_FAILED） */
    /* After a failure the error slot must really hold something (audio file that does not exist = VML_E_FAILED) */
    touch(541);
    r = ui_audio_play("no-such-file.wav", 0);
    chk(r == -1, "AUDIO_BAD_RC", r, -1);
    chk(ui_error_get_code() == VML_E_FAILED, "ERROR_CODE", ui_error_get_code(), VML_E_FAILED);
    n = ui_error_get_message(buf, 0);
    chk(n > 0, "ERROR_MSG_LEN", n, 0);

    /* 时间：等 60ms 之后读数必须真的前进（不是墙钟冻结） */
    /* Time: after 60ms the reading must really advance (the clock is not frozen) */
    r = ui_time_get_ms();
    wait_ms(60);
    n = ui_time_get_ms();
    chk(n - r >= 30, "TIME_ADVANCE", n - r, 0);

    /* 随机：20 次都要落在 0..9；n<=0 一律 0 */
    /* Random: 20 draws must all land in 0..9; n<=0 always returns 0 */
    r = 1;
    for (i = 0; i < 20; i++) {
        n = ui_math_rand(10);
        if (n < 0 || n >= 10) { r = 0; }
    }
    chk(r == 1, "RAND_RANGE", r, 1);
    chk(ui_math_rand(0) == 0 && ui_math_rand(-5) == 0, "RAND_ZERO", ui_math_rand(0), ui_math_rand(-5));

    /* 网格与棋子：都是"存进去能读回来"的模型接口 */
    /* Grid and pieces: model interfaces where "store then read back" must round-trip */
    ui_grid_clear();
    chk(ui_grid_get(0) == 0, "GRID_CLEAR", ui_grid_get(0), 0);
    ui_grid_set(3, 42);
    chk(ui_grid_get(3) == 42, "GRID_SET", ui_grid_get(3), 42);
    /* REVERSE：越界读 0（不是 -1、不是崩） */
    /* REVERSE: out-of-range reads 0 (not -1, no crash) */
    chk(ui_grid_get(9999) == 0, "GRID_OOB", ui_grid_get(9999), 0);
    ui_piece_init();
    r = 1;
    for (i = 0; i < 4; i++) {
        n = ui_piece_get_cell(0, 0, i);
        if (n < 0 || n > 255) { r = 0; }
    }
    chk(r == 1, "PIECE_CELLS", ui_piece_get_cell(0, 0, 0), ui_piece_get_cell(0, 0, 1));
    chk(ui_piece_get_cell(99, 0, 0) == -1, "PIECE_BAD", ui_piece_get_cell(99, 0, 0), -1);

    /* 参数：arg 0 是程序自己的路径（桌面实测 = 源文件名），后面才是 --arg */
    /* Args: arg 0 is the program's own path (measured on the desktop = the source file name); --arg follows */
    touch(556); /* 参数口与触摸查询共用号段，这里只记"用过宿主信息类接口" */
                 /* the arg port shares a band with touch query; recorded as a host-info interface */
    r = ui_arg_get_count();
    chk(r >= 1, "ARG_COUNT", r, 0);
    buf[0] = 0;
    if (r >= 1) { ui_arg_get(0, buf, 128); }
    chk(buf[0] != 0, "ARG0", buf[0], 0);

    /* JSON 通道：echo / text / pixel / 未知函数 */
    /* JSON channel: echo / text / pixel / unknown function */
    buf[0] = 0;
    n = ui_call_json("echo", "{\"a\":123}", buf, 256);
    chk(n > 0 && has(buf, "\"a\":123") && has(buf, "\"ok\":true"), "JSON_ECHO", n, 0);
    buf[0] = 0;
    n = ui_call_json("text", "{\"s\":\"HELLO\",\"size\":16}", buf, 256);
    chk(n > 0 && has(buf, "\"w\":40") && has(buf, "\"h\":16"), "JSON_TEXT", n, 0);
    /* 中日韩是**全角**：2 个字 × 20 号 = 40 宽（与半角同宽不同高） */
    /* CJK is **full width**: 2 chars x size 20 = 40 wide */
    buf[0] = 0;
    n = ui_call_json("text", "{\"s\":\"\xE4\xB8\xAD\xE6\x96\x87\",\"size\":20}", buf, 256);
    chk(n > 0 && has(buf, "\"w\":40") && has(buf, "\"h\":20"), "JSON_TEXT_CJK", n, 0);
    ui_2d_clear(VML_COLOR_BLACK);
    ui_2d_pixel(4, 6, VML_COLOR_RED);
    buf[0] = 0;
    n = ui_call_json("pixel", "{\"x\":4,\"y\":6}", buf, 256);
    chk(n > 0 && has(buf, "\"rgb\":16711680"), "JSON_PIXEL", n, 0);
    /* REVERSE：认不出的函数要回 `ok:false` 的信封，不是崩溃/空串 */
    /* REVERSE: an unknown function must return an `ok:false` envelope, not a crash or empty string */
    buf[0] = 0;
    n = ui_call_json("no_such_fn", "{}", buf, 256);
    chk(n > 0 && has(buf, "\"ok\":false"), "JSON_UNKNOWN", n, 0);
    /* 不求缓冲区的那条路（给拿不到指针的语言用） */
    /* The no-buffer variant (for languages that cannot obtain a pointer) */
    n = ui_call_json_s("version", "{}");
    chk(n > 0 && ui_call_json_get_len() == n, "JSON_S", n, ui_call_json_get_len());

    /* ══════════════════════════════════════════════════════════
     * K. 音频（有后端才验；没有就 UNIMPL）
     * K. Audio (verify when a backend exists; UNIMPL otherwise)
     * ══════════════════════════════════════════════════════════ */
    r = ui_tone_on(0, 69, 100);
    if (r == 0) {
        chk(ui_tone_get_voices() >= 1, "TONE_VOICES", ui_tone_get_voices(), 0);
        chk(ui_tone_off(0, 69) == 0, "TONE_OFF", 0, 0);
        chk(ui_tone_get_voices() == 0, "TONE_SILENT", ui_tone_get_voices(), 0);
    } else {
        unimpl("TONE", r);
    }
    ui_sfx_reset();
    chk(ui_sfx_get_active() == 0, "SFX_EMPTY", 0, 0);
    ui_sfx_add(0, 64, 0, 4, 100, VML_WAVE_SINE);
    chk(ui_sfx_get_active() == 1, "SFX_ADD", ui_sfx_get_active(), 1);
    ui_sfx_panic();
    /* REVERSE：panic 之后表必须清空（不是"还在响但没人管"） */
    /* REVERSE: after panic the table must be empty (not "still sounding, unattended") */
    chk(ui_sfx_get_active() == 0, "SFX_PANIC", ui_sfx_get_active(), 0);

    /* ══════════════════════════════════════════════════════════
     * L. 传感器 / 电池 / 定位（按"这一端有没有"分别验）
     * L. Sensors / battery / location (verified per "does this end have it")
     * ══════════════════════════════════════════════════════════ */
    touch(554);
    r = ui_sensor_is_available(VML_SENS_ACCEL);
    if (r == 1) {
        chk(ui_sensor_fetch(VML_SENS_ACCEL) == 1, "SENSOR_FETCH", 1, 0);
        /* 静止时读到的应当是重力（|z| 接近 1000 毫克），至少必须是**非零整数** */
        /* At rest it should read gravity (|z| near 1000 milligee), or at least a non-zero integer */
        chk(ui_sensor_get_z() != 0 || ui_sensor_get_x() != 0 || ui_sensor_get_y() != 0, "SENSOR_Z",
            ui_sensor_get_z(), 0);
    } else {
        /* 没有传感器的设备：read 必须回 0（**不能**冒充"读到 0"） */
        /* A device with no sensor: read must return 0 (**must not** pretend it read 0) */
        chk(ui_sensor_read(VML_SENS_ACCEL, msg) == 0, "SENSOR_ABSENT", 0, 0);
        unimpl("SENSOR", r);
    }

    touch(540);
    r = ui_battery_fetch();
    if (r == 1) {
        n = ui_battery_get_level();
        chk(n >= 0 && n <= 100, "BATTERY_LEVEL", n, 0);
        chk(ui_battery_is_charging() == 0 || ui_battery_is_charging() == 1, "BATTERY_CHARGING", ui_battery_is_charging(), 0);
        chk(ui_power_is_saving() == 0 || ui_power_is_saving() == 1, "POWER_SAVER", ui_power_is_saving(), 0);
    } else {
        /* 没有电池：电量必须是 0（**不能**冒充 100） */
        /* No battery: the level must be 0 (**must not** pretend 100) */
        chk(ui_battery_get_level() == 0, "BATTERY_ABSENT", ui_battery_get_level(), 0);
        unimpl("BATTERY", r);
    }

    touch(555);
    r = ui_gps_is_available();
    if (r == 1) {
        chk(ui_gps_fetch(1000) == 1, "GPS_FETCH", 1, 0);
        chk(ui_gps_get_lat_e6() != 0 && ui_gps_get_lon_e6() != 0, "GPS_COORD", ui_gps_get_lat_e6(), ui_gps_get_lon_e6());
    } else {
        /* 没有定位：fetch 必须回 0（不是 -1，也不是旧坐标） */
        /* No location: fetch must return 0 (not -1, not a stale coordinate) */
        chk(ui_gps_fetch(200) == 0, "GPS_ABSENT", 0, 0);
        unimpl("GPS", r);
    }

    /* ══════════════════════════════════════════════════════════
     * M. 关窗与"关窗之后"的状态
     * M. Close the window and check the state afterwards
     * ══════════════════════════════════════════════════════════ */
    touch(521);
    chk(ui_win_close() == 0, "WIN_CLOSE", 0, 0);
    chk(ui_win_is_closed() == 1, "WIN_CLOSED_AFTER", ui_win_is_closed(), 1);

    /* ══════════════════════════════════════════════════════════
     * 汇总（NUMS = 真的碰到几个接口号）
     * Summary (NUMS = how many interface numbers were really touched)
     * ══════════════════════════════════════════════════════════ */
    printf("OK=%d FAIL=%d UNIMPL=%d NUMS=%d\n", g_ok, g_fail, g_unimpl, g_nused);
    printf("DONE=1\n");
    return 0;
}
