lieui 0.2.0-beta.1

A Rust GUI library with C/S architecture and builder-driven UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! VelloRenderer — 基于 liecharts PixmapRenderer 模式
//!
//! RenderContext + set_paint + fill_rect/fill_path + glyph_run + render_to_pixmap
//! 文本渲染使用 parley TextLayout 中的 glyph 数据 + vello_cpu glyph_run

use vello_cpu::kurbo::{Affine, BezPath, Circle, Rect, Shape, Stroke as KurboStroke};
use vello_cpu::peniko::color::AlphaColor;
use vello_cpu::{CompositeMode, Pixmap, RasterizerSettings, RenderContext, Resources};

use crate::render::renderer::Renderer;
use crate::render::visual::{LayeredElement, Stroke, VisualElement};
use crate::view::paint::ImageFit;

pub struct VelloRenderer {
    ctx: RenderContext,
    resources: Resources,
    width: u16,
    height: u16,
}

impl VelloRenderer {
    pub fn new(w: u16, h: u16) -> Self {
        Self {
            ctx: RenderContext::new(w, h),
            resources: Resources::new(),
            width: w,
            height: h,
        }
    }
    pub fn resize(&mut self, w: u16, h: u16) {
        self.width = w;
        self.height = h;
        self.ctx = RenderContext::new(w, h);
    }
    pub fn width(&self) -> u16 {
        self.width
    }
    pub fn height(&self) -> u16 {
        self.height
    }

    fn cv(c: &crate::geometry::Color) -> AlphaColor<vello_cpu::color::Srgb> {
        c.as_vello()
    }

    fn apply_fill(&mut self, fill: &crate::geometry::Color, rect: &Rect) {
        self.ctx.set_paint(Self::cv(fill));
        self.ctx.fill_rect(rect);
    }

    fn apply_stroke(&mut self, stroke: &Stroke) {
        self.ctx.set_paint(Self::cv(&stroke.color));
        self.ctx.set_stroke(KurboStroke::new(stroke.width));
    }
}

impl Renderer for VelloRenderer {
    fn render(&mut self, elements: &[LayeredElement]) -> Pixmap {
        let w = self.width;
        let h = self.height;
        let mut pix = Pixmap::new(w, h);

        // 背景填充(最低层,之后每层都以 SrcOver 合成到其上)。
        self.ctx
            .set_paint(AlphaColor::from_rgba8(240, 240, 240, 255));
        self.ctx.fill_rect(&Rect::new(0.0, 0.0, w as f64, h as f64));
        self.ctx.flush();
        self.ctx.render(&mut pix, &mut self.resources);
        // 清空命令列表,避免后续层级重复绘制背景。
        self.ctx.reset();

        // 关键:Image 与矢量元素必须按真实 z 顺序合成。
        // 若把所有 Image 后处理 blit 到最顶层,会遮挡 Content 之上更高 z 的
        // Modal / Overlay 等内容(例如 pdfkit 预览图盖住退出确认弹窗)。
        // 因此按 z 升序分组:每一层先绘制矢量元素,再 blit 该层图像,逐层叠加。
        let mut sorted: Vec<&LayeredElement> = elements.iter().collect();
        sorted.sort_by_key(|e| e.z_index());

        // 同 z 层内的 Image 及其裁剪区域。
        let mut images: Vec<(LayeredElement, Option<Rect>)> = Vec::new();
        let mut idx = 0;
        while idx < sorted.len() {
            let z = sorted[idx].z_index();
            images.clear();
            // 收集并绘制当前 z 层级的全部元素(矢量元素直接入 ctx,Image 记录待 blit)。
            while idx < sorted.len() && sorted[idx].z_index() == z {
                self.render_element(sorted[idx], &mut images, None);
                idx += 1;
            }
            // 将该层矢量元素以 SrcOver 合成到 pix,再 blit 该层图像。
            self.ctx.flush();
            self.ctx.render_with(
                &mut pix,
                &mut self.resources,
                RasterizerSettings {
                    composite_mode: CompositeMode::SrcOver,
                    ..Default::default()
                },
            );
            for (img, clip) in &images {
                Self::blit_image(&mut pix, img, *clip);
            }
            // 清空命令列表,下一 z 层只携带自身的绘制命令。
            self.ctx.reset();
        }
        pix
    }
}

impl VelloRenderer {
    /// 递归渲染元素。Image 被收集到 `images` 中;Group 的 clip_rect 会作为当前裁剪区域传给子元素。
    fn render_element(
        &mut self,
        el: &LayeredElement,
        images: &mut Vec<(LayeredElement, Option<Rect>)>,
        current_clip: Option<Rect>,
    ) {
        match &el.element {
            VisualElement::Image { .. } => {
                images.push((el.clone(), current_clip));
            }
            VisualElement::Group {
                children,
                clip_rect,
                ..
            } => {
                let next_clip = match (current_clip, *clip_rect) {
                    (Some(parent), Some(child)) => Some(parent.intersect(child)),
                    (Some(parent), None) => Some(parent),
                    (None, Some(child)) => Some(child),
                    (None, None) => None,
                };
                if let Some(clip) = clip_rect {
                    self.ctx.push_clip_path(&clip.to_path(0.1));
                    for c in children {
                        self.render_element(c, images, next_clip);
                    }
                    self.ctx.pop_clip_path();
                } else {
                    for c in children {
                        self.render_element(c, images, next_clip);
                    }
                }
            }
            _ => {
                // 视口剔除:元素完全在裁剪区外时不提交绘制。
                if let Some(clip) = current_clip
                    && let Some(bbox) = el.element.bounding_rect()
                    && (clip.x1 <= bbox.x0
                        || clip.x0 >= bbox.x1
                        || clip.y1 <= bbox.y0
                        || clip.y0 >= bbox.y1)
                {
                    if crate::perf::enabled() {
                        eprintln!(
                            "[clip] skip  bbox=({:.1},{:.1})-({:.1},{:.1}) \
                                     clip=({:.1},{:.1})-({:.1},{:.1})",
                            bbox.x0, bbox.y0, bbox.x1, bbox.y1, clip.x0, clip.y0, clip.x1, clip.y1,
                        );
                    }
                    return; // 完全在裁剪区外,跳过
                }
                self.draw(&el.element)
            }
        }
    }

    /// 在 Pixmap 上直接 blit RGBA 图像数据,可选按 `clip` 矩形裁剪。
    fn blit_image(pix: &mut vello_cpu::Pixmap, img: &LayeredElement, clip: Option<Rect>) {
        if let VisualElement::Image {
            bounds,
            data,
            width,
            height,
            opacity,
            fit,
            border_radius,
            ..
        } = &img.element
        {
            let pw = pix.width() as usize;
            let ph = pix.height() as usize;
            let img_w = *width as f64;
            let img_h = *height as f64;
            if img_w <= 0.0 || img_h <= 0.0 || data.len() < 4 {
                return;
            }
            let bw = bounds.width();
            let bh = bounds.height();
            if bw <= 0.0 || bh <= 0.0 {
                return;
            }

            // 依据 fit 计算图像在容器中的绘制矩形(绘制坐标,左上角原点)。
            let (dw, dh, dx0, dy0) = match fit {
                ImageFit::None => (img_w, img_h, bounds.x0, bounds.y0),
                ImageFit::Fill => (bw, bh, bounds.x0, bounds.y0),
                ImageFit::Contain => {
                    let s = (bw / img_w).min(bh / img_h);
                    let dw = img_w * s;
                    let dh = img_h * s;
                    (
                        dw,
                        dh,
                        bounds.x0 + (bw - dw) / 2.0,
                        bounds.y0 + (bh - dh) / 2.0,
                    )
                }
                ImageFit::Cover => {
                    let s = (bw / img_w).max(bh / img_h);
                    let dw = img_w * s;
                    let dh = img_h * s;
                    (
                        dw,
                        dh,
                        bounds.x0 + (bw - dw) / 2.0,
                        bounds.y0 + (bh - dh) / 2.0,
                    )
                }
            };

            // 把外层 clip 与绘制矩形相交,减少逐像素判断。
            let clip = match clip {
                Some(c) => {
                    let x0 = c.x0.max(dx0);
                    let y0 = c.y0.max(dy0);
                    let x1 = c.x1.min(dx0 + dw);
                    let y1 = c.y1.min(dy0 + dh);
                    if x1 > x0 && y1 > y0 {
                        Some(Rect::new(x0, y0, x1, y1))
                    } else {
                        None
                    }
                }
                None => None,
            };

            let op = opacity.unwrap_or(1.0).clamp(0.0, 1.0);
            let radius = *border_radius;
            let iw = *width as usize;
            let ih = *height as usize;
            let d = pix.data_mut();

            let cols = dw.ceil() as usize;
            let rows = dh.ceil() as usize;
            for py in 0..rows {
                let dy = (dy0 + py as f64) as usize;
                if dy >= ph {
                    break;
                }
                for px in 0..cols {
                    let dx = (dx0 + px as f64) as usize;
                    if dx >= pw {
                        break;
                    }
                    if let Some(c) = clip {
                        let fx = dx as f64 + 0.5;
                        let fy = dy as f64 + 0.5;
                        if fx < c.x0 || fx >= c.x1 || fy < c.y0 || fy >= c.y1 {
                            continue;
                        }
                    }
                    // 圆角裁剪:超出圆角矩形外的像素跳过。
                    if radius > 0.5 {
                        let r = (radius as f64).min(dw / 2.0).min(dh / 2.0);
                        let in_corner_x = (dx as f64) < dx0 + r || (dx as f64) > dx0 + dw - r;
                        let in_corner_y = (dy as f64) < dy0 + r || (dy as f64) > dy0 + dh - r;
                        let inside = if in_corner_x && in_corner_y {
                            let ccx = if (dx as f64) < dx0 + r {
                                dx0 + r
                            } else {
                                dx0 + dw - r
                            };
                            let ccy = if (dy as f64) < dy0 + r {
                                dy0 + r
                            } else {
                                dy0 + dh - r
                            };
                            let ddx = dx as f64 - ccx;
                            let ddy = dy as f64 - ccy;
                            ddx * ddx + ddy * ddy <= r * r
                        } else {
                            true
                        };
                        if !inside {
                            continue;
                        }
                    }
                    // 由目标像素反算源像素(最近邻采样)。
                    let mut sx = ((px as f64 / dw) * img_w) as usize;
                    let mut sy = ((py as f64 / dh) * img_h) as usize;
                    if sx >= iw {
                        sx = iw - 1;
                    }
                    if sy >= ih {
                        sy = ih - 1;
                    }
                    let si = (sy * iw + sx) * 4;
                    if si + 3 >= data.len() {
                        continue;
                    }
                    let r = data[si];
                    let g = data[si + 1];
                    let b = data[si + 2];
                    let a = data[si + 3];
                    if a == 0 {
                        continue;
                    }
                    let final_a = (a as f32 * op) as u8;
                    let alpha = final_a as f32 / 255.0;
                    let r = (r as f32 * alpha) as u8;
                    let g = (g as f32 * alpha) as u8;
                    let b = (b as f32 * alpha) as u8;
                    d[dy * pw + dx] =
                        vello_cpu::color::PremulRgba8::from_u8_array([r, g, b, final_a]);
                }
            }
        }
    }

    fn draw(&mut self, el: &VisualElement) {
        match el {
            VisualElement::Rect { rect, style } => {
                if let Some(f) = &style.fill {
                    self.apply_fill(f, rect);
                }
                if let Some(s) = &style.stroke {
                    self.apply_stroke(s);
                    self.ctx.stroke_rect(rect);
                }
            }
            VisualElement::RoundedRect {
                rect,
                radius: r,
                style,
            } => {
                if let Some(f) = &style.fill {
                    if *r < 0.5 {
                        // radius 为 0 时直接矩形填充
                        self.apply_fill(f, rect);
                    } else {
                        // 普通圆角矩形路径填充。
                        // 注意不要用 fill_blurred_rounded_rect(std_dev=0):
                        // 那是高斯模糊专用路径,每像素代价比路径填充高一个量级。
                        let rr = vello_cpu::kurbo::RoundedRect::from_rect(*rect, *r);
                        self.ctx.set_paint(Self::cv(f));
                        self.ctx.fill_path(&rr.to_path(0.1));
                    }
                }
                if let Some(s) = &style.stroke {
                    self.apply_stroke(s);
                    if *r < 0.5 {
                        self.ctx.stroke_rect(rect);
                    } else {
                        let rr = vello_cpu::kurbo::RoundedRect::from_rect(*rect, *r);
                        self.ctx.stroke_path(&rr.to_path(0.1));
                    }
                }
            }
            VisualElement::ShadowRoundedRect {
                rect,
                radius,
                std_dev,
                color,
            } => {
                self.ctx.set_paint(Self::cv(color));
                self.ctx
                    .fill_blurred_rounded_rect(rect, *radius as f32, *std_dev as f32, false);
            }
            VisualElement::Circle {
                center,
                radius,
                style,
            } => {
                let circle = Circle::new(*center, *radius);
                let path = circle.to_path(0.1);
                if let Some(f) = &style.fill {
                    self.ctx.set_paint(Self::cv(f));
                    self.ctx.fill_path(&path);
                }
                if let Some(s) = &style.stroke {
                    self.apply_stroke(s);
                    self.ctx.stroke_path(&path);
                }
            }
            VisualElement::Line { start, end, style } => {
                let mut path = BezPath::new();
                path.move_to(*start);
                path.line_to(*end);
                self.ctx.set_paint(Self::cv(&style.color));
                self.ctx.set_stroke(KurboStroke::new(style.width));
                self.ctx.stroke_path(&path);
            }
            VisualElement::Path { path, style } => {
                if let Some(f) = &style.fill {
                    self.ctx.set_paint(Self::cv(f));
                    self.ctx.fill_path(path);
                }
                if let Some(s) = &style.stroke {
                    self.apply_stroke(s);
                    self.ctx.stroke_path(path);
                }
            }
            VisualElement::TextRun {
                text,
                position,
                color,
                font_size: _,
                rotation,
                layout,
                ..
            } => {
                let layout = match layout {
                    Some(l) => l,
                    None => return,
                };
                let transform =
                    Affine::translate((position.x, position.y)) * Affine::rotate(*rotation);

                for line in layout.lines() {
                    for item in line.items() {
                        if let parley::layout::PositionedLayoutItem::GlyphRun(glyph_run) = item {
                            let run = glyph_run.run();
                            let font_data = run.font();
                            let run_font_size = run.font_size();

                            let glyphs: Vec<vello_cpu::Glyph> = glyph_run
                                .positioned_glyphs()
                                .map(|g| vello_cpu::Glyph {
                                    id: g.id,
                                    x: g.x,
                                    y: g.y,
                                })
                                .collect();

                            if glyphs.is_empty() {
                                continue;
                            }

                            self.ctx.set_paint(Self::cv(color));
                            self.ctx
                                .glyph_run(&mut self.resources, font_data)
                                .font_size(run_font_size)
                                .glyph_transform(transform)
                                .fill_glyphs(glyphs.into_iter());
                        }
                    }
                }
                // suppress unused warning for `text`
                let _ = text;
            }
            VisualElement::Image { bounds, .. } => {
                self.ctx
                    .set_paint(AlphaColor::from_rgba8(200, 200, 200, 128));
                self.ctx.fill_rect(bounds);
            }
            VisualElement::Group { .. } => {
                // Group 由 render_element 处理,这里不应直接遇到。
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::Color;
    use crate::render::renderer::Renderer;
    use crate::render::visual::{FillStrokeStyle, KRect, LayeredElement, VisualElement};
    use std::sync::Arc;

    #[test]
    fn group_clip_rect_crops_children() {
        let mut renderer = VelloRenderer::new(100, 100);
        // 一个红色大矩形,但被 Group 的 clip_rect (0,0,50,50) 裁剪。
        let elements = vec![LayeredElement::new(
            VisualElement::Group {
                children: vec![LayeredElement::new(
                    VisualElement::Rect {
                        rect: KRect::new(0.0, 0.0, 100.0, 100.0),
                        style: FillStrokeStyle::new().with_fill(Color::RED),
                    },
                    0,
                )],
                transform: None,
                clip_rect: Some(KRect::new(0.0, 0.0, 50.0, 50.0)),
            },
            0,
        )];

        let pix = renderer.render(&elements);
        let data = pix.data();
        let w = pix.width() as usize;

        // clip 区域内应为红色
        let inside = data[25 * w + 25];
        assert_eq!(
            inside,
            vello_cpu::color::PremulRgba8::from_u8_array([255, 0, 0, 255])
        );

        // clip 区域外应保持默认背景色 (240,240,240)
        let outside = data[75 * w + 75];
        assert_eq!(
            outside,
            vello_cpu::color::PremulRgba8::from_u8_array([240, 240, 240, 255])
        );
    }

    #[test]
    fn blit_image_premultiplies_straight_rgba() {
        let mut pix = Pixmap::new(2, 2);
        // 直链 RGBA:半透明红色,alpha=128,r=255
        let img_data = Arc::new(vec![
            255, 0, 0, 128, 255, 0, 0, 128, 255, 0, 0, 128, 255, 0, 0, 128,
        ]);
        let img = LayeredElement::new(
            VisualElement::Image {
                bounds: KRect::new(0.0, 0.0, 2.0, 2.0),
                data: img_data,
                width: 2,
                height: 2,
                opacity: Some(1.0),
                fit: ImageFit::Fill,
                border_radius: 0.0,
            },
            0,
        );

        VelloRenderer::blit_image(&mut pix, &img, None);

        let data = pix.data();
        // 预乘后 r 应被 alpha 缩放:255 * 128 / 255 = 128
        let expected = vello_cpu::color::PremulRgba8::from_u8_array([128, 0, 0, 128]);
        for p in data {
            assert_eq!(*p, expected);
        }
    }

    #[test]
    fn blit_image_keeps_opaque_rgba_unchanged() {
        let mut pix = Pixmap::new(1, 1);
        let img_data = Arc::new(vec![255, 128, 64, 255]);
        let img = LayeredElement::new(
            VisualElement::Image {
                bounds: KRect::new(0.0, 0.0, 1.0, 1.0),
                data: img_data,
                width: 1,
                height: 1,
                opacity: Some(1.0),
                fit: ImageFit::Fill,
                border_radius: 0.0,
            },
            0,
        );

        VelloRenderer::blit_image(&mut pix, &img, None);

        assert_eq!(
            pix.data()[0],
            vello_cpu::color::PremulRgba8::from_u8_array([255, 128, 64, 255])
        );
    }
}