hf_repo4 / tools /logic_harness.cpp
fava21's picture
Backup: patch pack applied + verified on Win11 22000 (d446cc1, ba8617e, dcf5cb8)
2edf277 verified
Raw History Blame Contribute Delete
32.4 kB
// FCS Glass - portable logic test harness (runs on ANY machine, no Windows needed)
//
// The tested functions are EXTRACTED VERBATIM from the repo sources at build
// time by tools/extract_logic.py into generated_logic.inc. If the repo logic
// changes, the tests run against the new bytes. This file only provides the
// minimal shims (COLORREF/DWORD/mock COM) and the assertions.
//
// Build & run: tools/run_logic_tests.sh
// Results are appended to BUGS.md "Verification log" by the caller.
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <string>
#include <unordered_map>
#include <vector>
// --- minimal Win32-ish shims for the extracted logic ------------------------
using DWORD = uint32_t;
using COLORREF = DWORD;
using HRESULT = long;
// Compile-only shims for the MSVC-only bits inside ComPtr::QueryInto.
// The tested subset (refcount/move/attach/swap/reset) never calls them.
constexpr HRESULT kShimEPointer = 0x8000400EL;
#define E_POINTER kShimEPointer
#define __uuidof(x) (0)
// Mock IUnknown for the ComPtr tests.
struct MockUnknown {
long refs = 1; // starts alive, as COM factories return
unsigned long AddRef() { return static_cast<unsigned long>(++refs); }
unsigned long Release() { return static_cast<unsigned long>(--refs); }
long QueryInterface(void*, void**) { return -1; } // unused here
};
// fcs::Detail::ReportFailure is referenced by nothing we extract; ComPtr
// doesn't need it. But CoCreate does - not extracted, fine.
// --- extracted logic under test ---------------------------------------------
#include "generated_logic.inc"
// The extracted ComPtr sits in whatever namespace the source had (fcs).
// Extracted verbatim: it was inside `namespace fcs { ... }`, so re-open one.
namespace fcs {}
using namespace fcs;
// --- tiny test framework -----------------------------------------------------
static int g_pass = 0, g_fail = 0;
#define CHECK(cond) \
do { \
if (cond) { \
++g_pass; \
std::printf(" PASS %s:%d %s\n", __FILE__, __LINE__, #cond); \
} else { \
++g_fail; \
std::printf(" FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \
} \
} while (0)
static void T01_T02_BlockContrast() {
std::printf("T-01/T-02 BlockContrast (from blur_measure.cpp)\n");
// Hard 8px checkerboard: half 0, half 255 luma -> std dev 127.5 -> 0.5
std::vector<uint8_t> cb(128 * 128 * 4, 0);
for (int y = 0; y < 128; ++y) {
for (int x = 0; x < 128; ++x) {
const bool light = (((x / 8) + (y / 8)) & 1) == 0;
const uint8_t v = light ? 255 : 0;
uint8_t* p = &cb[(static_cast<size_t>(y) * 128 + x) * 4];
p[0] = p[1] = p[2] = v; // BGRA, achromatic
p[3] = 255;
}
}
const double c = BlockContrast(cb.data(), 128, 128);
std::printf(" checkerboard contrast = %.6f (expect 0.5000)\n", c);
CHECK(std::fabs(c - 0.5) < 1e-9);
std::vector<uint8_t> grey(64 * 64 * 4, 128);
const double g = BlockContrast(grey.data(), 64, 64);
std::printf(" uniform grey contrast = %.6f (expect 0.0000)\n", g);
// Repo claim (D-21) is "EXACTLY 0.0000" at 4 decimals; the sum2-mean
// variance path carries ~5e-9 FP noise; the 4-decimal claim holds.
std::printf(" uniform grey contrast = %.17g\n", g);
CHECK(g < 1e-6); // measured noise 5.3e-9; 4-decimal claim holds
}
static void T03_BlockContrast_Mixed() {
std::printf("T-03 BlockContrast half/half block == 0.2500\n");
// 2x2 px: two 128s and two 0s -> luma std dev = 64 -> 64/255 = 0.25098...
std::vector<uint8_t> px(2 * 2 * 4, 0);
px[0] = px[1] = px[2] = 128;
px[4 + 0] = px[4 + 1] = px[4 + 2] = 0;
px[8 + 0] = px[8 + 1] = px[8 + 2] = 128;
px[12 + 0] = px[12 + 1] = px[12 + 2] = 0;
const double c = BlockContrast(px.data(), 2, 2);
std::printf(" mixed contrast = %.6f (expect 0.250980)\n", c);
CHECK(std::fabs(c - (64.0 / 255.0)) < 1e-9);
}
static void T04_DpToPx() {
std::printf("T-04 DpToPx round-half-up at several scales\n");
CHECK(DpToPx(46.0f, 1.0f) == 46);
CHECK(DpToPx(46.5f, 1.0f) == 47); // 0.5 rounds UP
CHECK(DpToPx(10.0f, 1.5f) == 15); // 15.0
CHECK(DpToPx(10.5f, 1.5f) == 16); // 15.75 -> 16
CHECK(DpToPx(32.0f, 2.0f) == 64);
CHECK(DpToPx(0.4f, 1.0f) == 0); // 0.4 stays 0 (not -0)
// BUG-30. Every case above is non-negative, which is exactly why the
// truncation bug survived: `static_cast<int>((dp*scale) + 0.5f)` truncates
// TOWARD ZERO, so it only rounds correctly for dp >= 0. These three each came
// out one pixel high. Negative dp is a real layout input (a rect origin left
// of its parent, a negative inset), so the rounding is now floored.
CHECK(DpToPx(-0.6f, 1.0f) == -1); // was 0
CHECK(DpToPx(-1.4f, 1.0f) == -1); // was 0
CHECK(DpToPx(-2.4f, 1.0f) == -2); // was -1
CHECK(DpToPx(-0.5f, 1.0f) == 0); // exact half rounds toward +infinity
CHECK(DpToPx(-1.5f, 1.0f) == -1);
}
static void T05_ContentScale() {
std::printf("T-05 ContentScaleForWidthDp band + clamps\n");
CHECK(ContentScaleForWidthDp(1280.0f) == 1.0f); // inside band
CHECK(ContentScaleForWidthDp(960.0f) == 1.0f); // band edge
CHECK(ContentScaleForWidthDp(1600.0f) == 1.0f); // band edge
const float narrow = ContentScaleForWidthDp(480.0f); // 0.5 -> clamped 0.85
CHECK(std::fabs(narrow - 0.85f) < 1e-6f);
const float wide = ContentScaleForWidthDp(3200.0f); // 2.0 -> clamped 1.25
CHECK(std::fabs(wide - 1.25f) < 1e-6f);
CHECK(ContentScaleForWidthDp(0.0f) == 1.0f); // degenerate input
CHECK(ContentScaleForWidthDp(-5.0f) == 1.0f);
}
static void T06_DialToAlpha() {
std::printf("T-06 DialToAlpha endpoints + midpoint (B2)\n");
// floors: decorative 0.12, text floor 0.58
CHECK(std::fabs(DialToAlpha(0.0f, 0.12f, 0.58f) - 0.12f) < 1e-6f);
CHECK(std::fabs(DialToAlpha(1.0f, 0.12f, 0.58f) - 0.58f) < 1e-6f);
CHECK(std::fabs(DialToAlpha(0.5f, 0.12f, 0.58f) - 0.35f) < 1e-6f);
// clamped outside [0,1]
CHECK(std::fabs(DialToAlpha(-3.0f, 0.12f, 0.58f) - 0.12f) < 1e-6f);
CHECK(std::fabs(DialToAlpha(9.0f, 0.12f, 0.58f) - 0.58f) < 1e-6f);
}
static void T07_ToColorRef() {
std::printf("T-07 ToColorRef ARGB->COLORREF (BBGGRR)\n");
// 0xAARRGGBB -> 0x00BBGGRR
CHECK(ToColorRef(0xFF293847u) == 0x00473829u); // R41 G56 B71 -> B71 G56 R41
CHECK(ToColorRef(0x00000000u) == 0x00000000u);
CHECK(ToColorRef(0x00FFFFFFu) == 0x00FFFFFFu);
CHECK(ToColorRef(0x00102030u) == 0x00302010u); // R16 G32 B48
}
static void T08_SelectTier() {
std::printf("T-08 SelectTier decision table (B5)\n");
TierInputs in;
auto row = [&](DWORD build, bool has_c, double contrast, bool remote,
bool warp, bool transparency_off, bool t_known, bool hc,
BackdropTier want, const char* tag) {
in.build = build;
in.has_contrast = has_c;
in.checker_contrast = contrast;
in.session = remote ? SessionKind::Remote : SessionKind::Console;
in.warp_only = warp;
in.transparency_effects = !transparency_off;
in.transparency_known = t_known;
in.high_contrast = hc;
const TierDecision d = SelectTier(in);
const bool ok = (d.tier == want);
std::printf(" %-34s want %s got %s (%s)\n", tag, TierName(want),
TierName(d.tier), d.reason);
CHECK(ok);
};
using T = BackdropTier;
// environment vetoes first
row(26200, true, 0.10, false, false, true, true, false, T::C, "transparency off -> C");
row(26200, true, 0.10, true, false, false, true, false, T::C, "remote session -> C");
row(26200, true, 0.10, false, true, false, true, false, T::C, "WARP -> C");
row(26200, true, 0.10, false, false, false, true, true, T::C, "high contrast -> C");
// unmeasurable -> conservative C
row(26200, false, 1.0, false, false, false, true, false, T::C, "no measurement -> C");
// tier A gate: build >= 22621 + blur present (contrast < 0.35)
row(26200, true, 0.10, false, false, false, true, false, T::A, "A: build + blur");
row(26200, true, 0.50, false, false, false, true, false, T::C, "A-gate, no blur -> C");
// tier B gate: 17134 <= build < 22621
row(19045, true, 0.10, false, false, false, true, false, T::B, "B: build + blur");
row(19045, true, 0.50, false, false, false, true, false, T::C, "B-gate, no blur -> C");
// pre-1803
row(16299, true, 0.10, false, false, false, true, false, T::C, "pre-1803 -> C");
}
static void T09_JsonEscape() {
std::printf("T-09 JsonEscape control chars\n");
CHECK(JsonEscape("plain") == "plain");
CHECK(JsonEscape("a\"b") == "a\\\"b");
CHECK(JsonEscape("a\\b") == "a\\\\b");
CHECK(JsonEscape("a\nb") == "a\\nb");
CHECK(JsonEscape("a\tb") == "a\\tb");
// NOTE: "\x01b" would be ONE char (0x1B) - hex escapes eat hex digits.
CHECK(JsonEscape(std::string("a\x01" "b")) == "a\\u0001b");
CHECK(JsonEscape("a\rb") == "ab"); // \r dropped per the implementation
}
static void T10_ComPtr() {
std::printf("T-10 ComPtr refcount/move/attach (mock COM)\n");
{
ComPtr<MockUnknown> a;
CHECK(!a);
{
MockUnknown* raw = new MockUnknown(); // refs == 1
a.Attach(raw); // adopt
CHECK(a.Get() == raw);
CHECK(raw->refs == 1); // no extra ref taken
a.Get()->AddRef(); // refs == 2
ComPtr<MockUnknown> b = std::move(a);
CHECK(!a); // source emptied
CHECK(b.Get() && b.Get()->refs == 2);
} // b destructs -> refs == 1
// (raw intentionally leaks 1 ref here; the object outlives the check below)
}
{
// Reset releases exactly once.
MockUnknown* raw = new MockUnknown();
ComPtr<MockUnknown> c;
c.Attach(raw);
c.Get()->AddRef(); // 2
c.Reset(); // 1
CHECK(raw->refs == 1);
c.Reset(); // no-op: ptr_ already null (NO double release)
CHECK(raw->refs == 1); // correct ComPtr: second Reset does nothing
raw->Release(); // reach refs == 0 explicitly (c is empty now)
CHECK(raw->refs == 0);
delete raw;
}
{
// Swap non-template form.
ComPtr<MockUnknown> x, y;
MockUnknown* mo = new MockUnknown();
x.Attach(mo);
x.Swap(y);
CHECK(!x && y.Get() == mo);
y.Reset();
delete mo;
}
{
// Move assignment self-assignment guard.
ComPtr<MockUnknown> m1;
MockUnknown* mo = new MockUnknown();
m1.Attach(mo);
m1.Get()->AddRef(); // 2
ComPtr<MockUnknown>& alias = m1;
alias = std::move(m1); // must not release-then-adopt dangling
CHECK(m1.Get() == mo);
CHECK(mo->refs == 2);
m1.Reset(); // 1
CHECK(mo->refs == 1);
m1.Reset(); // 0
delete mo;
}
}
static void T11_P95IndexSafety() {
std::printf("T-11 ReportStats p95 index stays in bounds\n");
// The exact repo expression (see kP95Expr, extracted verbatim).
bool all_ok = true;
for (size_t n = 1; n <= 400; ++n) {
std::vector<double> samples(n, 0.0);
const size_t idx = static_cast<size_t>(static_cast<double>(samples.size()) * 0.95);
if (idx >= samples.size()) { all_ok = false; break; }
(void)samples[idx]; // in-bounds for every n tested
}
CHECK(all_ok);
std::printf(" expression: %s\n", kP95Expr ? kP95Expr : "(missing)");
}
static void T12_ThresholdsSanity() {
std::printf("T-12 threshold constants sane\n");
CHECK(kMinDropMargin > 0.0 && kMinDropMargin < 1.0);
CHECK(kBlurContrastThreshold > 0.0 && kBlurContrastThreshold < 1.0);
CHECK(kBlurContrastThreshold > kMinDropMargin / 4.0); // decider above noise floor
}
// T-13 (A2, M1): dp -> whole physical pixels, round half up, at the six scale
// factors A2 names, and SnapPx must agree with DpToPx everywhere.
static void T13_SnapPx() {
std::printf("T-13 A2 SnapPx: six scale factors, negative dp, agrees with DpToPx\n");
const float kScales[] = {1.0f, 1.25f, 1.5f, 1.75f, 2.0f, 2.5f};
for (float s : kScales) {
// 8 dp is the window radius - the most-used value in the project.
const int snapped = fcs::core::SnapPx(8.0f, s);
CHECK(snapped == static_cast<int>(std::floor(8.0f * s + 0.5f)));
// A sub-pixel dp change can never move the result by more than one pixel.
const int nudged = fcs::core::SnapPx(8.0f + 0.49f / s, s);
CHECK(nudged - snapped == 0 || nudged - snapped == 1);
}
// The input that broke DpToPx, pinned here too so the two cannot diverge.
CHECK(fcs::core::SnapPx(-0.6f, 1.0f) == -1);
CHECK(fcs::core::SnapPx(-1.4f, 1.0f) == -1);
CHECK(fcs::core::SnapPx(-2.4f, 1.0f) == -2);
// Exact halves round toward +infinity on BOTH sides.
CHECK(fcs::core::SnapPx(0.5f, 1.0f) == 1);
CHECK(fcs::core::SnapPx(-0.5f, 1.0f) == 0);
CHECK(fcs::core::SnapPx(-1.5f, 1.0f) == -1);
CHECK(fcs::core::SnapPx(0.0f, 1.5f) == 0);
// A 1 dp hairline stays 1 physical px at every scale: the one measurement
// that must NOT scale, or borders thicken as the user raises the scale.
CHECK(fcs::core::kHairlinePx == 1);
// DpToPx and SnapPx are two implementations of one rule, kept in step by
// this assertion rather than by delegation - extract_logic.py lifts bodies as
// bare text, so a body calling core::SnapPx would not resolve in the harness.
for (float s : kScales) {
for (float dp : {8.0f, 0.5f, 46.5f, -0.5f, -0.6f, -1.4f, -2.4f}) {
CHECK(DpToPx(dp, s) == fcs::core::SnapPx(dp, s));
}
}
}
// T-14 (A3, M1): the radius scale, the inner-radius clamp, and the pill rule.
static void T14_Radii() {
std::printf("T-14 A3 radius set, inner-radius clamp, pill radius\n");
const fcs::core::RadiusSet r;
CHECK(r.window_dp == 8); // 0 on Classic, which the caller sets
CHECK(r.card_dp == 8);
CHECK(r.control_dp == 4);
// An inner radius can never exceed the outer radius minus the inset, or the
// inner corner crosses the outer one and the outline self-intersects.
CHECK(fcs::core::InnerRadiusClamp(8, 2) == 6);
CHECK(fcs::core::InnerRadiusClamp(8, 8) == 0);
CHECK(fcs::core::InnerRadiusClamp(4, 8) == 0); // inset exceeds radius
CHECK(fcs::core::InnerRadiusClamp(8, -3) == 8); // negative inset = none
CHECK(fcs::core::InnerRadiusClamp(-1, 0) == 0); // never negative
// A pill is height/2, and ONLY for chips and toggles - hence the flag.
CHECK(fcs::core::PillRadiusPx(24, true) == 12);
CHECK(fcs::core::PillRadiusPx(24, false) == 0);
CHECK(fcs::core::PillRadiusPx(1, true) == 0); // half a pixel is no pill
CHECK(fcs::core::PillRadiusPx(0, true) == 0);
CHECK(fcs::core::PillRadiusPx(-4, true) == 0);
}
// T-15 (C2, M1): the id path. The point of these is not that the hash "works"
// but the two ways it must NOT work: concatenating a path (so "ab" and a nested
// "a" -> "b" collide) and folding an index in one step (so 0..255 and 256..511
// collide). Both are silent - no crash, just two widgets sharing state.
static void T15_IdStack() {
std::printf("T-15 C2 IdStack: determinism, path separation, no underflow\n");
using fcs::core::Id;
using fcs::core::IdStack;
using fcs::core::kNullId;
CHECK(kNullId == 0);
// Empty stack.
IdStack s;
CHECK(s.depth() == 0);
CHECK(s.Current() == kNullId);
CHECK(s.Parent() == kNullId);
// Pop at the bottom is a no-op, so depth can never go negative.
s.Pop();
s.Pop();
CHECK(s.depth() == 0);
CHECK(s.Current() == kNullId);
// Determinism: same inputs, same id, every call.
CHECK(fcs::core::HashName(kNullId, "panel") == fcs::core::HashName(kNullId, "panel"));
CHECK(fcs::core::HashName(kNullId, "panel") != fcs::core::HashName(kNullId, "rail"));
// The parent participates, so the same name under two parents differs.
CHECK(fcs::core::HashName(1, "x") != fcs::core::HashName(2, "x"));
// THE property. A path is not a string: one scope named "ab" must not collide
// with a scope "a" containing a scope "b".
IdStack flat;
flat.PushName("ab");
IdStack nested;
nested.PushName("a");
nested.PushName("b");
CHECK(flat.Current() != nested.Current());
// ... and the nested one equals the explicit hash of the same path.
CHECK(nested.Current() ==
fcs::core::HashName(fcs::core::HashName(kNullId, "a"), "b"));
// The same byte stream split a different way must also differ. This is the one
// a depth-based separator would NOT catch: both paths are two levels deep and
// both spell "abc", so only the per-segment length separates them.
IdStack ab_c, a_bc;
ab_c.PushName("ab");
ab_c.PushName("c");
a_bc.PushName("a");
a_bc.PushName("bc");
CHECK(ab_c.Current() != a_bc.Current());
// Indices fold a byte at a time, so the byte boundary is not a cliff.
CHECK(fcs::core::HashIndex(kNullId, 255) != fcs::core::HashIndex(kNullId, 256));
CHECK(fcs::core::HashIndex(kNullId, 0) != fcs::core::HashIndex(kNullId, 1));
// kNullId is unreachable, so the empty-stack sentinel is unambiguous.
CHECK(fcs::core::HashName(kNullId, "") != kNullId);
CHECK(fcs::core::HashName(kNullId, "a") != kNullId);
CHECK(fcs::core::HashIndex(kNullId, 0) != kNullId);
// Parent and Pop.
const Id a = nested.Parent();
CHECK(a == fcs::core::HashName(kNullId, "a"));
nested.Pop();
CHECK(nested.Current() == a);
CHECK(nested.Parent() == kNullId);
nested.Pop();
CHECK(nested.depth() == 0);
// Beyond kMaxIdDepth, Push is a no-op rather than an overflow.
IdStack deep;
for (int i = 0; i < fcs::core::kMaxIdDepth + 10; ++i) deep.PushIndex(i);
CHECK(deep.depth() == fcs::core::kMaxIdDepth);
}
// T-16 (C2 + C3, M1): the state store, and the one-frame hover lag C3 asks for.
static void T16_StateStore() {
std::printf("T-16 C2/C3 StateStore: one-frame lag, independence, clear\n");
using fcs::core::Id;
using fcs::core::StateStore;
using fcs::core::WidgetState;
const Id a = fcs::core::HashName(fcs::core::kNullId, "a");
const Id b = fcs::core::HashName(fcs::core::kNullId, "b");
StateStore st;
// An id nobody has seen reads as a default WidgetState, not garbage - which
// is what makes a widget appearing for the first time honest.
CHECK(!st.prev(a).hovered);
CHECK(st.size() == 0);
// Frame 1: hover a.
st.BeginFrame();
st.Get(a).hovered = true;
st.Get(a).anim = 0.5f;
CHECK(st.size() == 1);
// Same frame: prev() is still empty, because there was no previous frame.
CHECK(!st.prev(a).hovered);
// Frame 2: C3's one-frame lag. prev() is what the pointer saw last frame.
st.BeginFrame();
CHECK(st.prev(a).hovered);
CHECK(st.prev(a).anim > 0.49f && st.prev(a).anim < 0.51f);
// ... and the live entry is fresh, not a carried-over copy.
CHECK(!st.Get(a).hovered);
CHECK(st.Get(a).anim == 0.0f);
// b was never hovered, and ids are independent.
CHECK(!st.prev(b).hovered);
// An id that appears in frame 3 has no frame-2 state to report.
st.BeginFrame();
const Id c = fcs::core::HashName(fcs::core::kNullId, "c");
CHECK(!st.prev(c).hovered);
st.Get(c).hovered = true;
st.BeginFrame();
CHECK(st.prev(c).hovered);
// ... and a was not hovered in that frame, so its lag has cleared.
CHECK(!st.prev(a).hovered);
// T6: a surface rebuild forgets everything, including the history - keeping
// prev_ would leave widgets reporting hover against a surface that is gone.
st.Get(a).focused = true;
st.Clear();
CHECK(st.size() == 0);
CHECK(!st.prev(a).hovered);
CHECK(!st.prev(c).hovered);
// The defaults themselves are defined values, not indeterminate ones.
const WidgetState fresh;
CHECK(!fresh.hovered && !fresh.active && !fresh.focused);
CHECK(fresh.anim == 0.0f && fresh.scroll == 0.0f);
}
// T-17 (C3 + E11): the freeze, and the drag-capture rules.
static void T17_InputFrame() {
std::printf("T-17 C3/E11 InputFrame: freeze discipline, wheel accumulation, drag cancel\n");
using fcs::core::InputFrame;
using fcs::core::Key;
InputFrame f;
f.OnMouseMove(120, 64);
f.OnMouseButton(0, true);
f.OnWheel(1);
f.OnWheel(2); // two notches in one frame are ONE scroll, accumulated
f.OnKey(Key::Tab, true);
const fcs::core::InputSnapshot& s1 = f.Snapshot();
CHECK(s1.frame == 1);
CHECK(s1.mouse_x == 120 && s1.mouse_y == 64);
CHECK(s1.MouseDown(0));
CHECK(s1.MousePressed(0)); // the EDGE, true this frame only
CHECK(!s1.MouseDown(1));
CHECK(s1.wheel == 3);
CHECK(s1.KeyDown(Key::Tab));
CHECK(s1.KeyPressed(Key::Tab));
CHECK(!s1.KeyDown(Key::Escape));
// C3: the freeze. A snapshot a widget is already reading must not change when
// the next message arrives. Note this reads s1 BEFORE the second Snapshot() -
// afterwards s1 and s2 name the same object, so this assertion could no longer
// say anything. That ordering is the whole test.
f.OnMouseMove(999, 999);
CHECK(s1.mouse_x == 120);
const fcs::core::InputSnapshot& s2 = f.Snapshot();
CHECK(s2.frame == 2);
CHECK(s2.mouse_x == 999);
CHECK(s2.wheel == 0);
// WHEEL is per-frame and accumulates to zero. But the mouse button is LEVEL,
// and Windows sends ONE WM_LBUTTONDOWN for an entire held click - so with no
// button-up it must still read down on frame 2. Reading it as released here is
// the bug that ended every drag after one frame, and it is invisible in a test
// that pairs each down with an up.
CHECK(s2.MouseDown(0));
CHECK(!s2.MousePressed(0)); // ...and the edge is one frame only
CHECK(s2.KeyDown(Key::Tab));
InputFrame g;
g.OnKey(Key::Enter, true);
CHECK(g.Snapshot().KeyPressed(Key::Enter));
g.OnKey(Key::Enter, false);
CHECK(!g.Snapshot().KeyDown(Key::Enter));
// KEY REPEAT. Windows re-sends WM_KEYDOWN ~30x/second while Tab is held; only
// the first may be an edge, or holding Tab walks the focus ring 30 entries a
// second instead of one.
InputFrame rep;
rep.OnKey(Key::Tab, true);
CHECK(rep.Snapshot().KeyPressed(Key::Tab));
rep.OnKey(Key::Tab, true);
rep.OnKey(Key::Tab, true);
const fcs::core::InputSnapshot& srep = rep.Snapshot();
CHECK(srep.KeyDown(Key::Tab));
CHECK(!srep.KeyPressed(Key::Tab));
rep.OnKey(Key::Tab, false);
CHECK(!rep.Snapshot().KeyDown(Key::Tab));
// E11: focus loss delivers NO matching key-up, so keys must be released
// explicitly or they stay down for the rest of the session.
InputFrame lost;
lost.OnKey(Key::Tab, true);
lost.OnMouseButton(0, true);
lost.ReleaseAllKeys();
lost.ReleaseAllButtons();
const fcs::core::InputSnapshot& slost = lost.Snapshot();
CHECK(!slost.KeyDown(Key::Tab));
CHECK(!slost.MouseDown(0));
// E11: a drag that ends normally.
InputFrame d;
CHECK(d.BeginDrag());
CHECK(d.drag_active());
CHECK(!d.BeginDrag()); // a second press must not orphan the first drag
CHECK(!d.Snapshot().drag_cancelled);
d.EndDrag();
CHECK(!d.drag_active());
// E11: Esc cancels, and the cancellation is visible for exactly ONE frame -
// a widget needs it long enough to react, and it must not be sticky.
InputFrame e;
e.BeginDrag();
e.OnEscape();
// Both facts belong to the SAME frame - input is per-frame, so checking the
// key three snapshots later would be checking an accumulator that has already
// been cleared.
const fcs::core::InputSnapshot& se = e.Snapshot();
CHECK(se.drag_cancelled);
CHECK(se.KeyDown(Key::Escape));
CHECK(!e.Snapshot().drag_cancelled); // one frame only, not sticky
// E11: losing the capture cancels too - another window, a UAC prompt, a
// session switch. Without this the drag keeps reporting a pointer nobody can
// move.
InputFrame c;
c.BeginDrag();
c.OnCaptureChanged();
CHECK(c.Snapshot().drag_cancelled);
InputFrame c2;
c2.OnCaptureChanged();
CHECK(!c2.Snapshot().drag_cancelled);
// Overflow is counted, not silently eaten, so a text field can explain itself.
InputFrame o;
for (int i = 0; i < fcs::core::InputSnapshot::kMaxChars + 3; ++i) o.OnCharUnit('a');
const fcs::core::InputSnapshot& so = o.Snapshot();
CHECK(so.char_count == fcs::core::InputSnapshot::kMaxChars);
CHECK(o.dropped_chars() == 3);
}
// T-18 (E11): WM_CHAR delivers UTF-16 CODE UNITS. Everything outside the BMP
// arrives as a surrogate pair in two messages. Invisible in testing unless the
// test types an emoji.
static void T18_Surrogates() {
std::printf("T-18 E11 surrogate pairs: pair, drop unpaired, never split\n");
using fcs::core::InputFrame;
// U+1F600 GRINNING FACE = high 0xD83D, low 0xDE00.
InputFrame e;
e.OnCharUnit(0xD83Du);
e.OnCharUnit(0xDE00u);
const fcs::core::InputSnapshot& se = e.Snapshot();
CHECK(se.char_count == 1);
CHECK(se.chars[0] == 0x1F600);
CHECK(e.dropped_chars() == 0);
InputFrame b;
b.OnCharUnit('A');
b.OnCharUnit('b');
const fcs::core::InputSnapshot& sb = b.Snapshot();
CHECK(sb.char_count == 2);
CHECK(sb.chars[0] == 'A' && sb.chars[1] == 'b');
// A high surrogate still pending when the frame closes was never completed -
// its partner belongs to the NEXT frame. Emitting it here would put half a
// character in this frame's text.
InputFrame h;
h.OnCharUnit(0xD83Du);
CHECK(h.Snapshot().char_count == 0);
CHECK(h.dropped_chars() == 1);
h.OnCharUnit(0x41u); // the next frame starts clean, not pairing with a stale high
const fcs::core::InputSnapshot& sh2 = h.Snapshot();
CHECK(sh2.char_count == 1 && sh2.chars[0] == 0x41);
// A low surrogate with nothing pending is orphaned.
InputFrame l;
l.OnCharUnit(0xDE00u);
CHECK(l.Snapshot().char_count == 0);
CHECK(l.dropped_chars() == 1);
// Two high surrogates in a row: whatever produced the second orphaned the first.
InputFrame d;
d.OnCharUnit(0xD83Du);
d.OnCharUnit(0xD83Du);
d.OnCharUnit(0xDE00u);
const fcs::core::InputSnapshot& sd = d.Snapshot();
CHECK(sd.char_count == 1);
CHECK(sd.chars[0] == 0x1F600);
CHECK(d.dropped_chars() == 1);
// A pair split across a frame boundary is never split in the OUTPUT: either it
// completes, or the orphan is dropped.
InputFrame x;
x.OnCharUnit(0xD83Du);
CHECK(x.Snapshot().char_count == 0);
x.OnCharUnit(0xDE00u);
CHECK(x.Snapshot().char_count == 0);
}
// T-19 (C4): the Tab / Shift+Tab focus ring.
static void T19_FocusRing() {
std::printf("T-19 C4 FocusRing: wrap both ways, skip disabled, all-disabled is a no-op\n");
using fcs::core::FocusRing;
using fcs::core::Id;
const Id a = fcs::core::HashName(fcs::core::kNullId, "a");
const Id b = fcs::core::HashName(fcs::core::kNullId, "b");
const Id c = fcs::core::HashName(fcs::core::kNullId, "c");
FocusRing r;
r.SetIds(std::vector<Id>{a, b, c});
CHECK(r.count() == 3);
CHECK(r.focused() == -1);
CHECK(r.focused_id() == fcs::core::kNullId);
CHECK(r.MoveNext()); CHECK(r.focused() == 0);
CHECK(r.MoveNext()); CHECK(r.focused() == 1);
CHECK(r.MoveNext()); CHECK(r.focused() == 2);
CHECK(r.MoveNext()); CHECK(r.focused() == 0); // wraps forward
CHECK(r.MovePrev()); CHECK(r.focused() == 2); // and backward
CHECK(r.focused_id() == c);
// A disabled entry is skipped rather than focused. Focus is on index 2, and 0
// is the next enabled entry after it - index 1 must be stepped over, so the
// ring does NOT land back where a naive "+1 mod n" would put it.
r.SetEnabled(1, false);
CHECK(r.MoveNext());
CHECK(r.focused() == 0);
CHECK(r.MoveNext());
CHECK(r.focused() == 2); // and again past the gap
// Disabling an entry that is NOT focused leaves focus alone; disabling the
// focused entry drops it, because sitting on a disabled widget is worse than
// sitting on none.
r.SetEnabled(0, false);
CHECK(r.focused() == 2);
r.SetEnabled(2, false);
CHECK(r.focused() == -1);
// All disabled is a no-op, not a loop between the two ends. This needs TWO
// SetEnabled calls, which is exactly what caught the assign() bug above.
FocusRing all;
all.SetIds(std::vector<Id>{a, b});
all.SetEnabled(0, false);
all.SetEnabled(1, false);
CHECK(!all.MoveNext());
CHECK(!all.MovePrev());
CHECK(all.focused() == -1);
FocusRing empty;
empty.SetIds(std::vector<Id>{});
CHECK(!empty.MoveNext());
CHECK(!empty.MovePrev());
CHECK(empty.count() == 0);
}
// T-20 (J8): the three rules that keep a save from destroying user settings.
static void T20_SettingsRules() {
std::printf("T-20 J8 settings: same-directory temp, corrupt file never overwritten, stale temp removed\n");
using fcs::core::ClassifyLoad;
using fcs::core::LastSeparator;
using fcs::core::LoadAllowsOverwrite;
using fcs::core::LoadOutcome;
using fcs::core::SameDirectory;
using fcs::core::ShouldRemoveStaleTemp;
using fcs::core::TempPathFor;
// RULE 1: the temp must be in the SAME DIRECTORY, because that - not the
// rename API - is what makes the replace atomic. A cross-volume rename is a
// copy-then-delete, which can be interrupted halfway.
const std::string target = "C:\\Users\\x\\AppData\\Roaming\\FolderCloneSync\\ui.json";
const std::string temp = TempPathFor(target);
CHECK(SameDirectory(target, temp));
CHECK(SameDirectory(target, target));
CHECK(!SameDirectory(target, "C:\\Users\\x\\AppData\\Local\\FolderCloneSync\\ui.json.tmp"));
CHECK(!SameDirectory(target, "D:\\other\\ui.json.tmp"));
CHECK(!SameDirectory(target, "ui.json.tmp")); // bare filename vs absolute
CHECK(SameDirectory("ui.json.tmp", "other.tmp"));
// And a forward-slash path, because a UNC or a hand-built path may use either.
CHECK(SameDirectory("C:/a/b/ui.json", "C:/a/b/ui.json.tmp"));
CHECK(!SameDirectory("C:/a/b/ui.json", "C:/a/c/ui.json.tmp"));
// RULE 2: an unparseable file is NOT "no file". Both run on defaults, but
// only one may be overwritten - and conflating them silently destroys the
// user's settings on the next save.
CHECK(ClassifyLoad(false, false) == LoadOutcome::NoFile);
CHECK(ClassifyLoad(true, true) == LoadOutcome::UseFile);
CHECK(ClassifyLoad(true, false) == LoadOutcome::CorruptKeepFile);
CHECK(LoadAllowsOverwrite(LoadOutcome::UseFile));
CHECK(LoadAllowsOverwrite(LoadOutcome::NoFile));
CHECK(!LoadAllowsOverwrite(LoadOutcome::CorruptKeepFile));
// A file that exists but did not parse must NOT be savable, whatever the
// caller believes about it.
const LoadOutcome corrupt = ClassifyLoad(true, false);
CHECK(!LoadAllowsOverwrite(corrupt));
CHECK(!LoadAllowsOverwrite(ClassifyLoad(true, /*parsed_ok=*/false)));
// RULE 3: a leftover temp is removed on load, never read.
CHECK(ShouldRemoveStaleTemp(true, false));
CHECK(!ShouldRemoveStaleTemp(false, false));
// The helper both directory functions depend on.
CHECK(LastSeparator("ui.json") == std::string::npos);
CHECK(LastSeparator("a\\b\\c") == 4);
CHECK(LastSeparator("a/b/c") == 4);
}
int main() {
std::printf("=== FCS Glass portable logic harness ===\n");
T01_T02_BlockContrast();
T03_BlockContrast_Mixed();
T04_DpToPx();
T05_ContentScale();
T06_DialToAlpha();
T07_ToColorRef();
T08_SelectTier();
T09_JsonEscape();
T10_ComPtr();
T11_P95IndexSafety();
T12_ThresholdsSanity();
T13_SnapPx();
T14_Radii();
T15_IdStack();
T16_StateStore();
T17_InputFrame();
T18_Surrogates();
T19_FocusRing();
T20_SettingsRules();
std::printf("\n PASS=%d FAIL=%d\n", g_pass, g_fail);
return g_fail == 0 ? 0 : 1;
}