# oneplatform docs, all pages (OnePlatform 1.0.0) Every page of https://recursiveai.org/oneplatform/docs/ as markdown, getting started first. Index: https://recursiveai.org/oneplatform/llms.txt # Getting started with OnePlatform Open a window and run its event loop, then drive a window with no display at all, the way a test does. This guide was run on the 1.0.0 package from NuGet, on Linux: the window on X11 (a private Xvfb display), the test on the headless backend. ## Install You need the .NET 10 SDK. Make a console project and add the package: ```shell dotnet new console -n Hello cd Hello dotnet add package RecursiveAI.OnePlatform --version 1.0.0 ``` The package depends only on the .NET base class library. It talks to each operating system through that system’s own API: Win32 on Windows, Cocoa on macOS, Wayland or X11 on Linux. ## Open a window Replace `Program.cs` with: ```csharp using OnePlatform; // Picks Wayland, X11, Win32, Cocoa... for this system. using var app = PlatformApp.Create(); var window = app.CreateWindow( new WindowOptions { Title = "Hello", Width = 800, Height = 600 }); Console.WriteLine($"Backend: {app.Backend}"); Console.WriteLine( $"Window {window.Id}: {window.Width} x {window.Height} px, " + $"scale {window.Scale}, {window.NativeHandle.Kind}"); // Stop after two seconds. Wake() is safe from any thread and ends the wait. var timeUp = false; using var timer = new Timer(_ => { Volatile.Write(ref timeUp, true); app.Wake(); }, null, 2000, Timeout.Infinite); var running = true; while (running) { // Sleeps until an event arrives, a wake, or a second passes. app.PumpEvents(1000); while (app.TryGetEvent(out var e)) { Console.WriteLine($" {e.Kind}"); if (e.Kind == PlatformEventKind.QuitRequested || e.Kind == PlatformEventKind.WindowCloseRequested) { running = false; } } if (Volatile.Read(ref timeUp)) { running = false; } } Console.WriteLine("Closed"); ``` Run it with `dotnet run`. On X11 it printed: ```text Backend: X11 Window 1: 800 x 600 px, scale 1, X11 PointerInside WindowFocusChanged Closed ``` `PlatformApp.Create()` picks the backend for the system it runs on: Wayland when `WAYLAND_DISPLAY` is set, otherwise X11 when `DISPLAY` is set, Win32 on Windows and Cocoa on macOS. Without the timer, the loop runs until the user closes the window (`WindowCloseRequested`) or the session asks the app to quit (`QuitRequested`). `window.NativeHandle` is the native window for a renderer: its `Kind`, `Display` and `Window`. `window.Width` and `Height` are physical pixels, and `window.Scale` converts them to logical units. Work that arrives on another thread calls `app.Wake()` to end the wait, as the timer does here. See [Waking the event loop](https://recursiveai.org/oneplatform/docs/waking-the-loop/). ## Drive a window in a test The headless backend needs no display: its windows are in-memory objects, and `app.Injector` sends them the input a user would. Replace `Program.cs` with: ```csharp using OnePlatform; // No display needed: the headless backend's windows are in-memory objects. using var app = PlatformApp.Create( new PlatformOptions { Backend = PlatformBackendKind.Headless }); var window = app.CreateWindow( new WindowOptions { Title = "Test", Width = 640, Height = 480 }); // Drive it the way a user would. var input = app.Injector; input.PointerMove(window.Id, 120, 80); input.PointerButton(window.Id, MouseButton.Left, true); input.PointerButton(window.Id, MouseButton.Left, false); input.Text(window.Id, "héllo"); input.KeyPress(window.Id, Key.Enter); input.CloseRequest(window.Id); app.PumpEvents(); while (app.TryGetEvent(out var e)) { var detail = e.Kind switch { PlatformEventKind.PointerMoved => $"{e.X}, {e.Y}", PlatformEventKind.PointerButtonDown or PlatformEventKind.PointerButtonUp => $"{e.Button}", PlatformEventKind.TextInput => $"\"{e.Text}\"", PlatformEventKind.KeyDown or PlatformEventKind.KeyUp => $"{e.Key}", _ => "", }; Console.WriteLine($"{e.Kind,-20} {detail}"); } app.Clipboard.SetText("copied"); Console.WriteLine($"Clipboard: {app.Clipboard.GetText()}"); ``` It printed: ```text PointerMoved 120, 80 PointerButtonDown Left PointerButtonUp Left TextInput "héllo" KeyDown Enter KeyUp Enter WindowCloseRequested Clipboard: copied ``` Injected input goes through the same queue and the same input state (`app.Input`) as real input, so the code under test reads it as it would on a desktop. `InputInjector` also has wheel, touch, IME composition, gamepad, lifecycle and back-button events, and the README lists it on every system. ## Next - [Desktop windows](https://recursiveai.org/oneplatform/docs/desktop-windows/): decorations, dialogs, overlays, popups, placement, activation, keep-on-top. - Desktop services on [Linux](https://recursiveai.org/oneplatform/docs/linux-shell/), [macOS](https://recursiveai.org/oneplatform/docs/macos-shell/) and [Windows](https://recursiveai.org/oneplatform/docs/windows-shell/): tray icon, notifications, file dialogs, global hotkeys. - [Accessibility](https://recursiveai.org/oneplatform/docs/accessibility/) and [Browser pages](https://recursiveai.org/oneplatform/docs/browser/). # RecursiveAI.OnePlatform Windows, input, IME, clipboard, DPI, displays, gamepads and the desktop shell for .NET applications on Windows, macOS, Linux (Wayland and X11), Android, iOS and the browser. It depends only on the .NET base class library, and is NativeAOT- and trim-compatible. - One `PlatformApp` per process owns the windows, the event queue and the input state. - Each operating system's own API is used directly: Win32, the Objective-C runtime for Cocoa and UIKit, Xlib and the Wayland client protocol on Linux, the NDK on Android, and a small script in the browser. - Desktop windows are decorated, movable and resizable by default, and can be dialogs, always-on-top overlays or popups. - Desktop services sit beside the windows: a D-Bus client and the Linux portals, the Windows and macOS equivalents (tray icon, notifications, file dialogs, global hotkeys, menu bar, screenshots, single-instance hand-over), and a window accessibility provider that is bridged to UI Automation on Windows and NSAccessibility on macOS. - A headless backend and `InputInjector` drive an app with no display, so tests can click, type and resize without a window. - Game controllers, haptics, input actions with rebinding, and text clipboard access are included. ## Support | | Windows | macOS | Linux | Android, iOS | Browser | |---|---|---|---|---|---| | Windows | Win32: ordinary windows, dialogs, overlays, popups, size limits, fullscreen | Cocoa: ordinary windows, dialogs, overlays, popups, size limits, fullscreen | Wayland (`xdg-decoration`, `wlr-layer-shell`, `xdg_popup`) and X11 (EWMH) | one window per activity or scene | one canvas | | Input | keyboard, mouse, touch, gamepads (XInput) | keyboard, mouse, trackpad, gamepads | keyboard, mouse, touch, gamepads (evdev) | touch, keyboard, gamepads | keyboard, mouse, touch, Gamepad API | | IME | `WM_IME_*` | `NSTextInputClient` | `text-input-v3` on Wayland; composed keys on X11 | system soft keyboard | page text input | | Clipboard (UTF-8 text) | yes | yes | yes (X11 primary selection too) | yes | yes | | DPI and displays | per-monitor v2 | backing scale | `wp_fractional_scale`, `wp_viewporter`, X11 scale | system scale | `devicePixelRatio` | | Shell services | `WindowsDesktop`: tray icon, notifications, file dialogs, global hotkeys, menu bar, screenshots; `LocalSingleInstance` | `MacDesktop`: menu bar, status item, file panels, notifications, hotkeys; `LocalSingleInstance` | portals and notification, tray and single-instance services over D-Bus | none | none | | D-Bus and portals | n/a | n/a | `DBusConnection`, `FileChooserPortal`, `ScreenshotPortal`, `GlobalShortcutsSession`, `NotificationService`, `TrayIcon`, `SingleInstance` | n/a | n/a | | Accessibility | UI Automation provider | NSAccessibility provider | provider model only | provider model only | provider model only | | Injection and capture | `InputInjector`; window and region capture | `InputInjector` | `InputInjector`; screenshot portal | `InputInjector` | `InputInjector` | "Provider model only" means `Window.Accessibility` keeps the provider and nothing reads it on that system (`WindowAccessibility.IsSupported` is false). The headless backend works everywhere and has no operating-system window. ## Getting started ```csharp using OnePlatform; using var app = PlatformApp.Create(); // picks Wayland, X11, Win32, Cocoa... for this system var window = app.CreateWindow(new WindowOptions { Title = "Hello", Width = 800, Height = 600 }); var running = true; while (running) { app.PumpEvents(1000); // sleeps until an event arrives or a second passes while (app.TryGetEvent(out var e)) { if (e.Kind == PlatformEventKind.QuitRequested || e.Kind == PlatformEventKind.WindowCloseRequested) { running = false; } } } ``` `window.NativeHandle` gives the native window or view for a renderer, `window.Width`/`Height` are physical pixels and `window.Scale` converts to logical units. For tests, create the app with `Backend = PlatformBackendKind.Headless` and drive it with `app.Injector`. ## Browser On `browser-wasm` the platform's page script, `oneplatform.js`, comes with the package: it is a static web asset, so a .NET WebAssembly app that references `RecursiveAI.OnePlatform` publishes it at `_content/RecursiveAI.OnePlatform/oneplatform.js` with nothing to copy. The app's page imports it and registers it under the module name `oneplatform` before the program starts; the window is the `` whose id is `PlatformOptions.DisplayName` (default `oneplatform-canvas`). ```js import { dotnet } from './_framework/dotnet.js'; import * as platform from './_content/RecursiveAI.OnePlatform/oneplatform.js'; const runtime = await dotnet.create(); runtime.setModuleImports('oneplatform', platform); await runtime.runMain(); ``` See [Browser pages](https://recursiveai.org/oneplatform/docs/browser/) for the canvas, the page functions and development control. ## Documentation - [Desktop windows](https://recursiveai.org/oneplatform/docs/desktop-windows/): decorations, dialogs, overlays, popups, placement, activation, keep-on-top. - [Linux desktop services](https://recursiveai.org/oneplatform/docs/linux-shell/): the D-Bus client, portals, notifications, tray, single instance. - [macOS desktop services](https://recursiveai.org/oneplatform/docs/macos-shell/) and [Windows desktop services](https://recursiveai.org/oneplatform/docs/windows-shell/). - [Accessibility](https://recursiveai.org/oneplatform/docs/accessibility/): the provider model and the UI Automation and NSAccessibility bridges. - [Browser pages](https://recursiveai.org/oneplatform/docs/browser/): loading `oneplatform.js` and the canvas. - [Waking the event loop](https://recursiveai.org/oneplatform/docs/waking-the-loop/): ending a blocking wait from another thread. - [Changelog](https://recursiveai.org/oneplatform/docs/changelog/) Licensed under MIT OR Apache-2.0. # Desktop windows How windows behave as desktop-app windows on Linux, and on macOS where the section says so. ## Ordinary windows `PlatformApp.CreateWindow(WindowOptions)` makes a decorated, movable, resizable window. | Option | Wayland | X11 | |---|---|---| | `Title` | `xdg_toplevel.set_title` | `_NET_WM_NAME` and `WM_NAME` | | `AppId` | `xdg_toplevel.set_app_id`, which the compositor matches to the app's `.desktop` file | `WM_CLASS` (instance and class) | | `MinWidth`..`MaxHeight`, `Window.SetSizeLimits` | `set_min_size`, `set_max_size` (a client-side title bar is added to the heights) | `WM_NORMAL_HINTS` | | `Parent` (dialog) | `xdg_toplevel.set_parent` | `WM_TRANSIENT_FOR` and the dialog window type | | `Decorations` | see below | `Auto` and `ClientSide`: the window manager; `None`: `_MOTIF_WM_HINTS` | `Window.Role` tells ordinary windows, dialogs, overlays and popups apart; `Window.Parent` names the parent. ### Frames on Wayland `DecorationPreference.Auto` asks the compositor for server-side decorations (`zxdg_decoration_manager_v1`, bound at version 1) and follows its answer. If the compositor does not offer the protocol, or answers `client_side`, the platform layer draws a frame: a title bar (title, minimize, maximize/restore, close) and an invisible 8-pixel resize border, built from four `wl_subsurface`s around the window's own surface, so the content, CPU or GPU drawn, is untouched. The frame needs `wl_subcompositor`; without it `Window.Decoration` is `DecorationKind.None`. The frame hands moves and resizes to the compositor (`xdg_toplevel.move` and `resize` with the serial of the click), opens the window menu on a right click (`show_window_menu`), maximizes on a double click, and sets resize cursors through `wp_cursor_shape_v1`. Closing sends `PlatformEventKind.WindowCloseRequested`; the program decides. `DecorationPreference.ClientSide` forces the client-side frame. `PlatformOptions.UseServerDecorations = false` does not bind the decoration protocol at all, which is how the no-manager path is exercised. `Window.Decoration` reports who draws the frame now. The size a program sees (`Window.Width`, `Height`, `WindowResized`) is always the content area, below the title bar. ## Overlays `WindowOptions.Overlay` makes a keep-on-top window (`OverlayOptions`: layer, anchors, margins, exclusive zone, keyboard behaviour). - Wayland: a `zwlr_layer_shell_v1` surface, bound at version 4. Layer `Overlay` or `Top`; the compositor answers with the final size. If the compositor lacks the protocol, `CreateWindow` throws `OverlayUnavailableException` ("zwlr_layer_shell_v1 not offered by the compositor ..."); with `OverlayOptions.FallbackToToplevel` it makes an ordinary window instead (`Role` is `Toplevel`). - X11: a window of type `_NET_WM_WINDOW_TYPE_DOCK` with `_NET_WM_STATE_ABOVE`, `SKIP_TASKBAR` and `SKIP_PAGER`, placed from the anchors and margins on the screen. Anchoring to opposite edges stretches it. A positive exclusive zone along one edge sets `_NET_WM_STRUT_PARTIAL`. The keyboard setting is ignored. Overlays have no frame (`Decoration` is `None`). ## Popups `PlatformApp.CreatePopup(parent, PopupOptions)` makes a menu, drop-down or tooltip attached to a rectangle of the parent (in the parent's pixels). - Wayland: an `xdg_popup` with an `xdg_positioner` (anchor rectangle, anchor, gravity, offset, constraint adjustment). A popup may also belong to another popup or to an overlay (`zwlr_layer_surface_v1.get_popup`). With `Grab` the popup needs a recent click or key press in the app; `popup_done` ends it. Clicks inside the app's own windows are the app's input; a click outside them dismisses the popup. - X11: an override-redirect window placed by `PopupPlacement` (the same arithmetic as the positioner, constrained to the screen) with an owner-events pointer grab; a press that no window of the app receives dismisses it. Keyboard input stays with the parent window. Dismissal posts `PlatformEventKind.PopupDismissed` with the popup's window id, then closes the popup. `Window.PositionInParent` is where the system put the popup, relative to the parent's content area, in pixels. ## macOS (Cocoa) - Ordinary windows are titled `NSWindow`s: the system draws the frame (`Decoration` is `ServerSide`; `Auto` and `ClientSide` are the same here, `None` is borderless). `Resizable = false` drops the resize control. `MinWidth`..`MaxHeight` and `SetSizeLimits` set `contentMinSize` and `contentMaxSize` (pixels divided by the scale). `AppId` has no AppKit counterpart. - A dialog (`Parent`) is a child window (`addChildWindow:ordered:`): above its parent, moving and minimizing with it. - An overlay is a borderless window at a window level: `Overlay` is `NSStatusWindowLevel`, `Top` is `NSFloatingWindowLevel`. It is on every Space, shown beside full-screen windows, not movable, and placed from the anchors and margins on the main screen without AppKit moving it clear of the menu bar. With `Keyboard = None` it never becomes the key window. `ExclusiveZone` is ignored. `CreateWindow` never throws `OverlayUnavailableException` on macOS. - A popup is a borderless child window at `NSPopUpMenuWindowLevel`, placed by `PopupPlacement` inside the parent screen's visible area, and never takes the keyboard. AppKit has no pointer grab, so with `Grab` the loop watches the global mouse buttons (about 60 times a second, only while such a popup is open): a press that lands outside every window of the app posts `PopupDismissed` and closes the popup. A press in one of the app's own windows is the app's input. - `StartMove`, `StartResize` and `ShowWindowMenu` do nothing: the system frame does its own moves. `FillSolid` sets the window layer's background colour, which shows wherever nothing has been presented. - `Activate` of a popup throws `ActivationUnavailableException`. ## Showing CPU pixels `Window.CanPresentPixels` says whether a window can show an image drawn by the CPU, for a program with no usable graphics device (or one that asks for CPU drawing). `Window.PresentPixels(bgra, width, height)` takes the window's client area as 4 bytes per pixel in blue, green, red, unused order, top row first, and the unused byte is ignored: the picture is opaque. | Backend | `CanPresentPixels` | |---|---| | Win32 | true (`SetDIBitsToDevice`; redrawn on `WM_PAINT`) | | Wayland toplevel, layer-shell and popup windows | true, when the compositor offers `wl_shm` (always, by the core protocol) | | X11, Cocoa, Android, iOS, browser | false; `PresentPixels` throws `NotSupportedException` | On Wayland the image is copied into one of a few reusable `wl_shm` buffers (XRGB8888), attached, damaged and committed; nothing is allocated per picture. A buffer the compositor still holds (until its `release` event) is never drawn into, so a window cycles through two or three buffers, and a fourth is made only if the compositor keeps all of them. A picture of a new size drops the old-size buffers as they are released. The surface is sized to the picture: its logical size is the pixel size divided by the window's scale (through `wp_viewport` where offered, `wl_surface.set_buffer_scale` otherwise), so pass the window's pixel size (`Window.Width` and `Window.Height`, which follow `WindowResized`) for a window that fills exactly. A picture presented before the first configure is kept and appears with it. The compositor keeps showing the last committed buffer, so nothing is drawn on a timer or frame callback: call `PresentPixels` when the picture changes, and an idle window costs no CPU. A popup's picture is committed after its first configure, like a window's, and its position and dismissal (`popup_done`) are unchanged. A configure or a scale change recommits the last picture without copying it again; the program is told about the new size through `WindowResized` and presents a picture of that size. ## Window icons A desktop normally takes a window's icon from the application's installed launcher entry (on Linux a `.desktop` file named by the app id, with an icon in the icon theme). An application that runs without being installed, such as an AppImage launched directly, has none, and the system shows a placeholder. `Window.SetIcon(images, name)` gives the window its own icon: pass one or more `IconImage` pictures (straight RGBA, top row first); a single square picture also supplies the smaller standard sizes (16, 22, 24, 32, 48, 64, 128 and 256 pixels that are below it). | Backend | `SetIcon` | |---|---| | Wayland toplevels | yes, through `xdg_toplevel_icon_manager_v1` (staging protocol; KWin 6.6 offers it) with one `wl_shm` buffer per square picture and the themed `name` when given; applied with the toplevel's next commit | | Wayland, a compositor without that protocol; popups and overlays | returns false: the icon comes from the installed launcher entry | | X11 | yes, `_NET_WM_ICON` | | Win32, Cocoa | returns false for now | The same pictures go to the tray icon: `TrayIcon.CreateAsync(connection, id, title, images)` publishes them as the StatusNotifierItem `IconPixmap` (each size as width, height and ARGB bytes in network byte order) and `SetIcon(images)` changes them and emits `NewIcon`. With no themed name the item's `IconName` is empty, so the host has only the pictures to draw; with a name it may prefer the themed icon, and a host that cannot resolve the name may draw nothing, so give a name only when the theme has it. Plasma on KWin 6.6 drew the pictures with an unresolvable name set; do not depend on that elsewhere. ## Several windows Any number of ordinary windows can be open; every event carries its window id, and closing one leaves the others alone. ## Moves and resizes started by the program `Window.StartMove()`, `StartResize(ResizeEdge)` and `ShowWindowMenu(x, y)` call from a pointer-button-down handler. On Wayland they quote the serial of the latest button or key press. On X11 `StartMove` and `StartResize` send `_NET_WM_MOVERESIZE`; `ShowWindowMenu` does nothing there. ## Bringing a window forward `Window.Activate(token)` raises a window, un-minimizes it and gives it the keyboard. Window systems refuse a program that tries this unprompted, so the request carries proof that a user action started it. - Wayland: `xdg_activation_v1`. A token from the launcher (`XDG_ACTIVATION_TOKEN`, or `ActivationRequest.ActivationToken` when a second launch forwarded it) is used as it is. Without one, the platform layer asks the compositor for a token tied to the window's surface and the latest input serial and activates when it arrives; the compositor may still refuse a window that has had no recent input and show a taskbar hint instead. A compositor without the protocol makes `Activate` throw `ActivationUnavailableException` whose `Requirement` is `xdg_activation_v1`. Popups cannot be activated. Wayland announces no minimized state, so `IsMinimized` is true after `Minimize()` and false again once the window is handed the focus. - X11: the token is a startup-notification id (`DESKTOP_STARTUP_ID`), stored as `_NET_STARTUP_ID`. A minimized window is mapped again (ICCCM), then `_NET_ACTIVE_WINDOW` goes to the root with source "application" and the time of the latest key or button press. With no window manager the window raises itself and takes the focus. - Win32: `ShowWindow(SW_RESTORE)` and `SetForegroundWindow`. Windows only lets the foreground process, or one it permitted, do that, so the second launch calls `WindowActivation.AllowForeground(firstInstanceProcessId)` before it exits. If Windows still refuses, the call retries with the foreground thread's input queue attached for a moment. - Cocoa: `deminiaturize:`, `activateIgnoringOtherApps:` and `makeKeyAndOrderFront:`. A second launch under a launcher inherits the token in its environment; `SingleInstance.Acquire` forwards it in `platform_data` (`activation-token`, `desktop-startup-id`) and the running instance passes `request.ActivationToken` to `Activate`. ## Keeping a window on top `Window.SetKeepAbove(bool)` is the toggle for an ordinary decorated window (not for overlays, which are placed with `WindowOptions.Overlay`). `Window.KeepAbove` is the state, and `Window.CanKeepAbove` says whether it can work right now. Where it cannot, `SetKeepAbove` throws `KeepAboveUnavailableException` (a `PlatformException`; `Requirement` names what is missing). Call all three on the UI thread. - X11: the `_NET_WM_STATE` client message with `_NET_WM_STATE_ABOVE` (EWMH). It needs a window manager; without one `CanKeepAbove` is false. `KeepAbove` is read back from the property, so a change the person makes in the window menu shows up. - Win32: `SetWindowPos` with `HWND_TOPMOST` or `HWND_NOTOPMOST`, without moving, sizing or activating; the state read back is the `WS_EX_TOPMOST` bit. - Cocoa: the window level, floating (3) or normal (0). - Headless: the state only. - Wayland: `xdg-toplevel` has no keep-above request, and there is no cross-compositor protocol for it. Under KWin, and only there, the platform layer uses KWin's scripting interface on the session bus (`org.kde.KWin`, `/Scripting`). Each change writes one small script into `XDG_RUNTIME_DIR`, loads and runs it, waits for its report, then unloads it and deletes the file, all before the call returns, so nothing stays loaded. The script finds windows whose `resourceClass` or `desktopFileName` equals the `WindowOptions.AppId` the window was created with and sets or clears their `keepAbove`; it reads no title or size and writes no other property. KWin gives a client no way to name one of its own windows, so every window of the same app id changes together. The call blocks for the answer (normally milliseconds; at most 3 s, then it throws). It throws the typed error when the session bus has no KWin (any other compositor), when scripting is refused, or when KWin knows no window with the app id yet (ask again once the window is shown). `CanKeepAbove` asks the bus whether KWin is there. ## Protocols Bound versions: `xdg_wm_base` 5, `zxdg_decoration_manager_v1` 1, `zwlr_layer_shell_v1` 4, `wl_subcompositor` 1, `wp_cursor_shape_manager_v1` 1, `xdg_activation_v1` 1, `xdg_toplevel_icon_manager_v1` 1 (when offered). Tables are generated by `tools/WaylandGen` from `tools/WaylandGen/protocols`. # Linux desktop services `OnePlatform.DBus` is a D-Bus client written from the D-Bus specification using only the .NET base library. `OnePlatform.Shell` builds the desktop services apps need on top of it. Everything is typed code: no reflection, no runtime code generation, trimmable and NativeAOT-clean. ## D-Bus client (`OnePlatform.DBus`) - `DBusConnection.ConnectSession()` / `Connect(address)`: `unix:path=` and `unix:abstract=` addresses (a `;` list is tried in order), SASL `EXTERNAL`, `Hello`. One reader thread blocks on the socket; nothing polls. - `Call` (blocking), `CallAsync`, `Send`, `EmitSignal`, `Subscribe` (match rules), `RequestName`/`ReleaseName`. - `Export(path, DBusInterfaceHandler)` serves method calls; `org.freedesktop.DBus.Properties`, `Introspectable` and `Peer` are answered by the connection. - `Dispatcher` is an `Action`: signal handlers, exported methods and `CallAsync` completions are passed to it so an app can run them on its UI thread. Left null, they run on the reader thread. - `DBusValue` is the typed value tree (all types, variants, structs, dictionaries). `DBusMessage.Parse` reads untrusted bytes with bounds checks, both byte orders, and throws only `DBusProtocolException`. Implemented from the specification: type system and signatures, marshalling and alignment, message and header-field format, the authentication handshake (`EXTERNAL`), name and match-rule handling on the message bus, the standard interfaces named above. Not implemented: Unix file descriptor passing (`h` values marshal as indices only), `DBUS_COOKIE_SHA1` authentication, TCP and `unixexec` transports, `systemd:` addresses, the server side of the bus. Messages are limited to 32 MiB. ## Services (`OnePlatform.Shell`) | Type | Interface | |---|---| | `SingleInstance` | `org.freedesktop.Application` on a bus name equal to the app id | | `FileChooserPortal` | `org.freedesktop.portal.FileChooser` | | `ScreenshotPortal` | `org.freedesktop.portal.Screenshot` | | `GlobalShortcutsSession` | `org.freedesktop.portal.GlobalShortcuts` | | `NotificationService` | `org.freedesktop.portal.Notification`, falling back to `org.freedesktop.Notifications` | | `TrayIcon` | `org.kde.StatusNotifierItem` with a `com.canonical.dbusmenu` menu, registered with the StatusNotifierWatcher; icon from a themed name, or from `IconImage` pictures published as `IconPixmap` (see `desktop-windows.md`, "Window icons") | A service or interface that is not on the bus throws `DBusServiceUnavailableException`, whose message names both, for example `org.freedesktop.portal.GlobalShortcuts not available on the session bus (service org.freedesktop.portal.Desktop).` ## Telling the portal which app is calling `xdg-desktop-portal` attributes each request to an application id. It works the id out from how the program was started (a `.desktop` activation or a systemd scope named `app-…`). A program started directly, such as an AppImage that was never installed or a build output, has neither, and the portal refuses global shortcuts with `org.freedesktop.portal.Error.NotAllowed: An app id is required`. The portal's `org.freedesktop.host.portal.Registry` interface lets a program that is not sandboxed declare its id on its own bus connection. Set `DBusConnection.PortalAppId` right after connecting; the first call made through `FileChooserPortal`, `ScreenshotPortal`, `GlobalShortcutsSession` or `NotificationService` on that connection registers it first (the portal accepts the call only before any other portal call, and only once). `DBusConnection.PortalRegistration` reports `Registered`, `Unavailable` (a portal without the interface: the calls behave as before) or `Failed` (the portal refused, with its reason). The portal only accepts an id that matches an `applications/.desktop` file in the user's or the system's data directories ("App info not found"). Set `DBusConnection.PortalCreateDesktopEntry = true` to have a hidden entry (`NoDisplay=true`, `Exec` the running program or `$APPIMAGE`, `Name` from `PortalAppName`) written to `$XDG_DATA_HOME/applications` first when none exists. It is never overwritten or removed, and nothing is written unless the app sets the property. The desktop shows `PortalAppName` in its shortcut dialog. When the portal still answers "An app id is required", the call throws `PortalAppIdRequiredException` (a `DBusException`; the portal's `DBusErrorException` is its `InnerException`) whose message says whether an id was declared and why registering did not work. `tests/OnePlatform.ShortcutProof` binds a shortcut this way from a directly started program. ## Tests Tests start their own `dbus-daemon` with a minimal configuration (no service activation) and pass its address explicitly; they skip when the daemon is not installed. The portals, the tray watcher and the notification server are fakes in the tests, written from the interface documentation. `tests/OnePlatform.DBusFuzz` is a mutation fuzzer for the message reader. # macOS desktop services `OnePlatform.Shell.MacDesktop` gives an app the parts of a Mac desktop that are not windows: the menu bar, a status item, file panels, notifications and global hotkeys. It is written against Apple's documented AppKit, UserNotifications and Carbon APIs, reached through the Objective-C runtime (`objc_msgSend` with typed signatures) and Carbon's C functions; nothing is bundled. It is the counterpart of the Linux services in `linux-shell.md` and uses their types wherever one fits, so an app drives both the same way. It needs macOS on Apple silicon. On any other system the constructor throws `ShellUnavailableException`. ## Using it ```csharp using var app = PlatformApp.Create(new PlatformOptions { Backend = PlatformBackendKind.Cocoa }); using var mac = new MacDesktop(post); // post: runs an action on the main thread, callable from any thread ``` Create the `PlatformApp` first: its application menu is the one `MacDesktop` names after the bundle and adds the other menus to. Call every member on the main thread, which is the thread that pumps events. What AppKit raises (a menu item chosen, a notification answered, a hotkey pressed) is handed to `post`, so handlers run where the app wants them, and while the loop is waiting `PlatformApp.Wake` is the usual way to bring it back. | Service | Members | Apple API | Linux counterpart | |---|---|---|---| | Menu bar | `SetMenuBar(NativeMenu[])`, `DescribeMenuBar`, `ChooseMenuItem` | `NSMenu`, `NSMenuItem` | none (a menu is part of the page) | | Status item | `ShowStatusItem(title, icon, TrayMenuItem[])`, `DescribeStatusItem` | `NSStatusItem` | `TrayIcon` | | File panels | `OpenFileAsync`, `OpenFolderAsync`, `SaveFileAsync(FileChooserOptions)` → `FileChooserResult`; `IsPanelOpen`, `EndPanel` | `NSOpenPanel`, `NSSavePanel` | `FileChooserPortal` | | Notifications | `ShowAsync(DesktopNotification)`, `CloseAsync(id)`, `ActionInvoked(id, action)` | `UNUserNotificationCenter` | `NotificationService` | | Global hotkeys | `BindAsync(GlobalShortcut[])`, `Activated(id, timestamp)`, `PressHotkey(id)` | Carbon `RegisterEventHotKey` | `GlobalShortcutsSession` | | One copy per user | `LocalSingleInstance.Acquire(appId, args, onLaunch)` | a private Unix socket | `SingleInstance` | Menus are made of `TrayMenuItem`s: `Label`, `Enabled`, `Visible`, `Checked`, `Click`, `Children`, separators, and `Shortcut` (a key equivalent such as `Ctrl+Shift+S`, which the menu bar shows and handles; `Ctrl` means Command as on the other desktops, `Alt` is Option and `MacCtrl` is the Control key). The application's own menu stays first and `SetMenuBar` replaces everything after it. Inside a bundle the application menu reads the bundle's `CFBundleName` ("Quit Shell Demo") instead of the process file name. ## Behaviour worth knowing - **Notifications** need an app bundle with a bundle identifier; from a bare executable the system raises an Objective-C exception that would end the process, so the call throws `ShellUnavailableException` first. The first notification may make the system ask the user for permission. The app never answers that prompt; if the user has said no, the exception names System Settings, Notifications. A notification shows even while the app is frontmost. `DesktopNotification.DefaultAction` and each button's `Action` come back through `ActionInvoked`. - **Hotkeys** use Carbon, which needs no privacy permission. macOS has no shortcut chooser, so each `GlobalShortcut` needs a `PreferredTrigger` in portal syntax (`CTRL+ALT+d`; `CTRL` is Control, `ALT` Option, `LOGO`, `META`, `CMD` and `SUPER` Command, keys are letters, digits, punctuation, F1 to F12, arrows, Space, Tab, Return, Escape). A key another application holds, or one this table does not know, throws `ShellUnavailableException` through the task. `PressHotkey` sends the system's own hotkey event to the app, exercising the registration and the handler without a keyboard. - **Panels** are free-standing; the task completes when the panel closes. File filters are patterns of the form `*.ext`; anything else is an `ArgumentException`. One panel at a time. `EndPanel` ends the open one as its buttons would, which is how code and tests close it. - **Status item** images are drawn 18 points high; the icon is a file path, a named system image, or the application's icon. - **One copy per user.** `LocalSingleInstance` has the shape of `SingleInstance`: `Acquire`, `IsPrimary`, and `ActivationRequest`s (`Open` when an argument is a `scheme://` URI, otherwise `Activate`, with all arguments in `Arguments`) delivered on a background thread. The first launch listens on a socket in a folder only the user can open; a folder others can read is refused. When LaunchServices starts the app, macOS already keeps one copy and brings it forward; the socket covers launches from a terminal or another program. ## Errors A service the system will not give the app as it is throws `ShellUnavailableException` (a `PlatformException`) with `Service` and `Requirement` naming what to do. Methods that return tasks deliver it through the task. Nothing is skipped silently. ## Tests `MacDesktopTests` runs the shortcut tables, the typed errors and the single-instance hand-over everywhere, and drives the real AppKit and Carbon on a Mac: menu items chosen and replaced, the status item present with its menu and removed, open, folder and save panels opened and cancelled from code, the hotkey handler run by the system's hotkey event, and the notification error outside a bundle. The AOT smoke app repeats the services in a NativeAOT image. Notifications that actually reach Notification Centre need a signed bundle and the user's permission, so they are exercised by hand, not by the suite. # Windows What the Win32 backend does as a desktop-app backend, and what it leaves to the app. ## Windows | Feature | How | |---|---| | Ordinary window | Decorated, movable, resizable, with the system frame and per-monitor v2 DPI (`WM_DPICHANGED` applies the rectangle Windows suggests, so a window dragged between monitors keeps its physical size). | | Size limits | `MinWidth`..`MaxHeight` and `Window.SetSizeLimits` answer `WM_GETMINMAXINFO`; the limits are client sizes and the frame is added. | | Dialog | `WindowOptions.Parent` makes an owned window: it stays above its parent, is centred over it when no placement is given, minimizes and closes with it, and has no taskbar button. | | Overlay | `WindowOptions.Overlay` makes a topmost tool window placed from its anchors and margins on the primary work area. `OverlayKeyboard.None` also sets `WS_EX_NOACTIVATE`, so clicking it never steals the focus. | | Popup | `PlatformApp.CreatePopup` makes a borderless owned window placed against the anchor rectangle, flipped when it would leave the work area. With `Grab`, the application losing the foreground (`WM_ACTIVATEAPP`) posts `PopupDismissed` and closes it. | | Frameless | `Decorations = None` is a popup-style window that keeps its resize edges (`WM_NCCALCSIZE` gives the client the whole window); `StartMove`/`StartResize` hand a drag to the system (`SC_MOVE`/`SC_SIZE`). | | Keep above | `SetKeepAbove` uses `HWND_TOPMOST` without activating or moving the window. | | Activation | `Window.Activate` restores a minimized window and takes the foreground. Windows only allows that to a process that has the foreground, was started by the foreground process or was granted it, so the call falls back to briefly joining the foreground thread's input queue. | | `FillSolid` | Paints the client area with a GDI brush, also on `WM_PAINT`, for tests and placeholders. | | Pointer capture and input method | The window captures the mouse while a button is down; `WM_IME_*` composition and candidate messages become text-input events. | A window belongs to the thread that created it: create it, pump it and call its members on one thread. An `await` that resumes on another thread cannot pump the window's messages. ## Second launch `LocalSingleInstance` works on Windows over a Unix-domain socket in the per-user temp folder (the same transport as on macOS). The running copy sends its process id first; the second launch, which the user just started and so may give the foreground away, calls `WindowActivation.AllowForeground(pid)` and then sends its arguments. The running copy then calls `Window.Activate`. ## Desktop services: `OnePlatform.Shell.WindowsDesktop` The counterpart of `MacDesktop` for Windows, over the Win32 Shell APIs, with the same models (`TrayMenuItem`, `NativeMenu`, `FileChooserOptions`/`FileChooserResult`, `DesktopNotification`, `GlobalShortcut`, `ShellUnavailableException`). Create it after the Win32 `PlatformApp`, on the thread that pumps it, with a `post` delegate that runs actions on that thread. Events (a menu item, a click on the icon or a notification, a hotkey) go through `post`. In a menu label or menu bar title a single `&` marks the mnemonic letter (`&File` opens with Alt+F) and `&&` is a literal ampersand. | Service | API | How, and limits | |---|---|---| | Tray icon | `ShowTrayIcon(tooltip, iconPath, menu)`, `SetTrayMenu`, `TrayActivated`, `GetTrayBounds` | `Shell_NotifyIcon` (version 4 callbacks) with a hidden message window. A right click shows the menu with `TrackPopupMenuEx`; separators, checkmarks, submenus, disabled items and shortcut text are drawn. The icon is an `.ico` or `.png` file, or the default application icon. One icon at a time. The icon comes back after the shell restarts. Windows 11 puts a new icon in the overflow flyout until it is promoted in the taskbar settings; `GetTrayBounds` then answers with the flyout button. | | Notifications | `ShowAsync`, `CloseAsync`, `ActionInvoked` | A shell balloon (`NIF_INFO`), which Windows 10 and 11 draw as a toast, from the tray icon (or a temporary icon if none is shown). Title (63 characters), body (255), `DefaultAction` reported when the toast is clicked. **Buttons and reply fields are not possible this way**: they need a toast from an app with a package identity or a registered application id and a COM activator (the Windows App SDK's notification model), and a notification with `Buttons` throws `ShellUnavailableException`. Focus assist can hold a toast back without an error. When Windows has notifications switched off for a **packaged** app, `ShowAsync` fails with `NotificationsDisabledException` (a `ShellUnavailableException`) whose `Setting` is the toast notifier's `NotificationSetting`: `DisabledForApplication`, `DisabledForUser`, `DisabledByGroupPolicy` or `DisabledByManifest`. Windows exposes that setting only through the WinRT toast notifier, which needs a package identity, so an **unpackaged** app gets no answer: its balloon is sent and Windows may still drop it. Windows takes a change of the switch into the notification platform after a few seconds, so a call made just after the user turns notifications off can still be sent. | | File and folder dialogs | `OpenFileAsync`, `OpenFolderAsync`, `SaveFileAsync` | The Common Item Dialog through source-generated COM (`GeneratedComInterface`), on its own single-threaded-apartment thread, so the app keeps pumping. Title, accept label, start folder, suggested name, multi-select, filters by glob (MIME types have no meaning and match everything), overwrite prompt, default extension from the first filter. Owner: `ParentWindow = "win32:"`. | | Global hotkeys | `BindAsync`, `Activated`, `Deactivated` | `RegisterHotKey` without auto-repeat. Windows reports presses only, so after each press the main key is polled every 15 ms with `GetAsyncKeyState` and `Deactivated` follows within about 15 ms of the release; modifiers are not watched. A key another program holds throws `ShellUnavailableException` ("another application already uses ..."), and keys bound earlier in the same call are given back. A trigger such as `CTRL+ALT+d` is required; Windows has no shortcut chooser. | | Menu bar | `SetMenuBar(window, menus)`, `ClearMenuBar` | `SetMenu` on a decorated window, with each item's `Shortcut` shown at the right and, when enabled, handled as an accelerator whenever the window has the focus. The client area keeps its size. The bar is rebuilt, not live: call again to change a checkmark. Frameless, overlay and popup windows cannot carry one. | | Screenshots | `CaptureWindow(window, clientAreaOnly)`, `CaptureRegionAsync()` | `CaptureWindow` reads only the app's own window with `PrintWindow`, so nothing of another program is in it even when windows overlap. `CaptureRegionAsync` shows a dimmed see-through layer, lets the user drag a rectangle and copies the pixels only after the button is released; Escape or a right click cancels. No pixel of the screen is read before the user chooses the area. Both return a `ScreenshotImage` (BGRA pixels, `ToPng()`). | The tests in `tests/OnePlatform.Tests/WindowsDesktopTests.cs` use real input (`SendInput`) on a Windows desktop and drive the menu bar by mouse, by Alt and a mnemonic, and by accelerator; the tray icon and its menu; a notification and a click on its toast; the three dialogs owned by a window; a hotkey pressed while another window has the focus; and both screenshots. The notification setting's mapping to `NotificationsDisabledException` is tested on every OS; `tools/toast/proof.ps1` runs `tests/OnePlatform.ToastProof` as a packaged app with the setting off and on and keeps pictures of both. ## Not here Third-party toasts with actions, jump lists, taskbar progress and overlay icons, a Windows-side single-instance service beyond `LocalSingleInstance`, and the UI Automation patterns listed in `accessibility.md` as missing. Overlays are placed on the primary monitor only. The tests do not cover a GPU, multiple monitors, high-DPI scaling or a real input-method editor. # Accessibility A window can give assistive technologies (screen readers, switch control, voice control) a tree of accessible nodes and report changes to it. The API is the same on every platform and knows nothing of any UI engine: the app describes nodes, the platform bridge turns them into the system's own objects. macOS (NSAccessibility) and Windows (UI Automation) are bridged; other systems keep the provider and nothing reads it (`WindowAccessibility.IsSupported` is false). ## The model `window.Accessibility` (a `WindowAccessibility`) holds an `IAccessibilityProvider`: | Member | Meaning | |---|---| | `RootId` | the node standing for the window's content | | `GetNode(id)` | an `AccessibleNode` picture of one node, or null when it is gone | | `FocusedId` | the node with keyboard focus, or 0 | | `HitTest(x, y)` | the deepest node at a point in window pixels, or 0 | | `Perform(id, action, args)` | an action an assistive technology asked for | An `AccessibleNode` has an app-chosen `Id` (positive, stable for as long as the thing exists), `ParentId`, `Role`, `Name`, `Description`, `Value`, a numeric `NumberValue`/`Minimum`/`Maximum`, `States`, `Actions`, `Bounds` (window pixels, origin top left, as pointer positions are), `Children`, `Level`, and for text fields `Text` with `SelectionStart`/`SelectionEnd` in UTF-16 units (equal means a caret). Actions are `Press`, `Focus`, `Increment`, `Decrement`, `SetValue`, `Expand`, `Collapse` and `SetSelection`; only those a node lists in `Actions` are ever asked for. Everything runs on the UI thread. The provider owns the tree and answers from its current state; nodes may be fresh objects on every call. ## Pull, not push Setting `Provider` costs nothing. The platform builds its objects only when an assistive technology asks, and `IsActive` turns true (and `Activated` fires) at the first request. Until then the `Notify…` methods return at once, so an app can call them on every change. Once active they queue, and `Flush()` merges the queue and tells the system once: repeats are sent once, a structure change covers the name, value, state and selection changes of nodes under it, only the last focus change is kept, announcements all stay in order. Nothing runs at idle: no timer, no thread, no polling. Notifications: `NotifyFocusChanged`, `NotifyStructureChanged`, `NotifyNameChanged`, `NotifyValueChanged`, `NotifyStatesChanged`, `NotifySelectionChanged`, and `Announce(text, priority)` for speech that belongs to no node. ## macOS (NSAccessibility) The window's content view stands for the root node: it is an accessibility element with the root's role, label and children, and answers `accessibilityFocusedUIElement` and `accessibilityHitTest:`. Every other node is an `NSAccessibilityElement` subclass instance made the first time the node is asked for and kept, the same object for that node id, until the node disappears (then `AXUIElementDestroyed` is posted and it is released). Its properties are read from the provider on each query, so they are never stale. Frames are converted from window pixels to screen points with AppKit's own view, window and screen conversions. AppKit decides which actions an element advertises from which of `accessibilityPerformPress`, `…Increment` and `…Decrement` its class overrides, so there are four element classes (none, press, adjust, both) and a node that gains or loses an action gets an element of the right class. Values: check boxes, switches and toggle buttons report 0, 1 or 2 (mixed); ranges report numbers with minimum and maximum; text fields report their text, selection range, selected text and ranges for strings. Setting a value, focus, expansion or a selection range from a client reaches `Perform` (a range is clamped to the text first, since it comes from outside). Role mapping (the macOS column of the Core Accessibility API Mappings; names are the values of the `NSAccessibility…Role` and `…Subrole` constants): | `AccessibleRole` | AX role | AX subrole | |---|---|---| | Button | AXButton | | | ToggleButton | AXCheckBox | AXToggle | | MenuButton | AXPopUpButton | | | Link | AXLink | | | CheckBox | AXCheckBox | | | Switch | AXCheckBox | AXSwitch | | RadioButton / RadioGroup | AXRadioButton / AXRadioGroup | | | TextField (multiline: TextArea) | AXTextField (AXTextArea) | | | SearchField | AXTextField | AXSearchField | | ComboBox | AXComboBox | | | ListBox / Option | AXList / AXStaticText | | | List / ListItem | AXList / AXGroup | AXContentList / | | Menu, MenuBar, MenuItem (and its check and radio forms) | AXMenu, AXMenuBar, AXMenuItem | | | Slider / SpinButton | AXSlider / AXIncrementor | | | ProgressBar / Meter | AXProgressIndicator / AXLevelIndicator | / AXMeter | | Tab / TabList / TabPanel | AXRadioButton / AXTabGroup / AXGroup | AXTabButton / / AXTabPanel | | Table / Row / Cell, ColumnHeader, RowHeader | AXTable / AXRow / AXCell | | | Tree / TreeItem | AXOutline / AXRow | / AXOutlineRow | | Toolbar, Separator, ScrollBar | AXToolbar, AXSplitter, AXScrollBar | | | Image, Heading, StaticText | AXImage, AXHeading, AXStaticText | | | Group, Generic, Paragraph | AXGroup | AXApplicationGroup (Group only) | | Document, Article | AXGroup | AXDocument, AXDocumentArticle | | Dialog, AlertDialog, Alert, Status, Tooltip | AXGroup | AXApplicationDialog, …AlertDialog, …Alert, …Status, AXUserInterfaceTooltip | | Navigation, Main, Banner, ContentInfo, Complementary, Region, Search, Form | AXGroup | AXLandmarkNavigation, …Main, …Banner, …ContentInfo, …Complementary, …Region, …Search, …Form | Choices that differ from the table or fill a gap in it: - The name is exposed as `accessibilityLabel` (AXDescription), not `accessibilityTitle` (the table says AXTitle). Custom AppKit elements use the label and VoiceOver reads it the same; giving both would be read twice. A `StaticText` has no label: its text is its value. - The description is `accessibilityHelp`. The table asks for AXCustomContent (`aria-description`), which is not done. - `AXIdentifier` is `oneplatform-`, which helps tests and automation find a node. - Notifications: focus → `AXFocusedUIElementChanged`; structure → `AXLayoutChanged`; name → `AXTitleChanged`; value → `AXValueChanged`; text selection → `AXSelectedTextChanged`; a state change → `AXValueChanged` for checkable roles, `AXRowExpanded`/`AXRowCollapsed` for expandable nodes and `AXSelectedChildrenChanged` on the parent for selectable ones; announcements → `AXAnnouncementRequested` with the priority (polite 50, assertive 90). Notifications are posted only for nodes that already have an element: a client cannot know the others. ## A Windows UI Automation adapter The provider interface is enough for one. A UIA provider needs, per node, from `AccessibleNode`: `IRawElementProviderSimple` properties (ControlType from the role per the UIA column of the same mapping tables, Name, HelpText, IsEnabled, HasKeyboardFocus, IsKeyboardFocusable, BoundingRectangle in screen pixels, AutomationId from the id) and the patterns the node's `Actions` and role imply (Invoke for Press, Value and RangeValue for `Value`/`NumberValue`, Toggle for Checked/Mixed, ExpandCollapse, SelectionItem, Text for fields with `Text` and the selection). `IRawElementProviderFragment` navigation (parent, first/last child, siblings) comes from `ParentId` and `Children`; the fragment root is the root node answering WM_GETOBJECT on the window, with `ElementProviderFromPoint` from `HitTest` and `GetFocus` from `FocusedId`. Events map one to one: focus → `UiaRaiseAutomationEvent(AutomationFocusChanged)`, structure → `UiaRaiseStructureChangedEvent`, name/value/state → `UiaRaiseAutomationPropertyChangedEvent`, announcement → `UiaRaiseNotificationEvent`. Lazy pull fits: UIA only calls the provider once a client has asked, and `IsActive` can be set from the first WM_GETOBJECT. Two additions would help: a way for the platform to ask the app whether a node is still alive (the provider's `GetNode` null already says that), and bounds in screen pixels, which the window already converts. ## Testing `CocoaAccessibilityTests` open a window and send the NSAccessibility messages to the content view and its elements from inside the process, so no Accessibility permission is involved. `tests/OnePlatform.AxProof` is the out-of-process check: `host ` opens a window with a small tree and `client ` reads and operates it through the AXUIElement API as a screen reader would, and prints the notifications the system delivered. The client needs the Accessibility permission for whatever runs it (`AXIsProcessTrusted`), and exits with a message when it has none. Notifications cannot be observed in-process: macOS delivers them to out-of-process observers only, so the in-process tests record what the bridge hands to AppKit. ## Windows (UI Automation) A Win32 window answers `WM_GETOBJECT` for `UiaRootObjectId` with the provider's root node (`UiaReturnRawElementProvider`). Setting a provider still costs nothing: the first request is what makes `IsActive` true, every other element is made the first time UI Automation navigates to it (and is the same object for that node id until the node goes away), and events are raised only while `UiaClientsAreListening` says a client listens. The COM interfaces are source-generated (`[GeneratedComInterface]`/`[GeneratedComClass]`), so the bridge is NativeAOT- and trim-clean; the only native calls are `UIAutomationCore.dll`, `oleaut32.dll` and `user32.dll`. - **Threads.** UI Automation calls providers on threads of its own. Each call is carried to the window's thread with a sent message (`SendMessageTimeout`, 5 s), so `IAccessibilityProvider` is only ever used on the UI thread; a call that cannot get there in time fails with an error HRESULT, and so does one whose provider throws. The app's loop must pump messages (any `PumpEvents` does). - **The root is the window.** UI Automation merges the provider's root with the window's own element: it stays a Window and keeps the window's title unless the root node has a `Name` (the root's role and control type are not used), and the app's nodes are its children. - **Coordinates.** `Bounds` (window pixels) become screen pixels through `ClientToScreen`; `ElementProviderFromPoint` converts the other way and asks `HitTest`. `IsOffscreen` is true for an empty rectangle or one outside the client area. - **Properties:** control type, Name, HelpText (the node's `Description`), AutomationId (the node id), IsEnabled, IsKeyboardFocusable, HasKeyboardFocus, IsOffscreen, IsPassword, IsRequiredForForm, IsControlElement/IsContentElement (anonymous generic nodes are neither), FrameworkId (`OnePlatform`), landmark type and localized landmark type for the landmark roles, heading level. A localized control type is given only where the role is more specific than its control type (switch, heading, dialog, landmarks...), in English; for the rest UI Automation names the control type in the user's language. - **Patterns**, chosen from the role, states and actions: Invoke (`Press`, when no more specific pattern applies), Toggle (check box, switch, toggle button, check menu item; `Press` toggles), Value (text roles, or any node with `SetValue`; a password reads as empty), RangeValue (nodes with a number; small step is a hundredth and large step a tenth of the range, a write outside the range is refused), ExpandCollapse (`Expandable` or `Expand`/`Collapse`), SelectionItem (radio button, tab, option, radio menu item, and selectable list items, tree items, rows and cells; `Select` performs `Press`, else `SetSelection`, and selection is single). Disabled nodes refuse actions (`UIA_E_ELEMENTNOTENABLED`). The containers offer no Selection pattern, and there are no Text, Scroll, Grid or Table patterns yet. - **Events** from `Flush()`: focus (`AutomationFocusChanged`), structure (`ChildrenInvalidated`), property changes (Name; Value or RangeValue value; for a state change every state-derived property the node has, as the batch cannot say which moved: IsEnabled, IsKeyboardFocusable, ToggleState, ExpandCollapseState, IsSelected, Value.IsReadOnly), the SelectionItem `ElementSelected` event, and announcements as `UiaRaiseNotificationEvent` (polite speech is queued in order; assertive speech is important and replaces what is queued). - UI Automation asks a provider to focus an element before it runs a pattern on it, so a client's `Invoke` arrives as `Focus` then `Press`. `tests/OnePlatform.UiaProof` serves a window with a button, a check box, a text field, a slider and a list; `tools/uia/client.ps1` is a black-box UI Automation client (the framework's own `UIAutomationClient`) that walks it, hit-tests it, acts through the patterns and checks the events, and `tools/uia/run-guest.ps1` runs both in a Windows desktop session and saves a screenshot, `aot-guest.ps1` runs the NativeAOT smoke app, and `narrator-guest.ps1` runs Narrator beside the window (`-Repo` names the checkout and `-Out` the folder for logs and captures). ## Gaps No relations (labelled-by, controls), no table or outline row/column information beyond the roles, no custom content for descriptions, no text attributes or per-range bounds, no rotor or custom actions, and no AT-SPI bridge in this package (OneApp has its own AT-SPI bridge). On Windows there is no Text, Scroll, Grid, Table or Selection (container) pattern, no relations (labelled-by) and no localized strings. # Browser pages The browser backend (`PlatformBackendKind.Browser`, chosen automatically on `browser-wasm`) draws into one canvas and reads input from the page. Its half in JavaScript is `oneplatform.js`. ## Getting the script `RecursiveAI.OnePlatform` ships `oneplatform.js` as a static web asset (the same mechanism a Razor class library uses for its scripts). An app built with `Microsoft.NET.Sdk.WebAssembly` (or the Blazor WebAssembly SDK) that references the package gets the file in its build and publish output, under the base path `_content/RecursiveAI.OnePlatform/`: ``` wwwroot/_content/RecursiveAI.OnePlatform/oneplatform.js ``` Nothing needs copying. In an app that serves its own folder, the file is served at `/_content/RecursiveAI.OnePlatform/oneplatform.js`. ## Registering it The program's `[JSImport]`s name the module `oneplatform`, so the page registers the script under that name after creating the runtime and before running the program: ```html ``` Without the registration, creating the app fails with a JavaScript interop error that names the missing module. ## The canvas The window is the canvas whose id is `PlatformOptions.DisplayName`, or `oneplatform-canvas` when that is null. It is sized to the visible part of the page and follows the device pixel ratio, and a page has exactly one window. ## Development control `BrowserPage.SetControlHandler` lets a development build take control messages from the page's script: the page calls the exported `OnePlatform.BrowserPage.ControlAsync(message)` and gets the answer as text. A release build leaves the handler unset and the function answers with an error text. # Waking the event loop from another thread `PlatformApp.PumpEvents(timeout)` blocks until the system has an event or the timeout passes. Work that arrives on another thread (a request from a control listener, a D-Bus callback, a timer, a task continuation) calls `PlatformApp.Wake()` to end that wait at once, so the loop needs no polling interval. - `Wake()` is safe from any thread, any number of times, at any time, including during `Dispose`. - It makes the current wait return; if no wait is running, the next one returns immediately. Wakes that pile up before the loop looks coalesce into one early return. - A woken `PumpEvents` queues no event. After every return, check your own work queue. - A wake is not an event, so there is no `PlatformEventKind` for it. | Backend | Mechanism | |---|---| | Wayland, X11 | A non-blocking pipe polled beside the connection descriptor. A flag keeps a burst of wakes to one byte. | | Headless | A timed pump sleeps on a semaphore while nothing is queued; `Wake` releases it. | | Win32 | An auto-reset event passed to `MsgWaitForMultipleObjects` beside the message queue. | | Cocoa | An application-defined `NSEvent` posted with `postEvent:atStart:`, which may be called from any thread. | | Android | `ALooper_wake` on the loop's looper. | | Browser, iOS | No blocking wait; `Wake()` does nothing. | Headless `PumpEvents(timeout)` used to return at once; it now waits up to `timeout` when no event is queued and no wake arrives. # Changelog All notable changes to this project are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ## [1.0.0] - 2026-12-01 ### Added - Global shortcuts and other portal calls for a program that was started directly (no installed launcher entry): `DBusConnection.PortalAppId` declares the application id to the desktop portal (`org.freedesktop.host.portal.Registry.Register`) before the first portal call on the connection; `PortalCreateDesktopEntry` and `PortalAppName` write the hidden launcher entry the portal needs to recognise the id when none is installed; `PortalRegistration` reports the outcome (`PortalRegistrationState`, `PortalRegistrationResult`). Without an id the portal's "An app id is required" refusal is now `PortalAppIdRequiredException`, whose message says what is missing. See `docs/linux-shell.md`; `tests/OnePlatform.ShortcutProof` is a small program for trying it. - `IconImage` and application icons without an installed launcher entry: `Window.SetIcon(images, name)` sets a window's icon on Wayland (`xdg_toplevel_icon_manager_v1`, bound when the compositor offers it) and X11 (`_NET_WM_ICON`) and returns false where the window system cannot; `TrayIcon.CreateAsync(..., images)` and `TrayIcon.SetIcon(images, name)` publish the pictures as the StatusNotifierItem `IconPixmap` at several sizes. Before, a tray icon had only a themed name, which a desktop could not resolve for an app that was not installed, so Plasma drew an empty clickable item and a placeholder in the taskbar. See `docs/desktop-windows.md`. - `NativeEnvironment.Set(name, value)` sets or removes an environment variable where native libraries in the process read it (`getenv`) as well as for managed code; `Environment.SetEnvironmentVariable` alone does not reach them on Linux and macOS. - `tests/OnePlatform.IconProof`, a small program that opens a window and a tray icon with or without pictures, for looking at a desktop's taskbar and tray. - The browser backend's page script, `oneplatform.js`, ships in the package as a static web asset: a `browser-wasm` app that references `RecursiveAI.OnePlatform` publishes it at `_content/RecursiveAI.OnePlatform/oneplatform.js` and registers it as the module `oneplatform`. See `docs/browser.md`. ### Changed - Names renamed before 1.0: `ActionMap.Harness` is now `ActionMap.Injected` (the source for actions injected by scenarios, tests and live control; its label in reports is now `"injected"` instead of `"harness"`), and `BrowserPage.Control` is now `BrowserPage.ControlAsync` since it returns a `Task`. A page script that calls the exported method uses `exports.OnePlatform.BrowserPage.ControlAsync`. - `OnePlatform.Shell.MenuBarMenu` is now `OnePlatform.Shell.NativeMenu`, the menu type `MacDesktop.SetMenuBar` and `WindowsDesktop.SetMenuBar` take, so it no longer shares a name with menu types in apps built on the library. - `PlatformModule`, an unused placeholder, is removed. - Documentation and README are written for application authors: the support table, a getting-started example, and XML docs that no longer refer to types outside this package. ### Fixed - Linux tray: when a StatusNotifierWatcher starts, its owner-changed signal can arrive before it answers calls; the icon's registration is now retried (up to 10 times, 200 ms apart) instead of being lost until the watcher restarts again. - Win32: a key message that carries no scan code (input sent with virtual-key codes only, as some automation tools do) is named from its virtual-key code instead of arriving as an unknown key, so Escape, Tab, Enter, the arrows and the letters work for such input. Text sent as Unicode packets (`VK_PACKET`) no longer produces key events with a bogus key; its text arrives as before. - Win32: windows now honour `WindowOptions` for desktop use, as on Cocoa: size limits, dialogs (`Parent`, owned windows), overlays (topmost tool windows placed from anchors and margins), borderless windows with resize edges, popups with a grab that ends when the application loses the foreground, `StartMove`/`StartResize`, `Window.FillSolid`, mouse capture, `WM_IME_*` composition and the rectangle Windows suggests on a DPI change. `LocalSingleInstance` now works on Windows, and the second launch grants the running copy the foreground before the hand-over. See `docs/windows-shell.md`. - Cocoa: windows now honour `WindowOptions` for desktop use: size limits (`MinWidth`..`MaxHeight`, `SetSizeLimits`), dialogs (`Parent`), overlays (`Overlay`, a borderless window at a window level, placed from its anchors and margins), borderless windows (`Decorations = None`) and popups (`PlatformApp.CreatePopup`, with a grab that ends on a press outside the application). Before, these options were ignored and `CreatePopup` threw. `Window.Role`, `Parent` and `Decoration` are set. `Window.Activate` on a popup throws `ActivationUnavailableException`. `Window.FillSolid` sets the layer's background colour on Cocoa. See `docs/desktop-windows.md`. ### Added - `WindowsDesktop.ShowAsync` reports a notification Windows will not show instead of completing as if it had: for a packaged app it asks the toast notifier for its `NotificationSetting` first and fails with the new `NotificationsDisabledException` (`Setting`: the new `WindowsNotificationSetting` enum, `DisabledForApplication`, `DisabledForUser`, `DisabledByGroupPolicy` or `DisabledByManifest`). It derives from `ShellUnavailableException`, which is no longer sealed. An unpackaged app has no notifier to ask, so its balloon is sent as before. See `docs/windows-shell.md`. - `Window.CanPresentPixels` and `Window.PresentPixels(bgra, width, height)`: show a CPU-drawn image in a window that has no graphics device. Win32 copies it with `SetDIBitsToDevice` and keeps it to draw again on `WM_PAINT`; Wayland toplevel, layer-shell and popup windows copy it into reusable `wl_shm` buffers that respect `wl_buffer.release`, resize with the window and draw only when a picture is presented (see `docs/desktop-windows.md`); other backends report `CanPresentPixels` false and throw `NotSupportedException`. - `OnePlatform.Shell.WindowsDesktop`: the Windows desktop services, the counterpart of `MacDesktop`. A notification-area icon with a context menu (`ShowTrayIcon`, `SetTrayMenu`, `TrayActivated`, `GetTrayBounds`), balloon/toast notifications with click-to-activate (`ShowAsync`, `CloseAsync`, `ActionInvoked`; no buttons, which a balloon cannot have), the Common Item Dialog through source-generated COM (`OpenFileAsync`, `OpenFolderAsync`, `SaveFileAsync`, owner as `win32:` in `FileChooserOptions.ParentWindow`), `RegisterHotKey` hotkeys with press and polled release (`BindAsync`, `Activated`, `Deactivated`), a menu bar with accelerators on a window (`SetMenuBar`, `ClearMenuBar`; reuses `NativeMenu`) and screenshots of the app's own window or a region the user drags (`CaptureWindow`, `CaptureRegionAsync`, returning the new `ScreenshotImage` with `ToPng()`). Anything Windows cannot do throws `ShellUnavailableException`. See `docs/windows-shell.md`. - Windows UI Automation for `Window.Accessibility`: a Win32 window now answers `WM_GETOBJECT` with a provider tree built from the window's `IAccessibilityProvider` (fragment navigation, bounding rectangles, hit testing, focus, control types per Core-AAM, the properties screen readers read, Invoke, Toggle, Value, RangeValue, ExpandCollapse and SelectionItem patterns) and raises focus, property, structure, selection and notification events from `Flush()`. It costs nothing until a client asks, uses source-generated COM, and runs provider calls on the window's thread. `WindowAccessibility.IsSupported` is now true on Windows. See `docs/accessibility.md`. `tests/OnePlatform.UiaProof` and `tools/uia` check it from outside the process. - `Window.SetKeepAbove(bool)`, `Window.KeepAbove`, `Window.CanKeepAbove` and `KeepAboveUnavailableException`: a "keep on top" toggle for an ordinary window. X11 sends EWMH `_NET_WM_STATE_ABOVE` (and `KeepAbove` follows the window manager's property), Win32 uses `HWND_TOPMOST`/`HWND_NOTOPMOST`, Cocoa the floating window level, the headless backend holds the state. On Wayland `xdg-toplevel` has no such request, so under KWin only, a short KWin script sets or clears `keepAbove` on the windows with the app's own app id and is unloaded before the call returns; other compositors throw the typed error. See `docs/desktop-windows.md`. - `OnePlatform.Accessibility`: window accessibility. `Window.Accessibility` (`WindowAccessibility`) takes an `IAccessibilityProvider`, a pulled tree of `AccessibleNode`s (role, name, description, value and range, states, actions, bounds, children, text with selection) with focus, hit testing and actions, and queues change notifications (`NotifyFocusChanged`, `NotifyStructureChanged`, `NotifyNameChanged`, `NotifyValueChanged`, `NotifyStatesChanged`, `NotifySelectionChanged`, `Announce`) that `Flush` merges and sends. On macOS it is exposed through NSAccessibility on the content view and long-lived elements, built only when an assistive technology asks. See `docs/accessibility.md`. - `OnePlatform.Shell.MacDesktop`: the macOS desktop services, on Apple silicon: the menu bar (`SetMenuBar` with `NativeMenu`, the application menu named from `CFBundleName`), an `NSStatusItem` with a menu, open, folder and save panels (`NSOpenPanel`/`NSSavePanel`, taking `FileChooserOptions` and returning `FileChooserResult`), notifications through `UNUserNotificationCenter` with actions (`DesktopNotification`, `ActionInvoked`) and global hotkeys through Carbon `RegisterEventHotKey` (`GlobalShortcut`, `Activated`). `LocalSingleInstance` hands a second launch to the first over a private per-user Unix socket, shaped like `SingleInstance`. `ShellUnavailableException` (a `PlatformException`, with `Service` and `Requirement`) names what a missing permission or app bundle needs. `TrayMenuItem.Shortcut` carries a menu item's key equivalent. See `docs/macos-shell.md`. - `Window.Activate(string? activationToken = null)`: brings a window to the front, un-minimizes it and gives it the keyboard focus, on Wayland (`xdg_activation_v1`, with the token a launcher passed in or one requested from the latest input), X11 (`_NET_ACTIVE_WINDOW` with source and input time, `_NET_STARTUP_ID`, map to un-iconify), Win32 (`ShowWindow(SW_RESTORE)`, `SetForegroundWindow` with an input-queue attach fallback) and Cocoa (`deminiaturize:`, `activateIgnoringOtherApps:`, `makeKeyAndOrderFront:`). `ActivationUnavailableException` (with `Requirement`) names the missing protocol. `WindowActivation.AllowForeground(processId)` is the Windows launcher's half. `ActivationRequest.ActivationToken` returns the token or startup id a second launch forwarded, and `SingleInstance.Acquire` has an overload taking the token to forward (it also forwards `DESKTOP_STARTUP_ID` now). See `docs/desktop-windows.md`. - `OnePlatform.DBus`: a BCL-only D-Bus client (marshalling, authentication, calls, signals, exported objects, name ownership) and `OnePlatform.Shell`: single-instance activation, the FileChooser, Screenshot, GlobalShortcuts and Notification portals (with the `org.freedesktop.Notifications` fallback) and a StatusNotifierItem tray icon with a dbusmenu menu. See `docs/linux-shell.md`. - The platform layer: windows, input, IME, clipboard, displays, gamepads and haptics, the headless backend and `InputInjector`, and the Win32, Cocoa, X11, Wayland, Android, iOS and browser backends, in namespace `OnePlatform`. - Desktop windows on Wayland and X11: decorated, movable and resizable by default (`xdg-decoration` server-side frames, a client-side frame where the compositor has none, `WM_CLASS`/`_NET_WM_NAME` on X11), application id, size limits, dialogs with a parent, `StartMove`/`StartResize`/`ShowWindowMenu`, keep-on-top overlays (`wlr-layer-shell`; dock-type `_NET_WM_STATE_ABOVE` windows on X11) through `WindowOptions.Overlay`, and popups with an anchor, gravity, constraint adjustment and grab through `PlatformApp.CreatePopup`. See `docs/desktop-windows.md`. - `tools/WaylandGen` and its protocol XML, which produce the Wayland protocol tables.