tawasuyu/llimphi
Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.
⎇ efe361545d1db7a0857771dc6db4da1aed997289
widgets/terminal/examples/dump_blocks.rs
Historia
Quién tocó qué
crudo
refresh: stack al día (vello 0.7 / wgpu 27 / parley 0.6) + motor 3D voxel
1//! Dump headless del **modelo de bloques** virtualizado (Fase 2).
2//!
3//! Arma un stream de comandos como en el shell: cada comando = un header de
4//! card (chrome de alto fijo que el "caller" pinta) + un body de líneas del
5//! store. Incluye:
6//! - comandos cortos (ls, cargo) con stderr tintado,
7//! - un comando **colapsado** (sólo header, sin body),
8//! - un **flood** de 500 000 líneas (find /) en el medio,
9//! y ancla el scroll al fondo. Prueba que la virtualización por bloques
10//! materializa sólo los items + sub-filas visibles (costo constante) aunque un
11//! body tenga medio millón de líneas.
12//!
13//! Uso: `cargo run -p llimphi-widget-terminal --example dump_blocks --release [out.png]`
14
15use std::collections::HashSet;
16use std::fs::File;
17use std::io::BufWriter;
18
19use llimphi_ui::llimphi_compositor::{measure_text_node, mount, paint};
20use llimphi_ui::llimphi_hal::{wgpu, Hal};
21use llimphi_ui::llimphi_layout::taffy::prelude::{
22 auto, length, percent, AlignItems, FlexDirection, Rect, Size, Style,
23};
24use llimphi_ui::llimphi_layout::{taffy, LayoutTree};
25use llimphi_ui::llimphi_raster::peniko::Color;
26use llimphi_ui::llimphi_raster::{vello, Renderer};
27use llimphi_ui::llimphi_text::{Alignment, Typesetter};
28use llimphi_ui::View;
29use llimphi_widget_terminal::{
30 block_surface, blocks_height, blocks_scroll_to_bottom, visible_window, Item, LineStyle,
31 Scrollback, TermMetrics, TermPalette,
32};
33
34const W: u32 = 1100;
35const H: u32 = 760;
36const INFO_H: f32 = 36.0;
37const HEADER_H: f32 = 30.0;
38const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
39
40/// Un comando del stream: rango de body en el store + estado para el header.
41struct Cmd {
42 text: String,
43 exit: i32,
44 start: usize,
45 end: usize,
46 collapsed: bool,
47}
48
49fn main() {
50 let out = std::env::args()
51 .nth(1)
52 .unwrap_or_else(|| "blocks.png".to_string());
53 let theme = llimphi_theme::Theme::default();
54 let palette = TermPalette::from_theme(&theme);
55 let metrics = TermMetrics::for_font_size(13.0);
56
57 let mut store = Scrollback::new(0);
58 let mut stderr: HashSet<usize> = HashSet::new();
59 let mut cmds: Vec<Cmd> = Vec::new();
60
61 // Helper para registrar un comando con su body.
62 let run = |store: &mut Scrollback,
63 stderr: &mut HashSet<usize>,
64 cmds: &mut Vec<Cmd>,
65 text: &str,
66 exit: i32,
67 collapsed: bool,
68 body: &[(bool, String)]| {
69 let start = store.len();
70 for (is_err, line) in body {
71 if *is_err {
72 stderr.insert(store.len());
73 }
74 store.push_line(line);
75 }
76 cmds.push(Cmd {
77 text: text.to_string(),
78 exit,
79 start,
80 end: store.len(),
81 collapsed,
82 });
83 };
84
85 // 1) ls -la — salida normal corta.
86 run(
87 &mut store,
88 &mut stderr,
89 &mut cmds,
90 "ls -la ~/tawasuyu",
91 0,
92 false,
93 &[
94 (false, "total 248".into()),
95 (false, "drwxr-xr-x 12 sergio sergio 4096 jun 6 00_unanchay".into()),
96 (false, "drwxr-xr-x 8 sergio sergio 4096 jun 6 02_ruway".into()),
97 (false, "-rw-r--r-- 1 sergio sergio 11234 jun 6 CLAUDE.md".into()),
98 (false, "-rw-r--r-- 1 sergio sergio 8901 jun 6 README.md".into()),
99 ],
100 );
101
102 // 2) cargo build — con un warning a stderr.
103 run(
104 &mut store,
105 &mut stderr,
106 &mut cmds,
107 "cargo build -p llimphi-widget-terminal",
108 0,
109 false,
110 &[
111 (false, " Compiling llimphi-widget-terminal v0.1.0".into()),
112 (true, "warning: unused variable `x`".into()),
113 (true, " --> src/blocks.rs:42:9".into()),
114 (false, " Finished `dev` profile in 1.89s".into()),
115 ],
116 );
117
118 // 3) find / — el FLOOD: medio millón de líneas en un solo body.
119 {
120 let start = store.len();
121 for i in 0..500_000 {
122 store.push_line(&format!(
123 "/home/sergio/tawasuyu/02_ruway/llimphi/widgets/terminal/src/archivo_{i:06}.rs"
124 ));
125 }
126 cmds.push(Cmd {
127 text: "find / -name '*.rs'".into(),
128 exit: 0,
129 start,
130 end: store.len(),
131 collapsed: false,
132 });
133 }
134
135 // 4) git status — COLAPSADO (sólo header, body oculto).
136 run(
137 &mut store,
138 &mut stderr,
139 &mut cmds,
140 "git status",
141 0,
142 true,
143 &[
144 (false, "On branch main".into()),
145 (false, "Changes not staged for commit:".into()),
146 (false, " modified: src/blocks.rs".into()),
147 ],
148 );
149
150 // 5) cat inexistente — exit 1, stderr.
151 run(
152 &mut store,
153 &mut stderr,
154 &mut cmds,
155 "cat noexiste.txt",
156 1,
157 false,
158 &[(true, "cat: noexiste.txt: No such file or directory".into())],
159 );
160
161 // 6) echo final corto.
162 run(
163 &mut store,
164 &mut stderr,
165 &mut cmds,
166 "echo listo",
167 0,
168 false,
169 &[(false, "listo".into())],
170 );
171
172 // Construye los items: por cada comando, un header (chrome) y, salvo
173 // colapsado, su body (Lines). El widget virtualiza sobre estas alturas.
174 let mut items: Vec<Item<()>> = Vec::new();
175 for c in &cmds {
176 items.push(Item::chrome(HEADER_H, header_card(c, &theme)));
177 if !c.collapsed {
178 items.push(Item::lines(c.start, c.end));
179 }
180 }
181
182 let viewport_h = H as f32 - INFO_H;
183 let row_h = metrics.line_height;
184 let scroll_y = blocks_scroll_to_bottom(&items, viewport_h, row_h);
185
186 // Coloreo inyectado por el caller: stderr rojo (texto + tinte), resto tinta
187 // el prefijo hasta el primer espacio en acento (paths/tokens).
188 let accent = theme.accent;
189 let err_fg = theme.fg_destructive;
190 let err_bg = with_alpha(theme.fg_destructive, 0.14);
191 let line_style = move |idx: usize, text: &str| {
192 if stderr.contains(&idx) {
193 LineStyle {
194 fg: Some(err_fg),
195 bg: Some(err_bg),
196 ..Default::default()
197 }
198 } else {
199 let end = text.find(' ').unwrap_or(text.len());
200 LineStyle {
201 runs: vec![(0, end, accent)],
202 ..Default::default()
203 }
204 }
205 };
206
207 // Evidencia: cuántos items/filas se materializaron del total.
208 let total_lines = store.len();
209 let total_h = blocks_height(&items, row_h);
210 // Filas visibles ~ las que entran en el viewport (medida de costo).
211 let approx_rows = visible_window(total_lines, scroll_y, viewport_h, row_h).count();
212 let info = format!(
213 "{} comandos · {} líneas en scrollback · alto virtual {:.0}px · ~{} filas materializadas · anclado al fondo",
214 cmds.len(),
215 total_lines,
216 total_h,
217 approx_rows,
218 );
219
220 let surface = block_surface::<(), _, _>(
221 &store,
222 items,
223 scroll_y,
224 viewport_h,
225 metrics,
226 &palette,
227 line_style,
228 |_d| (),
229 None,
230 );
231
232 let info_bar = View::new(Style {
233 size: Size {
234 width: percent(1.0_f32),
235 height: length(INFO_H),
236 },
237 align_items: Some(AlignItems::Center),
238 ..Default::default()
239 })
240 .fill(theme.bg_panel_alt)
241 .text_aligned(info, 12.5, theme.fg_text, Alignment::Start);
242
243 let root = View::new(Style {
244 flex_direction: FlexDirection::Column,
245 size: Size {
246 width: percent(1.0_f32),
247 height: percent(1.0_f32),
248 },
249 ..Default::default()
250 })
251 .fill(theme.bg_input)
252 .children(vec![info_bar, surface]);
253
254 render_png(root, &out);
255 eprintln!("dump_blocks: {out} ({W}x{H}) — {total_lines} líneas, ~{approx_rows} filas materializadas");
256}
257
258/// Header de card de un comando — el "chrome" que el caller pinta: barra de
259/// acento a la izquierda + `$ comando` mono + estado `exit N` a la derecha.
260fn header_card(c: &Cmd, theme: &llimphi_theme::Theme) -> View<()> {
261 let (status_txt, status_col) = if c.exit == 0 {
262 (format!("exit {}", c.exit), Color::from_rgb8(120, 200, 130))
263 } else {
264 (format!("exit {}", c.exit), theme.fg_destructive)
265 };
266 // ASCII a propósito: la mono embebida no cubre triángulos geométricos
267 // (tofu) — `+` colapsado / `-` expandido, convención de árbol.
268 let chevron = if c.collapsed { "+" } else { "-" };
269
270 // Barra de acento (3px) a la izquierda.
271 let accent_bar = View::new(Style {
272 size: Size {
273 width: length(3.0_f32),
274 height: percent(1.0_f32),
275 },
276 ..Default::default()
277 })
278 .fill(if c.exit == 0 { theme.accent } else { theme.fg_destructive });
279
280 // Estado (alineado a la derecha): chevron de colapso + `exit N`.
281 let status = View::new(Style {
282 size: Size {
283 width: length(140.0_f32),
284 height: percent(1.0_f32),
285 },
286 align_items: Some(AlignItems::Center),
287 ..Default::default()
288 })
289 .text_aligned(
290 format!("{chevron} {status_txt}"),
291 12.0,
292 status_col,
293 Alignment::End,
294 )
295 .mono();
296
297 let cmd = View::new(Style {
298 flex_grow: 1.0,
299 size: Size {
300 width: auto(),
301 height: percent(1.0_f32),
302 },
303 align_items: Some(AlignItems::Center),
304 padding: Rect {
305 left: length(8.0_f32),
306 right: length(8.0_f32),
307 top: length(0.0_f32),
308 bottom: length(0.0_f32),
309 },
310 ..Default::default()
311 })
312 .text_aligned(format!("$ {}", c.text), 13.0, theme.fg_text, Alignment::Start)
313 .mono();
314
315 View::new(Style {
316 flex_direction: FlexDirection::Row,
317 size: Size {
318 width: percent(1.0_f32),
319 height: length(HEADER_H),
320 },
321 align_items: Some(AlignItems::Center),
322 ..Default::default()
323 })
324 .fill(theme.bg_panel)
325 .children(vec![accent_bar, cmd, status])
326}
327
328/// Devuelve `c` con la opacidad fijada a `alpha`.
329fn with_alpha(c: Color, alpha: f32) -> Color {
330 let rgba = c.to_rgba8();
331 Color::from_rgba8(rgba.r, rgba.g, rgba.b, (alpha.clamp(0.0, 1.0) * 255.0) as u8)
332}
333
334fn render_png(root: View<()>, out: &str) {
335 let mut layout = LayoutTree::new();
336 let mounted = mount(&mut layout, root);
337 let mut ts = Typesetter::new();
338 let computed = {
339 let tmap = &mounted.text_measures;
340 layout
341 .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
342 match tmap.get(&nid) {
343 Some(tm) => measure_text_node(&mut ts, tm, known, avail),
344 None => taffy::Size::ZERO,
345 }
346 })
347 .expect("layout")
348 };
349 let mut scene = vello::Scene::new();
350 paint(&mut scene, &mounted, &computed, &mut ts, None, None);
351
352 let hal = pollster::block_on(Hal::new(None)).expect("hal");
353 let mut renderer = Renderer::new(&hal).expect("renderer");
354 let target = hal.device.create_texture(&wgpu::TextureDescriptor {
355 label: Some("dump-blocks"),
356 size: wgpu::Extent3d {
357 width: W,
358 height: H,
359 depth_or_array_layers: 1,
360 },
361 mip_level_count: 1,
362 sample_count: 1,
363 dimension: wgpu::TextureDimension::D2,
364 format: FMT,
365 usage: wgpu::TextureUsages::STORAGE_BINDING
366 | wgpu::TextureUsages::RENDER_ATTACHMENT
367 | wgpu::TextureUsages::COPY_SRC,
368 view_formats: &[],
369 });
370 let view = target.create_view(&wgpu::TextureViewDescriptor::default());
371 renderer
372 .render_to_view(&hal, &scene, &view, W, H, Color::from_rgba8(18, 18, 24, 255))
373 .expect("render_to_view");
374 write_png(&hal, &target, out);
375}
376
377fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
378 let unpadded = (W * 4) as usize;
379 let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
380 let padded = unpadded.div_ceil(align) * align;
381 let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
382 label: Some("readback"),
383 size: (padded * H as usize) as u64,
384 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
385 mapped_at_creation: false,
386 });
387 let mut enc = hal
388 .device
389 .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
390 enc.copy_texture_to_buffer(
391 wgpu::TexelCopyTextureInfo {
392 texture: target,
393 mip_level: 0,
394 origin: wgpu::Origin3d::ZERO,
395 aspect: wgpu::TextureAspect::All,
396 },
397 wgpu::TexelCopyBufferInfo {
398 buffer: &buf,
399 layout: wgpu::TexelCopyBufferLayout {
400 offset: 0,
401 bytes_per_row: Some(padded as u32),
402 rows_per_image: Some(H),
403 },
404 },
405 wgpu::Extent3d {
406 width: W,
407 height: H,
408 depth_or_array_layers: 1,
409 },
410 );
411 hal.queue.submit(std::iter::once(enc.finish()));
412 let slice = buf.slice(..);
413 let (tx, rx) = std::sync::mpsc::channel();
414 slice.map_async(wgpu::MapMode::Read, move |r| {
415 let _ = tx.send(r);
416 });
417 hal.device.poll(wgpu::PollType::wait_indefinitely());
418 rx.recv().unwrap().unwrap();
419 let data = slice.get_mapped_range();
420 let mut pixels = Vec::with_capacity((W * H * 4) as usize);
421 for row in 0..H as usize {
422 let s = row * padded;
423 pixels.extend_from_slice(&data[s..s + unpadded]);
424 }
425 drop(data);
426 buf.unmap();
427 let file = File::create(path).expect("png");
428 let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
429 enc.set_color(png::ColorType::Rgba);
430 enc.set_depth(png::BitDepth::Eight);
431 let mut w = enc.write_header().unwrap();
432 w.write_image_data(&pixels).unwrap();
433}