From 6e6d1244478f5f4b8de26453df15ed533ab04271 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 19:31:02 -0500 Subject: [PATCH 1/7] Add a Win32 desktop provider and retire GTK on Windows Desktop UI moves to one provider per platform: GTK stays the Linux provider, Win32 becomes the Windows provider. The ui.v1 contract in ui_runtime.hpp is unchanged, and ui_runtime_shared.hpp now carries its toolkit-independent half -- handle allocation, UTF-8 validation, stored limits, kind codes and the event/placement records -- moved verbatim out of the GTK provider so a second backend reproduces those semantics and error strings instead of restating them. CMake compiles exactly one provider per platform. Win32 supplies no box or grid container, so containers are child windows of a private class and the provider owns the layout pass, measuring text with the system message font. Events come from WM_COMMAND BN_CLICKED and EN_CHANGE and from WM_CLOSE, which enqueues a close request without destroying a live handle. activate uses BM_CLICK, the same path a user click takes. Unlike the dynamically loaded GTK provider, this one calls USER32 and GDI32 directly, so every linked program imports them. user32.lib and gdi32.lib therefore join ws2_32.lib in both nillinker argument lists, both nilcompiler link invocations, the nilbuild toolchain-input seal that forms the incremental build identity, and its test fixture. Without that the AOT routes and both nilbuild contracts fail on unresolved externals. nil.ui-windows-loader and its script tested NIL_UI_GTK_DIRECTORY and libgtk-4-1.dll loading on Windows, which is no longer how Windows gets a provider, so both are removed; docs/standard-library/ui.md no longer instructs Windows users to deploy a GTK4 runtime. The provider builds and links, and the suite passes, but its window behavior is still undemonstrated: every path runs through initialize(), which requires an interactive window station, so a headless session can only reach the refusal path. Verified at this commit. Linux: 572 registered, 0 failed, 3 environment skips -- identical to before the change. Windows on the development VM: 573 registered, 568 passed, 4 environment skips, and the one pre-existing nil.windows-sdk-preflight failure, which cannot run while the machine PowerShell execution policy is Restricted. 569 tests are shared and all pass on both hosts. Co-Authored-By: Claude Opus 5 --- CMakeLists.txt | 4 - docs/platform-support.md | 19 + docs/standard-library/ui.md | 41 +- nilbuild/windows_toolchain_inputs.hpp | 3 +- nilcompiler/CMakeLists.txt | 16 +- nilcompiler/src/main.cpp | 5 +- nilcompiler/src/ui_runtime.cpp | 52 +- nilcompiler/src/ui_runtime_shared.hpp | 77 ++ nilcompiler/src/ui_runtime_win32.cpp | 1015 +++++++++++++++++++++ nillinker/main.cpp | 5 + notebook/2026-11-02-windows-port.md | 67 ++ tests/tools/windows_ui_loader_contract.py | 105 --- tests/windows_toolchain_inputs_tests.cpp | 3 +- 13 files changed, 1226 insertions(+), 186 deletions(-) create mode 100644 nilcompiler/src/ui_runtime_shared.hpp create mode 100644 nilcompiler/src/ui_runtime_win32.cpp delete mode 100644 tests/tools/windows_ui_loader_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ff214b14..42de5cae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -629,10 +629,6 @@ if(BUILD_TESTING) if(WIN32) set(NIL_UI_DISPLAY_CONTRACT "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/windows_ui_display_contract.py") set(NIL_UI_DISPLAY_TIMEOUT 660) - add_test(NAME nil.ui-windows-loader - COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/windows_ui_loader_contract.py" - --probe $) - set_tests_properties(nil.ui-windows-loader PROPERTIES LABELS "ui;runtime;windows" TIMEOUT 180) endif() add_test(NAME nil.ui-display COMMAND "${Python3_EXECUTABLE}" "${NIL_UI_DISPLAY_CONTRACT}" diff --git a/docs/platform-support.md b/docs/platform-support.md index ae2a1c3c..539153db 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -92,6 +92,25 @@ tests after the numeric-address correction, including IPv4/IPv6 timeout and socket-close checks. The original checkout, installed SDK and provider DLLs remain unchanged. +A private Windows build at `8aa60d2` records the first complete local suite since +the port closeout: 574 registered tests against 572 on the Linux reference. The +two inventories share 569 tests. Five are Windows-only: console UTF-8, +unmanifested UTF-8 file paths, the GTK loader, the native memory-limit self-test +and the SDK preflight. Three are Linux-only: toolchain inputs, POSIX process +semantics and a socket-backpressure check of the Python test client rather than +of a product surface. No language, frontend, type-checker, IR, interpreter, LLVM +or standard-library test fails. Four shared contracts fail only when the suite +runs as `SYSTEM`: that account reports `TEMP` cased `C:\WINDOWS\TEMP`, the +toolchain reports paths in their on-disk casing, and the affected assertions +compare the two strings exactly; the same four pass unchanged under an ordinary +user account. The Windows-only SDK preflight cannot run while the machine +execution policy is `Restricted`, the Windows client default, because it invokes +`powershell.exe -File` deliberately without a bypass and every subtest therefore +observes a policy refusal instead of a preflight diagnostic. Two display tests +skip for want of an interactive desktop session and both PostgreSQL tests skip +without a server. This supplements the recorded Windows baseline; it neither +replaces the accepted SDK nor qualifies a new one. + ## Native executable context Thin Mach-O64 x86_64 and arm64 objects and executables support bounded inspection diff --git a/docs/standard-library/ui.md b/docs/standard-library/ui.md index fdb1488e..cac8456a 100644 --- a/docs/standard-library/ui.md +++ b/docs/standard-library/ui.md @@ -2,11 +2,13 @@ `read nil.std.ui` provides a Matrix desktop library with typed windows, widgets, events and explicit model bindings. Ny programs can import the same module. -The VM and native compiler use the same checked GTK4 provider on Linux and +The VM and native compiler use one desktop provider per platform, each behind +the same checked boundary: a GTK4 provider on Linux and a Win32 provider on Windows. Windows remains a development target, not a qualified release platform. -The macOS provider is being integrated. Its private GTK stack and toolkit -window/event checks pass on Intel and Apple Silicon; product and language-level -desktop acceptance remain in progress. See [platform support](../platform-support.md). +The macOS provider is being integrated; AppKit replaces the earlier GTK-on-macOS +work, because a GTK process on macOS never runs the AppKit event loop and is +therefore invisible to the accessibility APIs that assistive technology and +directed input depend on. See [platform support](../platform-support.md). Examples display the framework generation as **NIL²**, with **NIL^2** as the plain-text spelling. This presentation does not change numeric release or artifact identities in `VERSION`. @@ -41,20 +43,19 @@ symbols can load; it does not connect to a display. Window creation returns `Result.Error` if the graphical session cannot be initialized. There is no headless widget simulation or automatic package installation. -On Windows, deploy a compatible x64 GTK4 runtime with its dependencies and -runtime data. Set `NIL_UI_GTK_DIRECTORY` to its absolute DLL directory, or place -the DLLs beside the executable. An explicitly empty, relative or invalid setting -fails closed rather than falling back. The loader accepts the `libgtk-4-1.dll` -or `gtk-4-1.dll` naming family and corresponding GLib/GObject names; ambiguous -duplicates are rejected. It uses wide paths and scoped DLL search flags, without -changing process-wide DLL policy or searching the current directory or `PATH`. -Already-loaded direct GTK/GLib/GObject modules must match the selected files. -This does not establish isolation from every transitive DLL already loaded by -an embedding host. GTK is an optional external dependency, not bundled in the SDK. - -Windows window creation requires an interactive, visible window station. -Service-session requests return a display error before GTK initialization; -successful provider availability alone does not prove a desktop is usable. +Windows needs no external toolkit. The provider is Win32 itself, so +`available with nothing` is always true there and no runtime has to be deployed +or configured; GTK is neither used nor loaded on Windows. Because USER32 and +GDI32 are called directly rather than loaded on demand, every linked program +imports them, which is why `user32.lib` and `gdi32.lib` join `ws2_32.lib` in the +Windows link lines and in the incremental build's toolchain identity. + +Windows window creation still requires an interactive, visible window station. +A service session, or an SSH session with no desktop, returns a display error +before any window is created; successful provider availability alone does not +prove a desktop is usable. Win32 supplies no box or grid container, so the +provider owns the layout pass for rows, columns and grids; sizes therefore come +from measuring text with the system message font rather than from the toolkit. The macOS source provider requires `NIL_UI_GTK_DIRECTORY` to name an existing absolute trusted directory containing `libgtk-4.1.dylib`, @@ -97,7 +98,7 @@ second window or widget. | `set-expansion(widget, horizontal, vertical)` | Set the two layout expansion flags. The writes are sequential, not transactional. | | `attach-grid(grid, child, column, row, column-span, row-span)` | Reposition an existing child of that grid; it cannot reparent a widget. | | `focus-widget(widget)` | Request keyboard focus, normally after showing the window. | -| `activate-widget(widget)` | Request GTK activation of an enabled button or checkbox. | +| `activate-widget(widget)` | Request the provider's real activation of an enabled button or checkbox. | | `widget-width(widget)`, `widget-height(widget)` | `Result`; current allocation in pixels, which can be zero before layout. | Mutation operations return `Result` with `yes` on success unless @@ -139,7 +140,7 @@ when a field cannot be read. A retained event therefore describes the original event even after another mutation or window close. Its copied target handle can still become stale. -Polling is nonblocking and processes a bounded batch of GTK work. An ordinary +Polling is nonblocking and processes a bounded batch of provider work. An ordinary event loop sleeps briefly when it receives `Option.None`; the example uses 16 milliseconds. Call UI operations from the context's creation thread and use one UI thread in the process. Worker jobs should return application data for diff --git a/nilbuild/windows_toolchain_inputs.hpp b/nilbuild/windows_toolchain_inputs.hpp index cd6c32ec..e1a270c4 100644 --- a/nilbuild/windows_toolchain_inputs.hpp +++ b/nilbuild/windows_toolchain_inputs.hpp @@ -189,7 +189,8 @@ class collector { } } if (error || !library(runtime, 0)) return {}; - for (const auto *name : {"kernel32.lib", "ws2_32.lib", "msvcrt.lib", "ucrt.lib", + for (const auto *name : {"kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", + "msvcrt.lib", "ucrt.lib", "vcruntime.lib", "legacy_stdio_definitions.lib"}) { const auto selected = resolve(name); if (!selected || !library(*selected, 0)) return {}; diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 2da6eba2..a597265e 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -45,6 +45,16 @@ set(NILCOMPILER_CORE_SOURCES src/executable_context.cpp ) +# One desktop provider per platform: GTK is the Linux (and macOS) provider, +# Win32 is the Windows provider. Both implement the same ui.v1 contract and +# share its toolkit-independent half through src/ui_runtime_shared.hpp, so +# exactly one of them is ever compiled into the runtime. +if(WIN32) + set(NIL_UI_PROVIDER_SOURCE src/ui_runtime_win32.cpp) +else() + set(NIL_UI_PROVIDER_SOURCE src/ui_runtime.cpp) +endif() + # Compile the runtime once as PIC so both the portable SDK shared library and # the static companion use the same implementation and versioned C ABI. add_library(nilruntime_objects OBJECT @@ -53,7 +63,7 @@ add_library(nilruntime_objects OBJECT src/owned_runtime.cpp src/secure_file_io.cpp src/database_runtime.cpp - src/ui_runtime.cpp + ${NIL_UI_PROVIDER_SOURCE} src/pattern_engine.cpp src/nildata.cpp ) @@ -73,7 +83,9 @@ foreach(nil_runtime_target IN ITEMS nilruntime nilruntime_shared) if(WIN32) # PostgreSQL's bounded socket wait and numeric-address validation use # Winsock; propagate it to static build-tree consumers as well as DLLs. - target_link_libraries(${nil_runtime_target} PUBLIC ws2_32) + # The Win32 desktop provider calls USER32 and GDI32 directly, unlike + # the dynamically loaded GTK provider, so those travel the same way. + target_link_libraries(${nil_runtime_target} PUBLIC ws2_32 user32 gdi32) endif() set_target_properties(${nil_runtime_target} PROPERTIES CXX_EXTENSIONS OFF diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 41c3f4b9..19b93afd 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -2244,8 +2244,8 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) // otherwise only ever inline - without it a generated call to printf // is an unresolved external. const std::vector windows_crt_libraries = { - "kernel32.lib", "ws2_32.lib", "msvcrt.lib", "ucrt.lib", "vcruntime.lib", - "legacy_stdio_definitions.lib"}; + "kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", "msvcrt.lib", + "ucrt.lib", "vcruntime.lib", "legacy_stdio_definitions.lib"}; const auto manifest_path = *private_output_workspace / "utf8.manifest"; const auto manifest_publish = ny::detail::write_file_atomic( manifest_path, @@ -2315,6 +2315,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) std::vector arguments = { driver->u8string(), "-o", link_output_path.u8string(), obj_path.u8string(), native_runtime->u8string(), "ws2_32.lib", + "user32.lib", "gdi32.lib", "-Xlinker", "/MANIFEST:EMBED", "-Xlinker", manifest_argument}; arguments.insert(arguments.end(), link_libraries.begin(), link_libraries.end()); diff --git a/nilcompiler/src/ui_runtime.cpp b/nilcompiler/src/ui_runtime.cpp index f87ec835..5ea9bc21 100644 --- a/nilcompiler/src/ui_runtime.cpp +++ b/nilcompiler/src/ui_runtime.cpp @@ -3,6 +3,7 @@ * SPDX-License-Identifier: MIT */ #include "ui_runtime.hpp" +#include "ui_runtime_shared.hpp" #include #include @@ -355,57 +356,6 @@ struct Api { }; Api &api() { static Api *value = new Api; return *value; } -constexpr std::size_t max_widgets = 4096, max_windows = 64; -constexpr std::size_t max_events = 4096, max_snapshots = 4096; -constexpr std::size_t max_text_bytes = 1024 * 1024; -constexpr std::size_t max_event_text_bytes = 16 * 1024 * 1024; -constexpr std::size_t max_entry_characters = 16384; -std::atomic next_handle{1}; -std::int64_t fresh_handle() { - auto value = next_handle.load(std::memory_order_relaxed); - for (;;) { - if (value <= 0 || value == std::numeric_limits::max()) return 0; - if (next_handle.compare_exchange_weak(value, value + 1, std::memory_order_relaxed)) return value; - } -} -Result failure(const std::string &message) { return {0, {}, "ui: " + message}; } -Result success(std::int64_t value = 1) { return {value, {}, {}}; } - -bool valid_text(const std::string &text) { - if (text.size() > max_text_bytes) return false; - // Validate scalar-value UTF-8, reject embedded NUL and overlong encodings. - for (std::size_t index = 0; index < text.size();) { - const auto first = static_cast(text[index++]); - if (!first) return false; - if (first < 0x80) continue; - unsigned count, scalar, minimum; - if (first >= 0xc2 && first <= 0xdf) { count = 1; scalar = first & 31; minimum = 0x80; } - else if (first >= 0xe0 && first <= 0xef) { count = 2; scalar = first & 15; minimum = 0x800; } - else if (first >= 0xf0 && first <= 0xf4) { count = 3; scalar = first & 7; minimum = 0x10000; } - else return false; - if (count > text.size() - index) return false; - while (count--) { - auto byte = static_cast(text[index++]); - if ((byte & 0xc0) != 0x80) return false; - scalar = (scalar << 6) | (byte & 63); - } - if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) return false; - } - return true; -} -const char *text_error = "text must be valid UTF-8 without NUL, at most 1048576 bytes"; -bool entry_text_fits(const std::string &text) { - return static_cast(std::count_if(text.begin(), text.end(), - [](unsigned char byte) { return (byte & 0xc0) != 0x80; })) <= max_entry_characters; -} -enum class Kind { window = 0, column = 1, row = 2, grid = 3, label = 4, button = 5, entry = 6, checkbox = 7 }; -bool container(Kind kind) { return kind == Kind::window || kind == Kind::column || kind == Kind::row || kind == Kind::grid; } -struct Event { std::int64_t kind, target, window, checked; std::string text; }; -struct Placement { std::int64_t column = 0, row = 0, columns = 1, rows = 1; }; -bool overlaps(const Placement &a, const Placement &b) { - return a.column < b.column + b.columns && b.column < a.column + a.columns && - a.row < b.row + b.rows && b.row < a.row + a.rows; -} } // namespace struct Context::Impl : std::enable_shared_from_this { diff --git a/nilcompiler/src/ui_runtime_shared.hpp b/nilcompiler/src/ui_runtime_shared.hpp new file mode 100644 index 00000000..0c74eb82 --- /dev/null +++ b/nilcompiler/src/ui_runtime_shared.hpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#pragma once +// Toolkit-independent parts of the ui.v1 contract: handle allocation, text +// validation, kind codes, event/placement records and the stored limits. +// Exactly one provider translation unit is compiled per platform (GTK on +// Linux, Win32 on Windows), so the internal linkage below is one definition +// per process and handles stay process-unique. Keeping these here is what +// makes a second provider reproduce the first provider's semantics -- limits, +// error text and validation -- instead of restating them and drifting. +#include "ui_runtime.hpp" + +#include +#include +#include +#include +#include + +namespace ny::ui { +namespace { + +constexpr std::size_t max_widgets = 4096, max_windows = 64; +constexpr std::size_t max_events = 4096, max_snapshots = 4096; +constexpr std::size_t max_text_bytes = 1024 * 1024; +constexpr std::size_t max_event_text_bytes = 16 * 1024 * 1024; +constexpr std::size_t max_entry_characters = 16384; +std::atomic next_handle{1}; +std::int64_t fresh_handle() { + auto value = next_handle.load(std::memory_order_relaxed); + for (;;) { + if (value <= 0 || value == std::numeric_limits::max()) return 0; + if (next_handle.compare_exchange_weak(value, value + 1, std::memory_order_relaxed)) return value; + } +} +Result failure(const std::string &message) { return {0, {}, "ui: " + message}; } +Result success(std::int64_t value = 1) { return {value, {}, {}}; } + +bool valid_text(const std::string &text) { + if (text.size() > max_text_bytes) return false; + // Validate scalar-value UTF-8, reject embedded NUL and overlong encodings. + for (std::size_t index = 0; index < text.size();) { + const auto first = static_cast(text[index++]); + if (!first) return false; + if (first < 0x80) continue; + unsigned count, scalar, minimum; + if (first >= 0xc2 && first <= 0xdf) { count = 1; scalar = first & 31; minimum = 0x80; } + else if (first >= 0xe0 && first <= 0xef) { count = 2; scalar = first & 15; minimum = 0x800; } + else if (first >= 0xf0 && first <= 0xf4) { count = 3; scalar = first & 7; minimum = 0x10000; } + else return false; + if (count > text.size() - index) return false; + while (count--) { + auto byte = static_cast(text[index++]); + if ((byte & 0xc0) != 0x80) return false; + scalar = (scalar << 6) | (byte & 63); + } + if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) return false; + } + return true; +} +const char *text_error = "text must be valid UTF-8 without NUL, at most 1048576 bytes"; +bool entry_text_fits(const std::string &text) { + return static_cast(std::count_if(text.begin(), text.end(), + [](unsigned char byte) { return (byte & 0xc0) != 0x80; })) <= max_entry_characters; +} +enum class Kind { window = 0, column = 1, row = 2, grid = 3, label = 4, button = 5, entry = 6, checkbox = 7 }; +bool container(Kind kind) { return kind == Kind::window || kind == Kind::column || kind == Kind::row || kind == Kind::grid; } +struct Event { std::int64_t kind, target, window, checked; std::string text; }; +struct Placement { std::int64_t column = 0, row = 0, columns = 1, rows = 1; }; +bool overlaps(const Placement &a, const Placement &b) { + return a.column < b.column + b.columns && b.column < a.column + a.columns && + a.row < b.row + b.rows && b.row < a.row + a.rows; +} + +} // namespace +} // namespace ny::ui diff --git a/nilcompiler/src/ui_runtime_win32.cpp b/nilcompiler/src/ui_runtime_win32.cpp new file mode 100644 index 00000000..5a3ff5ba --- /dev/null +++ b/nilcompiler/src/ui_runtime_win32.cpp @@ -0,0 +1,1015 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +// Windows provider for the ui.v1 contract, built instead of the GTK provider +// on Windows: one toolkit per platform. The observable contract is the one +// stated in ui_runtime.hpp and shared with the GTK provider through +// ui_runtime_shared.hpp -- identical handles, limits, error text, kind codes +// and event kinds. Only the toolkit beneath it differs. +// +// Win32 has no box or grid container, so containers are real child windows of +// a private class and this file owns the layout pass that USER32 does not +// provide. Keeping containers as windows is what makes visibility and +// sensitivity inherit, and clipping behave, the way the contract describes. +#include "ui_runtime.hpp" +#include "ui_runtime_shared.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +namespace ny::ui { +namespace { + +const wchar_t window_class[] = L"NyUi.Window"; +const wchar_t container_class[] = L"NyUi.Container"; + +// Control metrics. Win32 reports no natural size for a control, so the +// provider measures text with the message font and adds the padding the +// system themes expect. These are layout inputs, not contract values. +constexpr int button_padding_x = 24, button_padding_y = 10; +constexpr int label_padding_x = 2, label_padding_y = 4; +constexpr int entry_padding_x = 10, entry_padding_y = 8; +constexpr int entry_minimum_width = 120; +constexpr int checkbox_box_width = 20; + +std::wstring to_wide(const std::string &text) { + if (text.empty()) return {}; + const int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), + static_cast(text.size()), nullptr, 0); + if (size <= 0) return {}; + std::wstring wide(static_cast(size), L'\0'); + if (!MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), + static_cast(text.size()), wide.data(), size)) + return {}; + return wide; +} + +// Returns false rather than a lossy string: callers report invalid text. +bool to_utf8(const std::wstring &wide, std::string &out) { + if (wide.empty()) { out.clear(); return true; } + const int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wide.data(), + static_cast(wide.size()), nullptr, 0, nullptr, nullptr); + if (size <= 0) return false; + std::string text(static_cast(size), '\0'); + if (!WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wide.data(), static_cast(wide.size()), + text.data(), size, nullptr, nullptr)) + return false; + out = std::move(text); + return true; +} + +std::string window_text(HWND window) { + const int length = GetWindowTextLengthW(window); + if (length <= 0) return {}; + std::wstring wide(static_cast(length) + 1, L'\0'); + const int copied = GetWindowTextW(window, wide.data(), length + 1); + wide.resize(copied < 0 ? 0 : static_cast(copied)); + std::string text; + return to_utf8(wide, text) ? text : std::string{}; +} + +// A noninteractive station (a service, or an SSH session without a desktop) +// cannot create a window at all. Refuse before the first CreateWindowExW so +// the failure names the cause instead of surfacing a generic Win32 error. +bool interactive_window_station() noexcept { + const HWINSTA station = GetProcessWindowStation(); + if (!station) return false; + USEROBJECTFLAGS flags{}; + DWORD needed = 0; + if (!GetUserObjectInformationW(station, UOI_FLAGS, &flags, sizeof flags, &needed)) return false; + return (flags.dwFlags & WSF_VISIBLE) != 0; +} + +struct Platform { + std::mutex thread_mutex; + std::thread::id ui_thread; + bool initialized = false; + bool registered = false; + HFONT font = nullptr; + + // Message font, so measured text matches what the controls actually render. + HFONT message_font() { + if (font) return font; + NONCLIENTMETRICSW metrics{}; + metrics.cbSize = sizeof metrics; + if (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof metrics, &metrics, 0)) + font = CreateFontIndirectW(&metrics.lfMessageFont); + if (!font) font = static_cast(GetStockObject(DEFAULT_GUI_FONT)); + return font; + } +}; +Platform &platform() { static Platform *value = new Platform; return *value; } + +SIZE measure(const std::wstring &text) { + SIZE size{0, 0}; + const HDC screen = GetDC(nullptr); + if (!screen) return size; + const HDC memory = CreateCompatibleDC(screen); + if (memory) { + const HGDIOBJ previous = SelectObject(memory, platform().message_font()); + // An empty string still needs the font's line height for row sizing. + const wchar_t *measured = text.empty() ? L"Ag" : text.c_str(); + const int length = text.empty() ? 2 : static_cast(text.size()); + GetTextExtentPoint32W(memory, measured, length, &size); + if (text.empty()) size.cx = 0; + SelectObject(memory, previous); + DeleteDC(memory); + } + ReleaseDC(nullptr, screen); + return size; +} + +} // namespace + +struct Context::Impl : std::enable_shared_from_this { + struct Node { + Kind kind = Kind::window; + HWND object = nullptr; + HWND root = nullptr; // Window's automatic vertical container child. + std::int64_t parent = 0, window = 0; + std::string text; + std::map properties; + Placement placement; + RECT allocation{0, 0, 0, 0}; + unsigned suppress = 0; + bool event_failure = false; + }; + std::thread::id owner = std::this_thread::get_id(); + std::map nodes; + std::map handles; + std::map focus_targets; // window handle -> widget handle + std::deque events; + std::map snapshots; + std::size_t event_bytes = 0, snapshot_bytes = 0, text_bytes = 0; + std::atomic active{true}; + bool tearing_down = false; + + static std::mutex &deferred_mutex() { static auto *m = new std::mutex; return *m; } + static std::vector> &deferred() { + static auto *v = new std::vector>; return *v; + } + static void drain() { + std::vector> pending; + { std::lock_guard lock(deferred_mutex()); pending.swap(deferred()); } + for (auto &item : pending) item->dispose(); + } + Result check() { + if (owner != std::this_thread::get_id()) return failure("context must be used on its creation thread"); + if (!active.load()) return failure("context has been closed"); + auto &p = platform(); + bool initialized; + { + std::lock_guard lock(p.thread_mutex); + if (p.initialized && p.ui_thread != std::this_thread::get_id()) + return failure("Win32 windows must be used on the process UI thread"); + initialized = p.initialized; + } + if (initialized) drain(); + return success(); + } + Result initialize() { + if (auto result = check(); !result) return result; + auto &p = platform(); + std::lock_guard lock(p.thread_mutex); + if (p.initialized) { + if (p.ui_thread != std::this_thread::get_id()) + return failure("Win32 windows must be used on the process UI thread"); + return success(); + } + if (!interactive_window_station()) + return failure("Win32 could not open a display; an interactive Windows window station is required (noninteractive service and SSH desktops are unsupported)"); + if (!p.registered) { + WNDCLASSEXW description{}; + description.cbSize = sizeof description; + description.lpfnWndProc = &window_proc; + description.hInstance = GetModuleHandleW(nullptr); + description.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512)); // IDC_ARROW + description.hbrBackground = reinterpret_cast(COLOR_BTNFACE + 1); + description.lpszClassName = window_class; + if (!RegisterClassExW(&description) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) + return failure("Win32 could not register the window class"); + description.lpszClassName = container_class; + if (!RegisterClassExW(&description) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) + return failure("Win32 could not register the container class"); + p.registered = true; + } + p.ui_thread = std::this_thread::get_id(); + p.initialized = true; + return success(); + } + Node *find(std::int64_t handle) { + auto found = nodes.find(handle); + return found == nodes.end() ? nullptr : &found->second; + } + static Result bad_handle() { return failure("unknown, closed, or foreign widget handle"); } + + HWND container_window(const Node &node) const { return node.kind == Kind::window ? node.root : node.object; } + std::int64_t handle_of(HWND window) const { + auto found = handles.find(window); + return found == handles.end() ? 0 : found->second; + } + + bool effective_sensitive(const Node &node) { + if (!IsWindowEnabled(node.object)) return false; + for (auto parent = node.parent; parent;) { + auto *owner = find(parent); + if (!owner) break; + if (!IsWindowEnabled(owner->object)) return false; + parent = owner->parent; + } + return true; + } + + void enqueue(std::int64_t handle, std::int64_t kind) noexcept { + const auto mark_failure = [&] { + if (const auto *node = find(handle)) + if (auto *window = find(node->window)) window->event_failure = true; + }; + try { + auto *node = find(handle); + if (!node || node->suppress || tearing_down) return; + Event event{kind, handle, node->window, 0, {}}; + if (kind == 2) { + event.text = window_text(node->object); + if (!valid_text(event.text)) { mark_failure(); return; } + } else if (kind == 3) + event.checked = SendMessageW(node->object, BM_GETCHECK, 0, 0) == BST_CHECKED ? 1 : 0; + if (events.size() >= max_events || event.text.size() > max_event_text_bytes - event_bytes) { + mark_failure(); return; + } + events.push_back(std::move(event)); + event_bytes += events.back().text.size(); + } catch (...) { mark_failure(); } + } + + // ---- layout ------------------------------------------------------------- + // Win32 provides no natural size and no box/grid, so the provider computes + // both. Children of a container are its nodes in handle order, which is + // creation order because handles increase monotonically. + std::vector children_of(std::int64_t handle) { + std::vector result; + for (const auto &[id, node] : nodes) + if (node.parent == handle) result.push_back(id); + return result; + } + std::int64_t property(const Node &node, const char *name, std::int64_t fallback = 0) { + auto found = node.properties.find(name); + if (found != node.properties.end()) return found->second; + auto all = node.properties.find("margin"); + if (all != node.properties.end() && std::string(name).rfind("margin_", 0) == 0) return all->second; + return fallback; + } + SIZE natural(std::int64_t handle) { + auto *node = find(handle); + if (!node) return SIZE{0, 0}; + SIZE size{0, 0}; + switch (node->kind) { + case Kind::label: { + const auto text = measure(to_wide(node->text)); + size = SIZE{text.cx + label_padding_x, text.cy + label_padding_y}; + break; + } + case Kind::button: { + const auto text = measure(to_wide(node->text)); + size = SIZE{text.cx + button_padding_x, text.cy + button_padding_y}; + break; + } + case Kind::checkbox: { + const auto text = measure(to_wide(node->text)); + size = SIZE{text.cx + checkbox_box_width + label_padding_x, text.cy + label_padding_y}; + break; + } + case Kind::entry: { + const auto text = measure(to_wide(node->text)); + size = SIZE{(std::max)(static_cast(entry_minimum_width), text.cx + entry_padding_x), + text.cy + entry_padding_y}; + break; + } + default: { + const auto kids = children_of(handle); + const auto spacing = static_cast(property(*node, "spacing")); + if (node->kind == Kind::grid) { + std::map widths, heights; + for (auto id : kids) { + auto *child = find(id); + if (!child) continue; + const auto wanted = natural(id); + auto &width = widths[child->placement.column]; + auto &height = heights[child->placement.row]; + width = (std::max)(width, static_cast(wanted.cx / (std::max)(std::int64_t(1), child->placement.columns))); + height = (std::max)(height, static_cast(wanted.cy / (std::max)(std::int64_t(1), child->placement.rows))); + } + for (const auto &[column, width] : widths) { (void)column; size.cx += width; } + for (const auto &[row, height] : heights) { (void)row; size.cy += height; } + if (!widths.empty()) size.cx += spacing * static_cast(widths.size() - 1); + if (!heights.empty()) size.cy += spacing * static_cast(heights.size() - 1); + } else { + const bool vertical = node->kind != Kind::row; + for (auto id : kids) { + const auto wanted = natural(id); + if (vertical) { size.cx = (std::max)(size.cx, wanted.cx); size.cy += wanted.cy; } + else { size.cy = (std::max)(size.cy, wanted.cy); size.cx += wanted.cx; } + } + if (!kids.empty()) { + const auto gaps = spacing * static_cast(kids.size() - 1); + if (vertical) size.cy += gaps; else size.cx += gaps; + } + } + break; + } + } + if (node->kind != Kind::window) { + size.cx += static_cast(property(*node, "margin_start") + property(*node, "margin_end")); + size.cy += static_cast(property(*node, "margin_top") + property(*node, "margin_bottom")); + } + return size; + } + void place(std::int64_t handle, RECT area) { + auto *node = find(handle); + if (!node) return; + if (node->kind != Kind::window) { + area.left += static_cast(property(*node, "margin_start")); + area.right -= static_cast(property(*node, "margin_end")); + area.top += static_cast(property(*node, "margin_top")); + area.bottom -= static_cast(property(*node, "margin_bottom")); + if (area.right < area.left) area.right = area.left; + if (area.bottom < area.top) area.bottom = area.top; + node->allocation = area; + SetWindowPos(node->object, nullptr, area.left, area.top, area.right - area.left, + area.bottom - area.top, SWP_NOZORDER | SWP_NOACTIVATE); + } else { + node->allocation = area; + } + if (!container(node->kind)) return; + + // Containers lay out in their own client coordinates. + RECT inner{0, 0, area.right - area.left, area.bottom - area.top}; + if (node->kind == Kind::window) { + inner.left += static_cast(property(*node, "margin_start")); + inner.right -= static_cast(property(*node, "margin_end")); + inner.top += static_cast(property(*node, "margin_top")); + inner.bottom -= static_cast(property(*node, "margin_bottom")); + if (node->root) + SetWindowPos(node->root, nullptr, 0, 0, area.right - area.left, area.bottom - area.top, + SWP_NOZORDER | SWP_NOACTIVATE); + } + if (inner.right < inner.left) inner.right = inner.left; + if (inner.bottom < inner.top) inner.bottom = inner.top; + + const auto kids = children_of(handle); + if (kids.empty()) return; + const auto spacing = static_cast(property(*node, "spacing")); + + if (node->kind == Kind::grid) { + std::map widths, heights; + for (auto id : kids) { + auto *child = find(id); + if (!child) continue; + const auto wanted = natural(id); + auto &width = widths[child->placement.column]; + auto &height = heights[child->placement.row]; + width = (std::max)(width, static_cast(wanted.cx / (std::max)(std::int64_t(1), child->placement.columns))); + height = (std::max)(height, static_cast(wanted.cy / (std::max)(std::int64_t(1), child->placement.rows))); + } + std::map column_offset, row_offset; + LONG x = inner.left; + for (auto &[column, width] : widths) { column_offset[column] = x; x += width + spacing; } + LONG y = inner.top; + for (auto &[row, height] : heights) { row_offset[row] = y; y += height + spacing; } + for (auto id : kids) { + auto *child = find(id); + if (!child) continue; + LONG width = 0, height = 0; + for (std::int64_t span = 0; span < child->placement.columns; ++span) { + auto found = widths.find(child->placement.column + span); + if (found != widths.end()) width += found->second + (span ? spacing : 0); + } + for (std::int64_t span = 0; span < child->placement.rows; ++span) { + auto found = heights.find(child->placement.row + span); + if (found != heights.end()) height += found->second + (span ? spacing : 0); + } + const LONG left = column_offset.count(child->placement.column) ? column_offset[child->placement.column] : inner.left; + const LONG top = row_offset.count(child->placement.row) ? row_offset[child->placement.row] : inner.top; + place(id, RECT{left, top, left + width, top + height}); + } + return; + } + + const bool vertical = node->kind != Kind::row; + LONG used = spacing * static_cast(kids.size() - 1); + std::size_t expanding = 0; + std::vector wanted; + wanted.reserve(kids.size()); + for (auto id : kids) { + wanted.push_back(natural(id)); + used += vertical ? wanted.back().cy : wanted.back().cx; + auto *child = find(id); + if (child && property(*child, vertical ? "vexpand" : "hexpand")) ++expanding; + } + const LONG span = vertical ? inner.bottom - inner.top : inner.right - inner.left; + const LONG extra = span > used ? span - used : 0; + const LONG share = expanding ? extra / static_cast(expanding) : 0; + + LONG offset = vertical ? inner.top : inner.left; + for (std::size_t index = 0; index < kids.size(); ++index) { + auto *child = find(kids[index]); + if (!child) continue; + const bool expand = property(*child, vertical ? "vexpand" : "hexpand") != 0; + LONG length = (vertical ? wanted[index].cy : wanted[index].cx) + (expand ? share : 0); + RECT target; + if (vertical) { + const LONG width = property(*child, "hexpand") ? inner.right - inner.left + : (std::min)(wanted[index].cx, inner.right - inner.left); + target = RECT{inner.left, offset, inner.left + width, offset + length}; + } else { + const LONG height = property(*child, "vexpand") ? inner.bottom - inner.top + : (std::min)(wanted[index].cy, inner.bottom - inner.top); + target = RECT{offset, inner.top, offset + length, inner.top + height}; + } + place(kids[index], target); + offset += length + spacing; + } + } + void relayout(std::int64_t window) { + auto *node = find(window); + if (!node || node->kind != Kind::window) return; + RECT client{}; + if (!GetClientRect(node->object, &client) || (client.right == 0 && client.bottom == 0)) + client = RECT{0, 0, static_cast(property(*node, "width", 1)), + static_cast(property(*node, "height", 1))}; + place(window, client); + } + + // WM_COMMAND is delivered to a control's immediate parent, so windows and + // containers share this procedure and each services its own children. + // These are members for the same reason the GTK provider's callbacks are: + // Context::Impl is private, so a free function cannot name it. + static LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM first, LPARAM second) { + auto *impl = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); + if (impl && impl->active.load() && !impl->tearing_down) { + switch (message) { + case WM_COMMAND: { + const auto control = reinterpret_cast(second); + const auto notification = HIWORD(first); + const auto handle = control ? impl->handle_of(control) : 0; + if (handle) { + auto *node = impl->find(handle); + if (node) { + if (notification == BN_CLICKED && node->kind == Kind::button) impl->enqueue(handle, 1); + else if (notification == BN_CLICKED && node->kind == Kind::checkbox) impl->enqueue(handle, 3); + else if (notification == EN_CHANGE && node->kind == Kind::entry) impl->enqueue(handle, 2); + } + } + return 0; + } + case WM_CLOSE: { + // Matrix decides when to close; Win32 must not destroy a live handle. + const auto handle = impl->handle_of(window); + if (handle) { impl->enqueue(handle, 4); return 0; } + break; + } + case WM_SIZE: { + const auto handle = impl->handle_of(window); + if (handle) { + auto *node = impl->find(handle); + // Only the top level relayouts. The root container maps to the same + // handle, and laying out resizes it, so reacting here too would + // re-enter relayout without end. + if (node && node->kind == Kind::window && window == node->object) impl->relayout(handle); + } + break; + } + case WM_SETFOCUS: { + const auto handle = impl->handle_of(window); + if (handle) { + auto *node = impl->find(handle); + if (node && node->kind != Kind::window) impl->focus_targets[node->window] = handle; + } + break; + } + default: break; + } + } + return DefWindowProcW(window, message, first, second); + } + + // Controls are standard classes, so their notifications already reach the + // parent; only focus tracking needs the control's own messages. + static LRESULT CALLBACK control_proc(HWND control, UINT message, WPARAM first, LPARAM second) { + const auto original = reinterpret_cast(GetWindowLongPtrW(control, GWLP_USERDATA)); + if (message == WM_SETFOCUS) { + const HWND parent = GetParent(control); + if (parent) + if (auto *impl = reinterpret_cast(GetWindowLongPtrW(parent, GWLP_USERDATA))) + if (impl->active.load() && !impl->tearing_down) { + const auto handle = impl->handle_of(control); + if (handle) + if (auto *node = impl->find(handle)) impl->focus_targets[node->window] = handle; + } + } + return original ? CallWindowProcW(original, control, message, first, second) + : DefWindowProcW(control, message, first, second); + } + + void dispose() noexcept { + active.store(false); + tearing_down = true; + for (auto &[id, node] : nodes) + if (node.kind == Kind::window && node.object) { + SetWindowLongPtrW(node.object, GWLP_USERDATA, 0); + DestroyWindow(node.object); + } + nodes.clear(); handles.clear(); focus_targets.clear(); + events.clear(); snapshots.clear(); + event_bytes = snapshot_bytes = text_bytes = 0; + tearing_down = false; + } +}; + +namespace { + +bool focusable(Kind kind) { return kind == Kind::button || kind == Kind::entry || kind == Kind::checkbox; } + +} // namespace + +// The Windows provider is part of the operating system, so unlike the optional +// GTK provider there is nothing to locate or verify. Reporting availability +// must still not open a display. +bool available() noexcept { return true; } + +Context::Context() : impl_(std::make_shared()) {} +Context::~Context() { clear(); } +void Context::clear() noexcept { + if (!impl_) return; + auto old = std::move(impl_); + old->active.store(false); + if (old->owner == std::this_thread::get_id()) old->dispose(); + else if (!old->nodes.empty()) { + try { std::lock_guard lock(Impl::deferred_mutex()); Impl::deferred().push_back(std::move(old)); } + catch (...) { /* Windows owns the HWNDs; a failed defer may leak them but never frees context data twice. */ } + } + try { impl_ = std::make_shared(); } catch (...) {} +} + +Result Context::window(const std::string &title, std::int64_t width, std::int64_t height) { + if (!impl_) return failure("context allocation failed"); + if (!valid_text(title)) return failure(text_error); + if (width < 1 || width > 16384 || height < 1 || height > 16384) + return failure("window width and height must be between 1 and 16384"); + if (auto result = impl_->initialize(); !result) return result; + if (title.size() > max_event_text_bytes - impl_->text_bytes) return failure("stored text limit exceeded (16 MiB per context)"); + if (impl_->nodes.size() >= max_widgets || static_cast(std::count_if(impl_->nodes.begin(), impl_->nodes.end(), + [](const auto &item) { return item.second.kind == Kind::window; })) >= max_windows) + return failure("window or widget limit exceeded (64 windows, 4096 widgets per context)"); + const auto handle = fresh_handle(); + if (!handle) return failure("handle space exhausted"); + Impl::Node node; node.kind = Kind::window; node.window = handle; node.text = title; + node.properties = {{"width", width}, {"height", height}, {"spacing", 0}}; + + // Creation remains hidden: WS_VISIBLE is set only by visible=1. + RECT frame{0, 0, static_cast(width), static_cast(height)}; + AdjustWindowRectEx(&frame, WS_OVERLAPPEDWINDOW, FALSE, 0); + node.object = CreateWindowExW(0, window_class, to_wide(title).c_str(), WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, frame.right - frame.left, + frame.bottom - frame.top, nullptr, nullptr, + GetModuleHandleW(nullptr), nullptr); + if (!node.object) return failure("Win32 could not create a window"); + node.root = CreateWindowExW(0, container_class, L"", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, + 0, 0, static_cast(width), static_cast(height), node.object, + nullptr, GetModuleHandleW(nullptr), nullptr); + if (!node.root) { + DestroyWindow(node.object); + return failure("Win32 could not create the root layout"); + } + try { + const HWND object = node.object, root = node.root; + impl_->nodes.emplace(handle, std::move(node)); + impl_->handles.emplace(object, handle); + impl_->handles.emplace(root, handle); + SetWindowLongPtrW(object, GWLP_USERDATA, reinterpret_cast(impl_.get())); + SetWindowLongPtrW(root, GWLP_USERDATA, reinterpret_cast(impl_.get())); + impl_->text_bytes += title.size(); + impl_->relayout(handle); + } catch (...) { + auto found = impl_->nodes.find(handle); + HWND object = found == impl_->nodes.end() ? node.object : found->second.object; + if (found != impl_->nodes.end()) { + impl_->handles.erase(found->second.object); + impl_->handles.erase(found->second.root); + impl_->nodes.erase(found); + } + if (object) { SetWindowLongPtrW(object, GWLP_USERDATA, 0); DestroyWindow(object); } + return failure("window allocation failed"); + } + return success(handle); +} + +Result Context::widget(const std::string &kind, std::int64_t parent, const std::string &label) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + if (!valid_text(label)) return failure(text_error); + if (label.size() > max_event_text_bytes - impl_->text_bytes) return failure("stored text limit exceeded (16 MiB per context)"); + if (kind == "entry" && !entry_text_fits(label)) return failure("entry text exceeds 16384 Unicode characters"); + auto *owner = impl_->find(parent); + if (!owner) return Impl::bad_handle(); + if (!container(owner->kind)) return failure("parent must be a window, row, column, or grid"); + if (impl_->nodes.size() >= max_widgets) return failure("widget limit exceeded (4096 per context)"); + + Impl::Node node; node.parent = parent; node.window = owner->window; node.text = label; + const HWND host = impl_->container_window(*owner); + const auto wide = to_wide(label); + const DWORD common = WS_CHILD | WS_VISIBLE; + const HINSTANCE instance = GetModuleHandleW(nullptr); + if (kind == "column" || kind == "row") { + node.kind = kind == "column" ? Kind::column : Kind::row; + node.object = CreateWindowExW(0, container_class, L"", common | WS_CLIPCHILDREN, 0, 0, 0, 0, host, nullptr, instance, nullptr); + } else if (kind == "grid") { + node.kind = Kind::grid; + node.object = CreateWindowExW(0, container_class, L"", common | WS_CLIPCHILDREN, 0, 0, 0, 0, host, nullptr, instance, nullptr); + } else if (kind == "label") { + node.kind = Kind::label; + node.object = CreateWindowExW(0, L"STATIC", wide.c_str(), common | SS_LEFT | SS_NOPREFIX, 0, 0, 0, 0, host, nullptr, instance, nullptr); + } else if (kind == "button") { + node.kind = Kind::button; + node.object = CreateWindowExW(0, L"BUTTON", wide.c_str(), common | BS_PUSHBUTTON | WS_TABSTOP, 0, 0, 0, 0, host, nullptr, instance, nullptr); + } else if (kind == "entry") { + node.kind = Kind::entry; + node.object = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", wide.c_str(), + common | ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, 0, 0, 0, 0, host, nullptr, instance, nullptr); + } else if (kind == "checkbox") { + node.kind = Kind::checkbox; + node.object = CreateWindowExW(0, L"BUTTON", wide.c_str(), common | BS_AUTOCHECKBOX | WS_TABSTOP, 0, 0, 0, 0, host, nullptr, instance, nullptr); + } else return failure("widget kind must be column, row, grid, label, button, entry, or checkbox"); + if (!node.object) return failure("Win32 could not create the widget"); + + const auto handle = fresh_handle(); + if (!handle) { DestroyWindow(node.object); return failure("handle space exhausted"); } + try { + SendMessageW(node.object, WM_SETFONT, reinterpret_cast(platform().message_font()), TRUE); + if (node.kind == Kind::entry) SendMessageW(node.object, EM_SETLIMITTEXT, max_entry_characters, 0); + if (owner->kind == Kind::grid) { + std::vector> occupied; + for (const auto &[id, sibling] : impl_->nodes) + if (sibling.parent == parent && sibling.placement.column == 0) + occupied.emplace_back(sibling.placement.row, sibling.placement.row + sibling.placement.rows); + std::sort(occupied.begin(), occupied.end()); + for (const auto &[start, end] : occupied) { + if (node.placement.row < start) break; + node.placement.row = (std::max)(node.placement.row, end); + } + if (node.placement.row > 65535) { DestroyWindow(node.object); return failure("grid row limit exceeded"); } + } + const HWND object = node.object; + const bool track_focus = focusable(node.kind); + impl_->nodes.emplace(handle, std::move(node)); + impl_->handles.emplace(object, handle); + if (track_focus) { + // Keep the original procedure in the control's user data; the provider + // only needs WM_SETFOCUS, and every other message stays untouched. + const auto original = GetWindowLongPtrW(object, GWLP_WNDPROC); + SetWindowLongPtrW(object, GWLP_USERDATA, original); + SetWindowLongPtrW(object, GWLP_WNDPROC, reinterpret_cast(&Impl::control_proc)); + } + impl_->text_bytes += label.size(); + impl_->relayout(impl_->nodes.at(handle).window); + } catch (...) { + auto found = impl_->nodes.find(handle); + if (found != impl_->nodes.end()) { + impl_->handles.erase(found->second.object); + DestroyWindow(found->second.object); + impl_->nodes.erase(found); + } else DestroyWindow(node.object); + return failure("widget allocation failed"); + } + return success(handle); +} + +Result Context::grid_attach(std::int64_t grid, std::int64_t child, std::int64_t column, + std::int64_t row, std::int64_t column_span, std::int64_t row_span) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *parent = impl_->find(grid); auto *node = impl_->find(child); + if (!parent || !node) return Impl::bad_handle(); + if (parent->kind != Kind::grid || node->parent != grid) + return failure("grid_attach requires a child of the specified grid"); + if (column < 0 || row < 0 || column_span < 1 || row_span < 1 || + column > 65535 || row > 65535 || column_span > 65536 - column || row_span > 65536 - row) + return failure("grid coordinates and spans must fit within 0..65535"); + Placement placement{column, row, column_span, row_span}; + for (const auto &[id, other] : impl_->nodes) + if (id != child && other.parent == grid && overlaps(placement, other.placement)) + return failure("grid placement overlaps an existing child"); + node->placement = placement; + impl_->relayout(node->window); + return success(); +} + +Result Context::set_text(std::int64_t handle, const std::string &text) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + if (!valid_text(text)) return failure(text_error); + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (container(node->kind) && node->kind != Kind::window) return failure("container does not have a text property"); + if (node->kind == Kind::entry && !entry_text_fits(text)) return failure("entry text exceeds 16384 Unicode characters"); + if (text.size() > max_event_text_bytes - (impl_->text_bytes - node->text.size())) return failure("stored text limit exceeded (16 MiB per context)"); + std::string copy = text; + const auto wide = to_wide(copy); + // Programmatic writes must not raise a change event. + ++node->suppress; + const BOOL changed = SetWindowTextW(node->object, wide.c_str()); + --node->suppress; + if (!changed) return failure("Win32 could not set the widget text"); + impl_->text_bytes = impl_->text_bytes - node->text.size() + copy.size(); + node->text = std::move(copy); + if (node->kind != Kind::window) impl_->relayout(node->window); + return success(); +} + +Result Context::read_text(std::int64_t handle) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (container(node->kind) && node->kind != Kind::window) return failure("container does not have a text property"); + Result result; + if (node->kind == Kind::entry) { + const int length = GetWindowTextLengthW(node->object); + std::wstring wide(static_cast(length < 0 ? 0 : length) + 1, L'\0'); + const int copied = GetWindowTextW(node->object, wide.data(), length + 1); + wide.resize(copied < 0 ? 0 : static_cast(copied)); + if (!to_utf8(wide, result.text)) return failure("Win32 returned invalid text"); + } else result.text = node->text; + if (!valid_text(result.text)) return failure(text_error); + return result; +} + +Result Context::set_number(std::int64_t handle, const std::string &property, std::int64_t value) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (property == "focus") { + if (value != 1) return failure("focus accepts only 1 to request keyboard focus"); + if (!focusable(node->kind)) return failure("widget cannot receive keyboard focus"); + if (!impl_->effective_sensitive(*node)) return failure("widget cannot receive keyboard focus"); + impl_->focus_targets[node->window] = handle; + SetFocus(node->object); + return success(); + } + const bool flag = property == "visible" || property == "sensitive" || property == "hexpand" || property == "vexpand" || property == "checked"; + const bool margin = property == "margin" || property == "margin_start" || property == "margin_end" || property == "margin_top" || property == "margin_bottom"; + const bool size = property == "width" || property == "height"; + if (!flag && !margin && !size && property != "spacing") return failure("unknown or read-only numeric property"); + if (flag && value != 0 && value != 1) return failure("flag properties require exactly 0 or 1"); + if ((margin || property == "spacing") && (value < 0 || value > 4096)) return failure("margins and spacing must be between 0 and 4096"); + if (size && (node->kind != Kind::window || value < 1 || value > 16384)) return failure("width and height are window properties between 1 and 16384"); + if (property == "checked" && node->kind != Kind::checkbox) return failure("checked requires a checkbox"); + if (property == "spacing" && !container(node->kind)) return failure("spacing requires a window, row, column, or grid"); + node->properties[property] = value; + if (property == "margin") + for (const auto *side : {"margin_start", "margin_end", "margin_top", "margin_bottom"}) node->properties[side] = value; + + if (property == "visible") { + ShowWindow(node->object, value ? SW_SHOW : SW_HIDE); + if (value && node->kind == Kind::window) { + SetForegroundWindow(node->object); + impl_->relayout(handle); + } else impl_->relayout(node->window); + } else if (property == "sensitive") { + EnableWindow(node->object, value ? TRUE : FALSE); + } else if (property == "checked") { + ++node->suppress; + SendMessageW(node->object, BM_SETCHECK, value ? BST_CHECKED : BST_UNCHECKED, 0); + --node->suppress; + } else if (size) { + RECT frame{0, 0, static_cast(node->properties.at("width")), static_cast(node->properties.at("height"))}; + AdjustWindowRectEx(&frame, static_cast(GetWindowLongPtrW(node->object, GWL_STYLE)), FALSE, 0); + SetWindowPos(node->object, nullptr, 0, 0, frame.right - frame.left, frame.bottom - frame.top, + SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); + impl_->relayout(handle); + } else impl_->relayout(node->window); + return success(); +} + +Result Context::read_number(std::int64_t handle, const std::string &property) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (property == "kind") return success(static_cast(node->kind)); + if (property == "parent") return success(node->parent); + if (property == "checked") { + if (node->kind != Kind::checkbox) return failure("checked requires a checkbox"); + return success(SendMessageW(node->object, BM_GETCHECK, 0, 0) == BST_CHECKED ? 1 : 0); + } + if (property == "visible") + return success((GetWindowLongPtrW(node->object, GWL_STYLE) & WS_VISIBLE) ? 1 : 0); + if (property == "effective_visible") return success(IsWindowVisible(node->object) ? 1 : 0); + if (property == "sensitive") return success(IsWindowEnabled(node->object) ? 1 : 0); + if (property == "effective_sensitive") return success(impl_->effective_sensitive(*node) ? 1 : 0); + if (property == "focus") { + auto found = impl_->focus_targets.find(node->window); + if (found == impl_->focus_targets.end()) return success(0); + if (found->second == handle) return success(1); + auto *target = impl_->find(found->second); + // A compound widget's internal child counts as the widget's own focus. + return success(target && node->object && IsChild(node->object, target->object) ? 1 : 0); + } + if (property == "width" || property == "height") { + if (node->kind == Kind::window) { + RECT client{}; + if (!IsWindowVisible(node->object) || !GetClientRect(node->object, &client) || + (client.right == 0 && client.bottom == 0)) + return success(node->properties.at(property)); + return success(property == "width" ? client.right - client.left : client.bottom - client.top); + } + return success(property == "width" ? node->allocation.right - node->allocation.left + : node->allocation.bottom - node->allocation.top); + } + if (property == "spacing" && !container(node->kind)) return failure("spacing requires a window, row, column, or grid"); + if (property != "spacing" && property != "hexpand" && property != "vexpand" && property != "margin" && + property != "margin_start" && property != "margin_end" && property != "margin_top" && property != "margin_bottom") + return failure("unknown numeric property"); + auto found = node->properties.find(property); + if (property == "margin") { + const auto side_value = [&](const char *side) { + auto item = node->properties.find(side); return item == node->properties.end() ? std::int64_t(0) : item->second; + }; + const auto start = side_value("margin_start"); + if (start != side_value("margin_end") || start != side_value("margin_top") || start != side_value("margin_bottom")) + return failure("margins differ; read each margin side separately"); + return success(start); + } + if (found != node->properties.end()) return success(found->second); + if (property.rfind("margin_", 0) == 0) { + auto all = node->properties.find("margin"); if (all != node->properties.end()) return success(all->second); + } + return success(0); +} + +Result Context::activate(std::int64_t handle) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (node->kind != Kind::button && node->kind != Kind::checkbox) return failure("activate requires a button or checkbox"); + if (!impl_->effective_sensitive(*node)) + return failure("cannot activate an insensitive widget or a child of an insensitive container"); + // BM_CLICK is the real activation path: it toggles an auto checkbox and + // notifies the parent exactly as a user click does. + SendMessageW(node->object, BM_CLICK, 0, 0); + return success(); +} + +Result Context::poll(std::int64_t window) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(window); if (!node) return Impl::bad_handle(); + if (node->kind != Kind::window) return failure("poll requires a window"); + MSG message; + for (unsigned count = 0; count < 128; ++count) { + if (!PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) break; + TranslateMessage(&message); + DispatchMessageW(&message); + } + if (node->event_failure) { + node->event_failure = false; + return failure("event queue limit or allocation exceeded; one or more events were lost"); + } + auto found = std::find_if(impl_->events.begin(), impl_->events.end(), + [window](const auto &event) { return event.window == window; }); + if (found == impl_->events.end()) return success(0); + if (impl_->snapshots.size() >= max_snapshots || found->text.size() > max_event_text_bytes - impl_->snapshot_bytes) + return failure("event snapshot limit exceeded; release previously returned snapshots"); + auto handle = fresh_handle(); if (!handle) return failure("handle space exhausted"); + impl_->snapshots.emplace(handle, *found); + impl_->snapshot_bytes += found->text.size(); impl_->event_bytes -= found->text.size(); + impl_->events.erase(found); + return success(handle); +} + +Result Context::event_number(std::int64_t snapshot, const std::string &field) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto found = impl_->snapshots.find(snapshot); + if (found == impl_->snapshots.end()) return failure("unknown, released, or foreign event snapshot"); + const auto &event = found->second; + if (field == "kind") return success(event.kind); + if (field == "target") return success(event.target); + if (field == "window") return success(event.window); + if (field == "checked") return success(event.checked); + return failure("event field must be kind, target, window, or checked"); +} + +Result Context::event_text(std::int64_t snapshot) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto found = impl_->snapshots.find(snapshot); + if (found == impl_->snapshots.end()) return failure("unknown, released, or foreign event snapshot"); + return {0, found->second.text, {}}; +} + +Result Context::release_event(std::int64_t snapshot) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto found = impl_->snapshots.find(snapshot); + if (found == impl_->snapshots.end()) return failure("unknown, released, or foreign event snapshot"); + impl_->snapshot_bytes -= found->second.text.size(); impl_->snapshots.erase(found); + return success(); +} + +Result Context::destroy_widget(std::int64_t handle) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (node->kind == Kind::window) + return failure("destroy_widget requires a non-window widget; use close for windows"); + auto *parent = impl_->find(node->parent); + if (!parent || !container(parent->kind)) return failure("widget parent is no longer a live container"); + + // Handles increase monotonically and children are created after their + // parent, so one ordered pass collects the complete subtree. + std::vector removed; + try { + removed.reserve(impl_->nodes.size()); + for (const auto &[id, child] : impl_->nodes) + if (id == handle || std::binary_search(removed.begin(), removed.end(), child.parent)) + removed.push_back(id); + } catch (...) { return failure("widget removal allocation failed"); } + + const auto window = node->window; + const HWND root = node->object; + // DestroyWindow takes the descendants with it; ignore their notifications. + impl_->tearing_down = true; + for (auto id : removed) + if (auto *child = impl_->find(id)) impl_->handles.erase(child->object); + DestroyWindow(root); + impl_->tearing_down = false; + + for (auto it = removed.rbegin(); it != removed.rend(); ++it) { + auto found = impl_->nodes.find(*it); + if (found == impl_->nodes.end()) continue; + impl_->text_bytes -= found->second.text.size(); + impl_->nodes.erase(found); + } + const auto targeted = [&](std::int64_t target) { return std::binary_search(removed.begin(), removed.end(), target); }; + for (auto it = impl_->events.begin(); it != impl_->events.end();) { + if (!targeted(it->target)) { ++it; continue; } + impl_->event_bytes -= it->text.size(); it = impl_->events.erase(it); + } + for (auto it = impl_->snapshots.begin(); it != impl_->snapshots.end();) { + if (!targeted(it->second.target)) { ++it; continue; } + impl_->snapshot_bytes -= it->second.text.size(); it = impl_->snapshots.erase(it); + } + auto focus = impl_->focus_targets.find(window); + if (focus != impl_->focus_targets.end() && targeted(focus->second)) impl_->focus_targets.erase(focus); + impl_->relayout(window); + return success(); +} + +Result Context::close(std::int64_t window) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(window); if (!node) return Impl::bad_handle(); + if (node->kind != Kind::window) return failure("close requires a window"); + + const HWND object = node->object; + impl_->tearing_down = true; + for (const auto &[id, child] : impl_->nodes) + if (child.window == window) { + impl_->handles.erase(child.object); + if (child.root) impl_->handles.erase(child.root); + } + SetWindowLongPtrW(object, GWLP_USERDATA, 0); + DestroyWindow(object); + impl_->tearing_down = false; + + for (auto it = impl_->nodes.begin(); it != impl_->nodes.end();) { + if (it->second.window != window) { ++it; continue; } + impl_->text_bytes -= it->second.text.size(); + it = impl_->nodes.erase(it); + } + for (auto it = impl_->events.begin(); it != impl_->events.end();) { + if (it->window != window) { ++it; continue; } + impl_->event_bytes -= it->text.size(); it = impl_->events.erase(it); + } + for (auto it = impl_->snapshots.begin(); it != impl_->snapshots.end();) { + if (it->second.window != window) { ++it; continue; } + impl_->snapshot_bytes -= it->second.text.size(); it = impl_->snapshots.erase(it); + } + impl_->focus_targets.erase(window); + return success(); +} +} // namespace ny::ui diff --git a/nillinker/main.cpp b/nillinker/main.cpp index 2dee08cf..0277c069 100644 --- a/nillinker/main.cpp +++ b/nillinker/main.cpp @@ -1506,6 +1506,9 @@ bool Linker::link(const fs::path &requested_output) { arguments.push_back("legacy_stdio_definitions.lib"); // The runtime's PostgreSQL provider uses bounded Winsock readiness waits. arguments.push_back("ws2_32.lib"); + // The runtime's Win32 desktop provider creates windows and measures text. + arguments.push_back("user32.lib"); + arguments.push_back("gdi32.lib"); // A linked program gets exactly one C runtime, and nil.lib decides which: // it is built /MD, so every reference it makes is an import (__imp_*) that // only the dynamic CRT satisfies. `cl /c` defaults to the *static* CRT, @@ -1546,6 +1549,8 @@ bool Linker::link(const fs::path &requested_output) { // A clang-style driver must forward these as separate linker arguments; // in particular a manifest path containing spaces or commas is one token. arguments.push_back("ws2_32.lib"); + arguments.push_back("user32.lib"); + arguments.push_back("gdi32.lib"); arguments.push_back("-Xlinker"); arguments.push_back("/MANIFEST:EMBED"); arguments.push_back("-Xlinker"); diff --git a/notebook/2026-11-02-windows-port.md b/notebook/2026-11-02-windows-port.md index 6865656c..10aa5197 100644 --- a/notebook/2026-11-02-windows-port.md +++ b/notebook/2026-11-02-windows-port.md @@ -2677,3 +2677,70 @@ unchanged; the full paired SDK baseline remains `5630388`. Source/input/binary seals and owned cleanup were verified. See the [complete follow-up and retained setup failures](2026-11-04-macos-parity-plan.md#private-windows-compiler-identity-regression) for exact evidence and the process-local DIA/Release try-compile configuration. + + +## 2026-11-08: complete local suite and the per-platform provider decision + +The first complete Windows suite since the port closeout ran on the provisioned +VM at `8aa60d2`, against a same-commit Linux reference of 572 registered tests, +zero failures and three environment skips. + +**Inventory.** Windows registers 574 tests to Linux's 572; the two share 569. +Windows adds console UTF-8, unmanifested UTF-8 file paths, the GTK loader, a +native memory-limit self-test and the SDK preflight. Linux keeps toolchain +inputs, POSIX process semantics and `nilinterpreter.ai-checkpoint-channel`. The +last of those is worth naming precisely because a Linux-only interpreter test +reads like a missing Windows feature and is not one: it drives +`socket.socketpair()` backpressure in the Python acceptance client, while the +product-level `nilinterpreter.ai-checkpoint-contract` is registered and passes on +both hosts. The Windows-only memory-limit entry is likewise additive, a self-test +of the launcher Windows needs because Linux obtains the same bound from +`setrlimit`. An earlier estimate of 571 Windows tests was wrong: it assumed +platform gating only subtracts from the reference inventory. + +**No language gap.** Nothing in the language, frontend, type checker, IR, +interpreter, LLVM backend or standard library fails. Of the five reported +failures, four are an artifact of the harness rather than of the product. The +scheduled task had been registered `/ru SYSTEM`, and that account reports `TEMP` +as `C:\WINDOWS\TEMP`; `tempfile` propagates that casing into the paths handed to +the tools, the tools report paths in their on-disk casing `C:\Windows\Temp`, and +`matrix.annotations`, `matrix.execution`, `nil.bugpass-lexer-contract` and +`nilbuild.compiler-identity-contract` each assert an exact `path:line` substring. +All four pass unchanged when the same binaries are re-run under an ordinary user +account, where the environment variable, `tempfile` and the directory on disk +agree. Earlier green runs used a user account, so this was never product drift. + +**A genuine platform difference, recorded rather than fixed.** The tools report a +canonicalized path on Windows, so a caller can receive a different string from +the one it passed; Linux echoes the argument verbatim. Normal accounts never +observe this, but exact-match consumers such as editor and LSP clients would. + +**Two environment prerequisites the repository does not state.** +`nil.windows-sdk-preflight` invokes `powershell.exe -File scripts/build-sdk.ps1` +deliberately without a bypass, so all eleven subtests observe +"running scripts is disabled on this system" while the machine execution policy +is `Restricted` — the Windows client default. `nil.ui-display` and +`nilagent.window-discovery` self-skip for want of an interactive desktop session, +which SSH does not provide; Win32 UI acceptance will need a console or RDP +session on the VM rather than the headless path used for the language suite. + +**Harness faults worth remembering.** A `call vcvars64.bat` redirected into the +same log the rest of a batch script appends to leaves a background Visual Studio +process holding that inherited handle; every following `>>` then fails with a +sharing violation, cmd reports it on the console rather than in the log, skips +the redirected command outright and sets errorlevel 1. Under `schtasks` the +console is discarded, so an entire configure/build/test script can appear to hang +at the vcvars banner while nothing after it has run. Give vcvars its own file. +Separately, the prebuilt LLVM 18.1.8 package hardcodes a VS2019 Professional DIA +SDK path from its build machine; `cmake/NilLlvmDia.cmake` detects this and +declines to guess a replacement, so the configure needs +`-DNIL_LLVM_DIA_LIBRARY` pointed at the installed `diaguids.lib`. + +**Decision.** With core language parity established on Windows, desktop UI moves +to one provider per platform: GTK remains the Linux provider, Win32 becomes the +Windows provider and AppKit the macOS provider. GTK on macOS is retired; the +directed-input evidence at `8aa60d2` showed every accessibility query against a +GTK process returning `kAXErrorCannotComplete`, including the application +element's own role and attribute names, because GTK pumps GLib and never runs +`-[NSApplication run]` while AppKit services those requests from the main run +loop. Win32 is implemented first, since it can be exercised on a local VM. diff --git a/tests/tools/windows_ui_loader_contract.py b/tests/tools/windows_ui_loader_contract.py deleted file mode 100644 index d9953948..00000000 --- a/tests/tools/windows_ui_loader_contract.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env python3 -"""Isolated Windows GTK loader controls; no display or installed SDK mutation.""" -from __future__ import annotations - -import argparse -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile - -sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'validation/ny-3d/scripts')) -from debugger_process import OwnedProcess - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--probe', type=Path, required=True) - parser.add_argument('--gtk-directory', type=Path, - help='Optional real provider; when supplied, positive and search-isolation controls are mandatory.') - args = parser.parse_args() - if sys.platform != 'win32': - print('SKIP: Windows DLL loader contract') - return 77 - probe = args.probe.resolve(strict=True) - configured = args.gtk_directory or os.environ.get('NIL_UI_GTK_DIRECTORY') - runtime = Path(configured).resolve(strict=True) if configured else None - if runtime is not None and not runtime.is_dir(): - raise AssertionError('GTK runtime must be a directory') - root = Path(tempfile.mkdtemp(prefix='nil-ui-loader-cafĆ©-äø­ę–‡-')) - cases = [] - succeeded = False - try: - # The probe links nilruntime statically. Keep GTK out of its executable - # directory so PATH/CWD controls cannot accidentally use that fallback. - executable_dir = root / 'application' - executable_dir.mkdir() - executable = executable_dir / probe.name - shutil.copyfile(probe, executable) - clean = {key: value for key, value in os.environ.items() - if key.upper() not in ('NIL_UI_GTK_DIRECTORY', 'GDK_BACKEND')} - selected = root / 'selected cafĆ© äø­ę–‡' - selected.mkdir() - - def invoke(name, directory=None, present=False, cwd=selected, path_prefix=None): - environment = dict(clean) - if directory is not None: - environment['NIL_UI_GTK_DIRECTORY'] = str(directory) - if path_prefix: - environment['PATH'] = str(path_prefix) + os.pathsep + environment.get('PATH', '') - mode = '--provider-present' if present else '--provider-absent' - child = OwnedProcess([executable, mode], cwd=cwd, env=environment, - stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = child.communicate(timeout=15) - record = {'name': name, 'exit': child.process.returncode, - 'stdout': stdout.decode('utf-8', errors='replace'), - 'stderr': stderr.decode('utf-8', errors='replace')} - cases.append(record) - if child.process.returncode != 0: - raise AssertionError(record) - - invoke('missing optional provider') - invoke('explicit relative directory rejected', '.') - invoke('explicit empty directory rejected', '') - invoke('explicit missing directory rejected', selected / 'not present') - marker = root / 'not-a-directory' - marker.write_bytes(b'test-only ordinary file') - invoke('explicit regular file rejected', marker) - for name in ('libgtk-4-1.dll', 'libgobject-2.0-0.dll', 'libglib-2.0-0.dll'): - (selected / name).write_bytes(b'test-only invalid DLL, never executable') - invoke('invalid DLL payload rejected', selected) - - if runtime is not None: - invoke('explicit real runtime available without PATH', runtime, present=True) - invoke('real runtime in CWD and PATH is not searched', cwd=runtime, path_prefix=runtime) - invoke('invalid explicit directory does not use CWD or PATH', selected / 'missing', - cwd=runtime, path_prefix=runtime) - # All three direct libraries are present but their other runtime - # dependencies are not. Real dependencies in PATH/CWD must not be - # silently used by this provider's restricted LoadLibraryEx call. - incomplete = root / 'incomplete runtime' - incomplete.mkdir() - for stem in ('gtk-4-1.dll', 'gobject-2.0-0.dll', 'glib-2.0-0.dll'): - found = [runtime / name for name in (stem, 'lib' + stem) if (runtime / name).is_file()] - if len(found) != 1: - raise AssertionError(f'Expected one unambiguous runtime library: {stem}') - shutil.copyfile(found[0], incomplete / found[0].name) - invoke('dependencies do not fall back to CWD or PATH', incomplete, - cwd=runtime, path_prefix=runtime) - succeeded = True - print(json.dumps({'status': 'PASS', 'checks': len(cases), - 'realProviderControls': runtime is not None, 'cases': cases}, indent=2)) - return 0 - finally: - if succeeded: - shutil.rmtree(root) - else: - (root / 'failure-evidence.json').write_text(json.dumps(cases, indent=2), encoding='utf-8') - print(f'Windows GTK loader failure evidence retained: {root}', file=sys.stderr) - - -if __name__ == '__main__': - raise SystemExit(main()) diff --git a/tests/windows_toolchain_inputs_tests.cpp b/tests/windows_toolchain_inputs_tests.cpp index 76710d51..056aa0ac 100644 --- a/tests/windows_toolchain_inputs_tests.cpp +++ b/tests/windows_toolchain_inputs_tests.cpp @@ -70,7 +70,8 @@ void closure(const fs::path &root) { write(runtime, "NIL runtime archive"); for (const auto *name : {"msvcrt.lib", "vcruntime.lib", "legacy_stdio_definitions.lib", "msvcprt.lib", "oldnames.lib"}) write(vc / name, name); - for (const auto *name : {"kernel32.lib", "ws2_32.lib", "ucrt.lib", "uuid.lib"}) write(sdk / name, name); + for (const auto *name : {"kernel32.lib", "ws2_32.lib", "user32.lib", "gdi32.lib", + "ucrt.lib", "uuid.lib"}) write(sdk / name, name); write(ambient / "ambient.lib", "ambient library"); std::map directives; directives[runtime] = " /DEFAULTLIB:msvcprt /DEFAULTLIB:oldnames\n"; From f1b1acfb019bf61595d5928eeee683eb3d9bb5f8 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 19:52:57 -0500 Subject: [PATCH 2/7] Give Windows its own provider fixture and deliver its control events tests/ui_runtime_tests.cpp inspects loaded GTK modules, dlopen symbol origins and GTK's internal top-level registry, so it describes the GTK provider and cannot speak for Win32. The provider fixture now follows the provider: Windows builds tests/ui_runtime_win32_tests.cpp and both nil.ui-runtime and the display contract's --provider-test use whichever fixture matches the platform. The new fixture runs the published contract against a real desktop -- widget creation and kinds, UTF-8 text round-tripping, the provider's own layout allocation, button and checkbox activation events, event suppression for programmatic writes, keyboard focus, inherited sensitivity, grid placement and overlap rejection, subtree destruction and close invalidation -- and checks the documented rejection wording. Without an interactive window station it instead requires that window creation is refused, so a service session still exercises something. That fixture immediately found a real defect. WM_COMMAND is delivered to a control's immediate parent, which for anything inside a row, column or grid is that container rather than the window, but only windows and their root containers carried the context pointer in GWLP_USERDATA. Every button, checkbox and entry notification raised inside a container was therefore dropped, and no event ever reached poll. Containers now carry the same pointer. On a real desktop nil.ui-runtime passes with the Win32 provider, which is the first demonstration that the provider works rather than merely builds. nil.ui-display still fails at its lifecycle step: the fixture in tests/ui_lifecycle_tests.cpp observes GTK's registry directly and reports "GTK registry observer symbols unavailable", so it needs the same per-platform treatment next. Headless behaviour is unchanged -- nil.ui-runtime passes through its no-desktop branch and nil.ui-display still skips for want of a session. Co-Authored-By: Claude Opus 5 --- CMakeLists.txt | 24 ++- nilcompiler/src/ui_runtime_win32.cpp | 5 + tests/ui_runtime_win32_tests.cpp | 223 +++++++++++++++++++++++++++ 3 files changed, 246 insertions(+), 6 deletions(-) create mode 100644 tests/ui_runtime_win32_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 42de5cae..ae89cd88 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -247,11 +247,23 @@ if(BUILD_TESTING) add_test(NAME nil.etp-codec COMMAND $) set_tests_properties(nil.etp-codec PROPERTIES LABELS "tools;ipc;etp" TIMEOUT 30) - add_executable(nil_ui_runtime_tests tests/ui_runtime_tests.cpp) - target_link_libraries(nil_ui_runtime_tests PRIVATE nilruntime Threads::Threads) - target_include_directories(nil_ui_runtime_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") - target_compile_features(nil_ui_runtime_tests PRIVATE cxx_std_17) - add_test(NAME nil.ui-runtime COMMAND $) + # The provider fixture follows the provider: tests/ui_runtime_tests.cpp + # inspects loaded GTK modules and symbol origins, so it describes the GTK + # provider and cannot speak for Win32. + if(WIN32) + add_executable(nil_ui_runtime_win32_tests tests/ui_runtime_win32_tests.cpp) + target_link_libraries(nil_ui_runtime_win32_tests PRIVATE nilruntime Threads::Threads) + target_include_directories(nil_ui_runtime_win32_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_compile_features(nil_ui_runtime_win32_tests PRIVATE cxx_std_17) + set(NIL_UI_PROVIDER_TEST nil_ui_runtime_win32_tests) + else() + add_executable(nil_ui_runtime_tests tests/ui_runtime_tests.cpp) + target_link_libraries(nil_ui_runtime_tests PRIVATE nilruntime Threads::Threads) + target_include_directories(nil_ui_runtime_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_compile_features(nil_ui_runtime_tests PRIVATE cxx_std_17) + set(NIL_UI_PROVIDER_TEST nil_ui_runtime_tests) + endif() + add_test(NAME nil.ui-runtime COMMAND $) set_tests_properties(nil.ui-runtime PROPERTIES LABELS "ui;runtime" TIMEOUT 30) add_executable(nil_ui_lifecycle_tests tests/ui_lifecycle_tests.cpp) target_link_libraries(nil_ui_lifecycle_tests PRIVATE nilcompiler_core nilruntime ${CMAKE_DL_LIBS}) @@ -638,7 +650,7 @@ if(BUILD_TESTING) --sdk "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/ui/gtk_desktop.matrix" --interaction-source "${CMAKE_CURRENT_SOURCE_DIR}/tests/ui/gtk_interaction.matrix" - --provider-test $ + --provider-test $ --lifecycle-test $ --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(nil.ui-display PROPERTIES LABELS "ui;routes" SKIP_RETURN_CODE 77 TIMEOUT "${NIL_UI_DISPLAY_TIMEOUT}") diff --git a/nilcompiler/src/ui_runtime_win32.cpp b/nilcompiler/src/ui_runtime_win32.cpp index 5a3ff5ba..146f9c83 100644 --- a/nilcompiler/src/ui_runtime_win32.cpp +++ b/nilcompiler/src/ui_runtime_win32.cpp @@ -677,8 +677,13 @@ Result Context::widget(const std::string &kind, std::int64_t parent, const std:: } const HWND object = node.object; const bool track_focus = focusable(node.kind); + const bool is_container = container(node.kind); impl_->nodes.emplace(handle, std::move(node)); impl_->handles.emplace(object, handle); + // A control's WM_COMMAND is delivered to its immediate parent, which for + // anything inside a row, column or grid is that container rather than the + // window. Without the context here those notifications are dropped. + if (is_container) SetWindowLongPtrW(object, GWLP_USERDATA, reinterpret_cast(impl_.get())); if (track_focus) { // Keep the original procedure in the control's user data; the provider // only needs WM_SETFOCUS, and every other message stays untouched. diff --git a/tests/ui_runtime_win32_tests.cpp b/tests/ui_runtime_win32_tests.cpp new file mode 100644 index 00000000..ede003ec --- /dev/null +++ b/tests/ui_runtime_win32_tests.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +// Windows provider contract for ui.v1. The GTK fixture in ui_runtime_tests.cpp +// inspects loaded GTK modules and symbol origins, so it describes that +// provider rather than this one; Windows gets its own fixture for the same +// published contract. +// +// Modes match what tests/tools/windows_ui_display_contract.py invokes: +// --provider-present availability only, no window +// --display the full contract against a real desktop +// With no argument the fixture adapts: it runs the full contract when the +// process has an interactive window station and otherwise checks that window +// creation is refused, so the same test is meaningful in a service session. +#include "ui_runtime.hpp" + +#include +#include +#include + +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +namespace { + +int checks = 0; + +void require(bool condition, const char *what) { + ++checks; + if (condition) return; + std::cout.flush(); + std::cerr << "UI runtime test failure: " << what << "\n"; + std::exit(1); +} + +std::int64_t ok(const ny::ui::Result &result, const char *what) { + if (!result) { + std::cout.flush(); + std::cerr << "UI runtime test failure: " << what << ": " << result.error << "\n"; + std::exit(1); + } + ++checks; + return result.number; +} + +void rejected(const ny::ui::Result &result, const char *fragment, const char *what) { + ++checks; + if (!result.error.empty() && result.error.find(fragment) != std::string::npos) return; + std::cout.flush(); + std::cerr << "UI runtime test failure: " << what << ": expected rejection containing '" + << fragment << "', got '" << result.error << "'\n"; + std::exit(1); +} + +bool interactive_station() { + const HWINSTA station = GetProcessWindowStation(); + if (!station) return false; + USEROBJECTFLAGS flags{}; + DWORD needed = 0; + if (!GetUserObjectInformationW(station, UOI_FLAGS, &flags, sizeof flags, &needed)) return false; + return (flags.dwFlags & WSF_VISIBLE) != 0; +} + +// Drains one event for the window, pumping until it appears or the bound is +// reached. Activation delivers WM_COMMAND synchronously, so this is a guard +// against a lost event rather than a wait loop. +std::int64_t next_event(ny::ui::Context &context, std::int64_t window) { + for (int attempt = 0; attempt < 32; ++attempt) { + const auto polled = context.poll(window); + if (!polled) return 0; + if (polled.number) return polled.number; + Sleep(5); + } + return 0; +} + +void contract() { + ny::ui::Context context; + const auto window = ok(context.window("NIL Win32 provider", 420, 320), "create window"); + require(window > 0, "window handle is nonzero"); + require(ok(context.read_number(window, "kind"), "window kind") == 0, "window reports kind 0"); + require(ok(context.read_number(window, "parent"), "window parent") == 0, "window has no parent"); + + // Creation is hidden until visible is set, and width/height report the + // requested size while the window is unrealized. + require(ok(context.read_number(window, "visible"), "window visible") == 0, "window starts hidden"); + require(ok(context.read_number(window, "width"), "window width") == 420, "window reports requested width"); + require(ok(context.read_number(window, "height"), "window height") == 320, "window reports requested height"); + + const auto column = ok(context.widget("column", window, ""), "create column"); + require(ok(context.read_number(column, "kind"), "column kind") == 1, "column reports kind 1"); + require(ok(context.read_number(column, "parent"), "column parent") == window, "column parent is the window"); + + const auto label = ok(context.widget("label", column, "Hello"), "create label"); + const auto button = ok(context.widget("button", column, "Press"), "create button"); + const auto check = ok(context.widget("checkbox", column, "Check"), "create checkbox"); + const auto entry = ok(context.widget("entry", column, "abc"), "create entry"); + + const auto text = context.read_text(label); + require(ok(text, "read label") == 0 && text.text == "Hello", "label keeps its text"); + const auto typed = context.read_text(entry); + require(ok(typed, "read entry") == 0 && typed.text == "abc", "entry reports its live text"); + + // Non-ASCII must survive the UTF-8/UTF-16 conversion in both directions. + const std::string unicode = "caf\xc3\xa9 \xe4\xb8\xad\xe6\x96\x87"; + ok(context.set_text(label, unicode), "set unicode label"); + const auto round_trip = context.read_text(label); + require(ok(round_trip, "read unicode label") == 0 && round_trip.text == unicode, + "label round-trips non-ASCII text"); + + ok(context.set_number(window, "visible", 1), "present window"); + require(ok(context.read_number(window, "visible"), "window visible") == 1, "window reports visible"); + require(ok(context.read_number(label, "effective_visible"), "label effective visible") == 1, + "a child of a shown window is effectively visible"); + + // The provider owns layout on Win32, so a realized child must have a real + // allocation rather than the zero size USER32 creates it with. + require(ok(context.read_number(entry, "width"), "entry width") > 0, "provider allocates entry width"); + require(ok(context.read_number(entry, "height"), "entry height") > 0, "provider allocates entry height"); + + // Button activation travels the real BM_CLICK path and reports one event. + require(next_event(context, window) == 0, "no event is queued before activation"); + ok(context.activate(button), "activate button"); + const auto snapshot = next_event(context, window); + require(snapshot != 0, "button activation produces an event"); + require(ok(context.event_number(snapshot, "kind"), "event kind") == 1, "button activation is event kind 1"); + require(ok(context.event_number(snapshot, "target"), "event target") == button, "event targets the button"); + require(ok(context.event_number(snapshot, "window"), "event window") == window, "event names its window"); + ok(context.release_event(snapshot), "release button event"); + + // An auto checkbox toggles through the same path and reports its state. + require(ok(context.read_number(check, "checked"), "checkbox state") == 0, "checkbox starts clear"); + ok(context.activate(check), "activate checkbox"); + const auto toggled = next_event(context, window); + require(toggled != 0, "checkbox activation produces an event"); + require(ok(context.event_number(toggled, "kind"), "toggle kind") == 3, "checkbox toggle is event kind 3"); + require(ok(context.event_number(toggled, "checked"), "toggle checked") == 1, "toggle reports the new state"); + require(ok(context.read_number(check, "checked"), "checkbox state") == 1, "checkbox is now set"); + ok(context.release_event(toggled), "release toggle event"); + + // Programmatic writes must stay silent, or a model binding would see its + // own update echoed back as user input. + ok(context.set_text(entry, "quiet"), "set entry text"); + require(next_event(context, window) == 0, "programmatic set_text raises no event"); + ok(context.set_number(check, "checked", 0), "clear checkbox"); + require(next_event(context, window) == 0, "programmatic checked raises no event"); + + ok(context.set_number(entry, "focus", 1), "focus entry"); + require(ok(context.read_number(entry, "focus"), "entry focus") == 1, "entry reports keyboard focus"); + + // Sensitivity is inherited, and an insensitive control cannot be activated. + ok(context.set_number(column, "sensitive", 0), "disable column"); + require(ok(context.read_number(button, "effective_sensitive"), "button effective sensitive") == 0, + "a child of an insensitive container is insensitive"); + rejected(context.activate(button), "insensitive", "activate insensitive button"); + ok(context.set_number(column, "sensitive", 1), "re-enable column"); + + // Grid placement, automatic rows and overlap rejection. + const auto grid = ok(context.widget("grid", window, ""), "create grid"); + const auto first = ok(context.widget("label", grid, "one"), "create grid child one"); + const auto second = ok(context.widget("label", grid, "two"), "create grid child two"); + ok(context.grid_attach(grid, first, 0, 0, 1, 1), "attach first grid child"); + rejected(context.grid_attach(grid, second, 0, 0, 1, 1), "overlaps", "overlapping grid placement"); + ok(context.grid_attach(grid, second, 1, 0, 1, 1), "attach second grid child"); + + // Rejected inputs keep their published wording. + rejected(context.widget("menu", window, ""), "widget kind", "unknown widget kind"); + rejected(context.widget("label", 0, ""), "handle", "unknown parent handle"); + rejected(context.set_number(button, "visible", 2), "0 or 1", "non-boolean flag"); + rejected(context.set_number(column, "spacing", 9000), "4096", "out-of-range spacing"); + rejected(context.set_number(button, "checked", 1), "checkbox", "checked on a button"); + rejected(context.read_number(column, "text"), "numeric property", "unknown numeric property"); + rejected(context.read_text(column), "container", "text on a container"); + rejected(context.destroy_widget(window), "non-window", "destroy_widget on a window"); + rejected(context.poll(button), "window", "poll on a widget"); + rejected(context.set_text(label, std::string("\xff\xfe")), "UTF-8", "invalid UTF-8 text"); + + // Destroying a subtree invalidates its descendants but nothing else. + const auto doomed = ok(context.widget("row", column, ""), "create row"); + const auto child = ok(context.widget("label", doomed, "gone"), "create row child"); + ok(context.destroy_widget(doomed), "destroy row"); + rejected(context.read_number(child, "kind"), "handle", "descendant handle is invalidated"); + require(ok(context.read_number(label, "kind"), "surviving label") == 4, "unrelated widgets survive"); + + // Closing the window invalidates everything inside it. + ok(context.close(window), "close window"); + rejected(context.read_number(label, "kind"), "handle", "closed window invalidates its children"); + rejected(context.close(window), "handle", "closing twice is an error"); +} + +} // namespace + +int main(int argc, char **argv) { + const std::string mode = argc > 1 ? argv[1] : ""; + require(ny::ui::available(), "Windows provider is always available"); + if (mode == "--provider-present") { + std::cout << "UI runtime: " << checks << " checks passed (--provider-present)\n"; + return 0; + } + const bool desktop = interactive_station(); + if (mode == "--display") { + require(desktop, "--display requires an interactive window station"); + contract(); + std::cout << "UI runtime: " << checks << " checks passed (--display)\n"; + return 0; + } + if (desktop) contract(); + else { + // A service session has no desktop: creation must fail, and say why. + ny::ui::Context context; + rejected(context.window("no station", 320, 240), "interactive Windows window station", + "window creation without an interactive station"); + } + std::cout << "UI runtime: " << checks << " checks passed (" + << (desktop ? "desktop" : "no-desktop") << ")\n"; + return 0; +} From 3aea416f56b9cecd6e56917d91a88eb523653ece Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 20:17:21 -0500 Subject: [PATCH 3/7] Remove the GTK provider's dead Windows loader Windows builds the Win32 provider, so ui_runtime.cpp is no longer compiled there and its Windows half had become unreachable: the NIL_UI_GTK_DIRECTORY selection, the DLL naming family and search-flag handling, the already-loaded module matching, the interactive window station probe and the Windows branches of the loader and of the display error. Leaving them would invite maintenance of a path no build can reach and no test can reject. The one change that is not a deletion is the display error's `#elif defined(__APPLE__)` becoming `#if`, now that no Windows branch precedes it; the macOS and Linux messages are unchanged. Linux is unaffected at 572 registered, 0 failed and 3 environment skips. Windows cannot be affected, because this file is not part of its build. Co-Authored-By: Claude Opus 5 --- nilcompiler/src/ui_runtime.cpp | 142 +-------------------------------- 1 file changed, 1 insertion(+), 141 deletions(-) diff --git a/nilcompiler/src/ui_runtime.cpp b/nilcompiler/src/ui_runtime.cpp index 5ea9bc21..66f1d4e9 100644 --- a/nilcompiler/src/ui_runtime.cpp +++ b/nilcompiler/src/ui_runtime.cpp @@ -23,12 +23,6 @@ #include #include #endif -#elif defined(_WIN32) -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include -#include #endif namespace ny::ui { @@ -43,91 +37,6 @@ using Callback = void (*)(); using ClosureNotify = void (*)(void *, GClosure *); enum ConnectFlags { connect_default = 0 }; -#if defined(_WIN32) -// Windows has no system GTK installation convention. Select exactly one -// explicitly trusted runtime directory, or the application's own directory. -// Neither the current directory nor PATH participates, and the provider never -// changes process-wide DLL search settings or the caller's environment. -std::filesystem::path gtk_directory() { - constexpr DWORD limit = 32768; - SetLastError(ERROR_SUCCESS); - const DWORD required = GetEnvironmentVariableW(L"NIL_UI_GTK_DIRECTORY", nullptr, 0); - std::wstring directory; - if (required) { - if (required > limit) return {}; - directory.resize(required); - const DWORD length = GetEnvironmentVariableW(L"NIL_UI_GTK_DIRECTORY", directory.data(), required); - if (!length || length >= required) return {}; - directory.resize(length); - } else { - // An explicitly empty setting is invalid, not permission to fall back. - if (GetLastError() != ERROR_ENVVAR_NOT_FOUND) return {}; - directory.resize(limit); - const DWORD length = GetModuleFileNameW(nullptr, directory.data(), limit); - if (!length || length >= limit) return {}; - directory.resize(length); - directory = std::filesystem::path(directory).parent_path().native(); - } - std::filesystem::path result(directory); - std::error_code error; - if (!result.is_absolute() || !std::filesystem::is_directory(result, error) || error) return {}; - return result.make_preferred(); -} - -std::filesystem::path gtk_library(const std::filesystem::path &directory, const wchar_t *name) { - // GTK builds use either the MSVC or MinGW DLL naming convention. Resolve - // each component within the one directory; ambiguous names are rejected. - std::filesystem::path selected; - for (const auto &filename : {std::wstring(name), L"lib" + std::wstring(name)}) { - const auto candidate = directory / filename; - std::error_code error; - if (!std::filesystem::is_regular_file(candidate, error) || error) continue; - if (!selected.empty()) return {}; - selected = candidate; - } - return selected; -} - -bool gtk_library_matches(HMODULE library, const std::filesystem::path &file) { - std::wstring actual(32768, L'\0'); - const DWORD length = GetModuleFileNameW(library, actual.data(), static_cast(actual.size())); - if (!length || length >= actual.size()) return false; - actual.resize(length); - std::error_code error; - return std::filesystem::equivalent(file, std::filesystem::path(actual), error) && !error; -} - -HMODULE load_gtk_library(const std::filesystem::path &file) { - // A dependency may bind to an already loaded basename before consulting - // search directories. Refuse a different installation before loading more - // of the selected stack, as well as checking the returned module identity. - if (const auto existing = GetModuleHandleW(file.filename().c_str()); - existing && !gtk_library_matches(existing, file)) return nullptr; - const HMODULE library = LoadLibraryExW(file.c_str(), nullptr, - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); - return library && gtk_library_matches(library, file) ? library : nullptr; -} - -bool interactive_window_station() noexcept { - // GTK's Win32 backend can report successful initialization on a service - // window station, then fault while constructing its first GtkWindow. Refuse - // that unsupported environment before calling any GTK initialization API. - // GTK already loads User32. Resolve these read-only queries from that module - // instead of adding a new static dependency or changing station/desktop state. - const HMODULE user = GetModuleHandleW(L"user32.dll"); - if (!user) return false; - using Station = HWINSTA (WINAPI *)(); - using Information = BOOL (WINAPI *)(HANDLE, int, PVOID, DWORD, LPDWORD); - const auto station = reinterpret_cast(GetProcAddress(user, "GetProcessWindowStation")); - const auto information = reinterpret_cast(GetProcAddress(user, "GetUserObjectInformationW")); - if (!station || !information) return false; - const HWINSTA current = station(); // Borrowed handle; never close it. - USEROBJECTFLAGS flags{}; - DWORD required = 0; - return current && information(current, UOI_FLAGS, &flags, sizeof(flags), &required) && - required <= sizeof(flags) && (flags.dwFlags & WSF_VISIBLE) != 0; -} -#endif #if defined(__APPLE__) // Darwin has no ambient GTK runtime. A trusted provider directory names the @@ -307,49 +216,6 @@ struct Api { loaded = gtk_get_major_version() == 4; if (!loaded) unavailable = "GTK 4 provider is unavailable: the selected dylib does not provide GTK major version 4"; } catch (...) { /* Optional provider failures must not terminate the host. */ } -#elif defined(_WIN32) - unavailable = "GTK 4 provider is unavailable; set NIL_UI_GTK_DIRECTORY to an absolute trusted GTK 4 runtime bin directory, or place the runtime beside the executable"; - try { - const auto directory = gtk_directory(); - if (directory.empty()) { - unavailable = "GTK 4 provider is unavailable: NIL_UI_GTK_DIRECTORY must name an existing absolute directory"; - return; - } - const auto gtk_path = gtk_library(directory, L"gtk-4-1.dll"); - const auto object_path = gtk_library(directory, L"gobject-2.0-0.dll"); - const auto glib_path = gtk_library(directory, L"glib-2.0-0.dll"); - if (gtk_path.empty() || object_path.empty() || glib_path.empty()) { - unavailable = "GTK 4 provider is unavailable: the selected directory must contain one unambiguous GTK 4, GObject and GLib DLL set"; - return; - } - // Load dependencies first, before GTK can bind to a different stack. - // As on Linux, retain modules for process lifetime even on an incomplete - // load: toolkit global types/caches must never outlive their code. - const HMODULE glib = load_gtk_library(glib_path); - if (!glib) { - unavailable = "GTK 4 provider is unavailable: the selected GLib DLL or its dependencies could not load from the selected directory and System32"; - return; - } - const HMODULE object = load_gtk_library(object_path); - if (!object) { - unavailable = "GTK 4 provider is unavailable: the selected GObject DLL or its dependencies could not load from the selected directory and System32"; - return; - } - const HMODULE gtk = load_gtk_library(gtk_path); - if (!gtk) { - unavailable = "GTK 4 provider is unavailable: the selected GTK DLL or its dependencies could not load from the selected directory and System32"; - return; - } -#define LOAD_SYMBOL(result, name, arguments) \ - name = reinterpret_cast(GetProcAddress(gtk, #name)); \ - if (!name) name = reinterpret_cast(GetProcAddress(object, #name)); \ - if (!name) name = reinterpret_cast(GetProcAddress(glib, #name)); \ - if (!name) { unavailable = "GTK 4 provider is unavailable: missing symbol " #name; return; } - UI_SYMBOLS(LOAD_SYMBOL) -#undef LOAD_SYMBOL - loaded = gtk_get_major_version() == 4; - if (!loaded) unavailable = "GTK 4 provider is unavailable: the selected DLL does not provide GTK major version 4"; - } catch (...) { /* Optional provider failures must not terminate the host. */ } #endif } #undef UI_SYMBOLS @@ -420,14 +286,8 @@ struct Context::Impl : std::enable_shared_from_this { return failure("GTK must be used on the process UI thread"); return success(); } -#if defined(_WIN32) - if (!interactive_window_station()) - return failure("GTK could not open a display; an interactive Windows window station is required (noninteractive service and SSH desktops are unsupported)"); -#endif if (!a.gtk_init_check()) { -#if defined(_WIN32) - return failure("GTK could not open a display; a working Windows desktop session is required"); -#elif defined(__APPLE__) +#if defined(__APPLE__) return failure("GTK could not open a display; a working macOS Quartz desktop session is required"); #else return failure("GTK could not open a display; a working Wayland or X11 session is required"); From 0e0adf89e088bbdd23b6a54946049312d86eca36 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 20:52:57 -0500 Subject: [PATCH 4/7] Route keyboard input on Win32 and finish the Windows UI contract nil.ui-display now passes on Windows: the provider contract, the lifecycle fixture, the Matrix desktop suite and the interaction suite that drives real synthetic keyboard input all run against the Win32 provider on a real desktop. Three things were missing. The lifecycle fixture observed GTK's top-level registry directly and failed with "GTK registry observer symbols unavailable". The observer's purpose is platform-neutral -- prove a window was really released rather than merely invalidated -- so only its mechanism moves: GTK is asked for its registry, while Windows counts this process's live top-level windows of the provider's own class. The fixture's assertions are unchanged, and it still reports exactly the 235 checks the display contract requires, so that constant did not have to become per-platform. Tab order and the activations that go with it are the dialog manager's work on Win32, where GTK does them inside the toolkit, so poll runs messages through IsDialogMessageW and containers carry WS_EX_CONTROLPARENT; without that, Tab cannot reach a control nested in a row, column or grid. The real defect was routing. Windows delivers keystrokes straight to the focused control, so a top level only ever sees keys posted to it deliberately -- which is exactly how the contract drives a window it has not typed into, because GTK routes such input through the toplevel. The pump now retargets that input to the focused control before the dialog manager sees it. An earlier attempt to forward inside the window procedure could not work, because IsDialogMessageW consumed the message first; that code is removed rather than left to confuse. Diagnosis came from a new --input-probe mode, which posts the contract's own key sequence and reports which events arrive. It turned a 30-second deadline into "direct_to_edit=1" with nothing arriving via the top level, naming the fault immediately. That coverage now also runs inside --display, quietly, so a regression reports which event went missing instead of timing out. Linux is unchanged at 572 registered, 0 failed and 3 environment skips. Co-Authored-By: Claude Opus 5 --- nilcompiler/src/ui_runtime_win32.cpp | 30 +++++++- tests/ui_lifecycle_tests.cpp | 17 +++-- tests/ui_registry_observer.hpp | 52 +++++++++---- tests/ui_runtime_tests.cpp | 4 +- tests/ui_runtime_win32_tests.cpp | 109 +++++++++++++++++++++++++++ 5 files changed, 183 insertions(+), 29 deletions(-) diff --git a/nilcompiler/src/ui_runtime_win32.cpp b/nilcompiler/src/ui_runtime_win32.cpp index 146f9c83..578a0c72 100644 --- a/nilcompiler/src/ui_runtime_win32.cpp +++ b/nilcompiler/src/ui_runtime_win32.cpp @@ -544,6 +544,12 @@ struct Context::Impl : std::enable_shared_from_this { namespace { +bool keyboard_message(UINT message) { + return message == WM_KEYDOWN || message == WM_KEYUP || message == WM_CHAR || + message == WM_SYSKEYDOWN || message == WM_SYSKEYUP || message == WM_SYSCHAR || + message == WM_DEADCHAR || message == WM_SYSDEADCHAR; +} + bool focusable(Kind kind) { return kind == Kind::button || kind == Kind::entry || kind == Kind::checkbox; } } // namespace @@ -590,7 +596,8 @@ Result Context::window(const std::string &title, std::int64_t width, std::int64_ frame.bottom - frame.top, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); if (!node.object) return failure("Win32 could not create a window"); - node.root = CreateWindowExW(0, container_class, L"", WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, + node.root = CreateWindowExW(WS_EX_CONTROLPARENT, container_class, L"", + WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, 0, 0, static_cast(width), static_cast(height), node.object, nullptr, GetModuleHandleW(nullptr), nullptr); if (!node.root) { @@ -638,10 +645,12 @@ Result Context::widget(const std::string &kind, std::int64_t parent, const std:: const HINSTANCE instance = GetModuleHandleW(nullptr); if (kind == "column" || kind == "row") { node.kind = kind == "column" ? Kind::column : Kind::row; - node.object = CreateWindowExW(0, container_class, L"", common | WS_CLIPCHILDREN, 0, 0, 0, 0, host, nullptr, instance, nullptr); + node.object = CreateWindowExW(WS_EX_CONTROLPARENT, container_class, L"", + common | WS_CLIPCHILDREN, 0, 0, 0, 0, host, nullptr, instance, nullptr); } else if (kind == "grid") { node.kind = Kind::grid; - node.object = CreateWindowExW(0, container_class, L"", common | WS_CLIPCHILDREN, 0, 0, 0, 0, host, nullptr, instance, nullptr); + node.object = CreateWindowExW(WS_EX_CONTROLPARENT, container_class, L"", + common | WS_CLIPCHILDREN, 0, 0, 0, 0, host, nullptr, instance, nullptr); } else if (kind == "label") { node.kind = Kind::label; node.object = CreateWindowExW(0, L"STATIC", wide.c_str(), common | SS_LEFT | SS_NOPREFIX, 0, 0, 0, 0, host, nullptr, instance, nullptr); @@ -886,6 +895,21 @@ Result Context::poll(std::int64_t window) { MSG message; for (unsigned count = 0; count < 128; ++count) { if (!PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) break; + // Real keystrokes are delivered by the system straight to the focused + // control, so that is what the dialog manager and the control each expect + // to see. Input addressed to the top level instead -- which is how a + // caller drives a window it does not type into -- is retargeted here to + // the focused control, because GTK routes such input through the toplevel + // and the contract is written against that behaviour. + if (keyboard_message(message.message) && message.hwnd == node->object) { + const auto target = impl_->focus_targets.find(window); + if (target != impl_->focus_targets.end()) + if (auto *focused = impl_->find(target->second); focused && focused->object) + message.hwnd = focused->object; + } + // Tab order, arrow groups and the activations that go with them are the + // dialog manager's work on Win32, where GTK does it inside the toolkit. + if (IsDialogMessageW(node->object, &message)) continue; TranslateMessage(&message); DispatchMessageW(&message); } diff --git a/tests/ui_lifecycle_tests.cpp b/tests/ui_lifecycle_tests.cpp index b933284e..cc18dd70 100644 --- a/tests/ui_lifecycle_tests.cpp +++ b/tests/ui_lifecycle_tests.cpp @@ -27,27 +27,28 @@ void require(bool condition, const std::string &message) { } #if defined(__linux__) || defined(_WIN32) || defined(__APPLE__) -// Inspect the toolkit's real window registry, independently of the provider's -// handle map. A stale-handle rejection alone would not prove GTK was released. +// Inspect the toolkit's real live windows, independently of the provider's +// handle map. A stale-handle rejection alone would not prove the window was +// released. The observer is per platform; the assertions here are not. struct Windows { - std::unique_ptr registry; + std::unique_ptr registry; unsigned baseline = 0; Windows() { - require(ny::ui::available(), "GTK 4 is required for lifecycle --display tests"); + require(ny::ui::available(), "a desktop provider is required for lifecycle --display tests"); ny::ui::Context bootstrap; const auto window = bootstrap.window("UI lifecycle initialization", 100, 100); require(static_cast(window), window.error); require(static_cast(bootstrap.close(window.number)), "close initialization window"); - registry = std::make_unique(); + registry = std::make_unique(); baseline = count(); } unsigned count() const { return registry->count(); } void live(const std::string &operation) const { - require(count() == baseline + 1, operation + " must keep exactly one GTK window live"); + require(count() == baseline + 1, operation + " must keep exactly one toolkit window live"); } void empty(const std::string &operation) const { - require(count() == baseline, operation + " must release its GTK window"); + require(count() == baseline, operation + " must release its toolkit window"); } }; @@ -226,7 +227,7 @@ int main(int argc, char **argv) { std::cout << "UI lifecycle: " << checks << " checks passed\n"; return 0; #else - std::cerr << "SKIP: GTK UI lifecycle tests require Linux, Windows or macOS\n"; + std::cerr << "SKIP: UI lifecycle tests require Linux, Windows or macOS\n"; return 77; #endif } catch (const std::exception &error) { diff --git a/tests/ui_registry_observer.hpp b/tests/ui_registry_observer.hpp index 1e395e19..3760388f 100644 --- a/tests/ui_registry_observer.hpp +++ b/tests/ui_registry_observer.hpp @@ -3,6 +3,8 @@ * SPDX-License-Identifier: MIT */ #pragma once +#include +#include #include #if defined(__linux__) || defined(__APPLE__) #include @@ -17,11 +19,15 @@ #include #endif -// Test-only, independent observation of GTK's real top-level registry. The -// provider must already be loaded; Windows never performs a second DLL search. -class GtkRegistryObserver { +// Test-only, independent observation of the toolkit's real live top-level +// windows, so a lifecycle test can tell an actually released window from a +// merely invalidated handle. GTK is asked for its registry; Win32 has no such +// registry, so this counts the operating system's own top-level windows. +class UiRegistryObserver { +#if !defined(_WIN32) void *(*list_)() = nullptr; unsigned (*size_)(void *) = nullptr; +#endif #if defined(__linux__) || defined(__APPLE__) void *library_ = nullptr; #if defined(__APPLE__) @@ -44,14 +50,23 @@ class GtkRegistryObserver { } #endif #elif defined(_WIN32) - static HMODULE loaded(const wchar_t *msvc, const wchar_t *mingw) { - const auto first = GetModuleHandleW(msvc), second = GetModuleHandleW(mingw); - if (first && second) throw std::runtime_error("ambiguous loaded GTK registry dependency"); - return first ? first : second; + // The provider's own window class, which must match window_class in + // nilcompiler/src/ui_runtime_win32.cpp. Counting by class keeps the console + // window and any other process window out of the tally. + static constexpr const wchar_t *provider_class = L"NyUi.Window"; + static BOOL CALLBACK tally(HWND window, LPARAM parameter) { + DWORD process = 0; + GetWindowThreadProcessId(window, &process); + if (process != GetCurrentProcessId()) return TRUE; + wchar_t name[64] = {}; + const int length = GetClassNameW(window, name, static_cast(std::size(name))); + if (length > 0 && std::wcscmp(name, provider_class) == 0) + ++*reinterpret_cast(parameter); + return TRUE; } #endif public: - GtkRegistryObserver() { + UiRegistryObserver() { #if defined(__linux__) library_ = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); if (!library_) throw std::runtime_error("load GTK registry observer"); @@ -75,12 +90,8 @@ class GtkRegistryObserver { initialized_ = reinterpret_cast(initialized); } } -#elif defined(_WIN32) - const auto gtk = loaded(L"gtk-4-1.dll", L"libgtk-4-1.dll"); - const auto gio = loaded(L"gio-2.0-0.dll", L"libgio-2.0-0.dll"); - if (gtk) list_ = reinterpret_cast(GetProcAddress(gtk, "gtk_window_get_toplevels")); - if (gio) size_ = reinterpret_cast(GetProcAddress(gio, "g_list_model_get_n_items")); #endif +#if !defined(_WIN32) if (!list_ || !size_) { #if defined(__linux__) || defined(__APPLE__) if (library_) dlclose(library_); @@ -92,8 +103,9 @@ class GtkRegistryObserver { #endif throw std::runtime_error("GTK registry observer symbols unavailable"); } +#endif } - ~GtkRegistryObserver() { + ~UiRegistryObserver() { #if defined(__linux__) || defined(__APPLE__) if (library_) dlclose(library_); #if defined(__APPLE__) @@ -101,9 +113,17 @@ class GtkRegistryObserver { #endif #endif } - GtkRegistryObserver(const GtkRegistryObserver &) = delete; - GtkRegistryObserver &operator=(const GtkRegistryObserver &) = delete; + UiRegistryObserver(const UiRegistryObserver &) = delete; + UiRegistryObserver &operator=(const UiRegistryObserver &) = delete; +#if defined(_WIN32) + unsigned count() const { + unsigned total = 0; + EnumWindows(&tally, reinterpret_cast(&total)); + return total; + } +#else unsigned count() const { return size_(list_()); } +#endif #if defined(__APPLE__) bool initialized() const { return initialized_() != 0; } #endif diff --git a/tests/ui_runtime_tests.cpp b/tests/ui_runtime_tests.cpp index 9453024b..8a9e8463 100644 --- a/tests/ui_runtime_tests.cpp +++ b/tests/ui_runtime_tests.cpp @@ -139,7 +139,7 @@ void preload_mixed_provider() { void worker_first() { require(ny::ui::available(), "real provider is required for worker-first initialization test"); - GtkRegistryObserver registry; + UiRegistryObserver registry; require(!registry.initialized(), "symbol-only availability must not initialize GTK"); ny::ui::Result result; std::thread worker([&] { @@ -426,7 +426,7 @@ void display_tests() { #if defined(__linux__) || defined(_WIN32) || defined(__APPLE__) // Observe GTK's actual top-level registry across normal and deferred teardown. - GtkRegistryObserver registry; + UiRegistryObserver registry; const auto baseline = registry.count(); for (int index = 0; index < 8; ++index) { auto owner = std::make_unique(); diff --git a/tests/ui_runtime_win32_tests.cpp b/tests/ui_runtime_win32_tests.cpp index ede003ec..549767fb 100644 --- a/tests/ui_runtime_win32_tests.cpp +++ b/tests/ui_runtime_win32_tests.cpp @@ -194,6 +194,108 @@ void contract() { rejected(context.close(window), "handle", "closing twice is an error"); } +// Posts the display contract's own key sequence to the top level and reports +// which events arrive. The contract drives a window it has not brought to the +// foreground, so this isolates provider routing from the rest of that +// pipeline, where the only symptom is a deadline. +void input_probe(bool verbose) { + ny::ui::Context context; + const auto window = ok(context.window("NIL Win32 input probe", 420, 240), "create probe window"); + const auto column = ok(context.widget("column", window, ""), "create probe column"); + const auto entry = ok(context.widget("entry", column, ""), "create probe entry"); + const auto box = ok(context.widget("checkbox", column, "Enable setting"), "create probe checkbox"); + const auto button = ok(context.widget("button", column, "Finish probe"), "create probe button"); + ok(context.set_number(window, "visible", 1), "show probe window"); + ok(context.set_number(entry, "focus", 1), "focus probe entry"); + + HWND top = nullptr; + struct Search { DWORD process; const wchar_t *title; HWND found; } search{GetCurrentProcessId(), L"NIL Win32 input probe", nullptr}; + EnumWindows([](HWND candidate, LPARAM parameter) -> BOOL { + auto *state = reinterpret_cast(parameter); + DWORD process = 0; + GetWindowThreadProcessId(candidate, &process); + if (process != state->process) return TRUE; + wchar_t title[128] = {}; + if (GetWindowTextW(candidate, title, 128) && !wcscmp(title, state->title)) { + state->found = candidate; + return FALSE; + } + return TRUE; + }, reinterpret_cast(&search)); + top = search.found; + require(top != nullptr, "probe window is discoverable by title"); + + // Locate the EDIT so routing can be told apart from the control refusing + // the message, and report whether the system focus agrees with ours. + struct Child { HWND edit; } child{nullptr}; + EnumChildWindows(top, [](HWND candidate, LPARAM parameter) -> BOOL { + wchar_t name[64] = {}; + if (GetClassNameW(candidate, name, 64) && !_wcsicmp(name, L"EDIT")) { + reinterpret_cast(parameter)->edit = candidate; + return FALSE; + } + return TRUE; + }, reinterpret_cast(&child)); + if (verbose) + std::cout << "input probe: edit=" << (child.edit ? "found" : "missing") + << " system_focus_is_edit=" << (child.edit && GetFocus() == child.edit) + << " focus_null=" << (GetFocus() == nullptr) + << " foreground_is_probe=" << (GetForegroundWindow() == top) << "\n"; + + const UINT key_down = 0x100, key_up = 0x101, character = 0x102; + const WPARAM packet = 0xE7, tab = 0x09, space = 0x20; + + // Direct delivery first: if the control accepts this but not the same + // message posted to the top level, the gap is routing and nothing else. + if (child.edit) { + PostMessageW(child.edit, character, static_cast('Z'), 1); + bool direct = false; + for (int attempt = 0; attempt < 50 && !direct; ++attempt) { + const auto polled = context.poll(window); + if (!polled) break; + if (!polled.number) { Sleep(10); continue; } + if (ok(context.event_number(polled.number, "kind"), "direct kind") == 2) direct = true; + ok(context.release_event(polled.number), "release direct event"); + } + if (verbose) std::cout << "input probe: direct_to_edit=" << direct << "\n"; + ok(context.set_text(entry, ""), "reset probe entry"); + } + for (const char *c = "Matrix"; *c; ++c) { + PostMessageW(top, key_down, packet, 1); + PostMessageW(top, character, static_cast(*c), 1); + PostMessageW(top, key_up, packet, 0xC0000001); + } + for (WPARAM key : {tab, space, tab, space}) { + const LPARAM flags = 1 | static_cast(MapVirtualKeyW(static_cast(key), 0)) << 16; + PostMessageW(top, key_down, key, flags); + PostMessageW(top, key_up, key, flags | 0xC0000000); + } + + bool saw_text = false, saw_toggle = false, saw_click = false; + std::string observed; + for (int attempt = 0; attempt < 400 && !saw_click; ++attempt) { + const auto polled = context.poll(window); + if (!polled) break; + if (!polled.number) { Sleep(10); continue; } + const auto kind = ok(context.event_number(polled.number, "kind"), "probe event kind"); + const auto target = ok(context.event_number(polled.number, "target"), "probe event target"); + if (kind == 2 && target == entry) { + observed = context.event_text(polled.number).text; + if (observed == "Matrix") saw_text = true; + } else if (kind == 3 && target == box && + ok(context.event_number(polled.number, "checked"), "probe checked") == 1) saw_toggle = true; + else if (kind == 1 && target == button) saw_click = true; + ok(context.release_event(polled.number), "release probe event"); + } + if (verbose) + std::cout << "input probe: text=" << saw_text << " toggle=" << saw_toggle + << " click=" << saw_click << " entry=\"" << observed << "\"\n"; + ok(context.close(window), "close probe window"); + require(saw_text, "posted characters reach the focused entry"); + require(saw_toggle, "Tab then Space reaches the checkbox"); + require(saw_click, "Tab then Space reaches the button"); +} + } // namespace int main(int argc, char **argv) { @@ -204,9 +306,16 @@ int main(int argc, char **argv) { return 0; } const bool desktop = interactive_station(); + if (mode == "--input-probe") { + require(desktop, "--input-probe requires an interactive window station"); + input_probe(true); + std::cout << "UI runtime: " << checks << " checks passed (--input-probe)\n"; + return 0; + } if (mode == "--display") { require(desktop, "--display requires an interactive window station"); contract(); + input_probe(false); std::cout << "UI runtime: " << checks << " checks passed (--display)\n"; return 0; } From 6c500257c36a53931bcf4413688f3e89df2a909d Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 21:08:06 -0500 Subject: [PATCH 5/7] Record the completed Windows desktop UI docs/platform-support.md still said the GTK provider supports Linux and Windows, which stopped being true when Win32 became the Windows provider. The notebook records what the interactive session proved, the three defects it found that a headless suite could not reach, and the Defender-induced sharing violation that can fail nilbuild.incremental-contract once after a full rebuild without reproducing. Co-Authored-By: Claude Opus 5 --- docs/platform-support.md | 9 +++-- notebook/2026-11-02-windows-port.md | 51 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/docs/platform-support.md b/docs/platform-support.md index 539153db..8c265190 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -169,8 +169,13 @@ the complete admission rules. bound. Native diagnostics show that the fixed 96 MiB virtual-memory cap is rejected at process setup; larger diagnostic profiles do not replace it. Successful lifetime execution routes remain covered by the ordinary suite. -- The GTK provider currently supports Linux and Windows. macOS UI/provider - support and live desktop acceptance remain open. Both hosted Mac architectures +- Desktop UI now uses one provider per platform: GTK on Linux and Win32 on + Windows. The Windows provider passes the full desktop contract on a real + interactive session -- provider contract, lifecycle release observation, the + Matrix desktop suite and the interaction suite that drives real keyboard + input -- while a session without an interactive window station still skips. + macOS UI/provider support and live desktop acceptance remain open; AppKit + replaces the retired GTK-on-macOS work. Both hosted Mac architectures now pass the prerequisite GLib, Cairo-Quartz and HarfBuzz/CoreText compile, link and runtime checks, plus exact own-process AppKit key dispatch, view delivery and window closure. Directed keyboard input to a verified child and diff --git a/notebook/2026-11-02-windows-port.md b/notebook/2026-11-02-windows-port.md index 10aa5197..d6dc4204 100644 --- a/notebook/2026-11-02-windows-port.md +++ b/notebook/2026-11-02-windows-port.md @@ -2744,3 +2744,54 @@ GTK process returning `kAXErrorCannotComplete`, including the application element's own role and attribute names, because GTK pumps GLib and never runs `-[NSApplication run]` while AppKit services those requests from the main run loop. Win32 is implemented first, since it can be exercised on a local VM. + + +## 2026-11-09: the Win32 desktop provider passes the full UI contract + +`nil.ui-display` passes on Windows against the Win32 provider in an interactive +console session: the provider contract, the lifecycle fixture, the Matrix +desktop suite and the interaction suite that posts real keyboard input. The +headless suite is unchanged at 573 registered, with `nil.ui-display` and +`nilagent.window-discovery` skipping for want of a session. + +**Per-platform fixtures, not just a per-platform provider.** `ui_runtime_tests` +inspects loaded GTK modules, dlopen symbol origins and GTK's top-level +registry, so it describes GTK and cannot speak for Win32; Windows builds its +own fixture. The lifecycle observer was the same story in miniature. Its +purpose -- prove a window was really released rather than merely invalidated -- +is platform-neutral, so only the mechanism moved: GTK is asked for its +registry, Windows counts this process's live top-level windows of the +provider's class. The assertions did not change and it still reports exactly +the 235 checks the display contract demands, so that constant stayed put. + +**Three defects the desktop found that a headless suite could not.** First, +`WM_COMMAND` is delivered to a control's immediate parent, which inside a row, +column or grid is that container rather than the window; only windows carried +the context pointer, so every button, checkbox and entry notification was +dropped and no event reached `poll`. Second, Tab order is the dialog manager's +work on Win32, so the pump needs `IsDialogMessageW` and containers need +`WS_EX_CONTROLPARENT` or Tab cannot reach a nested control. Third, and the real +one: Windows delivers keystrokes straight to the focused control, so a top +level only sees keys posted to it deliberately -- which is exactly how the +contract drives a window it has not typed into, because GTK routes such input +through the toplevel. The pump now retargets that input to the focused control +before the dialog manager sees it. Forwarding inside the window procedure was +tried first and could not work, because `IsDialogMessageW` consumed the message +before the procedure ran. + +**Diagnosis needed a probe, not another guess.** Two rebuild-and-run cycles +produced only a thirty-second deadline. A `--input-probe` mode that posts the +contract's own key sequence and reports what arrives printed +`direct_to_edit=1` with nothing arriving through the top level, which named the +fault at once. That coverage now runs inside `--display` as well, so the next +regression reports which event went missing rather than timing out. + +**A Windows-only flake worth knowing.** `nilbuild.incremental-contract` failed +once during a full suite with `cannot read build input` on a compiler the test +had just copied. `file_digest` finds the path is a regular file and then fails +to open it, which is a sharing violation rather than a missing input; Defender +real-time scanning is enabled on the VM and the failure landed immediately +after a full rebuild had produced many unscanned binaries. It does not +reproduce -- three consecutive repeats pass -- and nothing in this work touches +nilbuild. A bounded open retry would make the digest robust against scanners, +but that changes a build-identity function and is a maintainer's decision. From 140a416e5c84203c5c3e29aee6c19f66a50b2da4 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 21:21:09 -0500 Subject: [PATCH 6/7] Add an AppKit desktop provider for macOS The macOS provider becomes AppKit, completing one provider per platform. It implements the same ui.v1 contract as the GTK and Win32 providers and shares the toolkit-independent half through ui_runtime_shared.hpp, so handles, limits, kind codes, event kinds and error text are identical; only the toolkit differs. AppKit has no box or grid container, so containers are plain flipped views and the provider owns the layout pass, as it does on Win32. AppKit replaces the GTK-on-macOS work because a GTK process never runs -[NSApplication run], and AppKit answers accessibility requests from the main run loop; such a process therefore has no accessibility hierarchy at all, which is what the directed-input evidence showed when every query returned kAXErrorCannotComplete. Events come from target/action for buttons and switches, from controlTextDidChange: for fields, and from windowShouldClose:, which enqueues a close request and returns NO so AppKit cannot destroy a live handle. poll drains pending events and gives the run loop one bounded nonblocking turn, never waiting for input. Linking follows the Windows precedent rather than rediscovering it: because the provider calls Cocoa and CoreGraphics directly, both are declared on the runtime targets, in nillinker's POSIX argument list and in the compiler's own Darwin link command, so AOT-compiled programs link against what nil.a now calls. tests/ui_runtime_appkit_tests.mm is the Darwin counterpart of the Win32 fixture and runs the published contract against a real session; without a window server it instead requires that window creation is refused. A workflow_dispatch workflow builds just this provider with LLVM off, so a macOS cycle costs minutes rather than a full source campaign -- which matters because there is no Mac here and every iteration is a CI run. Not yet verified: this is Objective-C++ that cannot be compiled on this host, so the first CI run is its first compile. Linux is unchanged at 572 registered, 0 failed and 3 environment skips. Co-Authored-By: Claude Opus 5 --- .github/workflows/macos-appkit-provider.yml | 68 ++ CMakeLists.txt | 11 + docs/platform-support.md | 13 +- nilcompiler/CMakeLists.txt | 11 + nilcompiler/src/main.cpp | 4 + nilcompiler/src/ui_runtime_appkit.mm | 963 ++++++++++++++++++++ nillinker/main.cpp | 8 + tests/ui_runtime_appkit_tests.mm | 186 ++++ 8 files changed, 1258 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/macos-appkit-provider.yml create mode 100644 nilcompiler/src/ui_runtime_appkit.mm create mode 100644 tests/ui_runtime_appkit_tests.mm diff --git a/.github/workflows/macos-appkit-provider.yml b/.github/workflows/macos-appkit-provider.yml new file mode 100644 index 00000000..a66168f4 --- /dev/null +++ b/.github/workflows/macos-appkit-provider.yml @@ -0,0 +1,68 @@ +name: macOS AppKit provider checks + +"on": + workflow_dispatch: + inputs: + architecture: + description: Host architecture to check + type: choice + options: [both, x86_64, arm64] + default: both + +permissions: + contents: read + +concurrency: + group: macos-appkit-provider-${{ github.ref }}-${{ inputs.architecture }} + cancel-in-progress: false + +# Build and exercise the AppKit desktop provider only. LLVM is off and no SDK +# is configured, qualified or published, so a cycle here costs minutes rather +# than a full source campaign. +jobs: + provider: + name: macOS ${{ matrix.host.arch }} AppKit provider + runs-on: ${{ matrix.host.runner }} + timeout-minutes: 30 + strategy: + fail-fast: false + max-parallel: 2 + matrix: + host: ${{ fromJSON(inputs.architecture == 'arm64' && '[{"runner":"macos-15","arch":"arm64"}]' || inputs.architecture == 'x86_64' && '[{"runner":"macos-15-intel","arch":"x86_64"}]' || '[{"runner":"macos-15-intel","arch":"x86_64"},{"runner":"macos-15","arch":"arm64"}]') }} + defaults: + run: + shell: bash + steps: + # Official v5 tag commit, matching the other workflows in this repository. + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - name: Report the desktop session + timeout-minutes: 2 + run: | + echo "runner arch: $(uname -m)" + # A provider that cannot reach a window server can still build, so + # record the session before anything is interpreted as a provider + # fault. + /usr/bin/python3 -c " + import ctypes, ctypes.util + core = ctypes.CDLL(ctypes.util.find_library('CoreGraphics')) + core.CGMainDisplayID.restype = ctypes.c_uint32 + print('CGMainDisplayID:', core.CGMainDisplayID()) + " + - name: Configure without LLVM + timeout-minutes: 8 + run: | + cmake -S . -B build/ci \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTING=ON \ + -DNIL_ENABLE_LLVM=OFF + - name: Build the AppKit provider and its fixture + timeout-minutes: 20 + run: cmake --build build/ci --target nil_ui_runtime_appkit_tests --parallel 3 + - name: Availability without opening a display + timeout-minutes: 2 + run: ./build/ci/bin/nil_ui_runtime_appkit_tests --provider-present + - name: Provider contract against a real session + timeout-minutes: 5 + run: ./build/ci/bin/nil_ui_runtime_appkit_tests --display diff --git a/CMakeLists.txt b/CMakeLists.txt index ae89cd88..f91660b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,6 +34,11 @@ if(MSVC) "/MANIFESTINPUT:${CMAKE_CURRENT_SOURCE_DIR}/cmake/utf8.manifest") endif() +if(APPLE) + # The macOS desktop provider and its fixture are Objective-C++. + enable_language(OBJCXX) +endif() + add_subdirectory(nilcompiler) add_subdirectory(nilinterpreter) add_subdirectory(nillsp) @@ -256,6 +261,12 @@ if(BUILD_TESTING) target_include_directories(nil_ui_runtime_win32_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") target_compile_features(nil_ui_runtime_win32_tests PRIVATE cxx_std_17) set(NIL_UI_PROVIDER_TEST nil_ui_runtime_win32_tests) + elseif(APPLE) + add_executable(nil_ui_runtime_appkit_tests tests/ui_runtime_appkit_tests.mm) + target_link_libraries(nil_ui_runtime_appkit_tests PRIVATE nilruntime Threads::Threads) + target_include_directories(nil_ui_runtime_appkit_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_compile_features(nil_ui_runtime_appkit_tests PRIVATE cxx_std_17) + set(NIL_UI_PROVIDER_TEST nil_ui_runtime_appkit_tests) else() add_executable(nil_ui_runtime_tests tests/ui_runtime_tests.cpp) target_link_libraries(nil_ui_runtime_tests PRIVATE nilruntime Threads::Threads) diff --git a/docs/platform-support.md b/docs/platform-support.md index 8c265190..b577e799 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -103,12 +103,13 @@ or standard-library test fails. Four shared contracts fail only when the suite runs as `SYSTEM`: that account reports `TEMP` cased `C:\WINDOWS\TEMP`, the toolchain reports paths in their on-disk casing, and the affected assertions compare the two strings exactly; the same four pass unchanged under an ordinary -user account. The Windows-only SDK preflight cannot run while the machine -execution policy is `Restricted`, the Windows client default, because it invokes -`powershell.exe -File` deliberately without a bypass and every subtest therefore -observes a policy refusal instead of a preflight diagnostic. Two display tests -skip for want of an interactive desktop session and both PostgreSQL tests skip -without a server. This supplements the recorded Windows baseline; it neither +user account. The Windows-only SDK preflight needs a machine execution +policy that permits local scripts, because it invokes `powershell.exe -File` +deliberately without a bypass; under the Windows client default of `Restricted` +every subtest observes a policy refusal instead of a preflight diagnostic, and +it passes once the policy is `RemoteSigned`. Two display tests skip for want of +an interactive desktop session and both PostgreSQL tests skip without a +server. This supplements the recorded Windows baseline; it neither replaces the accepted SDK nor qualifies a new one. ## Native executable context diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index a597265e..73733a5e 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -51,6 +51,12 @@ set(NILCOMPILER_CORE_SOURCES # exactly one of them is ever compiled into the runtime. if(WIN32) set(NIL_UI_PROVIDER_SOURCE src/ui_runtime_win32.cpp) +elseif(APPLE) + enable_language(OBJCXX) + set(NIL_UI_PROVIDER_SOURCE src/ui_runtime_appkit.mm) + # ARC owns the toolkit objects the provider stores in its node table. + set_source_files_properties(src/ui_runtime_appkit.mm PROPERTIES + COMPILE_OPTIONS "-fobjc-arc") else() set(NIL_UI_PROVIDER_SOURCE src/ui_runtime.cpp) endif() @@ -87,6 +93,11 @@ foreach(nil_runtime_target IN ITEMS nilruntime nilruntime_shared) # the dynamically loaded GTK provider, so those travel the same way. target_link_libraries(${nil_runtime_target} PUBLIC ws2_32 user32 gdi32) endif() + if(APPLE) + # The AppKit desktop provider calls Cocoa and CoreGraphics directly, + # so both travel to every consumer of the runtime. + target_link_libraries(${nil_runtime_target} PUBLIC "-framework Cocoa" "-framework CoreGraphics") + endif() set_target_properties(${nil_runtime_target} PROPERTIES CXX_EXTENSIONS OFF OUTPUT_NAME nil diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 19b93afd..9b0f1b65 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -2361,6 +2361,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) quote_posix_shell_argument(native_runtime->string()); #if defined(__linux__) cmd += " -ldl"; +#endif +#if defined(__APPLE__) + // As above: nil.a carries the AppKit provider on Darwin. + cmd += " -framework Cocoa -framework CoreGraphics"; #endif for (const auto &lib : link_libraries) { cmd += " " + quote_posix_shell_argument(lib); diff --git a/nilcompiler/src/ui_runtime_appkit.mm b/nilcompiler/src/ui_runtime_appkit.mm new file mode 100644 index 00000000..022bfdf0 --- /dev/null +++ b/nilcompiler/src/ui_runtime_appkit.mm @@ -0,0 +1,963 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +// macOS provider for the ui.v1 contract, built instead of the GTK provider on +// Darwin: one toolkit per platform. The observable contract is the one stated +// in ui_runtime.hpp and shared with the other providers through +// ui_runtime_shared.hpp -- identical handles, limits, error text, kind codes +// and event kinds. Only the toolkit beneath it differs. +// +// AppKit replaces the earlier GTK-on-macOS provider because a GTK process +// never runs -[NSApplication run]; AppKit answers accessibility requests from +// the main run loop, so such a process has no accessibility hierarchy at all +// and is invisible to assistive technology and to directed input. +// +// AppKit has no box or grid container either, so containers are plain views +// and this file owns the layout pass, exactly as the Win32 provider does. +#include "ui_runtime.hpp" +#include "ui_runtime_shared.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#import +#import +#import + +namespace ny::ui { +namespace { + +// Control metrics. The provider owns layout, so natural sizes come from each +// control's own fitting size with the padding AppKit expects around it. +constexpr CGFloat minimum_entry_width = 120; +constexpr CGFloat control_padding = 4; + +NSString *to_ns(const std::string &text) { + NSString *value = [[NSString alloc] initWithBytes:text.data() + length:static_cast(text.size()) + encoding:NSUTF8StringEncoding]; + return value ?: @""; +} + +bool from_ns(NSString *value, std::string &out) { + if (!value) { out.clear(); return true; } + const char *bytes = [value UTF8String]; + if (!bytes) return false; + out.assign(bytes); + return true; +} + +// A window server session is required before any window is created, so the +// failure names the cause instead of surfacing a late AppKit error. +bool window_server_available() { + return CGMainDisplayID() != 0; +} + +struct Platform { + std::mutex thread_mutex; + std::thread::id ui_thread; + bool initialized = false; +}; +Platform &platform() { static Platform *value = new Platform; return *value; } + +} // namespace +} // namespace ny::ui + +// Flipped so layout runs top-down, matching the other providers and the +// contract's description of rows and columns. +@interface NyUiContainer : NSView +@end +@implementation NyUiContainer +- (BOOL)isFlipped { return YES; } +@end + +@interface NyUiTarget : NSObject +@property(nonatomic, assign) void *owner; +- (void)buttonAction:(id)sender; +- (void)checkAction:(id)sender; +@end + +namespace ny::ui { + +struct Context::Impl : std::enable_shared_from_this { + struct Node { + Kind kind = Kind::window; + NSWindow *window_object = nil; // Windows only. + NSView *view = nil; // Every node, including a window's root. + std::int64_t parent = 0, window = 0; + std::string text; + std::map properties; + Placement placement; + NSRect allocation = NSZeroRect; + unsigned suppress = 0; + bool event_failure = false; + }; + std::thread::id owner = std::this_thread::get_id(); + std::map nodes; + std::map handles; // view or window -> handle + std::map focus_targets; + std::deque events; + std::map snapshots; + std::size_t event_bytes = 0, snapshot_bytes = 0, text_bytes = 0; + std::atomic active{true}; + bool tearing_down = false; + NyUiTarget *target = nil; + + static std::mutex &deferred_mutex() { static auto *m = new std::mutex; return *m; } + static std::vector> &deferred() { + static auto *v = new std::vector>; return *v; + } + static void drain() { + std::vector> pending; + { std::lock_guard lock(deferred_mutex()); pending.swap(deferred()); } + for (auto &item : pending) item->dispose(); + } + Result check() { + if (owner != std::this_thread::get_id()) return failure("context must be used on its creation thread"); + if (!active.load()) return failure("context has been closed"); + // AppKit services its windows and accessibility from the main run loop. + if (!pthread_main_np()) return failure("AppKit must be used on the process UI thread (macOS main thread)"); + auto &p = platform(); + bool initialized; + { + std::lock_guard lock(p.thread_mutex); + if (p.initialized && p.ui_thread != std::this_thread::get_id()) + return failure("AppKit must be used on the process UI thread"); + initialized = p.initialized; + } + if (initialized) drain(); + return success(); + } + Result initialize() { + if (auto result = check(); !result) return result; + auto &p = platform(); + std::lock_guard lock(p.thread_mutex); + if (p.initialized) { + if (p.ui_thread != std::this_thread::get_id()) + return failure("AppKit must be used on the process UI thread"); + return success(); + } + if (!window_server_available()) + return failure("AppKit could not open a display; a working macOS window server session is required"); + @autoreleasepool { + NSApplication *application = [NSApplication sharedApplication]; + if (!application) return failure("AppKit could not create the shared application"); + // Accessory keeps the provider out of the Dock and the menu bar while + // still giving real, answerable windows. + [application setActivationPolicy:NSApplicationActivationPolicyAccessory]; + [application finishLaunching]; + } + p.ui_thread = std::this_thread::get_id(); + p.initialized = true; + return success(); + } + Node *find(std::int64_t handle) { + auto found = nodes.find(handle); + return found == nodes.end() ? nullptr : &found->second; + } + static Result bad_handle() { return failure("unknown, closed, or foreign widget handle"); } + + std::int64_t handle_of(void *object) const { + auto found = handles.find(object); + return found == handles.end() ? 0 : found->second; + } + + bool effective_sensitive(const Node &node) { + for (const Node *current = &node;;) { + const auto found = current->properties.find("sensitive"); + if (found != current->properties.end() && found->second == 0) return false; + if (!current->parent) break; + auto *next = find(current->parent); + if (!next) break; + current = next; + } + return true; + } + bool effective_visible(const Node &node) { + for (const Node *current = &node;;) { + const auto found = current->properties.find("visible"); + const bool shown = current->kind == Kind::window + ? (found != current->properties.end() && found->second != 0) + : (found == current->properties.end() || found->second != 0); + if (!shown) return false; + if (!current->parent) break; + auto *next = find(current->parent); + if (!next) break; + current = next; + } + return true; + } + + void enqueue(std::int64_t handle, std::int64_t kind) noexcept { + const auto mark_failure = [&] { + if (const auto *node = find(handle)) + if (auto *window = find(node->window)) window->event_failure = true; + }; + try { + auto *node = find(handle); + if (!node || node->suppress || tearing_down) return; + Event event{kind, handle, node->window, 0, {}}; + if (kind == 2) { + auto *field = static_cast(node->view); + if (!from_ns(field.stringValue, event.text)) { mark_failure(); return; } + if (!valid_text(event.text)) { mark_failure(); return; } + } else if (kind == 3) { + auto *button = static_cast(node->view); + event.checked = button.state == NSControlStateValueOn ? 1 : 0; + } + if (events.size() >= max_events || event.text.size() > max_event_text_bytes - event_bytes) { + mark_failure(); return; + } + events.push_back(std::move(event)); + event_bytes += events.back().text.size(); + } catch (...) { mark_failure(); } + } + + // ---- layout ------------------------------------------------------------- + std::vector children_of(std::int64_t handle) { + std::vector result; + for (const auto &[id, node] : nodes) + if (node.parent == handle) result.push_back(id); + return result; + } + std::int64_t property(const Node &node, const char *name, std::int64_t fallback = 0) { + auto found = node.properties.find(name); + if (found != node.properties.end()) return found->second; + auto all = node.properties.find("margin"); + if (all != node.properties.end() && std::string(name).rfind("margin_", 0) == 0) return all->second; + return fallback; + } + NSSize natural(std::int64_t handle) { + auto *node = find(handle); + if (!node) return NSMakeSize(0, 0); + NSSize size = NSMakeSize(0, 0); + switch (node->kind) { + case Kind::label: + case Kind::button: + case Kind::checkbox: + case Kind::entry: { + auto *control = static_cast(node->view); + size = [control sizeThatFits:NSMakeSize(0, 0)]; + if (node->kind == Kind::entry) size.width = std::max(size.width, minimum_entry_width); + size.width += control_padding; + size.height += control_padding; + break; + } + default: { + const auto kids = children_of(handle); + const auto spacing = static_cast(property(*node, "spacing")); + if (node->kind == Kind::grid) { + std::map widths, heights; + for (auto id : kids) { + auto *child = find(id); + if (!child) continue; + const auto wanted = natural(id); + auto &width = widths[child->placement.column]; + auto &height = heights[child->placement.row]; + width = std::max(width, wanted.width / std::max(1, child->placement.columns)); + height = std::max(height, wanted.height / std::max(1, child->placement.rows)); + } + for (const auto &entry : widths) size.width += entry.second; + for (const auto &entry : heights) size.height += entry.second; + if (!widths.empty()) size.width += spacing * (widths.size() - 1); + if (!heights.empty()) size.height += spacing * (heights.size() - 1); + } else { + const bool vertical = node->kind != Kind::row; + for (auto id : kids) { + const auto wanted = natural(id); + if (vertical) { size.width = std::max(size.width, wanted.width); size.height += wanted.height; } + else { size.height = std::max(size.height, wanted.height); size.width += wanted.width; } + } + if (!kids.empty()) { + const auto gaps = spacing * (kids.size() - 1); + if (vertical) size.height += gaps; else size.width += gaps; + } + } + break; + } + } + if (node->kind != Kind::window) { + size.width += property(*node, "margin_start") + property(*node, "margin_end"); + size.height += property(*node, "margin_top") + property(*node, "margin_bottom"); + } + return size; + } + void place(std::int64_t handle, NSRect area) { + auto *node = find(handle); + if (!node) return; + if (node->kind != Kind::window) { + area.origin.x += property(*node, "margin_start"); + area.origin.y += property(*node, "margin_top"); + area.size.width -= property(*node, "margin_start") + property(*node, "margin_end"); + area.size.height -= property(*node, "margin_top") + property(*node, "margin_bottom"); + if (area.size.width < 0) area.size.width = 0; + if (area.size.height < 0) area.size.height = 0; + node->allocation = area; + [node->view setFrame:area]; + } else { + node->allocation = area; + } + if (!container(node->kind)) return; + + NSRect inner = NSMakeRect(0, 0, area.size.width, area.size.height); + if (node->kind == Kind::window) { + inner.origin.x += property(*node, "margin_start"); + inner.origin.y += property(*node, "margin_top"); + inner.size.width -= property(*node, "margin_start") + property(*node, "margin_end"); + inner.size.height -= property(*node, "margin_top") + property(*node, "margin_bottom"); + [node->view setFrame:NSMakeRect(0, 0, area.size.width, area.size.height)]; + } + if (inner.size.width < 0) inner.size.width = 0; + if (inner.size.height < 0) inner.size.height = 0; + + const auto kids = children_of(handle); + if (kids.empty()) return; + const auto spacing = static_cast(property(*node, "spacing")); + + if (node->kind == Kind::grid) { + std::map widths, heights; + for (auto id : kids) { + auto *child = find(id); + if (!child) continue; + const auto wanted = natural(id); + auto &width = widths[child->placement.column]; + auto &height = heights[child->placement.row]; + width = std::max(width, wanted.width / std::max(1, child->placement.columns)); + height = std::max(height, wanted.height / std::max(1, child->placement.rows)); + } + std::map column_offset, row_offset; + CGFloat x = inner.origin.x; + for (auto &entry : widths) { column_offset[entry.first] = x; x += entry.second + spacing; } + CGFloat y = inner.origin.y; + for (auto &entry : heights) { row_offset[entry.first] = y; y += entry.second + spacing; } + for (auto id : kids) { + auto *child = find(id); + if (!child) continue; + CGFloat width = 0, height = 0; + for (std::int64_t span = 0; span < child->placement.columns; ++span) { + auto found = widths.find(child->placement.column + span); + if (found != widths.end()) width += found->second + (span ? spacing : 0); + } + for (std::int64_t span = 0; span < child->placement.rows; ++span) { + auto found = heights.find(child->placement.row + span); + if (found != heights.end()) height += found->second + (span ? spacing : 0); + } + const CGFloat left = column_offset.count(child->placement.column) + ? column_offset[child->placement.column] : inner.origin.x; + const CGFloat top = row_offset.count(child->placement.row) + ? row_offset[child->placement.row] : inner.origin.y; + place(id, NSMakeRect(left, top, width, height)); + } + return; + } + + const bool vertical = node->kind != Kind::row; + CGFloat used = spacing * (kids.size() - 1); + std::size_t expanding = 0; + std::vector wanted; + wanted.reserve(kids.size()); + for (auto id : kids) { + wanted.push_back(natural(id)); + used += vertical ? wanted.back().height : wanted.back().width; + auto *child = find(id); + if (child && property(*child, vertical ? "vexpand" : "hexpand")) ++expanding; + } + const CGFloat span = vertical ? inner.size.height : inner.size.width; + const CGFloat extra = span > used ? span - used : 0; + const CGFloat share = expanding ? extra / expanding : 0; + + CGFloat offset = vertical ? inner.origin.y : inner.origin.x; + for (std::size_t index = 0; index < kids.size(); ++index) { + auto *child = find(kids[index]); + if (!child) continue; + const bool expand = property(*child, vertical ? "vexpand" : "hexpand") != 0; + const CGFloat length = (vertical ? wanted[index].height : wanted[index].width) + (expand ? share : 0); + NSRect target; + if (vertical) { + const CGFloat width = property(*child, "hexpand") + ? inner.size.width : std::min(wanted[index].width, inner.size.width); + target = NSMakeRect(inner.origin.x, offset, width, length); + } else { + const CGFloat height = property(*child, "vexpand") + ? inner.size.height : std::min(wanted[index].height, inner.size.height); + target = NSMakeRect(offset, inner.origin.y, length, height); + } + place(kids[index], target); + offset += length + spacing; + } + } + void relayout(std::int64_t window) { + auto *node = find(window); + if (!node || node->kind != Kind::window) return; + NSRect content = [node->window_object contentRectForFrameRect:node->window_object.frame]; + if (content.size.width <= 0 || content.size.height <= 0) + content = NSMakeRect(0, 0, static_cast(property(*node, "width", 1)), + static_cast(property(*node, "height", 1))); + place(window, NSMakeRect(0, 0, content.size.width, content.size.height)); + } + + void dispose() noexcept { + active.store(false); + tearing_down = true; + @autoreleasepool { + for (auto &entry : nodes) + if (entry.second.kind == Kind::window && entry.second.window_object) { + entry.second.window_object.delegate = nil; + [entry.second.window_object close]; + entry.second.window_object = nil; + } + for (auto &entry : nodes) entry.second.view = nil; + } + if (target) { target.owner = nullptr; target = nil; } + nodes.clear(); handles.clear(); focus_targets.clear(); + events.clear(); snapshots.clear(); + event_bytes = snapshot_bytes = text_bytes = 0; + tearing_down = false; + } +}; + +} // namespace ny::ui + +@implementation NyUiTarget +- (ny::ui::Context::Impl *)impl { + return static_cast(self.owner); +} +- (void)deliver:(id)sender kind:(std::int64_t)kind { + auto *impl = [self impl]; + if (!impl || !impl->active.load() || impl->tearing_down) return; + const auto handle = impl->handle_of((__bridge void *)sender); + if (handle) impl->enqueue(handle, kind); +} +- (void)buttonAction:(id)sender { [self deliver:sender kind:1]; } +- (void)checkAction:(id)sender { [self deliver:sender kind:3]; } +- (void)controlTextDidChange:(NSNotification *)notification { + [self deliver:notification.object kind:2]; +} +- (BOOL)windowShouldClose:(NSWindow *)sender { + auto *impl = [self impl]; + if (impl && impl->active.load() && !impl->tearing_down) { + const auto handle = impl->handle_of((__bridge void *)sender); + if (handle) impl->enqueue(handle, 4); + } + // Matrix decides when to close; AppKit must not destroy a live handle. + return NO; +} +@end + +namespace ny::ui { + +// AppKit is part of the operating system, so unlike the optional GTK provider +// there is nothing to locate or verify. Reporting availability must still not +// open a display. +bool available() noexcept { return true; } + +Context::Context() : impl_(std::make_shared()) {} +Context::~Context() { clear(); } +void Context::clear() noexcept { + if (!impl_) return; + auto old = std::move(impl_); + old->active.store(false); + if (old->owner == std::this_thread::get_id() && pthread_main_np()) old->dispose(); + else if (!old->nodes.empty()) { + try { std::lock_guard lock(Impl::deferred_mutex()); Impl::deferred().push_back(std::move(old)); } + catch (...) { /* Callbacks hold no owning reference; a failed defer may leak windows, never free twice. */ } + } + try { impl_ = std::make_shared(); } catch (...) {} +} + +Result Context::window(const std::string &title, std::int64_t width, std::int64_t height) { + if (!impl_) return failure("context allocation failed"); + if (!valid_text(title)) return failure(text_error); + if (width < 1 || width > 16384 || height < 1 || height > 16384) + return failure("window width and height must be between 1 and 16384"); + if (auto result = impl_->initialize(); !result) return result; + if (title.size() > max_event_text_bytes - impl_->text_bytes) return failure("stored text limit exceeded (16 MiB per context)"); + if (impl_->nodes.size() >= max_widgets || static_cast(std::count_if(impl_->nodes.begin(), impl_->nodes.end(), + [](const auto &item) { return item.second.kind == Kind::window; })) >= max_windows) + return failure("window or widget limit exceeded (64 windows, 4096 widgets per context)"); + const auto handle = fresh_handle(); + if (!handle) return failure("handle space exhausted"); + + @autoreleasepool { + Impl::Node node; node.kind = Kind::window; node.window = handle; node.text = title; + node.properties = {{"width", width}, {"height", height}, {"spacing", 0}, {"visible", 0}}; + NSWindow *window = [[NSWindow alloc] + initWithContentRect:NSMakeRect(0, 0, static_cast(width), static_cast(height)) + styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable + backing:NSBackingStoreBuffered + defer:NO]; + if (!window) return failure("AppKit could not create a window"); + // Creation remains hidden: ordering front happens only for visible=1. + window.releasedWhenClosed = NO; + window.title = to_ns(title); + NyUiContainer *root = [[NyUiContainer alloc] + initWithFrame:NSMakeRect(0, 0, static_cast(width), static_cast(height))]; + if (!root) return failure("AppKit could not create the root layout"); + window.contentView = root; + if (!impl_->target) { + impl_->target = [[NyUiTarget alloc] init]; + impl_->target.owner = impl_.get(); + } + window.delegate = impl_->target; + node.window_object = window; + node.view = root; + try { + impl_->nodes.emplace(handle, std::move(node)); + impl_->handles.emplace((__bridge void *)window, handle); + impl_->handles.emplace((__bridge void *)root, handle); + impl_->text_bytes += title.size(); + impl_->relayout(handle); + } catch (...) { + window.delegate = nil; + [window close]; + auto found = impl_->nodes.find(handle); + if (found != impl_->nodes.end()) impl_->nodes.erase(found); + return failure("window allocation failed"); + } + } + return success(handle); +} + +Result Context::widget(const std::string &kind, std::int64_t parent, const std::string &label) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + if (!valid_text(label)) return failure(text_error); + if (label.size() > max_event_text_bytes - impl_->text_bytes) return failure("stored text limit exceeded (16 MiB per context)"); + if (kind == "entry" && !entry_text_fits(label)) return failure("entry text exceeds 16384 Unicode characters"); + auto *owner = impl_->find(parent); + if (!owner) return Impl::bad_handle(); + if (!container(owner->kind)) return failure("parent must be a window, row, column, or grid"); + if (impl_->nodes.size() >= max_widgets) return failure("widget limit exceeded (4096 per context)"); + + const auto handle = fresh_handle(); + if (!handle) return failure("handle space exhausted"); + + @autoreleasepool { + Impl::Node node; node.parent = parent; node.window = owner->window; node.text = label; + NSString *text = to_ns(label); + if (kind == "column" || kind == "row") { + node.kind = kind == "column" ? Kind::column : Kind::row; + node.view = [[NyUiContainer alloc] initWithFrame:NSZeroRect]; + } else if (kind == "grid") { + node.kind = Kind::grid; + node.view = [[NyUiContainer alloc] initWithFrame:NSZeroRect]; + } else if (kind == "label") { + node.kind = Kind::label; + NSTextField *field = [[NSTextField alloc] initWithFrame:NSZeroRect]; + field.stringValue = text; + field.editable = NO; field.selectable = NO; field.bezeled = NO; field.drawsBackground = NO; + node.view = field; + } else if (kind == "button") { + node.kind = Kind::button; + NSButton *button = [[NSButton alloc] initWithFrame:NSZeroRect]; + button.title = text; + button.bezelStyle = NSBezelStyleRounded; + [button setButtonType:NSButtonTypeMomentaryPushIn]; + button.target = impl_->target; + button.action = @selector(buttonAction:); + node.view = button; + } else if (kind == "entry") { + node.kind = Kind::entry; + NSTextField *field = [[NSTextField alloc] initWithFrame:NSZeroRect]; + field.stringValue = text; + field.editable = YES; field.selectable = YES; field.bezeled = YES; + field.delegate = impl_->target; + node.view = field; + } else if (kind == "checkbox") { + node.kind = Kind::checkbox; + NSButton *button = [[NSButton alloc] initWithFrame:NSZeroRect]; + button.title = text; + [button setButtonType:NSButtonTypeSwitch]; + button.target = impl_->target; + button.action = @selector(checkAction:); + node.view = button; + } else return failure("widget kind must be column, row, grid, label, button, entry, or checkbox"); + if (!node.view) return failure("AppKit could not create the widget"); + + if (owner->kind == Kind::grid) { + std::vector> occupied; + for (const auto &[id, sibling] : impl_->nodes) + if (sibling.parent == parent && sibling.placement.column == 0) + occupied.emplace_back(sibling.placement.row, sibling.placement.row + sibling.placement.rows); + std::sort(occupied.begin(), occupied.end()); + for (const auto &[start, end] : occupied) { + if (node.placement.row < start) break; + node.placement.row = std::max(node.placement.row, end); + } + if (node.placement.row > 65535) return failure("grid row limit exceeded"); + } + NSView *view = node.view; + try { + [owner->view addSubview:view]; + impl_->nodes.emplace(handle, std::move(node)); + impl_->handles.emplace((__bridge void *)view, handle); + impl_->text_bytes += label.size(); + impl_->relayout(impl_->nodes.at(handle).window); + } catch (...) { + [view removeFromSuperview]; + auto found = impl_->nodes.find(handle); + if (found != impl_->nodes.end()) { + impl_->handles.erase((__bridge void *)view); + impl_->nodes.erase(found); + } + return failure("widget allocation failed"); + } + } + return success(handle); +} + +Result Context::grid_attach(std::int64_t grid, std::int64_t child, std::int64_t column, + std::int64_t row, std::int64_t column_span, std::int64_t row_span) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *parent = impl_->find(grid); auto *node = impl_->find(child); + if (!parent || !node) return Impl::bad_handle(); + if (parent->kind != Kind::grid || node->parent != grid) + return failure("grid_attach requires a child of the specified grid"); + if (column < 0 || row < 0 || column_span < 1 || row_span < 1 || + column > 65535 || row > 65535 || column_span > 65536 - column || row_span > 65536 - row) + return failure("grid coordinates and spans must fit within 0..65535"); + Placement placement{column, row, column_span, row_span}; + for (const auto &[id, other] : impl_->nodes) + if (id != child && other.parent == grid && overlaps(placement, other.placement)) + return failure("grid placement overlaps an existing child"); + node->placement = placement; + impl_->relayout(node->window); + return success(); +} + +Result Context::set_text(std::int64_t handle, const std::string &text) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + if (!valid_text(text)) return failure(text_error); + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (container(node->kind) && node->kind != Kind::window) return failure("container does not have a text property"); + if (node->kind == Kind::entry && !entry_text_fits(text)) return failure("entry text exceeds 16384 Unicode characters"); + if (text.size() > max_event_text_bytes - (impl_->text_bytes - node->text.size())) return failure("stored text limit exceeded (16 MiB per context)"); + std::string copy = text; + @autoreleasepool { + NSString *value = to_ns(copy); + // Programmatic writes must not raise a change event. + ++node->suppress; + switch (node->kind) { + case Kind::window: node->window_object.title = value; break; + case Kind::label: + case Kind::entry: static_cast(node->view).stringValue = value; break; + case Kind::button: + case Kind::checkbox: static_cast(node->view).title = value; break; + default: break; + } + --node->suppress; + } + impl_->text_bytes = impl_->text_bytes - node->text.size() + copy.size(); + node->text = std::move(copy); + if (node->kind != Kind::window) impl_->relayout(node->window); + return success(); +} + +Result Context::read_text(std::int64_t handle) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (container(node->kind) && node->kind != Kind::window) return failure("container does not have a text property"); + Result result; + @autoreleasepool { + if (node->kind == Kind::entry) { + if (!from_ns(static_cast(node->view).stringValue, result.text)) + return failure("AppKit returned invalid text"); + } else result.text = node->text; + } + if (!valid_text(result.text)) return failure(text_error); + return result; +} + +Result Context::set_number(std::int64_t handle, const std::string &property, std::int64_t value) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (property == "focus") { + if (value != 1) return failure("focus accepts only 1 to request keyboard focus"); + if (node->kind != Kind::button && node->kind != Kind::entry && node->kind != Kind::checkbox) + return failure("widget cannot receive keyboard focus"); + if (!impl_->effective_sensitive(*node)) return failure("widget cannot receive keyboard focus"); + auto *window = impl_->find(node->window); + if (!window || !window->window_object) return failure("widget cannot receive keyboard focus"); + impl_->focus_targets[node->window] = handle; + [window->window_object makeFirstResponder:node->view]; + return success(); + } + const bool flag = property == "visible" || property == "sensitive" || property == "hexpand" || property == "vexpand" || property == "checked"; + const bool margin = property == "margin" || property == "margin_start" || property == "margin_end" || property == "margin_top" || property == "margin_bottom"; + const bool size = property == "width" || property == "height"; + if (!flag && !margin && !size && property != "spacing") return failure("unknown or read-only numeric property"); + if (flag && value != 0 && value != 1) return failure("flag properties require exactly 0 or 1"); + if ((margin || property == "spacing") && (value < 0 || value > 4096)) return failure("margins and spacing must be between 0 and 4096"); + if (size && (node->kind != Kind::window || value < 1 || value > 16384)) return failure("width and height are window properties between 1 and 16384"); + if (property == "checked" && node->kind != Kind::checkbox) return failure("checked requires a checkbox"); + if (property == "spacing" && !container(node->kind)) return failure("spacing requires a window, row, column, or grid"); + node->properties[property] = value; + if (property == "margin") + for (const auto *side : {"margin_start", "margin_end", "margin_top", "margin_bottom"}) node->properties[side] = value; + + @autoreleasepool { + if (property == "visible") { + if (node->kind == Kind::window) { + if (value) [node->window_object makeKeyAndOrderFront:nil]; + else [node->window_object orderOut:nil]; + impl_->relayout(handle); + } else { + node->view.hidden = value ? NO : YES; + impl_->relayout(node->window); + } + } else if (property == "sensitive") { + if (!container(node->kind)) static_cast(node->view).enabled = value ? YES : NO; + } else if (property == "checked") { + ++node->suppress; + static_cast(node->view).state = value ? NSControlStateValueOn : NSControlStateValueOff; + --node->suppress; + } else if (size) { + NSRect frame = node->window_object.frame; + NSRect content = NSMakeRect(frame.origin.x, frame.origin.y, + static_cast(node->properties.at("width")), + static_cast(node->properties.at("height"))); + [node->window_object setFrame:[node->window_object frameRectForContentRect:content] display:YES]; + impl_->relayout(handle); + } else impl_->relayout(node->window); + } + return success(); +} + +Result Context::read_number(std::int64_t handle, const std::string &property) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (property == "kind") return success(static_cast(node->kind)); + if (property == "parent") return success(node->parent); + if (property == "checked") { + if (node->kind != Kind::checkbox) return failure("checked requires a checkbox"); + return success(static_cast(node->view).state == NSControlStateValueOn ? 1 : 0); + } + if (property == "visible") { + if (node->kind == Kind::window) return success(node->window_object.visible ? 1 : 0); + return success(node->view.hidden ? 0 : 1); + } + if (property == "effective_visible") return success(impl_->effective_visible(*node) ? 1 : 0); + if (property == "sensitive") { + if (container(node->kind)) { + auto found = node->properties.find("sensitive"); + return success(found == node->properties.end() || found->second ? 1 : 0); + } + return success(static_cast(node->view).enabled ? 1 : 0); + } + if (property == "effective_sensitive") return success(impl_->effective_sensitive(*node) ? 1 : 0); + if (property == "focus") { + auto found = impl_->focus_targets.find(node->window); + if (found == impl_->focus_targets.end()) return success(0); + if (found->second == handle) return success(1); + auto *target = impl_->find(found->second); + // A compound widget's internal child counts as the widget's own focus. + return success(target && [target->view isDescendantOf:node->view] ? 1 : 0); + } + if (property == "width" || property == "height") { + if (node->kind == Kind::window) { + if (!node->window_object.visible) return success(node->properties.at(property)); + const NSRect content = [node->window_object contentRectForFrameRect:node->window_object.frame]; + return success(static_cast(property == "width" ? content.size.width : content.size.height)); + } + return success(static_cast(property == "width" ? node->allocation.size.width + : node->allocation.size.height)); + } + if (property == "spacing" && !container(node->kind)) return failure("spacing requires a window, row, column, or grid"); + if (property != "spacing" && property != "hexpand" && property != "vexpand" && property != "margin" && + property != "margin_start" && property != "margin_end" && property != "margin_top" && property != "margin_bottom") + return failure("unknown numeric property"); + auto found = node->properties.find(property); + if (property == "margin") { + const auto side_value = [&](const char *side) { + auto item = node->properties.find(side); return item == node->properties.end() ? std::int64_t(0) : item->second; + }; + const auto start = side_value("margin_start"); + if (start != side_value("margin_end") || start != side_value("margin_top") || start != side_value("margin_bottom")) + return failure("margins differ; read each margin side separately"); + return success(start); + } + if (found != node->properties.end()) return success(found->second); + if (property.rfind("margin_", 0) == 0) { + auto all = node->properties.find("margin"); if (all != node->properties.end()) return success(all->second); + } + return success(0); +} + +Result Context::activate(std::int64_t handle) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (node->kind != Kind::button && node->kind != Kind::checkbox) return failure("activate requires a button or checkbox"); + if (!impl_->effective_sensitive(*node)) + return failure("cannot activate an insensitive widget or a child of an insensitive container"); + @autoreleasepool { + // performClick: is the real activation path: it toggles a switch button + // and sends the action exactly as a user click does. + [static_cast(node->view) performClick:nil]; + } + return success(); +} + +Result Context::poll(std::int64_t window) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(window); if (!node) return Impl::bad_handle(); + if (node->kind != Kind::window) return failure("poll requires a window"); + @autoreleasepool { + // Nonblocking: drain whatever AppKit already has, never wait for input. + for (unsigned count = 0; count < 128; ++count) { + NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny + untilDate:[NSDate distantPast] + inMode:NSDefaultRunLoopMode + dequeue:YES]; + if (!event) break; + [NSApp sendEvent:event]; + } + // Timers and other run-loop sources deliver AppKit work that is not an + // event, so give the run loop one bounded, nonblocking turn as well. + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]]; + } + if (node->event_failure) { + node->event_failure = false; + return failure("event queue limit or allocation exceeded; one or more events were lost"); + } + auto found = std::find_if(impl_->events.begin(), impl_->events.end(), + [window](const auto &event) { return event.window == window; }); + if (found == impl_->events.end()) return success(0); + if (impl_->snapshots.size() >= max_snapshots || found->text.size() > max_event_text_bytes - impl_->snapshot_bytes) + return failure("event snapshot limit exceeded; release previously returned snapshots"); + auto handle = fresh_handle(); if (!handle) return failure("handle space exhausted"); + impl_->snapshots.emplace(handle, *found); + impl_->snapshot_bytes += found->text.size(); impl_->event_bytes -= found->text.size(); + impl_->events.erase(found); + return success(handle); +} + +Result Context::event_number(std::int64_t snapshot, const std::string &field) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto found = impl_->snapshots.find(snapshot); + if (found == impl_->snapshots.end()) return failure("unknown, released, or foreign event snapshot"); + const auto &event = found->second; + if (field == "kind") return success(event.kind); + if (field == "target") return success(event.target); + if (field == "window") return success(event.window); + if (field == "checked") return success(event.checked); + return failure("event field must be kind, target, window, or checked"); +} + +Result Context::event_text(std::int64_t snapshot) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto found = impl_->snapshots.find(snapshot); + if (found == impl_->snapshots.end()) return failure("unknown, released, or foreign event snapshot"); + return {0, found->second.text, {}}; +} + +Result Context::release_event(std::int64_t snapshot) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto found = impl_->snapshots.find(snapshot); + if (found == impl_->snapshots.end()) return failure("unknown, released, or foreign event snapshot"); + impl_->snapshot_bytes -= found->second.text.size(); impl_->snapshots.erase(found); + return success(); +} + +Result Context::destroy_widget(std::int64_t handle) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(handle); if (!node) return Impl::bad_handle(); + if (node->kind == Kind::window) + return failure("destroy_widget requires a non-window widget; use close for windows"); + auto *parent = impl_->find(node->parent); + if (!parent || !container(parent->kind)) return failure("widget parent is no longer a live container"); + + // Handles increase monotonically and children are created after their + // parent, so one ordered pass collects the complete subtree. + std::vector removed; + try { + removed.reserve(impl_->nodes.size()); + for (const auto &[id, child] : impl_->nodes) + if (id == handle || std::binary_search(removed.begin(), removed.end(), child.parent)) + removed.push_back(id); + } catch (...) { return failure("widget removal allocation failed"); } + + const auto window = node->window; + impl_->tearing_down = true; + @autoreleasepool { + [node->view removeFromSuperview]; + for (auto it = removed.rbegin(); it != removed.rend(); ++it) { + auto found = impl_->nodes.find(*it); + if (found == impl_->nodes.end()) continue; + impl_->handles.erase((__bridge void *)found->second.view); + impl_->text_bytes -= found->second.text.size(); + found->second.view = nil; + impl_->nodes.erase(found); + } + } + impl_->tearing_down = false; + + const auto targeted = [&](std::int64_t target) { return std::binary_search(removed.begin(), removed.end(), target); }; + for (auto it = impl_->events.begin(); it != impl_->events.end();) { + if (!targeted(it->target)) { ++it; continue; } + impl_->event_bytes -= it->text.size(); it = impl_->events.erase(it); + } + for (auto it = impl_->snapshots.begin(); it != impl_->snapshots.end();) { + if (!targeted(it->second.target)) { ++it; continue; } + impl_->snapshot_bytes -= it->second.text.size(); it = impl_->snapshots.erase(it); + } + auto focus = impl_->focus_targets.find(window); + if (focus != impl_->focus_targets.end() && targeted(focus->second)) impl_->focus_targets.erase(focus); + impl_->relayout(window); + return success(); +} + +Result Context::close(std::int64_t window) { + if (!impl_) return failure("context allocation failed"); + if (auto result = impl_->check(); !result) return result; + auto *node = impl_->find(window); if (!node) return Impl::bad_handle(); + if (node->kind != Kind::window) return failure("close requires a window"); + + impl_->tearing_down = true; + @autoreleasepool { + node->window_object.delegate = nil; + [node->window_object close]; + impl_->handles.erase((__bridge void *)node->window_object); + for (auto it = impl_->nodes.begin(); it != impl_->nodes.end();) { + if (it->second.window != window) { ++it; continue; } + impl_->handles.erase((__bridge void *)it->second.view); + impl_->text_bytes -= it->second.text.size(); + it->second.view = nil; + it->second.window_object = nil; + it = impl_->nodes.erase(it); + } + } + impl_->tearing_down = false; + + for (auto it = impl_->events.begin(); it != impl_->events.end();) { + if (it->window != window) { ++it; continue; } + impl_->event_bytes -= it->text.size(); it = impl_->events.erase(it); + } + for (auto it = impl_->snapshots.begin(); it != impl_->snapshots.end();) { + if (it->second.window != window) { ++it; continue; } + impl_->snapshot_bytes -= it->second.text.size(); it = impl_->snapshots.erase(it); + } + impl_->focus_targets.erase(window); + return success(); +} +} // namespace ny::ui diff --git a/nillinker/main.cpp b/nillinker/main.cpp index 0277c069..5015db7e 100644 --- a/nillinker/main.cpp +++ b/nillinker/main.cpp @@ -1559,6 +1559,14 @@ bool Linker::link(const fs::path &requested_output) { #if defined(__linux__) arguments.push_back("-ldl"); #endif +#if defined(__APPLE__) + // The runtime's AppKit desktop provider is part of nil.a, so every program + // linked against it needs the frameworks that provider calls. + arguments.push_back("-framework"); + arguments.push_back("Cocoa"); + arguments.push_back("-framework"); + arguments.push_back("CoreGraphics"); +#endif #endif const auto process = ny::linker_detail::run_process( diff --git a/tests/ui_runtime_appkit_tests.mm b/tests/ui_runtime_appkit_tests.mm new file mode 100644 index 00000000..e2db66e8 --- /dev/null +++ b/tests/ui_runtime_appkit_tests.mm @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +// macOS provider contract for ui.v1, the Darwin counterpart of +// tests/ui_runtime_win32_tests.cpp. The GTK fixture inspects loaded GTK +// modules and symbol origins, so it describes that provider and cannot speak +// for AppKit. +// +// Modes: --provider-present reports availability without opening a display, +// --display runs the full contract against a window server session. With no +// argument the fixture adapts, so a session-less runner still checks that +// window creation is refused rather than silently skipping everything. +// +// main() runs on the process main thread, which is where AppKit requires the +// provider to be used. +#include "ui_runtime.hpp" + +#include +#include + +#import + +namespace { + +int checks = 0; + +void require(bool condition, const char *what) { + ++checks; + if (condition) return; + std::cout.flush(); + std::cerr << "UI runtime test failure: " << what << "\n"; + std::exit(1); +} + +std::int64_t ok(const ny::ui::Result &result, const char *what) { + if (!result) { + std::cout.flush(); + std::cerr << "UI runtime test failure: " << what << ": " << result.error << "\n"; + std::exit(1); + } + ++checks; + return result.number; +} + +void rejected(const ny::ui::Result &result, const char *fragment, const char *what) { + ++checks; + if (!result.error.empty() && result.error.find(fragment) != std::string::npos) return; + std::cout.flush(); + std::cerr << "UI runtime test failure: " << what << ": expected rejection containing '" + << fragment << "', got '" << result.error << "'\n"; + std::exit(1); +} + +bool window_server() { return CGMainDisplayID() != 0; } + +std::int64_t next_event(ny::ui::Context &context, std::int64_t window) { + for (int attempt = 0; attempt < 64; ++attempt) { + const auto polled = context.poll(window); + if (!polled) return 0; + if (polled.number) return polled.number; + } + return 0; +} + +void contract() { + ny::ui::Context context; + const auto window = ok(context.window("NIL AppKit provider", 420, 320), "create window"); + require(window > 0, "window handle is nonzero"); + require(ok(context.read_number(window, "kind"), "window kind") == 0, "window reports kind 0"); + require(ok(context.read_number(window, "parent"), "window parent") == 0, "window has no parent"); + require(ok(context.read_number(window, "visible"), "window visible") == 0, "window starts hidden"); + require(ok(context.read_number(window, "width"), "window width") == 420, "window reports requested width"); + + const auto column = ok(context.widget("column", window, ""), "create column"); + require(ok(context.read_number(column, "kind"), "column kind") == 1, "column reports kind 1"); + const auto label = ok(context.widget("label", column, "Hello"), "create label"); + const auto button = ok(context.widget("button", column, "Press"), "create button"); + const auto check = ok(context.widget("checkbox", column, "Check"), "create checkbox"); + const auto entry = ok(context.widget("entry", column, "abc"), "create entry"); + + const auto text = context.read_text(label); + require(ok(text, "read label") == 0 && text.text == "Hello", "label keeps its text"); + const auto typed = context.read_text(entry); + require(ok(typed, "read entry") == 0 && typed.text == "abc", "entry reports its live text"); + + const std::string unicode = "caf\xc3\xa9 \xe4\xb8\xad\xe6\x96\x87"; + ok(context.set_text(label, unicode), "set unicode label"); + const auto round_trip = context.read_text(label); + require(ok(round_trip, "read unicode label") == 0 && round_trip.text == unicode, + "label round-trips non-ASCII text"); + + ok(context.set_number(window, "visible", 1), "present window"); + require(ok(context.read_number(window, "visible"), "window visible") == 1, "window reports visible"); + require(ok(context.read_number(label, "effective_visible"), "label effective visible") == 1, + "a child of a shown window is effectively visible"); + require(ok(context.read_number(entry, "width"), "entry width") > 0, "provider allocates entry width"); + require(ok(context.read_number(entry, "height"), "entry height") > 0, "provider allocates entry height"); + + require(next_event(context, window) == 0, "no event is queued before activation"); + ok(context.activate(button), "activate button"); + const auto snapshot = next_event(context, window); + require(snapshot != 0, "button activation produces an event"); + require(ok(context.event_number(snapshot, "kind"), "event kind") == 1, "button activation is event kind 1"); + require(ok(context.event_number(snapshot, "target"), "event target") == button, "event targets the button"); + require(ok(context.event_number(snapshot, "window"), "event window") == window, "event names its window"); + ok(context.release_event(snapshot), "release button event"); + + require(ok(context.read_number(check, "checked"), "checkbox state") == 0, "checkbox starts clear"); + ok(context.activate(check), "activate checkbox"); + const auto toggled = next_event(context, window); + require(toggled != 0, "checkbox activation produces an event"); + require(ok(context.event_number(toggled, "kind"), "toggle kind") == 3, "checkbox toggle is event kind 3"); + require(ok(context.event_number(toggled, "checked"), "toggle checked") == 1, "toggle reports the new state"); + require(ok(context.read_number(check, "checked"), "checkbox state") == 1, "checkbox is now set"); + ok(context.release_event(toggled), "release toggle event"); + + ok(context.set_text(entry, "quiet"), "set entry text"); + require(next_event(context, window) == 0, "programmatic set_text raises no event"); + ok(context.set_number(check, "checked", 0), "clear checkbox"); + require(next_event(context, window) == 0, "programmatic checked raises no event"); + + ok(context.set_number(entry, "focus", 1), "focus entry"); + require(ok(context.read_number(entry, "focus"), "entry focus") == 1, "entry reports keyboard focus"); + + ok(context.set_number(column, "sensitive", 0), "disable column"); + require(ok(context.read_number(button, "effective_sensitive"), "button effective sensitive") == 0, + "a child of an insensitive container is insensitive"); + rejected(context.activate(button), "insensitive", "activate insensitive button"); + ok(context.set_number(column, "sensitive", 1), "re-enable column"); + + const auto grid = ok(context.widget("grid", window, ""), "create grid"); + const auto first = ok(context.widget("label", grid, "one"), "create grid child one"); + const auto second = ok(context.widget("label", grid, "two"), "create grid child two"); + ok(context.grid_attach(grid, first, 0, 0, 1, 1), "attach first grid child"); + rejected(context.grid_attach(grid, second, 0, 0, 1, 1), "overlaps", "overlapping grid placement"); + ok(context.grid_attach(grid, second, 1, 0, 1, 1), "attach second grid child"); + + rejected(context.widget("menu", window, ""), "widget kind", "unknown widget kind"); + rejected(context.widget("label", 0, ""), "handle", "unknown parent handle"); + rejected(context.set_number(button, "visible", 2), "0 or 1", "non-boolean flag"); + rejected(context.set_number(column, "spacing", 9000), "4096", "out-of-range spacing"); + rejected(context.set_number(button, "checked", 1), "checkbox", "checked on a button"); + rejected(context.read_number(column, "text"), "numeric property", "unknown numeric property"); + rejected(context.read_text(column), "container", "text on a container"); + rejected(context.destroy_widget(window), "non-window", "destroy_widget on a window"); + rejected(context.poll(button), "window", "poll on a widget"); + rejected(context.set_text(label, std::string("\xff\xfe")), "UTF-8", "invalid UTF-8 text"); + + const auto doomed = ok(context.widget("row", column, ""), "create row"); + const auto child = ok(context.widget("label", doomed, "gone"), "create row child"); + ok(context.destroy_widget(doomed), "destroy row"); + rejected(context.read_number(child, "kind"), "handle", "descendant handle is invalidated"); + require(ok(context.read_number(label, "kind"), "surviving label") == 4, "unrelated widgets survive"); + + ok(context.close(window), "close window"); + rejected(context.read_number(label, "kind"), "handle", "closed window invalidates its children"); + rejected(context.close(window), "handle", "closing twice is an error"); +} + +} // namespace + +int main(int argc, char **argv) { + const std::string mode = argc > 1 ? argv[1] : ""; + require(ny::ui::available(), "macOS provider is always available"); + if (mode == "--provider-present") { + std::cout << "UI runtime: " << checks << " checks passed (--provider-present)\n"; + return 0; + } + const bool desktop = window_server(); + if (mode == "--display") { + require(desktop, "--display requires a window server session"); + contract(); + std::cout << "UI runtime: " << checks << " checks passed (--display)\n"; + return 0; + } + if (desktop) contract(); + else { + ny::ui::Context context; + rejected(context.window("no session", 320, 240), "window server", + "window creation without a window server session"); + } + std::cout << "UI runtime: " << checks << " checks passed (" + << (desktop ? "desktop" : "no-desktop") << ")\n"; + return 0; +} From bb72478d91247d276e04e66c23e7ed962f48e5e7 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Sun, 8 Nov 2026 21:23:54 -0500 Subject: [PATCH 7/7] Correct three AppKit defects found by review, not by CI With no Mac here, every compile is a CI run, so the provider was read again before spending one. Context::Impl is private to Context, so an Objective-C class outside that scope cannot name it -- the same access wall the Win32 callbacks hit. The delegate now carries a block built inside Impl, which closes over a weak reference and takes the access with it, so the target never names the private type. AppKit has no -[NSControl sizeThatFits:]; that is UIKit. Natural sizes come from NSView fittingSize. Objective-C pointer downcasts are not C++ class casts, so the static_casts from NSView * to the concrete control types become ordinary Objective-C casts. Co-Authored-By: Claude Opus 5 --- nilcompiler/src/ui_runtime_appkit.mm | 92 ++++++++++++++-------------- 1 file changed, 45 insertions(+), 47 deletions(-) diff --git a/nilcompiler/src/ui_runtime_appkit.mm b/nilcompiler/src/ui_runtime_appkit.mm index 022bfdf0..0ebb5336 100644 --- a/nilcompiler/src/ui_runtime_appkit.mm +++ b/nilcompiler/src/ui_runtime_appkit.mm @@ -81,12 +81,29 @@ @implementation NyUiContainer - (BOOL)isFlipped { return YES; } @end +// The delivery block is built inside Context::Impl, which is private to +// Context; a block carries that access, where naming the type here could not. +typedef void (^NyUiDeliver)(id sender, long long kind); + @interface NyUiTarget : NSObject -@property(nonatomic, assign) void *owner; +@property(nonatomic, copy) NyUiDeliver deliver; - (void)buttonAction:(id)sender; - (void)checkAction:(id)sender; @end +@implementation NyUiTarget +- (void)buttonAction:(id)sender { if (self.deliver) self.deliver(sender, 1); } +- (void)checkAction:(id)sender { if (self.deliver) self.deliver(sender, 3); } +- (void)controlTextDidChange:(NSNotification *)notification { + if (self.deliver) self.deliver(notification.object, 2); +} +- (BOOL)windowShouldClose:(NSWindow *)sender { + if (self.deliver) self.deliver(sender, 4); + // Matrix decides when to close; AppKit must not destroy a live handle. + return NO; +} +@end + namespace ny::ui { struct Context::Impl : std::enable_shared_from_this { @@ -208,11 +225,11 @@ void enqueue(std::int64_t handle, std::int64_t kind) noexcept { if (!node || node->suppress || tearing_down) return; Event event{kind, handle, node->window, 0, {}}; if (kind == 2) { - auto *field = static_cast(node->view); + auto *field = ((NSTextField *)node->view); if (!from_ns(field.stringValue, event.text)) { mark_failure(); return; } if (!valid_text(event.text)) { mark_failure(); return; } } else if (kind == 3) { - auto *button = static_cast(node->view); + auto *button = ((NSButton *)node->view); event.checked = button.state == NSControlStateValueOn ? 1 : 0; } if (events.size() >= max_events || event.text.size() > max_event_text_bytes - event_bytes) { @@ -246,8 +263,7 @@ NSSize natural(std::int64_t handle) { case Kind::button: case Kind::checkbox: case Kind::entry: { - auto *control = static_cast(node->view); - size = [control sizeThatFits:NSMakeSize(0, 0)]; + size = node->view.fittingSize; if (node->kind == Kind::entry) size.width = std::max(size.width, minimum_entry_width); size.width += control_padding; size.height += control_padding; @@ -406,6 +422,20 @@ void relayout(std::int64_t window) { place(window, NSMakeRect(0, 0, content.size.width, content.size.height)); } + // Built here so the block closes over a weak reference with full access to + // Impl; the target itself never names the private type. + NyUiTarget *make_target() { + NyUiTarget *created = [[NyUiTarget alloc] init]; + std::weak_ptr weak = weak_from_this(); + created.deliver = ^(id sender, long long kind) { + auto impl = weak.lock(); + if (!impl || !impl->active.load() || impl->tearing_down) return; + const auto handle = impl->handle_of((__bridge void *)sender); + if (handle) impl->enqueue(handle, static_cast(kind)); + }; + return created; + } + void dispose() noexcept { active.store(false); tearing_down = true; @@ -418,7 +448,7 @@ void dispose() noexcept { } for (auto &entry : nodes) entry.second.view = nil; } - if (target) { target.owner = nullptr; target = nil; } + if (target) { target.deliver = nil; target = nil; } nodes.clear(); handles.clear(); focus_targets.clear(); events.clear(); snapshots.clear(); event_bytes = snapshot_bytes = text_bytes = 0; @@ -426,35 +456,6 @@ void dispose() noexcept { } }; -} // namespace ny::ui - -@implementation NyUiTarget -- (ny::ui::Context::Impl *)impl { - return static_cast(self.owner); -} -- (void)deliver:(id)sender kind:(std::int64_t)kind { - auto *impl = [self impl]; - if (!impl || !impl->active.load() || impl->tearing_down) return; - const auto handle = impl->handle_of((__bridge void *)sender); - if (handle) impl->enqueue(handle, kind); -} -- (void)buttonAction:(id)sender { [self deliver:sender kind:1]; } -- (void)checkAction:(id)sender { [self deliver:sender kind:3]; } -- (void)controlTextDidChange:(NSNotification *)notification { - [self deliver:notification.object kind:2]; -} -- (BOOL)windowShouldClose:(NSWindow *)sender { - auto *impl = [self impl]; - if (impl && impl->active.load() && !impl->tearing_down) { - const auto handle = impl->handle_of((__bridge void *)sender); - if (handle) impl->enqueue(handle, 4); - } - // Matrix decides when to close; AppKit must not destroy a live handle. - return NO; -} -@end - -namespace ny::ui { // AppKit is part of the operating system, so unlike the optional GTK provider // there is nothing to locate or verify. Reporting availability must still not @@ -504,10 +505,7 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { initWithFrame:NSMakeRect(0, 0, static_cast(width), static_cast(height))]; if (!root) return failure("AppKit could not create the root layout"); window.contentView = root; - if (!impl_->target) { - impl_->target = [[NyUiTarget alloc] init]; - impl_->target.owner = impl_.get(); - } + if (!impl_->target) impl_->target = impl_->make_target(); window.delegate = impl_->target; node.window_object = window; node.view = root; @@ -652,9 +650,9 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { switch (node->kind) { case Kind::window: node->window_object.title = value; break; case Kind::label: - case Kind::entry: static_cast(node->view).stringValue = value; break; + case Kind::entry: ((NSTextField *)node->view).stringValue = value; break; case Kind::button: - case Kind::checkbox: static_cast(node->view).title = value; break; + case Kind::checkbox: ((NSButton *)node->view).title = value; break; default: break; } --node->suppress; @@ -673,7 +671,7 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { Result result; @autoreleasepool { if (node->kind == Kind::entry) { - if (!from_ns(static_cast(node->view).stringValue, result.text)) + if (!from_ns(((NSTextField *)node->view).stringValue, result.text)) return failure("AppKit returned invalid text"); } else result.text = node->text; } @@ -720,10 +718,10 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { impl_->relayout(node->window); } } else if (property == "sensitive") { - if (!container(node->kind)) static_cast(node->view).enabled = value ? YES : NO; + if (!container(node->kind)) ((NSControl *)node->view).enabled = value ? YES : NO; } else if (property == "checked") { ++node->suppress; - static_cast(node->view).state = value ? NSControlStateValueOn : NSControlStateValueOff; + ((NSButton *)node->view).state = value ? NSControlStateValueOn : NSControlStateValueOff; --node->suppress; } else if (size) { NSRect frame = node->window_object.frame; @@ -745,7 +743,7 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { if (property == "parent") return success(node->parent); if (property == "checked") { if (node->kind != Kind::checkbox) return failure("checked requires a checkbox"); - return success(static_cast(node->view).state == NSControlStateValueOn ? 1 : 0); + return success(((NSButton *)node->view).state == NSControlStateValueOn ? 1 : 0); } if (property == "visible") { if (node->kind == Kind::window) return success(node->window_object.visible ? 1 : 0); @@ -757,7 +755,7 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { auto found = node->properties.find("sensitive"); return success(found == node->properties.end() || found->second ? 1 : 0); } - return success(static_cast(node->view).enabled ? 1 : 0); + return success(((NSControl *)node->view).enabled ? 1 : 0); } if (property == "effective_sensitive") return success(impl_->effective_sensitive(*node) ? 1 : 0); if (property == "focus") { @@ -808,7 +806,7 @@ - (BOOL)windowShouldClose:(NSWindow *)sender { @autoreleasepool { // performClick: is the real activation path: it toggles a switch button // and sends the action exactly as a user click does. - [static_cast(node->view) performClick:nil]; + [((NSButton *)node->view) performClick:nil]; } return success(); }