tawasuyu

tawasuyu/llimphi

Sovereign retained-mode GPU UI framework in Rust (wgpu+vello+taffy+parley), Elm loop, 40+ widgets.

Rust 660Markdown 302TOML 157RON 312382 Sutichaykuna

⎇ 168cd187519c0ad575d3ce63baee2f164c38d9d1 llimphi-compositor/examples/rich_text_demo.rs Rust · 262 siq'ikuna · 9.5 KB Ñawpa willay Pi imata llamkarqan ch'uya

chore: refresco desde el monorepo — vello 0.9 / wgpu 29, 120 miembros d251eb32b · Sergio ·

1//! Volcado headless de **RichText spans** (Bloque 13 de PARIDAD-FLUTTER:
2//! cierra Tier 2 final): un mismo nodo de texto con defaults a nivel
3//! bloque (tamaño 16 px, color gris oscuro, weight 400, sin italic) más
4//! un arreglo de `TextSpan` que sobreescriben por rango de bytes
5//! `weight=700` (bold), `italic=true`, `color`, `underline=true`,
6//! `size_px=22` (heading inline), `font_family=mono` (`<code>`-like) y
7//! `strikethrough=true`. Verifica que la **medida** y el **pintado**
8//! consumen el mismo `layout_spans` (taffy reserva el alto del span más
9//! alto en su línea).
10//!
11//! `cargo run -p llimphi-compositor --example rich_text_demo -- [out.png]`
12
13use std::fs::File;
14use std::io::BufWriter;
15
16use llimphi_compositor::{measure_text_node, mount, paint, View};
17use llimphi_hal::{wgpu, Hal};
18use llimphi_layout::taffy;
19use llimphi_layout::taffy::prelude::{length, percent, FlexDirection, Size, Style};
20use llimphi_layout::taffy::{AlignItems, JustifyContent, Rect};
21use llimphi_layout::LayoutTree;
22use llimphi_raster::peniko::Color;
23use llimphi_raster::{vello, Renderer};
24use llimphi_text::{Alignment, TextSpan, TextSpanStyle, Typesetter, MONOSPACE};
25
26const W: u32 = 980;
27const H: u32 = 380;
28const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
29
30fn rgb(r: u8, g: u8, b: u8) -> Color {
31    Color::from_rgba8(r, g, b, 255)
32}
33
34/// Helper para localizar un substring exacto en `text` y devolver el
35/// `[start, end)` en bytes — así los spans del demo son legibles ("apply
36/// bold to 'NEGRITA'") sin offsets a mano.
37fn range_of(text: &str, needle: &str) -> (usize, usize) {
38    let start = text.find(needle).unwrap_or_else(|| panic!("'{needle}' not found"));
39    (start, start + needle.len())
40}
41
42fn main() {
43    let out = std::env::args().nth(1).unwrap_or_else(|| "rich_text.png".to_string());
44    let theme = llimphi_theme::Theme::light();
45
46    let panel = theme.bg_panel;
47    let dark = rgb(30, 34, 44);
48    let accent = rgb(52, 152, 219);
49    let danger = rgb(231, 76, 60);
50    let muted = rgb(128, 132, 144);
51
52    // Párrafo con seis tipos de override + texto plano alrededor para que
53    // se note el contraste de cada lente.
54    let parrafo = "Esto es un párrafo que mezcla NEGRITA, cursiva, un \
55                   link.com, un cambio de TAMAÑO inline, una palabra \
56                   tachada y código de muestra inline.";
57    let (b0, b1) = range_of(parrafo, "NEGRITA");
58    let (i0, i1) = range_of(parrafo, "cursiva");
59    let (l0, l1) = range_of(parrafo, "link.com");
60    let (sz0, sz1) = range_of(parrafo, "TAMAÑO");
61    let (st0, st1) = range_of(parrafo, "tachada");
62    let (m0, m1) = range_of(parrafo, "código de muestra");
63    let spans = vec![
64        TextSpan::new(b0, b1, TextSpanStyle { weight: Some(700.0), ..Default::default() }),
65        TextSpan::new(i0, i1, TextSpanStyle { italic: Some(true), ..Default::default() }),
66        TextSpan::new(
67            l0,
68            l1,
69            TextSpanStyle {
70                color: Some(accent),
71                underline: Some(true),
72                ..Default::default()
73            },
74        ),
75        TextSpan::new(
76            sz0,
77            sz1,
78            TextSpanStyle {
79                size_px: Some(24.0),
80                weight: Some(700.0),
81                color: Some(rgb(46, 204, 113)),
82                ..Default::default()
83            },
84        ),
85        TextSpan::new(
86            st0,
87            st1,
88            TextSpanStyle {
89                color: Some(danger),
90                strikethrough: Some(true),
91                ..Default::default()
92            },
93        ),
94        TextSpan::new(
95            m0,
96            m1,
97            TextSpanStyle {
98                font_family: Some(MONOSPACE.to_string()),
99                color: Some(rgb(155, 89, 182)),
100                ..Default::default()
101            },
102        ),
103    ];
104
105    let texto_rico = View::<()>::new(Style {
106        size: Size { width: percent(1.0_f32), height: length(160.0_f32) },
107        ..Default::default()
108    })
109    .text_spans(parrafo, 16.0, dark, spans, Alignment::Start);
110
111    // Subtítulo + descripción + el párrafo rico, todo dentro de una card
112    // (apilada con flex_direction Column).
113    let titulo = View::<()>::new(Style {
114        size: Size { width: percent(1.0_f32), height: length(28.0_f32) },
115        ..Default::default()
116    })
117    .text_aligned(
118        "RichText spans (Bloque 13 — cierra Tier 2)",
119        18.0,
120        dark,
121        Alignment::Start,
122    )
123    .bold();
124    let descripcion = View::<()>::new(Style {
125        size: Size { width: percent(1.0_f32), height: length(20.0_f32) },
126        ..Default::default()
127    })
128    .text_aligned(
129        "Un solo nodo, seis tipos de override aplicados por rango de bytes:",
130        13.0,
131        muted,
132        Alignment::Start,
133    );
134
135    let card = View::<()>::new(Style {
136        size: Size { width: length(W as f32 - 80.0), height: length(H as f32 - 60.0) },
137        flex_direction: FlexDirection::Column,
138        align_items: Some(AlignItems::FLEX_START),
139        justify_content: Some(JustifyContent::FLEX_START),
140        gap: Size { width: length(0.0_f32), height: length(12.0_f32) },
141        padding: Rect {
142            left: length(24.0_f32),
143            right: length(24.0_f32),
144            top: length(20.0_f32),
145            bottom: length(20.0_f32),
146        },
147        ..Default::default()
148    })
149    .fill(panel)
150    .radius(16.0)
151    .border(1.0, rgb(220, 224, 232))
152    .children(vec![titulo, descripcion, texto_rico]);
153
154    let root = View::<()>::new(Style {
155        size: Size { width: percent(1.0_f32), height: percent(1.0_f32) },
156        align_items: Some(AlignItems::CENTER),
157        justify_content: Some(JustifyContent::CENTER),
158        ..Default::default()
159    })
160    .fill(theme.bg_app)
161    .children(vec![card]);
162
163    let mut layout = LayoutTree::new();
164    let mounted = mount(&mut layout, root);
165    let mut ts = Typesetter::new();
166    let computed = {
167        let tmap = &mounted.text_measures;
168        layout
169            .compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
170                match tmap.get(&nid) {
171                    Some(tm) => measure_text_node(&mut ts, tm, known, avail),
172                    None => taffy::Size::ZERO,
173                }
174            })
175            .expect("layout")
176    };
177    let mut scene = vello::Scene::new();
178    paint(&mut scene, &mounted, &computed, &mut ts, None, None);
179
180    let hal = pollster::block_on(Hal::new(None)).expect("hal");
181    let mut renderer = Renderer::new(&hal).expect("renderer");
182    let target = hal.device.create_texture(&wgpu::TextureDescriptor {
183        label: Some("dump-rich-text"),
184        size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
185        mip_level_count: 1,
186        sample_count: 1,
187        dimension: wgpu::TextureDimension::D2,
188        format: FMT,
189        usage: wgpu::TextureUsages::STORAGE_BINDING
190            | wgpu::TextureUsages::RENDER_ATTACHMENT
191            | wgpu::TextureUsages::COPY_SRC,
192        view_formats: &[],
193    });
194    let view = target.create_view(&wgpu::TextureViewDescriptor::default());
195    let [r, g, b, _] = theme.bg_app.components;
196    let bg = Color::from_rgba8((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, 255);
197    renderer
198        .render_to_view(&hal, &scene, &view, W, H, bg)
199        .expect("render_to_view");
200
201    write_png(&hal, &target, &out);
202    eprintln!(
203        "rich_text_demo: escrito {out} ({W}x{H}) — un nodo de texto con \
204         seis spans aplicados por rango de bytes: bold, italic, link \
205         (color + underline), heading inline (size 24 + bold + verde), \
206         strikethrough rojo, y un fragmento en mono morado."
207    );
208}
209
210fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
211    let unpadded = (W * 4) as usize;
212    let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
213    let padded = unpadded.div_ceil(align) * align;
214    let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
215        label: Some("readback"),
216        size: (padded * H as usize) as u64,
217        usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
218        mapped_at_creation: false,
219    });
220    let mut enc = hal
221        .device
222        .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
223    enc.copy_texture_to_buffer(
224        wgpu::TexelCopyTextureInfo {
225            texture: target,
226            mip_level: 0,
227            origin: wgpu::Origin3d::ZERO,
228            aspect: wgpu::TextureAspect::All,
229        },
230        wgpu::TexelCopyBufferInfo {
231            buffer: &buf,
232            layout: wgpu::TexelCopyBufferLayout {
233                offset: 0,
234                bytes_per_row: Some(padded as u32),
235                rows_per_image: Some(H),
236            },
237        },
238        wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
239    );
240    hal.queue.submit(std::iter::once(enc.finish()));
241    let slice = buf.slice(..);
242    let (tx, rx) = std::sync::mpsc::channel();
243    slice.map_async(wgpu::MapMode::Read, move |r| {
244        let _ = tx.send(r);
245    });
246    let _ = hal.device.poll(wgpu::PollType::wait_indefinitely());
247    rx.recv().unwrap().unwrap();
248    let data = slice.get_mapped_range();
249    let mut pixels = Vec::with_capacity((W * H * 4) as usize);
250    for row in 0..H as usize {
251        let s = row * padded;
252        pixels.extend_from_slice(&data[s..s + unpadded]);
253    }
254    drop(data);
255    buf.unmap();
256    let file = File::create(path).expect("png");
257    let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
258    enc.set_color(png::ColorType::Rgba);
259    enc.set_depth(png::BitDepth::Eight);
260    let mut w = enc.write_header().unwrap();
261    w.write_image_data(&pixels).unwrap();
262}