tawasuyu/llimphi
Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.
chore: refresco desde el monorepo — 132 miembros, 79 widgets, la galería vuelve y licencia dual
1//! `reproductor` — pinta una app que vive en un ARCHIVO, no en un binario.
2//!
3//! `allichay::Schema` deriva `Serialize`/`Deserialize`, así que una app
4//! declarada es un documento JSON: secciones, campos, controles y valores. Este
5//! ejemplo lo lee de disco y lo pinta con el MISMO renderizador que usan las
6//! apps compiladas (`schema_panel`), sin compilar nada.
7//!
8//! Es el «F5» del constructor: editás el archivo, volvés a correr, y la app
9//! cambió. El binario es siempre el mismo.
10//!
11//! El documento lleva **el cable adentro**: cada botón declara qué invoca
12//! (`Field::triggers`) y cada valor de dónde sale (`Field::bound_to`). allichay
13//! no interpreta ninguna de las dos cuerdas — las transporta hasta el host, que
14//! es quien sabe qué es `compra.adjudicar`.
15//!
16//! ```sh
17//! # 1. escribí una app de muestra (la de compras del expediente)
18//! cargo run -p llimphi-module-allichay --example reproductor -- --write-sample app.json
19//! # 2. pintala
20//! cargo run -p llimphi-module-allichay --example reproductor -- app.json app.png
21//! # 3. editá app.json a mano y repetí el paso 2: el binario no se recompila
22//! ```
23use std::fs::File;
24use std::io::BufWriter;
25
26use allichay::{Action, Column, Field, Schema, Section};
27use llimphi_module_allichay::{schema_panel, AllichayMsg, AllichayState};
28
29use llimphi_ui::llimphi_compositor::{measure_text_node, mount, paint};
30use llimphi_ui::llimphi_hal::{wgpu, Hal};
31use llimphi_ui::llimphi_layout::taffy;
32use llimphi_ui::llimphi_layout::taffy::prelude::{percent, FlexDirection, Size, Style};
33use llimphi_ui::llimphi_layout::LayoutTree;
34use llimphi_ui::llimphi_raster::peniko::Color;
35use llimphi_ui::llimphi_raster::{vello, Renderer};
36use llimphi_ui::llimphi_text::Typesetter;
37use llimphi_ui::View;
38
39const W: u32 = 900;
40const H: u32 = 620;
41const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
42
43/// La app de muestra: el expediente de compras. Es la MISMA que existe
44/// compilada en `qillqa-compras-llimphi` (412 LOC de Rust, 215 de ellas sólo
45/// para acomodar cosas en la pantalla); acá son datos.
46fn muestra() -> Schema {
47 Schema::new().section(
48 Section::new("compras", "Compras · expediente")
49 .icon("🧾")
50 .help("4 hitos del proceso")
51 // Los tres montos no se escriben en el documento: se DECLARA de
52 // dónde salen. El host resuelve la cuerda contra su almacén.
53 .field(Field::display("partida", "PARTIDA CERTIFICADA", "1.000,00")
54 .bound_to("compra.presupuesto"))
55 .field(Field::display("comprometido", "COMPROMETIDO", "550,00")
56 .bound_to("compra.comprometido"))
57 .field(Field::display("disponible", "DISPONIBLE", "450,00")
58 .bound_to("compra.disponible"))
59 .field(Field::display("aviso", "estado", "la partida no puede sobregirarse en silencio"))
60 // Y los botones declaran QUÉ invocan. allichay no sabe qué es
61 // `compra.adjudicar`: sólo lo transporta hasta el host.
62 .field(Field::button("award", "adjudicar 300,00").triggers(
63 Action::new("compra.adjudicar").arg("monto", "30000")))
64 .field(Field::button("pay", "pagar 250,00").triggers(
65 Action::new("compra.pagar").arg("monto", "25000")))
66 .field(Field::button("reset", "reiniciar").triggers(Action::new("compra.reiniciar")))
67 .field(Field::table(
68 "hitos",
69 "hitos del proceso",
70 vec![
71 Column::new("seq", "#"),
72 Column::new("tipo", "etapa"),
73 Column::new("proveedor", "proveedor"),
74 Column::new("monto", "monto"),
75 Column::new("saldo", "saldo tras"),
76 ],
77 vec![
78 vec!["1".into(), "convocatoria".into(), String::new(), "—".into(), "1.000,00".into()],
79 vec!["2".into(), "oferta".into(), "carpinteria-norte".into(), "550,00".into(), "1.000,00".into()],
80 vec!["3".into(), "oferta".into(), "maderas-sur".into(), "700,00".into(), "1.000,00".into()],
81 vec!["4".into(), "adjudicacion".into(), "carpinteria-norte".into(), "550,00".into(), "450,00".into()],
82 ],
83 )),
84 )
85}
86
87fn main() {
88 let args: Vec<String> = std::env::args().collect();
89
90 // Modo escritura: deja el JSON de la app de muestra. Prueba el round-trip
91 // (lo que se escribe se vuelve a leer) y da el formato exacto sin adivinarlo.
92 if args.get(1).map(String::as_str) == Some("--write-sample") {
93 let out = args.get(2).cloned().unwrap_or_else(|| "app.json".into());
94 let s = muestra();
95 let txt = serde_json::to_string_pretty(&s).expect("serializa");
96 std::fs::write(&out, &txt).expect("escribe");
97 let ida_y_vuelta: Schema = serde_json::from_str(&txt).expect("deserializa");
98 assert_eq!(ida_y_vuelta, s, "el documento no reproduce la app");
99 println!("escrito {out} · {} bytes · ida y vuelta IDENTICA", txt.len());
100 return;
101 }
102
103 let ruta = args.get(1).expect("uso: reproductor <app.json> [out.png] [seccion]");
104 let out = args.get(2).cloned().unwrap_or_else(|| "app.png".into());
105 let sel: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(0);
106
107 let txt = std::fs::read_to_string(ruta).expect("no pude leer el archivo de la app");
108 let app: Schema = serde_json::from_str(&txt).expect("el archivo no es una app valida");
109
110 // Lo que el documento declara, contado: es el certificado barato, antes
111 // de mirar un solo pixel.
112 let sec = &app.sections[sel.min(app.sections.len().saturating_sub(1))];
113 println!("app leida de {ruta}");
114 println!(" {} seccion(es) · pintando «{}» ({} campos)", app.sections.len(), sec.title, sec.fields.len());
115 for f in &sec.fields {
116 let cable = match (&f.action, &f.source) {
117 (Some(a), _) => format!("-> dispara {}{}", a.verb,
118 if a.args.is_empty() { String::new() } else { format!(" {:?}", a.args) }),
119 (_, Some(s)) => format!("<- toma su valor de {s}"),
120 _ => String::new(),
121 };
122 println!(" {:<14} {cable}", f.id);
123 }
124
125 let theme = llimphi_theme::Theme::default();
126 let state = AllichayState::new();
127 let one = Schema { sections: vec![sec.clone()] };
128 let panel = schema_panel::<(), _>(&one, &state, &theme, H as f32 - 40.0, |_m: AllichayMsg| ());
129 let v = View::<()>::new(Style {
130 flex_direction: FlexDirection::Column,
131 size: Size { width: percent(1.0), height: percent(1.0) },
132 ..Default::default()
133 })
134 .fill(theme.bg_app)
135 .children(vec![panel]);
136
137 // view -> layout -> escena, la misma secuencia del bucle de eventos.
138 let mut layout = LayoutTree::new();
139 let mounted = mount(&mut layout, v);
140 let mut ts = Typesetter::new();
141 let computed = {
142 let tmap = &mounted.text_measures;
143 layout
144 .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
145 match tmap.get(&nid) {
146 Some(tm) => measure_text_node(&mut ts, tm, known, avail),
147 None => taffy::Size::ZERO,
148 }
149 })
150 .expect("layout")
151 };
152 let mut scene = vello::Scene::new();
153 paint(&mut scene, &mounted, &computed, &mut ts, None, None);
154
155 let hal = pollster::block_on(Hal::new(None)).expect("hal");
156 let mut renderer = Renderer::new(&hal).expect("renderer");
157 let target = hal.device.create_texture(&wgpu::TextureDescriptor {
158 label: Some("reproductor"),
159 size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
160 mip_level_count: 1,
161 sample_count: 1,
162 dimension: wgpu::TextureDimension::D2,
163 format: FMT,
164 usage: wgpu::TextureUsages::STORAGE_BINDING
165 | wgpu::TextureUsages::RENDER_ATTACHMENT
166 | wgpu::TextureUsages::COPY_SRC,
167 view_formats: &[],
168 });
169 let view = target.create_view(&wgpu::TextureViewDescriptor::default());
170 let [r, g, b, _] = theme.bg_app.components;
171 let bg8 = [(r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8];
172 let bg = Color::from_rgba8(bg8[0], bg8[1], bg8[2], 255);
173 renderer.render_to_view(&hal, &scene, &view, W, H, bg).expect("render_to_view");
174
175 let pintados = write_png(&hal, &target, &out, bg8);
176 let total = (W * H) as f64;
177 println!(
178 " pintado {out} ({W}x{H}) · {pintados} px distintos del fondo ({:.1} %)",
179 pintados as f64 * 100.0 / total
180 );
181}
182
183/// Escribe el PNG y devuelve cuántos píxeles difieren del fondo — el número
184/// que distingue «pintó la app» de «pintó un rectángulo del color del tema».
185fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str, bg: [u8; 3]) -> usize {
186 let unpadded = (W * 4) as usize;
187 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
188 let padded = unpadded.div_ceil(align) * align;
189 let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
190 label: Some("readback"),
191 size: (padded * H as usize) as u64,
192 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
193 mapped_at_creation: false,
194 });
195 let mut enc = hal.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
196 enc.copy_texture_to_buffer(
197 wgpu::TexelCopyTextureInfo {
198 texture: target,
199 mip_level: 0,
200 origin: wgpu::Origin3d::ZERO,
201 aspect: wgpu::TextureAspect::All,
202 },
203 wgpu::TexelCopyBufferInfo {
204 buffer: &buf,
205 layout: wgpu::TexelCopyBufferLayout {
206 offset: 0,
207 bytes_per_row: Some(padded as u32),
208 rows_per_image: Some(H),
209 },
210 },
211 wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
212 );
213 hal.queue.submit(std::iter::once(enc.finish()));
214 let slice = buf.slice(..);
215 let (tx, rx) = std::sync::mpsc::channel();
216 slice.map_async(wgpu::MapMode::Read, move |r| {
217 let _ = tx.send(r);
218 });
219 let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
220 rx.recv().unwrap().unwrap();
221 let data = slice.get_mapped_range();
222 let mut pixels = Vec::with_capacity((W * H * 4) as usize);
223 for row in 0..H as usize {
224 let s = row * padded;
225 pixels.extend_from_slice(&data[s..s + unpadded]);
226 }
227 drop(data);
228 buf.unmap();
229 let distintos = pixels
230 .chunks_exact(4)
231 .filter(|p| p[0] != bg[0] || p[1] != bg[1] || p[2] != bg[2])
232 .count();
233 let file = File::create(path).expect("png");
234 let mut e = png::Encoder::new(BufWriter::new(file), W, H);
235 e.set_color(png::ColorType::Rgba);
236 e.set_depth(png::BitDepth::Eight);
237 let mut w = e.write_header().unwrap();
238 w.write_image_data(&pixels).unwrap();
239 distintos
240}