1// Windows, their events and input on every platform (PLAN.md,2// stage F1): Wayland on Linux, Win32 on Windows, AppKit on macOS (F7), a3// canvas in the browser, and a headless window for tests. A program gives4// `run` its state and a handler, which the platform's event loop calls5// with each event until the program closes the window.6//7// ```text8// import pkg::alloy::window;9//10// fn on_event(clicks: &var u32, window: &var Window, event: &Event) {11// match (event) {12// ::Button |&b| {13// if (b.pressed) {14// clicks += 1;15// }16// }17// ::CloseRequested {18// window.close();19// }20// else {}21// }22// }23//24// fn main() -> i32 {25// return run(&WindowConfig::titled(&"Clicks"), 0 to u32, on_event);26// }27// ```28//29// What a program uses of the platform beyond the window it installs:30// screen readers (`window.install_access()`, which pkg::alloy::ui_access31// calls) and file dialogs and drops (`window.install_files()`, which32// pkg::alloy::ui_app calls); a program installing neither links none of33// their code.34//35// Sizes and positions are in physical pixels, the display's own; the36// scale says how many make one logical pixel (2 on a typical high-density37// display), so a program draws `scale` times larger to look the same38// everywhere.39//40// ## How it was built41//42// Notes kept from each stage as it was finished, the sizes and numbers43// of their day; what changed since is in REVIEW.md and the history.44//45// **F1 as built** (2026-10-12):46// - `run(config, state, handler)` erases the state and handler into one47// closure the platform's loop calls; `Window` carries what the handler48// asks (title, redraw, close, a presented frame), applied once it49// returns. Sizes and positions are physical pixels with the scale apart.50// - Headless: `run_headless` replays a list of events, keeping each frame51// presented; `alloyc test window/tests.alloy`.52// - Wayland: libwayland-client and xkbcommon loaded through `Library`; the53// protocols' XML (`window/protocols/`) read at compile time into tables54// identical to wayland-scanner's; one dispatcher for every event; frames55// in `wl_shm` buffers paced by frame callbacks; xdg-decoration,56// fractional-scale, viewporter and cursor-shape used where offered (GNOME57// offers no server-side decorations: client-side ones come with the UI).58// Key repeat from the compositor's rate; no compose or IME yet (F4).59// - Win32: a window procedure reaches its state only through a call60// (`GetWindowLongPtrW`), so a loaded library's functions cannot reach it;61// user32, gdi32 and dwmapi are therefore linked into Windows programs,62// imported only by programs calling them. Per-monitor DPI, GDI frames,63// `DwmFlush` pacing. Runs over SSH up to drawing, which a session without64// a desktop never asks for.65// - Web: `browser.alloy` with `browser.web.js`, a canvas (`#alloy` or a new66// one) and the page's events, `requestAnimationFrame` pacing; state kept67// for callbacks through `std::ffi::c_pointer::keep`. A program using tasks68// runs in a worker, with no page: its window cannot open yet.69// - `std::ffi` gained `view`, `view_var`, `c_text`, `c_pointer::of`,70// `c_pointer::keep` and `take` (spec section 6.3).71// - `scripts/test.sh` runs the tests, builds the samples and test programs72// for four targets, and runs `tests/frames.alloy` in a page node fakes73// and under a headless weston.74//75// **F6a as built** (2026-10-13):76// - `window`: the tree's types (`Role`, `Semantics` with defaults,77// `AccessNode` with bounds in window pixels, `TreeUpdate`, `Action`,78// `ActionRequest`, and `AccessTree`, which applies updates);79// `window.update_access(update)`, `Event::AccessRequested` when a screen80// reader starts and `Event::Action` for what it asks. `Semantics` is81// flat (`value` a string, `checked: Option<bool>`, `range`,82// `selection` as anchor and caret, `disabled`, `focusable`,83// `multiline`) rather than the design's nested states.84// - Headless: `Replay.access`, the tree the program left. Web: a hidden85// "Turn on accessibility" button is what a screen reader finds first;86// pressing it gives `AccessRequested` and makes a layer of `div`s over87// the canvas, one a node, with ARIA roles, labels, states and values,88// placed at their bounds; a click on one is `Action::Click`, focusing89// one `Action::Focus`, and keys pressed in the layer go to the window.90// The tree goes to the page as JSON (`layer.alloy`'s `access_json`).91// Windows and Wayland drop the updates until F6b and F6c.92// - The clipboard, text only: `window.set_clipboard(text)` and93// `window.request_clipboard()`, answered by `Event::Clipboard(text)`,94// empty when it holds none. Wayland: `wl_data_device_manager` v3, a95// data source offering `text/plain;charset=utf-8`, `UTF8_STRING` and96// `text/plain`, set as the selection with the serial of the last input;97// a paste reads the selection's offer through a pipe the loop polls98// beside the socket and the waker, or answers at once while the window99// holds the selection. Windows: `CF_UNICODETEXT` through `GlobalAlloc`.100// The web: `navigator.clipboard`. Headless: kept in `Replay.clipboard`.101// - `ui`: `Widget::semantics` (default: no role, the element's children102// given to its nearest described ancestor); `Text` a label, `Button`,103// `Checkbox`, `Slider` (its `accessible` text the label), `TextField`104// (its text, selection and multiline; labelled by `accessible` or its105// placeholder), `Image` (described only with `accessible` text),106// `Scroll` and `ui.list`. Every built-in option struct with a label107// gained `accessible`. Node ids are an element's generation and index;108// the window is node `1 << 63`.109// - The walk, sent once a screen reader asks, and the actions: in110// pkg::alloy::ui_access's notes since R6f.111// - `TextField` takes Ctrl+C, Ctrl+X and Ctrl+V: `ui.set_clipboard(text)`112// and `ui.request_paste()`, the text coming back to the element that113// asked as `Input::Paste`.114// - Tests: `window/tests.alloy` (the clipboard and the tree in replays),115// `ui/tests.alloy` (the tree and its updates, actions, copy, cut and116// paste, an app answering a screen reader); `tests/access` under weston117// (no seat: an empty clipboard) and in node's page, whose fake DOM118// (`tests/web/dom.mjs`) gained elements, a clipboard and, with119// `ALLOY_SCREEN_READER=1`, a screen reader printing the layer and120// clicking and focusing in it. Sample `notes.alloy`.121// - `text` draws a face's empty .notdef (Inter's) as a hollow box, so a122// character the bundled font lacks, such as Japanese typed through an123// input method, shows until F10's fallback draws it.124// - Sizes: the tree, its comparisons and the clipboard add about 50 KB to125// the counter (1.47 MB native, 1.17 MB on the web, whose budget went126// from 1.15 to 1.2 MB) and 12 to 15 KB to a program using `window`127// alone; the page's JSON carries numbers as their bits so no program128// takes float formatting for it.129//130// **F6b as built** (2026-10-13), with the files and drops every platform131// shares:132// - `window`: `window.open_files(dialog)`, `save_file(dialog)` and133// `save_bytes(dialog, bytes)` (the web's download), each giving a134// request id answered by `Event::FilesChosen(Chosen { request, files })`,135// no files when cancelled; `ChosenFile { name, path, bytes }` as136// question 5 decided. Drops: `Event::DragEntered(Dragged { position,137// files, text })`, `DragMoved(Point)`, `DragLeft`, `Dropped(Drop {138// position, files, text })`. Headless: `Replay.dialogs`139// answers dialogs from the script. The web: an `<input type=file>`140// read into bytes, `showSaveFilePicker` where the browser has it and a141// download otherwise, and the canvas's drag events.142// - `ui`: `ui.open_files(dialog, (ui, files) => ...)` and143// `ui.save_file(...)`, handlers kept by request id; `on_drop` on144// `Column`, `Row` and `Stack`, the container under the pointer drawn145// with `look.drop_target` while something is dragged over it.146// - COM (`window/com.alloy`): interfaces as structs of C function types147// read from an object's table by slot (`method(obj, i)`), GUIDs parsed148// at compile time (`guid("...")`), objects Alloy makes being149// `c_pointer::keep`'d memory starting with their tables, counted by150// `AddRef` / `Release`, `QueryInterface` answering by GUID. The slots151// are checked against MinGW's headers by `tests/windows/com_layout.sh`.152// The window initializes OLE (single-threaded) on its thread.153// - UI Automation (`window/uia.alloy`): `WM_GETOBJECT` with154// `UiaRootObjectId` returns the window's root provider through155// `UiaReturnRawElementProvider`; every node is a provider with the156// Simple, Fragment and (the root) FragmentRoot tables, answering157// control type, name, value, enabled, focusable and focused, automation158// id, bounds, navigation through the kept tree, and the Invoke, Toggle,159// RangeValue, Value and ScrollItem patterns, each turned into an160// `Event::Action`; focus changes raise `UIA_AutomationFocusChangedEventId`161// and structure changes `ChildrenInvalidated` on the root. The Text162// pattern (caret and selection read by Narrator inside a field) is left163// out: fields read as their Value.164// - `window/shell.alloy`: `IFileOpenDialog` / `IFileSaveDialog` shown165// modal to the window, filters as `COMDLG_FILTERSPEC`, the results'166// `IShellItem` paths; an OLE `IDropTarget` registered with167// `RegisterDragDrop`, reading `CF_HDROP` files and `CF_UNICODETEXT`.168// - The compiler links `ole32`, `oleaut32`, `shell32` and169// `uiautomationcore` into Windows programs (17 libraries in all).170// - Tests: `tests/files` (dialogs and drops headless, under weston and in171// node's page), `ui/tests.alloy` (handlers and `on_drop`);172// `tests/automation.alloy` reads a window's tree back through173// `IUIAutomation` and presses, toggles and sets through the patterns,174// built here for Windows and run there by hand, as the window tests are.175// - Sizes: the counter grows to about 1.55 MB native and 1.25 MB on the176// web, whose budgets went to 1.6 and 1.3 MB.177//178// **F6c as built** (2026-10-13):179// - `pkg::alloy::dbus` (`dbus`, packed by `scripts/pack.sh`180// before `window`, which imports it): `wire.alloy` the marshalling181// (every basic type, arrays, structs, variants and dictionaries as one182// `Value` enum, aligned from the message's start, little-endian, read183// back either way), `dbus.alloy` messages (`Message::call`,184// `Message::signal`, `reply`, `error`) and the `Connection`:185// `session()`, `open(address)` over a Unix socket (`unix:path=` and186// `unix:abstract=`), SASL `EXTERNAL`, `Hello`, `call` waiting for its187// reply while queueing what else arrives, `send`, `receive` never188// blocking, `wait`, `add_match`, `request_name`, `get_property`, and189// `fd()` for a loop to poll. `dbus/tests.alloy`190// checks the wire format; `dbus/check.alloy` talks to a real bus.191// - File dialogs (`window/portal.alloy`): xdg-desktop-portal's192// `FileChooser.OpenFile` / `SaveFile` with the title, filters,193// `multiple` and `current_name`, its `Request.Response` signal read194// from the session bus the loop polls, `file://` URIs turned into195// paths. With no portal a dialog answers at once with no files.196// `dbus/fake_portal.alloy` answers dialogs for the tests.197// - AT-SPI (`window/atspi.alloy`): when `org.a11y.Status` says198// accessibility or a screen reader is on, the window joins the199// accessibility bus (`org.a11y.Bus.GetAddress`), embeds its application200// in the registry's desktop (`Socket.Embed`) and gives201// `Event::AccessRequested`; each node is an object under202// `/org/a11y/atspi/accessible/` answering `Accessible` (role, name,203// states, children, parent, index), `Component` (extents, in window204// coordinates, since Wayland gives no position), `Action` (press,205// toggle, focus), `Value`, `Text` and `EditableText` (a field's text,206// caret and selection, setting its contents), and the properties.207// Changes go out as `Object:StateChanged`, `PropertyChange`,208// `ChildrenChanged` and focus signals. `tests/atspi` reads its own209// window's tree through the registry as Orca does, then presses, toggles210// and sets values, under weston on the tests' own bus with211// at-spi2-core's launcher.212// - Wayland drops: `wl_data_device`'s `enter`, `motion`, `leave` and213// `drop`, offers of `text/uri-list` read as files and text as text,214// through the pipe the clipboard already polls; untested here, weston's215// headless backend having no seat to drag from.216// - `scripts/test.sh` runs every window program on a session bus of its217// own (a `dbus-daemon` that starts no service on demand), never the218// desktop's.219// - Sample `samples/viewer.alloy`: PNGs opened through the dialog or220// dropped, shown one at a time, turned gray or flipped, saved again221// (`samples/images/png.alloy` reads 8-bit and palette PNGs through its222// own inflate and writes stored deflate blocks; `images/check.alloy`223// compared it with zlib on the system's PNGs).224// - Sizes: D-Bus, AT-SPI, the portal and the data device add about225// 260 KB to a native Linux program using `window` (hello 1.57 MB, the226// counter 1.83 MB, the canvas's startup program 1.15 MB; budgets 1.6,227// 1.85 and 1.2 MB, the last raised with F7a), nothing on the web.228// - On the way the checker learnt that a `|&x|` capture into a temporary229// subject, kept past its statement, dangles (section 5.5), which the230// viewer's reader met as freed memory.231//232// **F7a as built** (2026-10-13), not yet run on a Mac:233// - `window/objc.alloy` (now `objc`): `Objc::load()` opens `libobjc.A.dylib` (on Linux234// libobjc2's `libobjc.so.4.6`) and keeps the runtime's functions;235// `send<F>()` and `send_struct<F>()` read `objc_msgSend` (or236// `objc_msgSend_stret` on x86-64) as a prototype; `sel`, `class`, and237// helpers for the common shapes (`call`, `call_with`, `call_integer`,238// `call_bool`, `integer`, `boolean`, `number`, `make`, `release`,239// `string`, `text_of`). Classes: `subclass` (the registered class when240// the name exists), `method` (a C function), `method_with` (a block241// holding a state pointer, through `imp_implementationWithBlock`),242// `add_state` / `state` / `set_state` (an instance variable), `adopt`.243// Blocks are global blocks in C's heap (`block`, `block_state`,244// `free_block`), never copied by the runtime. A lambda passed where a245// generic `F: CFunction` is expected does not take a C function type246// from it, so methods are written as typed constants first:247// `const f: extern (c_pointer, c_pointer, i64) -> i64 = (this, _, x) => x;`.248// - `window/objc_check.alloy` (now `objc/check.alloy`) runs on libobjc2 in `scripts/test.sh`: a249// root class made while running, messages with integers, doubles,250// floats, `BOOL`s, a 32-byte struct through `objc_msgSend_stret` and a251// 16-byte one in registers, methods as blocks holding Alloy values, an252// instance variable, a class found again by name.253// - `window/appkit.alloy`, `run`'s choice on both macOS targets: the254// frameworks open by their paths in `/System/Library/Frameworks`;255// classes `AlloyView` (an `NSView`: flipped, the mouse, wheel and256// touchpad, keys and modifiers, the cursor through a tracking area),257// `AlloyWindowDelegate` (closing, resizing, the scale, focus) and258// `AlloyApplicationDelegate` (quitting asks the program through259// `CloseRequested`; activation once launched), made once a process,260// their methods blocks reading the running window from a cell in C's261// heap, which is 0 between windows. The application menu holds Hide,262// Hide Others, Show All and Quit. `[NSApp run]` is the loop; closing263// the window stops it, a posted event making `stop:` take effect, and264// `run` returns.265// - Two run loop sources on the main thread, in the common modes so they266// fire during live resizing too: a Waker's (`Waker::AppKit`, which any267// thread signals through `CFRunLoopSourceSignal` and268// `CFRunLoopWakeUp`) and the frames', which a `CVDisplayLink` signals269// each refresh while a redraw is wanted and stops when none is. A270// resize is delivered and drawn at once, inside AppKit's resizing loop.271// - Keys by their virtual key codes (Events.h's `kVK_`), others by the272// character they write unmodified; text from `characters` when neither273// Command nor Control is held (input methods and dead keys wait for274// `NSTextInputClient` in F7c). Command is `Modifiers.super`, and `ui`'s275// fields take Command for their shortcuts on macOS (`shortcut` in276// `ui/fields.alloy`), Control elsewhere.277// - CPU frames become a `CGImage` (sRGB, 32-bit little-endian with the278// top byte skipped, the same pixels as Wayland's and GDI's) set as the279// view's layer's contents. `Target::AppKit` gives the window and view280// for F7b's Metal surface; the Vulkan device does not open on macOS, so281// the CPU device draws.282// - F7c's services answered as nothing until F7c: the clipboard empty,283// dialogs with no files, the accessibility tree dropped.284// - `scripts/test.sh` builds every sample and test program for both285// macOS targets; `scripts/macos.sh build <dir>` builds them in release286// beside the tests' expected output, and `run <dir> <host>` runs the287// tests on a Mac over SSH.288//289// **F7b as built** (2026-10-13), not yet run on a Mac:290// - The Objective-C layer became its own package, `pkg::alloy::objc`291// (`objc`, its check `objc/check.alloy`), which `window` and292// `gpu` both import.293// - MSL (`gpu/shader/msl.alloy`) is written from the SPIR-V the compiler294// makes of the checked WGSL rather than from the syntax tree: the295// module's types, layouts and structured control flow are settled there,296// and only what the compiler emits is read (no phi, selections and loops297// with their merges). Every value is a variable declared at the top of298// its function; components are read by index, never by swizzle; loops299// become `while (true)` with the continuing block repeated before each300// `continue`; structs keep their WGSL offsets through padding members,301// 3-component vectors in them packed; a function takes the resources it302// and its callees use as parameters. An entry point `name` becomes303// `alloy_name`, with structs of its stage's inputs and outputs and its304// resources at `metal_index`'s indices: buffers, textures and samplers305// each from 0 in the order the entry uses them, vertex buffers after the306// vertex stage's buffers.307// - `#shader` keeps the MSL in its blob (format version 3) on the macOS308// targets only; `#msl(source)` gives it on any target.309// `tests/msl_dump.alloy` writes the tests' and the canvas's, which310// `scripts/test.sh` compares with `tests/golden/msl` and compiles as311// C++17 with clang against `tests/metal/metal_stdlib`, a stand-in312// declaring the vector, matrix, packed, array and texture types, their313// operators and the functions MSL uses: it catches unknown names, wrong314// arities and mismatched types, not what Metal alone checks.315// - `gpu/metal/metal.alloy`, `Backend::Metal`, which `Automatic` takes on316// macOS: `MTLCreateSystemDefaultDevice`, one queue, buffers and textures317// in private storage, writes staged into a shared buffer and copied by a318// blit at the start of the next command buffer, reads through a shared319// buffer after waiting, at most three command buffers in flight. Bind320// groups keep their bindings and are bound per stage at each draw or321// dispatch, as are vertex buffers, whose index depends on the pipeline.322// Objects are released at once, command buffers keeping what they use.323// - Surfaces: a `CAMetalLayer` (BGRA8, not framebuffer-only, so copies324// reach it) set as the window's view's layer, each frame a drawable325// whose texture takes the surface's one texture slot, presented by a326// command buffer of its own.327// - `tests/scenes` and `tests/canvas` take `metal`; `scripts/macos.sh run`328// checks both against the goldens on a Mac.329//330// **F7c as built** (2026-10-13), not yet run on a Mac:331// - `pkg::alloy::objc` gained blocks returning structs larger than 16332// bytes (`struct_method_with`, `struct_block`): the block carries its333// type encoding and, on x86-64, `BLOCK_USE_STRET`, so a method made of334// it is called through `objc_msgSend_stret` (`block_signature` turns a335// method's encoding into the block's); `bool_code()` gives `BOOL`'s336// encoding, `B` on ARM64 and `c` on x86-64. The check on libobjc2 calls337// such a method and prints its signature.338// - `window/cocoa.alloy`: Foundation's points, sizes, rectangles and339// ranges, arrays, and the conversions between the view's pixels and the340// screen's points and between UTF-8 offsets and NSString's UTF-16 ones.341// - Input methods: `AlloyView` is an `NSTextInputClient`. While the342// program takes text (`set_text_input`), a key goes to343// `interpretKeyEvents:` after its `Key` event; `insertText:` gives344// `Text`, `setMarkedText:` gives `Preedit` (its caret at the end of the345// input method's selection), `unmarkText` types the composition as it346// is, and commands (`insertNewline:` and the others) do nothing, the347// `Key` events having carried them. A key pressed during a composition348// is the input method's alone, as on Windows. The candidates go below349// `firstRectForCharacterRange:`, the text input's area on the screen;350// moving it invalidates the input context's coordinates and taking no351// text discards a composition. With no text input, text still comes352// from the key's `characters`.353// - The menu bar gains an Edit menu (Cut, Copy, Paste, Select All with354// Command's keys); the view takes its commands as the key events they355// stand for (`Character('c')` with `super`), since AppKit gives Command356// shortcuts to the menu before the view.357// - The clipboard is the general `NSPasteboard`'s string358// (`setString:forType:`, `stringForType:`). Dialogs are `NSOpenPanel`359// and `NSSavePanel` run modal once the handler returns, as on Windows:360// the title as title and message, the filters' extensions as allowed361// types unless a pattern takes any file, several files when asked, the362// proposed name; paths from the chosen URLs.363// - Drops: the view registers for file URLs and strings and copies them;364// `draggingEntered:`, `draggingUpdated:`, `draggingExited:` and365// `performDragOperation:` give `DragEntered`, `DragMoved`, `DragLeft`366// and `Dropped`, files read as `NSURL`s through `filePathURL` (Finder367// gives file reference URLs), else the text.368// - VoiceOver (`window/nsaccessibility.alloy`): the view stands for the369// tree's root (`AXGroup`, its label the root's), and every other node370// gets an `AlloyAccessibilityElement`, a subclass of371// `NSAccessibilityElement` holding the node's id, made as it is reached372// and released once the node is gone. Nodes of no role are left out,373// their children standing in for them. Roles map to `AXButton`,374// `AXCheckBox`, `AXSlider`, `AXTextField` / `AXTextArea`,375// `AXStaticText` (a label's text as its value), `AXImage`, `AXList`,376// `AXScrollArea` and `AXGroup`; values are a checkbox's state and a377// slider's value as numbers, with its limits, and a field's text with378// its selection in UTF-16 units. Frames come from the nodes' bounds on379// the screen, hit tests and the focused element from the tree.380// Pressing, incrementing, decrementing, setting a value, focusing and381// selecting are queued as `Action`s and given once VoiceOver's call382// returns, through a third run loop source; `isAccessibilitySelectorAllowed:`383// offers each only on the nodes that take it. The first question about384// the view gives `AccessRequested`; updates post `AXValueChanged`,385// `AXTitleChanged`, `AXLayoutChanged`, `AXFocusedUIElementChanged` and386// `AXUIElementDestroyed` for the elements VoiceOver has.387// - Every sample and test program builds for both macOS targets; nothing388// of it has run on a Mac.389//390// **Fonts arriving** (2026-10-14; decisions/F10.md, question 6A):391// - `Event::FontsArrived` on the web once a font a program fetched for392// fallback (pkg::alloy::text's `fonts.fetch`) arrives: text's393// `browser.web.js` dispatches an `alloyfontsarrived` event on the page,394// which this package's listens to, so text knows nothing of windows.395// Never sent natively, where `fetch` reads the file at once. `ui` lays396// every text out again on it; a program drawing with `draw` alone lays397// its own out again.398// - Tests: `tests/fetch.alloy` lays its text out on the first frame and399// on the event only, in node's page (whose fetch now answers a fifth of400// a second late, past the first frames) and under weston.401//402// **F11a as built** (2026-10-15; decisions/F11.md, question 7A403// and "Accessibility on each platform"):404// - The window's clock: `window.now()`, monotonic from when the window405// opened; `Event::Redraw` carries the frame's time on it (on the web406// the `requestAnimationFrame` time). `window.wake_at(at)` sets the one407// deadline (`None` clears it), answered by `Event::Timer` at or after408// it: Wayland's `poll` timeout, Win32's `SetTimer` (`WM_TIMER`, at most409// about 24 days ahead), AppKit's `CFRunLoopTimer`, the page's410// `setTimeout`. A headless window's clock moves only as a script's411// `Redraw(at)` says, delivering the `Timer` passed on the way, and412// never goes back. With no deadline nothing wakes.413// - Roles `Dialog`, `Alert`, `Menu`, `MenuItem` and `Tooltip`;414// `Semantics` gains `modal`, `expanded: Option<bool>` and415// `description`; actions `Expand`, `Collapse` and `Dismiss`; `Key::Menu`.416// `window.announce(text, assertive)` speaks without the tree.417// - UI Automation: Menu, MenuItem and ToolTip control types, dialogs and418// alerts panes with `IsDialog`, the description as `HelpText` and419// `FullDescription`, the ExpandCollapse pattern, announcements through420// `UiaRaiseNotificationEvent` (assertive ones as `ImportantAll`,421// polite ones as `CurrentThenMostRecent`). No Window pattern, so Narrator's422// close goes through Escape.423// - AT-SPI: dialog, alert, menu, menu item and tool tip roles; states424// `MODAL`, `EXPANDABLE`, `EXPANDED` and `COLLAPSED`; `Description`;425// announcements as the `Announcement` signal, polite or assertive.426// - The web: `dialog`, `alertdialog`, `menu`, `menuitem`, `tooltip`;427// `aria-modal` with the content before it `inert`, `aria-expanded`,428// `aria-haspopup`, `aria-description`; announcements into `status` and429// `alert` live regions. The fake DOM's reader says them430// (`tests/access`).431// - macOS (built only): `AXMenu`, `AXMenuItem`, `AXHelpTag`, dialogs432// with the subroles `AXApplicationDialog` and433// `AXApplicationAlertDialog`, modal and expanded states, the434// description as help, `accessibilityPerformCancel` as `Dismiss`,435// announcements posted with their priority.436// - Tests: the clock in `window/tests.alloy`; `tests/frames` waits for a437// timer; `tests/access`, `tests/atspi` and `tests/automation` (by hand438// on Windows) read a menu, a modal alert and an announcement.439//440// **F11b as built** (2026-10-15; decisions/F11.md, "Choices" and441// "Accessibility on each platform"):442// - Roles `ComboBox`, `ListBox`, `ListOption`, `RadioGroup` and443// `RadioButton`; `Semantics` gains `selected: Option<bool>` and444// `position: Option<[u32 : 2]>` (from 1, and the count); `Action::Select`.445// What opens a popup says so by `expanded` alone: a combo box's is a446// list box, a button's or a menu item's a menu.447// - UI Automation: ComboBox with ExpandCollapse and a read-only Value,448// List with the Selection pattern (`GetSelection` a SAFEARRAY of the449// selected options' providers, through com's new `unknowns`), ListItem450// and RadioButton with SelectionItem (`Select` and `AddToSelection` as451// `Action::Select`, the container their parent), `PositionInSet` and452// `SizeOfSet`; an option or radio becoming selected raises453// `SelectionItemIsSelected` and `ElementSelected`.454// - AT-SPI: combo box (with the Text interface reading its value), list455// box, list item and radio button roles, a radio group a panel; states456// `SELECTABLE`, `SELECTED` and `HAS_POPUP`; `posinset` and `setsize`457// attributes; `StateChanged` `selected`.458// - The web: `combobox` (its value as its text), `listbox`, `option`,459// `radiogroup`, `radio`; `aria-selected`, `aria-posinset`,460// `aria-setsize`, `aria-haspopup` `listbox` or `menu`.461// - macOS (built only): `AXPopUpButton`, `AXMenuButton` for a button462// opening a menu, `AXList` of `AXStaticText` options, `AXRadioGroup`,463// `AXRadioButton`; `isAccessibilitySelected`, `setAccessibilitySelected:`464// as `Select`, `accessibilityPerformShowMenu` as `Expand`.465// - Tests: `tests/access` sends a combo box, a list box and a radio group,466// which node's page prints; `tests/atspi` and `tests/automation` (by467// hand on Windows) open a `Select`, choose an option and a radio.468//469// **F11c as built** (2026-10-15; decisions/F11.md, "Screens",470// question 6B, and "Accessibility on each platform"):471// - Roles `TabList` and `Tab` (`selected`, `position`): UI Automation's472// Tab with the Selection pattern and TabItem with SelectionItem (and473// its selection events); AT-SPI's page tab list and page tab, a tab474// `SELECTABLE`, `SELECTED` and pressed by its action; ARIA's `tablist`475// and `tab` with `aria-selected`; macOS (built only) an `AXTabGroup` of476// `AXRadioButton`s of subrole `AXTabButton`, their value 1 when477// selected, `setAccessibilitySelected:` as `Select`.478// - The page's history: `HistoryEntry { depth, path }`,479// `window.set_history(depth, path)` (kept, and sent once a change),480// `window.start_path()` and `Event::Navigated`. On the web481// `browser.web.js` marks the page's entries with their depth482// (`history.state.alloyDepth`): a deeper entry is pushed, a level each,483// at `#<path>`, a shallower one reached by `history.go`, whose484// `popstate` it waits for before following again, a new path at the485// same depth replaces the address, and an empty path keeps it. A486// `popstate` it did not cause gives `Navigated` with the entry's depth487// (one deeper for an entry it did not make, as an address typed) and488// the fragment's path. Headless, `Replay.history` keeps each entry489// set; elsewhere nothing has a history.490// - Tests: the history headless in `window/tests.alloy`;491// `tests/history` in node's page, whose fake `history` opens at492// `#/start` and a person goes back twice and forward once, and under493// weston, which has none; `tests/access` sends a tab list.494//495// **F11d as built** (2026-10-15; decisions/F11.md, "Dates and496// times" and "Accessibility on each platform"):497// - Roles `Grid` and `GridCell`; `Semantics` gains `cell: Option<[u32 :498// 2]>` (a cell's row and column, from 0, which each tree's rows and499// counts come from) and `current` (today among a calendar's days).500// - UI Automation: Calendar with the Grid (`GetItem`, row and column501// counts), Table (no headers, row major) and Selection patterns,502// DataItem with GridItem (its place, spans of one, the grid) and503// SelectionItem; `current` as `AriaProperties` `current=date`.504// - AT-SPI: calendar with the Table interface (`NRows`, `NColumns`,505// `GetAccessibleAt`, `GetIndexAt`, `GetRowAtIndex`,506// `GetColumnAtIndex`, `IsSelected`), table cell with TableCell507// (`Position`, spans, `Table`, `GetRowColumnSpan`), clicked by its508// action; `current` as the attribute `current:date`.509// - The web: `grid`, its cells put in `row` elements the page makes from510// their rows, `gridcell`, `aria-current="date"`.511// - macOS (built only): `AXTable` of `AXRow` elements standing for no512// node, made per grid and row and released with the grid, holding the513// `AXCell`s; `accessibilityRows`, row and column counts and index514// ranges; `current` not given.515// - Tests: `tests/access` sends three days in two rows, which node's516// page prints.517// - Question 19A (2026-10-16): a button with a value, a date picker's518// date, gives it in every tree: UI Automation's Value pattern, read519// only; AT-SPI's Text interface, as a combo box's; the web's520// `aria-label` "<label>, <value>"; `AXValue` on macOS, as before.521// `tests/access`, `tests/atspi` and `tests/automation` read it.522//523// **F11e as built** (2026-10-15; decisions/F11.md, "Reduced524// motion"): `window.reduced_motion()`, read as the window opens, and525// `Event::ReducedMotion(bool)` as it changes. Linux: the settings portal526// (`org.freedesktop.portal.Settings.Read`, a second at most) for GNOME's527// `enable-animations`, else KDE's `AnimationDurationFactor` at 0, and its528// `SettingChanged` signal, the portal's session bus now joined as the529// window opens; Windows: `SPI_GETCLIENTAREAANIMATION` and530// `WM_SETTINGCHANGE`; macOS (built only): `NSWorkspace`'s531// `accessibilityDisplayShouldReduceMotion` and its notification, observed532// by the window's delegate; the web: `matchMedia("(prefers-reduced-motion:533// reduce)")` and its `change`; headless: off but as a script's event says.534// The test portal (`dbus/fake_portal.alloy`) answers the setting.535//536// **F12a as built** (2026-10-15; decisions/F12.md, "Timers"):537// on the web the page shown again (`visibilitychange` to visible, the538// page event Timer with `a` set) gives an `Event::Timer` whether or not539// the deadline has come, a hidden page's `setTimeout` running late; the540// fake page's `ALLOY_PAGE=shown` hides and shows it. A headless run's541// `Replay` counts `wakes`, the deadlines `wake_at` changed.542//543// **F12c as built** (2026-10-16; decisions/F12.md, "Waiting in544// ui"):545// - The page's `Waker::Page`, which `run_browser` gives the window: its546// `wake()` posts a message on a `MessageChannel` (`al_window_wake`),547// once for wakes close together, which comes back as the page event548// Woken (24) and an `Event::Woken`, the next task, before the next549// frame; the channel closes with the window.550// - `Role::ProgressBar` (UI Automation's ProgressBar, its RangeValue read551// only; AT-SPI's `progress bar` with the Value interface; ARIA's552// `progressbar` with `aria-valuenow`; `AXProgressIndicator`), its value553// in `range` and as text in `value`, none while not known; and554// `Semantics.busy` (UIA's `AriaProperties` `busy=true`, after555// `current=` when both, AT-SPI's `BUSY` state with its `StateChanged`556// event, `aria-busy`, and `isAccessibilityElementBusy` for AXElementBusy,557// not yet run on a Mac). `tests/access` gives a progress bar and a busy558// list, read by node's fake screen reader; `tests/atspi` reads both559// through at-spi2-core.560// - The fake page's `fetch` (tests/web/dom.mjs) hands a URL naming a561// server to node's own fetch.562//563// **F12d as built** (2026-10-16; decisions/F12.md, "Storage"):564// `WindowConfig.app` (default "", `app_name()` giving the title then),565// kept as `Window.app` and sent as the toplevel's `app_id` on Wayland,566// `window.app_name()` giving it to pkg::alloy::ui's store as the app starts567// (2026-10-17, question 23B); the fake page's `localStorage`, kept in the file `ALLOY_PAGE_STORAGE`568// names and refusing every write with `ALLOY_PAGE=full`.569//570// **Closing refused** (2026-10-17; decisions/showcase.md,571// question 6A): `Event::CloseRequested` comes on every platform and the572// window stays open until the program calls `close` (Wayland's573// `xdg_toplevel.close`, Win32's `WM_CLOSE`, AppKit's `windowShouldClose:`574// and `applicationShouldTerminate:` answered no, as since F1 and F7a);575// the web gains it from `beforeunload`, the page's handler giving the576// event and, when the program did not close its window, asking the577// browser to ask the person (its own words: the most a page may do).578// `Navigated` now sets the window's history entry, so an entry the579// program sets after it goes to the page only when it differs: a program580// refusing to go back is put back deeper. `tests/history` in node's page581// leaves the page, which the program refuses.582//583// **Fields in error** (2026-10-17; showcase.md, question 11A):584// `Semantics.invalid`, a field whose value is refused, its description585// saying why: UI Automation's `IsDataValidForForm` false and `invalid=true`586// in `AriaProperties`, AT-SPI's `INVALID_ENTRY` state (with its587// `StateChanged`), `aria-invalid` on the web. NSAccessibility has no588// property for it (the old API's `AXInvalid` attribute only), so on macOS589// the message as the element's help is what VoiceOver says, not yet run590// on a Mac. `tests/access` gives a field in error (read in node's page),591// `tests/atspi` and `tests/automation` an empty field "Required".592//593// **Checked menu items** (2026-10-17; showcase.md, question 12A):594// `Role::MenuItemCheckbox` with `checked`: UI Automation's MenuItem with595// the Toggle pattern, AT-SPI's CHECK_MENU_ITEM with its CHECKABLE and596// CHECKED states, ARIA's `menuitemcheckbox` with `aria-checked`, and597// macOS's `AXMenuItem` with the value 0 or 1. `tests/access` gives one.598//599// **Secret input** (2026-10-20; decisions/F13.md, question600// 13A): `Semantics.secret`, a field hiding what is typed, its value the601// dots it shows: UI Automation's `IsPassword` (the Value pattern giving602// the dots), AT-SPI's `PASSWORD_TEXT` role (its Text the dots), on the603// web the layer's node an `<input type="password">` holding the dots, as604// a page's own password field reads (no ARIA role says it), and on605// macOS the `AXSecureTextField` subrole, not yet run on a Mac.606// `window.set_secret_input(secret)` tells the input method: Wayland's607// text-input-v3 content type (purpose password, hints hidden_text and608// sensitive_data; enabled again to go back to normal), on Windows no609// input context associated, as an ES_PASSWORD edit has (characters610// still as WM_CHAR), on the web a hidden `<input type="password">`611// taking the keyboard instead of the textarea, and on macOS keys612// skipping the input method and `EnableSecureEventInput` held while the613// window has the focus, as NSSecureTextField does. Headless:614// `Replay.secret_input`. `tests/access` gives a password's field.615//616// **F14a as built** (2026-10-20; decisions/F14.md, "Right to617// left"): `WindowConfig.languages` lists the languages an app has, its618// first the one it falls back to (`["en"]` by default), which619// pkg::alloy::ui chooses among. `window.set_language(tag, right_to_left)`620// says what its content is in, kept as `language()` and621// `right_to_left()` and taken by each platform as it asks622// (`Requests.language`): UI Automation's `Culture` property, the LCID623// `LocaleNameToLCID` gives, on every node; AT-SPI's `GetLocale` and624// `Locale` (`ar_EG.UTF-8`, as POSIX writes it); on the web the layer's625// `lang` and `dir`; on macOS the view's626// `userInterfaceLayoutDirection` (NSAccessibility has no language of627// its own for an element), not yet run on a Mac. `Semantics.right_to_left`628// marks a node reading the other way than the window, the web's `dir`629// on it (UI Automation and AT-SPI have no direction for a node).630// Headless: `Replay.language` and `right_to_left`. Tests: `tests/access`631// (`lang`, `dir` and a node's own), `tests/atspi` (the locale of an app632// in British English), `window/tests.alloy` (the replay keeping the633// last).634//635// **F14b as built** (2026-10-20; decisions/F14.md, "Text for636// screen readers"): `AccessNode.text`, a `TextMap` (graphemes' starts and637// edges, word starts, lines with their boxes in the node's pixels and638// direction, one `TextFormat`) that pkg::alloy::ui sends with a field and639// a text of several lines while a screen reader reads, never on the web;640// maps compare by `revision` alone. `text_ranges.alloy` answers from one641// for every platform: `unit_at` and `moved` by `TextUnit` (a character a642// grapheme, a word to the next one's start, a line as drawn, a paragraph643// to a line break, the document), `boxes` (one a line, more where the644// direction changes, the caret's a pixel wide), `offset_at`,645// `grapheme_at`, `visible_lines`, `clamped`, and `TextMap::plain` for a646// value no layout was sent for. A secret field's map is of its dots.647// - UI Automation (`uia.alloy`, not yet run on Windows): `ITextProvider`648// and `ITextProvider2` on a node with a map, each range an649// `ITextRangeProvider` of its own holding the node and two byte650// offsets clamped to the text at each call, the attributes and the651// events of F14.md's list; ranges whose provider is gone answer652// `UIA_E_ELEMENTNOTAVAILABLE`. `tests/windows/com_layout.sh` checks the653// three tables' slots and those the client in `tests/automation` calls654// against MinGW's headers; `tests/automation` reads a note by line and655// word, its rectangles, its font, a field's caret range, a word selected656// through `Select` and the `TextSelectionChanged` that follows (its657// expected output written by hand), and `windows-tests.ps1` lists the658// steps to try with Narrator and NVDA in `notes.exe`, which gains an659// Arabic note.660// - AT-SPI (`atspi.alloy`): `Text` completed, offsets in code points:661// `GetStringAtOffset` by granularity (sentences as paragraphs),662// `GetTextAtOffset`, `Before` and `After` by boundary,663// `GetCharacterAtOffset`, `GetCharacterExtents` and `GetRangeExtents`664// in window coordinates, `GetOffsetAtPoint`, the selection's five665// methods (one selection, a field's), `GetAttributes`,666// `GetAttributeRun`, `GetDefaultAttributes` and `AttributeSet`,667// `GetAttributeValue` (`family-name`, `size` in points, `weight`,668// `fg-color`, `language`, `direction`, `editable`), `ScrollSubstringTo`,669// and the signals `TextChanged:delete` and `insert` (the text between a670// common start and end), `TextCaretMoved` and `TextSelectionChanged`. A671// combo box's and a button's value answer through a plain map.672// `tests/atspi` reads a wrapped note and a field through at-spi2-core.673// The window reaches AT-SPI's handling of trees through674// `Window.atspi`, which `update_access` sets, and Text's answers675// through `Atspi.texts`, which the first tree taken sets, so a program676// sending no tree (hello world) links neither: 63.5 KB of it.677// - macOS (`nsaccessibility.alloy`, built for both targets, not yet run678// on a Mac): `accessibilityInsertionPointLineNumber`, `LineForIndex:`,679// `RangeForLine:`, `StringForRange:`, `AttributedStringForRange:` (the680// font's family and size, the color, `NSAccessibilityLanguageTextAttribute`),681// `FrameForRange:`, `RangeForPosition:`, `RangeForIndex:` (graphemes),682// `StyleRangeForIndex:`, `VisibleCharacterRange` and `SelectedText`, in683// UTF-16 units, and `AXSelectedTextChanged` when a selection moves.684// - Tests: `window/tests.alloy` over maps written by hand (every unit at685// both ends, moves past the ends, boxes across a change of direction,686// points between lines and past the text).687//688// **R6f as built** (2026-10-26; REFOCUS.md, question 3B, and689// the portal and drops under pkg::alloy::ui_app): what a program690// installs.691// - `window.install_access()` (pkg::alloy::ui_access calls it) and692// `window.install_files()` (ui_app's `Files`, and `open_files` and693// `save_file` themselves) each push a `Start` into the requests: one694// variant a platform, holding the function that platform starts the695// part with once the handler returns. That function sets the platform's696// `Parts`, the function values its loop and window procedure call from697// then on, so a program never installing either reaches none of their698// code: on Linux AT-SPI and D-Bus, the portal and the data device's699// drags and drops; on Windows UI Automation (`Uia` made at the start,700// WM_GETOBJECT passed on to Windows before), the OLE drop target and701// the shell's dialogs; on macOS the view's accessibility methods and702// the elements' class (added to the registered class at the start),703// `MacAccess`, the dragging methods and the panels; on the web the704// "Turn on accessibility" button (`al_window_access_start`, the layer's705// code in `layer.web.js` since 14B) and drops reaching the program706// (`al_window_files_start`; before, the page refuses them), the layer's707// JSON and the dialogs. Headless windows need nothing started.708// - Without `install_access`, `update_access` and `announce` do nothing709// and nothing gives `Event::AccessRequested`; `set_language` still710// keeps the language (a replay's `language`) but reaches no screen711// reader. Without `install_files`, a drag over a Wayland window is let712// go unaccepted, and a dropped file opens nothing in the page.713// - Reduced motion on Linux is read through the settings portal only714// once either is installed (`start_portal`, then715// `Event::ReducedMotion` if it is on), with screen readers alone716// through `Portal::read_settings`, which leaves the file chooser's717// answers out; until then a Wayland window reads it as off. Windows,718// macOS and the web read it as before.719// - AT-SPI starts after the first handler installing it, no longer as720// the window opens; `Window.atspi` (F14b's indirect tree) is gone, its721// work done by the start.722// - Tests: `window/tests.alloy` installs in its tree's replays and checks723// one not installing; `tests/access` and `tests/files` install.724//725// **14B as built** (2026-10-27; REFOCUS.md, question 14): the page's726// accessibility layer in a module of its own, `layer.alloy` with727// `layer.web.js`, whose externs only the installed layer calls, so a web728// program bundles its JavaScript only when it installs screen readers;729// it reaches the canvas, its scale, events, keys and focus through730// `alloy.page`, which `browser.web.js` fills, and records there the731// elements it adds (removed as the window closes) and the layer (part of732// the window when focus moves). The counter's glue 9.8 KB smaller.733734import std::string;735import std::vector;736import std::option;737import std::process;738import std::io;739import std::ffi;740import std::map;741import std::fs;742import std::time;743import std::equal;744745import headless;746import wayland;747import win32;748import appkit;749import browser;750import posix;751import text_ranges;752753// A size in pixels.754exp type Size = struct {755 exp width: u32,756 exp height: u32,757};758759// A position in pixels from the window's top left.760exp type Point = struct {761 exp x: f32,762 exp y: f32,763};764765// A rectangle in pixels from the window's top left.766exp type Area = struct {767 exp x: f32,768 exp y: f32,769 exp width: f32,770 exp height: f32,771};772773pub fn contains(self area: &Area, point: Point) -> bool {774 return point.x >= area.x775 && point.y >= area.y776 && point.x < area.x + area.width777 && point.y < area.y + area.height;778}779780// How the window opens.781exp type WindowConfig = struct {782 exp title: &[u8],783 exp size: Size, // in logical pixels784 exp resizable: bool,785 // the app's name, which its data is kept under (std::storage) and786 // Wayland's app_id; the title when empty787 exp app: &[u8] = &"",788 // the languages the app is written in, as BCP 47 tags, its first789 // the one it falls back to: `ui` lays it out in the first of the790 // system's preferred languages it has, and in that one's direction791 exp languages: &[&[u8]] = &[&"en"],792};793794// A resizable window of 800 by 600 logical pixels.795exp fn WindowConfig::titled(title: &[u8]) -> WindowConfig {796 return WindowConfig {797 .title = &title,798 .size = Size { .width = 800, .height = 600 },799 .resizable = true800 };801}802803// The name the app's data is kept under: its own, else the title.804exp fn app_name(self config: &WindowConfig) -> &[u8] {805 return if (config.app.length() > 0) &config.app else &config.title;806}807808// The modifier keys held during an event.809exp type Modifiers = struct {810 exp shift: bool,811 exp control: bool,812 exp alt: bool,813 exp super: bool, // the Windows or Command key814};815816// No modifier key held.817exp fn Modifiers::none() -> Modifiers => Modifiers {818 .shift = false,819 .control = false,820 .alt = false,821 .super = false822};823824// A key, by what the keyboard layout makes of it: the same physical key825// is `Character('z')` on a QWERTY layout and `Character('y')` on a QWERTZ826// one. Text typed comes separately, as `Event::Text`.827exp type Key = enum {828 // a key writing a character, as a Unicode code point, lower case:829 // `Character(' ')` for the space bar830 Character: u32,831 Enter,832 Escape,833 Backspace,834 Tab,835 Delete,836 Insert,837 Left,838 Right,839 Up,840 Down,841 Home,842 End,843 PageUp,844 PageDown,845 Function: u8, // F1 to F24846 Shift,847 Control,848 Alt,849 Super,850 CapsLock,851 Menu, // the context menu's key852 Unknown: u32, // the platform's code for the key853};854855// A key pressed or released.856exp type KeyEvent = struct {857 exp key: Key,858 exp pressed: bool,859 exp repeat: bool, // a press repeated while the key is held860 exp modifiers: Modifiers,861};862863// A mouse button, or a pen's or touchpad's equivalent.864exp type PointerButton = enum {865 Left,866 Right,867 Middle,868 Back,869 Forward,870 Other: u32,871};872873// A button pressed or released where the pointer is.874exp type ButtonEvent = struct {875 exp button: PointerButton,876 exp pressed: bool,877 exp position: Point,878 exp modifiers: Modifiers,879};880881// A wheel's or touchpad's scrolling, positive down and to the right.882exp type ScrollEvent = struct {883 exp delta: Point,884 // the delta is in physical pixels (a touchpad), not in lines (a885 // wheel's notches)886 exp precise: bool,887 exp modifiers: Modifiers,888};889890// What happens to the window, in the order it happens.891exp type Event = enum {892 // the window's size changed, and when it opens; a Redraw follows893 Resized: Size,894 // the scale changed, and when it opens if not 1; a Resized follows895 Scaled: f32,896 // the window needs drawing: when it opens, after a resize, and after897 // `request_redraw`, paced by the display; the frame's time on the898 // window's clock (`now`)899 Redraw: Duration,900 // the time `wake_at` asked for has come901 Timer,902 // the user asked to close the window (on the web, to leave or reload903 // the page); it closes when the program calls `close`, and a program904 // not calling it keeps it open (on the web the browser then asks the905 // person whether to leave, in its own words)906 CloseRequested,907 Focused: bool,908 PointerMoved: Point,909 PointerLeft,910 Button: ButtonEvent,911 Scroll: ScrollEvent,912 Key: KeyEvent,913 // text typed, as UTF-8: a character, or several when an input method914 // commits a composition915 Text: String,916 // the composition an input method has in progress, which the program917 // shows at the caret in place of the last one, until a Text commits918 // it; an empty one ends it, and comes before the Text919 Preedit: Preedit,920 // another task woke the loop through the window's `Waker`; wakes921 // close together may come as one922 Woken,923 // the clipboard's text, after `request_clipboard`; empty when it924 // holds none925 Clipboard: String,926 // a screen reader started reading the window: the program sends its927 // whole accessibility tree, then its changes (`update_access`)928 AccessRequested,929 // what a screen reader asks of a node of the tree930 Action: ActionRequest,931 // the files a dialog `open_files` or `save_file` showed gave, none932 // when cancelled933 FilesChosen: Chosen,934 // something dragged from another program came over the window, moved935 // over it, left it, or was dropped on it936 DragEntered: Dragged,937 DragMoved: Point,938 DragLeft,939 Dropped: Drop,940 // on the web, a font the program fetched (pkg::alloy::text's941 // `fonts.fetch`) has arrived: text laid out before it may show boxes942 // it now covers, to lay out again; never sent elsewhere, where a943 // fetch reads the file at once944 FontsArrived,945 // on the web, the browser's Back or Forward, or an address typed,946 // moved to another entry of the page's history (`set_history`)947 Navigated: HistoryEntry,948 // the system's setting asking for less motion changed: whether it949 // asks now (`reduced_motion`)950 ReducedMotion: bool,951};952953// Where a program is in the page's history: how deep in its own954// entries, from 1, and its path, which the address shows after a `#`955// (`/events/42`), empty for none.956exp type HistoryEntry = struct {957 exp depth: u64,958 exp path: String,959};960961// Text an input method is composing, not yet typed.962exp type Preedit = struct {963 exp text: String,964 exp cursor: u64, // the input method's caret in the text, in bytes965};966967/* --- Files and drops (PLAN.md, F6) --- */968969// A kind of file a dialog offers: its name and its patterns, `*.png`.970exp type FileFilter = struct {971 exp name: String,972 exp patterns: Vector<String>,973};974975exp fn FileFilter::of(name: &[u8], patterns: &[&[u8]]) -> FileFilter {976 var filter = FileFilter { .name = String::from(&name), .patterns = Vector<String>::empty() };977 for (patterns) |&pattern| {978 filter.patterns.push(String::from(&pattern));979 }980 return move filter;981}982983// What a file dialog shows.984exp type FileDialog = struct {985 exp title: String = String::empty(),986 exp filters: Vector<FileFilter> = Vector<FileFilter>::empty(),987 exp multiple: bool = false, // opening: more than one file988 exp name: String = String::empty(), // saving: the name proposed989};990991// A file chosen or dropped: its name, and on the desktop its path, on992// the web its bytes when opened or dropped (a page reaches no paths).993exp type ChosenFile = struct {994 exp name: String,995 exp path: Option<String> = ::None,996 exp bytes: Option<Vector<u8>> = ::None,997 // the page's handle to write a saved file through, 0 for a download998 pub handle: u32 = 0,999};10001001// The file at the path, named by its last part in the style.1002pub fn ChosenFile::at(style: PathStyle, path: &[u8]) -> ChosenFile => ChosenFile {1003 .name = String::from(&file_name_in(style, &path)),1004 .path = ::Some(String::from(&path))1005};10061007// The files a dialog gave, for the request `open_files` or `save_file`1008// returned.1009exp type Chosen = struct {1010 exp request: u64,1011 exp files: Vector<ChosenFile>,1012};10131014// What is being dragged over the window, where.1015exp type Dragged = struct {1016 exp position: Point,1017 exp files: bool,1018 exp text: bool,1019};10201021// What was dropped on the window, where.1022exp type Drop = struct {1023 exp position: Point,1024 exp files: Vector<ChosenFile>,1025 exp text: Option<String>,1026};10271028// A dialog the program asked for, which the platform shows once the1029// handler returns.1030pub type DialogRequest = struct {1031 pub id: u64,1032 pub save: bool,1033 pub dialog: FileDialog,1034};10351036// A saved file's bytes for the page to write.1037pub type PageSave = struct {1038 pub file: ChosenFile,1039 pub bytes: Vector<u8>,1040};10411042/* --- Accessibility (PLAN.md, F6) --- */10431044// What a node of the accessibility tree is to a screen reader.1045exp type Role = enum {1046 Unknown, // nothing a screen reader shows; its children stand in for it1047 Window,1048 Group,1049 Label,1050 Button,1051 CheckBox,1052 Slider,1053 TextInput,1054 Image,1055 List,1056 ListItem,1057 ScrollView,1058 // a layer above the content (decisions/F11.md): a dialog, an1059 // alert asking for an answer, a menu and its items, a tooltip1060 Dialog,1061 Alert,1062 Menu,1063 MenuItem,1064 Tooltip,1065 // choices (F11b): a closed list showing the chosen item, opening a1066 // list box of options; radio buttons in a group1067 ComboBox,1068 ListBox,1069 ListOption,1070 RadioGroup,1071 RadioButton,1072 // screens (F11c): a row of tabs, one selected, showing a view of its1073 // own beside it1074 TabList,1075 Tab,1076 // dates (F11d): cells in rows and columns, a calendar's days1077 Grid,1078 GridCell,1079 // waiting (F12c): how much of a piece of work is done, its range's1080 // value, or not known without one1081 ProgressBar,1082 // a menu item turning a setting on or off, `checked` saying which1083 MenuItemCheckbox,1084};10851086// How a node describes itself: its role, what a screen reader says of it1087// and what can be done with it.1088exp type Semantics = struct {1089 exp role: Role = Role::Unknown,1090 exp label: String = String::empty(),1091 exp value: String = String::empty(), // a field's text, a slider's value as said1092 exp disabled: bool = false,1093 exp focusable: bool = false,1094 exp checked: Option<bool> = ::None, // a checkbox's or a checked menu item's state1095 exp multiline: bool = false,1096 exp range: Option<AccessRange> = ::None, // a slider's1097 exp selection: Option<[u64 : 2]> = ::None, // a field's anchor and caret, in bytes1098 // a dialog keeping the pointer and the keyboard from the rest1099 exp modal: bool = false,1100 // whether what it opens is open: a menu item's submenu1101 exp expanded: Option<bool> = ::None,1102 // what more a screen reader says of it after its label: a tooltip's text1103 exp description: String = String::empty(),1104 // whether an option or a tab is the one selected1105 exp selected: Option<bool> = ::None,1106 // where an option or a radio is among its group's, from 1, and how1107 // many there are: "2 of 3"1108 exp position: Option<[u32 : 2]> = ::None,1109 // a grid cell's row and column, from 01110 exp cell: Option<[u32 : 2]> = ::None,1111 // the current one of its kind: today among a calendar's days1112 exp current: bool = false,1113 // what it shows is still coming: a list loading1114 exp busy: bool = false,1115 // a field whose value is refused, its description saying why1116 exp invalid: bool = false,1117 // a field a form needs filled in1118 exp required: bool = false,1119 // a field hiding what is typed, a password: its value is the dots1120 // shown, one a character1121 exp secret: bool = false,1122 // a subtree reading in a direction of its own, against what holds it:1123 // true right to left (the web's `dir` on its element)1124 exp right_to_left: Option<bool> = ::None,1125};11261127exp type AccessRange = struct {1128 exp value: f64,1129 exp minimum: f64,1130 exp maximum: f64,1131 exp step: f64,1132};11331134// A node of the tree: its semantics, where it is in the window, in1135// pixels, its children in order, and a field's text or a text of several1136// lines as laid out, while a screen reader reads (text_ranges.alloy).1137exp type AccessNode = struct {1138 exp id: u64,1139 exp semantics: Semantics,1140 exp bounds: Area,1141 exp children: Vector<u64>,1142 exp text: Option<TextMap> = ::None,1143};11441145// A node's text as laid out (decisions/F14.md, F14b): its1146// value, a field's, or else its label, cut into graphemes, words and1147// lines, positions in bytes and pixels from the node's top left. Maps1148// compare by revision alone.1149exp type TextMap : Equal = struct {1150 exp revision: u32, // changes whenever anything below does1151 exp graphemes: Vector<u32>, // where each grapheme starts, then the text's end1152 exp edges: Vector<[f32 : 2]>, // each grapheme's left and right on its line1153 exp words: Vector<u32>, // where each word starts (UAX #29)1154 exp lines: Vector<TextLine>,1155 exp format: TextFormat, // one: a node's text has one style1156};11571158exp fn equals(self map: &TextMap, other: &TextMap) -> bool => map.revision == other.revision;11591160// A line as drawn: its bytes, its box and whether it reads right to left.1161exp type TextLine = struct {1162 exp start: u32,1163 exp end: u32,1164 exp box: Area,1165 exp right_to_left: bool,1166};11671168// How a node's text is drawn, as screen readers tell it.1169exp type TextFormat = struct {1170 exp family: String,1171 exp size: f32, // in pixels1172 exp weight: u32,1173 exp color: [u8 : 4], // red, green, blue, alpha1174 exp language: String, // BCP 471175 exp heading: bool,1176 exp read_only: bool,1177};11781179// What changed in the tree: the nodes new or changed, whole, and those1180// gone; the root and the focused node as they are now.1181exp type TreeUpdate = struct {1182 exp nodes: Vector<AccessNode>,1183 exp removed: Vector<u64>,1184 exp root: u64,1185 exp focus: Option<u64>,1186};11871188// What a screen reader asks of a node.1189exp type Action = enum {1190 Click,1191 Focus,1192 Increment,1193 Decrement,1194 SetValue: String,1195 ScrollIntoView,1196 SetSelection: [u64 : 2], // anchor and caret, in bytes1197 Expand, // open what it opens: a submenu1198 Collapse,1199 Dismiss, // close a dialog or menu, as Escape does1200 Select, // choose an option, a radio, a tab or a day1201};12021203exp type ActionRequest = struct {1204 exp node: u64,1205 exp action: Action,1206};12071208// What a screen reader is to say at once, without the focus moving: a1209// toast's text; `assertive` interrupts what it is saying.1210exp type Announcement = struct {1211 exp text: String,1212 exp assertive: bool,1213};12141215// The tree as the updates sent so far leave it, with each node's1216// parent.1217exp type AccessTree = struct {1218 exp nodes: Map<u64, AccessNode>,1219 exp root: u64,1220 exp focus: Option<u64>,1221 parents: Map<u64, u64> = Map<u64, u64>::empty(),1222};12231224exp fn AccessTree::empty() -> AccessTree => AccessTree {1225 .nodes = Map<u64, AccessNode>::empty(),1226 .root = 0,1227 .focus = ::None1228};12291230exp fn apply(self tree: &var AccessTree, update: TreeUpdate) {1231 for (update.removed.view()) |id| {1232 tree.nodes.remove(&id);1233 tree.parents.remove(&id);1234 }1235 var nodes = move update.nodes;1236 while (nodes.pop() is ::Some |move node|) {1237 if (tree.nodes.try_get(&node.id) is ::Some |&old|) {1238 // a child moved under another node keeps that one1239 for (old.children.view()) |child| {1240 if (tree.try_parent_of(child) == ::Some(node.id)) {1241 tree.parents.remove(&child);1242 }1243 }1244 }1245 for (node.children.view()) |child| {1246 tree.parents.insert(child, node.id);1247 }1248 tree.nodes.insert(node.id, move node);1249 }1250 tree.root = update.root;1251 tree.focus = update.focus;1252}12531254// The node holding a node, none for the root or one not in the tree.1255exp fn try_parent_of(self tree: &AccessTree, id: u64) -> Option<u64> {1256 if (tree.parents.try_get(&id) is ::Some |&parent|) {1257 return ::Some(parent);1258 }1259 return ::None;1260}12611262// The deepest node under `from` holding the point, in the window's1263// pixels, the last child holding it at each level.1264exp fn node_at(self tree: &AccessTree, from: u64, point: Point) -> Option<u64> {1265 var found = Option<u64>::None;1266 var k = from;1267 while (tree.nodes.try_get(&k) is ::Some |&node|) {1268 var next = Option<u64>::None;1269 for (node.children.view()) |child| {1270 if (tree.nodes.try_get(&child) is ::Some |&c| && c.bounds.contains(point)) {1271 next = ::Some(child);1272 }1273 }1274 if (next is ::Some |child|) {1275 found = next;1276 k = child;1277 } else {1278 break;1279 }1280 }1281 return found;1282}12831284// How the pointer looks over the window.1285exp type Cursor = enum {1286 Arrow,1287 Hand, // over something to click1288 Text, // over text to select or type into1289};12901291// Wakes a window's event loop from another task (`window.waker()`), its1292// handler then given an Event::Woken: tasks finishing work tell the1293// window this way. Copied to as many tasks as need it; one woken after1294// its window closed does nothing.1295exp type Waker = enum {1296 None, // a headless window, which no other task wakes1297 Eventfd: i32, // Wayland's loop polls it beside the compositor's socket1298 Win32: c_pointer, // the HWND, posted a message1299 AppKit: AppKitWaker,1300 // the page's, which a callback of the browser's wakes: a message1301 // posted to it, taken before the next frame1302 Page,1303};13041305// The main run loop's source a Waker signals on macOS, and the1306// CoreFoundation functions signalling it, which any thread may call.1307exp type AppKitWaker = struct {1308 pub signal: c_pointer, // CFRunLoopSourceSignal1309 pub wake_up: c_pointer, // CFRunLoopWakeUp1310 pub source: c_pointer,1311 pub run_loop: c_pointer,1312};13131314// Signals the source and wakes its run loop, from any thread.1315pub fn signal(self waker: &AppKitWaker) {1316 (copy waker.signal as extern (c_pointer))(waker.source);1317 (copy waker.wake_up as extern (c_pointer))(waker.run_loop);1318}13191320// The native objects a GPU surface draws into, for pkg::alloy::gpu.1321exp type Target = enum {1322 None, // a headless window, or one only `present` draws into1323 Wayland: WaylandTarget,1324 Win32: Win32Target,1325 AppKit: AppKitTarget,1326 // the page's canvas, marked `data-alloy-window` with the number1327 Canvas: u32,1328};13291330exp type WaylandTarget = struct {1331 exp display: c_pointer, // the wl_display1332 exp surface: c_pointer, // the wl_surface1333};13341335exp type Win32Target = struct {1336 exp instance: c_pointer, // the HINSTANCE1337 exp window: c_pointer, // the HWND1338};13391340exp type AppKitTarget = struct {1341 exp window: c_pointer, // the NSWindow1342 exp view: c_pointer, // its content view, an NSView whose layer is drawn into1343};13441345// What the handler asked of the window, which the platform takes once1346// the handler returns (`take_requests`) and does in this order: the1347// title, the cursor and the text input's area when they changed (the1348// window holding them), the clipboard's new text, the accessibility1349// tree's updates, file dialogs and the page's saves, a wish for the1350// clipboard's text, then closing. Frames (`present`, `request_redraw`)1351// stay on the window, which painting reads.1352pub type Requests = struct {1353 pub title: bool = false,1354 pub cursor: bool = false,1355 pub text_input: bool = false,1356 pub clipboard: Option<String> = ::None,1357 pub access: Vector<TreeUpdate> = Vector<TreeUpdate>::empty(),1358 pub announcements: Vector<Announcement> = Vector<Announcement>::empty(),1359 pub dialogs: Vector<DialogRequest> = Vector<DialogRequest>::empty(),1360 pub page_saves: Vector<PageSave> = Vector<PageSave>::empty(),1361 pub clipboard_wanted: bool = false,1362 pub close: bool = false,1363 pub wake: bool = false, // `wake_at` changed the deadline1364 pub history: bool = false, // `set_history` changed the entry1365 pub language: bool = false, // `set_language` changed it1366 // what `install_access` and `install_files` installed, for the1367 // platform to start1368 pub starting: Vector<Start> = Vector<Start>::empty(),1369};13701371// How a platform starts what a program installs into its window1372// (REFOCUS.md, R6f): screen readers (`install_access`), file1373// dialogs and drops (`install_files`). The platform reaches them only1374// through the function an install gives here and what it sets up, so a1375// program installing neither links none of their code: AT-SPI and1376// D-Bus, UI Automation, NSAccessibility and the page's accessibility1377// layer, the portal, the shell's dialogs and the drop targets.1378pub type Start = enum {1379 Wayland: (&var Wayland),1380 Win32: (&var Win32),1381 AppKit: (&var AppKit),1382 Browser: (&var Browser),1383};13841385// The window the handler is given with each event. What the handler asks1386// of it takes effect once the handler returns.1387exp type Window = struct {1388 pub size: Size,1389 pub scale: f32,1390 pub focused: bool = false,1391 pub title: String,1392 pub app: String, // the config's app, else its title1393 pub redraw_requested: bool = false,1394 pub closing: bool = false,1395 // the pixels presented since the platform last took them1396 pub frame: *var [u32],1397 pub frame_size: Size = Size { .width = 0, .height = 0 },1398 pub presented: bool = false,1399 pub target: Target = Target::None,1400 // a GPU surface presented a frame since the platform last looked1401 pub surface_presented: bool = false,1402 pub text_input: Option<Area> = ::None,1403 pub secret_input: bool = false, // the text typed is a password's1404 pub cursor: Cursor = Cursor::Arrow,1405 pub waker: Waker = Waker::None,1406 pub asked: Requests = Requests {}, // since the platform last took them1407 pub requests: u64 = 0, // the last file dialog's id1408 // the window's clock: monotonic from when it opened, or for a headless1409 // window (None) standing at `time` but as its script moves it1410 pub clock: Option<Instant> = ::None,1411 pub time: Duration = Duration::from_nanoseconds(0),1412 pub wake: Option<Duration> = ::None, // when to give an Event::Timer1413 // where the program is in the page's history, once it said, and the1414 // path the page was opened at1415 pub history: Option<HistoryEntry> = ::None,1416 pub start_path: String = String::empty(),1417 // whether the system asks for less motion, as read when the window1418 // opened and since changed1419 pub reduced_motion: bool = false,1420 // the language its content is in, a BCP 47 tag, and whether it reads1421 // right to left1422 pub language: String = String::from(&"en"),1423 pub right_to_left: bool = false,1424 // whether screen readers and files are installed1425 pub access: bool = false,1426 pub files: bool = false,1427};14281429pub fn Window::opening(config: &WindowConfig, scale: f32) -> Window {1430 return Window {1431 .size = physical(&config.size, scale),1432 .scale = scale,1433 .title = String::from(&config.title),1434 .app = String::from(&config.app_name()),1435 .frame = new [0 to u32 : 0],1436 .clock = ::Some(Instant::now())1437 };1438}14391440// The name the app's data is kept under (`WindowConfig.app_name()`).1441exp fn app_name(self window: &Window) -> &[u8] => &window.app.view();14421443// What the handler asked since the platform last took it.1444pub fn take_requests(self window: &var Window) -> Requests {1445 var taken = move window.asked;1446 window.asked = Requests {};1447 return move taken;1448}14491450// Shows the cursor while the pointer is over the window.1451exp fn set_cursor(self window: &var Window, cursor: Cursor) {1452 if (window.cursor != cursor) {1453 window.cursor = cursor;1454 window.asked.cursor = true;1455 }1456}14571458exp fn cursor(self window: &Window) -> Cursor {1459 return window.cursor;1460}14611462// Lets the platform's screen readers reach the window: AT-SPI on Linux1463// (with the settings portal's wish for less motion), UI Automation on1464// Windows, NSAccessibility on macOS, and on the web a layer of elements1465// behind a "Turn on accessibility" button. Until then nothing gives1466// Event::AccessRequested and `update_access` and `announce` do nothing;1467// a program never calling it links none of them (pkg::alloy::ui_access1468// calls it).1469exp fn install_access(self window: &var Window) {1470 if (!window.access) {1471 window.access = true;1472 if (target() == "linux-x86_64" || target() == "linux-aarch64") {1473 window.asked.starting.push(Start::Wayland((w) => w.start_atspi()));1474 } else if (target() == "windows-x86_64") {1475 window.asked.starting.push(Start::Win32(start_automation));1476 } else if (target() == "macos-arm64" || target() == "macos-x86_64") {1477 window.asked.starting.push(Start::AppKit(start_voiceover));1478 } else if (target() == "web-wasm32") {1479 window.asked.starting.push(Start::Browser(start_layer));1480 }1481 }1482}14831484// Lets files be chosen through the platform's dialogs and dropped on1485// the window: the desktop portal on Linux (with its wish for less1486// motion), the shell's dialogs and OLE's drops on Windows, NSOpenPanel,1487// NSSavePanel and the view's dragging on macOS, the page's file input,1488// file pickers and drops. `open_files` and `save_file` install them;1489// without, nothing dropped reaches the program, and a program never1490// installing them links none of them (pkg::alloy::ui_app calls it).1491exp fn install_files(self window: &var Window) {1492 if (!window.files) {1493 window.files = true;1494 if (target() == "linux-x86_64" || target() == "linux-aarch64") {1495 window.asked.starting.push(Start::Wayland(start_files_wayland));1496 } else if (target() == "windows-x86_64") {1497 window.asked.starting.push(Start::Win32(start_files_win32));1498 } else if (target() == "macos-arm64" || target() == "macos-x86_64") {1499 window.asked.starting.push(Start::AppKit(start_files_appkit));1500 } else if (target() == "web-wasm32") {1501 window.asked.starting.push(Start::Browser(start_files_page));1502 }1503 }1504}15051506// Sends the accessibility tree's changes to the platform's screen1507// readers, after an Event::AccessRequested.1508exp fn update_access(self window: &var Window, update: TreeUpdate) {1509 if (window.access) {1510 window.asked.access.push(move update);1511 }1512}15131514// Has the platform's screen readers say the text, politely or, when1515// `assertive`, at once, once the tree's updates are sent.1516exp fn announce(self window: &var Window, text: String, assertive: bool) {1517 if (window.access) {1518 window.asked.announcements.push(Announcement { .text = move text, .assertive = assertive });1519 }1520}15211522// Puts the text on the clipboard.1523exp fn set_clipboard(self window: &var Window, text: String) {1524 window.asked.clipboard = ::Some(move text);1525}15261527// Asks for the clipboard's text, which an Event::Clipboard gives.1528exp fn request_clipboard(self window: &var Window) {1529 window.asked.clipboard_wanted = true;1530}15311532// Shows a dialog choosing files to open; an Event::FilesChosen with the1533// returned request gives them.1534exp fn open_files(self window: &var Window, dialog: FileDialog) -> u64 {1535 return window.ask(false, move dialog);1536}15371538// Shows a dialog choosing where to save, `dialog.name` proposed; an1539// Event::FilesChosen with the returned request gives the file, which1540// `save_bytes` writes.1541exp fn save_file(self window: &var Window, dialog: FileDialog) -> u64 {1542 return window.ask(true, move dialog);1543}15441545fn ask(self window: &var Window, save: bool, dialog: FileDialog) -> u64 {1546 window.install_files();1547 window.requests += 1;1548 window.asked.dialogs.push(DialogRequest {1549 .id = window.requests,1550 .save = save,1551 .dialog = move dialog1552 });1553 return window.requests;1554}15551556// Writes the bytes into a file `save_file` gave: at its path on the1557// desktop, and on the web through the page (where the browser lets a1558// page write a chosen file) or as a download; whether it was written or1559// given to the page.1560exp fn save_bytes(self window: &var Window, file: &ChosenFile, bytes: &[u8]) -> bool {1561 if (file.path is ::Some |&path|) {1562 return write_file(&path.view(), &bytes);1563 }1564 if (target() != "web-wasm32") {1565 return false;1566 }1567 window.asked.page_saves.push(PageSave { .file = copy file, .bytes = Vector<u8>::from(&bytes) });1568 return true;1569}15701571// The time on the window's clock: monotonic, from when the window1572// opened; a headless window's stands still but as its script moves it.1573exp fn now(self window: &Window) -> Duration {1574 if (window.clock is ::Some |&opened|) {1575 return opened.elapsed();1576 }1577 return window.time;1578}15791580// Asks for an Event::Timer at the time on the window's clock, or after;1581// each call replaces the time the last asked for, and None asks for none.1582exp fn wake_at(self window: &var Window, at: Option<Duration>) {1583 if (window.wake != at) {1584 window.wake = at;1585 window.asked.wake = true;1586 }1587}15881589// The deadline `wake_at` set, once it has come, taken so the Timer is1590// given once.1591pub fn take_due(self window: &var Window) -> bool {1592 if (window.wake is ::Some |at| && window.now().nanoseconds >= at.nanoseconds) {1593 window.wake = ::None;1594 return true;1595 }1596 return false;1597}15981599// How long until the deadline `wake_at` set, none when there is none.1600pub fn until_wake(self window: &Window) -> Option<Duration> {1601 if (window.wake is ::Some |at|) {1602 const now = window.now().nanoseconds;1603 return ::Some(1604 Duration::from_nanoseconds(if (at.nanoseconds > now) at.nanoseconds - now else 0)1605 );1606 }1607 return ::None;1608}16091610// Keeps the page's history in step with where the program is: a deeper1611// entry goes into the history after the one shown (the browser's Back1612// then giving Event::Navigated), a shallower one goes back to it and a1613// new path replaces the shown entry's; an empty path leaves the address1614// as it is. Only a page has a history: elsewhere this does nothing.1615exp fn set_history(self window: &var Window, depth: u64, path: String) {1616 var entry = HistoryEntry { .depth = depth, .path = move path };1617 if (window.history != ::Some(copy entry)) {1618 window.history = ::Some(move entry);1619 window.asked.history = true;1620 }1621}16221623// Tells screen readers the language the window's content is in, a BCP1624// 47 tag, and whether it reads right to left: UI Automation's Culture,1625// AT-SPI's locale, the accessibility layer's `lang` and `dir` on the1626// web, the view's layout direction on macOS.1627exp fn set_language(self window: &var Window, tag: &[u8], right_to_left: bool) {1628 if (window.language.view() != tag || window.right_to_left != right_to_left) {1629 window.language = String::from(&tag);1630 window.right_to_left = right_to_left;1631 window.asked.language = true;1632 }1633}16341635// The language `set_language` gave, "en" until then.1636exp fn language(self window: &Window) -> &[u8] => &window.language.view();16371638exp fn right_to_left(self window: &Window) -> bool => window.right_to_left;16391640// Whether the system asks programs for less motion: GNOME's animations1641// off or KDE's at no length through the settings portal, Windows'1642// "Animation effects" off, macOS's "Reduce motion", a page's1643// `prefers-reduced-motion`; never in a headless window but as its script1644// says. Event::ReducedMotion tells a change.1645exp fn reduced_motion(self window: &Window) -> bool {1646 return window.reduced_motion;1647}16481649// The path the page was opened or reloaded at, after the address's `#`;1650// empty elsewhere.1651exp fn start_path(self window: &Window) -> &[u8] {1652 return &window.start_path.view();1653}16541655// What wakes the window's loop from another task.1656exp fn waker(self window: &Window) -> Waker {1657 return window.waker;1658}16591660// Wakes the window's loop, which gives its handler an Event::Woken.1661exp fn wake(self waker: &Waker) {1662 if (target() == "linux-x86_64" || target() == "linux-aarch64") {1663 if (waker is ::Eventfd |fd|) {1664 wake_eventfd(fd);1665 }1666 } else if (target() == "windows-x86_64") {1667 if (waker is ::Win32 |hwnd|) {1668 wake_win32(hwnd);1669 }1670 } else if (target() == "macos-arm64" || target() == "macos-x86_64") {1671 if (waker is ::AppKit |&w|) {1672 w.signal();1673 }1674 } else if (target() == "web-wasm32") {1675 if (waker is ::Page) {1676 wake_page();1677 }1678 }1679}16801681// The size in physical pixels.1682exp fn size(self window: &Window) -> Size {1683 return window.size;1684}16851686// Physical pixels per logical pixel.1687exp fn scale(self window: &Window) -> f32 {1688 return window.scale;1689}16901691// Whether the window has the keyboard.1692exp fn focused(self window: &Window) -> bool {1693 return window.focused;1694}16951696// The title the window shows.1697exp fn title(self window: &Window) -> &[u8] {1698 return &window.title.view();1699}17001701// Changes the title the window shows.1702exp fn set_title(self window: &var Window, title: &[u8]) {1703 window.title = String::from(&title);1704 window.asked.title = true;1705}17061707// Asks for a Redraw event when the display is next ready for a frame:1708// called while handling Redraw, it draws one frame after another.1709exp fn request_redraw(self window: &var Window) {1710 window.redraw_requested = true;1711}17121713// Closes the window, which ends `run` once the handler returns.1714exp fn close(self window: &var Window) {1715 window.closing = true;1716 window.asked.close = true;1717}17181719// Turns the platform's input method on while a text field has the1720// keyboard, giving the caret's area, which the input method's own windows1721// keep clear of: compositions then come as Preedit events. ::None turns it1722// off, as it starts. Text typed comes as Text events either way.1723exp fn set_text_input(self window: &var Window, area: Option<Area>) {1724 if (window.text_input != area) {1725 window.text_input = area;1726 window.asked.text_input = true;1727 }1728}17291730// Tells the input method whether the text typed is a password, hidden as1731// it is typed: then nothing composes and nothing typed is remembered or1732// suggested (Wayland's content purpose, no input context on Windows, a1733// password input on the web, secure input on macOS).1734exp fn set_secret_input(self window: &var Window, secret: bool) {1735 if (window.secret_input != secret) {1736 window.secret_input = secret;1737 window.asked.text_input = true;1738 }1739}17401741// Shows the pixels, `size` of them row by row from the top left, each1742// 0xRRGGBB (the top byte unused): software drawing, for a window no GPU1743// surface draws into. The window shows them scaled to its size when the1744// two differ.1745exp fn present(self window: &var Window, pixels: &[u32], size: Size) {1746 if (pixels.length() != size.width to u64 * size.height to u64) {1747 panic "present: the pixels are not width by height";1748 }1749 if (window.frame.length() != pixels.length()) {1750 window.frame = new [0 to u32 : pixels.length()];1751 }1752 window.frame[..] = pixels;1753 window.frame_size = size;1754 window.presented = true;1755}17561757// The native objects a GPU surface draws into.1758exp fn target(self window: &Window) -> Target {1759 return window.target;1760}17611762// Tells the window a GPU surface presented a frame into it, in place of1763// `present`, for pkg::alloy::gpu: the window then neither draws its own1764// frame nor waits for the display before the next Redraw, which the1765// surface's presenting paces.1766exp fn surface_presented(self window: &var Window) {1767 window.surface_presented = true;1768}17691770// Keeps what the event says of the window, before the handler sees it.1771pub fn apply(self window: &var Window, event: &Event) {1772 match (event) {1773 ::Resized |size| {1774 window.size = size;1775 }1776 ::Scaled |scale| {1777 window.scale = scale;1778 }1779 ::Focused |focused| {1780 window.focused = focused;1781 }1782 ::ReducedMotion |reduced| {1783 window.reduced_motion = reduced;1784 }1785 // the page is at that entry now: an entry the program sets after1786 // it, as one deeper when it stays, goes to the page again1787 ::Navigated |&entry| {1788 window.history = ::Some(copy entry);1789 }1790 else {}1791 }1792 window.time = if (event is ::Redraw |t|) t else window.now();1793}17941795// The size in physical pixels for a logical size at the scale.1796pub fn physical(logical: &Size, scale: f32) -> Size {1797 return Size {1798 .width = scaled(logical.width, scale),1799 .height = scaled(logical.height, scale)1800 };1801}18021803pub fn scaled(length: u32, scale: f32) -> u32 {1804 return (length to f32 * scale + 0.5) to u32;1805}18061807// Copies the pixels of one size into another, scaled to it, nearest1808// first.1809pub fn copy_scaled(source: &[u32], from: Size, target: &var [u32], size: Size) {1810 if (from == size) {1811 target[..source.length()] = source;1812 return;1813 }1814 if (from.width == 0 || from.height == 0) {1815 return;1816 }1817 for ([..size.height to u64]) |y| {1818 const row = (y * from.height to u64 / size.height to u64) * from.width to u64;1819 const out = y * size.width to u64;1820 for ([..size.width to u64]) |x| {1821 target[out + x] = source[row + x * from.width to u64 / size.width to u64];1822 }1823 }1824}18251826type App<S> = struct {1827 state: S,1828 handler: |=| (&var S, &var Window, &Event),1829};18301831// Opens the window and runs the platform's event loop, calling the1832// handler with the state and each event until the window closes; gives1833// the exit status for `main`, 1 when no window can open (the reason1834// printed). In a browser, whose event loop goes on after `main` returns,1835// it returns 0 at once, leaving the window running.1836exp fn run<S>(config: &WindowConfig, state: S, handler: |=| (&var S, &var Window, &Event)) -> i32 {1837 var app: *var App<S> = new App<S> { .state = move state, .handler = move handler };1838 return run_platform(&config, |move app| (window: &var Window, event: &Event) {1839 app.handler(&var app.state, &var window, &event);1840 });1841}18421843fn run_platform(config: &WindowConfig, handler: |&| (&var Window, &Event)) -> i32 {1844 if (target() == "web-wasm32") {1845 return run_browser(&config, move handler);1846 } else if (target() == "linux-x86_64" || target() == "linux-aarch64") {1847 return run_wayland(&config, move handler);1848 } else if (target() == "windows-x86_64") {1849 return run_win32(&config, move handler);1850 } else if (target() == "macos-arm64" || target() == "macos-x86_64") {1851 return run_appkit(&config, move handler);1852 }1853 print_error(&"pkg::alloy::window: no window system for this target\n");1854 return 1;1855}