1// The app: a window, a device and its surface, a canvas, and the loop2// turning the window's events into the Ui's input and its changes into3// frames; worker tasks running the Ui's background work, and a task for4// what a package serves beside them (pkg::alloy::ui_app's requests),5// which wake the loop when done.67import std::io;8import std::string;9import std::vector;10import std::option;11import std::map;12import std::sync;13import std::process;14import std::time;15import std::languages as system;16import pkg::alloy::window;17import pkg::alloy::window::headless;18import pkg::alloy::gpu;19import pkg::alloy::draw;2021import ui;22import store;23import tree;24import layout;25import painting;26import events;27import timers;28import views;29import motion;30import languages;31import extensions;3233exp type App = struct {34 exp ui: Ui,35 pub view: |=| (&var Ui) -> Element,36 pub built: bool,37 pub backend: Backend,38 pub workers: Option<&Workers>,39 // a replay's wall clock when its script's time is 0; None reads the40 // system's41 exp wall: Option<i64>,42 // the times of the Redraws a replay draws; None draws every one43 pub drawn_at: Option<Vector<Duration>>,44};4546exp fn App::create(47 view: |=| (&var Ui) -> Element,48 backend: Backend,49 workers: Option<&Workers>50) -> App {51 var app = App {52 .ui = Ui::create(),53 .view = move view,54 .built = false,55 .backend = backend,56 .workers = workers,57 .wall = ::None,58 .drawn_at = ::None59 };60 app.ui.workers = workers;61 return move app;62}6364// The worker tasks an app runs, beside the one waiting for a service to65// start.66const WORKERS: u64 = 4;6768pub fn run_app(config: &WindowConfig, view: |=| (&var Ui) -> Element) -> i32 {69 // a page's loop goes on after `run` returns, and its program has no70 // tasks: the work runs at once71 if (target() == "web-wasm32") {72 var app = App::create(move view, Backend::Automatic, ::None);73 app.ui.choose_language(&config.languages, &system::preferred_languages().view());74 return run(&config, move app, on_app_event);75 } else {76 // in a branch of its own, so that a page's build leaves the tasks out77 return run_workers(&|&| (workers: &Workers) -> i32 {78 var app = App::create(copy view, Backend::Automatic, ::Some(&workers));79 app.ui.choose_language(&config.languages, &system::preferred_languages().view());80 return run(&config, move app, on_app_event);81 });82 }83}8485// Runs the body with worker tasks beside it, ending them once it86// returns: the workers with the work they are doing, a service with what87// it serves. On the web, where a program has no tasks, none run and the88// body is given workers to leave unused.89pub fn run_workers<R>(body: &|&| (&Workers) -> R) -> R {90 const workers = Workers {91 .jobs = Channel<|=| (&Workers) -> |=| (&var Ui)>::empty(),92 .done = Channel<|=| (&var Ui)>::empty(),93 .waker = Mutex<Waker>::from(Waker::None),94 .starting = Channel<bool>::empty()95 };96 if (target() == "web-wasm32") {97 return body(&workers);98 } else {99 // in a branch of its own, so that a page's build leaves the tasks out100 var result: Option<R> = ::None;101 scope {102 for ([..WORKERS]) {103 spawn {104 workers.serve();105 }106 }107 spawn {108 workers.start_service();109 }110 result = ::Some(body(&workers));111 workers.jobs.close();112 workers.starting.close();113 if (workers.service is ::Some |&service|) {114 service.end();115 }116 }117 if (result is ::Some |move r|) {118 return move r;119 }120 panic "pkg::alloy::ui: the workers' body gave nothing";121 }122}123124// What the workers finished, taken to run at the next update, after the125// loop was woken.126pub fn take_done(self ui: &var Ui) {127 if (ui.workers is ::Some |&workers|) {128 while (workers.done.try_receive() is ::Some |move done|) {129 ui.finished.push(move done);130 }131 }132}133134// The work `background` queued, given to the workers.135pub fn send_jobs(self ui: &var Ui) {136 if (ui.workers is ::Some |&workers|) {137 for (ui.jobs.items()) |&var work| {138 workers.jobs.send(move work);139 }140 ui.jobs.clear();141 }142}143144// Runs work until the app ends, waking the loop as each is done.145fn serve(self workers: &Workers) {146 while (workers.jobs.receive() is ::Some |move work|) {147 workers.finish(work(&workers));148 }149}150151// Waits for the service to start, then serves it until the app ends.152fn start_service(self workers: &Workers) {153 if (workers.starting.receive() is ::Some && workers.service is ::Some |&service|) {154 service.serve(&workers);155 }156}157158// Gives the loop what finished work gives, and wakes it.159exp fn finish(self workers: &Workers, done: |=| (&var Ui)) {160 workers.done.send(move done);161 var waker = workers.waker.lock();162 waker.value().wake();163 waker.dispose();164}165166exp fn replay_app(167 config: &WindowConfig,168 options: ReplayConfig,169 view: |=| (&var Ui) -> Element,170 events: &[Event]171) -> Replayed {172 var app = App::create(move view, Backend::Cpu, ::None);173 app.wall = ::Some(options.wall);174 app.drawn_at = match (options.drawn) {175 ::All ::None;176 ::Last ::Some(Vector<Duration>::from(&[last_redraw(&events)]));177 ::At |×| ::Some(copy times);178 };179 app.ui.replaying = true;180 app.ui.choose_language(&config.languages, &options.languages.view());181 var replay = run_headless(&config, options.scale, move app, on_app_event, &events);182 // the replay's end is the app's183 replay.state.ui.extensions_closing();184 var replayed = Replayed {185 .frames = move replay.frames,186 .access = move replay.access,187 .announcements = move replay.announcements,188 .history = move replay.history,189 .toasts = Vector<String>::empty(),190 .language = move replay.language,191 .right_to_left = replay.right_to_left192 };193 replay.state.ui.extensions_replayed(&var replayed);194 return move replayed;195}196197// The time of the last Redraw among the events.198fn last_redraw(events: &[Event]) -> Duration {199 var last = Duration::from_nanoseconds(0);200 for (events) |&event| {201 if (event is ::Redraw |t| && t.nanoseconds > last.nanoseconds) {202 last = t;203 }204 }205 return last;206}207208// Whether a Redraw at the time is drawn.209fn draws(self app: &App, time: Duration) -> bool {210 if (app.drawn_at is ::Some |×|) {211 for (times.view()) |&t| {212 if (t.nanoseconds == time.nanoseconds) {213 return true;214 }215 }216 return false;217 }218 return true;219}220221exp fn on_app_event(app: &var App, window: &var Window, event: &Event) {222 app.handle(&var window, &event);223 if (app.ui.quitting) {224 app.ui.close_window(&var window);225 }226 // the work queued meanwhile to the workers227 app.ui.send_jobs();228}229230fn handle(self app: &var App, window: &var Window, event: &Event) {231 // the clocks as the event came, which the view first made reads too232 const time = if (event is ::Redraw |t|) t else window.now();233 app.ui.time = time;234 app.ui.wall = match (app.wall) {235 ::Some |start| start + time.nanoseconds to i64;236 ::None wall_clock();237 };238 if (!app.built) {239 app.built = true;240 if (app.workers is ::Some |&workers|) {241 var waker = workers.waker.lock();242 waker.value() = window.waker();243 waker.dispose();244 }245 app.ui.scale = window.scale();246 // what the page's callbacks wake the loop by247 if (target() == "web-wasm32") {248 app.ui.waker = window.waker();249 }250 app.ui.start_path = String::from(&window.start_path());251 app.ui.app = String::from(&window.app_name());252 const root = app.ui.untracked(&app.view);253 const size = window.size();254 app.ui.mount(root, size.width to f32 / app.ui.scale, size.height to f32 / app.ui.scale);255 }256 const drawing = app.draws(time);257 const ui = &var app.ui;258 ui.begin_event(&window, &event);259 match (event) {260 ::Redraw {261 if (ui.scene is ::None) {262 if (open_scene(&window, app.backend, &ui.theme) is ::Some |move scene|) {263 ui.use_scene(move scene);264 } else {265 window.close();266 return;267 }268 }269 ui.frame();270 if (drawing) {271 ui.render(&var window);272 }273 ui.handled();274 ui.show_in(&var window);275 return;276 }277 ::CloseRequested {278 if (ui.may_close()) {279 ui.close_window(&var window);280 return;281 }282 }283 ::Woken {284 ui.take_done();285 }286 else {287 ui.input_event(&var window, &event);288 }289 }290 ui.end_event(&var window);291}292293// What comes before any event's handling, an app's or a HUD's: the294// system's wish for less motion, and the timers whose time came, as the295// event did.296pub fn begin_event(self ui: &var Ui, window: &Window, event: &Event) {297 ui.reduced_system = window.reduced_motion();298 ui.run_timers();299 ui.extensions_event(&event);300}301302// What follows it: what changed laid out, a frame asked for when303// something is to paint, and the window given what the Ui asks of it.304pub fn end_event(self ui: &var Ui, window: &var Window) {305 ui.update_all();306 if (ui.paint_pending) {307 window.request_redraw();308 }309 ui.handled();310 ui.show_in(&var window);311}312313// The window's input, its size and scale, its focus and what its314// clipboard and fonts give, as an app and a HUD take them.315pub fn input_event(self ui: &var Ui, window: &var Window, event: &Event) {316 match (event) {317 ::Resized, ::Scaled {318 ui.scale = window.scale();319 const size = window.size();320 ui.viewport = Extent {321 .width = size.width to f32 / ui.scale,322 .height = size.height to f32 / ui.scale323 };324 if (ui.root is ::Some |root|) {325 ui.node_var(root).moved = true;326 ui.mark_sync(root);327 ui.mark_layout(root);328 }329 for ([..ui.layers.length()]) |k| {330 const host = ui.layers.get(k).host.index;331 ui.node_var(host).moved = true;332 ui.mark_sync(host);333 ui.mark_layout(host);334 }335 ui.paint_pending = true;336 if (ui.scene is ::Some |&var scene|) {337 scene.canvas.damage_all();338 }339 }340 ::PointerMoved |p| {341 ui.pointer_moved(logical(p, ui.scale));342 }343 ::PointerLeft {344 ui.pointer_left();345 }346 ::Button |&b| {347 ui.modifiers = b.modifiers;348 const at = logical(b.position, ui.scale);349 // Control and a click is the right button's on macOS350 const mac = target() == "macos-arm64" || target() == "macos-x86_64";351 const context = b.button is ::Right352 || (mac && b.button is ::Left && b.modifiers.control);353 if (context) {354 if (b.pressed) {355 ui.context_press(at);356 } else {357 ui.context_release(at);358 }359 } else if (b.button is ::Left) {360 ui.pointer_button(b.pressed, at);361 }362 }363 ::Key |&k| {364 ui.key_event(&k);365 }366 ::Scroll |&scroll| {367 ui.modifiers = scroll.modifiers;368 // a wheel's notches as lines of 40 logical pixels369 const by: f32 = if (scroll.precise) 1.0 / ui.scale else 40.0;370 var delta = Point { .x = scroll.delta.x * by, .y = scroll.delta.y * by };371 if (scroll.modifiers.shift && delta.x == 0.0) {372 delta = Point { .x = delta.y, .y = 0.0 };373 }374 if (ui.pointer is ::Some |at|) {375 ui.scroll_event(delta, at);376 }377 }378 ::Text |&t| {379 ui.text_event(&t);380 }381 ::Preedit |&p| {382 ui.preedit_event(&p);383 }384 ::Focused |focused| {385 if (!focused && ui.focused is ::Some) {386 // the ring shows again only when the keyboard moves the387 // focus388 ui.focus_node(ui.focused, false);389 }390 }391 ::Clipboard |&text| {392 ui.paste_event(&text);393 }394 ::FontsArrived {395 // text laid out in boxes may now have a face396 ui.fonts_changed += 1;397 ui.invalidate_all();398 }399 else {}400 }401}402403// What follows an event's handling: the store written back.404pub fn handled(self ui: &var Ui) {405 ui.extensions_handled();406}407408// Whether `on_close_requested`, when set, lets the window close.409fn may_close(self ui: &var Ui) -> bool {410 var asking = move ui.close_asks;411 ui.close_asks = ::None;412 var closes = true;413 if (asking is ::Some |&ask|) {414 closes = ask(&var ui);415 }416 ui.close_asks = move asking;417 return closes;418}419420// Closes the window, which ends the app, its requests cancelled.421pub fn close_window(self ui: &var Ui, window: &var Window) {422 ui.extensions_closing();423 window.close();424}425426// Runs what finished work gave, as handlers.427pub fn run_finished(self ui: &var Ui) {428 var finished = move ui.finished;429 ui.finished = Vector<|=| (&var Ui)>::empty();430 for (finished.view()) |&done| {431 done(&var ui);432 }433}434435// Gives the window the cursor, the input method's area, the time the436// next timer waits for, what the extensions give it (where the437// navigators are in the page's history, file dialogs, the accessibility438// tree and what screen readers say) and what goes to the clipboard or is439// asked of it.440pub fn show_in(self ui: &var Ui, window: &var Window) {441 window.wake_at(ui.next_due());442 window.set_language(&ui.spoken.view(), ui.flow is ::RightToLeft);443 // while something moves, one frame after another444 if (ui.animating()) {445 window.request_redraw();446 }447 ui.extensions_show_in(&var window);448 // said, by pkg::alloy::ui_access when installed449 ui.announced.clear();450 var out = move ui.clipboard_out;451 ui.clipboard_out = ::None;452 if (out is ::Some |move text|) {453 window.set_clipboard(move text);454 }455 if (ui.paste_wanted) {456 ui.paste_wanted = false;457 window.request_clipboard();458 }459 window.set_cursor(ui.cursor);460 if (ui.input_area() is ::Some |r|) {461 const s = ui.scale;462 window.set_text_input(::Some(Area {463 .x = r.x * s,464 .y = r.y * s,465 .width = r.width * s,466 .height = r.height * s467 }));468 window.set_secret_input(ui.input_secret());469 } else {470 window.set_text_input(::None);471 window.set_secret_input(false);472 }473}474475pub fn logical(p: Point, scale: f32) -> Point => Point { .x = p.x / scale, .y = p.y / scale };476477fn open_scene(window: &Window, backend: Backend, theme: &Theme) -> Option<Scene> {478 var device = if (Device::open(backend) is ::Ok |move d|) move d else {479 print_error(&"pkg::alloy::ui: no device to draw with\n");480 return ::None;481 };482 const surface = match (device.surface(&window)) {483 ::Ok |s| s;484 ::Error |&error| {485 print_error(&f"pkg::alloy::ui: no surface: {error}\n".view());486 return ::None;487 }488 };489 var canvas = Canvas::create(&var device, surface.format);490 canvas.set_background(theme.background);491 return ::Some(Scene {492 .own = ::Some(move device),493 .surface = ::Some(surface),494 .canvas = move canvas,495 .target = ::None496 });497}498499// Draws with the scene from now on, its canvas's fonts laying out text500// again.501pub fn use_scene(self ui: &var Ui, scene: Scene) {502 ui.scene = ::Some(move scene);503 if (ui.scene is ::Some |&var made|) {504 for (ui.font_installs.view()) |install| {505 install(&var made.canvas.fonts());506 }507 ui.marks.check = ::Some(check_mark(&var made.canvas, &var made.device()));508 }509 ui.marks.chevron = ::None; // made on this canvas when wanted510 ui.own_fonts = ::None;511 ui.fonts_changed += 1;512 ui.invalidate_all();513}514515// Draws a frame when the canvas changed.516fn render(self ui: &var Ui, window: &var Window) {517 const scene = if (ui.scene is ::Some |&var s|) &var s else {518 return;519 };520 if (!scene.canvas.damaged()) {521 return;522 }523 const surface = if (scene.surface is ::Some |s|) s else {524 return;525 };526 const device = &var scene.device();527 if (device.acquire(surface, window.size()) is ::Some |frame|) {528 var encoder = Encoder::empty();529 scene.canvas.render(&var device, &var encoder, frame);530 device.submit(move encoder);531 device.present(surface, &var window);532 }533}534535pub fn draw_offscreen_frame(self ui: &var Ui, width: u32, height: u32) {536 if (ui.scene is ::None) {537 var device = if (Device::open(Backend::Cpu) is ::Ok |move d|) move d else {538 panic "pkg::alloy::ui: the CPU device does not open";539 };540 var canvas = Canvas::create(&var device, TextureFormat::Rgba8Unorm);541 canvas.set_background(ui.theme.background);542 const target = device.texture(&TextureDescriptor {543 .width = width,544 .height = height,545 .format = TextureFormat::Rgba8Unorm,546 .usage = TEXTURE_RENDER_TARGET | TEXTURE_COPY_SOURCE | TEXTURE_COPY_DESTINATION547 });548 ui.use_scene(Scene {549 .own = ::Some(move device),550 .surface = ::None,551 .canvas = move canvas,552 .target = ::Some(target)553 });554 }555 ui.frame();556 const scene = if (ui.scene is ::Some |&var s|) &var s else {557 return;558 };559 if (scene.target is ::Some |target|) {560 var encoder = Encoder::empty();561 scene.canvas.render(&var scene.device(), &var encoder, target);562 scene.device().submit(move encoder);563 }564}