diff --git a/.github/workflows/source-validation.yml b/.github/workflows/source-validation.yml index 700d226d..1baca741 100644 --- a/.github/workflows/source-validation.yml +++ b/.github/workflows/source-validation.yml @@ -38,7 +38,8 @@ jobs: sudo apt-get install --no-install-recommends -y \ build-essential cmake ninja-build python3 pandoc \ libffi-dev libtinfo-dev libx11-dev zlib1g-dev libzstd-dev \ - libsqlite3-dev libpq-dev postgresql-16 + libsqlite3-dev libpq-dev postgresql-16 \ + libgtk-4-1 xvfb xauth libxtst6 dbus-daemon if [ "$NIL_CI_LLVM" = ON ]; then sudo apt-get install --no-install-recommends -y llvm-18-dev fi diff --git a/CMakeLists.txt b/CMakeLists.txt index e0492da7..da6faa11 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -131,6 +131,16 @@ if(BUILD_TESTING) add_test(NAME nil.database-runtime COMMAND $) set_tests_properties(nil.database-runtime PROPERTIES LABELS "database;runtime" SKIP_RETURN_CODE 77 TIMEOUT 60) + 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 $) + 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}) + target_compile_features(nil_ui_lifecycle_tests PRIVATE cxx_std_17) + add_executable(ny_native_owned_tests tests/native_owned_tests.cpp) target_link_libraries(ny_native_owned_tests PRIVATE nilruntime Threads::Threads) target_include_directories(ny_native_owned_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") @@ -433,6 +443,39 @@ if(BUILD_TESTING) # test suite when testing was explicitly enabled. find_package(Python3 3.8 REQUIRED COMPONENTS Interpreter) if(Python3_Interpreter_FOUND) + find_program(NIL_UI_XVFB NAMES Xvfb DOC "Optional Xvfb for isolated desktop UI tests") + add_test(NAME nil.ui-display + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/ui_display_contract.py" + --xvfb "${NIL_UI_XVFB}" + --tester $ --compiler $ + --interpreter $ + --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 $ + --lifecycle-test $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.ui-display PROPERTIES LABELS "ui;routes" SKIP_RETURN_CODE 77 TIMEOUT 240) + add_test(NAME nil.ui-intrinsic-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/ui_intrinsic_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.ui-intrinsic-contract PROPERTIES LABELS "ui;routes;typecheck" TIMEOUT 180) + add_test(NAME matrix.consider-block-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/consider_block_contract.py" + --compiler $ --interpreter $ + --tester $ --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(matrix.consider-block-contract PROPERTIES LABELS "matrix;routes" TIMEOUT 120) + set(NIL_UI_TEST_ROUTES vm) + if(NIL_ENABLE_LLVM) + set(NIL_UI_TEST_ROUTES all) + endif() + add_test(NAME nil.ui-models + COMMAND $ run + --compiler $ --interpreter $ + --target ${NIL_UI_TEST_ROUTES} --filter nil.std.ui.models + "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src/ui/models.matrix") + set_tests_properties(nil.ui-models PROPERTIES LABELS "ui;routes" TIMEOUT 60) set(NY_IDENTITY_TEST_ARGUMENTS) foreach(tool IN ITEMS nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent nilbuild niltest) if(TARGET ${tool}) @@ -1916,6 +1959,15 @@ if(BUILD_TESTING) --expected-exit 0 --routes all ) + foreach(nil_enum_language IN ITEMS ny matrix) + add_ny_route_test( + nil.routes.enum-assignment-context-${nil_enum_language} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/enum-assignment-context.${nil_enum_language}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/enum-assignment-context.stdout" + --expected-exit 0 --routes all + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src) + endforeach() add_ny_route_test( ny.routes.native-rejects-unknown-nominal-signature --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/native-unknown-nominal-signature.ny" diff --git a/README.md b/README.md index 90d1a838..35710cec 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,15 @@ The framework includes: workspace snapshot. Compiler-resolved source bindings support Go to Definition for local variables, parameters and imported functions across both languages. Certified local variables also support references and checked rename. +- **Tests beside code.** `niltest` discovers compiler-checked test declarations, + annotated functions, and suites in Ny and Matrix. Inline test regions can + check a function's local state. Cases run in isolated VM or native processes + and appear in VS Code's Test Explorer. See the + [testing guide](docs/tools/testing.md). +- **Desktop applications.** The Matrix-authored + [`nil.std.ui`](docs/standard-library/ui.md) provides windows, layout containers, + standard controls, typed events, and explicit model synchronization. Its first + backend uses the optional GTK 4 runtime on Linux, on both execution routes. - **Aperture runtime diagnostics.** Memory profiles record runtime allocations, frees, retained storage, peaks and source locations for VM and native programs. Saved JSON reports support inspection and automated analysis. See diff --git a/docs/README.md b/docs/README.md index 43913915..ec316a0b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,6 +25,8 @@ command-line help, and executable tests as bugs. - [Standard-library status](standard-library/index.md) — layout, maturity, and what is deliberately outside the core library. - [NILData](standard-library/nildata.md) — structured data, JSON interchange and explicit NyData migration. +- [Tests beside code](tools/testing.md) — co-located suites, inline checks and VM/native execution. +- [Desktop UI](standard-library/ui.md) — Matrix windows, layouts, controls and typed events. - [Examples](../examples/README.md) — small examples tied to repository fixtures. - [Matrix](../matrix/README.md) — prose-oriented frontend, syntax, and examples. - [Ny](../ny/README.md) — systems-language frontend and reference entry point. diff --git a/docs/design/NIL-0025-matrix-desktop-ui.md b/docs/design/NIL-0025-matrix-desktop-ui.md new file mode 100644 index 00000000..e2d3ded0 --- /dev/null +++ b/docs/design/NIL-0025-matrix-desktop-ui.md @@ -0,0 +1,73 @@ +# NIL-0025: Matrix desktop UI + +Status: initial Linux desktop profile. + +## Purpose + +Provide a standard application UI library authored in Matrix, usable from Ny +and Matrix through the same VM and native runtime. The public library and +provider code use the repository's MIT license. GTK remains an optional system +dependency under its own license; the SDK does not redistribute it. + +The earlier `packages/ny.ui.mimic` and `nilaix` experiments are not the +implementation base. Their simulated or incomplete providers cannot establish +desktop behavior. The new library lives under `nilstd/src/ui` with the public +identity `nil.std.ui`. + +## Boundaries + +Matrix owns typed Window, Widget, EventKind and Event values, constructors, +checked operations, event decoding, and text/flag model synchronization. A +small versioned `ui.v1.*` intrinsic boundary carries only Boolean, integer, +text, and the standard Result type. The checker, VM and LLVM backend validate +this ABI; a similarly named user enum is not an interchangeable Result. + +The shared C++ runtime loads GTK 4 through its public opaque-pointer ABI on +Linux. Loading is optional and does not require toolkit development headers. +It never fabricates successful windows when a provider or display is missing. +Creating a window returns Result.Error with the reason in that case. + +GTK callbacks enqueue copied events; they do not invoke arbitrary language +function pointers. `poll-event` returns Result of Option of Event: absence is +an empty queue, and failure is an error. Close requests are events which the +application can accept by explicitly closing the window. Programmatic setters +suppress change events, so explicit model synchronization cannot recursively +feed itself. This boundary leaves room for a future checked callback API. + +## Resources + +Each runtime context owns its window tree and snapshots. Handles are checked +identities, not addresses. Closing a window invalidates its children and queued +snapshots; cross-context and stale handles fail. Snapshot data is copied into +Matrix values and released even when decoding fails. VM completion, faults, +reset and native invocation completion release the context's resources. + +The provider enforces its creation thread and one GTK thread per process. +Widget, window, text, event and snapshot counts are bounded. Text is valid UTF-8 +without embedded NUL; Boolean properties accept only zero or one. Grid +placement rejects overlap and invalid parentage. Application code owns the +event loop and can use ordinary runtime timing primitives between polls. + +## Verification and scope + +Pure models have co-located niltest cases. Provider tests cover error paths, +resource lifetimes and toolkit state. An isolated authenticated Xvfb display +hosts the actual GTK windows for VM/native tests. XTest drives entry typing and +keyboard activation; a window-manager close message verifies close requests. +The harness never targets the developer's desktop. Missing Xvfb is an explicit +test skip, not desktop evidence. + +The initial controls are row/column/grid layouts, labels, buttons, entries and +checkboxes, with common sizing, spacing, margins, visibility and sensitivity. +This is a foundation for application development. Declarative NILData views, +menus, dialogs, tree/table models, styling, richer bindings, accessibility +audits, application packaging and additional OS providers remain follow-up +work. GTK supplies native text rendering and control behavior; those features +must receive focused evidence before broader cross-platform claims. + +## Public version presentation + +Examples and public UI may display the generation as **NIL²**, followed by +NIL³, NIL⁴ and later generations. Plain-text surfaces can use `NIL^2`. +This presentation is separate from the Execute-format numeric release and +artifact identity in `VERSION`; this change does not cut or renumber a release. diff --git a/docs/design/README.md b/docs/design/README.md index f2734bc3..1876bb69 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -47,6 +47,7 @@ not assigned architecture identifiers. | NIL-0022 | [Incremental project builds and NILData configuration](NIL-0022-incremental-project-builds.md) | Implemented initial local project graph and target scheduling profile | | NIL-0023 | [Dynamic values and Boolean vocabulary](NIL-0023-dynamic-values-and-booleans.md) | Implemented | | NIL-0024 | [Tests alongside source](NIL-0024-colocated-testing.md) | Implemented initial unit/integration profile | +| NIL-0025 | [Matrix desktop UI](NIL-0025-matrix-desktop-ui.md) | Initial Linux GTK 4 desktop profile | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index ed312c15..908655b0 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -1,7 +1,7 @@ # Standard-library status Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its active -Ny and Matrix sources form 17 logical SDK modules, including `prelude`. +Ny and Matrix sources form 18 logical SDK modules, including `prelude`. Support remains evidence-scoped. Focused fixtures exercise `nilstd` and `nillib` through textual/binary NIL, bundles, LLVM JIT and AOT, and standalone assembler/linker pipelines. Local SDK qualification records the exact source @@ -31,7 +31,7 @@ averaging, nonfinite compatibility behavior and numerical accuracy limits. ```text nilstd/ - src/ Ny and Matrix sources organized as 17 logical modules + src/ Ny and Matrix sources organized as 18 logical modules native/ 14 preserved C and C++ interoperability shims tests/ 8 preserved design-era library tests experimental/ 65 quarantined Ny sources excluded from the SDK @@ -43,7 +43,7 @@ remain aliases of the same module identities. The active logical modules are `prelude` and `nil.std.core`, `collections`, `datetime`, `db`, `diagnostics`, `io`, `math`, `net`, `nildata`, `reflection`, `runtime`, -`security`, `system`, `testing`, `text`, and `threading`. Quarantine is broader than parser +`security`, `system`, `testing`, `text`, `threading`, and `ui`. Quarantine is broader than parser failure: an experimental source may compile yet still lack complete language semantics, an executable provider, or behavioral evidence. @@ -57,8 +57,8 @@ nillib/ matching strictly compiled binary NIL modules For every source under `nilstd/path/module` (`.ny`, `.matrix`, or `.mat`), a complete SDK contains `nillib/path/module.nil`. `manifest.json` records both inventories and hashes. -First-party engine and UI experiments are intentionally separate from the core -library: +The active [desktop UI library](ui.md) lives in `nilstd/src/ui` and is authored +in Matrix. The earlier engine and UI experiments remain separate: ```text packages/ny.engine/ @@ -78,6 +78,15 @@ them in test blocks makes them test-only. See the [co-located testing guide](../tools/testing.md) for language syntax, discovery, execution routes, and editor integration. +## Desktop UI + +`nil.std.ui` supplies checked windows, rows, columns, grids, labels, buttons, +text entries, and checkboxes. Copied typed events and explicit text/flag models +keep application logic in Matrix; the shared runtime owns native resources. +The initial provider uses GTK 4 on Linux and returns an explanatory error when +the optional provider or a display is unavailable. See the [UI reference](ui.md) +and [NIL² counter application](../../examples/projects/nil2-counter). + ## NILData `nil.std.nildata` provides checked, versioned data loading and serialization, diff --git a/docs/standard-library/ui.md b/docs/standard-library/ui.md new file mode 100644 index 00000000..6465ddf2 --- /dev/null +++ b/docs/standard-library/ui.md @@ -0,0 +1,166 @@ +# NIL² desktop UI + +`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. +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`. + +This first version supports real windows, row and column layouts, grids, +labels, buttons, text entries and checkboxes. Application logic stays in Matrix; +the provider implements widget operations and copies events across the runtime +boundary. It does not call application code from GTK callbacks. + +## Run the example + +The [counter and settings project](../../examples/projects/nil2-counter/README.md) +contains a complete event loop. Editing the name updates its greeting, the +checkbox changes the increment from one to ten, and the buttons increment, +reset and close the application. + +With a current SDK on `PATH`, run from `examples/projects/nil2-counter`: + +```sh +nilbuild run +nilbuild run --target native +``` + +For a source checkout, pass `--sdk /absolute/path/to/exec-nil-framework` and use +the tools from that checkout's build. See the [project workflow](../tools/projects.md) +for compiler selection. Native output requires an LLVM-enabled compiler and +the host linker. + +The Linux host must provide GTK4 and a working graphical session, through +X11 or Wayland. `available with nothing` checks whether the provider's required +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. + +## Windows and widgets + +`Window` and `Widget` are distinct records containing checked provider handles. +Use constructors to obtain them. Operations validate context ownership, kind +and lifetime; a fabricated, closed or foreign handle returns an error. +Copying a record refers to the same underlying object and does not create a +second window or widget. + +| Operation | Result and behavior | +| --- | --- | +| `create-window(title, width, height)` | `Result`; creates a hidden window. | +| `window-root(window)` | `Widget`; the window's automatic column container. | +| `create-column(parent)`, `create-row(parent)`, `create-grid(parent)` | `Result`; nested layout containers. | +| `create-label(parent, text)`, `create-button(parent, text)` | `Result`; labeled controls. | +| `create-entry(parent, text)`, `create-checkbox(parent, text)` | `Result`; initial entry content or checkbox label. A new checkbox is unchecked. | +| `show-window(window)`, `close-window(window)` | `Result`; present or destroy the window. | +| `set-widget-text(widget, text)`, `widget-text(widget)` | Write or read label/entry text; reading returns `Result`. | +| `set-checked(widget, boolean)`, `widget-checked(widget)` | Checkbox state; reading returns `Result`. | +| `set-sensitive(widget, boolean)`, `set-visible(widget, boolean)` | Enable/disable interaction or show/hide a widget. | +| `set-margin(widget, pixels)`, `set-spacing(container, pixels)` | Equal outer margins or spacing between children. For the window root, affect its automatic column. | +| `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. | +| `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 +a model synchronization operation explicitly reports that no write was needed. +Inappropriate properties return errors: for example, a label has no checked +state, and a button cannot be a parent container. + +Grid children initially occupy successive rows in column zero, each spanning +one cell. `attach-grid` validates the new rectangle against existing child +rectangles. When rearranging a grid, choose an order that does not temporarily +overlap another child. + +Closing a window invalidates its children and queued provider events. Calling +close again is an error. Runtime teardown closes any remaining windows, but +applications should close windows explicitly when they are finished. + +## Events + +`poll-event(surface)` returns `Result,text>`. The public +`PendingEvent` alias names `Option`, so Matrix spells this return type +`Result of PendingEvent, text`. `Option.None` means +the queue is currently empty. `Result.Error` reports a provider or resource +failure. No public null or sentinel handle represents an empty queue. + +An `Event` contains `kind`, `window`, `target`, `content` and `checked`: + +| Kind | Target | Event data | +| --- | --- | --- | +| `EventKind.Clicked` | `Option.Some` containing the button | Empty content. | +| `EventKind.TextChanged` | `Option.Some` containing the entry | A copy of the new text in `content`. | +| `EventKind.Toggled` | `Option.Some` containing the checkbox | The new Boolean state in `checked`. | +| `EventKind.CloseRequested` | `Option.None` | A window-manager close request. The window remains open until `close-window` is called. | + +Use `event-for(event, widget)` to match a target, and `is-click`, +`is-text-change`, `is-toggle` or `is-close-request` to test the kind. `content` +is empty for other event kinds; `checked` is `no` for kinds other than a toggle. +Fields are copied before the provider snapshot is released, including cleanup +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 +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 +that thread to apply. + +## Explicit model bindings + +`create-text-model(initial)` constructs a `TextModel` with a `content` field; +`create-flag-model(initial)` constructs a `FlagModel` with an `enabled` field. +Records share identity when assigned. Construct another model for independent +state. + +| Operation | Behavior | +| --- | --- | +| `update-text-model(model, next-value)`, `update-flag-model(model, next-value)` | Update model state and return whether it changed. | +| `sync-text(widget, model)`, `sync-flag(widget, model)` | Read the widget, write only if different, and return `Result` indicating whether a write was needed. | +| `apply-text-event(model, widget, event)`, `apply-flag-event(model, widget, event)` | Update the model only for the matching widget and event kind; return whether the model changed. | + +Programmatic text and checked-state setters suppress feedback events. Model +synchronization also compares values before writing. The application decides +when to synchronize and which dependent views to refresh; this is not an +automatic subscription or asynchronous command system. + +## Bounds and errors + +The provider validates text as NUL-free UTF-8. A value is limited to 1 MiB; +entries additionally accept at most 16,384 Unicode scalar values. Window +dimensions are 1–16,384 pixels, margins and spacing are 0–4,096 pixels, and grid +coordinates and extents must remain within the provider's 0–65,535 range. + +Each context allows 64 windows and 4,096 registered nodes, including windows. +It bounds queued events and outstanding snapshots at 4,096 each, with separate +16 MiB budgets for retained labels and event text. Queue overflow is reported +as an error rather than silently presenting a complete event stream. Handle +validation and these limits apply equally to VM and native execution. + +Errors describe the failed operation or violated bound. Handle errors do not +grant access to another context's objects. GTK supplies system styling, fonts +and baseline accessibility behavior. Custom drawing, menus and dialogs, +virtualized views, a visual designer, and providers for other operating systems +are outside this initial release. + +## Testing + +The pure model tests are colocated in `nilstd/src/ui/models.matrix` and need no +display. The `nil.std.ui.gtk.desktop` suite in `tests/ui/gtk_desktop.matrix` +exercises real controls, layouts, bindings, immutable event copies, errors and +closed handles. The separate `nil.std.ui.gtk.interaction` suite checks actual +keyboard input and a window-manager close request. + +`nil.ui-display` runs the desktop suites through both routes when native +compilation is enabled, using a private Xvfb display and X11 input driver. It +does not send input to an existing desktop session. Desktop interaction cases +run sequentially with `niltest --jobs 1`; see [compiler-backed testing](../tools/testing.md) +for filtering, reports and timeouts. + +The same display harness checks real GTK window counts during VM pauses and +after completion, faults, resets, reloads and destruction. Native context +completion/restart releases windows, while copied text remains valid across +managed collection. CI installs the optional GTK/Xvfb dependencies so desktop +coverage is required there; local builds without them report a test skip. diff --git a/examples/projects/nil2-counter/.gitignore b/examples/projects/nil2-counter/.gitignore new file mode 100644 index 00000000..84c048a7 --- /dev/null +++ b/examples/projects/nil2-counter/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/examples/projects/nil2-counter/README.md b/examples/projects/nil2-counter/README.md new file mode 100644 index 00000000..aa93d32f --- /dev/null +++ b/examples/projects/nil2-counter/README.md @@ -0,0 +1,34 @@ +# NIL² counter and settings + +A Matrix desktop application built with `nil.std.ui`. It has a live greeting, +a text entry, a checkbox that selects increments of one or ten, and increment, +reset and close buttons. The controls use native GTK4 layouts and events. + +With a current NIL SDK on `PATH`, run from this directory: + +```sh +nilbuild run +nilbuild run --target native +``` + +For tools built from a source checkout, supply that checkout as the SDK: + +```sh +/path/to/exec-nil-framework/build/cmake/bin/nilbuild run --sdk /path/to/exec-nil-framework +/path/to/exec-nil-framework/build/cmake/bin/nilbuild run --sdk /path/to/exec-nil-framework --target native +``` + +The host needs Linux, GTK4 and a working graphical session. Native compilation +also needs an LLVM-enabled compiler and the host linker. Missing provider or +display support produces an explanatory error. + +The window starts hidden while its controls are constructed. The event loop +copies queued events, updates explicit `TextModel` and `FlagModel` state, and +refreshes dependent controls only after a change. Programmatic setters suppress +feedback events. Clicking Close or using the window manager exits the loop and +closes the window. + +The example displays the framework generation as **NIL²**, with **NIL^2** as +the plain-text spelling; this does not change its numeric release identity. +See the [UI API and lifecycle](../../../docs/standard-library/ui.md) and +[project workflow](../../../docs/tools/projects.md) for details. diff --git a/examples/projects/nil2-counter/nil.project.nildata b/examples/projects/nil2-counter/nil.project.nildata new file mode 100644 index 00000000..40249e5f --- /dev/null +++ b/examples/projects/nil2-counter/nil.project.nildata @@ -0,0 +1,7 @@ +nildata 1 +object + schema is "nil.project.v1" + name is "nil2-counter" + entry is "src/main.matrix" + outputDirectory is "build" +end object diff --git a/examples/projects/nil2-counter/src/main.matrix b/examples/projects/nil2-counter/src/main.matrix new file mode 100644 index 00000000..1fe4de4b --- /dev/null +++ b/examples/projects/nil2-counter/src/main.matrix @@ -0,0 +1,86 @@ +book nil2.counter + +read nil.std.ui +read nil.std.core.option +read nil.std.core.result +read nil.std.threading + +!!! Startup and unrecoverable provider errors include their operation. Runtime +!!! teardown still releases the surface if a failure ends the application. +ui-value of type T receives outcome as Result of T, text, operation as text returns T begin paragraph + consider outcome + when Result.Ok holding found then give found + when Result.Error holding failure then evaluate panic with ("NIL²: " plus operation plus ": " plus failure) + end consider +end paragraph + +refresh-view receives display as Widget, increment as Widget, reset as Widget, name as TextModel, large-step as FlagModel, count as number begin paragraph + evaluate ui-value of boolean with outcome being (set-widget-text with display, formatted "Hello, {name.content}. Count: {count}"), operation being "refresh counter" + variable action-label as text is "Add 1" + when large-step.enabled then set action-label to "Add 10" end when + evaluate ui-value of boolean with outcome being (set-widget-text with increment, action-label), operation being "refresh increment label" + evaluate ui-value of boolean with outcome being (set-sensitive with reset, count does not equal 0), operation being "refresh reset button" +end paragraph + +main returns override integer begin paragraph + value surface is ui-value of Window with outcome being (create-window with "NIL² — Counter and settings", 560, 320), operation being "open window" + value root is window-root with surface + evaluate ui-value of boolean with outcome being (set-margin with root, 20), operation being "set window margin" + evaluate ui-value of boolean with outcome being (set-spacing with root, 12), operation being "set window spacing" + value heading is ui-value of Widget with outcome being (create-label with root, "NIL² · Counter and settings"), operation being "create heading" + value display is ui-value of Widget with outcome being (create-label with root, ""), operation being "create counter display" + value settings is ui-value of Widget with outcome being (create-grid with root), operation being "create settings grid" + evaluate ui-value of boolean with outcome being (set-spacing with settings, 8), operation being "space settings" + value name-label is ui-value of Widget with outcome being (create-label with settings, "Your name"), operation being "create name label" + value name-entry is ui-value of Widget with outcome being (create-entry with settings, "Matrix"), operation being "create name entry" + value step-checkbox is ui-value of Widget with outcome being (create-checkbox with settings, "Count in steps of ten"), operation being "create step checkbox" + evaluate ui-value of boolean with outcome being (attach-grid with settings, name-label, 0, 0, 1, 1), operation being "place name label" + evaluate ui-value of boolean with outcome being (attach-grid with settings, name-entry, 1, 0, 1, 1), operation being "place name entry" + evaluate ui-value of boolean with outcome being (attach-grid with settings, step-checkbox, 0, 1, 2, 1), operation being "place checkbox" + evaluate ui-value of boolean with outcome being (set-expansion with name-entry, yes, no), operation being "expand name entry" + value actions is ui-value of Widget with outcome being (create-row with root), operation being "create actions" + evaluate ui-value of boolean with outcome being (set-spacing with actions, 8), operation being "space actions" + value increment is ui-value of Widget with outcome being (create-button with actions, "Add 1"), operation being "create increment button" + value reset is ui-value of Widget with outcome being (create-button with actions, "Reset"), operation being "create reset button" + value finish is ui-value of Widget with outcome being (create-button with actions, "Close"), operation being "create close button" + value explanation is ui-value of Widget with outcome being (create-label with root, "Edit your name, choose a step, and update the counter."), operation being "create explanation" + + value name is create-text-model with "Matrix" + value large-step is create-flag-model with no + variable count as number is 0 + variable running as boolean is yes + evaluate refresh-view with display, increment, reset, name, large-step, count + evaluate ui-value of boolean with outcome being (show-window with surface), operation being "show window" + evaluate ui-value of boolean with outcome being (focus-widget with name-entry), operation being "focus name entry" + + repeat while running + value pending is ui-value of PendingEvent with outcome being (poll-event with surface), operation being "poll events" + consider pending + when Option.None then evaluate sleep-ms with 16 + when Option.Some holding notification then begin block + variable changed as boolean is no + when is-close-request with notification then + set running to no + otherwise when (is-click with notification) and (event-for with notification, finish) then + set running to no + otherwise when (is-click with notification) and (event-for with notification, increment) then + when large-step.enabled then set count to count plus 10 + otherwise set count to count plus 1 end when + set changed to yes + otherwise when (is-click with notification) and (event-for with notification, reset) then + set count to 0 + set changed to yes + otherwise when apply-text-event with name, name-entry, notification then + set changed to yes + otherwise when apply-flag-event with large-step, step-checkbox, notification then + set changed to yes + end when + when changed then + evaluate refresh-view with display, increment, reset, name, large-step, count + end when + end block + end consider + end repeat + evaluate ui-value of boolean with outcome being (close-window with surface), operation being "close window" + give 0 +end paragraph diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index 969606bc..6cf87724 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -331,6 +331,25 @@ value label as text is consider state end consider ``` +Use an explicit arm block when a statement arm contains its own `when`: + +```matrix +consider state + when job-state.Failed holding code then begin block + when code is at least 500 then + say "retry later" + otherwise + say "check the request" + end when + end block + otherwise say "ready" +end consider +``` + +`end block` distinguishes a nested conditional from the next pattern arm. +It creates the ordinary arm scope; `give` still returns from the paragraph. +The value form of `consider` continues to require one expression per arm. + Switching selects a literal case, then falls through subsequent case bodies until `stop switching` or the end. The selector runs once: diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index dc959597..dc40947c 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -311,8 +311,11 @@ repeat_head = 'while' expression * such a body returns from the enclosing FUNCTION, as it does anywhere else * in a statement position. *) consider_stmt = 'consider' expression { consider_arm } - [ 'otherwise' { statement } ] 'end' 'consider' ; -consider_arm = 'when' pattern [ 'provided' expression ] 'then' { statement } ; + [ 'otherwise' consider_body ] 'end' 'consider' ; +consider_arm = 'when' pattern [ 'provided' expression ] 'then' consider_body ; +consider_body = { statement } | 'begin' 'block' { statement } 'end' 'block' ; +(* Unbracketed pattern arms end at the next when/otherwise/end consider. + * Use an explicit body for a nested when statement. block is contextual. *) pattern = '(' pattern { ',' pattern } [ ',' ] ')' | literal | signed_number | ( 'negative' | 'minus' ) number_literal | type_name '.' identifier [ 'holding' identifier ] diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 3c58230c..4a8b399f 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2412,3 +2412,71 @@ library boundaries. Polling typed events avoids assuming the unimplemented native function-value callback ABI. Real display tests must complement headless logic tests; accessibility, Unicode text shaping, clipboard, and platform backends require explicit implementation and evidence before support claims. + +**Implemented foundation:** `nil.std.ui` now has a Matrix public API and shared +optional GTK 4 provider. Real windows, layouts, controls, copied typed events, +strict resource lifetimes and explicit text/flag model synchronization replace +simulated identities for this new API. `tests/tools/ui_display_contract.py` +drives actual keyboard and close events on a private authenticated display; +co-located model tests need no display. The old experiments remain separate. +See [NIL-0025](../../docs/design/NIL-0025-matrix-desktop-ui.md) for boundaries +and outstanding widget/platform work. + +### F84 — Folded declaration collisions must identify the conflicting names + +**Observed:** A record named `TextModel` and a factory named `text-model` resolve +to the same Matrix identity. The compiler accepted both, then reported that the +record had no `content` field because its symbol described the function. + +**Fixed:** Matrix diagnoses the colliding spellings at the declaration, including +the earlier line. The shared checker rejects different declaration kinds with +the same module identity. Tests cover declaration order, visibility, Ny, and +valid extension/test names. The library factories are `create-text-model` and +`create-flag-model`. + +**Remaining friction:** Imported type names and page-local values can still +interact awkwardly with page-wide folding. UI code uses distinct names such as +`surface`, `control` and `notification`, and qualifies record constructions. +Type-position and value-position resolution deserve a separate namespace audit; +authors should never receive an unresolved generated variable for this case. + +### F85 — Pattern arms need an explicit boundary for nested conditionals + +**Observed:** Both a `consider` arm and an ordinary conditional begin with +`when`. Without a closing arm boundary, a conditional immediately inside an arm +was parsed as another pattern and produced misleading errors at `equals`. + +**Fixed:** Statement arms accept `then begin block ... end block`; the wildcard +can use `otherwise begin block ... end block`. Existing unbracketed arms remain +valid. The explicit form supports nested conditionals, loops and matches with +the same lexical scope and return behavior. `block` remains contextual. +`tests/matrix/consider_block_contract.py` checks nested control flow, guards, +scope, and missing boundaries on VM/native paths. + +### F86 — Nested generic applications and error propagation need clearer prose + +**Observed:** `Result of Option of Event, text` does not express a unique +application boundary: the inner `of` consumes the comma. The UI API uses the +named alias `PendingEvent` for `Option`, then `Result of PendingEvent, +text`. That is readable, but authors need an explicit grouping form for other +nested applications. + +Copying and checking a UI event also requires forwarding several Result errors. +The current `consider` form is explicit and safe but creates deeply nested code. +A future checked propagation form or compositional Result helpers could retain +the operation's diagnostic context while reducing this repetition. Neither +automatic unwrapping nor fallback values should hide failures. + +### F87 — Generic enum assignments must retain the checked destination type + +**Observed:** The UI event decoder assigned `Option.Some` to an existing +`Option` local. VM execution worked, but native compilation rejected the +constructor because its concrete enum schema was missing. Written local type +annotations retained short payload names, and assignment lowering did not pass +the checked destination type to the constructor. + +**Fixed:** Annotated bindings retain canonical checked types, and assignment +RHS lowering receives the destination context. Paired Ny/Matrix fixtures cover +local and record-field assignments of `Option`, with side effects +proving each payload is evaluated once. They run through textual/binary NIL, +bundles, LLVM JIT and AOT. This does not extend native global storage to enums. diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index e8fa1e31..35157f3c 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -53,6 +53,7 @@ add_library(nilruntime_objects OBJECT src/owned_runtime.cpp src/secure_file_io.cpp src/database_runtime.cpp + src/ui_runtime.cpp src/pattern_engine.cpp src/nildata.cpp ) diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index d8b36e39..ec2d3fcb 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -3649,7 +3649,7 @@ class emitter { if (reject_reference_dereference(*ue.operand, asn.line)) break; emit_expr(*ue.operand); // Pushes ptr - emit_expr(*asn.value); // Pushes value + emit_expr(*asn.value, asn.target->inferred_type); // Pushes value push_instr("WRITE_PTR", {}, asn.line); break; } @@ -3668,7 +3668,7 @@ class emitter { } push_instr("PTR_ADD", {}, asn.line); } - emit_expr(*asn.value); // Value + emit_expr(*asn.value, asn.target->inferred_type); // Value if (owned) emit_scalar_boundary(ie.inferred_type, asn.line); push_instr(owned ? "WRITE_PTR" : "SET_INDEX", {}, asn.line); break; @@ -3687,7 +3687,7 @@ class emitter { break; emit_expr(*ue.operand); // Push the POINTER address (not // dereferenced value) - emit_expr(*asn.value); // Push value + emit_expr(*asn.value, asn.target->inferred_type); // Push value emit_scalar_boundary(ma.inferred_type, asn.line); push_instr("SET_FIELD_PTR", {ma.member_name}, asn.line); break; @@ -3699,7 +3699,7 @@ class emitter { const auto &obj_id = static_cast(*ma.object); emit_member_receiver(*ma.object); // LOAD_LOCAL obj_id - emit_expr(*asn.value); // push value + emit_expr(*asn.value, asn.target->inferred_type); // push value emit_scalar_boundary(ma.inferred_type, asn.line); push_instr("SET_FIELD", {ma.member_name}, asn.line); push_instr("STORE_LOCAL", {obj_id.name}, asn.line); // write back @@ -3721,7 +3721,7 @@ class emitter { push_instr("LOAD_LOCAL", {root_id.name}, asn.line); push_instr("LOAD_LOCAL", {root_id.name}, asn.line); push_instr("GET_FIELD", {inner_ma.member_name}, asn.line); - emit_expr(*asn.value); + emit_expr(*asn.value, asn.target->inferred_type); emit_scalar_boundary(ma.inferred_type, asn.line); push_instr("SET_FIELD", {ma.member_name}, asn.line); push_instr("SET_FIELD", {inner_ma.member_name}, asn.line); @@ -3731,14 +3731,14 @@ class emitter { } // Fallback: emit as before, then discard leaked struct via temp store emit_member_receiver(*ma.object); // Push struct reference - emit_expr(*asn.value); // Push value + emit_expr(*asn.value, asn.target->inferred_type); // Push value emit_scalar_boundary(ma.inferred_type, asn.line); push_instr("SET_FIELD", {ma.member_name}, asn.line); push_instr("STORE_LOCAL", {new_temp("_sf_discard")}, asn.line); break; } - emit_expr(*asn.value); + emit_expr(*asn.value, asn.target->inferred_type); if (asn.target->kind == ast_node_kind::identifier_expr_node) { auto &id = static_cast(*asn.target); emit_scalar_boundary(id.inferred_type, asn.line); @@ -6880,7 +6880,8 @@ codegen::assemble_module(const ast_program &program, std::string ret_type_str = "void"; if (intrinsic_name.rfind("regex.", 0) == 0 || - intrinsic_name.rfind("nildata.", 0) == 0) { + intrinsic_name.rfind("nildata.", 0) == 0 || + intrinsic_name.rfind("ui.v1.", 0) == 0) { ret_type_str = canonical_nil_type_name(fn.return_type); } else if (is_declared_enum_type(*this, fn.return_type)) { ret_type_str = canonical_nil_type_name(fn.return_type); diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index dd594ca0..21e0db58 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -6,6 +6,7 @@ #include "owned_contract.hpp" #include "diagnostics.hpp" #include "dynamic_type.hpp" +#include "ui_intrinsic.hpp" #include "executable_context.hpp" #include "native_runtime.hpp" #include "owned_runtime.hpp" @@ -2757,7 +2758,72 @@ bool NativeCodegen::generateModule(const nil_module &mod) { ann.find("@intrinsic(io.console.error)") != std::string::npos || ann.find("@intrinsic(\"console.error\")") != std::string::npos || ann.find("@intrinsic(console.error)") != std::string::npos; - if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("db2.", 0) == 0) { + if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("ui.v1.", 0) == 0) { + const auto contract = ui::intrinsic(dispatch_provider); + if (!contract) { + std::cerr << "[NativeCodegen] unknown UI intrinsic '" << dispatch_provider << "'\n"; + return false; + } + std::vector parameter_types; + for (const auto ¶meter : fn.params) parameter_types.push_back(nil_parameter_type(parameter)); + bool valid = ui::signature_matches(*contract, parameter_types, fn.return_type) && + impl_->current_function->arg_size() == contract->parameters.size(); + for (std::size_t index = 0; valid && index < contract->parameters.size(); ++index) { + auto *actual = impl_->current_function->getArg(index)->getType(); + valid = contract->parameters[index] == "i64" ? actual->isIntegerTy(64) : actual->isPointerTy(); + } + const bool capability = contract->output == ui::Output::capability; + const bool text_result = contract->output == ui::Output::text; + valid = valid && (capability ? impl_->current_function->getReturnType()->isIntegerTy() + : impl_->current_function->getReturnType()->isIntegerTy(64)); + if (!capability) { + std::size_t schemas = 0; + for (const auto &definition : mod.enums) + if (ui::result_schema_matches(*contract, definition)) ++schemas; + valid = valid && schemas == 1; + } + if (!valid) { + std::cerr << "[NativeCodegen] " << dispatch_provider << " requires the exact UI ABI " + << ui::signature(*contract) << " and the standard Result schema\n"; + return false; + } + auto *word_type = llvm::Type::getInt64Ty(ctx); + auto *pointer_type = llvm::PointerType::getUnqual(ctx); + llvm::Type *payload_type = text_result ? static_cast(pointer_type) : word_type; + std::vector arguments; + for (auto &argument : impl_->current_function->args()) arguments.push_back(&argument); + llvm::AllocaInst *value_out = nullptr, *error_out = nullptr; + if (!capability) { + // Entry allocas and loaded payloads are published by native root + // instrumentation before any enum allocation can collect them. + value_out = impl_->builder->CreateAlloca(payload_type); + error_out = impl_->builder->CreateAlloca(pointer_type); + arguments.push_back(value_out); arguments.push_back(error_out); + } + std::vector types; + for (auto *argument : arguments) types.push_back(argument->getType()); + auto *runtime_type = llvm::FunctionType::get(capability ? word_type : llvm::Type::getInt32Ty(ctx), types, false); + auto runtime = impl_->module->getOrInsertFunction("nyrt_ui_v1_" + contract->operation, runtime_type); + auto *status = impl_->builder->CreateCall(runtime_type, runtime.getCallee(), arguments); + if (capability) { + impl_->builder->CreateRet(impl_->builder->CreateIntCast(status, impl_->current_function->getReturnType(), false)); + } else { + auto *success = llvm::BasicBlock::Create(ctx, "ui.success", impl_->current_function); + auto *failure = llvm::BasicBlock::Create(ctx, "ui.failure", impl_->current_function); + impl_->builder->CreateCondBr(impl_->builder->CreateICmpNE(status, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0)), success, failure); + impl_->builder->SetInsertPoint(success); + auto *value = impl_->builder->CreateLoad(payload_type, value_out); + auto *ok = emit_single_payload_variant("Result::Ok", value, fn.return_type, text_result ? "text" : "i64"); + if (!ok) return false; + impl_->builder->CreateRet(ok); + impl_->builder->SetInsertPoint(failure); + auto *error = impl_->builder->CreateLoad(pointer_type, error_out); + auto *failed = emit_single_payload_variant("Result::Error", error, fn.return_type, "text"); + if (!failed) return false; + impl_->builder->CreateRet(failed); + } + annotation_handled = true; + } else if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("db2.", 0) == 0) { std::vector expected; bool capability = false, text_result = false; int operation = 0; @@ -8828,6 +8894,20 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { llvm::orc::ExecutorSymbolDef(llvm::orc::ExecutorAddr::fromPtr(address), llvm::JITSymbolFlags::Exported); }; + expose_runtime_symbol("nyrt_ui_v1_available", &nyrt_ui_v1_available); + expose_runtime_symbol("nyrt_ui_v1_window", &nyrt_ui_v1_window); + expose_runtime_symbol("nyrt_ui_v1_widget", &nyrt_ui_v1_widget); + expose_runtime_symbol("nyrt_ui_v1_grid_attach", &nyrt_ui_v1_grid_attach); + expose_runtime_symbol("nyrt_ui_v1_set_text", &nyrt_ui_v1_set_text); + expose_runtime_symbol("nyrt_ui_v1_read_text", &nyrt_ui_v1_read_text); + expose_runtime_symbol("nyrt_ui_v1_set_number", &nyrt_ui_v1_set_number); + expose_runtime_symbol("nyrt_ui_v1_read_number", &nyrt_ui_v1_read_number); + expose_runtime_symbol("nyrt_ui_v1_activate", &nyrt_ui_v1_activate); + expose_runtime_symbol("nyrt_ui_v1_poll", &nyrt_ui_v1_poll); + expose_runtime_symbol("nyrt_ui_v1_event_number", &nyrt_ui_v1_event_number); + expose_runtime_symbol("nyrt_ui_v1_event_text", &nyrt_ui_v1_event_text); + expose_runtime_symbol("nyrt_ui_v1_release_event", &nyrt_ui_v1_release_event); + expose_runtime_symbol("nyrt_ui_v1_close", &nyrt_ui_v1_close); expose_runtime_symbol("nyrt_db2_available", &nyrt_db2_available); expose_runtime_symbol("nyrt_db2_open", &nyrt_db2_open); expose_runtime_symbol("nyrt_db2_execute", &nyrt_db2_execute); diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 21a801e9..c697c578 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -345,6 +345,14 @@ void parser::reject_type_name_collision(const token &at, "them (for example '" + written + "-value')"); } +void parser::register_declaration_name(const token &name) { + const auto [previous, inserted] = parsed_declarations_.emplace(name.key, name); + if (!inserted) + error(name, "declaration '" + name.lexeme + "' conflicts with '" + previous->second.lexeme + + "' declared on line " + std::to_string(previous->second.line), + "Matrix names fold case and separators, so these are one name; rename one declaration"); +} + std::string parser::resolve_name(const std::string &written) const { // A QUALIFIED name is a path: its dots normalise to '::', because Ny's // module declaration does the same and NIL identity uses '::'. A book-local @@ -1403,6 +1411,7 @@ std::shared_ptr parser::parse_declaration() { } if (check(kw::begin) && peek(1).is(kw::record)) { + register_declaration_name(name_token); // A record carries its annotations into the artifact now, so a 'context' // written above one is kept rather than refused. The other declaration // kinds below still refuse, because textual NIL has nowhere to put theirs @@ -1412,11 +1421,13 @@ std::shared_ptr parser::parse_declaration() { return named(record, name_token); } if (check(kw::begin) && peek(1).is(kw::choice)) { + register_declaration_name(name_token); auto choice = parse_choice(is_public, line, name, std::move(generics)); if (choice) choice->annotations = std::move(annotations); return named(choice, name_token); } if (check(kw::begin) && peek(1).is(kw::contract)) { + register_declaration_name(name_token); refuse_annotations("a contract"); return named(parse_contract(is_public, line, name, std::move(generics)), name_token); } @@ -1426,6 +1437,7 @@ std::shared_ptr parser::parse_declaration() { return named(test, name_token); } if (check(kw::inherits) || (check(kw::begin) && peek(1).is(kw::class_))) { + register_declaration_name(name_token); auto klass = parse_class(is_public, is_abstract, line, name, std::move(generics)); if (klass) klass->annotations = std::move(annotations); return named(klass, name_token); @@ -1459,6 +1471,7 @@ std::shared_ptr parser::parse_declaration() { } if (match(kw::means)) { + register_declaration_name(name_token); refuse_annotations("a type alias"); auto target = parse_type(); skip_terminators(); @@ -1483,6 +1496,7 @@ std::shared_ptr parser::parse_declaration() { // A declaration carrying 'note intrinsic' has no body: the named runtime // provider is the implementation. + register_declaration_name(name_token); bool intrinsic_backed = false; for (const auto &annotation : annotations) if (annotation.name == "intrinsic") intrinsic_backed = true; @@ -3550,6 +3564,34 @@ std::shared_ptr parser::parse_consider_statement() { advance(); // 'consider' auto target = parse_expression(); + // An explicit arm boundary permits ordinary `when` statements inside a + // match arm without confusing them with the next pattern. `block` remains + // a contextual word, so this does not reserve existing identifiers. + const auto arm_body = [&](bool wildcard) { + skip_terminators(); + const bool explicit_block = check(kw::begin) && exact_phrase_word(peek(1), "block"); + if (explicit_block) { advance(); advance(); } + auto body = std::make_shared(peek().line); + for (;;) { + skip_terminators(); + if (explicit_block && check(kw::end) && exact_phrase_word(peek(1), "block")) { + advance(); advance(); skip_terminators(); + break; + } + if (at_end() || (check(kw::end) && peek(1).is(kw::consider))) { + if (explicit_block) + error(peek(), "expected 'end block' before closing the 'consider' arm", + "close 'then begin block' with 'end block' before the next arm or 'end consider'"); + break; + } + if (!explicit_block && !wildcard && (check(kw::when) || check(kw::otherwise))) break; + const size_t before = pos_; + if (auto stmt = parse_statement()) body->statements.push_back(stmt); + if (pos_ == before) advance(); + } + return body; + }; + std::vector arms; for (;;) { skip_terminators(); @@ -3563,15 +3605,8 @@ std::shared_ptr parser::parse_consider_statement() { } if (match(kw::otherwise)) { - // The wildcard arm. Its body runs to 'end consider'. - auto body = std::make_shared(peek().line); - for (;;) { - skip_terminators(); - if (at_end() || (check(kw::end) && peek(1).is(kw::consider))) break; - const size_t before = pos_; - if (auto stmt = parse_statement()) body->statements.push_back(stmt); - if (pos_ == before) advance(); - } + // Unbracketed wildcard bodies retain their existing end-consider boundary. + auto body = arm_body(true); ny::ast_pattern wildcard; wildcard.kind = ny::ast_pattern_kind::wildcard_pattern; wildcard.name = "_"; @@ -3591,17 +3626,7 @@ std::shared_ptr parser::parse_consider_statement() { if (match(kw::provided)) guard = parse_expression(); if (!expect(kw::then, "after a 'consider' arm pattern")) continue; - // An arm body runs until the next arm, the wildcard, or the terminator. - auto body = std::make_shared(peek().line); - for (;;) { - skip_terminators(); - if (at_end()) break; - if (check(kw::when) || check(kw::otherwise)) break; - if (check(kw::end) && peek(1).is(kw::consider)) break; - const size_t before = pos_; - if (auto stmt = parse_statement()) body->statements.push_back(stmt); - if (pos_ == before) advance(); - } + auto body = arm_body(false); arms.emplace_back(std::move(pattern), body, guard); } return std::make_shared(target, std::move(arms), line); diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index d71173f0..78327e45 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -119,6 +119,11 @@ class parser { // surfaces much later as a method call with no receiver. std::unordered_map declared_types_; + // Only actual module-level definitions participate. Implementations refer + // to an existing type and test names are metadata, not new symbols. + std::unordered_map parsed_declarations_; + void register_declaration_name(const token &name); + // Diagnose a value name that collides with a declared type name. void reject_type_name_collision(const token &at, const std::string &written); diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index a469780b..fc5fb06a 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1,6 +1,7 @@ #include "native_runtime.hpp" #include "dynamic_type.hpp" #include "database_runtime.hpp" +#include "ui_runtime.hpp" #include "integer_conversion.hpp" #include "memory_profile.hpp" #include "pattern_engine.hpp" @@ -80,6 +81,7 @@ struct nyrt_any_box { struct runtime_context { ny::memory_profile::Session profile; ny::database::Context databases; + ny::ui::Context ui; struct allocation { void *data; std::size_t size; @@ -588,8 +590,99 @@ const char *integer_to_text(Integer value) noexcept { } // namespace +namespace { +template +std::int32_t ui_number_result(std::int64_t *value, const char **error, + Invoke invoke) noexcept { + if (!value || !error) return 0; + *value = 0; *error = nullptr; + try { + auto result = invoke(); + if (!result) { set_error(error, result.error); return 0; } + *value = result.number; + return 1; + } catch (const std::invalid_argument &invalid) { set_error(error, invalid.what()); return 0; } + catch (...) { *error = "ui: host allocation failed"; return 0; } +} +template +std::int32_t ui_text_result(const char **value, const char **error, + Invoke invoke) noexcept { + if (!value || !error) return 0; + *value = nullptr; *error = nullptr; + try { + auto result = invoke(); + if (!result) { set_error(error, result.error); return 0; } + // The snapshot may be released immediately after this call. Never return + // provider storage, even when its lifetime presently spans the caller. + *value = own_string(result.text); + if (!*value) { *error = "ui: host allocation failed"; return 0; } + return 1; + } catch (const std::invalid_argument &invalid) { set_error(error, invalid.what()); return 0; } + catch (...) { *error = "ui: host allocation failed"; return 0; } +} +const char *ui_text_argument(const char *text) { + if (!text) throw std::invalid_argument("ui: expected text argument"); + return text; +} +} // namespace + extern "C" { +std::int64_t nyrt_ui_v1_available() noexcept { return ny::ui::available() ? 1 : 0; } +std::int32_t nyrt_ui_v1_window(const char *title, std::int64_t width, std::int64_t height, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.window(ui_text_argument(title), width, height); }); +} +std::int32_t nyrt_ui_v1_widget(const char *kind, std::int64_t parent, const char *label, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.widget(ui_text_argument(kind), parent, ui_text_argument(label)); }); +} +std::int32_t nyrt_ui_v1_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, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.grid_attach(grid, child, column, row, column_span, row_span); }); +} +std::int32_t nyrt_ui_v1_set_text(std::int64_t handle, const char *text, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.set_text(handle, ui_text_argument(text)); }); +} +std::int32_t nyrt_ui_v1_read_text(std::int64_t handle, + const char **value, const char **error) noexcept { + return ui_text_result(value, error, [&] { return context.ui.read_text(handle); }); +} +std::int32_t nyrt_ui_v1_set_number(std::int64_t handle, const char *property, std::int64_t number, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.set_number(handle, ui_text_argument(property), number); }); +} +std::int32_t nyrt_ui_v1_read_number(std::int64_t handle, const char *property, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.read_number(handle, ui_text_argument(property)); }); +} +std::int32_t nyrt_ui_v1_activate(std::int64_t handle, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.activate(handle); }); +} +std::int32_t nyrt_ui_v1_poll(std::int64_t window, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.poll(window); }); +} +std::int32_t nyrt_ui_v1_event_number(std::int64_t snapshot, const char *field, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.event_number(snapshot, ui_text_argument(field)); }); +} +std::int32_t nyrt_ui_v1_event_text(std::int64_t snapshot, + const char **value, const char **error) noexcept { + return ui_text_result(value, error, [&] { return context.ui.event_text(snapshot); }); +} +std::int32_t nyrt_ui_v1_release_event(std::int64_t snapshot, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.release_event(snapshot); }); +} +std::int32_t nyrt_ui_v1_close(std::int64_t window, + std::int64_t *value, const char **error) noexcept { + return ui_number_result(value, error, [&] { return context.ui.close(window); }); +} + + std::int64_t nyrt_db2_available(const char *driver) noexcept { try { return driver && ny::database::available(driver) ? 1 : 0; } @@ -745,6 +838,7 @@ void nyrt_context_end() noexcept { if (!context.profile.finish()) nyrt_fail("NIL native runtime error: memory capture failed\n"); context.databases.clear(); + context.ui.clear(); nyrt_owned_v1_unwind(0); context.pending_fault.reset(); std::vector().swap(context.fault_frames); @@ -765,6 +859,7 @@ void nyrt_profile_site(const char *file, const char *function, } [[noreturn]] void nyrt_fail(const char *message) noexcept { + context.ui.clear(); (void)context.profile.finish("failed", false); if (message != nullptr) std::fputs(message, stderr); diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 23d1f911..3ca0d934 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -21,6 +21,36 @@ enum nyrt_array_kind : std::uint32_t { NYRT_ARRAY_ANYTHING = 8, }; +// Versioned UI ABI. Success is 1, failure 0. Text outputs are copied into +// managed context storage; toolkit pointers never cross this boundary. +std::int64_t nyrt_ui_v1_available() noexcept; +std::int32_t nyrt_ui_v1_window(const char *title, std::int64_t width, std::int64_t height, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_widget(const char *kind, std::int64_t parent, const char *label, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_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, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_set_text(std::int64_t handle, const char *text, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_read_text(std::int64_t handle, + const char **value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_set_number(std::int64_t handle, const char *property, std::int64_t number, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_read_number(std::int64_t handle, const char *property, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_activate(std::int64_t handle, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_poll(std::int64_t window, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_event_number(std::int64_t snapshot, const char *field, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_event_text(std::int64_t snapshot, + const char **value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_release_event(std::int64_t snapshot, + std::int64_t *value, const char **error) noexcept; +std::int32_t nyrt_ui_v1_close(std::int64_t window, + std::int64_t *value, const char **error) noexcept; + // Additive database ABI. Success is 1, failure 0; outputs are context-owned. std::int64_t nyrt_db2_available(const char *driver) noexcept; std::int32_t nyrt_db2_open(const char *driver, const char *address, diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 6196662b..58900c07 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -6,6 +6,7 @@ #include "type_checker.hpp" #include "diagnostics.hpp" #include "dynamic_type.hpp" +#include "ui_intrinsic.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" @@ -2656,6 +2657,41 @@ void type_checker::visit(ast_program &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, declaration->source_file); check_test_target(*declaration); } + // A value/function cannot replace a nominal type's symbol. Otherwise + // module-member preregistration can erase a record's fields before any body + // is checked. Repeated imports of the same kind remain harmless here. + std::unordered_map declaration_owners; + std::string declaration_module; + bool declaration_conflict = false; + for (const auto &declaration : p.declarations) { + if (!declaration) continue; + if (declaration->kind == ast_node_kind::module_decl_node) { + declaration_module = static_cast(*declaration).name; + continue; + } + std::string name; + switch (declaration->kind) { + case ast_node_kind::function_decl_node: name = static_cast(*declaration).name; break; + case ast_node_kind::variable_decl_node: name = static_cast(*declaration).name; break; + case ast_node_kind::struct_decl_node: name = static_cast(*declaration).name; break; + case ast_node_kind::class_decl_node: name = static_cast(*declaration).name; break; + case ast_node_kind::enum_decl_node: name = static_cast(*declaration).name; break; + case ast_node_kind::trait_decl_node: name = static_cast(*declaration).name; break; + case ast_node_kind::type_alias_decl_node: name = static_cast(*declaration).name; break; + default: continue; + } + const auto qualified = declaration_module.empty() ? name : declaration_module + "::" + name; + const auto [previous, inserted] = declaration_owners.emplace(qualified, declaration.get()); + if (!inserted && previous->second->kind != declaration->kind) { + diagnostic_source_scope source_scope(diagnostic_source_file_, declaration->source_file); + add_error(declaration->line, "Declaration '" + qualified + + "' conflicts with another declaration kind on line " + std::to_string(previous->second->line) + + "; types, functions, and values in one module must have distinct names"); + declaration_conflict = true; + } + } + if (declaration_conflict) return; + // Keep declared module identities independently of symbol registration // order. Never select a global merely because its suffix matches a name. std::string global_module; @@ -3179,6 +3215,41 @@ void type_checker::visit(ast_function_decl &p) { current_function_return_type_ = type_void; } + for (const auto &annotation : p.annotations) { + if (!annotation.has_name("intrinsic")) continue; + const auto parsed = parse_annotation_arguments(annotation.args.value_or("")); + const auto &arguments = annotation.typed_arguments ? *annotation.typed_arguments : parsed.arguments; + if (arguments.size() != 1 || arguments.front().name || arguments.front().kind != "text") continue; + const auto &provider = arguments.front().value; + if (provider.rfind("ui.v1.", 0) != 0) continue; + const auto contract = ui::intrinsic(provider); + if (!contract) { + add_error(p.line, "Unknown UI intrinsic '" + provider + "'"); + continue; + } + // Core Result may remain a short built-in name after ordinary import + // resolution. Prove its declaration owner before qualifying the ABI; + // never accept an unrelated user enum merely because its leaf is Result. + if (contract->output != ui::Output::capability && p.return_type) { + const auto parts = parse_generic_type_string(*p.return_type); + const auto *owner = resolve_pattern_type_symbol(parts.base_name); + if (owner && canonical_std_namespace(owner->name) == "nil::std::core::Result" && + parts.type_args.size() == 2) { + p.return_type = "nil::std::core::Result<" + parts.type_args[0] + "," + parts.type_args[1] + ">"; + current_function_return_type_ = type_info{*p.return_type, true}; + } + } + std::vector parameters; + bool ordinary = !current_class_name_ && p.generic_params.empty(); + for (const auto ¶meter : p.params) { + parameters.push_back(parameter.type_name.value_or("")); + ordinary = ordinary && !parameter.is_ref && !parameter.is_variadic && !parameter.default_value; + } + if (!ordinary || !ui::signature_matches(*contract, parameters, p.return_type.value_or("void"))) + add_error(p.line, provider + " requires the exact UI ABI " + ui::signature(*contract) + + "; use a module-level, non-generic function without reference, variadic, or default parameters and import nil.std.core.result"); + } + if (p.body) { p.body->accept(*this); } @@ -3333,6 +3404,12 @@ void type_checker::visit(ast_variable_decl &p) { type == "bool" || type == "f64"; }; const auto canonical_variable_type = resolve_type(var_type_name).name; + // Lowering must see the same nominal identities as the checked binding. + // Keeping a written Option here while the symbol holds a qualified + // Widget lets its initializer materialize a different generic enum schema. + if (p.type_name && canonical_variable_type != "any" && + !canonical_variable_type.empty() && canonical_variable_type.front() != '<') + p.type_name = canonical_variable_type; if (contains_ownership_type(canonical_variable_type)) p.type_name = canonical_variable_type; if (scalar_type(canonical_variable_type) || canonical_variable_type == "anything") { diff --git a/nilcompiler/src/ui_intrinsic.hpp b/nilcompiler/src/ui_intrinsic.hpp new file mode 100644 index 00000000..13776945 --- /dev/null +++ b/nilcompiler/src/ui_intrinsic.hpp @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#pragma once + +#include "dynamic_type.hpp" +#include "standard_namespace.hpp" +#include +#include +#include + +namespace ny::ui { +enum class Output { capability, number, text }; +struct Intrinsic { + std::string operation; + std::vector parameters; + Output output = Output::number; + + std::string return_type() const { + if (output == Output::capability) return "bool"; + return std::string("nil::std::core::Result<") + + (output == Output::text ? "text" : "i64") + ",text>"; + } +}; + +inline std::optional intrinsic(const std::string &name) { + if (name.rfind("ui.v1.", 0) != 0) return std::nullopt; + Intrinsic value; + value.operation = name.substr(6); + const auto &op = value.operation; + if (op == "available") value.output = Output::capability; + else if (op == "window") value.parameters = {"text", "i64", "i64"}; + else if (op == "widget") value.parameters = {"text", "i64", "text"}; + else if (op == "grid_attach") value.parameters = {"i64", "i64", "i64", "i64", "i64", "i64"}; + else if (op == "set_text" || op == "read_number" || op == "event_number") + value.parameters = {"i64", "text"}; + else if (op == "set_number") value.parameters = {"i64", "text", "i64"}; + else if (op == "read_text" || op == "event_text") { + value.parameters = {"i64"}; value.output = Output::text; + } else if (op == "activate" || op == "poll" || op == "release_event" || op == "close") + value.parameters = {"i64"}; + else return std::nullopt; + return value; +} + +// Preserve nominal ownership: an unrelated enum named Result is not this ABI. +// Source aliases have already resolved before this check; legacy standard +// namespace aliases remain accepted in loaded NIL. +inline std::string abi_type(const std::string &type) { + return canonical_std_namespace(canonical_dynamic_type(type)); +} + +inline bool signature_matches(const Intrinsic &intrinsic, + const std::vector ¶meters, + const std::string &result) { + if (parameters.size() != intrinsic.parameters.size() || + abi_type(result) != intrinsic.return_type()) return false; + for (std::size_t index = 0; index < parameters.size(); ++index) + if (abi_type(parameters[index]) != intrinsic.parameters[index]) return false; + return true; +} + +template +inline bool result_schema_matches(const Intrinsic &intrinsic, + const EnumDefinition &definition) { + if (abi_type(definition.name) != intrinsic.return_type() || + definition.variants.size() != 2) return false; + bool ok = false, error = false; + for (const auto &variant : definition.variants) { + if (variant.name == "Ok") + ok = abi_type(variant.associated_type) == + (intrinsic.output == Output::text ? "text" : "i64"); + else if (variant.name == "Error") error = abi_type(variant.associated_type) == "text"; + else return false; + } + return ok && error; +} + +inline std::string signature(const Intrinsic &intrinsic) { + std::string value = "("; + for (std::size_t index = 0; index < intrinsic.parameters.size(); ++index) { + if (index) value += ", "; + value += intrinsic.parameters[index]; + } + return value + ") -> " + intrinsic.return_type(); +} +} // namespace ny::ui diff --git a/nilcompiler/src/ui_runtime.cpp b/nilcompiler/src/ui_runtime.cpp new file mode 100644 index 00000000..2a16b4a6 --- /dev/null +++ b/nilcompiler/src/ui_runtime.cpp @@ -0,0 +1,623 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#include "ui_runtime.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__linux__) +#include +#endif + +namespace ny::ui { +namespace { +// This optional loader uses only GTK 4's public opaque-pointer C ABI. It does +// not reproduce toolkit object layouts or depend on the legacy generic FFI. +struct GtkWidget; struct GtkWindow; struct GtkBox; struct GtkGrid; +struct GtkLabel; struct GtkButton; struct GtkEditable; struct GtkCheckButton; struct GtkEntry; +struct GObject; struct GClosure; struct GMainContext; +enum GtkOrientation { horizontal = 0, vertical = 1 }; +using Callback = void (*)(); +using ClosureNotify = void (*)(void *, GClosure *); +enum ConnectFlags { connect_default = 0 }; + +struct Api { + bool loaded = false; + std::mutex thread_mutex; + bool initialized = false; + std::thread::id ui_thread; +#define UI_SYMBOLS(X) \ + X(int, gtk_init_check, ()) \ + X(unsigned, gtk_get_major_version, ()) \ + X(GtkWidget *, gtk_window_new, ()) \ + X(void, gtk_window_set_title, (GtkWindow *, const char *)) \ + X(void, gtk_window_set_default_size, (GtkWindow *, int, int)) \ + X(void, gtk_window_set_child, (GtkWindow *, GtkWidget *)) \ + X(void, gtk_window_present, (GtkWindow *)) \ + X(void, gtk_window_destroy, (GtkWindow *)) \ + X(GtkWidget *, gtk_box_new, (GtkOrientation, int)) \ + X(void, gtk_box_append, (GtkBox *, GtkWidget *)) \ + X(void, gtk_box_set_spacing, (GtkBox *, int)) \ + X(GtkWidget *, gtk_grid_new, ()) \ + X(void, gtk_grid_attach, (GtkGrid *, GtkWidget *, int, int, int, int)) \ + X(void, gtk_grid_remove, (GtkGrid *, GtkWidget *)) \ + X(void, gtk_grid_set_row_spacing, (GtkGrid *, unsigned)) \ + X(void, gtk_grid_set_column_spacing, (GtkGrid *, unsigned)) \ + X(GtkWidget *, gtk_label_new, (const char *)) \ + X(void, gtk_label_set_text, (GtkLabel *, const char *)) \ + X(GtkWidget *, gtk_button_new_with_label, (const char *)) \ + X(void, gtk_button_set_label, (GtkButton *, const char *)) \ + X(GtkWidget *, gtk_entry_new, ()) \ + X(void, gtk_entry_set_max_length, (GtkEntry *, int)) \ + X(const char *, gtk_editable_get_text, (GtkEditable *)) \ + X(void, gtk_editable_set_text, (GtkEditable *, const char *)) \ + X(GtkWidget *, gtk_check_button_new_with_label, (const char *)) \ + X(int, gtk_check_button_get_active, (GtkCheckButton *)) \ + X(void, gtk_check_button_set_active, (GtkCheckButton *, int)) \ + X(void, gtk_check_button_set_label, (GtkCheckButton *, const char *)) \ + X(int, gtk_widget_activate, (GtkWidget *)) \ + X(void, gtk_widget_set_visible, (GtkWidget *, int)) \ + X(int, gtk_widget_get_visible, (GtkWidget *)) \ + X(void, gtk_widget_set_sensitive, (GtkWidget *, int)) \ + X(int, gtk_widget_get_sensitive, (GtkWidget *)) \ + X(int, gtk_widget_is_sensitive, (GtkWidget *)) \ + X(int, gtk_widget_grab_focus, (GtkWidget *)) \ + X(int, gtk_widget_has_focus, (GtkWidget *)) \ + X(void, gtk_widget_set_hexpand, (GtkWidget *, int)) \ + X(void, gtk_widget_set_vexpand, (GtkWidget *, int)) \ + X(void, gtk_widget_set_margin_start, (GtkWidget *, int)) \ + X(void, gtk_widget_set_margin_end, (GtkWidget *, int)) \ + X(void, gtk_widget_set_margin_top, (GtkWidget *, int)) \ + X(void, gtk_widget_set_margin_bottom, (GtkWidget *, int)) \ + X(int, gtk_widget_get_width, (GtkWidget *)) \ + X(int, gtk_widget_get_height, (GtkWidget *)) \ + X(int, gtk_widget_get_realized, (GtkWidget *)) \ + X(unsigned long, g_signal_connect_data, (void *, const char *, Callback, void *, ClosureNotify, ConnectFlags)) \ + X(void, g_signal_handler_disconnect, (void *, unsigned long)) \ + X(void *, g_object_ref, (void *)) \ + X(void *, g_object_ref_sink, (void *)) \ + X(void, g_object_unref, (void *)) \ + X(int, g_main_context_iteration, (GMainContext *, int)) +#define DECLARE_SYMBOL(result, name, arguments) result (*name) arguments = nullptr; + UI_SYMBOLS(DECLARE_SYMBOL) +#undef DECLARE_SYMBOL + Api() noexcept { +#if defined(__linux__) + // Keep these libraries loaded: GTK owns process-wide types, callbacks and + // caches which must not outlive their code. No display is opened here. + void *gtk = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); + void *object = dlopen("libgobject-2.0.so.0", RTLD_NOW | RTLD_LOCAL); + void *glib = dlopen("libglib-2.0.so.0", RTLD_NOW | RTLD_LOCAL); + if (!gtk || !object || !glib) return; +#define LOAD_SYMBOL(result, name, arguments) \ + name = reinterpret_cast(dlsym(gtk, #name)); \ + if (!name) name = reinterpret_cast(dlsym(object, #name)); \ + if (!name) name = reinterpret_cast(dlsym(glib, #name)); \ + if (!name) return; + UI_SYMBOLS(LOAD_SYMBOL) +#undef LOAD_SYMBOL + loaded = gtk_get_major_version() == 4; +#endif + } +#undef UI_SYMBOLS +}; + +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 { + struct Node { + Kind kind; + GtkWidget *object = nullptr; + GtkWidget *root = nullptr; // Window's auto-column, owned by GTK's parent tree. + std::int64_t parent = 0, window = 0; + std::string text; + std::map properties; + std::vector signals; + Placement placement; + unsigned suppress = 0; + }; + struct SignalData { std::weak_ptr context; std::int64_t handle; std::int64_t kind; }; + std::thread::id owner = std::this_thread::get_id(); + std::map nodes; + std::deque events; + std::map snapshots; + std::size_t event_bytes = 0, snapshot_bytes = 0; + std::size_t text_bytes = 0; + bool event_failure = false; + std::atomic active{true}; + + // Deferred teardown keeps GTK calls on its UI thread even when an embedding + // host destroys a Context elsewhere. Each callback also holds only a weak + // context reference, so no callback can dereference a destroyed Context. + 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 &a = api(); + bool initialized; + { + std::lock_guard lock(a.thread_mutex); + if (a.initialized && a.ui_thread != std::this_thread::get_id()) + return failure("GTK must be used on the process UI thread"); + initialized = a.initialized; + } + if (initialized) drain(); + return success(); + } + Result initialize() { + if (auto result = check(); !result) return result; + auto &a = api(); + if (!a.loaded) return failure("GTK 4 provider is unavailable; install the GTK 4 runtime"); + std::lock_guard lock(a.thread_mutex); + // A different context may have initialized GTK between check() and this + // lock. Never allow that race to create a widget on the losing thread. + if (a.initialized) { + if (a.ui_thread != std::this_thread::get_id()) + return failure("GTK must be used on the process UI thread"); + return success(); + } + if (!a.gtk_init_check()) return failure("GTK could not open a display; a working Wayland or X11 session is required"); + a.ui_thread = std::this_thread::get_id(); + a.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"); } + static void destroy_signal(void *raw, GClosure *) noexcept { delete static_cast(raw); } + static void notify(void *, void *raw) noexcept { + auto *data = static_cast(raw); + if (auto context = data->context.lock(); context && context->active.load()) context->enqueue(data->handle, data->kind); + } + static int close_requested(GtkWindow *, void *raw) noexcept { + notify(nullptr, raw); + // Matrix decides when to close. GTK must not destroy a still-live handle. + return 1; + } + void connect(std::int64_t handle, const char *name, std::int64_t kind, bool closing = false) { + auto &node = nodes.at(handle); + auto data = std::make_unique(SignalData{weak_from_this(), handle, kind}); + // Reserve before GTK takes ownership, so allocation failure cannot leave an + // untracked live signal attached to a widget being rolled back. + node.signals.reserve(node.signals.size() + 1); + auto callback = closing ? reinterpret_cast(&close_requested) : reinterpret_cast(¬ify); + auto signal = api().g_signal_connect_data(node.object, name, callback, data.get(), &destroy_signal, connect_default); + data.release(); + node.signals.push_back(signal); + } + void enqueue(std::int64_t handle, std::int64_t kind) noexcept { + try { + auto *node = find(handle); + if (!node || node->suppress) return; + Event event{kind, handle, node->window, 0, {}}; + if (kind == 2) { + const char *value = api().gtk_editable_get_text(reinterpret_cast(node->object)); + if (!value) { event_failure = true; return; } + event.text = value; + if (!valid_text(event.text)) { event_failure = true; return; } + } else if (kind == 3) + event.checked = api().gtk_check_button_get_active(reinterpret_cast(node->object)) ? 1 : 0; + if (events.size() >= max_events || event.text.size() > max_event_text_bytes - event_bytes) { + event_failure = true; return; + } + events.push_back(std::move(event)); + event_bytes += events.back().text.size(); + } catch (...) { event_failure = true; } + } + void disconnect(Node &node) noexcept { + for (auto signal : node.signals) api().g_signal_handler_disconnect(node.object, signal); + node.signals.clear(); + } + void dispose() noexcept { + active.store(false); + // Normal VM/native invocations also clear their unused UI context. Keep + // the optional toolkit completely unloaded until a UI operation needs it. + if (!nodes.empty()) { + auto &a = api(); + for (auto &[id, node] : nodes) disconnect(node); + for (auto &[id, node] : nodes) if (node.kind == Kind::window) + a.gtk_window_destroy(reinterpret_cast(node.object)); + for (auto &[id, node] : nodes) a.g_object_unref(node.object); + } + nodes.clear(); events.clear(); snapshots.clear(); event_bytes = snapshot_bytes = text_bytes = 0; + } +}; + +bool available() noexcept { try { return api().loaded; } catch (...) { return false; } } +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 (...) { /* Callbacks retain weak references; an OOM may leak GTK objects but cannot use freed context data. */ } + } + 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 || 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}}; + auto &a = api(); + node.object = a.gtk_window_new(); + if (!node.object) return failure("GTK could not create a window"); + a.g_object_ref(node.object); // gtk_window_new returns GTK's reference. + try { + node.root = a.gtk_box_new(vertical, 0); + if (!node.root) throw std::runtime_error("GTK could not create the root layout"); + a.gtk_window_set_child(reinterpret_cast(node.object), node.root); + a.gtk_window_set_title(reinterpret_cast(node.object), title.c_str()); + a.gtk_window_set_default_size(reinterpret_cast(node.object), static_cast(width), static_cast(height)); + impl_->nodes.emplace(handle, std::move(node)); + impl_->connect(handle, "close-request", 4, true); + impl_->text_bytes += title.size(); + } catch (...) { + auto found = impl_->nodes.find(handle); + GtkWidget *object = found == impl_->nodes.end() ? node.object : found->second.object; + if (found != impl_->nodes.end()) { impl_->disconnect(found->second); impl_->nodes.erase(found); } + a.gtk_window_destroy(reinterpret_cast(object)); a.g_object_unref(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; + auto &a = api(); + if (kind == "column" || kind == "row") { + node.kind = kind == "column" ? Kind::column : Kind::row; + node.object = a.gtk_box_new(kind == "column" ? vertical : horizontal, 0); + } else if (kind == "grid") { node.kind = Kind::grid; node.object = a.gtk_grid_new(); } + else if (kind == "label") { node.kind = Kind::label; node.object = a.gtk_label_new(label.c_str()); } + else if (kind == "button") { node.kind = Kind::button; node.object = a.gtk_button_new_with_label(label.c_str()); } + else if (kind == "entry") { node.kind = Kind::entry; node.object = a.gtk_entry_new(); } + else if (kind == "checkbox") { node.kind = Kind::checkbox; node.object = a.gtk_check_button_new_with_label(label.c_str()); } + else return failure("widget kind must be column, row, grid, label, button, entry, or checkbox"); + if (!node.object) return failure("GTK could not create the widget"); + a.g_object_ref_sink(node.object); + const auto handle = fresh_handle(); + if (!handle) { a.g_object_unref(node.object); return failure("handle space exhausted"); } + try { + if (node.kind == Kind::entry) { + a.gtk_entry_set_max_length(reinterpret_cast(node.object), static_cast(max_entry_characters)); + a.gtk_editable_set_text(reinterpret_cast(node.object), label.c_str()); + } + if (owner->kind == Kind::grid) { + for (const auto &[id, sibling] : impl_->nodes) if (sibling.parent == parent) + node.placement.row = std::max(node.placement.row, sibling.placement.row + sibling.placement.rows); + if (node.placement.row > 65535) { a.g_object_unref(node.object); return failure("grid row limit exceeded"); } + } + impl_->nodes.emplace(handle, std::move(node)); + auto &stored = impl_->nodes.at(handle); + if (stored.kind == Kind::button) impl_->connect(handle, "clicked", 1); + if (stored.kind == Kind::entry) impl_->connect(handle, "changed", 2); + if (stored.kind == Kind::checkbox) impl_->connect(handle, "toggled", 3); + if (owner->kind == Kind::grid) + a.gtk_grid_attach(reinterpret_cast(owner->object), stored.object, 0, static_cast(stored.placement.row), 1, 1); + else a.gtk_box_append(reinterpret_cast(owner->kind == Kind::window ? owner->root : owner->object), stored.object); + impl_->text_bytes += label.size(); + } catch (...) { + auto found = impl_->nodes.find(handle); + if (found != impl_->nodes.end()) { impl_->disconnect(found->second); a.g_object_unref(found->second.object); impl_->nodes.erase(found); } + else a.g_object_unref(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"); + auto &a = api(); + a.gtk_grid_remove(reinterpret_cast(parent->object), node->object); + a.gtk_grid_attach(reinterpret_cast(parent->object), node->object, + static_cast(column), static_cast(row), static_cast(column_span), static_cast(row_span)); + node->placement = placement; + 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)"); + // Allocate before touching GTK, keeping the operation unchanged on failure. + std::string copy = text; + auto &a = api(); + ++node->suppress; + switch (node->kind) { + case Kind::window: a.gtk_window_set_title(reinterpret_cast(node->object), copy.c_str()); break; + case Kind::label: a.gtk_label_set_text(reinterpret_cast(node->object), copy.c_str()); break; + case Kind::button: a.gtk_button_set_label(reinterpret_cast(node->object), copy.c_str()); break; + case Kind::entry: a.gtk_editable_set_text(reinterpret_cast(node->object), copy.c_str()); break; + case Kind::checkbox: a.gtk_check_button_set_label(reinterpret_cast(node->object), copy.c_str()); break; + default: break; + } + --node->suppress; + impl_->text_bytes = impl_->text_bytes - node->text.size() + copy.size(); + node->text = std::move(copy); + 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"); + const char *text = node->kind == Kind::entry + ? api().gtk_editable_get_text(reinterpret_cast(node->object)) : node->text.c_str(); + if (!text) return failure("GTK returned invalid text"); + Result result; result.text = 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"); + return api().gtk_widget_grab_focus(node->object) ? success() : failure("widget cannot receive keyboard focus"); + } + 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; + auto &a = api(); const int number = static_cast(value); + if (property == "visible") { + if (value && node->kind == Kind::window) a.gtk_window_present(reinterpret_cast(node->object)); + else a.gtk_widget_set_visible(node->object, number); + } else if (property == "sensitive") a.gtk_widget_set_sensitive(node->object, number); + else if (property == "hexpand") a.gtk_widget_set_hexpand(node->object, number); + else if (property == "vexpand") a.gtk_widget_set_vexpand(node->object, number); + else if (property == "checked") { + ++node->suppress; + a.gtk_check_button_set_active(reinterpret_cast(node->object), number); + --node->suppress; + } else if (property == "spacing") { + if (node->kind == Kind::grid) { + a.gtk_grid_set_row_spacing(reinterpret_cast(node->object), static_cast(number)); + a.gtk_grid_set_column_spacing(reinterpret_cast(node->object), static_cast(number)); + } else a.gtk_box_set_spacing(reinterpret_cast(node->kind == Kind::window ? node->root : node->object), number); + } else if (size) a.gtk_window_set_default_size(reinterpret_cast(node->object), + static_cast(node->properties.at("width")), static_cast(node->properties.at("height"))); + else if (margin) { + GtkWidget *target = node->kind == Kind::window ? node->root : node->object; + if (property == "margin" || property == "margin_start") a.gtk_widget_set_margin_start(target, number); + if (property == "margin" || property == "margin_end") a.gtk_widget_set_margin_end(target, number); + if (property == "margin" || property == "margin_top") a.gtk_widget_set_margin_top(target, number); + if (property == "margin" || property == "margin_bottom") a.gtk_widget_set_margin_bottom(target, number); + } + 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(); + auto &a = api(); + 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(a.gtk_check_button_get_active(reinterpret_cast(node->object)) ? 1 : 0); + } + if (property == "visible") return success(a.gtk_widget_get_visible(node->object) ? 1 : 0); + if (property == "sensitive") return success(a.gtk_widget_get_sensitive(node->object) ? 1 : 0); + if (property == "focus") return success(a.gtk_widget_has_focus(node->object) ? 1 : 0); + if (property == "width" || property == "height") { + if (node->kind == Kind::window && !a.gtk_widget_get_realized(node->object)) return success(node->properties.at(property)); + return success(property == "width" ? a.gtk_widget_get_width(node->object) : a.gtk_widget_get_height(node->object)); + } + 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 (!api().gtk_widget_is_sensitive(node->object)) return failure("cannot activate an insensitive widget or a child of an insensitive container"); + return api().gtk_widget_activate(node->object) ? success() : failure("GTK could not activate the widget"); +} +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"); + for (unsigned count = 0; count < 128; ++count) if (!api().g_main_context_iteration(nullptr, 0)) break; + if (impl_->event_failure) { + impl_->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::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"); + for (auto &[id, child] : impl_->nodes) if (child.window == window) impl_->disconnect(child); + api().gtk_window_destroy(reinterpret_cast(node->object)); + for (auto it = impl_->nodes.begin(); it != impl_->nodes.end();) { + if (it->second.window != window) { ++it; continue; } + impl_->text_bytes -= it->second.text.size(); + api().g_object_unref(it->second.object); 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); + } + return success(); +} +} // namespace ny::ui diff --git a/nilcompiler/src/ui_runtime.hpp b/nilcompiler/src/ui_runtime.hpp new file mode 100644 index 00000000..29d8868c --- /dev/null +++ b/nilcompiler/src/ui_runtime.hpp @@ -0,0 +1,72 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#pragma once +#include +#include +#include + +namespace ny::ui { +struct Result { + std::int64_t number = 0; + std::string text; + std::string error; + explicit operator bool() const noexcept { return error.empty(); } +}; + +// Checks the optional GTK 4 provider's symbols, without opening a display. +bool available() noexcept; + +// Handles are nonzero, process-unique, and owned by one Context. No toolkit +// pointers cross this boundary. UI calls run on the context's creation thread +// and, once GTK initializes, the single process UI thread. +class Context { +public: + Context(); + ~Context(); + Context(const Context &) = delete; + Context &operator=(const Context &) = delete; + void clear() noexcept; + + // Creates a real window with an automatic vertical root box. Explicit + // present is set_number(window, "visible", 1); creation remains hidden. + Result window(const std::string &title, std::int64_t width, std::int64_t height); + // kind: column, row, grid, label, button, entry, checkbox. Parent must be a + // window/container in this context. Grid children initially occupy successive + // rows; grid_attach repositions an existing child of that exact grid. + // Text is at most 1 MiB per value and 16 MiB of stored labels per context; + // single-line entries accept at most 16384 Unicode scalar values. + Result widget(const std::string &kind, std::int64_t parent, const std::string &label); + Result 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); + Result set_text(std::int64_t handle, const std::string &text); + Result read_text(std::int64_t handle); + // Setter flags require exactly 0/1: visible, sensitive, hexpand, vexpand, + // checked (checkbox only). focus accepts only 1 and requests keyboard focus. + // Bounds: spacing/margin/margin_start/margin_end/ + // margin_top/margin_bottom 0..4096; width/height 1..16384 (window only). + // Read supports those properties, plus kind, parent, width and height + // (allocated widget size, or requested window size before realization). + // kind codes: window=0,column=1,row=2,grid=3,label=4,button=5,entry=6,checkbox=7. + Result set_number(std::int64_t handle, const std::string &property, std::int64_t value); + Result read_number(std::int64_t handle, const std::string &property); + // Button/checkbox activation uses GTK's actual widget activation path. + Result activate(std::int64_t handle); + // Nonblocking: pumps a bounded number of GLib iterations, then snapshots one + // event for this window. number==0 means no event, solely in this private ABI. + Result poll(std::int64_t window); + // Immutable snapshot fields: kind, target, window, checked. Event kinds: + // 1 button activation; 2 entry changed; 3 checkbox toggled; 4 close requested. + // Programmatic set_text/set_number(checked) suppress change notifications. + Result event_number(std::int64_t snapshot, const std::string &field); + Result event_text(std::int64_t snapshot); + Result release_event(std::int64_t snapshot); + // Destroys a window and invalidates its descendants and queued/saved events. + Result close(std::int64_t window); + +private: + struct Impl; + std::shared_ptr impl_; +}; +} // namespace ny::ui diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 0f7c62b2..afab4345 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -9,6 +9,7 @@ #include "matrix_hag_bridge.hpp" #include "nil_contract.hpp" #include "dynamic_type.hpp" +#include "ui_intrinsic.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "integer_conversion.hpp" @@ -714,6 +715,9 @@ void VM::beginMemoryProfile() { } bool VM::finishMemoryProfile(const char *status, bool completed) noexcept { + // This hook runs at every invocation terminal, even without profiling. + // Paused debugger steps retain their UI until completion/reset. + ui_.clear(); if (!memory_profile_started_ || memory_profile_finished_) return true; memory_profile_finished_ = true; @@ -4130,6 +4134,63 @@ void VM::executeInstruction(const Instruction &instr) { return; } + if (lib_name == "intrinsic" && fn_name.rfind("ui.v1.", 0) == 0) { + const auto contract = ui::intrinsic(fn_name); + if (!contract) throw std::runtime_error("ui: unknown intrinsic '" + fn_name + "'"); + const auto declared = call_stack_.empty() ? functions_.end() + : functions_.find(call_stack_.back().fn_name); + if (declared == functions_.end() || + !ui::signature_matches(*contract, declared->second.parameter_types, + declared->second.return_type) || + instr.args.size() != 4 || ui::abi_type(instr.args[3]) != contract->return_type() || + args.size() != contract->parameters.size()) + throw std::runtime_error(fn_name + " requires the exact UI ABI " + ui::signature(*contract)); + if (contract->output != ui::Output::capability) { + std::size_t schemas = 0; + if (class_metadata_) + for (const auto &definition : class_metadata_->enums) + if (ui::result_schema_matches(*contract, definition)) ++schemas; + if (schemas != 1) + throw std::runtime_error(fn_name + " requires the standard Result schema with exact Ok and Error payloads"); + } + for (std::size_t index = 0; index < args.size(); ++index) { + const bool valid = contract->parameters[index] == "text" + ? std::holds_alternative(args[index]) + : std::holds_alternative(args[index]); + if (!valid) throw std::runtime_error(fn_name + " argument " + + std::to_string(index + 1) + " requires " + contract->parameters[index]); + } + auto text_arg = [&](std::size_t index) -> const std::string & { + return std::get(args[index]); + }; + auto word_arg = [&](std::size_t index) { return std::get(args[index]); }; + if (contract->output == ui::Output::capability) { + pushStack(int64_t(ui::available())); return; + } + ui::Result result; + const auto &op = contract->operation; + if (op == "window") result = ui_.window(text_arg(0), word_arg(1), word_arg(2)); + else if (op == "widget") result = ui_.widget(text_arg(0), word_arg(1), text_arg(2)); + else if (op == "grid_attach") result = ui_.grid_attach(word_arg(0), word_arg(1), word_arg(2), word_arg(3), word_arg(4), word_arg(5)); + else if (op == "set_text") result = ui_.set_text(word_arg(0), text_arg(1)); + else if (op == "read_text") result = ui_.read_text(word_arg(0)); + else if (op == "set_number") result = ui_.set_number(word_arg(0), text_arg(1), word_arg(2)); + else if (op == "read_number") result = ui_.read_number(word_arg(0), text_arg(1)); + else if (op == "activate") result = ui_.activate(word_arg(0)); + else if (op == "poll") result = ui_.poll(word_arg(0)); + else if (op == "event_number") result = ui_.event_number(word_arg(0), text_arg(1)); + else if (op == "event_text") result = ui_.event_text(word_arg(0)); + else if (op == "release_event") result = ui_.release_event(word_arg(0)); + else if (op == "close") result = ui_.close(word_arg(0)); + EnumValue value; + value.variant_name = result ? "Result::Ok" : "Result::Error"; + if (!result) value.payloads.push_back(std::move(result.error)); + else if (contract->output == ui::Output::text) value.payloads.push_back(std::move(result.text)); + else value.payloads.push_back(result.number); + pushStack(std::move(value)); + return; + } + if (lib_name == "intrinsic" && fn_name.rfind("db2.", 0) == 0) { auto text_arg = [&](std::size_t i) -> const std::string & { if (i >= args.size() || !std::holds_alternative(args[i])) diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 602726ff..3651ad78 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -16,6 +16,7 @@ #include #include "source_debug.hpp" #include "database_runtime.hpp" +#include "ui_runtime.hpp" #include "memory_profile.hpp" namespace ny { @@ -479,6 +480,7 @@ class VM { // Heap management for manual memory (unsafe mode) and GC (safe mode) database::Context databases_; + ui::Context ui_; struct HeapBlock { std::string type_name; // Logical element metadata for type_name == "array". Textual and binary diff --git a/nilstd/README.md b/nilstd/README.md index a7e1e53b..885b8945 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -17,17 +17,18 @@ nilstd/ The standard namespace root is omitted on disk. For example, `nil.std.io.console` belongs under `src/io/`. The parser treats legacy `ny.lang.*` imports as aliases of `nil.std.*`, including qualified names; -there is one module identity and one copy of each implementation. Engine and UI prototypes +there is one module identity and one copy of each implementation. The active +Matrix desktop library lives under `src/ui`. Earlier engine and UI prototypes are first-party packages rather than standard-library modules and live in `packages/ny.engine` and `packages/ny.ui.mimic`. ## Current status -The active tree contains 75 sources (68 Ny and seven Matrix) organized into 16 +The active tree contains 80 sources (68 Ny and 12 Matrix) organized into 18 logical SDK modules: `prelude` plus `nil.std.core`, `collections`, `datetime`, `db`, `diagnostics`, -`io`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `text`, and -`threading`. The SDK packaging gate compiles every logical module with normal +`io`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `testing`, `text`, +`threading`, and `ui`. The SDK packaging gate compiles every logical module with normal type checking, emits a NIL library (v2, or v4 when carrying classes), and fails atomically rather than publishing a partial set. Matrix sources retain their extensions in installed `nilstd` and embedded NIL interfaces, allowing both @@ -45,13 +46,19 @@ below. | Area | Files | Status | | --- | ---: | --- | -| `src/` | 68 Ny files, 7 Matrix files | Sixteen logical SDK modules. Matrix contributes checked arrays/text spans, stable sorting, reflection values, vector helpers and independent random generators, consumed from both frontends. | +| `src/` | 68 Ny files, 12 Matrix files | Eighteen logical SDK modules. Matrix contributes checked arrays/text spans, sorting, reflection values, vector helpers, random generators, testing helpers and the desktop UI library, consumed from both frontends. | | `experimental/` | 65 Ny files | Design sources excluded from `nilstd`/`nillib` because language semantics, executable providers, or behavioral evidence are incomplete. | | `tests/` | 8 Ny files | Preserved design-era tests; these are still separate from the registered route fixtures under the repository-level `tests/` tree. | | `native/` | 14 C/C++ files | Preserved platform/provider shims; source presence alone is neither a build, shipment, nor native-support claim. | ### Active evidence boundary +`nil.std.testing` supplies checks and checked value extraction with co-located +niltest cases. `nil.std.ui` supplies typed windows, layouts, controls, events and +model synchronization through the optional Linux GTK 4 provider. See the +[testing guide](../docs/tools/testing.md) and [UI reference](../docs/standard-library/ui.md) +for execution evidence and current scope. + `nil.std.nildata` replaces NyData with versioned data blocks, one array kind, exact numeric tokens and checked JSON interchange. The compiler conversions and VM/native library share one engine. Legacy imports are explicit. See the diff --git a/nilstd/src/ui/models.matrix b/nilstd/src/ui/models.matrix new file mode 100644 index 00000000..86043a2a --- /dev/null +++ b/nilstd/src/ui/models.matrix @@ -0,0 +1,52 @@ +@pragma once +book nil.std.ui + +!!! Explicit binding state. Records share identity when assigned; construct a +!!! new model for independent state. Updates return whether the value changed. +public TextModel begin record + field content as text +end record + +public FlagModel begin record + field enabled as boolean +end record + +public create-text-model receives initial as text returns TextModel begin paragraph + give build TextModel with content being initial +end paragraph + +public create-flag-model receives initial as boolean returns FlagModel begin paragraph + give build FlagModel with enabled being initial +end paragraph + +public update-text-model receives model as TextModel, next-value as text returns boolean begin paragraph + when model.content equals next-value then give no end when + set model.content to next-value + give yes +end paragraph + +public update-flag-model receives model as FlagModel, next-value as boolean returns boolean begin paragraph + when model.enabled equals next-value then give no end when + set model.enabled to next-value + give yes +end paragraph + +note suite "nil.std.ui.models" +text_updates_only_when_changed begin test + value model is create-text-model with "first" + expect not (update-text-model with model being model, next-value being "first") + expect update-text-model with model being model, next-value being "Matrix" + expect model.content equals "Matrix" + value independent is create-text-model with model.content + expect update-text-model with model being model, next-value being "changed" + expect independent.content equals "Matrix" +end test + +note suite "nil.std.ui.models" +flag_updates_only_when_changed begin test + value model is create-flag-model with no + expect not (update-flag-model with model being model, next-value being no) + expect update-flag-model with model being model, next-value being yes + expect model.enabled + expect not (update-flag-model with model being model, next-value being yes) +end test diff --git a/nilstd/src/ui/package.matrix b/nilstd/src/ui/package.matrix new file mode 100644 index 00000000..92403ffe --- /dev/null +++ b/nilstd/src/ui/package.matrix @@ -0,0 +1,337 @@ +@pragma once +book nil.std.ui + +read nil.std.core.option +read nil.std.core.result +read nil.std.ui.types +read nil.std.ui.models + +note intrinsic "ui.v1.available" +ui-provider-available returns boolean + +note intrinsic "ui.v1.window" +ui-provider-window receives title as text, width as number, height as number returns Result of number, text + +note intrinsic "ui.v1.widget" +ui-provider-widget receives kind as text, parent as number, label as text returns Result of number, text + +note intrinsic "ui.v1.grid_attach" +ui-provider-grid-attach receives grid as number, child as number, column as number, row as number, column-span as number, row-span as number returns Result of number, text + +note intrinsic "ui.v1.set_text" +ui-provider-set-text receives handle as number, content as text returns Result of number, text + +note intrinsic "ui.v1.read_text" +ui-provider-read-text receives handle as number returns Result of text, text + +note intrinsic "ui.v1.set_number" +ui-provider-set-number receives handle as number, property as text, content as number returns Result of number, text + +note intrinsic "ui.v1.read_number" +ui-provider-read-number receives handle as number, property as text returns Result of number, text + +note intrinsic "ui.v1.activate" +ui-provider-activate receives handle as number returns Result of number, text + +note intrinsic "ui.v1.poll" +ui-provider-poll receives handle as number returns Result of number, text + +note intrinsic "ui.v1.event_number" +ui-provider-event-number receives snapshot as number, property as text returns Result of number, text + +note intrinsic "ui.v1.event_text" +ui-provider-event-text receives snapshot as number returns Result of text, text + +note intrinsic "ui.v1.release_event" +ui-provider-release-event receives snapshot as number returns Result of number, text + +note intrinsic "ui.v1.close" +ui-provider-close receives handle as number returns Result of number, text + +!!! Provider declarations are private. Public constructors never expose the +!!! private zero sentinel used by an empty notification queue. +ui-success receives outcome as Result of number, text returns Result of boolean, text begin paragraph + consider outcome + when Result.Ok holding status then begin block + when status does not equal 1 then give Result.Error holding "UI provider returned an invalid operation status" end when + give Result.Ok holding yes + end block + when Result.Error holding failure then give Result.Error holding failure + end consider +end paragraph + +ui-flag-number receives enabled as boolean returns number begin paragraph + when enabled then give 1 end when + give 0 +end paragraph + +public available returns boolean begin paragraph + give ui-provider-available with nothing +end paragraph + +public create-window receives title as text, width as number, height as number returns Result of Window, text begin paragraph + consider ui-provider-window with title, width, height + when Result.Ok holding handle then give Result.Ok holding (build nil.std.ui.Window with handle being handle) + when Result.Error holding failure then give Result.Error holding failure + end consider +end paragraph + +!!! A surface owns its automatic column root. Children created below this +!!! parent belong to the surface and are invalidated when it closes. +public window-root receives surface as Window returns Widget begin paragraph + give build nil.std.ui.Widget with handle being surface.handle +end paragraph + +ui-create-widget receives kind as text, parent as Widget, label as text returns Result of Widget, text begin paragraph + consider ui-provider-widget with kind, parent.handle, label + when Result.Ok holding handle then give Result.Ok holding (build nil.std.ui.Widget with handle being handle) + when Result.Error holding failure then give Result.Error holding failure + end consider +end paragraph + +public create-column receives parent as Widget returns Result of Widget, text begin paragraph + give ui-create-widget with "column", parent, "" +end paragraph + +public create-row receives parent as Widget returns Result of Widget, text begin paragraph + give ui-create-widget with "row", parent, "" +end paragraph + +public create-grid receives parent as Widget returns Result of Widget, text begin paragraph + give ui-create-widget with "grid", parent, "" +end paragraph + +public create-label receives parent as Widget, label as text returns Result of Widget, text begin paragraph + give ui-create-widget with "label", parent, label +end paragraph + +public create-button receives parent as Widget, label as text returns Result of Widget, text begin paragraph + give ui-create-widget with "button", parent, label +end paragraph + +public create-entry receives parent as Widget, label as text returns Result of Widget, text begin paragraph + give ui-create-widget with "entry", parent, label +end paragraph + +public create-checkbox receives parent as Widget, label as text returns Result of Widget, text begin paragraph + give ui-create-widget with "checkbox", parent, label +end paragraph + +public show-window receives surface as Window returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with surface.handle, "visible", 1) +end paragraph + +public close-window receives surface as Window returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-close with surface.handle) +end paragraph + +public set-widget-text receives control as Widget, content as text returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-text with control.handle, content) +end paragraph + +public set-checked receives control as Widget, checked as boolean returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with control.handle, "checked", (ui-flag-number with checked)) +end paragraph + +public set-sensitive receives control as Widget, enabled as boolean returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with control.handle, "sensitive", (ui-flag-number with enabled)) +end paragraph + +public set-visible receives control as Widget, visible as boolean returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with control.handle, "visible", (ui-flag-number with visible)) +end paragraph + +public set-margin receives control as Widget, pixels as number returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with control.handle, "margin", pixels) +end paragraph + +public set-spacing receives control as Widget, pixels as number returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with control.handle, "spacing", pixels) +end paragraph + +public focus-widget receives control as Widget returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-set-number with control.handle, "focus", 1) +end paragraph + +public activate-widget receives control as Widget returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-activate with control.handle) +end paragraph + +public attach-grid receives grid as Widget, child as Widget, column as number, row as number, column-span as number, row-span as number returns Result of boolean, text begin paragraph + give ui-success with (ui-provider-grid-attach with grid.handle, child.handle, column, row, column-span, row-span) +end paragraph + +public widget-text receives control as Widget returns Result of text, text begin paragraph + give ui-provider-read-text with control.handle +end paragraph + +public widget-checked receives control as Widget returns Result of boolean, text begin paragraph + consider ui-provider-read-number with control.handle, "checked" + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding state then begin block + when state equals 0 then give Result.Ok holding no end when + when state equals 1 then give Result.Ok holding yes end when + give Result.Error holding "UI provider returned an invalid checkbox state" + end block + end consider +end paragraph + +public set-expansion receives control as Widget, horizontal as boolean, vertical as boolean returns Result of boolean, text begin paragraph + consider ui-provider-set-number with control.handle, "hexpand", (ui-flag-number with horizontal) + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding changed then begin block + give ui-success with (ui-provider-set-number with control.handle, "vexpand", (ui-flag-number with vertical)) + end block + end consider +end paragraph + +public widget-width receives control as Widget returns Result of number, text begin paragraph + give ui-provider-read-number with control.handle, "width" +end paragraph + +public widget-height receives control as Widget returns Result of number, text begin paragraph + give ui-provider-read-number with control.handle, "height" +end paragraph + +ui-event-kind receives code as number returns Result of EventKind, text begin paragraph + when code equals 1 then give Result.Ok holding EventKind.Clicked end when + when code equals 2 then give Result.Ok holding EventKind.TextChanged end when + when code equals 3 then give Result.Ok holding EventKind.Toggled end when + when code equals 4 then give Result.Ok holding EventKind.CloseRequested end when + give Result.Error holding "UI provider returned an unknown event kind" +end paragraph + +ui-copy-event receives snapshot as number, surface as Window returns Result of Event, text begin paragraph + consider ui-provider-event-number with snapshot, "window" + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding origin then begin block + when origin does not equal surface.handle then give Result.Error holding "UI event belongs to another window" end when + consider ui-provider-event-number with snapshot, "kind" + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding kind-code then begin block + consider ui-event-kind with kind-code + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding snapshot-kind then begin block + consider ui-provider-event-number with snapshot, "target" + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding target-handle then begin block + consider ui-provider-event-number with snapshot, "checked" + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding checked-value then begin block + when checked-value does not equal 0 and checked-value does not equal 1 then give Result.Error holding "UI event has an invalid checked state" end when + consider ui-provider-event-text with snapshot + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding content then begin block + variable target as Option of Widget is Option.None + when kind-code does not equal 4 then + when target-handle is at most 0 then give Result.Error holding "UI event has an invalid widget target" end when + set target to Option.Some holding (build nil.std.ui.Widget with handle being target-handle) + end when + give Result.Ok holding (build nil.std.ui.Event with kind being snapshot-kind, window being surface, target being target, content being content, checked being (checked-value equals 1)) + end block + end consider + end block + end consider + end block + end consider + end block + end consider + end block + end consider + end block + end consider +end paragraph + +!!! Copy all fields before releasing the provider snapshot, including when a +!!! getter fails. An empty queue is Option.None, never a public zero handle. +public poll-event receives surface as Window returns Result of PendingEvent, text begin paragraph + consider ui-provider-poll with surface.handle + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding snapshot then begin block + when snapshot equals 0 then give Result.Ok holding Option.None end when + value copied is ui-copy-event with snapshot, surface + value released is ui-provider-release-event with snapshot + consider released + when Result.Error holding release-failure then begin block + consider copied + when Result.Error holding copy-failure then give Result.Error holding (copy-failure plus "; event release failed: " plus release-failure) + when Result.Ok holding notification then give Result.Error holding release-failure + end consider + end block + when Result.Ok holding released-status then begin block + consider copied + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding notification then give Result.Ok holding (Option.Some holding notification) + end consider + end block + end consider + end block + end consider +end paragraph + +public event-for receives notification as Event, control as Widget returns boolean begin paragraph + consider notification.target + when Option.Some holding target then give target.handle equals control.handle + when Option.None then give no + end consider +end paragraph + +public is-click receives notification as Event returns boolean begin paragraph + consider notification.kind + when EventKind.Clicked then give yes + when _ then give no + end consider +end paragraph + +public is-text-change receives notification as Event returns boolean begin paragraph + consider notification.kind + when EventKind.TextChanged then give yes + when _ then give no + end consider +end paragraph + +public is-toggle receives notification as Event returns boolean begin paragraph + consider notification.kind + when EventKind.Toggled then give yes + when _ then give no + end consider +end paragraph + +public is-close-request receives notification as Event returns boolean begin paragraph + consider notification.kind + when EventKind.CloseRequested then give yes + when _ then give no + end consider +end paragraph + +!!! Synchronization compares the control and model before writing. GTK setters +!!! also suppress programmatic changed/toggled events to avoid feedback loops. +public sync-text receives control as Widget, model as TextModel returns Result of boolean, text begin paragraph + consider widget-text with control + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding current then begin block + when current equals model.content then give Result.Ok holding no end when + give set-widget-text with control, model.content + end block + end consider +end paragraph + +public sync-flag receives control as Widget, model as FlagModel returns Result of boolean, text begin paragraph + consider widget-checked with control + when Result.Error holding failure then give Result.Error holding failure + when Result.Ok holding current then begin block + when current equals model.enabled then give Result.Ok holding no end when + give set-checked with control, model.enabled + end block + end consider +end paragraph + +public apply-text-event receives model as TextModel, control as Widget, notification as Event returns boolean begin paragraph + when not (is-text-change with notification) or not (event-for with notification, control) then give no end when + give update-text-model with model, notification.content +end paragraph + +public apply-flag-event receives model as FlagModel, control as Widget, notification as Event returns boolean begin paragraph + when not (is-toggle with notification) or not (event-for with notification, control) then give no end when + give update-flag-model with model, notification.checked +end paragraph diff --git a/nilstd/src/ui/types.matrix b/nilstd/src/ui/types.matrix new file mode 100644 index 00000000..cf89ac83 --- /dev/null +++ b/nilstd/src/ui/types.matrix @@ -0,0 +1,34 @@ +@pragma once +book nil.std.ui + +read nil.std.core.option + +!!! Handles are checked by the provider on every operation. They are not GTK +!!! addresses and are valid only in their originating runtime context. +public Window begin record + field handle as number +end record + +public Widget begin record + field handle as number +end record + +public EventKind begin choice + when Clicked + when TextChanged + when Toggled + when CloseRequested +end choice + +!!! A complete copied event. A close request has no widget target. Text and +!!! checked state belong to the event snapshot, not to later widget state. +public Event begin record + field kind as EventKind + field window as Window + field target as nil.std.core.Option of Widget + field content as text + field checked as boolean +end record + +!!! Alias keeps a nested optional event readable in Result type applications. +public PendingEvent means nil.std.core.Option of Event diff --git a/tests/language/enum-assignment-context.matrix b/tests/language/enum-assignment-context.matrix new file mode 100644 index 00000000..b3888614 --- /dev/null +++ b/tests/language/enum-assignment-context.matrix @@ -0,0 +1,38 @@ +book validation.enum_assignment +read nil.std.core.option + +PayloadRecord begin record + field amount as number +end record +Holder begin record + field item as nil.std.core.Option of PayloadRecord +end record +variable evaluations as number is 0 + +make-payload returns PayloadRecord begin paragraph + set evaluations to evaluations plus 1 + give build PayloadRecord with amount being 40 plus evaluations +end paragraph + +main returns number begin paragraph + variable selected as Option of PayloadRecord is Option.None + set selected to Option.Some holding (make-payload with nothing) + variable saved as Option of PayloadRecord is Option.None + set saved to Option.Some holding (make-payload with nothing) + variable container is build Holder with item being Option.None + set container.item to Option.Some holding (make-payload with nothing) + consider selected + when Option.Some holding item then say item.amount + when Option.None then give 9 + end consider + consider saved + when Option.Some holding item then say item.amount + when Option.None then give 9 + end consider + consider container.item + when Option.Some holding item then say item.amount + when Option.None then give 9 + end consider + say evaluations + give 0 +end paragraph diff --git a/tests/language/enum-assignment-context.ny b/tests/language/enum-assignment-context.ny new file mode 100644 index 00000000..7da8ea4e --- /dev/null +++ b/tests/language/enum-assignment-context.ny @@ -0,0 +1,38 @@ +module validation.enum_assignment +import nil.std.core.option + +struct PayloadRecord + amount: i64 +end struct +struct Holder + item: nil::std::core::Option +end struct +let mut evaluations: i64 = 0 + +fn make_payload() -> PayloadRecord + evaluations = evaluations + 1 + return PayloadRecord { amount: 40 + evaluations } +end fn + +fn main() -> i32 + let mut selected: Option = Option.None + selected = Option.Some(make_payload()) + let mut saved: Option = Option.None + saved = Option.Some(make_payload()) + let mut container = Holder { item: Option.None } + container.item = Option.Some(make_payload()) + match selected + Option.Some(item) -> println(item.amount) + Option.None -> return 9 + end match + match saved + Option.Some(item) -> println(item.amount) + Option.None -> return 9 + end match + match container.item + Option.Some(item) -> println(item.amount) + Option.None -> return 9 + end match + println(evaluations) + return 0 +end fn diff --git a/tests/language/enum-assignment-context.stdout b/tests/language/enum-assignment-context.stdout new file mode 100644 index 00000000..81598707 --- /dev/null +++ b/tests/language/enum-assignment-context.stdout @@ -0,0 +1,4 @@ +41 +42 +43 +3 diff --git a/tests/matrix/consider_block_contract.py b/tests/matrix/consider_block_contract.py new file mode 100644 index 00000000..f8f992e5 --- /dev/null +++ b/tests/matrix/consider_block_contract.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Explicit consider arms preserve nested control flow and lexical scope.""" +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + +SOURCE = '''book nested.arms +Response begin choice + when Good holding number + when Bad holding text +end choice +score receives item as Response returns number begin paragraph + consider item + when Response.Good holding amount provided amount is at least 0 then begin block + variable total as number is 0 + when amount is greater than 3 then + repeat for index from 0 to 3 + set total to total plus amount + end repeat + otherwise + set total to amount plus 1 + end when + consider amount + when 4 then begin block + when total equals 12 then set total to 20 end when + end block + otherwise begin block + when total equals 1 then set total to 2 end when + end block + end consider + give total + end block + when Response.Good holding amount then give 0 + when Response.Bad holding reason then begin block + when reason equals "retry" then give -1 end when + give -2 + end block + end consider +end paragraph +note suite "matrix.consider.blocks" +nested_branches begin test + expect (score with (Response.Good holding 4)) equals 20 + expect (score with (Response.Good holding 0)) equals 2 + expect (score with (Response.Good holding -1)) equals 0 + expect (score with (Response.Bad holding "retry")) equals -1 + expect (score with (Response.Bad holding "stop")) equals -2 +end test +''' + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for option in ('compiler', 'interpreter', 'tester'): + parser.add_argument('--' + option, type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='nil-consider-block-') as directory: + work = Path(directory) + source = work / 'nested.matrix' + source.write_text(SOURCE) + command = [args.tester.resolve(), 'run', '--compiler', args.compiler.resolve(), + '--interpreter', args.interpreter.resolve(), '--target', + 'all' if args.llvm == 'ON' else 'vm', '--format', 'json', source] + result = subprocess.run(list(map(str, command)), capture_output=True, text=True, timeout=90) + assert result.returncode == 0, (result.stdout, result.stderr) + report = json.loads(result.stdout) + assert report['summary']['passed'] == (2 if args.llvm == 'ON' else 1), report + invalid = { + 'missing-close': ('main begin paragraph\n consider 1\n when 1 then begin block\n say 2\n end consider\nend paragraph\n', "expected 'end block'"), + 'scope': ('main begin paragraph\n consider 1\n when 1 then begin block\n value inside is 2\n end block\n when 2 then say inside\n end consider\nend paragraph\n', 'inside'), + 'outside-arm': ('main begin paragraph\n begin block\n say 2\n end block\nend paragraph\n', 'expected a statement'), + } + for name, (text, diagnostic) in invalid.items(): + path = work / (name + '.matrix') + path.write_text('book invalid.arm\n' + text) + artifact = work / (name + '.nil') + artifact.write_text('retained output') + result = subprocess.run([str(args.compiler.resolve()), '--no-bundle', '-o', str(artifact), str(path)], + capture_output=True, text=True, timeout=30) + assert result.returncode != 0 and diagnostic in result.stderr, (name, result.stdout, result.stderr) + assert artifact.read_text() == 'retained output', name + print('Nested consider control flow, guards, scope and missing boundaries passed') + + +if __name__ == '__main__': + main() diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index c16a5d4e..e179adb8 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -58,6 +58,7 @@ "input", "either", # NIL-0021 switch vocabulary is contextual, including explicit exits. "switch", "case", "switching", + "block", # Contextual only in consider arm begin/end boundaries. # NIL-0023 keeps ordinary variables and parameters named flag valid. "flag", "expect", diff --git a/tests/tools/ui_display_contract.py b/tests/tools/ui_display_contract.py new file mode 100644 index 00000000..1c90744b --- /dev/null +++ b/tests/tools/ui_display_contract.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Exercise the optional UI provider on a private, authenticated X11 display.""" +from __future__ import annotations + +import argparse +from contextlib import contextmanager +import ctypes as c +import ctypes.util +import json +import os +from pathlib import Path +import secrets +import select +import shutil +import signal +import subprocess +import sys +import tempfile +import time + + +def terminate(process): + if process.poll() is not None: + return + try: + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=3) + except ProcessLookupError: + pass + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=3) + + +@contextmanager +def isolated_display(xvfb): + with tempfile.TemporaryDirectory(prefix='nil-ui-display-') as directory: + root = Path(directory) + authority = root / 'authority' + authority.touch(mode=0o600) + cookie = secrets.token_hex(16) + subprocess.run(['xauth', '-f', authority, 'add', ':0', '.', cookie], + check=True, capture_output=True, timeout=10) + read_fd, write_fd = os.pipe() + with (root / 'server.log').open('w+b') as log: + server = subprocess.Popen([str(xvfb), '-displayfd', str(write_fd), + '-screen', '0', '1024x768x24', '-nolisten', 'tcp', '-auth', str(authority)], + stdin=subprocess.DEVNULL, stdout=log, stderr=log, + pass_fds=(write_fd,), start_new_session=True) + os.close(write_fd) + try: + if not select.select([read_fd], [], [], 15)[0]: + raise AssertionError('Xvfb did not publish a display number within 15 seconds') + display_number = os.read(read_fd, 64).decode('ascii').strip() + if not display_number.isdecimal() or server.poll() is not None: + log.seek(0) + raise AssertionError('Xvfb startup failed: ' + log.read().decode(errors='replace')) + display = ':' + display_number + subprocess.run(['xauth', '-f', authority, 'add', display, '.', cookie], + check=True, capture_output=True, timeout=10) + env = dict(os.environ) + for key in ('WAYLAND_DISPLAY', 'DBUS_SESSION_BUS_ADDRESS', 'DBUS_SESSION_BUS_PID'): + env.pop(key, None) + env.update(DISPLAY=display, XAUTHORITY=str(authority), + GDK_BACKEND='x11', GSK_RENDERER='cairo', GTK_A11Y='none', + XDG_RUNTIME_DIR=str(root)) + yield env + finally: + os.close(read_fd) + terminate(server) + + +class X11Input: + """Drive only the two known NIL test windows on our private display.""" + def __init__(self, env): + self.x = c.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6') + self.xt = c.CDLL(ctypes.util.find_library('Xtst') or 'libXtst.so.6') + self.x.XOpenDisplay.argtypes = [c.c_char_p] + self.x.XOpenDisplay.restype = c.c_void_p + self.x.XDefaultRootWindow.argtypes = [c.c_void_p] + self.x.XDefaultRootWindow.restype = c.c_ulong + self.x.XQueryTree.argtypes = [c.c_void_p, c.c_ulong, c.POINTER(c.c_ulong), + c.POINTER(c.c_ulong), c.POINTER(c.POINTER(c.c_ulong)), c.POINTER(c.c_uint)] + self.x.XFetchName.argtypes = [c.c_void_p, c.c_ulong, c.POINTER(c.c_void_p)] + self.x.XFree.argtypes = [c.c_void_p] + self.x.XSetInputFocus.argtypes = [c.c_void_p, c.c_ulong, c.c_int, c.c_ulong] + self.x.XStringToKeysym.argtypes = [c.c_char_p] + self.x.XStringToKeysym.restype = c.c_ulong + self.x.XKeysymToKeycode.argtypes = [c.c_void_p, c.c_ulong] + self.x.XKeysymToKeycode.restype = c.c_ubyte + self.x.XFlush.argtypes = [c.c_void_p] + self.x.XSync.argtypes = [c.c_void_p, c.c_int] + self.x.XCloseDisplay.argtypes = [c.c_void_p] + self.x.XInternAtom.argtypes = [c.c_void_p, c.c_char_p, c.c_int] + self.x.XInternAtom.restype = c.c_ulong + self.x.XSendEvent.argtypes = [c.c_void_p, c.c_ulong, c.c_int, c.c_long, c.c_void_p] + self.xt.XTestFakeKeyEvent.argtypes = [c.c_void_p, c.c_uint, c.c_int, c.c_ulong] + previous = os.environ.get('XAUTHORITY') + os.environ['XAUTHORITY'] = env['XAUTHORITY'] + try: + self.display = self.x.XOpenDisplay(env['DISPLAY'].encode()) + finally: + if previous is None: + os.environ.pop('XAUTHORITY', None) + else: + os.environ['XAUTHORITY'] = previous + assert self.display, 'cannot connect to the private authenticated X11 display' + self.root = self.x.XDefaultRootWindow(self.display) + self.handled = set() + class Error(c.Structure): + _fields_ = [('type', c.c_int), ('display', c.c_void_p), ('resourceid', c.c_ulong), + ('serial', c.c_ulong), ('code', c.c_ubyte), ('request', c.c_ubyte), ('minor', c.c_ubyte)] + # A window may disappear between QueryTree, FetchName and focus. Xlib's + # default handler exits the process for this ordinary stale-window race. + self.xerrors = [] + callback = c.CFUNCTYPE(c.c_int, c.c_void_p, c.POINTER(Error)) + def on_error(display, error): + self.xerrors.append((error.contents.code, error.contents.request)) + return 0 + self.error_callback = callback(on_error) + self.x.XSetErrorHandler.argtypes = [c.c_void_p] + self.x.XSetErrorHandler.restype = c.c_void_p + self.old_error_handler = self.x.XSetErrorHandler(c.cast(self.error_callback, c.c_void_p)) + class Attributes(c.Structure): + _fields_ = [(key, c.c_int) for key in ('x', 'y', 'width', 'height', 'border_width', 'depth')] + [ + ('visual', c.c_void_p), ('root', c.c_ulong), ('window_class', c.c_int), + ('bit_gravity', c.c_int), ('win_gravity', c.c_int), ('backing_store', c.c_int), + ('backing_planes', c.c_ulong), ('backing_pixel', c.c_ulong), ('save_under', c.c_int), + ('colormap', c.c_ulong), ('map_installed', c.c_int), ('map_state', c.c_int), + ('all_event_masks', c.c_long), ('your_event_mask', c.c_long), ('do_not_propagate_mask', c.c_long), + ('override_redirect', c.c_int), ('screen', c.c_void_p)] + self.Attributes = Attributes + self.x.XGetWindowAttributes.argtypes = [c.c_void_p, c.c_ulong, c.POINTER(Attributes)] + + def close(self): + if self.display: + self.x.XSync(self.display, False) + self.x.XCloseDisplay(self.display) + self.display = None + self.x.XSetErrorHandler(self.old_error_handler) + + def key(self, name, down): + code = self.x.XKeysymToKeycode(self.display, self.x.XStringToKeysym(name.encode())) + assert code, f'no keycode for {name}' + assert self.xt.XTestFakeKeyEvent(self.display, code, int(down), 0) + self.x.XFlush(self.display) + + def press(self, name, shifted=False): + if shifted: + self.key('Shift_L', True) + self.key(name, True) + self.key(name, False) + if shifted: + self.key('Shift_L', False) + time.sleep(.06) + + def request_close(self, window): + class Data(c.Union): + _fields_ = [('b', c.c_char * 20), ('s', c.c_short * 10), ('l', c.c_long * 5)] + class Message(c.Structure): + _fields_ = [('type', c.c_int), ('serial', c.c_ulong), ('send_event', c.c_int), + ('display', c.c_void_p), ('window', c.c_ulong), ('message_type', c.c_ulong), + ('format', c.c_int), ('data', Data)] + class Event(c.Union): + _fields_ = [('message', Message), ('pad', c.c_long * 24)] + event = Event() + event.message.type = 33 # ClientMessage, from Xlib.h. + event.message.display = self.display + event.message.window = window + event.message.message_type = self.x.XInternAtom(self.display, b'WM_PROTOCOLS', False) + event.message.format = 32 + event.message.data.l[0] = self.x.XInternAtom(self.display, b'WM_DELETE_WINDOW', False) + assert self.x.XSendEvent(self.display, window, False, 0, c.byref(event)) + self.x.XFlush(self.display) + + def drive_ready_window(self): + root, parent = c.c_ulong(), c.c_ulong() + children, count = c.POINTER(c.c_ulong)(), c.c_uint() + if not self.x.XQueryTree(self.display, self.root, c.byref(root), c.byref(parent), + c.byref(children), c.byref(count)): + return + try: + for index in range(count.value): + window = children[index] + name = c.c_void_p() + if not self.x.XFetchName(self.display, window, c.byref(name)) or not name.value: + continue + try: + title = c.string_at(name).decode('utf8', errors='replace') + finally: + self.x.XFree(name) + key = (window, title) + if key in self.handled: + continue + if title not in ('NIL2 UI keyboard probe', 'NIL2 UI close probe'): + continue + attributes = self.Attributes() + if not self.x.XGetWindowAttributes(self.display, window, c.byref(attributes)) or attributes.map_state != 2: + continue # IsViewable: do not inject into an unmapped window. + if title == 'NIL2 UI close probe': + self.handled.add(key) + self.request_close(window) + continue + self.x.XSetInputFocus(self.display, window, 2, 0) + self.x.XSync(self.display, False) + if any(request == 42 for _, request in self.xerrors): + self.check_errors() + continue + self.handled.add(key) + time.sleep(.1) # Allow GTK's entry focus request to finish. + for char in 'Matrix': + self.press(char, char.isupper()) + self.press('Tab') + self.press('space') + self.press('Tab') + self.press('space') + finally: + if children: + self.x.XFree(children) + self.check_errors() + + def check_errors(self): + self.x.XSync(self.display, False) + errors, self.xerrors = self.xerrors, [] + unexpected = [(code, request) for code, request in errors + if not (code == 3 and request in (3, 15, 20, 25, 42)) + and not (code == 8 and request == 42)] + assert not unexpected, ('unexpected X11 protocol error', unexpected) + + +def checked(command, env, timeout=180): + process = subprocess.Popen(list(map(str, command)), env=env, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, start_new_session=True) + try: + output, errors = process.communicate(timeout=timeout) + assert process.returncode == 0, (command, process.returncode, output, errors) + return subprocess.CompletedProcess(command, process.returncode, output, errors) + finally: + # Give niltest time to forward cancellation to its separately grouped + # compiler/test children before killing the harness session. + terminate(process) + if process.stdout: process.stdout.close() + if process.stderr: process.stderr.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--xvfb', default=shutil.which('Xvfb')) + parser.add_argument('--probe', action='store_true') + parser.add_argument('--tester', type=Path) + parser.add_argument('--compiler', type=Path) + parser.add_argument('--interpreter', type=Path) + parser.add_argument('--sdk', type=Path) + parser.add_argument('--source', type=Path) + parser.add_argument('--interaction-source', type=Path) + parser.add_argument('--provider-test', type=Path) + parser.add_argument('--lifecycle-test', type=Path) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + if sys.platform != 'linux' or not args.xvfb or not Path(args.xvfb).is_file() or not shutil.which('xauth'): + print('SKIP: GTK display contracts need Linux, Xvfb and xauth') + return 77 + try: + c.CDLL('libX11.so.6') + c.CDLL('libXtst.so.6') + if not args.probe: c.CDLL('libgtk-4.so.1') + except OSError as error: + print('SKIP: optional desktop test dependency is unavailable: ' + str(error)) + return 77 + with isolated_display(Path(args.xvfb).resolve()) as env: + driver = X11Input(env) + driver.close() + if args.probe: + print('Private Xvfb authentication and XTest connection passed') + return 0 + assert all((args.tester, args.compiler, args.interpreter, args.sdk, args.source, args.interaction_source)) + base = [args.tester.resolve(), 'run', '--compiler', args.compiler.resolve(), + '--interpreter', args.interpreter.resolve(), '--sdk-path', args.sdk.resolve(), + '--format', 'json', '--jobs', '1', '--timeout', '30'] + session = ['dbus-run-session', '--'] if shutil.which('dbus-run-session') else [] + if args.provider_test: + checked([*session, args.provider_test.resolve(), '--display'], env) + if args.lifecycle_test: + checked([*session, args.lifecycle_test.resolve(), '--display'], env) + desktop = checked([*session, *base, '--target', 'all' if args.llvm == 'ON' else 'vm', + '--filter', 'nil.std.ui.gtk.desktop', args.source.resolve()], env) + report = json.loads(desktop.stdout) + assert report['tests'] and not report['errors'], report + assert all(test['status'] == 'passed' for test in report['tests']), report + checks = len(report['tests']) + for route in (['vm', 'native'] if args.llvm == 'ON' else ['vm']): + command = [*session, *base, '--target', route, '--filter', 'nil.std.ui.gtk.interaction', + args.interaction_source.resolve()] + process = subprocess.Popen(list(map(str, command)), env=env, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, start_new_session=True) + driver = None + try: + driver = X11Input(env) + deadline = time.monotonic() + 120 + while process.poll() is None and time.monotonic() < deadline: + driver.drive_ready_window() + time.sleep(.04) + if process.poll() is None: + raise AssertionError(f'{route} UI interaction exceeded its outer deadline') + output, errors = process.communicate(timeout=3) + assert process.returncode == 0, (route, output, errors) + report = json.loads(output) + assert len(report['tests']) == 2 and not report['errors'], report + assert all(test['status'] == 'passed' for test in report['tests']), report + assert {title for _, title in driver.handled} == {'NIL2 UI keyboard probe', 'NIL2 UI close probe'} + checks += len(report['tests']) + finally: + if driver: driver.close() + terminate(process) + if process.stdout: process.stdout.close() + if process.stderr: process.stderr.close() + print(f'GTK display contracts passed ({checks} VM/native cases, real keyboard and close events)') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/tools/ui_intrinsic_contract.py b/tests/tools/ui_intrinsic_contract.py new file mode 100644 index 00000000..15c2e298 --- /dev/null +++ b/tests/tools/ui_intrinsic_contract.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""UI provider declarations must preserve their exact checked cross-route ABI.""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + env = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-ui-intrinsic-') as directory: + work = Path(directory) + base = [compiler, '--quiet', '--sdk-path', ROOT / 'nilstd/src'] + + def run(command, status=0): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=work, env=env, + stdin=subprocess.DEVNULL, capture_output=True, + text=True, timeout=120) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + entry = 'fn main() -> i32\n return 0\nend fn\n' + imported = 'import nil.std.core.result\n' + invalid = { + 'unknown': ('@intrinsic("ui.v1.unknown")\nfn provider() -> bool\n', 'Unknown UI intrinsic'), + 'arity': ('@intrinsic("ui.v1.available")\nfn provider(unused: i64) -> bool\n', 'exact UI ABI'), + 'scalar-width': (imported + '@intrinsic("ui.v1.read_text")\nfn provider(handle: i32) -> Result\n', 'exact UI ABI'), + 'capability-result': ('@intrinsic("ui.v1.available")\nfn provider() -> i64\n', 'exact UI ABI'), + 'number-result': (imported + '@intrinsic("ui.v1.poll")\nfn provider(handle: i64) -> Result\n', 'exact UI ABI'), + 'text-result': (imported + '@intrinsic("ui.v1.read_text")\nfn provider(handle: i64) -> Result\n', 'exact UI ABI'), + 'error-payload': (imported + '@intrinsic("ui.v1.poll")\nfn provider(handle: i64) -> Result\n', 'exact UI ABI'), + 'reference': (imported + '@intrinsic("ui.v1.read_text")\nfn provider(ref handle: i64) -> Result\n', 'exact UI ABI'), + 'default': (imported + '@intrinsic("ui.v1.read_text")\nfn provider(handle: i64 = 0) -> Result\n', 'exact UI ABI'), + 'variadic': (imported + '@intrinsic("ui.v1.read_text")\nfn provider(..handles: i64) -> Result\n', 'exact UI ABI'), + 'generic': ('@intrinsic("ui.v1.available")\nfn provider() -> bool\n', 'exact UI ABI'), + 'lookalike-result': ('''module impostor +enum Result + Ok(T) + Error(E) +end enum +@intrinsic("ui.v1.read_text") +fn provider(handle: i64) -> Result +''', 'exact UI ABI'), + } + for name, (declaration, diagnostic) in invalid.items(): + source = work / (name + '.ny') + source.write_text(declaration + entry) + output = work / (name + '.nil') + output.write_bytes(b'previous artifact') + result = run([*base, '--no-bundle', '-o', output, source], 1) + assert diagnostic in result.stderr, (name, result.stderr) + assert output.read_bytes() == b'previous artifact', name + + matrix = work / 'wrong-width.matrix' + matrix.write_text('''book invalid-ui +read nil.std.core.result +note intrinsic "ui.v1.read_text" +provider receives handle as i32 returns Result of text, text +main returns number begin paragraph + give 0 +end paragraph +''') + result = run([*base, '--no-bundle', '-o', work / 'matrix.nil', matrix], 1) + assert 'exact UI ABI' in result.stderr, result.stderr + + # Matrix folding applies equally to public and private declarations, + # and neither source order may silently turn a record into its factory. + for reverse in (False, True): + for record_visibility in ("", "public "): + for function_visibility in ("", "public "): + record = record_visibility + "TextModel begin record\n field content as text\nend record\n" + function = function_visibility + "text-model returns number begin paragraph\n give 0\nend paragraph\n" + source = work / 'folded-collision.matrix' + source.write_text('book collisions\n' + (function + record if reverse else record + function) + + 'main returns number begin paragraph\n give 0\nend paragraph\n') + result = run([*base, '--no-bundle', '-o', work / 'collision.nil', source], 1) + assert 'Matrix names fold case and separators' in result.stderr, result.stderr + assert 'text-model' in result.stderr and 'TextModel' in result.stderr, result.stderr + + # Ny does not fold spelling, but the shared checker must also prevent + # a function from replacing a type with the exact same module identity. + for reverse in (False, True): + record = 'struct Shared\n content: text\nend struct\n' + function = 'fn Shared() -> i32\n return 0\nend fn\n' + source = work / 'cross-kind.ny' + source.write_text((function + record if reverse else record + function) + entry) + result = run([*base, '--no-bundle', '-o', work / 'cross-kind.nil', source], 1) + assert 'conflicts with another declaration kind' in result.stderr, result.stderr + + # Implementations refer to an existing declaration, while named tests + # carry display metadata. Neither is another module-level value symbol. + source = work / 'non-collisions.matrix' + source.write_text('''book valid-declarations +TextModel begin record + field content as text +end record +TextModel begin implementation +end implementation +TextModel begin test + expect yes +end test +main returns number begin paragraph + give 0 +end paragraph +''') + run([*base, '--no-bundle', '-o', work / 'valid-declarations.nil', source]) + + # Disabling source checking must not permit an incompatible declaration + # to reinterpret its return value in either backend. + for name, declaration, expression in ( + ('unchecked-arity', '@intrinsic("ui.v1.available")\nfn provider(unused: i64) -> bool\n', 'provider(0)'), + ('unchecked-return', '@intrinsic("ui.v1.available")\nfn provider() -> i64\n', 'provider()'), + ): + source = work / (name + '.ny') + source.write_text(declaration + 'fn main() -> i32\n println(' + expression + ')\n return 0\nend fn\n') + output = work / (name + '.nil') + compiled = subprocess.run(list(map(str, [*base, '--no-typecheck', '--no-bundle', '-o', output, source])), + cwd=work, env=env, capture_output=True, text=True, timeout=120) + checks += 1 + if compiled.returncode == 0: + result = run([interpreter, '--no-ai', output], 1) + else: + assert compiled.returncode == 1, compiled + result = compiled + assert 'UI ABI' in result.stderr, (name, result.stderr) + if args.llvm == 'ON': + output.write_bytes(b'previous artifact') + result = run([*base, '--no-typecheck', '--native', '-o', output, source], 1) + assert 'UI ABI' in result.stderr, result.stderr + assert output.read_bytes() == b'previous artifact' + + # A valid declaration works without a display. Read failures are typed + # Result errors, and obtaining a capability cannot open a window. + source = work / 'checked.ny' + source.write_text(imported + '''@intrinsic("ui.v1.available") +fn provider_available() -> flag +@intrinsic("ui.v1.read_text") +fn provider_text(handle: i64) -> Result +fn main() -> i32 + let capability: bool = provider_available() + let result = provider_text(0) + match result + Result.Ok(value) -> return 9 + Result.Error(message) -> println("checked UI failure") + end match + return 0 +end fn +''') + for route in ['text', 'binary', 'bundle'] + (['native', 'jit'] if args.llvm == 'ON' else []): + output = work / ('checked-' + route) + flags = ['--native', '--jit'] if route == 'jit' else ['--native'] if route == 'native' else [] if route == 'bundle' else ['--no-bundle'] + if route == 'binary': + flags += ['--emit-binary-nil'] + result = run([*base, *flags, '-o', output, source]) + if route != 'jit': + command = [interpreter, '--no-ai', output] if route in ('text', 'binary') else [output] + result = run(command) + assert result.stdout == 'checked UI failure\n', (route, result.stdout, result.stderr) + print(f'UI intrinsic ABI: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/ui/gtk_desktop.matrix b/tests/ui/gtk_desktop.matrix new file mode 100644 index 00000000..87bc6be6 --- /dev/null +++ b/tests/ui/gtk_desktop.matrix @@ -0,0 +1,122 @@ +book nil2.ui.desktop + +read nil.std.ui +read nil.std.testing +read nil.std.threading +read nil.std.core.option +read nil.std.core.result + +expect-ui-error of type T receives outcome as Result of T, text begin paragraph + consider outcome + when Result.Error holding failure then expect (the length of failure) is greater than 0 + when Result.Ok holding unexpected then expect no + end consider +end paragraph + +expect-empty-queue receives surface as Window begin paragraph + variable checks as number is 0 + repeat while checks is less than 3 + value pending is require-ok of PendingEvent, text with (poll-event with surface), "poll quiet window" + consider pending + when Option.None then expect yes + when Option.Some holding unexpected then expect no + end consider + evaluate sleep-ms with 5 + set checks to checks plus 1 + end repeat +end paragraph + +next-event receives surface as Window returns Event begin paragraph + variable attempts as number is 0 + repeat while attempts is less than 200 + value pending is require-ok of PendingEvent, text with (poll-event with surface), "poll activated widget" + consider pending + when Option.Some holding notification then give notification + when Option.None then evaluate sleep-ms with 5 + end consider + set attempts to attempts plus 1 + end repeat + evaluate panic with "GTK widget activation did not produce an event" +end paragraph + +note suite "nil.std.ui.gtk.desktop" +widgets_layout_and_model_binding begin test + expect available with nothing + value surface is require-ok of Window, text with (create-window with "NIL2 desktop contract", 460, 300), "create desktop window" + value root is window-root with surface + value column is require-ok of Widget, text with (create-column with root), "create column" + value row is require-ok of Widget, text with (create-row with column), "create row" + value label is require-ok of Widget, text with (create-label with row, "before"), "create label" + value button is require-ok of Widget, text with (create-button with row, "Click"), "create button" + value grid is require-ok of Widget, text with (create-grid with column), "create grid" + value entry is require-ok of Widget, text with (create-entry with grid, "initial"), "create entry" + value checkbox is require-ok of Widget, text with (create-checkbox with grid, "Enabled"), "create checkbox" + evaluate require-ok of boolean, text with (attach-grid with grid, entry, 0, 0, 2, 1), "attach entry" + evaluate require-ok of boolean, text with (attach-grid with grid, checkbox, 0, 1, 2, 1), "attach checkbox" + evaluate require-ok of boolean, text with (set-margin with column, 12), "set margin" + evaluate require-ok of boolean, text with (set-spacing with column, 6), "set column spacing" + evaluate require-ok of boolean, text with (set-spacing with row, 8), "set row spacing" + evaluate require-ok of boolean, text with (set-spacing with grid, 4), "set grid spacing" + evaluate require-ok of boolean, text with (set-expansion with entry, yes, no), "set expansion" + evaluate require-ok of boolean, text with (set-sensitive with button, no), "disable button" + evaluate require-ok of boolean, text with (set-sensitive with button, yes), "enable button" + evaluate require-ok of boolean, text with (set-visible with label, no), "hide label" + evaluate require-ok of boolean, text with (set-visible with label, yes), "show label" + evaluate require-ok of boolean, text with (set-widget-text with label, "NIL²"), "change label" + expect (require-ok of text, text with (widget-text with label), "read label") equals "NIL²" + evaluate require-ok of boolean, text with (show-window with surface), "show desktop window" + + value name is create-text-model with "initial" + value flag is create-flag-model with no + expect not (require-ok of boolean, text with (sync-text with entry, name), "sync equal text") + expect not (require-ok of boolean, text with (sync-flag with checkbox, flag), "sync equal flag") + expect update-text-model with name, "Matrix" + expect update-flag-model with flag, yes + expect require-ok of boolean, text with (sync-text with entry, name), "sync changed text" + expect require-ok of boolean, text with (sync-flag with checkbox, flag), "sync changed flag" + expect (require-ok of text, text with (widget-text with entry), "read entry") equals "Matrix" + expect require-ok of boolean, text with (widget-checked with checkbox), "read checkbox" + evaluate expect-empty-queue with surface + + evaluate require-ok of boolean, text with (activate-widget with button), "activate button" + value click is next-event with surface + expect is-click with click + expect event-for with click, button + expect not (apply-text-event with name, entry, click) + expect not (apply-flag-event with flag, checkbox, click) + evaluate require-ok of boolean, text with (activate-widget with checkbox), "activate checkbox" + value toggled is next-event with surface + expect is-toggle with toggled + expect event-for with toggled, checkbox + expect not toggled.checked + expect apply-flag-event with flag, checkbox, toggled + expect not flag.enabled + evaluate require-ok of boolean, text with (set-checked with checkbox, yes), "set after snapshot" + expect not toggled.checked + evaluate expect-empty-queue with surface + + evaluate expect-ui-error of boolean with (set-margin with column, -1) + evaluate expect-ui-error of boolean with (set-spacing with row, 4097) + evaluate expect-ui-error of boolean with (set-checked with label, yes) + evaluate expect-ui-error of boolean with (attach-grid with grid, button, 0, 0, 1, 1) + evaluate expect-ui-error of boolean with (attach-grid with grid, entry, 0, 0, 0, 1) + evaluate require-ok of boolean, text with (close-window with surface), "close desktop window" + evaluate expect-ui-error of text with (widget-text with entry) + evaluate expect-ui-error of boolean with (close-window with surface) + evaluate expect-ui-error of PendingEvent with (poll-event with surface) + expect is-click with click + expect click.window.handle equals surface.handle +end test + +note suite "nil.std.ui.gtk.desktop" +window_ownership_and_size_errors begin test + evaluate expect-ui-error of Window with (create-window with "invalid size", 0, 200) + value first is require-ok of Window, text with (create-window with "NIL2 first owner", 320, 180), "create first owner" + value second is require-ok of Window, text with (create-window with "NIL2 second owner", 320, 180), "create second owner" + value grid is require-ok of Widget, text with (create-grid with (window-root with first)), "create owned grid" + value foreign is require-ok of Widget, text with (create-label with (window-root with second), "other window"), "create other child" + evaluate expect-ui-error of boolean with (attach-grid with grid, foreign, 0, 0, 1, 1) + evaluate require-ok of boolean, text with (close-window with first), "close first owner" + expect (require-ok of text, text with (widget-text with foreign), "second owner remains live") equals "other window" + evaluate require-ok of boolean, text with (close-window with second), "close second owner" +end test diff --git a/tests/ui/gtk_interaction.matrix b/tests/ui/gtk_interaction.matrix new file mode 100644 index 00000000..239c3ff6 --- /dev/null +++ b/tests/ui/gtk_interaction.matrix @@ -0,0 +1,78 @@ +book nil2.ui.interaction + +read nil.std.ui +read nil.std.testing +read nil.std.threading +read nil.std.core.option +read nil.std.core.result + +note suite "nil.std.ui.gtk.interaction" +keyboard_events begin test + value surface is require-ok of Window, text with (create-window with "NIL2 UI keyboard probe", 420, 240), "create keyboard probe" + value root is window-root with surface + value entry is require-ok of Widget, text with (create-entry with root, ""), "create entry" + value checkbox is require-ok of Widget, text with (create-checkbox with root, "Enable setting"), "create checkbox" + value button is require-ok of Widget, text with (create-button with root, "Finish probe"), "create button" + evaluate require-ok of boolean, text with (show-window with surface), "show keyboard probe" + evaluate require-ok of boolean, text with (focus-widget with entry), "focus probe entry" + variable saw-text as boolean is no + variable saw-toggle as boolean is no + variable saw-click as boolean is no + variable attempts as number is 0 + repeat while attempts is less than 2000 and not saw-click + value pending is require-ok of PendingEvent, text with (poll-event with surface), "poll keyboard probe" + consider pending + when Option.None then evaluate sleep-ms with 10 + when Option.Some holding notification then begin block + when (is-text-change with notification) and (event-for with notification, entry) and notification.content equals "Matrix" then + set saw-text to yes + otherwise when (is-toggle with notification) and (event-for with notification, checkbox) and notification.checked then + set saw-toggle to yes + otherwise when (is-click with notification) and (event-for with notification, button) then + set saw-click to yes + end when + end block + end consider + set attempts to attempts plus 1 + end repeat + evaluate require-ok of boolean, text with (close-window with surface), "close keyboard probe" + expect saw-text + expect saw-toggle + expect saw-click + say "NIL2 UI interaction passed" +end test + +note suite "nil.std.ui.gtk.interaction" +close_request begin test + value surface is require-ok of Window, text with (create-window with "NIL2 UI close probe", 360, 160), "create close probe" + value root is window-root with surface + value label is require-ok of Widget, text with (create-label with root, "Close this window through the window manager."), "create close label" + evaluate require-ok of boolean, text with (show-window with surface), "show close probe" + variable saw-close as boolean is no + variable no-widget-target as boolean is no + variable attempts as number is 0 + repeat while attempts is less than 2000 and not saw-close + value pending is require-ok of PendingEvent, text with (poll-event with surface), "poll close probe" + consider pending + when Option.None then evaluate sleep-ms with 10 + when Option.Some holding notification then begin block + when is-close-request with notification then + set saw-close to yes + consider notification.target + when Option.None then set no-widget-target to yes + when Option.Some holding unexpected then set no-widget-target to no + end consider + end when + end block + end consider + set attempts to attempts plus 1 + end repeat + evaluate require-ok of boolean, text with (close-window with surface), "close close probe" + expect saw-close + expect no-widget-target + consider widget-text with label + when Result.Error holding failure then expect (the length of failure) is greater than 0 + when Result.Ok holding unexpected then expect no + end consider + say "NIL2 UI close passed" +end test diff --git a/tests/ui_lifecycle_tests.cpp b/tests/ui_lifecycle_tests.cpp new file mode 100644 index 00000000..5cf89d5c --- /dev/null +++ b/tests/ui_lifecycle_tests.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#include "codegen.hpp" +#include "native_runtime.hpp" +#include "nil_loader.hpp" +#include "ui_runtime.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__linux__) +#include +#endif + +namespace { +int checks = 0; +void require(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} + +#if defined(__linux__) +// 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. +struct Windows { + void *library = nullptr; + void *(*list)() = nullptr; + unsigned (*size)(void *) = nullptr; + unsigned baseline = 0; + + Windows() { + require(ny::ui::available(), "GTK 4 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"); + library = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); + require(library != nullptr, "load GTK registry observer"); + list = reinterpret_cast(dlsym(library, "gtk_window_get_toplevels")); + size = reinterpret_cast(dlsym(library, "g_list_model_get_n_items")); + require(list && size, "GTK registry observer symbols"); + baseline = count(); + } + ~Windows() { if (library) dlclose(library); } + unsigned count() const { return size(list()); } + void live(const std::string &operation) const { + require(count() == baseline + 1, operation + " must keep exactly one GTK window live"); + } + void empty(const std::string &operation) const { + require(count() == baseline, operation + " must release its GTK window"); + } +}; + +const std::string number_result = "nil::std::core::Result"; +const std::string text_result = "nil::std::core::Result"; +ny::nil_function function(std::string name, std::vector parameters, + std::string result, std::vector body) { + ny::nil_function value; + value.name = std::move(name); value.params = std::move(parameters); + value.return_type = std::move(result); value.body = std::move(body); + return value; +} + +struct Program { + std::vector code; + std::unordered_map constants; +}; +Program fixture(bool binary, bool fault) { + ny::nil_module module; + module.module_name = "ui_lifecycle"; + module.enums = {{number_result, {{"Ok", "i64"}, {"Error", "text"}}}, + {text_result, {{"Ok", "text"}, {"Error", "text"}}}}; + module.string_constants = {{"title", "UI lifecycle VM window"}}; + module.functions.push_back(function("open_window", {"title:text", "width:i64", "height:i64"}, number_result, + {{"STORE_LOCAL", {"height"}}, {"STORE_LOCAL", {"width"}}, {"STORE_LOCAL", {"title"}}, + {"LOAD_LOCAL", {"title"}}, {"LOAD_LOCAL", {"width"}}, {"LOAD_LOCAL", {"height"}}, + {"INTEROP_CALL", {"intrinsic", "ui.v1.window", "3", number_result}}, {"RET", {}}})); + module.functions.push_back(function("read_window", {"handle:i64"}, text_result, + {{"STORE_LOCAL", {"handle"}}, {"LOAD_LOCAL", {"handle"}}, + {"INTEROP_CALL", {"intrinsic", "ui.v1.read_text", "1", text_result}}, {"RET", {}}})); + std::vector body{ + {"PUSH_CONST_STR", {"title"}}, {"PUSH_CONST", {"240"}}, {"PUSH_CONST", {"120"}}, + {"CALL", {"open_window", "3"}}, {"UNWRAP_VARIANT", {"1", number_result, "i64"}}, + {"STORE_GLOBAL", {"opened", "i64"}}}; + if (fault) { + body.push_back({"PUSH_CONST", {"1"}}); + body.push_back({"PUSH_CONST", {"0"}}); + body.push_back({"DIV", {"i64"}}); + } else body.push_back({"PUSH_CONST", {"0"}}); + body.push_back({"RET", {}}); + module.functions.push_back(function("main", {}, "i64", std::move(body))); + + std::ostringstream serialized(std::ios::out | std::ios::binary); + if (binary) { + ny::codegen_options options; + ny::nil_binary_writer writer(serialized, options); writer.emit_binary_module(module); + } else { + ny::nil_writer writer(serialized); writer.emit_text_module(module); + } + std::istringstream input(serialized.str(), std::ios::in | std::ios::binary); + Program result; + result.code = binary ? ny::parseBinaryProgram(input, result.constants) + : ny::parseProgram(input, result.constants); + return result; +} + +std::int64_t pause_with_window(ny::VM &vm, const Program &program, const Windows &windows) { + vm.loadProgram(program.code, program.constants); + vm.resetExecution("main"); + for (unsigned step = 0; step < 100 && !vm.hasGlobal("opened"); ++step) + require(vm.stepInstruction(), "VM ended before storing the live window handle"); + require(vm.hasGlobal("opened"), "VM must reach the UI lifecycle pause"); + const auto handle = std::get(vm.getGlobal("opened")); + require(handle > 0, "UI window creation must return a positive handle"); + require(vm.getDebugState() == ny::VM::DebugState::PAUSED, "window fixture must be debugger-paused"); + windows.live("debugger pause"); + return handle; +} + +void stale_vm_handle(ny::VM &vm, std::int64_t handle) { + vm.pushValue(handle); + vm.callFunction("read_window", 1); + require(!vm.getStack().empty(), "stale VM read must return its Result"); + const auto *result = std::get_if(&vm.getStack().back()); + require(result && result->variant_name == "Result::Error" && result->payloads.size() == 1, + "VM invocation boundary must invalidate the previous window handle"); + const auto *error = std::get_if(&result->payloads.front()); + require(error && error->find("closed") != std::string::npos, "VM stale handle error must explain closure"); +} + +void vm_lifecycles(const Windows &windows) { + for (bool binary : {false, true}) { + const auto normal = fixture(binary, false); + const auto failing = fixture(binary, true); + { + ny::VM vm; + auto handle = pause_with_window(vm, normal, windows); + vm.execute(false); + windows.empty("VM normal completion"); + stale_vm_handle(vm, handle); + + (void)pause_with_window(vm, normal, windows); + vm.resetExecution("main"); + windows.empty("VM debugger reset"); + require(!vm.hasGlobal("opened"), "debugger reset must clear the previous program globals"); + + handle = pause_with_window(vm, normal, windows); + vm.loadProgram(normal.code, normal.constants); + windows.empty("VM program reload"); + stale_vm_handle(vm, handle); + + (void)pause_with_window(vm, failing, windows); + bool caught = false; + try { vm.execute(false); } + catch (const std::runtime_error &error) { + caught = std::string(error.what()).find("Division by zero") != std::string::npos; + } + require(caught, "VM must actually execute and report the division fault"); + windows.empty("VM uncaught runtime fault"); + } + { + auto vm = std::make_unique(); + (void)pause_with_window(*vm, normal, windows); + vm.reset(); + windows.empty("paused VM destruction"); + } + } +} + +std::int64_t native_window() { + std::int64_t handle = 0; + const char *error = nullptr; + const auto status = nyrt_ui_v1_window("UI lifecycle native window", 240, 120, &handle, &error); + require(status == 1 && handle > 0 && !error, error ? error : "native window result"); + return handle; +} +void stale_native_handle(std::int64_t handle) { + const char *value = nullptr, *error = nullptr; + require(nyrt_ui_v1_read_text(handle, &value, &error) == 0 && !value && error && + std::string(error).find("closed") != std::string::npos, + "native context boundary must invalidate the previous window handle"); +} +void native_lifecycles(const Windows &windows) { + nyrt_context_begin(0, nullptr); + auto handle = native_window(); + windows.live("native invocation"); + // A recoverable provider Result error must not destroy the valid window. + stale_native_handle(-1); + windows.live("recoverable native provider error"); + const char *value = nullptr, *error = nullptr; + require(nyrt_ui_v1_read_text(handle, &value, &error) == 1 && value && !error, + "native live window title read"); + const void *roots[] = {&value}; + nyrt_roots_enter(roots, 1); + nyrt_collect(); + require(std::string(value) == "UI lifecycle native window", "native UI text must survive collection while rooted"); + std::int64_t changed = 0; + require(nyrt_ui_v1_set_text(handle, "Changed title", &changed, &error) == 1 && changed == 1, + "native UI title mutation"); + require(std::string(value) == "UI lifecycle native window", "native UI reads must copy provider text"); + nyrt_roots_leave(roots); + nyrt_context_end(); + windows.empty("native invocation completion"); + stale_native_handle(handle); + + nyrt_context_begin(0, nullptr); + handle = native_window(); + windows.live("native invocation before restart"); + nyrt_context_begin(0, nullptr); + windows.empty("native invocation restart"); + stale_native_handle(handle); + nyrt_context_end(); + windows.empty("idempotent native completion"); +} +#endif +} // namespace + +int main(int argc, char **argv) { + try { + require(argc == 2 && std::string(argv[1]) == "--display", + "usage: nil_ui_lifecycle_tests --display (requires an isolated display)"); +#if defined(__linux__) + Windows windows; + vm_lifecycles(windows); + native_lifecycles(windows); + std::cout << "UI lifecycle: " << checks << " checks passed\n"; + return 0; +#else + std::cerr << "SKIP: GTK UI lifecycle tests require Linux\n"; + return 77; +#endif + } catch (const std::exception &error) { + std::cerr << "UI lifecycle test failure: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/ui_runtime_tests.cpp b/tests/ui_runtime_tests.cpp new file mode 100644 index 00000000..3ec7e44d --- /dev/null +++ b/tests/ui_runtime_tests.cpp @@ -0,0 +1,222 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#include "ui_runtime.hpp" + +#include +#include +#include +#include +#include +#include +#include +#if defined(__linux__) +#include +#endif + +namespace { +int checks = 0; +void require(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} +std::int64_t ok(const ny::ui::Result &result) { + require(static_cast(result), result.error); + return result.number; +} +void rejected(const ny::ui::Result &result, const std::string &message) { + require(!result && result.error.find(message) != std::string::npos, + "expected rejection containing '" + message + "', got '" + result.error + "'"); +} +std::int64_t wait_event(ny::ui::Context &context, std::int64_t window) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(3); + while (std::chrono::steady_clock::now() < deadline) { + const auto event = ok(context.poll(window)); + if (event) return event; + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + throw std::runtime_error("timed out waiting for GTK activation event"); +} +void basic_validation() { + ny::ui::Context context; + rejected(context.window("invalid", 0, 100), "between 1 and 16384"); + rejected(context.window("invalid", 100, 16385), "between 1 and 16384"); + rejected(context.window(std::string("bad\0title", 9), 100, 100), "without NUL"); + rejected(context.window(std::string("\xc0\x80", 2), 100, 100), "UTF-8"); + rejected(context.window(std::string("\xed\xa0\x80", 3), 100, 100), "UTF-8"); + rejected(context.window(std::string("\xf4\x90\x80\x80", 4), 100, 100), "UTF-8"); + rejected(context.window(std::string(1048577, 'x'), 100, 100), "1048576"); + rejected(context.read_text(1), "foreign"); + rejected(context.set_number(-1, "checked", 1), "foreign"); + rejected(context.event_text(1), "snapshot"); + rejected(context.release_event(1), "snapshot"); + ny::ui::Result wrong_thread; + std::thread worker([&] { wrong_thread = context.poll(1); }); worker.join(); + rejected(wrong_thread, "creation thread"); +} + +void no_display() { +#if defined(__linux__) + // This mode is deliberately independent of the developer's desktop. + unsetenv("WAYLAND_DISPLAY"); + setenv("DISPLAY", ":65534", 1); + setenv("GDK_BACKEND", "x11", 1); +#endif + ny::ui::Context context; + auto result = context.window("unavailable display", 300, 200); + rejected(result, ny::ui::available() ? "display" : "provider"); +} + +void display_tests() { + require(ny::ui::available(), "GTK 4 provider is required for --display tests"); + ny::ui::Context context; + auto window = ok(context.window("NIL UI provider contract", 420, 320)); + require(window > 0, "window must have a nonzero handle"); + require(ok(context.read_number(window, "visible")) == 0, "window must start hidden"); + require(ok(context.read_number(window, "width")) == 420, "hidden window width"); + require(ok(context.read_number(window, "height")) == 320, "hidden window height"); + auto column = ok(context.widget("column", window, "")); + auto row = ok(context.widget("row", column, "")); + auto label = ok(context.widget("label", row, "NIL — Matrix ✓")); + auto entry = ok(context.widget("entry", column, "naïve 🌍")); + auto checkbox = ok(context.widget("checkbox", column, "Enabled")); + auto button = ok(context.widget("button", column, "Apply")); + auto grid = ok(context.widget("grid", column, "")); + auto first = ok(context.widget("label", grid, "First")); + auto second = ok(context.widget("label", grid, "Second")); + require(ok(context.read_number(entry, "kind")) == 6, "entry kind code"); + require(ok(context.read_number(entry, "parent")) == column, "parent identity"); + require(context.read_text(entry).text == "naïve 🌍", "entry text UTF-8 roundtrip"); + require(context.read_text(label).text == "NIL — Matrix ✓", "label text UTF-8 roundtrip"); + rejected(context.widget("unsupported", column, ""), "widget kind"); + rejected(context.widget("button", label, "bad parent"), "parent must"); + rejected(context.set_text(row, "not text"), "container"); + rejected(context.widget("entry", column, std::string(16385, 'a')), "16384"); + rejected(context.set_text(entry, std::string(16385, 'a')), "16384"); + rejected(context.set_text(entry, std::string("bad\0entry", 9)), "without NUL"); + rejected(context.set_text(entry, std::string("\xf0\x80", 2)), "UTF-8"); + require(context.read_text(entry).text == "naïve 🌍", "rejected setter must preserve text"); + rejected(context.set_number(checkbox, "checked", 2), "exactly 0 or 1"); + require(ok(context.read_number(checkbox, "checked")) == 0, "invalid Boolean must not mutate"); + rejected(context.set_number(label, "checked", 1), "checkbox"); + rejected(context.read_number(label, "checked"), "checkbox"); + rejected(context.set_number(label, "width", 100), "window properties"); + rejected(context.set_number(button, "spacing", 5), "spacing requires"); + rejected(context.set_number(column, "margin", -1), "between 0 and 4096"); + rejected(context.set_number(column, "unknown", 1), "unknown"); + rejected(context.read_number(column, "unknown"), "unknown"); + rejected(context.set_number(entry, "focus", 0), "only 1"); + ok(context.set_number(column, "spacing", 8)); + require(ok(context.read_number(column, "spacing")) == 8, "container spacing"); + ok(context.set_number(column, "margin_start", 3)); + rejected(context.read_number(column, "margin"), "margins differ"); + ok(context.set_number(column, "margin", 12)); + require(ok(context.read_number(column, "margin_start")) == 12, "uniform margin overrides earlier side"); + require(ok(context.read_number(column, "margin")) == 12, "uniform margin read"); + ok(context.set_number(entry, "hexpand", 1)); + require(ok(context.read_number(entry, "hexpand")) == 1, "expansion property"); + ok(context.grid_attach(grid, second, 1, 0, 1, 1)); + rejected(context.grid_attach(grid, first, 1, 0, 1, 1), "overlaps"); + rejected(context.grid_attach(grid, first, 65535, 0, 2, 1), "coordinates"); + rejected(context.grid_attach(grid, button, 3, 0, 1, 1), "child of"); + + // Setters update actual toolkit state without feeding back user change events. + ok(context.set_text(entry, "Matrix")); + ok(context.set_number(checkbox, "checked", 1)); + require(context.read_text(entry).text == "Matrix", "programmatic entry update"); + require(ok(context.read_number(checkbox, "checked")) == 1, "programmatic checkbox update"); + require(ok(context.poll(window)) == 0, "programmatic setters must suppress feedback"); + ok(context.set_number(window, "visible", 1)); + ok(context.set_number(entry, "focus", 1)); + for (int index = 0; index < 20; ++index) { + require(ok(context.poll(window)) == 0, "window rendering should not synthesize control events"); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + require(ok(context.read_number(entry, "width")) > 0, "GTK must allocate entry width"); + + ok(context.activate(checkbox)); + auto snapshot = wait_event(context, window); + require(ok(context.event_number(snapshot, "kind")) == 3, "real checkbox activation event"); + require(ok(context.event_number(snapshot, "checked")) == 0, "checkbox toggles from active to false"); + require(ok(context.event_number(snapshot, "target")) == checkbox, "event identifies checkbox"); + require(ok(context.event_number(snapshot, "window")) == window, "event identifies window"); + ok(context.set_number(checkbox, "checked", 1)); + require(ok(context.event_number(snapshot, "checked")) == 0, "snapshot survives later state changes"); + rejected(context.event_number(snapshot, "unknown"), "event field"); + ok(context.release_event(snapshot)); + rejected(context.release_event(snapshot), "released"); + rejected(context.event_text(snapshot), "released"); + + ok(context.set_number(button, "sensitive", 0)); + rejected(context.activate(button), "insensitive"); + ok(context.set_number(button, "sensitive", 1)); + ok(context.set_number(column, "sensitive", 0)); + rejected(context.activate(button), "insensitive container"); + rejected(context.activate(checkbox), "insensitive container"); + require(ok(context.poll(window)) == 0, "disabled ancestor must prevent activation events"); + ok(context.set_number(column, "sensitive", 1)); + ok(context.activate(button)); + snapshot = wait_event(context, window); + require(ok(context.event_number(snapshot, "kind")) == 1, "real button activation event"); + require(ok(context.event_number(snapshot, "target")) == button, "button event target"); + require(context.event_text(snapshot).text.empty(), "button event has no invented text"); + + ny::ui::Context other; + rejected(other.read_text(entry), "foreign"); + rejected(other.event_text(snapshot), "foreign"); + ny::ui::Result thread_error; + std::thread foreign_thread([&] { + ny::ui::Context foreign_context; + thread_error = foreign_context.window("Wrong thread", 100, 100); + }); foreign_thread.join(); + rejected(thread_error, "process UI thread"); + + ok(context.close(window)); + rejected(context.close(window), "closed"); + rejected(context.read_text(entry), "closed"); + rejected(context.event_text(snapshot), "snapshot"); + const auto replacement = ok(context.window("Fresh handles", 200, 100)); + require(replacement != window, "closed handles must never be reused"); + context.clear(); + rejected(context.poll(replacement), "closed"); + +#if defined(__linux__) + // Observe GTK's actual top-level registry across normal and deferred teardown. + void *library = dlopen("libgtk-4.so.1", RTLD_NOW | RTLD_LOCAL); + auto windows = reinterpret_cast(dlsym(library, "gtk_window_get_toplevels")); + auto count = reinterpret_cast(dlsym(library, "g_list_model_get_n_items")); + require(windows && count, "GTK top-level list symbols"); + const auto baseline = count(windows()); + for (int index = 0; index < 8; ++index) { + auto owner = std::make_unique(); + const auto owned_window = ok(owner->window("Lifetime check", 150, 100)); + ok(owner->widget("button", owned_window, "Callback lifetime")); + require(count(windows()) == baseline + 1, "real GTK window registration"); + if (index % 2) { + std::thread destroy_elsewhere([moved = std::move(owner)]() mutable { moved.reset(); }); + destroy_elsewhere.join(); + // Any subsequent call on the process UI thread drains deferred teardown. + rejected(context.read_text(-1), "foreign"); + } else owner.reset(); + require(count(windows()) == baseline, "context teardown must release GTK top-level windows"); + } + dlclose(library); +#endif +} +} // namespace + +int main(int argc, char **argv) { + try { + require(argc <= 2, "usage: ui_runtime_tests [--no-display|--display]"); + const std::string mode = argc == 2 ? argv[1] : "--no-display"; + require(mode == "--no-display" || mode == "--display", "unknown UI test mode"); + basic_validation(); + if (mode == "--display") display_tests(); else no_display(); + std::cout << "UI runtime: " << checks << " checks passed (" << mode << ")\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "UI runtime test failure: " << error.what() << '\n'; + return 1; + } +} diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 58da6abd..6bb82bd6 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Highlight, indent and fold explicit Matrix `begin block` / `end block` + consider arms. The `consider` snippet now includes an explicit block so its + body can contain nested `when` conditions; `block` remains an ordinary name + outside the delimiter phrases. + - Highlight `anything`, `boolean`/`flag`, and `yes`/`no` in Ny and Matrix. Infer Matrix Boolean literals for member completion and keep `flag` usable as an ordinary binding name outside type positions. diff --git a/vscode/language-configuration.matrix.json b/vscode/language-configuration.matrix.json index 17c1ed41..d133e208 100644 --- a/vscode/language-configuration.matrix.json +++ b/vscode/language-configuration.matrix.json @@ -58,12 +58,12 @@ ], "wordPattern": "[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*(?:-[A-Za-z\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)*|-?0[xX][0-9A-Fa-f]+|-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", "indentationRules": { - "increaseIndentPattern": "^[ \\t]*(?:(?:[^!\"`]|\"[^\"\\r\\n]*\"|`[^`\\r\\n]*`)*(? { + const grammar = await loadMatrixGrammar(); + for (const line of ["when Result.Ok holding found then begin block", "END BLOCK", "otherwise BeGiN BlOcK"]) { + const fragment = line.match(/block/i)![0]; + assertScope(grammar, line, fragment, "keyword.control.block"); + } + for (const name of ["block", "block-value", "begin-block", "end-block", "`block`"]) + assertScope(grammar, "say " + name, name === "`block`" ? "block" : name, "variable.other.readwrite"); + for (const line of ['say "begin block"', "!!! end block", "say item.block", "say begin-block"]) { + const result = grammar.tokenizeLine(line, INITIAL); + assert.equal(result.tokens.some(token => token.scopes.includes("keyword.control.block.matrix")), false, line); + } + let state = INITIAL; + for (const line of ["consider outcome", "when Result.Ok holding found then begin block", + "when found then", "say \"end block\"", "end when", "end block", "when Result.Error holding failure then say failure", "end consider"]) + state = grammar.tokenizeLine(line, state).ruleStack; + const after = grammar.tokenizeLine("say block", state); + assert.ok(scopesAt(after, "say block", "block").includes("variable.other.readwrite.matrix")); + + const config = JSON.parse(fs.readFileSync("language-configuration.matrix.json", "utf8")) as { + indentationRules: { increaseIndentPattern: string; decreaseIndentPattern: string }; + folding: { markers: { start: string; end: string } }; + }; + const increase = new RegExp(config.indentationRules.increaseIndentPattern); + const decrease = new RegExp(config.indentationRules.decreaseIndentPattern); + const foldStart = new RegExp(config.folding.markers.start); + const foldEnd = new RegExp(config.folding.markers.end); + for (const line of ["when Result.Ok holding found then begin block", "otherwise BEGIN BLOCK !!! fallback"]) { + assert.ok(increase.test(line), line); + assert.ok(foldStart.test(line), line); + } + assert.ok(decrease.test(" end block")); + assert.ok(foldEnd.test(" END BLOCK")); + for (const line of ['say "begin block"', "value begin-block is 1", "when yes then begin block say 1 end block"]) { + assert.equal(increase.test(line), false, line); + assert.equal(foldStart.test(line), false, line); + } +}); + test("Matrix prose patterns fold keywords, preserve capture names and nest safely", async () => { const grammar = await loadMatrixGrammar(); const opened = grammar.tokenizeLine("price-pattern BEGIN PATTERN", INITIAL); @@ -413,6 +452,8 @@ test("Matrix snippets use current paragraph, type, text, and extension spellings assert.match(snippets["Paragraph"]!.body.join("\n"), /give \$\{2:argument\}/); assert.match(snippets["Variable binding"]!.body.join("\n"), /is \$\{3:0\}/); assert.deepEqual(snippets["Raw text block"]!.body, ["begin text", " ${0:text}", "end text"]); + assert.deepEqual(snippets["Consider block"]!.body, ["consider ${1:subject}", + " when ${2:pattern} then begin block", " ${0}", " end block", "end consider"]); assert.deepEqual(snippets["Formatted text"]!.body, ['formatted "${1:Height}: {${2:height}}"']); assert.deepEqual(snippets["Metadata annotation"]!.body, ['@${1:custom}(${2:key}=${3:true})']); assert.deepEqual(snippets["Prose metadata annotation"]!.body, ['note ${1:custom} with ${2:key} being ${3:true}']); diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index d740c5c8..982a2ae9 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -364,6 +364,18 @@ }, "keywords": { "patterns": [ + { + "match": "((?