1// A retained, fine-grained reactive UI over pkg::alloy::draw2// (PLAN.md, stage F5): values the UI shows live in signals,3// elements are made once from option structs, and a binding remakes an4// element's options when a signal it read changes, so only that element5// is laid out or painted again.6//7// ```text8// fn counter(ui: &var Ui) -> Element {9// const count = ui.signal(0);10// return ui.add(Column {11// .gap = 8.0,12// .padding = Padding::all(16.0),13// .children = &[14// ui.bind((ui) => Text::from(f"Clicked {count.get(&ui)} times")),15// ui.add(Button::text(&"Add one", (ui) => count.update(&var ui, (n) => n += 1))),16// ],17// });18// }19//20// fn main() -> i32 {21// return app(&WindowConfig::titled(&"Counter"), counter);22// }23// ```24//25// Coordinates are logical pixels from an element's top left, y down.26//27// ## How it was built28//29// Notes kept from each stage as it was finished, the sizes and numbers30// of their day; what changed since is in REVIEW.md and the history.31//32// **F5a as built** (2026-10-13):33// - `ui`, the package `pkg::alloy::ui`: `ui.alloy` the API34// (`Ui`, `Signal<T>`, `Element`, `Widget` and its defaults, `Arrange`,35// `Look`, `Input`, the option types, `app`, and `replay`, which runs an36// app headless on the CPU device over events for tests), `store.alloy`37// (signals, effects, owners, `show` and `each`), `tree.alloy`,38// `layout.alloy` (with `Column`, `Row`, `Stack`), `painting.alloy`,39// `events.alloy`, `widgets.alloy` (`Text`, `Button`), `running.alloy`.40// - A signal's value sits behind an object downcast per instantiation; a41// read inside a binding goes into a `Mutex`-held list, since `get` has42// only `&Ui`, and subscribes the binding stamped with its run, so a43// rerun forgets what it no longer reads without unsubscribing. Effects44// run owners nearer the root first; `show` and `each` keep their own45// state in signals nothing reads.46// - `each` took `u64` keys at first, `std::hash::Key` and `window`'s `Key`47// clashing in the module importing both; since 2026-10-13 it takes any48// `K: hash::Key`, std's module imported `as hash` (section 6.4's49// aliases, which reach its names only qualified). A row reads its item50// through its own signal and changes it through the list's.51// - An element's children are `&[Element]` in its options, adopted by52// `add`; `show` and `each` make transparent elements laid out as part53// of their parent. Canvas nodes are added under the parent's as the tree54// is painted, so a row moved by `each` keeps its place in drawing order55// (only overlapping rows would show it).56// - `window`'s mouse button enum is now `PointerButton`, `Button` being57// the widget; `draw` gained `canvas.contains(node)`.58// - Tests: `ui/tests.alloy` (signals and reruns, layout as numbers,59// `show` and `each` with what they free, clicks), `tests/widgets.alloy`60// goldens in `tests/golden/ui` through `replay`. Samples61// `counter.alloy`, `toggles.alloy`. The counter idles at no CPU under62// weston.63//64// **F5b as built** (2026-10-13):65// - Focus: Tab and Shift+Tab move it in tree order among the elements66// taking it, a press gives it without the ring, the keyboard with it;67// `Input` gains `Key`, `Text`, `Preedit` and `Focus`, which go to the68// focused element and bubble; `ui.focus`, `ui.has_focus`, and69// `ui.refresh(change)`, by which a widget handling input says its own70// state changed.71// - `Widget` gains `focusable`, `cursor`, `caret` (the input method's72// area) and `clips`: a clipping element paints into a canvas node under73// one clipped to its bounds, its children beside it.74// - `TextField` (`fields.alloy`, from `samples/editor.alloy`: one line75// scrolling to the caret, or several wrapping; placeholder,76// `on_change`, `on_submit`), `Checkbox` (its check mark a coverage mask77// made with the canvas, in `Look.marks`), `Slider`; `Theme::dark()`.78// - `window` gains `Cursor` and `set_cursor` (Wayland's cursor-shape79// with the pointer's entering serial, Win32's `WM_SETCURSOR`, the80// page's CSS); the app shows the hovered element's cursor and gives the81// focused field's caret to the input method.82// - Not built: the waker and background work, question 4 (built after83// F5c, "Background work as built").84// - Tests: keyboard, fields, compositions, checkboxes and sliders in85// `ui/tests.alloy`; goldens `inputs`, `inputs_dark`, `editing`. Samples86// `todo.alloy`, `form.alloy`.87//88// **F5c as built** (2026-10-13):89// - `Scroll` (`scrolling.alloy`): its one child moved under a clip by the90// wheel (a notch 40 logical pixels, a touchpad's pixels as given) or by91// dragging its bar; at its ends the wheel goes on to the scrolls around92// it; the keyboard's focus scrolls the scrolls holding the focused93// element to show it. `Widget` gains `overlay`, what a clipping element94// draws over its children (the bar), in a canvas node after theirs.95// - `ui.list(count, row, options)`: `count` a binding, rows made by `row`96// from their index for the view and a screen's worth either side, each97// in an owner freed once out of that range; rows measured as made, the98// rest standing at the average measured (or `estimate`; `fixed` rows99// are not measured); the view keeps its place as a row and an offset100// within it. The list asks for rows from its layout through a signal,101// so `update_all` runs bindings and layout again, up to four times,102// until nothing is marked.103// - `Wrap`, `Grid` (`Track::Fixed`, `Content`, `Fraction`; its columns a104// `Vector<Track>`: options a binding renews may hold no references to105// temporaries, which children's `&[Element]` escape only because `add`106// reads them at once), and `Image` (`ui.image(width, height, pixels)`107// keeps RGBA pixels, made a picture on the canvas when it is there;108// `Fit::Contain`, `Cover`, `Fill`).109// - `Input::Scroll` to the element under the pointer, bubbling;110// `ui.scroll_at` drives it in tests and benchmarks. `tests/support/png`'s111// `Image` is `Bitmap`, `Image` being the widget.112// - Tests: wraps, grids, scrolls, revealing the focused element, the list113// in `ui/tests.alloy`; goldens `grid_wrap`, `images`, `list`,114// `scrolled`. Samples `gallery.alloy`, `rows.alloy` (10,000 rows).115// - Benchmarks (`bench/ui.alloy`, on the CPU; budgets set from these):116// 1,000 bound texts made and laid out in 4.5 ms; one change among117// 10,000 bound texts 0.2 ms; the 10,000-row list scrolled a row 0.03118// ms. The counter is 1.39 MB native and 1.08 MB on the web, the bundled119// font most of it. Frames are the canvas's benchmarks'; scrolling a row120// a frame on a GPU waits for the person running the samples.121// - Memory (2026-10-13, after F5c): an element's bytes measured from the122// resident set's growth over 10,000 texts, each Ui first showing one so123// its fonts and device are not counted, and now also with the canvas's124// part, drawn offscreen on the CPU device (`ui.draw_offscreen`). From125// 6,390 bytes a drawn text (1,480 not drawn, 2,000 bound) to 1,440126// (1,030, 1,120), the frames as fast and every golden image the same:127// - the canvas no longer keeps each node's instances encoded (48 floats128// a glyph) from frame to frame, only its bounds, a text's its layout's129// box with half its size around; a frame encodes the nodes meeting its130// damaged rectangles as it gathers them, and a node's world transform131// and clip are worked out on the way down instead of kept;132// - a `Text` makes its paint when laid out and drops its layout at once,133// and painting takes that paint (`Widget::take_paint`), so no text134// keeps a layout;135// - kept vectors give back their room (`Vector::shrink`, std; layouts136// and paints), and std's vectors grow by half rather than doubling,137// which keeps the copies a growth fills within half the elements (the138// compiler builds itself as fast);139// - `draw` gained `Paint::shrink`.140// An element is still past the plan's "well under 1 KB" drawn: the two141// node structs (the Ui's 144 bytes, the canvas's about 210) and a142// glyph's 36 bytes in the canvas are most of it.143// - Images freed (2026-10-13): `ui.set_image(id, width, height, pixels)`144// shows other pixels in every element showing the image and145// `ui.free_image(id)` gives it back, an `ImageId` carrying a generation146// so an id freed names nothing; `draw`'s `canvas.release_picture` gives147// back a large picture's texture or its area of an atlas page, the next148// picture fitting taking it and a page holding none starting again.149// Sample: `gallery.alloy`'s "Move the disc".150//151// **Background work as built** (2026-10-13, question 4):152// - `window`: `Event::Woken` and `window.waker()`, a `Waker` copied to153// other tasks whose `wake()` gives the loop a `Woken` (wakes close154// together may come as one): on Wayland an `eventfd` polled beside the155// compositor's socket, on Windows a `WM_APP + 1` posted to the window,156// on the web and headless nothing.157// - `ui.background(work)`: in `app`, natively, four worker tasks in a158// `scope` around the window's loop take the work through a159// `std::sync::Channel`, send what each gives back through another and160// wake the loop, whose `Woken` moves those into the Ui to run before the161// next update; closing the window closes the work's channel, and `app`162// returns once the workers end the work they are doing. On the web, in163// `replay` and in a Ui made on its own the work runs at once and what164// it gives at the next update. `ui.quit()` closes the app's window.165// - std: `Channel::try_receive`; and the runtime's futex wake took a166// count of every waiter as -1, so `Channel::close` woke one receiver167// waiting on Linux (`tests/run/sync.alloy` now waits on four).168// - The work owns what it captures: decided as capture bounds on function169// types (spec section 5.4), `background` taking170// `|=| () -> |=| (&var Ui)`. Every callback the Ui keeps (options'171// `on_press` and `on_change`, `bind`, `show`, `each`, `list`, `app`'s172// view, `window::run`'s handler) is `|=|`, so none outlives what it would173// borrow; `Signal::update`'s change, called at once, is `|&|`.174// - Tests: `ui/tests.alloy` (work with no workers), `tests/background`175// (eight pieces of work on the workers, under weston and in node's176// page). Sample `background.alloy` (counting primes below 100 million,177// a billion and ten billion, 0.2 s, 1.8 s and about 20 s here, with a178// button and a field to use meanwhile).179//180// **Fonts arriving** (2026-10-14; decisions/F10.md, question181// 6A): on `Event::FontsArrived` (the web, a fetched font arrived) `app`182// lays out and paints every element again (`invalidate_all`), so text183// shown in boxes until then takes the font unasked; tested in184// `ui/tests.alloy`.185//186// **F11a as built** (2026-10-15; decisions/F11.md, "Layers"):187// - Time (question 7A, `timers.alloy`): `ui.now()` is the window's clock,188// set from each event's time (`Redraw` carries it); `ui.after(delay,189// then)` gives a `Timer` (an index and a generation, so a cancelled or190// run timer names nothing) whose `then` runs as a handler, `ui.cancel`191// forgets one. Timers sit in a heap of due times, belong to the owner192// making them and go with it; after each update `ui` asks193// `window.wake_at` for the earliest, or for none. `replay` scripts194// time by `Redraw(at)` events.195// - Layers (`layers.alloy`): `ui.open(overlay, view) -> Layer`, `close`196// (nothing if closed), `is_open`, `source()` (the element whose handler197// runs, an anchor; a fault outside handlers). A layer is a host node198// after the content's root, its own canvas node, holding the scrim199// (modal, the theme's new `scrim`, black at 40% light and 60% dark), and200// a panel (the theme's surface, `radius`, a border and the theme's new201// `shadow`) around the view's element. The host lays the view out202// within the window less 16 pixels and places it (`Place::Center`,203// `Below`, `Above`, `After` 4 pixels from the anchor and flipped when204// there is no room, `At` a point, `Corner`), kept inside the window; an205// anchored layer moves with its anchor and closes once it is freed or206// out of view. A layer belongs to the owner of the element whose207// handler opened it, else the app; its view's elements belong to it.208// Widgets freed during a handler wait in a graveyard until the event209// ends, so a handler may close the layer holding its button.210// - Pointer and keys: hits go through the layers, topmost first, a modal211// one ending the search and its scrim taking presses; a press outside212// the topmost non-modal layer with `outside` closes it and goes no213// further. Opening a layer that takes the keyboard focuses its first214// element taking focus (a modal one keeping the focus off what is215// below), closing it gives the focus back. Tab goes round a modal216// layer's elements and closes menus. Escape goes to the focused217// element, then closes a tooltip, the focus's layer, else the topmost218// layer with `escape`. `on_close` runs whichever way it closes.219// - Size: menus, tooltips and toasts are reached only through `Hooks`220// function values a program sets by using them, and the toasts' state221// is behind an object; the counter grew by 32 KB natively and 28 KB on222// the web all the same (question 16), from 159 KB before the hooks.223// - Accessibility: each layer's panel is a node after the content's,224// `Dialog` or `Alert` and `modal`, a `Menu` of `MenuItem`s (`expanded`225// on one with a submenu, its shortcut as the description), a toast226// layer a group; a tooltip's text is its child's description, and227// `Action::Dismiss` closes a layer. The roles each platform gives are228// in pkg::alloy::window's notes.229// - Tests: eight in `ui/tests.alloy` (a dialog's focus, Tab, Escape and230// scrim; placement and flipping; a layer going with its row; menu keys231// and submenus; context menus by press, drag and release and by232// Shift+F10; a tooltip's time, keys and description; toasts' order,233// pausing and waiting; a dialog in the access tree); goldens234// `dialog.png`, `dialog_dark.png`, `menu.png`, `tooltip.png` and235// `toasts.png` in `tests/golden/ui`; `tests/atspi` and236// `tests/automation` open an alert and show a toast. Benchmark237// `ui_dialog`: a dialog opened and closed over the 10,000-row list,238// 0.021 ms; a program opening no layer pays one empty vector's check.239// - Sample `dialogs.alloy`: orders with a "⋯" menu and a context menu, a240// rename dialog, a delete alert with a toast offering Undo, tooltips,241// and a popover of filters with the dark theme.242//243// **F11c as built** (2026-10-15; decisions/F11.md, "Screens",244// questions 5A and 6B):245// - Hidden views (`screens.alloy`): a node is `hidden` with all under it:246// layout's flattening, hit tests, Tab's order and the accessibility247// tree pass over it, a layer anchored in it closes, and painting hides248// its canvas node (`draw`'s new `canvas.set_hidden`, keeping what it249// drew) and goes no further. The view's owner is hidden too: a binding250// under it marked meanwhile waits on that owner, still queued, and251// runs as it shows (`set_owner_hidden`; `flush` looks for a hidden252// owner only while one is). Hiding a view takes the focus, the hover253// and the press from it.254// - `ui.switch(key, view, keep)`: a transparent element holding the255// views made by key (`K: hash::Key`, which a program's enum satisfies256// with no marker, question 18), the one shown before kept hidden257// (`Keep::All`) or freed (`Keep::None`).258// - Size (question 16A): the counter grew by 5.9 KB natively (1,798,704259// bytes) and 6.9 KB on the web (1,295,272): the hidden checks in260// layout, painting, hit tests, focus and the tree, the owners' in261// `flush`, the navigators' checks and the history after each event,262// and the window's new roles and history.263// - Tests: seven in `ui/tests.alloy` (switch keeping a view and its264// waiting binding, `Keep::None`; tabs by the keys, the pointer and a265// screen reader; a navigator keeping, freeing (by `census`) and giving266// the focus back; nested navigators and the history's depth; a start267// path; an app's Back button and Navigated, through `Replay.history`);268// goldens `tabs.png` and `tabs_dark.png`; `tests/atspi` and269// `tests/automation` select a tab. An app replayed interpreted took270// gigabytes to draw text (a page with a field past 7 GB), the271// interpreter keeping a record of every allocation and frame ever272// made; it keeps the live ones only since, that page's test peaking273// at 290 MB, and that test's screens draw their text.274// - Sample `screens.alloy`: forty events, an event's page with tabs275// (Details, Seats, Reviews and a review to write), the basket; back by276// the header's button, the mouse, the keys and the browser; on the web277// the address follows (`#/events/12`) and a reload stays.278//279// **F11e as built** (2026-10-15; decisions/F11.md, "Motion",280// questions 11A, 12A and 13A):281// - Frames (`motion.alloy`): a Redraw runs `ui.frame()`: what moves is282// marked (elements easing or settling painted again, the bindings283// reading a moving number queued, rooms revealing laid out), the284// bindings run and layout and painting follow, then the canvas nodes285// of what comes and goes are moved; while anything moves the app asks286// for the next frame after each, and for none once it rests. Motion's287// state is behind an object and its frame, owner and placing hooks are288// set only once a program moves something; the counter pays for the289// hover and press easing, `Look`'s new fields, `settling` and the290// checks.291// - `Motion` (duration, `Easing` with CSS's cubic-bezier solved by292// Newton's method, delay, `Repeat` once, a number of times, forever or293// back and forth, `essential`) and the theme's `motion` durations294// (short 100 ms, medium 200, long 300).295// - `ui.transition(element, Transition)`: the element is held by a296// `Moving` element (its grow copied, clipping only to reveal) whose297// canvas node visuals (`transitions.alloy`) move between two poses298// (opacity, offset, scale about the center, how much of the room299// shows) after layout and painting, from `canvas.set_opacity` (new in300// `draw`, multiplying alpha as each primitive is drawn, question 12A)301// and transforms. It comes in once the first frame was drawn, from302// where a visual already moving it has it. As its owner goes,303// `free_owner` first lets the transitioned elements among its own keep304// their canvas nodes (their elements letting go of theirs), which the305// visual moves back and then removes; the elements go at once, out of306// the tree and the input. A revealed one leaves a room of its size in307// its place, in an owner of its own, which `each` keeps after the row308// that preceded it and `show` among its children, shrinking with it;309// `each` and `show` now free what goes before taking their children.310// With `moves`, an element placed anew (its node's new `moving` flag,311// checked as painting moves it) goes from where it was drawn, unless a312// room is opening or closing that frame.313// - Built in: a dialog's or alert's host fades with its scrim and its314// panel grows from 0.96 (medium), a popup, menu or list fades and drops315// 4 pixels (up when above, short), a tooltip fades, each backwards as316// it closes; toasts slide up 16 pixels and close up as one goes, their317// corner fading out with the last; a pushed screen slides in from the318// window's width over the last, kept shown until covered, and one taken319// off slides out over the one under (long), each screen held by a320// `Ground` painting the theme's background over all it takes, so the321// one moving covers the other (2026-10-16: a screen painting nothing322// showed the one under between its elements; goldens323// `screen_going_back`, dark, and `screen_fading`, reduced motion's324// fade); `switch` crossfades (medium), a kept view shown until faded325// out, given no ground: its views fade together, and often sit on a326// card's surface. `Look` gains `hover` and `press` easing over the327// short duration (an `Ease` per element whose state changed, from its328// amounts then), `since` (each node's new `changed`, milliseconds on329// the clock, set as made and by a renew that changes something) and330// `reduced`; `emphasis` paints with the amounts.331// `Widget::settling(since)`: a widget saying so is painted again next332// frame. The checkbox's fill and check fade, a radio's dot333// grows, the slider's thumb goes to a value not dragged to and the334// tabs' underline slides from the tab before, each for 400 ms at most335// (`SETTLE`, settling having no theme to read). `Spinner`: eight dots,336// the brightest going round once a second, pulsing every two seconds337// under reduced motion; a label to screen readers, there being no338// progress role yet. `ui.scroll_to(element)` moves the scrolls around339// it over the medium duration (`reveal_offsets`, shared with focus's340// `reveal`).341// - Reduced motion (question 13A): `ui.reduced_motion()`, the app's342// `set_reduced_motion(Option<bool>)` else the window's, read at each343// event. Then slides, scales, reveals and moves are left out, fades kept344// at the short duration, values and scrolls jump, the spinner pulses.345// - Accessibility: nothing new; what leaves is out of the tree at once.346// - Size (question 16A): the counter is 1,866,320 bytes natively347// (1,852,016 before F11e, +14 KB) and its wasm 1,328,924 (1,322,765,348// +6 KB), built as `bench.sh` builds it; the native budget, which349// F11c-d had already passed, raised to 1.9 MB as 16A raised wasm's.350// Benchmarks `ui_moving` (100 cards coming in, a frame 0.09 ms351// without drawing) and `ui_animated` (20 bound numbers, 0.02 ms).352// - Tests: eleven in `ui/tests.alloy` (curves, a retargeted number,353// easing states, transitions coming and going, rooms and moves, reduced354// motion, layers, `switch`, the navigator, `scroll_to` and settling,355// the app's frames), a frame driven by `Redraw(at)` as replays do;356// every replay ends with `Redraw(2 s)` so goldens show things at rest,357// and goldens `dialog_entering` and `screen_pushing` catch a frame358// midway. Under the headless weston and lavapipe, presents back to359// back stall about 2.7 s each, so `tests/atspi`'s toast takes an360// action to stay while read and its run is given 60 s.361// - Sample `motion.alloy`: six cards dealt one after another (a delay a362// card) into a wrap, sorted and shuffled by tabs and moving there,363// removed closing up; a basket total counting; details revealing; a364// spinner; a smooth scroll to the end; "Reduce motion". The earlier365// samples move without a change to their code.366//367// **F12a as built** (2026-10-15; decisions/F12.md, "Timers",368// questions 1A and 2A):369// - `ui.every(period, then)` (`timers.alloy`): a slot with a period, due370// again a period after it was due and past the runs missed, so a long371// gap runs it once; cancelling it inside its own run ends it. A period372// of 0 faults.373// - `ui.at(moment, then)`: a second heap of due moments on the wall374// clock beside the window clock's, both read at each event (`ui.wall`375// set with `ui.time`, before the first view is made too), the entry376// due longest ago running first (since question 17B the window clock's377// timers run first, then the wall's). While one waits, the window's378// deadline is at most 5 seconds ahead (`next_due`), so after a sleep379// or the system's time set it runs at most that late.380// - `ui.clock(step) -> Signal<i64>`: one signal per step, the Ui's own381// (owner 0), the wall clock at the start of its step. At each event,382// before the timers run, each clock's signal is set to where the wall383// clock is, a clock moved having its tick set again; before the window384// is given its deadline, a clock a shown binding reads (one whose last385// run read it, not in a hidden view: `read_shown`) gets a wall timer386// at its next step, which only wakes the loop, and one no binding reads387// loses it, so nothing wakes. Both run through `Hooks` set as the first388// clock is made.389// - Replays: `replay(config, ReplayConfig, view, events)`, the config390// taking the scale and `wall`, the wall clock at script time 0 going on391// with the script's time (the App's `wall`); window's `Replay` counts392// `wakes`.393// - The web: the page shown again (`visibilitychange`) gives an394// `Event::Timer` whether the deadline came or not, so what came due395// while hidden runs at once.396// - `std::time::sleep_until(moment)` for programs with no window: sleeps397// of at most 5 seconds until the wall clock reaches the moment, no new398// OS call.399// - Size: the counter is 1,829,792 bytes natively (1,826,512 before400// F12a, +3.2 KB) and its wasm 1,305,487 (1,302,508, +2.9 KB), built as401// `bench.sh` builds it; the clocks' 0.8 KB is behind the hooks, the402// rest the wall heap, the repeating slots and reading the wall clock403// (question 17).404// - Tests: four in `ui/tests.alloy` (`every`'s fixed rate and a gap,405// cancelling itself; `at` with the wall clock set back and forward and406// the 5-second wait; a clock's ticks, a jump and no tick unread; a407// replay's wall clock, counting down to an `at`, and an unread clock408// asking no wake); golden `countdown` (a clock and a countdown in its409// last minute, red, 12.5 s into a replay); `tests/timers` counts a410// 100 ms timer over a second ended by `at`, under weston, under qemu,411// in node's page hidden and shown halfway, and on Windows by hand.412// - Sample `clock.alloy`: a clock in the corner on the second, a413// countdown to a time typed in, red in its last minute and ended by414// `at`, a stopwatch with laps counted by `every`, a note saved a415// second after typing stops (`after` cancelled and set again).416//417// **Sizes after F12** (2026-10-17; decisions/F12.md, questions418// 17B, 20B and 23B: a program using no timers, requests or storage grows419// by nothing):420// - Timers: the window clock's heap runs first, then the wall's through421// the `run_wall` hook, and `next_due` asks `next_wall`, both set by the422// first wall timer (`at`, a clock's tick); a repeating timer runs and423// is set due again through `repeat`, set by the first `every`.424// - Requests: one task in `app`'s scope waits for the first request and425// runs what it set (`Network.service`, `serve_requests`): a scope of426// the eight network tasks and the app's `std::http::Client`, a local427// there each request borrows as the task runs it (a request is a428// `|=| (&Network, &Client) -> |=| (&var Ui)`), so an app sending429// nothing links neither the client nor Mbed TLS, which the client in430// `Network` had pulled into every native app (question 18A, +96 KB,431// now gone).432// - Storage: the store opens under `Ui.app`, the window's `app_name()`433// taken as the app mounts its view, none in a Ui on its own. Writes go434// one at a time; a worker's sets `Network.store_writing` (an `Atomic`435// the workers share with the loop) and clears it once written, and the436// last write as the app ends waits for it, so the older never lands437// over the newer.438// - These first passed raw `c_pointer` handles between ui's own code439// (the window, the client, the store's flag); since 2026-10-17 they are440// the borrows, owned name and shared atomic above, closer to the spec441// (section 6.3 gives `c_pointer` for state crossing C), for 4 KB. The442// page's inbox stays one (`page_inbox`): it is state the browser calls443// back after `main` returns, reached by the callback `std::http::start`444// hands to the page, which section 6.3 keeps with `c_pointer::keep`.445// - Size, release builds as `bench.sh` builds them: the counter is446// 1,839,440 bytes natively (1,835,376 with the handles, 1,931,728447// before these changes, 1,835,664 before question 18A) and 1,311,894 of448// wasm (1,311,213 with the handles, 1,312,590 before): the wall heap and449// repeat code are gone, the starting task and an out-of-line450// `Channel::receive` (two callers now) taking most of it back, then451// the requests' own channel type, the flag and the name; what stays is452// the timers' heaps, the requests' channel and exchanges, `app_id` and453// the accessibility roles.454//455// **Showcase answers as built** (2026-10-17; decisions/showcase.md,456// the questions `samples/tickets` raised, decided 2026-10-16):457// - Hover (question 1A): `Widget::wants_hover()`, false by default; laying458// out an element wanting it sets the hovering hook, as `ChoiceList`,459// `Radios`, `Tabs` and `Calendar` now say they do, so a program's own460// widget gets `Input::Hover` on a screen with none of them.461// - Bound containers (question 2A): `ui.bind_options(element, options)`462// binds the options of an element `add` made, the function run now and463// as what it read changes, its result renewing the element through its464// widget's `renew` while the node keeps its children (options holding465// children panic, as `bind`'s do).466// - Rounded clips (question 3A): `Widget::clip_radii()` (square by467// default) gives a clipping element's corners, which painting sets on468// its canvas node's clip, so `draw` tests each pixel of its paint and its469// children against the rounded rectangle; `Column`, `Row`, `Stack`,470// `Wrap` and `Grid` take `clip_radii: Option<Radii>`, clipping when set.471// Hit tests stay rectangular. Golden `clipped` (a picture across a472// card's top, one filling a card rounded at two corners).473// - Pixels (question 4A): painting snaps each element's edges to device474// pixels as browsers snap boxes: each edge rounded where it lies on the475// window at its scale, the size the distance between them, so siblings476// meeting still meet and nothing starts between two pixel rows (the477// lighter row along the top of the tickets' posters is gone). Layout,478// hit tests and the accessibility tree keep fractions; a node keeps479// where it is shown (`shown_at`, `shown_size`, logical) and its480// `residue`, how far its top left lies past its pixel, which is all its481// children's snapping needs, so a node is snapped again only when it482// moves or resizes, or its parent's residue or the scale changes (a483// scroll by whole pixels snaps nothing under it). A widget painted at484// another size is painted again, but not one whose paint came with its485// layout (`Text`'s, through `take_paint`), whose glyphs keep their486// quarter-pixel positions. Transitions place and scale from the shown487// rectangle. 60 goldens moved by a pixel here and there (`ui` 46,488// `tickets` all 14), looked at: borders and fields sharper, text the489// same. The counter grows by 400 bytes natively and 290 of wasm, to490// 1,892,160 and 1,350,172 as `bench.sh` builds it (with absolute paths,491// whose fault locations the earlier measures here, with relative ones,492// left out), 172 bytes past its wasm budget (showcase.md, question 16).493// Test in `ui/tests.alloy`.494495// - Owners (question 5B): `Owner`, a handle on what a view made (an496// index and a generation, the slot's, renamed `OwnerSlot`, counting its497// reuses), `ui.root_owner()`, and `HandlerOptions { .owner }` taken by498// overloads of `after`, `every`, `at` and `send` and by499// `LoadOptions.owner`: what they make belongs to that owner, so a hold's500// expiry or a payment's answer outlives the screen that started it.501// An owner gone faults when named (`owner_index`).502// - Leaving (question 6A): `nav.on_leaving(ui, asks)` keeps a function503// in the navigator's routes, which `back` asks with the top route504// before going (the header's Back, the mouse's, Alt+Left, the browser's505// Navigated: all go through `back`), refusing keeping the screen (the506// page then put back deeper); `nav.pop` goes without asking, for the507// "Leave" of the program's own question. `ui.on_close_requested(asks)`508// is asked on `Event::CloseRequested`, refusing keeping the window open509// until `ui.quit()`. Tests in `ui/tests.alloy`.510511// - Replays (question 7A): `replay` gives a `Replayed`: the frames, the512// access tree the app sent (after an `Event::AccessRequested`), the513// announcements, the history entries and each toast's text as it514// showed (`Ui.toasts_shown`, kept only in a replay).515516// - Frames drawn (question 8B): `ReplayConfig.drawn`, a `Drawn` (`All`,517// `Last`: the Redraws at the last Redraw's time, `At(times)`); at the518// others the app lays out and paints its canvas but does not render519// it, the CPU device's rasterizing being most of a frame's time, the520// canvas keeping the damage for the next frame drawn, so that frame is521// the same. The goldens draw `Last`: `tests/widgets` 39 s to 19 s, the522// showcase's thirteen scenes 14 to 1.6 minutes of CPU. 8A (the CPU523// device's shaders compiled to closures) waits.524// - Fields in error (question 11A): `TextField.error`, a message: its525// border in the theme's new `danger` color (`Ink::Danger`, red, lighter526// in the dark theme), 1.5 pixels, 2 focused; to screen readers the527// field is `invalid` with the message as its description (the four528// trees in pkg::alloy::window's notes). The program shows the message529// where it likes. Goldens `field_error`, `field_error_dark`.530// - Checks and clearing (question 12A): `MenuItem.checked`, an531// `Option<bool>`: a check mark before the label while true, every row of532// a menu holding one leaving its room, and to screen readers a533// `MenuItemCheckbox`. `DatePicker.clearable` puts a plain "Clear" under534// its calendar, enabled while a day is chosen, closing it and calling535// `on_clear`. Tests in `ui/tests.alloy`; goldens `menu_checked`,536// `date_picker_clearable`.537538// - Size, release builds as `bench.sh` builds them: the counter is539// 1,850,544 bytes natively (1,839,440 before, +11.1 KB) and 1,322,170540// of wasm (1,311,894, +10.3 KB): the nested rounded clip in `draw`'s541// `child_state` (1 KB), the hovering hook's function now reachable542// from layout (1 KB), `clip_radii` and `wants_hover` asked of every543// widget, the close asked and the frames drawn in `handle`, `invalid`544// and the new role in each accessibility tree, the theme's `danger`545// and the Ui's new fields. The new options are not linked unless used.546//547// **F13's secret fields** (in `ui`; F13's other notes are in548// pkg::alloy::ui_app since R6e):549// Secret fields (2026-10-20, question 13A): `TextField.secret` lays out550// a bullet (U+2022, which Inter has) for each grapheme of the text, so551// the caret, the selection, the arrows, Home, End, Backspace, Delete552// and presses move among the dots, offsets taken to and from the553// text's (`shown_at`, `text_at`, through pkg::alloy::text's new554// `grapheme_ends`); Ctrl+C and Ctrl+X are taken and do nothing, Ctrl+V555// and Ctrl+A work as ever, and compositions are dropped (the input556// method is told, so none should come); the placeholder shows as557// written. To screen readers `Semantics.secret` with the dots as the558// value and the selection among them, a screen reader's selection559// taken back to the text's; `ui.input_secret()` (the focused element's560// semantics) goes to window's new `set_secret_input` beside the caret561// (window's "Secret input"). The counter is 1,866,640 bytes natively562// (+784) and 1,329,722 of wasm (+356), built as `bench.sh` builds it:563// the semantics' new field in its glue and each tree, the focused564// element's semantics asked after each event, Wayland's content type565// natively. Tests: four in `ui/tests.alloy` (the dots, caret and566// selection, copying refused, the tree, the replay's input method);567// golden `secret`; `tests/access` (the layer's password input),568// `tests/atspi` (`password text`, its text dots), `tests/automation`569// (`IsPassword`, its value dots; by hand on Windows). Signup's password570// and its repetition and the tickets' security code are secret.571// `test.sh` now draws `tests/atspi` on the CPU device: through lavapipe572// its checked frames after a tab's switch took about 6 seconds (at573// HEAD before this too), past the reader's 5-second calls.574//575// **F14a as built** (2026-10-20; decisions/F14.md, "Right to576// left", decided as recommended):577// - Language (`languages.alloy`, 1A): the app's languages are578// `WindowConfig.languages`; as `app` starts, the Ui takes the first of579// the system's `std::locale::preferred_languages()` the app has, by the same tag,580// the app's cut from it (`en` for `en-GB`), then the same language,581// else the app's first (`chosen_language`); a replay's system is582// `ReplayConfig.languages`, and a Ui on its own reads none ("en").583// `ui.set_language` and `set_direction` override (signals, so584// bindings reading `ui.language()` or `ui.direction()` run again);585// the direction is `writes_right_to_left` of the language shown. A586// change lays everything out again and tells the window587// (`set_language`), which `Replayed.language` and `right_to_left`588// record.589// - Directions: each node keeps the direction layout resolved on the590// way down (`resolve_direction`: `ui.directed(element, d)`'s, else the591// parent's, else the Ui's; transparent groups in `flatten_into`), a592// change marking all under it. `Arrange.direction()` and593// `Look.direction` give it to widgets, `Look.from_start(x, width)`594// turns a start-based x into the element's.595// - Mirroring once in placement (2A): `arrange.place` keeps x from the596// start; in a right-to-left node whose widget `mirrors_children()`597// (all but `LayerHost`, whose layers place themselves) each child's x598// becomes `width - x - child width` once its own size is known, so599// Row, Wrap, Grid, Column's and Stack's alignment, Scroll's content600// and every container mirror with no code of their own, and hit tests601// and accessibility bounds follow the placed rectangles.602// - `Padding`'s `start` and `end` replace `left` and `right` (3A), in603// `ui`, the samples, the tickets and the tests. `TextAlign::Start` and604// `End` are the element's sides (4A): `Text` and widgets' labels lay605// lines out through pkg::alloy::text's new `Align::Left` and `Right`606// (`TextAlign.lines(direction)`, `Layout::fitted` with an alignment).607// - Widgets, right to left: Checkbox's box and Radios' circles at the608// right; Slider's minimum at the right, a press measured from it, Left609// and Right the way they point; ProgressBar filling and sweeping from610// the right; Tabs and Radios from the right (`mirror_boxes`, their611// parts too), Left and Right the way they point; Select's, MenuButton's612// and the pickers' chevrons at the left; menus' checks at the right,613// shortcuts and a submenu's arrow ("‹") at the left, Left opening a614// submenu and Right closing it; TextField's padding and placeholder615// from the start, its typed text on its own side, nothing typed616// reading right to left (its caret at the right, as `dir=auto`);617// Scroll's bar at the left, a horizontal scroll starting at its right618// end, the sideways wheel turned so the content follows the fingers,619// `reveal` measured from the start; ListView's bar at the left;620// `Image.mirrors` drawing a picture that points mirrored. Calendars621// follow their element's direction, not the locale's (`calendar_ar`622// unchanged by a directed calendar in its scene).623// - Layers: `placed` takes the anchor's direction (the Ui's without624// one): Below and Above right edges aligned, After to the left else625// the right, At reaching left of the point else right, `TopEnd` and626// `BottomEnd` corners at the left (toasts); a layer's content reads as627// the Ui does. Transitions: `Pose.x` toward the end, so a screen pushed628// slides in from the left (`Kept.mirrored`).629// - Accessibility: the tree's order is the reading order as before; a630// node whose direction differs from the window's sets631// `Semantics.right_to_left`, and the window gets the language632// (pkg::alloy::window's "F14a as built").633// - Size: the counter is 1,928,352 bytes natively (1,908,176 before634// F14a, +20,176) and 1,378,589 of wasm (1,357,674, +20,915), built as635// `bench.sh` builds it, past F14.md's estimates of about 6 KB: the636// language chosen at the start, inlined into the event handler (6 KB,637// `preferred_languages` 2.5 of it natively and 1.7 of wasm;638// `writes_right_to_left` scans its tag's first two subtags rather than639// reading it whole, which saved 9 KB), the app's languages copied into640// the Ui (2 KB in `app`), layout resolving directions and641// mirroring placements (`lay_out_node`, the lines' placing, a vector642// of placements: 4 KB), text's `fitted` with an alignment, AT-SPI's643// locale and the trees' direction (1.5 KB), the rest spread. The644// budgets still pass, wasm's 21 KB under its 1.4 MB. Since, choosing645// the language as `app` starts, from the config's languages as they646// are (`chosen_language` takes `&[&[u8]]`), rather than copying them647// into the Ui for the first event to choose by: the counter 2.2 KB648// smaller natively and 2.3 KB of wasm.649// - Tests: in `ui/tests.alloy`, the mirror law over a gallery of every650// kind of element in Latin letters (x' = W - x - w, a directed row kept651// inside), Radios' parts, reading order and bounds in the tree, keys652// (Slider, Tabs, Radios, menus and submenus), the layers' places, a653// screen pushed, an empty field's caret, the language chosen from654// `languages` and `ReplayConfig.languages`, and a change of language655// laying out again and running bindings; the calendar's test reads it656// right to left through the language. Goldens `rtl_inputs_ar`,657// `rtl_menu_he`, `rtl_form_ar`, `rtl_screens_he`, `rtl_layers_ar` and658// `rtl_list_he` in the committed Arabic and Hebrew fonts of659// `tests/fonts`. The scenes' `FontsRead` now reads those fonts again660// into the window's canvas's fonts once its first frame replaces the661// Ui's own: before, Hebrew and the complex scripts came from the662// machine's fonts (this one's Liberation Mono for Hebrew), so663// `bidi_hebrew`, `bidi_arabic`, `bidi_composing` and `complex_scripts`664// are drawn again in the committed ones, whose Thai and Khmer are now665// whole blocks (`tests/fonts/fonts.sh`: the old subsets lacked the666// glyphs shaping reaches, sara am's nikhahit and Khmer's split vowels).667// Question 11 (text with no letters), queued in F14.md, is built since.668// - Sample `directions.alloy`: a mail app in English, Arabic and Hebrew.669//670// **F14b as built** (2026-10-20; decisions/F14.md, "Text for671// screen readers", decided as recommended):672// - Maps (5B, 6A), what a screen reader reads a field and a text of673// several lines by: in pkg::alloy::ui_access's notes since R6f.674// - Words in `TextField` (8A, `fields.alloy`): Ctrl+Left and Ctrl+Right675// (Option on macOS) go to the word start before or after the caret,676// the other way on a line reading right to left, Shift selecting;677// Ctrl+Backspace and Ctrl+Delete delete to that start; a second press678// within half a second and four pixels of the first selects its word.679// - Tests: in `ui/tests.alloy`, word moves in both directions with680// Shift, Ctrl+Backspace and Delete, a double click; maps from real681// layouts: a field's graphemes, words, line and format, made again on682// an edit and not on a frame with nothing new nor in a composition; a683// family emoji, a decomposed "é", Hangul syllables and jamo, Arabic684// after Latin and Latin after Arabic; a text of one line without a map,685// one wrapped and a heading with one, a field's map following its686// scrolling; a secret field's map of dots, with no words.687// - Size, built as `bench.sh` builds them: the counter 1,987,760 bytes688// natively (1,928,352 before F14b, +59,408) and 1,380,033 of wasm689// (1,378,589, +1,444, maps never being made there); hello world, which690// has no ui, 1,697,200 natively (+34.6 KB, AT-SPI's Text) and wasm691// +255 bytes. Natively, past F14.md's 13-20 KB for every ui program692// and 10-15 KB for AT-SPI: words 12.5 KB (7.5 of table), maps, word693// moves and `text_ranges.alloy` 12 KB, AT-SPI's Text 35 KB (its694// answers 18 KB, the signals' diffing 5 KB, attributes 3.5 KB, extents695// and ranges the rest). Every budget passes, the counter 12 KB under696// its 2 MB and hello world 2.8 KB under its 1.7 MB. Since, AT-SPI697// takes trees and answers Text only once a program sends a tree698// (pkg::alloy::window's "F14b as built"): hello world 1,633,664 bytes699// natively (-63.5 KB, the tree's handling of F6c too) and wasm +20700// bytes; the counter, which sends trees, +0.8 KB natively for the701// indirect calls. Words and maps stay in every program with a `Text`,702// which a screen reader may read by words once it wraps; `TextField`'s703// word moves are linked only where a field is.704//705// **F14 question 11A as built** (2026-10-20): text with no letters in an706// element reading right to left reads right to left, as with dir=auto:707// `Arrange.text_style(size)` gives pkg::alloy::text's708// `Direction::AutoRightToLeft` there, which `Text`, widgets' labels,709// `TextField` (its placeholder too, replacing the empty field's own710// case), `Select`, `ChoiceList` and menus lay out with; a submenu's711// arrow is "›" everywhere, mirrored right to left. Every golden is712// unchanged. Tested in `ui/tests.alloy`: a text of digits and signs and713// one of Latin letters by their maps' lines, digits typed in a field714// keeping the caret at its right. Size: the counter +624 bytes natively715// and +503 of wasm, hello world +320 and +116.716//717// **R6e as built** (2026-10-26; REFOCUS.md, questions 8A and718// 9A): the core. The controls went to pkg::alloy::ui_controls (`Select`,719// `ChoiceList`, `Radios`, `Tabs`, `MenuButton`, menus, `Tooltip`, toasts,720// `ProgressBar`, `Spinner`) and the app services to pkg::alloy::ui_app721// (navigators and the history, `ui.animated`, the calendar, the pickers722// and the locale's tables, forms, requests, storage, file dialogs and723// drops), their notes with them.724// - Extensions (8A): `Hooks` and the Ui's fields for those features are725// gone. An `Extension` is a struct of its own state that the Ui calls at726// the points of its work its functions name, each doing nothing by727// default; `ui.install(new E {...})` adds one as it is first used and728// `ui.extension<E>()`, `extension_var<E>()` find it by a downcast;729// `extensions.alloy` calls them in turn. The core's own are730// `LayerCalls` (presses outside, Escape, Dismiss, layers following731// their anchors), `WallTimers` (`ui.at`, `ui.clock`) and `Visuals`732// (motion's visuals, scrolls and rooms). A Redraw asks for frames only733// while an extension painted something moving.734// - Services: `Workers` hold an optional `Service`, which a task in735// `app`'s scope serves once its first use sends `starting` (ui_app's736// network); `ui.background`'s jobs are given the workers.737// - Without ui_app, `ui.locale()` is the app's language's; `std::languages`738// gives the system's languages, so std::locale's CLDR tables, `http`,739// `json` and `storage` are out of the core's imports.740// - Changed forms: `on_drop` left `Column`, `Row` and `Stack` for741// ui_app's `DropArea`; `ReplayConfig.responses` became ui_app's742// `replay(config, options, responses, view, events)`.743// - What the other two reach of the core is `exp` in its inner modules744// (`pkg::alloy::ui::tree`, `layers`, `events`, ...), which a program745// importing `pkg::alloy::ui` does not see; `Scene` moved into746// `painting.alloy` for that.747// - Tests: `ui/tests.alloy` 69, `ui_controls/tests.alloy` 24 and748// `ui_app/tests.alloy` 44, the 137 of before; goldens in749// `tests/golden/ui` (24), `ui_controls` (11) and `ui_app` (18), each750// image the same, `tests/widgets` taking `tests/golden`.751//752// **R6f as built** (2026-10-26; REFOCUS.md, question 3B): screen753// readers went to pkg::alloy::ui_access, which an app installs754// (`ui_access::install(&var ui)`), with `access.alloy` (the walk, ids,755// actions), `text_maps.alloy` and the Ui's `access_sent`, `access_focus`756// and `map_revision`; `running.alloy` no longer takes757// `Event::AccessRequested` and `Event::Action` nor sends the tree, and758// gives the window nothing announced: ui_access's extension does.759// - Kept: `Widget::semantics`, `parts` and the widgets' descriptions,760// linked only where something walks them; `ui.access_on` and761// `access_stale` (now `exp`); `Extension::text_map` and `TextLook`,762// which `Text` of several lines and `TextField` ask while `access_on`763// (224 bytes of the counter); `ui.announce`, its queue emptied after764// each event. `ui.input_secret()` reads `TextField.secret` in place of765// the semantics, so the counter asks no widget's. `paste_event` moved766// to `events.alloy`.767// - What ui_access reaches is `exp` in the inner modules: `Node.position`768// and `direction`, `LayerSlot.host`, `fonts`, `dispatch`, `reveal`,769// `extensions_describing` and `extensions_dismissed`,770// `fields.alloy`'s `text_map_of`, `languages.alloy`'s771// `spoken_language` and `reading_flow`; its tests, `input_area` and772// `preedit_event`.773// - Tests: the twelve of `ui/tests.alloy` reading the tree, actions and774// maps went to `ui_access/tests.alloy`; 57 stay.775//776// The accessibility tree's types, the platforms' screen readers, dialogs777// and drops of F6 are in pkg::alloy::window's notes, the tree's walk in778// pkg::alloy::ui_access's.779780import std::string;781import std::vector;782import std::option;783import std::math;784import std::number;785import std::sync;786import std::io;787import std::process;788import std::map;789import std::hash as hash;790import std::equal;791import std::time;792import std::format;793import pkg::alloy::window;794import pkg::alloy::window::headless;795import pkg::alloy::gpu;796import pkg::alloy::draw;797import pkg::alloy::text as text;798799import store;800import tree;801import layout;802import painting;803import events;804import widgets;805import fields;806import scrolling;807import running;808import timers;809import layers;810import motion;811import transitions;812import languages;813import extensions;814import views;815import hud;816817// A length no limit reaches: a maximum that does not constrain.818exp const UNBOUNDED: f32 = 1000000000.0;819820// Text weights, from pkg::alloy::text.821exp const REGULAR: u32 = text::REGULAR;822exp const SEMIBOLD: u32 = text::SEMIBOLD;823exp const BOLD: u32 = text::BOLD;824825/* --- Geometry --- */826827pub const ORIGIN: Point = Point { .x = 0.0, .y = 0.0 };828829exp type Extent = struct {830 exp width: f32,831 exp height: f32,832};833834exp fn Extent::zero() -> Extent => Extent { .width = 0.0, .height = 0.0 };835836// The sizes an element may take: its parent's constraints.837exp type Limits = struct {838 exp min_width: f32 = 0.0,839 exp max_width: f32 = UNBOUNDED,840 exp min_height: f32 = 0.0,841 exp max_height: f32 = UNBOUNDED,842};843844// Any size up to the extent.845exp fn Limits::loose(width: f32, height: f32) -> Limits => Limits {846 .max_width = width,847 .max_height = height848};849850// Exactly the extent.851exp fn Limits::tight(width: f32, height: f32) -> Limits => Limits {852 .min_width = width,853 .max_width = width,854 .min_height = height,855 .max_height = height856};857858// The extent brought within the limits.859exp fn constrain(self limits: &Limits, extent: Extent) -> Extent => Extent {860 .width = clamp(extent.width, limits.min_width, limits.max_width),861 .height = clamp(extent.height, limits.min_height, limits.max_height)862};863864// The limits with no minimum.865exp fn loosened(self limits: &Limits) -> Limits => Limits {866 .max_width = limits.max_width,867 .max_height = limits.max_height868};869870// The limits less the padding on each side.871exp fn inside(self limits: &Limits, padding: &Padding) -> Limits {872 const across = padding.start + padding.end;873 const down = padding.top + padding.bottom;874 return Limits {875 .min_width = max(limits.min_width - across, 0.0),876 .max_width = max(limits.max_width - across, 0.0),877 .min_height = max(limits.min_height - down, 0.0),878 .max_height = max(limits.max_height - down, 0.0)879 };880}881882// Room inside an element's edges: `start` on the side it reads from, the883// left left to right and the right right to left, `end` on the other.884exp type Padding = struct {885 exp start: f32 = 0.0,886 exp top: f32 = 0.0,887 exp end: f32 = 0.0,888 exp bottom: f32 = 0.0,889};890891exp fn Padding::all(length: f32) -> Padding => Padding {892 .start = length,893 .top = length,894 .end = length,895 .bottom = length896};897898exp fn Padding::symmetric(horizontal: f32, vertical: f32) -> Padding => Padding {899 .start = horizontal,900 .top = vertical,901 .end = horizontal,902 .bottom = vertical903};904905// The size an element asks for, whatever lays it out: with no width or906// height it takes the size of what it holds; `grow` shares the room a907// row or column has left among its children in proportion.908exp type Sizing = struct {909 exp width: Option<f32> = ::None,910 exp height: Option<f32> = ::None,911 exp min_width: f32 = 0.0,912 exp min_height: f32 = 0.0,913 exp max_width: f32 = UNBOUNDED,914 exp max_height: f32 = UNBOUNDED,915 exp grow: f32 = 0.0,916};917918// Which way an element reads (decisions/F14.md, F14a): from919// the left or from the right, its children placed from its start and920// its own drawing following.921exp type LayoutDirection = enum {922 LeftToRight,923 RightToLeft,924};925926// Where children go across a row or column, or within a stack: Start927// and End on the element's own sides, the right and the left right to928// left.929exp type Alignment = enum {930 Start,931 Center,932 End,933 Stretch,934};935936// How far into the room left a child aligned so goes.937pub fn offset(self align: &Alignment, room: f32) -> f32 => match (align) {938 ::Center room / 2.0;939 ::End room;940 else 0.0;941};942943// Where children go along a row or column with room left.944exp type Justify = enum {945 Start,946 Center,947 End,948 Between,949};950951/* --- Themes --- */952953// Colors by role, and the scales widgets take their lengths from.954exp type Theme = struct {955 exp background: Color, // under everything956 exp surface: Color, // cards, fields957 exp text: Color,958 exp muted: Color, // text of lesser importance959 exp primary: Color,960 exp on_primary: Color, // text over primary961 exp neutral: Color, // secondary buttons962 exp border: Color,963 // what is wrong: a field in error's border, a failure's text964 exp danger: Color = Color::rgb(0.8, 0.15, 0.15),965 exp scrim: Color = Color::rgba(0.0, 0.0, 0.0, 0.4), // over what a modal layer covers966 exp shadow: Shadow = Shadow::soft(967 0.0,968 8.0,969 24.0,970 Color::rgba(0.0, 0.0, 0.0, 0.18)971 ), // a layer's panel's972 exp hover: f32, // how much hovering lightens or darkens, 0 to 1973 exp press: f32,974 // how long built-in motion takes: hovering and fades, popups, dialogs975 // and toasts, screens976 exp motion: Durations = Durations {977 .short = Duration::from_milliseconds(100),978 .medium = Duration::from_milliseconds(200),979 .long = Duration::from_milliseconds(300)980 },981 exp focus: Color,982 exp radius: f32,983 exp spacing: f32,984 exp text_size: f32,985 exp heading_size: f32,986};987988exp fn Theme::light() -> Theme => Theme {989 .background = Color::rgb(0.96, 0.96, 0.97),990 .surface = Color::white(),991 .text = Color::rgb(0.11, 0.12, 0.14),992 .muted = Color::rgb(0.42, 0.44, 0.48),993 .primary = Color::rgb(0.2, 0.4, 0.92),994 .on_primary = Color::white(),995 .neutral = Color::rgb(0.89, 0.9, 0.92),996 .border = Color::rgb(0.8, 0.81, 0.84),997 .hover = 0.08,998 .press = 0.16,999 .focus = Color::rgb(0.2, 0.4, 0.92),1000 .radius = 6.0,1001 .spacing = 8.0,1002 .text_size = 15.0,1003 .heading_size = 22.01004};10051006exp fn Theme::dark() -> Theme => Theme {1007 .background = Color::rgb(0.09, 0.1, 0.11),1008 .surface = Color::rgb(0.15, 0.16, 0.18),1009 .text = Color::rgb(0.92, 0.93, 0.95),1010 .muted = Color::rgb(0.6, 0.62, 0.66),1011 .primary = Color::rgb(0.36, 0.55, 1.0),1012 .on_primary = Color::white(),1013 .neutral = Color::rgb(0.24, 0.25, 0.28),1014 .border = Color::rgb(0.32, 0.34, 0.38),1015 .danger = Color::rgb(0.98, 0.45, 0.45),1016 .scrim = Color::rgba(0.0, 0.0, 0.0, 0.6),1017 .shadow = Shadow::soft(0.0, 8.0, 24.0, Color::rgba(0.0, 0.0, 0.0, 0.5)),1018 .hover = 0.1,1019 .press = 0.2,1020 .focus = Color::rgb(0.45, 0.62, 1.0),1021 .radius = 6.0,1022 .spacing = 8.0,1023 .text_size = 15.0,1024 .heading_size = 22.01025};10261027// A color by its role in the theme, looked up when drawn, so switching1028// the theme changes it; or one given (`Exact`). `None` is the widget's1029// own: the theme's text color for text, nothing for a background or a1030// border.1031exp type Ink = enum {1032 None,1033 Text,1034 Muted,1035 Primary,1036 OnPrimary,1037 Neutral,1038 Surface,1039 Background,1040 Border,1041 Focus,1042 Danger,1043 Exact: Color,1044};10451046exp fn Ink::rgb(r: f32, g: f32, b: f32) -> Ink => Ink::Exact(Color::rgb(r, g, b));10471048exp fn Ink::rgba(r: f32, g: f32, b: f32, a: f32) -> Ink => Ink::Exact(Color::rgba(r, g, b, a));10491050// The ink's color in the theme, None for `None`.1051exp fn color(self ink: &Ink, theme: &Theme) -> Option<Color> => match (ink) {1052 ::None ::None;1053 ::Text ::Some(theme.text);1054 ::Muted ::Some(theme.muted);1055 ::Primary ::Some(theme.primary);1056 ::OnPrimary ::Some(theme.on_primary);1057 ::Neutral ::Some(theme.neutral);1058 ::Surface ::Some(theme.surface);1059 ::Background ::Some(theme.background);1060 ::Border ::Some(theme.border);1061 ::Focus ::Some(theme.focus);1062 ::Danger ::Some(theme.danger);1063 ::Exact |c| ::Some(c);1064};10651066/* --- Handles --- */10671068// An element of a Ui: a copyable handle, valid until its owner goes.1069exp type Element = struct {1070 exp index: u32,1071 exp generation: u32,1072};10731074// What a view made, freed together as it goes (a screen, a row of1075// `each`), or the app's root: a copyable handle, naming nothing once it1076// went. Timers and requests may be given one (`HandlerOptions`).1077exp type Owner = struct {1078 exp index: u32,1079 exp generation: u32,1080};10811082// A function `after`, `every` or `at` runs: a copyable handle, naming1083// nothing once it ran (but repeating), was cancelled or its owner went.1084exp type Timer = struct {1085 exp index: u32,1086 exp generation: u32,1087};10881089// A value the UI shows, in a Ui's store: a copyable handle, valid until1090// its owner goes. Reading it in a binding makes the binding run again1091// when it changes.1092exp type Signal<T> = struct {1093 exp index: u32,1094 exp generation: u32,1095};10961097/* --- Widgets --- */10981099// What a binding's new options change of an element.1100exp type Change = enum {1101 Nothing,1102 Paint,1103 Layout,1104};11051106// What an element is: an option struct declaring Widget, laid out,1107// painted and given input through these functions. Only `paint` and1108// `renew` have no default.1109exp interface Widget {1110 // Its size within the limits, its children laid out and placed1111 // through `arrange`; by default the smallest size holding its1112 // children, each at its top left.1113 fn layout(self: &var, arrange: &var Arrange, limits: Limits) -> Extent;1114 // What it draws, in its own coordinates, its size in `look`; its1115 // children draw over it.1116 fn paint(self: &, look: &Look, paint: &var Paint);1117 // Input sent to it, or bubbling up from a child; whether it handled1118 // it, which stops the bubbling.1119 fn event(self: &var, ui: &var Ui, input: &Input) -> bool;1120 // Takes the options a binding gave again, keeping its own state.1121 fn renew(self: &var, next: Self) -> Change;1122 // The elements it holds, which `add` adopts.1123 fn children(self: &) -> &[Element];1124 fn sizing(self: &) -> Sizing;1125 // Whether the pointer finds it, which hovering and pressing repaint.1126 fn interactive(self: &) -> bool;1127 // Whether it takes the keyboard's focus, by Tab or a press.1128 fn focusable(self: &) -> bool;1129 // How the pointer looks over it.1130 fn cursor(self: &) -> Cursor;1131 // Where text is typed into it while focused, in its coordinates, for1132 // the input method to show its candidates by.1133 fn caret(self: &) -> Option<Rect>;1134 // Whether its children and its own paint are kept within its bounds.1135 fn clips(self: &) -> bool;1136 // The corners' radii of the rounded rectangle a clipping element keeps1137 // them within, each pixel tested; by default none, square corners.1138 fn clip_radii(self: &) -> Radii;1139 // What a clipping element draws over its children, as a scroll's bar.1140 fn overlay(self: &, look: &Look, paint: &var Paint);1141 // A paint made ahead, as when laying out, which painting takes in1142 // place of calling `paint`.1143 fn take_paint(self: &var) -> Option<Paint>;1144 // What it is to a screen reader (PLAN.md, F6); by default1145 // nothing, its children standing for it.1146 fn semantics(self: &) -> Semantics;1147 // The items it draws itself, each a node of the accessibility tree1148 // under its own: an option, a radio; by default none. What a screen1149 // reader asks of one comes as Input::Part.1150 fn parts(self: &) -> Vector<Part>;1151 // Whether its drawing still moves, `since` its options last changed1152 // (`look.since`): while true it is painted again next frame. By1153 // default false.1154 fn settling(self: &, since: Duration) -> bool;1155 // Whether it follows the pointer over what it draws (a list's rows),1156 // getting Input::Hover as it moves with no button held; by default1157 // false. Laying it out sets the hook giving those.1158 fn wants_hover(self: &) -> bool;1159 // Whether the x its layout places a child at is from its start edge,1160 // which the Ui turns into one from the left in an element read right1161 // to left; by default true. One placing in window coordinates, as a1162 // layer's host, says false and mirrors what it means itself.1163 fn mirrors_children(self: &) -> bool;1164}11651166exp fn layout(self widget: &var Widget, arrange: &var Arrange, limits: Limits) -> Extent {1167 var size = Extent::zero();1168 for ([..arrange.count()]) |k| {1169 const child = arrange.lay_out(k, limits.loosened());1170 arrange.place(k, ORIGIN);1171 size.width = max(size.width, child.width);1172 size.height = max(size.height, child.height);1173 }1174 return limits.constrain(size);1175}11761177exp fn event(self widget: &var Widget, ui: &var Ui, input: &Input) -> bool => false;11781179exp fn children(self widget: &Widget) -> &[Element] => &[];11801181exp fn sizing(self widget: &Widget) -> Sizing => Sizing {};11821183exp fn interactive(self widget: &Widget) -> bool => false;11841185exp fn focusable(self widget: &Widget) -> bool => false;11861187exp fn cursor(self widget: &Widget) -> Cursor => Cursor::Arrow;11881189exp fn caret(self widget: &Widget) -> Option<Rect> => ::None;11901191exp fn clips(self widget: &Widget) -> bool => false;11921193exp fn clip_radii(self widget: &Widget) -> Radii => Radii::none();11941195exp fn overlay(self widget: &Widget, look: &Look, paint: &var Paint) {}11961197exp fn take_paint(self widget: &var Widget) -> Option<Paint> => ::None;11981199exp fn semantics(self widget: &Widget) -> Semantics => Semantics {};12001201exp fn parts(self widget: &Widget) -> Vector<Part> => Vector<Part>::empty();12021203exp fn settling(self widget: &Widget, since: Duration) -> bool => false;12041205exp fn wants_hover(self widget: &Widget) -> bool => false;12061207exp fn mirrors_children(self widget: &Widget) -> bool => true;12081209// An item an element draws itself, to a screen reader.1210exp type Part = struct {1211 exp semantics: Semantics,1212 exp bounds: Rect, // in the element's coordinates1213 exp focused: bool = false, // holds the keyboard's focus while the element has it1214};12151216// What a screen reader asks of one of an element's parts, by its index1217// among them: Click, Select, Focus or ScrollIntoView.1218exp type PartRequest = struct {1219 exp part: u32,1220 exp action: Action,1221};12221223// Input an element is given, at a point in its own coordinates.1224exp type Input = enum {1225 Press: Point,1226 Release: Point,1227 // a press and a release on the element1228 Click: Point,1229 // the pointer moved while the element captured it by a press1230 Moved: Point,1231 // to the focused element, then up its ancestors1232 Key: KeyEvent,1233 Text: String,1234 Preedit: Preedit,1235 // the element took the focus, or lost it1236 Focus: bool,1237 // the wheel or a touchpad, in logical pixels, to the element under1238 // the pointer, then up its ancestors1239 Scroll: Point,1240 // what a screen reader asks of the element that no other input1241 // gives: setting a value or a selection (a click comes as Click,1242 // stepping as arrow keys, focusing and scrolling into view through1243 // the Ui)1244 Action: Action,1245 // the clipboard's text, to the element that asked for it with1246 // `ui.request_paste()`1247 Paste: String,1248 // what a screen reader asks of one of its parts1249 Part: PartRequest,1250 // the pointer moved over the element with no button held, once an1251 // element wanting it (`Widget::wants_hover`) was laid out1252 Hover: Point,1253};12541255// What an element paints with: its size, the theme and its state.1256exp type Look = struct {1257 exp size: Extent,1258 exp theme: &Theme,1259 exp hovered: bool,1260 exp pressed: bool,1261 // how hovered and pressed it is, from 0 to 1, easing over the theme's1262 // short duration as the pointer comes and goes1263 exp hover: f32,1264 exp press: f32,1265 // the time since its options last changed, or since it was made: what1266 // a widget moving its own drawing goes by (`Widget::settling`)1267 exp since: Duration,1268 exp focused: bool,1269 // focused from the keyboard, which shows the focus ring1270 exp focus_ring: bool,1271 exp marks: &Marks,1272 exp images: &[StoredImage],1273 exp reduced: bool, // the motion asked for is less1274 // which way the element reads: its own drawing at its start, the1275 // right right to left1276 exp direction: LayoutDirection = LayoutDirection::LeftToRight,1277};12781279// The x of something `width` wide at `x` from the element's start edge:1280// x itself left to right, from the right edge right to left.1281exp fn from_start(self look: &Look, x: f32, width: f32) -> f32 {1282 return if (look.direction is ::RightToLeft) look.size.width - x - width else x;1283}12841285// Small pictures widgets paint, made with the canvas.1286exp type Marks = struct {1287 exp check: Option<Picture>, // a check mark's coverage1288 exp chevron: Option<Picture> = ::None, // a downward chevron's, made as a Select first lays out1289 // chevrons to the left and to the right, made as a calendar first lays out1290 exp previous: Option<Picture> = ::None,1291 exp next: Option<Picture> = ::None,1292};12931294// The children of an element being laid out, the elements `show` and1295// `each` make standing in place of those.1296exp type Arrange = struct {1297 exp ui: &var Ui,1298 pub children: Vector<u32>,1299 pub direction: LayoutDirection = LayoutDirection::LeftToRight,1300 // right to left and mirroring: the children placed, from the start,1301 // turned into x from the left once the size is known1302 pub mirrored: bool = false,1303 pub placed: Vector<Placement> = Vector<Placement>::empty(),1304};13051306pub type Placement = struct {1307 pub node: u32,1308 pub at: Point,1309};13101311// How many children there are.1312exp fn count(self arrange: &Arrange) -> u64 => arrange.children.length();13131314// Lays a child out within the limits, its sizing applied, giving its size.1315exp fn lay_out(self arrange: &var Arrange, child: u64, limits: Limits) -> Extent {1316 return arrange.ui.lay_out_node(arrange.children.get(child), limits);1317}13181319// Puts a child's top left at the point, its x from the element's start1320// edge: the left, or the right right to left.1321exp fn place(self arrange: &var Arrange, child: u64, at: Point) {1322 if (arrange.mirrored) {1323 arrange.placed.push(Placement { .node = arrange.children.get(child), .at = at });1324 } else {1325 arrange.ui.place_node(arrange.children.get(child), at);1326 }1327}13281329// Which way the element being laid out reads.1330exp fn direction(self arrange: &Arrange) -> LayoutDirection => arrange.direction;13311332exp fn sizing(self arrange: &Arrange, child: u64) -> Sizing {1333 return arrange.ui.node_sizing(arrange.children.get(child));1334}13351336exp fn theme(self arrange: &Arrange) -> &Theme => &arrange.ui.theme;13371338exp fn fonts(self arrange: &var Arrange) -> &var text::Fonts => &var arrange.ui.fonts();13391340// The theme's font at the size, a paragraph with no letter reading as1341// the element does (decisions/F14.md, question 11A, as an1342// element with dir=auto).1343exp fn text_style(self arrange: &var Arrange, size: f32) -> text::TextStyle {1344 var style = text::TextStyle::of(arrange.fonts().default(), size);1345 if (arrange.direction is ::RightToLeft) {1346 style.direction = text::Direction::AutoRightToLeft;1347 }1348 return move style;1349}13501351/* --- The Ui --- */13521353// Elements are named by their index in `nodes`, signals, effects and1354// owners by theirs in their own vectors; a freed slot goes on its free1355// list for the next one made.1356exp type Ui = struct {1357 exp signals: Vector<SignalSlot> = Vector<SignalSlot>::empty(),1358 pub free_signals: Vector<u32> = Vector<u32>::empty(),1359 exp nodes: Vector<Node> = Vector<Node>::empty(),1360 pub free_nodes: Vector<u32> = Vector<u32>::empty(),1361 exp effects: Vector<Effect> = Vector<Effect>::empty(),1362 pub free_effects: Vector<u32> = Vector<u32>::empty(),1363 exp owners: Vector<OwnerSlot> = Vector<OwnerSlot>::empty(),1364 pub free_owners: Vector<u32> = Vector<u32>::empty(),1365 exp owner: u32 = 0, // what is made now belongs to1366 pub tracking: Mutex<Tracking> = Mutex::from(Tracking {1367 .effect = ::None,1368 .reads = Vector<u32>::empty()1369 }),1370 pub dirty: Vector<u64> = Vector<u64>::empty(), // effects to run again, a heap (store.alloy)1371 exp root: Option<u32> = ::None,1372 exp theme: Theme = Theme::light(),1373 pub own_fonts: Option<text::Fonts> = ::None, // with no scene1374 // what each fonts made is given (`install_fonts`)1375 pub font_installs: Vector<(&var text::Fonts)> = Vector<(&var text::Fonts)>::empty(),1376 // counts changes to the fonts text is laid out with, for widgets1377 // keeping layouts (a calendar's names)1378 exp fonts_changed: u32 = 0,1379 exp scene: Option<Scene> = ::None,1380 exp viewport: Extent = Extent::zero(),1381 exp scale: f32 = 1.0,1382 pub snapped_scale: f32 = 0.0, // the scale painting last snapped at1383 pub layout_pending: bool = false,1384 pub paint_pending: bool = false,1385 exp pointer: Option<Point> = ::None,1386 exp hovered: Option<u32> = ::None,1387 pub pressed: Option<u32> = ::None,1388 exp focused: Option<u32> = ::None,1389 exp focus_ring: bool = false,1390 pub modifiers: Modifiers = Modifiers::none(),1391 exp marks: Marks = Marks { .check = ::None },1392 // what the window shows, applied by the app after each event1393 pub cursor: Cursor = Cursor::Arrow,1394 pub text_input: Option<Rect> = ::None,1395 exp handling: Option<u32> = ::None, // the element given input now1396 pub images: Vector<StoredImage> = Vector<StoredImage>::empty(),1397 pub free_images: Vector<u32> = Vector<u32>::empty(),1398 // the app's worker tasks, when it has them, and the work `background`1399 // queued for them1400 exp workers: Option<&Workers> = ::None,1401 exp jobs: Vector<|=| (&Workers) -> |=| (1402 &var Ui1403 )> = Vector<|=| (&Workers) -> |=| (&var Ui)>::empty(),1404 // what finished work gives, run before the next update1405 exp finished: Vector<|=| (&var Ui)> = Vector<|=| (&var Ui)>::empty(),1406 pub quitting: bool = false, // the app closes its window after the event1407 exp replaying: bool = false, // run by `replay`, which scripts what the window gives1408 // asked when the person closes the window (`on_close_requested`)1409 pub close_asks: Option<|=| (&var Ui) -> bool> = ::None,1410 // whether a screen reader reads, once one asked (pkg::alloy::ui_access),1411 // and whether an element was laid out or painted since the tree was1412 // last sent1413 exp access_on: bool = false,1414 exp access_stale: bool = true,1415 // the clipboard: text to put on it, and the element a paste goes to1416 pub clipboard_out: Option<String> = ::None,1417 pub paste_target: Option<Element> = ::None,1418 pub paste_wanted: bool = false,1419 // the window's clock and the wall clock as the event handled now1420 // came, the timers waiting for each, a heap by time for each1421 // (timers.alloy), and the clocks `clock` made1422 exp time: Duration = Duration::from_nanoseconds(0),1423 exp wall: i64 = 0,1424 pub timers: Vector<TimerSlot> = Vector<TimerSlot>::empty(),1425 pub free_timers: Vector<u32> = Vector<u32>::empty(),1426 pub due: Vector<Due> = Vector<Due>::empty(),1427 pub wall_due: Vector<Due> = Vector<Due>::empty(),1428 pub clocks: Vector<WallClock> = Vector<WallClock>::empty(),1429 // the layers open, in the order they opened (layers.alloy), what1430 // their elements' handlers freed while running, kept to the event's1431 // end, and the press a popup opened1432 exp layers: Vector<LayerSlot> = Vector<LayerSlot>::empty(),1433 pub layer_serial: u32 = 0,1434 pub graveyard: Vector<*var Widget> = Vector<*var Widget>::empty(),1435 pub pointer_down: Option<Point> = ::None,1436 pub popup_press: Option<PopupPress> = ::None,1437 // what the program reached that the Ui calls at points of its work1438 // (extensions.alloy), each installed as it is first used, so a1439 // program not using one carries none of its code1440 pub extensions: Vector<*var Extension> = Vector<*var Extension>::empty(),1441 // an element following the pointer over what it draws was laid out1442 // (`Widget::wants_hover`): the pointer's moves go to it as Hover1443 pub hovers: bool = false,1444 // what screen readers are to say, given the window after the event1445 exp announced: Vector<Announcement> = Vector<Announcement>::empty(),1446 // the owners of views hidden (views.alloy), whose bindings wait1447 // until shown, and where the focus goes once a view shown is laid out1448 pub hidden_owners: u32 = 0,1449 exp focus_after: Option<ScreenFocus> = ::None,1450 // the path the page was opened at, for the first navigator with paths1451 exp start_path: String = String::empty(),1452 // the languages (languages.alloy, F14a): the one chosen as the app1453 // starts, what the app set of the language and the direction, in1454 // signals of the Ui's own, and what they come to, which layout and the1455 // window read1456 pub chosen: String = String::from(&"en"),1457 exp language_set: Signal<Option<String>> = Signal<Option<String>> {1458 .index = 0,1459 .generation = 01460 },1461 pub direction_set: Signal<Option<LayoutDirection>> = Signal<Option<LayoutDirection>> {1462 .index = 0,1463 .generation = 01464 },1465 pub spoken: String = String::from(&"en"),1466 pub flow: LayoutDirection = LayoutDirection::LeftToRight,1467 // motion (motion.alloy): whether the window and the app ask for less,1468 // whether a frame was drawn yet (what is there before it does not1469 // move in), the elements whose hover or press eases and those1470 // settling, painted each frame; the rest of motion's state is an1471 // extension made once a program moves something, which asks for1472 // frames while `moving`1473 pub reduced_system: bool = false,1474 pub reduced_app: Option<bool> = ::None,1475 exp drawn: bool = false,1476 pub eases: Vector<Ease> = Vector<Ease>::empty(),1477 pub settling: Vector<u32> = Vector<u32>::empty(),1478 exp moving: bool = false,1479 // the window's waker, which the page's callbacks wake the loop by, and1480 // the name the app's data is kept under, the window's, taken as the1481 // app starts1482 exp waker: Waker = Waker::None,1483 exp app: String = String::empty(),1484};14851486pub type StoredImage = struct {1487 pub width: u32,1488 pub height: u32,1489 pub pixels: Vector<u8>, // until made a picture1490 pub picture: Option<Picture>,1491 pub generation: u32, // of the ImageId naming it1492 pub alive: bool,1493};14941495// A Ui with nothing in it, in the light theme, drawing nowhere until1496// `app` gives it a scene.1497exp fn Ui::create() -> Ui {1498 var ui = Ui {};1499 ui.owners.push(OwnerSlot::create(::None, 0));1500 var language: Option<String> = ::None;1501 ui.language_set = ui.signal(move language);1502 const direction: Option<LayoutDirection> = ::None;1503 ui.direction_set = ui.signal(direction);1504 return move ui;1505}15061507// The node of the element at the index.1508exp fn node(self ui: &Ui, index: u32) -> &Node => &ui.nodes.get(index to u64);15091510exp fn node_var(self ui: &var Ui, index: u32) -> &var Node => &var ui.nodes.get_var(index to u64);15111512// A new signal holding the value, belonging to what is being made.1513exp fn signal<T>(self ui: &var Ui, value: T) -> Signal<T> {1514 const index = ui.new_signal(new Held<T> { .value = move value });1515 return Signal<T> { .index = index, .generation = ui.signals.get(index to u64).generation };1516}15171518// The value; in a binding, recorded so the binding runs again when it1519// changes.1520exp fn get<T>(self signal: &Signal<T>, ui: &Ui) -> &T {1521 ui.read_signal(signal.index, signal.generation);1522 if (ui.signals.get(signal.index to u64).value is ::Some |&held|) {1523 if (held is Held<T> |&h|) {1524 return &h.value;1525 }1526 }1527 panic "pkg::alloy::ui: a signal of another type";1528}15291530// Replaces the value; the bindings that read it run again once the1531// handler returns.1532exp fn set<T>(self signal: &Signal<T>, ui: &var Ui, value: T) {1533 signal.update(&var ui, |move value| (v: &var T) {1534 v = move value;1535 });1536}15371538// Changes the value in place; the bindings that read it run again once1539// the handler returns.1540exp fn update<T>(self signal: &Signal<T>, ui: &var Ui, change: |&| (&var T)) {1541 ui.check_signal(signal.index, signal.generation);1542 if (ui.signals.get_var(signal.index to u64).value is ::Some |&var held|) {1543 if (held is Held<T> |&var h|) {1544 change(&var h.value);1545 ui.changed_signal(signal.index);1546 return;1547 }1548 }1549 panic "pkg::alloy::ui: a signal of another type";1550}15511552// Changes in place the items `picks` picks, as `update` does: the item1553// of a row `each` made, by its id.1554exp fn update_where<T>(1555 self items: &Signal<Vector<T>>,1556 ui: &var Ui,1557 picks: |&| (&T) -> bool,1558 change: |&| (&var T)1559) {1560 items.update(&var ui, |&picks, &change| (list: &var Vector<T>) {1561 for (list.items()) |&var item| {1562 if (picks(&item)) {1563 change(&var item);1564 }1565 }1566 });1567}15681569// A new element with the options, which stay as given; the elements1570// they hold become its children.1571exp fn add<W: Widget>(self ui: &var Ui, options: W) -> Element {1572 const index = ui.new_node(new options, false);1573 return ui.element(index);1574}15751576// A new element whose options the function gives, now and again each1577// time a signal it read changes; the options may hold no children (an1578// element holding some is bound by `bind_options`).1579exp fn bind<W: Widget>(self ui: &var Ui, options: |=| (&Ui) -> W) -> Element {1580 const effect = ui.new_effect();1581 const first = ui.tracked(effect, &options);1582 const index = ui.new_node(new first, false);1583 if (ui.node(index).children.length() != 0) {1584 panic "pkg::alloy::ui: a bound element holds no children; use bind_options, show or each";1585 }1586 const element = ui.element(index);1587 ui.set_effect(effect, ::Some(element.index), |move options, element| (ui: &var Ui) {1588 var next = options(&ui);1589 ui.renew_node<W>(element, move next);1590 });1591 return element;1592}15931594// Binds the options of an element `add` made, holding children: the1595// function gives them now and again each time a signal it read changes,1596// the element keeping its children and its own state; its options hold1597// no children. The element must be of the options' type.1598//1599// ```text1600// const card = ui.add(Card { .children = &[poster, title] });1601// ui.bind_options(card, (ui) => Card { .accessible = f"{event.get(&ui).title}" });1602// ```1603exp fn bind_options<W: Widget>(1604 self ui: &var Ui,1605 element: Element,1606 options: |=| (&Ui) -> W1607) -> Element {1608 ui.check_node(element.index, element.generation);1609 var same = false;1610 if (ui.node(element.index).widget is ::Some |&w| && w is W) {1611 same = true;1612 }1613 if (!same) {1614 panic "pkg::alloy::ui: bind_options on an element of another type";1615 }1616 const effect = ui.new_effect();1617 ui.set_effect(effect, ::Some(element.index), |move options, element| (ui: &var Ui) {1618 var next = options(&ui);1619 if (next.children().length() != 0) {1620 panic "pkg::alloy::ui: bound options hold no children; the element keeps its own";1621 }1622 ui.renew_node<W>(element, move next);1623 });1624 ui.run_effect(effect);1625 return element;1626}16271628// An element holding the view while the condition holds, made when it1629// starts to and freed, with all it made, when it stops.1630exp fn show(1631 self ui: &var Ui,1632 condition: |=| (&Ui) -> bool,1633 view: |=| (&var Ui) -> Element1634) -> Element {1635 const element = ui.element(ui.new_node(new Group {}, true));1636 const state = ui.signal(Option<u32>::None);1637 const effect = ui.new_effect();1638 ui.set_effect(effect, ::Some(element.index), |move condition, move view, element, state| (ui: &var Ui) {1639 ui.run_show(element, state, &condition, &view);1640 });1641 ui.run_effect(effect);1642 return element;1643}16441645// What `switch` does with a view no longer shown.1646exp type Keep = enum {1647 All, // kept hidden, as it was left, until shown again1648 None, // freed with all it made, made again from nothing when shown1649};16501651// An element showing the view for the key `key` gives, made when the key1652// first comes; when it changes, the view shown before is kept hidden1653// (Keep::All) or freed (Keep::None). A hidden view is not laid out,1654// drawn, hit, focused nor read by screen readers; its signals and its1655// widgets' own state stay as they were, and its bindings whose signals1656// changed run once it shows again.1657exp fn switch<K: hash::Key>(1658 self ui: &var Ui,1659 key: |=| (&Ui) -> K,1660 view: |=| (&var Ui, K) -> Element,1661 keep: Keep1662) -> Element {1663 const element = ui.element(ui.new_node(new Group {}, true));1664 const state = ui.signal(Views<K> { .shown = ::None, .views = Map<K, View>::empty() });1665 const effect = ui.new_effect();1666 ui.set_effect(effect, ::Some(element.index), |move key, move view, element, state, keep| (ui: &var Ui) {1667 ui.run_switch(element, state, &key, &view, keep);1668 });1669 ui.run_effect(effect);1670 return element;1671}16721673// An element holding a row for each item of the vector, in order, made1674// by `row` from a signal of its own holding the item. Items are told1675// apart by the key `key` gives: a row whose key stays keeps its elements1676// and has its signal set when the vector changes, and a row whose key1677// goes is freed with all it made.1678exp fn each<T, K: hash::Key>(1679 self ui: &var Ui,1680 items: Signal<Vector<T>>,1681 key: |=| (&T) -> K,1682 row: |=| (&var Ui, Signal<T>) -> Element1683) -> Element {1684 const element = ui.element(ui.new_node(new Group {}, true));1685 const state = ui.signal(Rows<T, K> { .rows = Map<K, RowOf<T>>::empty() });1686 const effect = ui.new_effect();1687 ui.set_effect(effect, ::Some(element.index), |move key, move row, items, element, state| (ui: &var Ui) {1688 ui.run_each(element, items, state, &key, &row);1689 });1690 ui.run_effect(effect);1691 return element;1692}16931694// A scrolled list of `count` rows, of which only those in view, and a1695// screen's worth around them, are made: by `row` from the row's index,1696// each freed with all it made once far out of view. Rows are measured as1697// they are made; the list keeps its place on a row, so a row measured1698// taller than its estimate moves nothing in view.1699exp fn list(1700 self ui: &var Ui,1701 count: |=| (&Ui) -> u64,1702 row: |=| (&var Ui, u64) -> Element,1703 options: ListOptions1704) -> Element {1705 const element = ui.element(ui.new_node(new ListView::create(options), false));1706 const wanted = ui.signal(RowSpan { .first = 0, .end = 0 });1707 const counting = ui.new_effect();1708 ui.set_effect(counting, ::Some(element.index), |move count, element| (ui: &var Ui) {1709 const n = count(&ui);1710 ui.set_list_count(element, n);1711 });1712 ui.run_effect(counting);1713 const building = ui.new_effect();1714 ui.set_effect(building, ::Some(element.index), |move row, element, wanted| (ui: &var Ui) {1715 ui.build_rows(element, &wanted.get(&ui), &row);1716 });1717 ui.run_effect(building);1718 ui.set_list_wanted(element, wanted);1719 return element;1720}17211722// Keeps the RGBA pixels, row after row, as a picture image elements show.1723exp fn image(self ui: &var Ui, width: u32, height: u32, pixels: Vector<u8>) -> ImageId {1724 var stored = StoredImage {1725 .width = width,1726 .height = height,1727 .pixels = move pixels,1728 .picture = ::None,1729 .generation = 0,1730 .alive = true1731 };1732 ui.paint_pending = true;1733 if (ui.free_images.pop() is ::Some |index|) {1734 const generation = ui.images.get(index to u64).generation;1735 ui.images.set(index to u64, move stored);1736 ui.images.get_var(index to u64).generation = generation;1737 return ImageId { .index = index, .generation = generation };1738 }1739 ui.images.push(move stored);1740 return ImageId { .index = (ui.images.length() - 1) to u32, .generation = 0 };1741}17421743// Shows other pixels in place of the image's, in every element showing1744// it, giving back the picture they replace.1745exp fn set_image(self ui: &var Ui, image: ImageId, width: u32, height: u32, pixels: Vector<u8>) {1746 ui.check_image(image);1747 ui.release_picture(image.index);1748 const stored = &var ui.images.get_var(image.index to u64);1749 stored.width = width;1750 stored.height = height;1751 stored.pixels = move pixels;1752 ui.show_image_changed(image);1753}17541755// Gives back the image's pixels and picture; elements showing it show1756// nothing, and its id names nothing from now on.1757exp fn free_image(self ui: &var Ui, image: ImageId) {1758 ui.check_image(image);1759 ui.release_picture(image.index);1760 const stored = &var ui.images.get_var(image.index to u64);1761 stored.pixels = Vector<u8>::empty();1762 stored.alive = false;1763 stored.generation += 1;1764 ui.free_images.push(image.index);1765 ui.show_image_changed(image);1766}17671768// The image an id names, if it is still kept.1769pub fn stored_image(self ui: &Ui, image: ImageId) -> Option<&StoredImage> {1770 return stored_in(&ui.images.view(), image);1771}17721773pub fn stored_in(images: &[StoredImage], image: ImageId) -> Option<&StoredImage> {1774 if (image.index to u64 < images.length()) {1775 const stored = &images[image.index to u64];1776 if (stored.alive && stored.generation == image.generation) {1777 return ::Some(&stored);1778 }1779 }1780 return ::None;1781}17821783fn check_image(self ui: &Ui, image: ImageId) {1784 if (ui.stored_image(image) is ::None) {1785 panic "pkg::alloy::ui: an image used after it was freed";1786 }1787}17881789fn release_picture(self ui: &var Ui, index: u32) {1790 const stored = &var ui.images.get_var(index to u64);1791 if (stored.picture is ::Some |p| && ui.scene is ::Some |&var scene|) {1792 if (scene.has_device()) {1793 scene.canvas.release_picture(&var scene.device(), p);1794 } else {1795 scene.unreleased.push(p); // for the overlay's next frame1796 }1797 }1798 stored.picture = ::None;1799}18001801// Lays out and paints again the elements showing the image.1802fn show_image_changed(self ui: &var Ui, image: ImageId) {1803 ui.paint_pending = true;1804 for ([..ui.nodes.length() to u32]) |k| {1805 const node = &ui.node(k);1806 if (1807 node.alive1808 && node.widget is ::Some |&widget|1809 && widget is Image |&i|1810 && i.image.index == image.index1811 ) {1812 ui.apply(k, Change::Layout);1813 }1814 }1815}18161817// The theme the widgets paint in.1818exp fn theme(self ui: &Ui) -> &Theme => &ui.theme;18191820// Paints and lays everything out again in the theme.1821exp fn set_theme(self ui: &var Ui, theme: Theme) {1822 ui.theme = theme;1823 if (ui.scene is ::Some |&var scene| && !scene.over) {1824 scene.canvas.set_background(theme.background);1825 }1826 ui.invalidate_all();1827}18281829// Makes the element the root, laid out at the size given in logical1830// pixels.1831exp fn mount(self ui: &var Ui, root: Element, width: f32, height: f32) {1832 ui.check_node(root.index, root.generation);1833 ui.root = ::Some(root.index);1834 ui.viewport = Extent { .width = width, .height = height };1835 ui.mark_layout(root.index);1836}18371838// Runs the bindings marked, then lays out what changed; what an event1839// changed shows after this.1840exp fn update_all(self ui: &var Ui) {1841 ui.graveyard.clear();1842 ui.run_finished();1843 ui.extensions_updating();1844 // a layout may change what bindings read, as a list asking for rows1845 for ([..4 to u64]) |pass| {1846 ui.flush();1847 ui.lay_out_all();1848 if (ui.dirty.length() == 0) {1849 break;1850 }1851 }1852 // the focus a screen shown takes, once it is laid out1853 if (ui.focus_after is ::Some |after|) {1854 ui.focus_after = ::None;1855 ui.focus_screen(after);1856 }1857 // the layers whose owner or anchor went, and those whose anchor moved1858 ui.extensions_updated();1859}18601861// Runs the work on one of the app's worker tasks, away from the UI1862// thread, then the function the work gives on the UI thread, as a1863// handler: the window goes on drawing and taking input meanwhile. The1864// work owns what it captures, as its type says, and leaves the Ui and1865// its signals to the function it gives:1866//1867// ```text1868// ui.background(|move files| () -> |=| (&var Ui) {1869// const pictures = decode_all(&files);1870// return |move pictures| (ui: &var Ui) => shown.set(&var ui, move pictures);1871// });1872// ```1873//1874// With no workers (a page, `replay`, a Ui made on its own) the work1875// runs at once and its function at the next update.1876exp fn background(self ui: &var Ui, work: |=| () -> |=| (&var Ui)) {1877 if (ui.workers is ::Some) {1878 // a worker passes what the app's tasks share, which work leaves be1879 ui.jobs.push(|move work| (workers: &Workers) -> |=| (&var Ui) => work());1880 } else {1881 ui.finished.push(work());1882 }1883}18841885// Puts the text on the clipboard, once the event is handled.1886exp fn set_clipboard(self ui: &var Ui, text: String) {1887 ui.clipboard_out = ::Some(move text);1888}18891890// Asks for the clipboard's text, which comes to the element handling1891// input now as Input::Paste.1892exp fn request_paste(self ui: &var Ui) {1893 if (ui.handling is ::Some |handling|) {1894 ui.paste_target = ::Some(ui.element(handling));1895 ui.paste_wanted = true;1896 }1897}18981899// Asks the function when the person closes the window (or, on the web,1900// leaves or reloads the page): true closes it, false keeps it open, as1901// for a cart held or a form half done, the function asking the person1902// (a dialog whose "Close" then calls `quit`). On the web the browser1903// asks too, in its own words, when the function refuses.1904exp fn on_close_requested(self ui: &var Ui, asks: |=| (&var Ui) -> bool) {1905 ui.close_asks = ::Some(move asks);1906}19071908// Closes the app's window once the event is handled, which ends `app`.1909exp fn quit(self ui: &var Ui) {1910 ui.quitting = true;1911}19121913// The time on the window's clock when the event being handled came,1914// monotonic from when the window opened; in `replay`, as the events'1915// Redraws set it.1916exp fn now(self ui: &Ui) -> Duration => ui.time;19171918// Runs `then` as a handler once the delay has passed on the window's1919// clock, unless cancelled first or its owner goes, the timer belonging to1920// what is being made as a signal does.1921exp fn after(self ui: &var Ui, delay: Duration, then: |=| (&var Ui)) -> Timer {1922 return ui.new_timer(ui.time.nanoseconds + delay.nanoseconds, 0, move then);1923}19241925// Runs `then` every period from now on the window's clock, as a handler,1926// until cancelled or its owner goes. Fixed rate: each run is due a1927// period after the last was due, and runs missed while the loop was1928// busy or the machine slept are skipped, not run in a burst.1929exp fn every(self ui: &var Ui, period: Duration, then: |=| (&var Ui)) -> Timer {1930 if (period.nanoseconds == 0) {1931 panic "pkg::alloy::ui: a timer repeating every 0 seconds";1932 }1933 return ui.new_timer(ui.time.nanoseconds + period.nanoseconds, period.nanoseconds, move then);1934}19351936// Runs `then` as a handler once the wall clock reaches the moment1937// (nanoseconds since 1970 UTC, as `std::time::wall_clock()` gives),1938// unless cancelled first or its owner goes: for deadlines another machine1939// sets. It is at most 5 seconds late after the machine slept or the1940// system's time was set.1941exp fn at(self ui: &var Ui, moment: i64, then: |=| (&var Ui)) -> Timer {1942 return ui.new_wall_timer(moment, move then);1943}19441945// A signal of the wall clock (nanoseconds since 1970 UTC) at the start1946// of the step it is in, changing on each multiple of the step: each1947// second, each minute. Every call with one step gives the same signal,1948// the Ui's own, which ticks only while some binding shown reads it.1949exp fn clock(self ui: &var Ui, step: Duration) -> Signal<i64> {1950 if (step.nanoseconds == 0) {1951 panic "pkg::alloy::ui: a clock stepping by 0 seconds";1952 }1953 return ui.wall_clock_signal(step.nanoseconds);1954}19551956// What a timer or a request belongs to, going with it.1957exp type HandlerOptions = struct {1958 // None: what is being made now, or the element whose handler runs;1959 // `ui.root_owner()` keeps it until the app ends or it is cancelled1960 exp owner: Option<Owner> = ::None,1961};19621963// The app's root: what belongs to it stays until the app ends.1964exp fn root_owner(self ui: &Ui) -> Owner => Owner {1965 .index = 0,1966 .generation = ui.owners.get(0).generation1967};19681969// `after` with the options: a timer belonging to their owner.1970exp fn after(1971 self ui: &var Ui,1972 delay: Duration,1973 then: |=| (&var Ui),1974 options: HandlerOptions1975) -> Timer {1976 const saved = ui.owner;1977 ui.owner = ui.owner_given(options.owner);1978 const timer = ui.after(delay, move then);1979 ui.owner = saved;1980 return timer;1981}19821983// `every` with the options.1984exp fn every(1985 self ui: &var Ui,1986 period: Duration,1987 then: |=| (&var Ui),1988 options: HandlerOptions1989) -> Timer {1990 const saved = ui.owner;1991 ui.owner = ui.owner_given(options.owner);1992 const timer = ui.every(period, move then);1993 ui.owner = saved;1994 return timer;1995}19961997// `at` with the options: a deadline outliving the screen setting it, as1998// seats held until a moment the server gave.1999exp fn at(self ui: &var Ui, moment: i64, then: |=| (&var Ui), options: HandlerOptions) -> Timer {2000 const saved = ui.owner;2001 ui.owner = ui.owner_given(options.owner);2002 const timer = ui.at(moment, move then);2003 ui.owner = saved;2004 return timer;2005}20062007// Forgets the timer; nothing when it ran or went already.2008exp fn cancel(self ui: &var Ui, timer: Timer) {2009 ui.drop_timer(timer);2010}20112012/* --- Layers (decisions/F11.md, F11a) --- */20132014// How a layer opens over the window's content.2015exp type Overlay = struct {2016 exp place: Place = Place::Center,2017 // a scrim under it; the pointer and the keyboard reach nothing below,2018 // and Tab goes round within it2019 exp modal: bool = false,2020 exp escape: bool = true, // Escape closes it2021 exp outside: bool = true, // a press outside it closes it, and goes no further2022 exp role: LayerRole = LayerRole::Plain, // what a screen reader calls it2023 exp label: String = String::empty(), // what a screen reader says of it2024 exp panel: bool = true, // drawn on the theme's surface, rounded, with a shadow2025 exp on_close: |=| (&var Ui) = (ui) {}, // closed by Escape, a press outside, or ui.close2026 exp keyboard: bool = true, // takes the focus as it opens: not a tooltip's or the toasts'2027 exp passive: bool = false, // takes no pointer and goes at any press: a tooltip's2028 exp tabbed: bool = false, // Tab goes to what has the focus first: a Select's list2029};20302031// A modal dialog, centered, which a press outside does not close.2032exp fn Overlay::dialog(label: &[u8]) -> Overlay => Overlay {2033 .modal = true,2034 .outside = false,2035 .role = LayerRole::Dialog,2036 .label = String::from(&label)2037};20382039// A dialog asking for an answer: "Delete the order?"2040exp fn Overlay::alert(label: &[u8]) -> Overlay => Overlay {2041 .modal = true,2042 .outside = false,2043 .role = LayerRole::Alert,2044 .label = String::from(&label)2045};20462047// A popup below the element, closed by a press outside.2048exp fn Overlay::popup(anchor: Element) -> Overlay => Overlay { .place = Place::Below(anchor) };20492050// What a layer is to a screen reader.2051exp type LayerRole = enum {2052 Plain,2053 Dialog,2054 Alert,2055 Menu,2056 Tooltip,2057};20582059// Where a layer goes in the window.2060exp type Place = enum {2061 Center, // dialogs2062 // under the element, start edges aligned (left, or right right to2063 // left); above it when there is no room below2064 Below: Element,2065 Above: Element, // over the element; below it when there is no room above2066 After: Element, // beside it at its end, else its start: submenus2067 // where the pointer was, from the window's top left, reaching toward2068 // the end: a context menu2069 At: Point,2070 Corner: Corner, // the toasts2071};20722073exp type Corner = enum {2074 TopStart,2075 TopEnd,2076 BottomStart,2077 BottomEnd,2078};20792080// A layer open: a copyable handle, naming nothing once it closed.2081exp type Layer = struct {2082 pub id: u32,2083};20842085// Opens a layer over the content showing what the view makes, given the2086// layer to close it with; it belongs to the owner of the element whose2087// handler opens it (a row's goes with the row), or to the app, and what2088// its view made goes when it closes. A layer taking the keyboard focuses2089// its first element taking the focus, or the one its view focused, and2090// gives the focus back as it closes.2091exp fn open(self ui: &var Ui, overlay: Overlay, view: |=| (&var Ui, Layer) -> Element) -> Layer {2092 return ui.open_layer(move overlay, move view);2093}20942095// Closes the layer, calling its `on_close`; nothing when it closed2096// already.2097exp fn close(self ui: &var Ui, layer: Layer) {2098 if (ui.layer_index(layer) is ::Some |k|) {2099 ui.close_at(k);2100 }2101}21022103// Whether the layer is still open.2104exp fn is_open(self ui: &Ui, layer: Layer) -> bool => ui.layer_index(layer) is ::Some;21052106// The element whose handler runs now: what a menu or popup is placed by.2107exp fn source(self ui: &Ui) -> Element {2108 if (ui.handling is ::Some |h| && ui.node(h).alive) {2109 return ui.element(h);2110 }2111 panic "pkg::alloy::ui: source() outside an element's handler";2112}21132114/* --- Extensions (REFOCUS.md, question 8A) --- */21152116// What a part of the Ui that a program reaches only by using it keeps and2117// does: its state in a struct of its own, installed as it is first used2118// (`install`) and found by its type (`extension`), the Ui calling it at2119// these points of its work, each of which does nothing by default. The2120// core's layers, wall-clock timers and motion are extensions, as are what2121// pkg::alloy::ui_controls and ui_app add; a program using none carries2122// none of their code.2123//2124// ```text2125// type Counted : Extension = struct { events: u64 = 0 };2126// fn handled(self c: &var Counted, ui: &var Ui) => c.events += 1;2127//2128// fn counted(self ui: &var Ui) -> &var Counted {2129// if (ui.extension<Counted>() is ::None) {2130// ui.install(new Counted {});2131// }2132// if (ui.extension_var<Counted>() is ::Some |&var c|) {2133// return &var c;2134// }2135// panic "no count";2136// }2137// ```2138exp interface Extension {2139 // A window event came, after the timers it brought due ran.2140 fn event(self: &var, ui: &var Ui, event: &Event);2141 // The clocks were read as an event came, before any timer runs.2142 fn clock(self: &var, ui: &var Ui);2143 // The window clock's timers due ran: the extension's own run now.2144 fn timers(self: &var, ui: &var Ui);2145 // When the window is to wake for it next, in nanoseconds on its clock;2146 // asked before the Ui's timers are, so it may set some.2147 fn deadline(self: &var, ui: &var Ui) -> Option<u64>;2148 // An update begins, before the bindings run.2149 fn updating(self: &var, ui: &var Ui);2150 // The bindings ran, and what changed was laid out.2151 fn updated(self: &var, ui: &var Ui);2152 // A frame begins, before its update: what moves this frame marked.2153 fn frame(self: &var, ui: &var Ui);2154 // The frame was painted: what moves shown on the canvas; whether2155 // something still moves, for which the app draws the next frame.2156 fn painted(self: &var, ui: &var Ui) -> bool;2157 // An element marked `moving` was placed anew.2158 fn placed(self: &var, ui: &var Ui, index: u32);2159 // An owner goes, before what it made is freed.2160 fn owner_going(self: &var, ui: &var Ui, owner: u32);2161 // The pointer moved to the point, or left the window (None).2162 fn pointer(self: &var, ui: &var Ui, at: Option<Point>);2163 // The pointer came onto the element.2164 fn hovered(self: &var, ui: &var Ui, index: u32);2165 // A button pressed at the point, before any element has it: true takes2166 // it, and it goes no further.2167 fn pressed(self: &var, ui: &var Ui, at: Point) -> bool;2168 // A button released at the point, over the element there, after the2169 // element it pressed had it.2170 fn released(self: &var, ui: &var Ui, at: Point, under: Option<u32>);2171 // A key, before the focused element has it: true takes it.2172 fn key(self: &var, ui: &var Ui, key: &KeyEvent) -> bool;2173 // Escape, which no element took: true when the extension took it.2174 fn escaped(self: &var, ui: &var Ui) -> bool;2175 // The focus moved from one element to another, either of them none;2176 // `ring` when by the keyboard.2177 fn focused(self: &var, ui: &var Ui, from: Option<u32>, onto: Option<u32>, ring: bool);2178 // A screen reader asked to dismiss the element.2179 fn dismissed(self: &var, ui: &var Ui, index: u32);2180 // The accessibility tree is about to be sent.2181 fn describing(self: &var, ui: &var Ui);2182 // A text a screen reader reads, laid out while one does (`access_on`)2183 // and drawn at `origin` in its element: the map it reads it by2184 // (pkg::alloy::ui_access); none by default.2185 fn text_map(2186 self: &var,2187 ui: &var Ui,2188 laid: &text::Layout,2189 origin: Point,2190 look: TextLook2191 ) -> Option<TextMap>;2192 // An event was handled, and the Ui updated.2193 fn handled(self: &var, ui: &var Ui);2194 // After an event, what the extension gives the window.2195 fn show_in(self: &var, ui: &var Ui, window: &var Window);2196 // The app closes its window, or a replay ends.2197 fn closing(self: &var, ui: &var Ui);2198 // A replay ended: what the extension adds to what it gives.2199 fn replayed(self: &var, ui: &var Ui, replayed: &var Replayed);2200}22012202exp fn event(self e: &var Extension, ui: &var Ui, event: &Event) {}22032204exp fn clock(self e: &var Extension, ui: &var Ui) {}22052206exp fn timers(self e: &var Extension, ui: &var Ui) {}22072208exp fn deadline(self e: &var Extension, ui: &var Ui) -> Option<u64> => ::None;22092210exp fn updating(self e: &var Extension, ui: &var Ui) {}22112212exp fn updated(self e: &var Extension, ui: &var Ui) {}22132214exp fn frame(self e: &var Extension, ui: &var Ui) {}22152216exp fn painted(self e: &var Extension, ui: &var Ui) -> bool => false;22172218exp fn placed(self e: &var Extension, ui: &var Ui, index: u32) {}22192220exp fn owner_going(self e: &var Extension, ui: &var Ui, owner: u32) {}22212222exp fn pointer(self e: &var Extension, ui: &var Ui, at: Option<Point>) {}22232224exp fn hovered(self e: &var Extension, ui: &var Ui, index: u32) {}22252226exp fn pressed(self e: &var Extension, ui: &var Ui, at: Point) -> bool => false;22272228exp fn released(self e: &var Extension, ui: &var Ui, at: Point, under: Option<u32>) {}22292230exp fn key(self e: &var Extension, ui: &var Ui, key: &KeyEvent) -> bool => false;22312232exp fn escaped(self e: &var Extension, ui: &var Ui) -> bool => false;22332234exp fn focused(2235 self e: &var Extension,2236 ui: &var Ui,2237 from: Option<u32>,2238 onto: Option<u32>,2239 ring: bool2240) {}22412242exp fn dismissed(self e: &var Extension, ui: &var Ui, index: u32) {}22432244exp fn describing(self e: &var Extension, ui: &var Ui) {}22452246exp fn text_map(2247 self e: &var Extension,2248 ui: &var Ui,2249 laid: &text::Layout,2250 origin: Point,2251 look: TextLook2252) -> Option<TextMap> => ::None;22532254// How a text a screen reader reads is drawn (Extension::text_map): its2255// size in logical pixels, weight and color, and whether it is a heading2256// or cannot be edited.2257exp type TextLook = struct {2258 exp size: f32,2259 exp weight: u32,2260 exp color: Color,2261 exp heading: bool = false,2262 exp read_only: bool = false,2263};22642265exp fn handled(self e: &var Extension, ui: &var Ui) {}22662267exp fn show_in(self e: &var Extension, ui: &var Ui, window: &var Window) {}22682269exp fn closing(self e: &var Extension, ui: &var Ui) {}22702271exp fn replayed(self e: &var Extension, ui: &var Ui, replayed: &var Replayed) {}22722273// Adds the extension, which the Ui calls from now on.2274exp fn install(self ui: &var Ui, extension: *var Extension) {2275 ui.extensions.push(move extension);2276}22772278// The extension of the type, if one was installed.2279exp fn extension<E: Extension>(self ui: &Ui) -> Option<&E> {2280 for (ui.extensions.view()) |&e| {2281 if (e is E |&found|) {2282 return ::Some(&found);2283 }2284 }2285 return ::None;2286}22872288exp fn extension_var<E: Extension>(self ui: &var Ui) -> Option<&var E> {2289 for (ui.extensions.items()) |&var e| {2290 if (e is E |&var found|) {2291 return ::Some(&var found);2292 }2293 }2294 return ::None;2295}22962297/* --- Fonts (REFOCUS.md, R6d) --- */22982299// Installs what a package adds to text, as pkg::alloy::text_scripts' and2300// text_fonts' `install_into`, on every fonts the Ui lays text out with:2301// its own, and each scene's canvas's as it comes; what was laid out is2302// laid out again.2303exp fn install_fonts(self ui: &var Ui, install: (&var text::Fonts)) {2304 ui.font_installs.push(install);2305 if (ui.scene is ::Some |&var scene|) {2306 install(&var scene.canvas.fonts());2307 }2308 if (ui.own_fonts is ::Some |&var fonts|) {2309 install(&var fonts);2310 }2311 ui.fonts_changed += 1;2312 ui.invalidate_all();2313}23142315/* --- Languages and directions (decisions/F14.md, F14a) --- */23162317// The language the Ui's content is in, a BCP 47 tag: the one2318// `set_language` gave, else the first of the system's preferred2319// languages the app is written in (`WindowConfig.languages`), else the2320// app's first. A binding reading it runs again when it changes.2321exp fn language(self ui: &Ui) -> String {2322 if (ui.language_set.get(&ui) is ::Some |&tag|) {2323 return copy tag;2324 }2325 return copy ui.chosen;2326}23272328// Sets the app's language, None giving the system's choice again; the2329// direction follows it unless set, and everything is laid out again.2330exp fn set_language(self ui: &var Ui, language: Option<String>) {2331 ui.language_set.set(&var ui, move language);2332 ui.redirect();2333}23342335// Which way the Ui reads: the one `set_direction` gave, else its2336// language's. A binding reading it runs again when it changes.2337exp fn direction(self ui: &Ui) -> LayoutDirection {2338 if (ui.direction_set.get(&ui) is ::Some |d|) {2339 return d;2340 }2341 return direction_of_language(&ui.language().view());2342}23432344// Sets which way the Ui reads, None giving its language's again;2345// everything is laid out again.2346exp fn set_direction(self ui: &var Ui, direction: Option<LayoutDirection>) {2347 ui.direction_set.set(&var ui, direction);2348 ui.redirect();2349}23502351// The element, and all it holds, reading in the direction whatever holds2352// it, as `dir` on an HTML element: a quotation in another language,2353// media controls keeping their sides.2354exp fn directed(self ui: &var Ui, element: Element, direction: LayoutDirection) -> Element {2355 ui.check_node(element.index, element.generation);2356 ui.node_var(element.index).directed = ::Some(direction);2357 ui.mark_layout(element.index);2358 return element;2359}23602361// Which way the element read as last laid out.2362exp fn direction_of(self ui: &Ui, element: Element) -> LayoutDirection {2363 ui.check_node(element.index, element.generation);2364 return ui.node(element.index).direction;2365}23662367// Has screen readers say the text, politely or, when `assertive`, at2368// once, without the focus moving; once pkg::alloy::ui_access is2369// installed, before which nothing is said.2370exp fn announce(self ui: &var Ui, text: String, assertive: bool) {2371 ui.announced.push(Announcement { .text = move text, .assertive = assertive });2372}23732374// Gives the element the keyboard's focus, when it takes it.2375exp fn focus(self ui: &var Ui, element: Element) {2376 ui.check_node(element.index, element.generation);2377 ui.focus_node(::Some(element.index), false);2378}23792380// Paints what changed and draws a frame of the size, in physical2381// pixels, on the CPU device with no window, for tests and benchmarks2382// measuring all a Ui keeps.2383exp fn draw_offscreen(self ui: &var Ui, width: u32, height: u32) {2384 ui.draw_offscreen_frame(width, height);2385}23862387// Scrolls what is under the point by the delta, in logical pixels, as2388// the wheel does: for tests and benchmarks driving a Ui directly.2389exp fn scroll_at(self ui: &var Ui, delta: Point, at: Point) {2390 ui.scroll_event(delta, at);2391}23922393// Presses and releases the primary button at the point, in logical2394// pixels, as the pointer does: for tests and benchmarks driving a Ui2395// directly.2396exp fn click_at(self ui: &var Ui, at: Point) {2397 ui.pointer_moved(at);2398 ui.pointer_button(true, at);2399 ui.pointer_button(false, at);2400}24012402// Whether the element has the keyboard's focus.2403exp fn has_focus(self ui: &Ui, element: Element) -> bool {2404 return ui.exists(element) && ui.focused == ::Some(element.index);2405}24062407// Lays out or paints again the element handling input now, whose own2408// state the input changed.2409exp fn refresh(self ui: &var Ui, change: Change) {2410 if (ui.handling is ::Some |handling|) {2411 ui.apply(handling, change);2412 }2413}24142415// The size of the element handling input now, as last laid out.2416exp fn handling_size(self ui: &Ui) -> Extent {2417 if (ui.handling is ::Some |handling|) {2418 return ui.node(handling).size;2419 }2420 return Extent::zero();2421}24222423// Which way the element handling input now reads, as last laid out:2424// what its pointer's points and arrow keys mean.2425pub fn handling_direction(self ui: &Ui) -> LayoutDirection {2426 if (ui.handling is ::Some |handling|) {2427 return ui.node(handling).direction;2428 }2429 return ui.flow;2430}24312432// Whether the element handling input now reads right to left.2433exp fn handling_rtl(self ui: &Ui) -> bool => ui.handling_direction() is ::RightToLeft;24342435// The modifier keys held now.2436exp fn modifiers(self ui: &Ui) -> Modifiers => ui.modifiers;24372438// Where the element is, from the root's top left, and its size, as last2439// laid out.2440exp fn frame_of(self ui: &Ui, element: Element) -> Rect {2441 ui.check_node(element.index, element.generation);2442 const origin = ui.origin_of(element.index);2443 const size = ui.node(element.index).size;2444 return Rect::at(origin.x, origin.y, size.width, size.height);2445}24462447// Whether the element's owner is still there.2448exp fn exists(self ui: &Ui, element: Element) -> bool {2449 if (ui.nodes.try_get(element.index to u64) is ::Some |&node|) {2450 return node.generation == element.generation && node.alive;2451 }2452 return false;2453}24542455// The number of elements, signals and bindings alive, for tests.2456exp fn census(self ui: &Ui) -> [u64 : 3] {2457 var counts: [u64 : 3] = [0, 0, 0];2458 for (ui.nodes.view()) |&n| {2459 if (n.alive) {2460 counts[0] += 1;2461 }2462 }2463 for (ui.signals.view()) |&s| {2464 if (s.value is ::Some) {2465 counts[1] += 1;2466 }2467 }2468 for (ui.effects.view()) |&e| {2469 if (e.alive) {2470 counts[2] += 1;2471 }2472 }2473 return counts;2474}24752476/* --- Motion (decisions/F11.md, F11e) --- */24772478// How something moves: for how long, along which curve, after what2479// delay and how many times. Under reduced motion a value jumps and an2480// element only fades, unless `essential`.2481exp type Motion = struct {2482 exp duration: Duration = Duration::from_milliseconds(200),2483 exp easing: Easing = Easing::Standard,2484 exp delay: Duration = Duration::from_milliseconds(0),2485 exp repeat: Repeat = Repeat::Once,2486 exp essential: bool = false, // still moves under reduced motion: a progress bar2487};24882489// How far along a motion is at each moment of its duration.2490exp type Easing = enum {2491 Linear,2492 Standard, // cubic-bezier(0.2, 0, 0, 1): fast out, slow in2493 In,2494 Out,2495 InOut,2496 Cubic: [f32 : 4], // CSS's cubic-bezier(x1, y1, x2, y2)2497};24982499exp type Repeat = enum {2500 Once,2501 Times: u32,2502 Forever,2503 Alternate, // back and forth, forever2504};25052506// How long the built-in motion takes.2507exp type Durations = struct {2508 exp short: Duration, // hovering, pressing, fades, popups and menus2509 exp medium: Duration, // dialogs, toasts, views switched2510 exp long: Duration, // screens2511};25122513// How an element comes, goes and moves: the state it comes from and goes2514// to, from its place as laid out.2515exp type Transition = struct {2516 exp fade: bool = true,2517 // where it comes from and goes to, from its place, x toward the end:2518 // the left right to left2519 exp slide: Point = ORIGIN,2520 exp scale: f32 = 1.0, // its size at the start: 0.96 grows to 12521 exp reveal: bool = false, // its room opens and closes (layout each frame)2522 exp moves: bool = false, // a new place from layout is moved to, not jumped to2523 exp motion: Motion = Motion {},2524};25252526// The element, playing the transition when it first shows, once the app2527// has drawn its first frame, and backwards when its owner goes: what it2528// drew stays, taking no input and out of the accessibility tree, until2529// the transition ends; with `reveal` its room shrinks meanwhile. Gives2530// the element to place, which holds the one given.2531exp fn transition(self ui: &var Ui, element: Element, transition: Transition) -> Element {2532 return ui.make_transition(element, move transition);2533}25342535// Whether motion is reduced: as the app set it, else as the system asks.2536exp fn reduced_motion(self ui: &Ui) -> bool {2537 if (ui.reduced_app is ::Some |reduced|) {2538 return reduced;2539 }2540 return ui.reduced_system;2541}25422543// Reduces motion, or not, whatever the system asks; None follows the2544// system again.2545exp fn set_reduced_motion(self ui: &var Ui, reduced: Option<bool>) {2546 ui.reduced_app = reduced;2547}25482549// Scrolls the scrolls around the element, smoothly, until it shows.2550exp fn scroll_to(self ui: &var Ui, element: Element) {2551 ui.check_node(element.index, element.generation);2552 ui.scroll_smoothly(element.index);2553}25542555/* --- Options of the base widgets --- */25562557// Text in one style, wrapped at the width it is given.2558exp type Text : Widget = struct {2559 exp text: String,2560 exp size: Option<f32> = ::None, // None: the theme's2561 exp weight: u32 = REGULAR,2562 exp color: Ink = Ink::None, // None: the theme's text color2563 exp heading: bool = false, // at the theme's heading size when no size is given2564 exp align: TextAlign = TextAlign::Start,2565 exp sizing: Sizing = Sizing {},2566 exp drawn: Option<Paint> = ::None, // made by layout, taken by painting2567 // made by layout while a screen reader reads, when on several lines2568 pub map: Option<*TextMap> = ::None,2569};25702571// Where text goes across its room, the box and each line: Start and End2572// on its element's sides, the right right to left, whatever script the2573// text is in (decisions/F14.md, question 4A).2574exp type TextAlign = enum {2575 Start,2576 Center,2577 End,2578};25792580// How text's lines go within its box, in an element reading so.2581pub fn lines(self align: &TextAlign, direction: LayoutDirection) -> text::Align {2582 const rtl = direction is ::RightToLeft;2583 return match (align) {2584 ::Start if (rtl) text::Align::Right else text::Align::Left;2585 ::Center text::Align::Center;2586 ::End if (rtl) text::Align::Left else text::Align::Right;2587 };2588}25892590// How far from the left a box of text goes in room left beside it.2591pub fn offset(self align: &TextAlign, room: f32, direction: LayoutDirection) -> f32 {2592 return match (align.lines(direction)) {2593 ::Right room;2594 ::Center room / 2.0;2595 else 0.0;2596 };2597}25982599exp fn Text::from(text: String) -> Text => Text { .text = move text };26002601exp fn Text::from(text: &[u8]) -> Text => Text { .text = String::from(&text) };26022603// A title: bold, at the theme's heading size.2604exp fn Text::heading(text: &[u8]) -> Text => Text {2605 .text = String::from(&text),2606 .weight = BOLD,2607 .heading = true2608};26092610// A button showing its label, calling `on_press` when clicked.2611exp type Button : Widget = struct {2612 exp label: String,2613 exp accessible: String = String::empty(), // what a screen reader says, the label when empty2614 exp on_press: |=| (&var Ui) = (ui) {},2615 exp variant: ButtonVariant = ButtonVariant::Neutral,2616 exp enabled: bool = true,2617 exp padding: Padding = Padding::symmetric(14.0, 8.0),2618 exp sizing: Sizing = Sizing {},2619 exp laid: Option<*text::Layout> = ::None,2620};26212622exp type ButtonVariant = enum {2623 Neutral,2624 Primary,2625 Plain, // text only2626};26272628exp fn Button::text(label: &[u8], on_press: |=| (&var Ui)) -> Button => Button {2629 .label = String::from(&label),2630 .on_press = move on_press2631};26322633// The button standing for the main action, in the theme's primary color.2634exp fn Button::primary(label: &[u8], on_press: |=| (&var Ui)) -> Button => Button {2635 .label = String::from(&label),2636 .on_press = move on_press,2637 .variant = ButtonVariant::Primary2638};26392640// A button showing its label alone.2641exp fn Button::plain(label: &[u8], on_press: |=| (&var Ui)) -> Button => Button {2642 .label = String::from(&label),2643 .on_press = move on_press,2644 .variant = ButtonVariant::Plain2645};26462647// A box with a check mark and a label: a click, Space or Enter calls2648// `on_change` with the other state.2649exp type Checkbox : Widget = struct {2650 exp checked: bool,2651 exp label: String = String::empty(),2652 exp accessible: String = String::empty(),2653 exp on_change: |=| (&var Ui, bool) = (ui, checked) {},2654 exp enabled: bool = true,2655 // what is wrong, none when empty: the box in the theme's danger color,2656 // and to screen readers invalid, the message its description;2657 // `required` a form needs it checked2658 exp error: String = String::empty(),2659 exp required: bool = false,2660 exp sizing: Sizing = Sizing {},2661 exp laid: Option<*text::Layout> = ::None,2662 pub flipped: bool = false, // its last options changed `checked`2663};26642665exp fn Checkbox::of(2666 checked: bool,2667 label: &[u8],2668 on_change: |=| (&var Ui, bool)2669) -> Checkbox => Checkbox {2670 .checked = checked,2671 .label = String::from(&label),2672 .on_change = move on_change2673};26742675// A value between `min` and `max`, by `step` when not 0, which dragging2676// the thumb or the arrow keys change, calling `on_change`.2677exp type Slider : Widget = struct {2678 exp value: f32,2679 exp min: f32 = 0.0,2680 exp max: f32 = 1.0,2681 exp step: f32 = 0.0,2682 exp label: String = String::empty(), // shown before the track2683 exp accessible: String = String::empty(), // the label when empty2684 exp on_change: |=| (&var Ui, f32) = (ui, value) {},2685 exp enabled: bool = true,2686 exp sizing: Sizing = Sizing {},2687 exp laid: Option<*text::Layout> = ::None,2688 pub from: Option<f32> = ::None, // the value its last options changed, which the thumb leaves2689};26902691// Text to type into, on one line or several: `on_change` gets the text2692// after each edit, which the field shows at once; options giving other2693// text replace it, the caret kept where it can be.2694exp type TextField : Widget = struct {2695 exp text: String = String::empty(),2696 exp on_change: |=| (&var Ui, String) = (ui, text) {},2697 // Enter on one line2698 exp on_submit: |=| (&var Ui) = (ui) {},2699 exp placeholder: String = String::empty(),2700 exp accessible: String = String::empty(), // the placeholder when empty2701 // what is wrong with the text, none when empty: a border in the2702 // theme's danger color, and to screen readers the field is invalid,2703 // the message its description2704 exp error: String = String::empty(),2705 // what more a screen reader says of it, after the error: a hint2706 exp description: String = String::empty(),2707 exp required: bool = false, // a form needs it filled in, which screen readers say2708 exp multiline: bool = false,2709 // a password: shown as dots, one a character, the caret and the2710 // selection among them; never copied nor cut (pasting is); to screen2711 // readers a password field whose value is the dots, and the input2712 // method told so2713 exp secret: bool = false,2714 exp enabled: bool = true,2715 exp padding: Padding = Padding::symmetric(10.0, 7.0),2716 exp sizing: Sizing = Sizing {},2717 exp editing: Editing = Editing {},2718};27192720// A text field's own state, which its options never give.2721pub type Editing = struct {2722 pub caret: u64 = 0, // byte offsets on grapheme boundaries2723 pub anchor: u64 = 0, // the selection's other end, the caret's when none2724 pub preedit: Preedit = Preedit { .text = String::empty(), .cursor = 0 },2725 pub dragging: bool = false,2726 // when and where the last press was, for a second to take a word2727 pub pressed: Option<Duration> = ::None,2728 pub pressed_at: Point = Point { .x = 0.0, .y = 0.0 },2729 pub scroll: f32 = 0.0, // how far one line is scrolled left2730 pub shift: f32 = 0.0, // how far one short line right to left is moved to the right2731 pub inset: f32 = 0.0, // where the text's room starts from the left: its padding at the start2732 pub hint_at: f32 = 0.0, // how far one line's placeholder is moved to the right, right to left2733 pub laid: Option<text::Layout> = ::None, // the text with the composition in it2734 pub hint: Option<text::Layout> = ::None, // the placeholder2735 pub map: Option<*TextMap> = ::None, // what a screen reader reads, while one does2736 pub line: f32 = 0.0, // one line's height2737 pub width: f32 = 0.0, // the room the text has2738};27392740exp fn TextField::of(text: String, on_change: |=| (&var Ui, String)) -> TextField => TextField {2741 .text = move text,2742 .on_change = move on_change2743};27442745// Children one under the other.2746exp type Column : Widget = struct {2747 exp children: &[Element] = &[],2748 exp gap: f32 = 0.0,2749 exp padding: Padding = Padding {},2750 exp align: Alignment = Alignment::Start,2751 exp justify: Justify = Justify::Start,2752 exp background: Ink = Ink::None,2753 exp border: Ink = Ink::None,2754 exp radius: f32 = 0.0,2755 // keeps its paint and its children within its rounded rectangle2756 exp clip_radii: Option<Radii> = ::None,2757 exp sizing: Sizing = Sizing {},2758 // a context menu's: the right button, the Menu key, Shift+F10, or2759 // Control and a click on macOS, at a point from the window's top left2760 exp on_context_menu: Option<|=| (&var Ui, Point)> = ::None,2761};27622763// Children side by side.2764exp type Row : Widget = struct {2765 exp children: &[Element] = &[],2766 exp gap: f32 = 0.0,2767 exp padding: Padding = Padding {},2768 exp align: Alignment = Alignment::Start,2769 exp justify: Justify = Justify::Start,2770 exp background: Ink = Ink::None,2771 exp border: Ink = Ink::None,2772 exp radius: f32 = 0.0,2773 // keeps its paint and its children within its rounded rectangle2774 exp clip_radii: Option<Radii> = ::None,2775 exp sizing: Sizing = Sizing {},2776 exp on_context_menu: Option<|=| (&var Ui, Point)> = ::None,2777};27782779// Children over each other, the later ones on top.2780exp type Stack : Widget = struct {2781 exp children: &[Element] = &[],2782 exp padding: Padding = Padding {},2783 exp align: Alignment = Alignment::Start,2784 exp background: Ink = Ink::None,2785 exp border: Ink = Ink::None,2786 exp radius: f32 = 0.0,2787 // keeps its paint and its children within its rounded rectangle2788 exp clip_radii: Option<Radii> = ::None,2789 exp sizing: Sizing = Sizing {},2790 exp on_context_menu: Option<|=| (&var Ui, Point)> = ::None,2791};27922793// Children in rows that wrap at the width: chips, tags, thumbnails.2794exp type Wrap : Widget = struct {2795 exp children: &[Element] = &[],2796 exp gap: f32 = 0.0, // between children on a line2797 exp line_gap: f32 = 0.0, // between lines2798 exp align: Alignment = Alignment::Start, // within a line's height2799 exp padding: Padding = Padding {},2800 exp background: Ink = Ink::None,2801 exp border: Ink = Ink::None,2802 exp radius: f32 = 0.0,2803 // keeps its paint and its children within its rounded rectangle2804 exp clip_radii: Option<Radii> = ::None,2805 exp sizing: Sizing = Sizing {},2806};28072808// A column's width: `Fixed` logical pixels, the widest of its children2809// (`Content`), or a share of what is left (`Fraction`).2810exp type Track = enum {2811 Fixed: f32,2812 Content,2813 Fraction: f32,2814};28152816// Children in cells, row after row, as many to a row as there are2817// columns; each row as tall as its tallest child.2818exp type Grid : Widget = struct {2819 exp children: &[Element] = &[],2820 exp columns: Vector<Track> = Vector<Track>::empty(),2821 exp column_gap: f32 = 0.0,2822 exp row_gap: f32 = 0.0,2823 exp align: Alignment = Alignment::Start, // within a cell2824 exp padding: Padding = Padding {},2825 exp background: Ink = Ink::None,2826 exp border: Ink = Ink::None,2827 exp radius: f32 = 0.0,2828 // keeps its paint and its children within its rounded rectangle2829 exp clip_radii: Option<Radii> = ::None,2830 exp sizing: Sizing = Sizing {},2831};28322833// Its one child, scrolled within its bounds by the wheel, a touchpad, or2834// dragging the bar that shows while the child does not fit.2835exp type Scroll : Widget = struct {2836 exp children: &[Element] = &[],2837 exp horizontal: bool = false, // scrolled sideways instead2838 exp sizing: Sizing = Sizing {},2839 pub offset: f32 = 0.0,2840 pub content: f32 = 0.0, // the child's length along the axis2841 exp length: f32 = 0.0, // the scroll's own2842 pub grab: Option<f32> = ::None, // where the bar was grabbed, while dragged2843};28442845// A picture the Ui keeps, made from pixels with `ui.image`.2846exp type ImageId = struct {2847 exp index: u32,2848 exp generation: u32, // an id of an image freed names none2849};28502851// How a picture fills an image element of another shape.2852exp type Fit = enum {2853 Contain, // all of it, centered2854 Cover, // all of the element, clipped2855 Fill, // stretched2856};28572858// A picture: its pixels' size in logical pixels unless sized.2859exp type Image : Widget = struct {2860 exp image: ImageId,2861 exp accessible: String = String::empty(), // none: a screen reader passes over it2862 exp fit: Fit = Fit::Contain,2863 // drawn the other way round in an element read right to left: a2864 // picture that points (an arrow, a reply), not a photo or a logo2865 exp mirrors: bool = false,2866 exp sizing: Sizing = Sizing {},2867 pub natural: Extent = Extent { .width = 0.0, .height = 0.0 },2868};28692870// A list's rows: how many, and an estimate of a row's height, which2871// rows not yet shown stand at; `fixed` rows are all that height.2872exp type ListOptions = struct {2873 exp estimate: f32 = 32.0,2874 exp fixed: bool = false,2875 exp gap: f32 = 0.0,2876 exp sizing: Sizing = Sizing {},2877};28782879// The element `show` and `each` hold their views in, laid out as part of2880// its parent.2881exp type Group : Widget = struct {};28822883// Room taking what its row or column leaves, pushing what follows it to2884// the far end.2885exp type Spacer : Widget = struct {2886 exp sizing: Sizing = Sizing { .grow = 1.0 },2887};28882889exp fn spacer(self ui: &var Ui) -> Element => ui.add(Spacer {});28902891/* --- Running --- */28922893// Opens a window showing the view the function makes, and runs until2894// the window closes; gives the exit status for `main`.2895exp fn app(config: &WindowConfig, view: |=| (&var Ui) -> Element) -> i32 {2896 return run_app(&config, move view);2897}28982899// A Ui in an engine's own loop (F15.md): drawn over the engine's frame2900// on the engine's device, its input taken from the engine's window,2901// which it gives the cursor, the input method's area and the clipboard.2902// It owns no window, device, surface or loop:2903//2904// ```text2905// var hud = Hud::create(&var device, surface.format, &window, view);2906// // each event, before the game's own handling2907// if (hud.event(&var window, &event)) {2908// return; // the HUD took it2909// }2910// // each frame, after the game's drawing into the frame2911// hud.draw(&var device, &var encoder, frame, &var window);2912// ```2913//2914// It covers the whole window, following its size and scale. Its2915// background work (`ui.background`) runs at once on the loop's thread,2916// as a page's does, unless it is given workers (`with_workers`).2917exp type Hud = struct {2918 exp ui: Ui,2919 pub waking: bool = false, // whether the workers wake the window2920};29212922// A HUD showing the view the function makes over the window, drawn into2923// frames of the format, the engine's surface's, on its device.2924exp fn Hud::create(2925 device: &var Device,2926 format: TextureFormat,2927 window: &Window,2928 view: |=| (&var Ui) -> Element2929) -> Hud {2930 return open_hud(&var device, format, &window, move view);2931}29322933// Handles one of the window's events as an app's Ui would, and says2934// whether the HUD took it, the game then leaving it: a pointer's move,2935// button or scroll over an element taking input or while one is2936// pressed, a key or text while an element edits text. A Redraw draws2937// nothing (`draw` does), and closing the window is the game's to decide.2938exp fn event(self hud: &var Hud, window: &var Window, event: &Event) -> bool {2939 return hud.take_event(&var window, &event);2940}29412942// Brings the HUD to a frame and records its drawing into the encoder:2943// what changed redrawn into the texture it keeps, which is then blended2944// over the frame, premultiplied, after what the frame holds. The window2945// is given the cursor, the input method's area and the clipboard, and a2946// frame is asked for while something moves.2947exp fn draw(2948 self hud: &var Hud,2949 device: &var Device,2950 encoder: &var Encoder,2951 frame: Texture,2952 window: &var Window2953) {2954 hud.draw_over(&var device, &var encoder, frame, &var window);2955}29562957// Runs the HUD's background work from now on on the workers, which wake2958// the window as each job finishes; on the web, where a program has no2959// tasks, it still runs at once. The workers come from `Workers::run`2960// around the engine's loop:2961//2962// ```text2963// fn main() -> i32 {2964// return Workers::run(&|&| (workers: &Workers) -> i32 {2965// const game = Game { .workers = &workers, ... };2966// return run(&config, move game, on_event);2967// });2968// }2969// // once the HUD is made2970// hud.with_workers(&game.workers);2971// ```2972exp fn with_workers(self hud: &var Hud, workers: &Workers) {2973 if (target() != "web-wasm32") {2974 hud.ui.workers = ::Some(&workers);2975 }2976}29772978// The texture the HUD keeps its drawing in, for an engine placing it2979// itself; None before its first frame.2980exp fn texture(self hud: &Hud) -> Option<Texture> {2981 if (hud.ui.scene is ::Some |&scene|) {2982 return scene.canvas.texture();2983 }2984 return ::None;2985}29862987// How `replay` runs an app: at the scale, its wall clock at the moment2988// when the script's time is 0 and going on with the script's time.2989exp type ReplayConfig = struct {2990 exp scale: f32 = 1.0,2991 exp wall: i64 = 0, // nanoseconds since 1970 UTC2992 // the Redraws drawn on the CPU and presented; at the others the app2993 // lays out and paints its canvas but draws no pixels, most of a2994 // frame's time2995 exp drawn: Drawn = Drawn::All,2996 // the system's preferred languages, most wanted first, which the app's2997 // language is chosen from; none chooses the app's first2998 exp languages: Vector<String> = Vector<String>::empty(),2999};30003001// Which Redraws a replay draws.3002exp type Drawn = enum {3003 All,3004 Last, // those at the last Redraw's time among the events: the app at rest3005 At: Vector<Duration>, // those at these times3006};30073008// What a replay gives: the frames presented and what the app told the3009// window and screen readers.3010exp type Replayed = struct {3011 exp frames: Vector<Frame>,3012 // the accessibility tree as the app left it, sent once an3013 // Event::AccessRequested came among the events3014 exp access: AccessTree,3015 exp announcements: Vector<Announcement>, // what screen readers were given to say3016 exp history: Vector<HistoryEntry>, // each entry the app put the page's history at3017 exp toasts: Vector<String>, // each toast's text as it showed3018 // the language the app told the window, and whether it reads right to3019 // left3020 exp language: String,3021 exp right_to_left: bool,3022};30233024// Runs the app as `app` does, in a headless window drawn on the CPU,3025// over the events, for tests.3026exp fn replay(3027 config: &WindowConfig,3028 replay: ReplayConfig,3029 view: |=| (&var Ui) -> Element,3030 events: &[Event]3031) -> Replayed {3032 return replay_app(&config, move replay, move view, &events);3033}30343035// What the app's worker tasks share with the loop: the work queued, the3036// functions finished work gives, the window's waker, set once the window3037// opens, and what a package serves beside them, set by the loop before it3038// starts it, and its start.3039exp type Workers : Shared = struct {3040 exp jobs: Channel<|=| (&Workers) -> |=| (&var Ui)>,3041 exp done: Channel<|=| (&var Ui)>,3042 exp waker: Mutex<Waker>,3043 exp service: Option<*Service> = ::None,3044 exp starting: Channel<bool>,3045};30463047// What a package serves on a task of its own beside the app's workers,3048// sharing its state with the loop: pkg::alloy::ui_app's requests, on3049// their own tasks so that a slow download never holds a worker.3050exp interface Service {3051 // Serves until the app ends, once started.3052 fn serve(self: &, workers: &Workers);3053 // The app is ending: what `serve` waits on ends.3054 fn end(self: &);3055}30563057// Runs the body with an app's worker tasks beside it (four, and one3058// for a service), for a HUD in the engine's own loop (`with_workers`),3059// and gives what the body gives once the workers end: those running3060// work with it, a service with what it serves.3061exp fn Workers::run<R>(body: &|&| (&Workers) -> R) -> R {3062 return run_workers(&body);3063}