//! `reproductor` — pinta una app que vive en un ARCHIVO, no en un binario. //! //! `allichay::Schema` deriva `Serialize`/`Deserialize`, así que una app //! declarada es un documento JSON: secciones, campos, controles y valores. Este //! ejemplo lo lee de disco y lo pinta con el MISMO renderizador que usan las //! apps compiladas (`schema_panel`), sin compilar nada. //! //! Es el «F5» del constructor: editás el archivo, volvés a correr, y la app //! cambió. El binario es siempre el mismo. //! //! El documento lleva **el cable adentro**: cada botón declara qué invoca //! (`Field::triggers`) y cada valor de dónde sale (`Field::bound_to`). allichay //! no interpreta ninguna de las dos cuerdas — las transporta hasta el host, que //! es quien sabe qué es `compra.adjudicar`. //! //! ```sh //! # 1. escribí una app de muestra (la de compras del expediente) //! cargo run -p llimphi-module-allichay --example reproductor -- --write-sample app.json //! # 2. pintala //! cargo run -p llimphi-module-allichay --example reproductor -- app.json app.png //! # 3. editá app.json a mano y repetí el paso 2: el binario no se recompila //! ``` use std::fs::File; use std::io::BufWriter; use allichay::{Action, Column, Field, Schema, Section}; use llimphi_module_allichay::{schema_panel, AllichayMsg, AllichayState}; use llimphi_ui::llimphi_compositor::{measure_text_node, mount, paint}; use llimphi_ui::llimphi_hal::{wgpu, Hal}; use llimphi_ui::llimphi_layout::taffy; use llimphi_ui::llimphi_layout::taffy::prelude::{percent, FlexDirection, Size, Style}; use llimphi_ui::llimphi_layout::LayoutTree; use llimphi_ui::llimphi_raster::peniko::Color; use llimphi_ui::llimphi_raster::{vello, Renderer}; use llimphi_ui::llimphi_text::Typesetter; use llimphi_ui::View; const W: u32 = 900; const H: u32 = 620; const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; /// La app de muestra: el expediente de compras. Es la MISMA que existe /// compilada en `qillqa-compras-llimphi` (412 LOC de Rust, 215 de ellas sólo /// para acomodar cosas en la pantalla); acá son datos. fn muestra() -> Schema { Schema::new().section( Section::new("compras", "Compras · expediente") .icon("🧾") .help("4 hitos del proceso") // Los tres montos no se escriben en el documento: se DECLARA de // dónde salen. El host resuelve la cuerda contra su almacén. .field(Field::display("partida", "PARTIDA CERTIFICADA", "1.000,00") .bound_to("compra.presupuesto")) .field(Field::display("comprometido", "COMPROMETIDO", "550,00") .bound_to("compra.comprometido")) .field(Field::display("disponible", "DISPONIBLE", "450,00") .bound_to("compra.disponible")) .field(Field::display("aviso", "estado", "la partida no puede sobregirarse en silencio")) // Y los botones declaran QUÉ invocan. allichay no sabe qué es // `compra.adjudicar`: sólo lo transporta hasta el host. .field(Field::button("award", "adjudicar 300,00").triggers( Action::new("compra.adjudicar").arg("monto", "30000"))) .field(Field::button("pay", "pagar 250,00").triggers( Action::new("compra.pagar").arg("monto", "25000"))) .field(Field::button("reset", "reiniciar").triggers(Action::new("compra.reiniciar"))) .field(Field::table( "hitos", "hitos del proceso", vec![ Column::new("seq", "#"), Column::new("tipo", "etapa"), Column::new("proveedor", "proveedor"), Column::new("monto", "monto"), Column::new("saldo", "saldo tras"), ], vec![ vec!["1".into(), "convocatoria".into(), String::new(), "—".into(), "1.000,00".into()], vec!["2".into(), "oferta".into(), "carpinteria-norte".into(), "550,00".into(), "1.000,00".into()], vec!["3".into(), "oferta".into(), "maderas-sur".into(), "700,00".into(), "1.000,00".into()], vec!["4".into(), "adjudicacion".into(), "carpinteria-norte".into(), "550,00".into(), "450,00".into()], ], )), ) } fn main() { let args: Vec = std::env::args().collect(); // Modo escritura: deja el JSON de la app de muestra. Prueba el round-trip // (lo que se escribe se vuelve a leer) y da el formato exacto sin adivinarlo. if args.get(1).map(String::as_str) == Some("--write-sample") { let out = args.get(2).cloned().unwrap_or_else(|| "app.json".into()); let s = muestra(); let txt = serde_json::to_string_pretty(&s).expect("serializa"); std::fs::write(&out, &txt).expect("escribe"); let ida_y_vuelta: Schema = serde_json::from_str(&txt).expect("deserializa"); assert_eq!(ida_y_vuelta, s, "el documento no reproduce la app"); println!("escrito {out} · {} bytes · ida y vuelta IDENTICA", txt.len()); return; } let ruta = args.get(1).expect("uso: reproductor [out.png] [seccion]"); let out = args.get(2).cloned().unwrap_or_else(|| "app.png".into()); let sel: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(0); let txt = std::fs::read_to_string(ruta).expect("no pude leer el archivo de la app"); let app: Schema = serde_json::from_str(&txt).expect("el archivo no es una app valida"); // Lo que el documento declara, contado: es el certificado barato, antes // de mirar un solo pixel. let sec = &app.sections[sel.min(app.sections.len().saturating_sub(1))]; println!("app leida de {ruta}"); println!(" {} seccion(es) · pintando «{}» ({} campos)", app.sections.len(), sec.title, sec.fields.len()); for f in &sec.fields { let cable = match (&f.action, &f.source) { (Some(a), _) => format!("-> dispara {}{}", a.verb, if a.args.is_empty() { String::new() } else { format!(" {:?}", a.args) }), (_, Some(s)) => format!("<- toma su valor de {s}"), _ => String::new(), }; println!(" {:<14} {cable}", f.id); } let theme = llimphi_theme::Theme::default(); let state = AllichayState::new(); let one = Schema { sections: vec![sec.clone()] }; let panel = schema_panel::<(), _>(&one, &state, &theme, H as f32 - 40.0, |_m: AllichayMsg| ()); let v = View::<()>::new(Style { flex_direction: FlexDirection::Column, size: Size { width: percent(1.0), height: percent(1.0) }, ..Default::default() }) .fill(theme.bg_app) .children(vec![panel]); // view -> layout -> escena, la misma secuencia del bucle de eventos. let mut layout = LayoutTree::new(); let mounted = mount(&mut layout, v); let mut ts = Typesetter::new(); let computed = { let tmap = &mounted.text_measures; layout .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| { match tmap.get(&nid) { Some(tm) => measure_text_node(&mut ts, tm, known, avail), None => taffy::Size::ZERO, } }) .expect("layout") }; let mut scene = vello::Scene::new(); paint(&mut scene, &mounted, &computed, &mut ts, None, None); let hal = pollster::block_on(Hal::new(None)).expect("hal"); let mut renderer = Renderer::new(&hal).expect("renderer"); let target = hal.device.create_texture(&wgpu::TextureDescriptor { label: Some("reproductor"), size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: FMT, usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }); let view = target.create_view(&wgpu::TextureViewDescriptor::default()); let [r, g, b, _] = theme.bg_app.components; let bg8 = [(r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8]; let bg = Color::from_rgba8(bg8[0], bg8[1], bg8[2], 255); renderer.render_to_view(&hal, &scene, &view, W, H, bg).expect("render_to_view"); let pintados = write_png(&hal, &target, &out, bg8); let total = (W * H) as f64; println!( " pintado {out} ({W}x{H}) · {pintados} px distintos del fondo ({:.1} %)", pintados as f64 * 100.0 / total ); } /// Escribe el PNG y devuelve cuántos píxeles difieren del fondo — el número /// que distingue «pintó la app» de «pintó un rectángulo del color del tema». fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str, bg: [u8; 3]) -> usize { let unpadded = (W * 4) as usize; let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; let padded = unpadded.div_ceil(align) * align; let buf = hal.device.create_buffer(&wgpu::BufferDescriptor { label: Some("readback"), size: (padded * H as usize) as u64, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let mut enc = hal.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }); enc.copy_texture_to_buffer( wgpu::TexelCopyTextureInfo { texture: target, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All, }, wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded as u32), rows_per_image: Some(H), }, }, wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 }, ); hal.queue.submit(std::iter::once(enc.finish())); let slice = buf.slice(..); let (tx, rx) = std::sync::mpsc::channel(); slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); }); let _ = hal.device.poll(wgpu::PollType::wait_indefinitely()); rx.recv().unwrap().unwrap(); let data = slice.get_mapped_range(); let mut pixels = Vec::with_capacity((W * H * 4) as usize); for row in 0..H as usize { let s = row * padded; pixels.extend_from_slice(&data[s..s + unpadded]); } drop(data); buf.unmap(); let distintos = pixels .chunks_exact(4) .filter(|p| p[0] != bg[0] || p[1] != bg[1] || p[2] != bg[2]) .count(); let file = File::create(path).expect("png"); let mut e = png::Encoder::new(BufWriter::new(file), W, H); e.set_color(png::ColorType::Rgba); e.set_depth(png::BitDepth::Eight); let mut w = e.write_header().unwrap(); w.write_image_data(&pixels).unwrap(); distintos }