Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

H12: <Screen app> drawn on a Blitz document of its own

shinyobjectz2262e1cc7d5e
diff --git a/Cargo.lock b/Cargo.lock
index 9d2ec048..17d37eb8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14989,6 +14989,24 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-runtime-appscreen"
+version = "0.1.0"
+dependencies = [
+ "bevy",
+ "blitz-traits",
+ "keyboard-types",
+ "raea-io-home",
+ "raea-page",
+ "raea-runtime-bundle",
+ "raea-runtime-dom",
+ "raea-runtime-js",
+ "raea-runtime-jsengine",
+ "raea-sys-fonts",
+ "raea-sys-page",
+ "wgpu",
+]
+
[[package]]
name = "raea-runtime-bake"
version = "0.1.0"
@@ -15284,6 +15302,7 @@ dependencies = [
"raea-io-net",
"raea-page",
"raea-render",
+ "raea-runtime-appscreen",
"raea-runtime-input",
"raea-runtime-react",
"raea-runtime-twins",
diff --git a/Cargo.toml b/Cargo.toml
index 9b35f5a1..d6e82584 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -168,6 +168,7 @@ members = [
"runtime/export",
"runtime/live",
"runtime/page",
+ "runtime/appscreen",
"runtime/sound",
"runtime/look",
"runtime/scene",
diff --git a/runtime/appscreen/Cargo.toml b/runtime/appscreen/Cargo.toml
new file mode 100644
index 00000000..55bf87e1
--- /dev/null
+++ b/runtime/appscreen/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "raea-runtime-appscreen"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "App screens (<Screen app>): a module on @raea/ui's react-dom in a Blitz document of its own at the screen's size, stepped once a frame on the frame's clock with the input routed to it"
+
+[dependencies]
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "bevy_render", "bevy_window"] }
+blitz-traits = "=0.3.0-beta.4"
+keyboard-types = "0.8"
+wgpu = "=30.0.1"
+raea-page = { path = "../../engine/page" }
+raea-runtime-dom = { path = "../dom" }
+raea-runtime-js = { path = "../js" }
+raea-runtime-jsengine = { path = "../jsengine" }
+raea-runtime-bundle = { path = "../bundle" }
+raea-sys-page = { path = "../../systems/page" }
+raea-sys-fonts = { path = "../../systems/fonts" }
+raea-io-home = { path = "../../io/home" }
diff --git a/runtime/appscreen/src/lib.rs b/runtime/appscreen/src/lib.rs
new file mode 100644
index 00000000..35a49d1a
--- /dev/null
+++ b/runtime/appscreen/src/lib.rs
@@ -0,0 +1,248 @@
+//! App screens (`<Screen app="kit.tsx">`, docs/blitz-bevy.feature H12): each one's module, its default export a React
+//! component given `{width, height}`, runs on @raea/ui's react-dom in a Blitz document of its own at the screen's
+//! size, on a page App of its own (raea-page's BlitzPage), so it is stepped exactly once a frame however often the
+//! composition's page is synced or drawn. A step sends the input routed to it as Blitz's pointer, wheel and key
+//! events, then runs one update that runs its JS (its frame, timers and commits) with the JS clock held at the
+//! frame's time (raea-runtime-jsengine `at_clock`), and paints it. A render and its play step it on the same frames
+//! with the same input, so the screen shows the same picture in both. Its picture goes where a nested <Screen>'s
+//! goes: its texture on the shared device in play (Engine::copy_screen), read back in a render.
+//!
+//! An app's own timers and performance.now follow the frames; its Date doesn't (a module reading the wall clock draws
+//! another time in a render).
+
+use std::path::{Path, PathBuf};
+
+use bevy::input::ButtonState;
+use bevy::input::mouse::{MouseButton, MouseButtonInput, MouseScrollUnit, MouseWheel};
+use bevy::input::touch::TouchPhase;
+use bevy::prelude::*;
+use bevy::render::settings::RenderCreation;
+use bevy::window::{CursorLeft, CursorMoved, WindowEvent};
+use blitz_traits::events::{BlitzKeyEvent, KeyState, UiEvent};
+use keyboard_types::{Code, Key, Location, Modifiers};
+use raea_page::motion::BlitzPage;
+use raea_runtime_dom::host::{self, WindowInput};
+
+type R<T> = Result<T, String>;
+
+/// What a prebuilt app screen's script is called beside its module (`kit.tsx` -> `kit.tsx.surface.js`): an exported
+/// game's, which bundles nothing (apps/game gather.rs). Its CSS is beside it as [`BUNDLED_CSS`].
+pub const BUNDLED: &str = ".surface.js";
+pub const BUNDLED_CSS: &str = ".surface.css";
+
+/// One frame's input for an app screen: the pointer on its picture (its px) and whether it's down, the keys held
+/// for it (while it has the focus), and the wheel's turns over it (CSS px, down positive, as the DOM's deltaY).
+#[derive(Default, Clone, Debug, PartialEq)]
+pub struct Input {
+ pub pointer: Option<(f64, f64, bool)>,
+ pub keys: Vec<String>,
+ pub wheel: Vec<f64>,
+}
+
+/// Set for the one update a step runs the page's JS in (the draw's later updates, while faces and images load, only
+/// paint).
+#[derive(Resource, Default)]
+struct StepNow(bool);
+
+fn step_once(world: &mut World) {
+ if std::mem::take(&mut world.resource_mut::<StepNow>().0) {
+ host::step(world);
+ }
+}
+
+/// An app screen's document, open.
+pub struct AppScreen {
+ page: BlitzPage,
+ root: Entity,
+ /// the module, as the composition names it
+ pub module: String,
+ pub size: (u32, u32),
+ window: WindowInput,
+ was: Input,
+ stepped: Option<i64>,
+}
+
+/// Frame `f`'s time in ms at `fps`.
+fn ms_at(f: i64, fps: f64) -> f64 {
+ f as f64 * 1000.0 / fps.max(1.0)
+}
+
+impl AppScreen {
+ /// `module` (a path from `dir`, the composition's folder) opened `w` x `h` at frame `f` of `fps`: its script (see
+ /// [`code_of`]) mounted on a Blitz page on the device `render` makes (None: Bevy's own), in raea's bundled faces.
+ pub fn open(dir: &Path, module: &str, w: u32, h: u32, f: i64, fps: f64, render: Option<RenderCreation>) -> R<AppScreen> {
+ let (code, css) = code_of(&dir.join(module))?;
+ let fonts = raea_io_home::home().join("core/fonts");
+ let mut page = BlitzPage::new_on(w.max(1), h.max(1), Some(&fonts), render)?;
+ page.not_dumped();
+ let app = page.app();
+ app.init_resource::<StepNow>();
+ app.add_systems(PreUpdate, step_once.in_set(raea_sys_page::PageSystems::Step));
+ let world = app.world_mut();
+ world.init_resource::<raea_runtime_js::HostCalls>();
+ world.insert_resource(raea_runtime_js::UiFrame(f.max(0) as u64));
+ let root = raea_runtime_jsengine::at_clock(ms_at(f, fps), || host::mount(world, w.max(1), h.max(1), &code, &[], Some(raea_sys_fonts::context(&fonts))))?;
+ // as raea's page host mounts an app (engine/page/host page.rs)
+ host::add_style(world, root, "html, body { height: 100%; }");
+ if !css.trim().is_empty() {
+ host::add_style(world, root, &css);
+ }
+ page.show(root);
+ Ok(AppScreen { page, root, module: module.to_string(), size: (w, h), window: WindowInput::default(), was: Input::default(), stepped: None })
+ }
+
+ /// Stepped to frame `f` of `fps` with `input`: its events, then one update running its JS on the frame's clock, drawn.
+ /// Once a frame: stepped again at the same frame, nothing happens.
+ pub fn step(&mut self, f: i64, fps: f64, input: &Input) {
+ if self.stepped == Some(f) {
+ return;
+ }
+ self.stepped = Some(f);
+ let events = self.events(input);
+ self.was = input.clone();
+ let root = self.root;
+ let page = &mut self.page;
+ raea_runtime_jsengine::at_clock(ms_at(f, fps), || {
+ page.at_frame(f, fps);
+ let world = page.app().world_mut();
+ world.insert_resource(raea_runtime_js::UiFrame(f.max(0) as u64));
+ for (press, ev) in events {
+ // each press a click of its own (a double click needs presses closer than a frame apart)
+ if press {
+ host::set_clicks(world, root, 1);
+ }
+ host::input(world, root, ev);
+ }
+ world.resource_mut::<StepNow>().0 = true;
+ page.draw();
+ });
+ }
+
+ /// Its picture as last drawn: its texture on the page's device (sRGB-encoded premultiplied RGBA, as a nested
+ /// <Screen>'s).
+ pub fn texture(&self) -> Option<wgpu::Texture> {
+ self.page.texture().map(|t| (*t).clone())
+ }
+
+ /// Its picture as last drawn, read back: RGBA rows at its size.
+ pub fn rgba(&mut self) -> R<Vec<u8>> {
+ self.page.frame()
+ }
+
+ /// The events that take the document from the last step's input to `now`'s, as Blitz takes them, each marked
+ /// when it's a press: the pointer's move, press and release (a release, then a leave, when it goes off the
+ /// picture), the wheel, the keys let go and the keys pressed.
+ fn events(&mut self, now: &Input) -> Vec<(bool, UiEvent)> {
+ let window = Entity::PLACEHOLDER;
+ let was = self.was.clone();
+ let mut out = Vec::new();
+ let mut put = |w: &mut WindowInput, ev: WindowEvent, press: bool| {
+ if let Some(e) = w.event(&ev) {
+ out.push((press, e));
+ }
+ };
+ let button = |state| WindowEvent::MouseButtonInput(MouseButtonInput { button: MouseButton::Left, state, window });
+ let held = was.pointer.is_some_and(|p| p.2);
+ match now.pointer {
+ Some((x, y, down)) => {
+ if was.pointer.is_none_or(|(bx, by, _)| bx != x || by != y) {
+ put(&mut self.window, WindowEvent::CursorMoved(CursorMoved { window, position: Vec2::new(x as f32, y as f32), delta: None }), false);
+ }
+ if down && !held {
+ put(&mut self.window, button(ButtonState::Pressed), true);
+ }
+ if !down && held {
+ put(&mut self.window, button(ButtonState::Released), false);
+ }
+ }
+ None if was.pointer.is_some() => {
+ if held {
+ put(&mut self.window, button(ButtonState::Released), false);
+ }
+ put(&mut self.window, WindowEvent::CursorLeft(CursorLeft { window }), false);
+ }
+ None => {}
+ }
+ for dy in &now.wheel {
+ // Blitz's wheel is Bevy's way up (raea-runtime-dom gives the DOM -y)
+ put(&mut self.window, WindowEvent::MouseWheel(MouseWheel { unit: MouseScrollUnit::Pixel, x: 0.0, y: -(*dy as f32), window, phase: TouchPhase::Moved }), false);
+ }
+ let mods = mods_of(&now.keys);
+ for k in was.keys.iter().filter(|k| !now.keys.contains(k)) {
+ out.push((false, UiEvent::KeyUp(key_event(k, mods, false))));
+ }
+ for k in now.keys.iter().filter(|k| !was.keys.contains(k)) {
+ out.push((false, UiEvent::KeyDown(key_event(k, mods, true))));
+ }
+ out
+ }
+}
+
+/// The modifiers the held keys (by their DOM names) make.
+fn mods_of(keys: &[String]) -> Modifiers {
+ let mut m = Modifiers::empty();
+ for (name, bit) in [("Shift", Modifiers::SHIFT), ("Control", Modifiers::CONTROL), ("Alt", Modifiers::ALT), ("Meta", Modifiers::META)] {
+ if keys.iter().any(|k| k == name) {
+ m |= bit;
+ }
+ }
+ m
+}
+
+/// Key `name` (the DOM's: a character, or a named key like "Enter") pressed or let go: a character types itself
+/// unless Control or Meta is held.
+fn key_event(name: &str, modifiers: Modifiers, down: bool) -> BlitzKeyEvent {
+ let name = if name == "Space" { " " } else { name };
+ let key = name.parse::<Key>().unwrap_or_else(|_| Key::Character(name.into()));
+ let types = matches!(key, Key::Character(_)) && !modifiers.intersects(Modifiers::CONTROL | Modifiers::META);
+ BlitzKeyEvent {
+ key,
+ code: Code::Unidentified,
+ modifiers,
+ location: Location::Standard,
+ is_auto_repeating: false,
+ is_composing: false,
+ state: if down { KeyState::Pressed } else { KeyState::Released },
+ text: (types && down).then(|| blitz_traits::SmolStr::new(name)),
+ }
+}
+
+/// The module's script and CSS: its prebuilt bundle beside it (an exported game's, [`BUNDLED`]), or [`build`] now.
+pub fn code_of(file: &Path) -> R<(String, String)> {
+ let pre = PathBuf::from(format!("{}{BUNDLED}", file.display()));
+ if pre.is_file() {
+ let js = std::fs::read_to_string(&pre).map_err(|e| format!("{}: {e}", pre.display()))?;
+ let css = std::fs::read_to_string(format!("{}{BUNDLED_CSS}", file.display())).unwrap_or_default();
+ return Ok((js, css));
+ }
+ build(file)
+}
+
+/// `file` bundled as an app screen (raea-runtime-bundle-lib's app bundle, its default export given the screen's size):
+/// its script, and its CSS, what its modules import, then Tailwind's for the classes its folder uses, as `raea app`
+/// builds an app's (apps/targets web.rs).
+pub fn build(file: &Path) -> R<(String, String)> {
+ if !file.is_file() {
+ return Err(format!("{}: no such module", file.display()));
+ }
+ let (js, imported) = raea_runtime_bundle::inproc::app::bundle_screen(file, &raea_io_home::home())?;
+ let tw = raea_runtime_bundle::styles::tailwind(file.parent().unwrap_or(Path::new(".")))?;
+ Ok((js, format!("{imported}\n{tw}")))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn keys_type_characters_but_not_with_control() {
+ let a = key_event("a", Modifiers::empty(), true);
+ assert_eq!(a.text.as_deref(), Some("a"));
+ assert!(key_event("a", Modifiers::CONTROL, true).text.is_none());
+ assert!(key_event("a", Modifiers::empty(), false).text.is_none());
+ let enter = key_event("Enter", Modifiers::empty(), true);
+ assert!(matches!(enter.key, Key::Named(_)) && enter.text.is_none());
+ assert_eq!(key_event("Space", Modifiers::empty(), true).text.as_deref(), Some(" "));
+ assert_eq!(mods_of(&["Shift".into(), "a".into()]), Modifiers::SHIFT);
+ }
+}
diff --git a/runtime/page/Cargo.toml b/runtime/page/Cargo.toml
index 238e4542..7e4a2a9f 100644
--- a/runtime/page/Cargo.toml
+++ b/runtime/page/Cargo.toml
@@ -8,6 +8,7 @@ description = "A composition's page in Bevy: React's elements laid out and paint
[dependencies]
raea-runtime-view = { path = "../view" }
+raea-runtime-appscreen = { path = "../appscreen" }
raea-sys-frame = { path = "../../systems/frame" }
raea-io-assets = { path = "../../io/assets" }
raea-io-net = { path = "../../io/net" }
diff --git a/runtime/page/src/bevy_page.rs b/runtime/page/src/bevy_page.rs
index cbbacfdc..02acead8 100644
--- a/runtime/page/src/bevy_page.rs
+++ b/runtime/page/src/bevy_page.rs
@@ -98,11 +98,7 @@ impl BevyPage {
}
}
crate::screen::retire(&mut self.apps, &self.app_screens);
- for (name, _, _, app) in &self.app_screens {
- if self.apps.failed.insert(name.clone(), app.clone()).is_none() {
- eprintln!("raea: screen {name:?}: its app {app:?} isn't drawn yet: app screens move to raea-runtime-js roots of their own (ts-native P27)");
- }
- }
+ crate::screen::step_all(&mut self.apps, &self.app_screens, &self.dir);
self.page.place_videos(videos)
}
@@ -147,12 +143,26 @@ impl BevyPage {
/// The page and each <Screen>'s picture drawn and read back: the page's premultiplied RGBA, and each screen's name,
/// size and RGBA.
pub fn frame_all(&mut self) -> R<(Vec<u8>, Vec<(String, u32, u32, Vec<u8>)>)> {
- self.page.frame_all()
+ let (px, mut pics) = self.page.frame_all()?;
+ pics.extend(crate::screen::pictures(&mut self.apps)?);
+ Ok((px, pics))
}
- /// The page drawn at frame `f` of a composition at `fps`: its CSS animations and transitions where they are then.
+ /// The page drawn at frame `f` of a composition at `fps`: its CSS animations and transitions where they are then,
+ /// and its app screens stepped there.
pub fn at_frame(&mut self, f: i64, fps: f64) {
self.page.at_frame(f, fps);
+ self.set_app_frame(f, fps);
+ }
+
+ /// The frame the app screens step to at the next sync (live play, whose page keeps its own CSS clock).
+ pub fn set_app_frame(&mut self, f: i64, fps: f64) {
+ self.apps.frame = Some((f, fps));
+ }
+
+ /// What reached the app screens this frame, for the input log (runtime/page/src/screen.rs `logged`).
+ pub fn app_input(&self) -> Option<Value> {
+ crate::screen::logged(&self.apps)
}
/// The page drawn and read back: premultiplied RGBA rows, `w` x `h`.
@@ -276,9 +286,11 @@ impl BevyPage {
&mut self.apps
}
- /// Each <Screen>'s picture as last drawn, by name: its texture on the shared device.
+ /// Each <Screen>'s picture as last drawn, by name: its texture on the shared device (an app screen's too).
pub fn screen_textures(&self) -> Vec<(String, wgpu::Texture)> {
- self.page.sub_textures().into_iter().map(|(k, t, _, _)| (k, (*t).clone())).collect()
+ let mut all: Vec<_> = self.page.sub_textures().into_iter().map(|(k, t, _, _)| (k, (*t).clone())).collect();
+ all.extend(crate::screen::textures(&self.apps));
+ all
}
/// The page's picture as last drawn, on the shared device (`Rgba8UnormSrgb`, premultiplied).
diff --git a/runtime/page/src/screen.rs b/runtime/page/src/screen.rs
index d4e6a188..783ac7e1 100644
--- a/runtime/page/src/screen.rs
+++ b/runtime/page/src/screen.rs
@@ -5,20 +5,36 @@
//! (engine/render/src/engine/screen.rs). A render's screen equals its play's, and a game on a screen plays live with the
//! player's input (the nested game reads the same useInput).
//!
-//! An app screen (`<Screen app="chat.tsx">`) shows a page of its own instead: the module's component on @raea/ui's
-//! react-dom in a raea-runtime-js root of its own. In live play the pointer reaches it through the 3D (`route`: the camera's
-//! ray to the screen, Engine::screen_at): a press on an app screen gives it the keys, which the game then doesn't get,
-//! until a press anywhere else or Escape.
+//! An app screen (`<Screen app="chat.tsx">`, docs/blitz-bevy.feature H12) shows a page of its own instead: the module's
+//! component on @raea/ui's react-dom in a Blitz document of its own (raea-runtime-appscreen), stepped once a frame
+//! (`step_all`, from the page's sync) and drawn into its picture, which goes to the 3D as a nested screen's does. In
+//! live play the pointer reaches it through the 3D (`route`: the camera's ray to the screen, Engine::screen_at): a
+//! press on an app screen gives it the keys, which the game then doesn't get, until a press anywhere else or Escape.
+//! What reached the app screens each frame goes in the input log (`logged`), and a render of the log gives them the
+//! same (`APP_LOG`), so the render draws what was played.
-/// What an app's prebuilt bundle is called beside its module (`chat.tsx` -> `chat.tsx.surface.js`): an exported game's
-/// (game.rs gather).
-pub const BUNDLED: &str = ".surface.js";
+use std::collections::{BTreeMap, HashMap};
-/// The page's app screens: the input live play routed to them for their next step.
+use raea_runtime_appscreen::{AppScreen, Input};
+use serde_json::{Value, json};
+
+/// What an app's prebuilt bundle is called beside its module (`chat.tsx` -> `chat.tsx.surface.js`, its CSS
+/// `chat.tsx.surface.css`): an exported game's (game.rs gather).
+pub use raea_runtime_appscreen::{BUNDLED, BUNDLED_CSS, build as build_app};
+
+/// A render's input log, by frame: what reached the app screens in the play it logged (its `apps`), given them again
+/// in place of live play's routing. Set by `raea render --input`; None in play.
+pub static APP_LOG: std::sync::Mutex<Option<BTreeMap<i64, Value>>> = std::sync::Mutex::new(None);
+
+/// The page's app screens: their documents, and the input live play routed to them for their next step.
#[derive(Default)]
pub(crate) struct Apps {
+ /// each app screen's document, by name
+ docs: HashMap<String, AppScreen>,
+ /// the frame and fps the next step is at (BevyPage::at_frame, set_app_frame)
+ pub(crate) frame: Option<(i64, f64)>,
/// screens whose app didn't open, with the module (said once)
- pub(crate) failed: std::collections::HashMap<String, String>,
+ pub(crate) failed: HashMap<String, String>,
/// the app screen the keys go to (the one last pressed on), and the keys held for it
focus: Option<String>,
keys: Vec<String>,
@@ -79,6 +95,8 @@ pub fn route(page: &mut crate::BevyPage, engine: &mut raea_render::engine::Engin
pub(crate) fn retire(a: &mut Apps, screens: &[(String, u32, u32, String)]) {
let now = |name: &str, app: &str| screens.iter().any(|s| s.0 == name && s.3 == app);
a.failed.retain(|name, app| now(name, app));
+ // a document goes with its screen, or when the screen shows another module or size (opened again fresh)
+ a.docs.retain(|name, d| screens.iter().any(|s| &s.0 == name && s.3 == d.module && (s.1, s.2) == d.size));
let shown = |name: &str| screens.iter().any(|s| s.0 == name);
if a.focus.as_deref().is_some_and(|f| !shown(f)) {
a.focus = None;
@@ -89,3 +107,92 @@ pub(crate) fn retire(a: &mut Apps, screens: &[(String, u32, u32, String)]) {
}
}
+/// Each app screen stepped to the page's frame with its input (`dir`: the composition's folder, its modules' from),
+/// its document opened the first frame it's seen; one that won't open is said once and left blank.
+pub(crate) fn step_all(a: &mut Apps, screens: &[(String, u32, u32, String)], dir: &std::path::Path) {
+ let (f, fps) = a.frame.unwrap_or((0, 30.0));
+ if let Some(log) = APP_LOG.lock().unwrap().as_ref() {
+ set_logged(a, log.get(&f));
+ }
+ for (name, w, h, module) in screens {
+ if a.failed.contains_key(name) || *w == 0 || *h == 0 {
+ continue;
+ }
+ if !a.docs.contains_key(name) {
+ match AppScreen::open(dir, module, *w, *h, f, fps, Some(raea_runtime_view::render_creation())) {
+ Ok(d) => {
+ a.docs.insert(name.clone(), d);
+ }
+ Err(e) => {
+ eprintln!("raea: screen {name:?}: its app {module:?} didn't open: {e}");
+ a.failed.insert(name.clone(), module.clone());
+ continue;
+ }
+ }
+ }
+ let input = input_of(a, name);
+ if let Some(d) = a.docs.get_mut(name) {
+ d.step(f, fps, &input);
+ }
+ }
+}
+
+/// App screen `name`'s input this frame: the pointer when it's on it (with the wheel turned there), the keys while it
+/// has the focus (a DOM key's name; the live wire's marked keys, "Mouse:Right" or "Pad0:South", aren't keys to it).
+fn input_of(a: &Apps, name: &str) -> Input {
+ let on = a.pointer.as_ref().filter(|p| p.0 == name);
+ let key = |k: &&String| k.chars().count() == 1 || !k.contains(':');
+ Input {
+ pointer: on.map(|p| (p.1, p.2, p.3)),
+ keys: if a.focus.as_deref() == Some(name) { a.keys.iter().filter(key).cloned().collect() } else { Vec::new() },
+ wheel: if on.is_some() { a.wheel.iter().filter_map(|w| w.strip_prefix("Wheel:Y ")?.trim().parse().ok()).collect() } else { Vec::new() },
+ }
+}
+
+/// What reached the app screens this frame, as the input log keeps it (`apps`): the screen with the focus and its
+/// keys, the pointer on a screen (its name, x, y and whether it's down) and the wheel there. None when nothing did.
+pub(crate) fn logged(a: &Apps) -> Option<Value> {
+ if a.focus.is_none() && a.pointer.is_none() && a.wheel.is_empty() {
+ return None;
+ }
+ Some(json!({ "focus": a.focus, "keys": a.keys, "pointer": a.pointer.as_ref().map(|p| json!([p.0, p.1, p.2, p.3])), "wheel": a.wheel }))
+}
+
+/// The app screens' input set from a log's entry for the frame (`logged`'s); none when there's none.
+fn set_logged(a: &mut Apps, v: Option<&Value>) {
+ let strings = |v: Option<&Value>| v.and_then(Value::as_array).map(|l| l.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default();
+ a.focus = v.and_then(|v| v["focus"].as_str()).map(String::from);
+ a.keys = strings(v.map(|v| &v["keys"]));
+ a.wheel = strings(v.map(|v| &v["wheel"]));
+ a.pointer = v.and_then(|v| v["pointer"].as_array()).and_then(|p| Some((p.first()?.as_str()?.to_string(), p.get(1)?.as_f64()?, p.get(2)?.as_f64()?, p.get(3)?.as_bool()?)));
+}
+
+/// Each app screen's picture as last drawn, read back: its name, size and RGBA.
+pub(crate) fn pictures(a: &mut Apps) -> Result<Vec<(String, u32, u32, Vec<u8>)>, String> {
+ a.docs.iter_mut().map(|(name, d)| Ok((name.clone(), d.size.0, d.size.1, d.rgba()?))).collect()
+}
+
+/// Each app screen's picture as last drawn: its texture on the shared device.
+pub(crate) fn textures(a: &Apps) -> Vec<(String, wgpu::Texture)> {
+ a.docs.iter().filter_map(|(name, d)| Some((name.clone(), d.texture()?))).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_logged_input_comes_back_the_same() {
+ let mut a = Apps { focus: Some("kit".into()), keys: vec!["a".into(), "Pad0:South".into()], pointer: Some(("kit".into(), 12.5, 40.0, true)), wheel: vec!["Wheel:Y 120".into()], ..Default::default() };
+ let v = logged(&a).unwrap();
+ let mut b = Apps::default();
+ set_logged(&mut b, Some(&v));
+ assert_eq!(logged(&b), Some(v));
+ let i = input_of(&b, "kit");
+ assert_eq!(i, Input { pointer: Some((12.5, 40.0, true)), keys: vec!["a".into()], wheel: vec![120.0] });
+ assert_eq!(input_of(&b, "other"), Input::default());
+ set_logged(&mut a, None);
+ assert_eq!(logged(&a), None);
+ }
+}
+
diff --git a/tools/layers.toml b/tools/layers.toml
index 09fb0a33..9a212298 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -152,6 +152,7 @@ raea-runtime-export = "runtime"
raea-runtime-pagestore = "runtime"
raea-runtime-cssurls = "runtime"
raea-runtime-page = "runtime"
+raea-runtime-appscreen = "runtime"
raea-runtime-sound = "runtime"
raea-runtime-view = "runtime"
raea-runtime-world = "runtime"