arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! ReflectiveCard 原生移植,参考 React Bits © David Haz,MIT + Commons Clause。
//! Props见Config;状态为hover/intro/media/error;动效复用arc-motion时钟、弹簧和指数平滑。
//! 原生GPU材质与内容统一透视,后台渲染;摄像头由宿主显式提供帧,本组件不申请设备权限。
use super::reflective_media::VideoReader;
pub use arc_graphics3d::ReflectiveTexture as ReflectiveCardTexture;
use arc_graphics3d::ReflectiveTexture;
use arc_graphics3d::{ReflectiveParams, ReflectiveRenderer};
use arc_motion::{
    ExponentialSmoother, arc_spring_with_options, is_reduced_motion, motion_now,
    spring::SpringOptions,
};
use arc_tokens::SpringSpec;
use gpui_kit::{
    App, Bounds, ElementId, Entity, Hsla, IntoElement, MouseMoveEvent, ParentElement, Pixels,
    RenderImage, RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window, bounds,
    canvas, div, point, prelude::*, px, size,
};
use std::{
    rc::Rc,
    sync::{Arc, Mutex},
    time::Duration,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ReflectiveCardTheme {
    #[default]
    Dark,
    Light,
}
#[derive(Clone, Debug)]
pub struct ReflectiveCardConfig {
    pub name: SharedString,
    pub role: SharedString,
    pub badge: SharedString,
    pub status: SharedString,
    pub status_color: Hsla,
    pub id_label: SharedString,
    pub id_value: SharedString,
    pub theme: ReflectiveCardTheme,
    pub video_src: SharedString,
    pub webcam: bool,
    pub tint: Hsla,
    pub metalness: f32,
    pub roughness: f32,
    pub blur_strength: f32,
    pub grayscale: f32,
    pub warp: f32,
    pub warp_scale: f32,
    pub shine: f32,
    pub bevel: f32,
    pub glare: f32,
    pub enable_tilt: bool,
    pub tilt_strength: f32,
    pub intro: bool,
    pub width: f32,
    pub height: f32,
    pub radius: f32,
}
impl Default for ReflectiveCardConfig {
    fn default() -> Self {
        Self {
            name: "Alexander Doe".into(),
            role: "Senior Developer".into(),
            badge: "Verified".into(),
            status: "Active".into(),
            status_color: gpui_kit::rgb(0x22c55e).into(),
            id_label: "ID number".into(),
            id_value: "8901 2345 6789".into(),
            theme: Default::default(),
            video_src: "".into(),
            webcam: false,
            tint: gpui_kit::rgb(0xffffff).into(),
            metalness: 1.,
            roughness: 0.3,
            blur_strength: 6.,
            grayscale: 1.,
            warp: 0.6,
            warp_scale: 1.,
            shine: 1.,
            bevel: 3.,
            glare: 0.5,
            enable_tilt: true,
            tilt_strength: 12.,
            intro: true,
            width: 320.,
            height: 500.,
            radius: 24.,
        }
    }
}
fn finite(v: f32, default: f32, lo: f32, hi: f32) -> f32 {
    if v.is_finite() {
        v.clamp(lo, hi)
    } else {
        default
    }
}
impl ReflectiveCardConfig {
    fn normalized(mut self) -> Self {
        macro_rules! clamp {
            ($f:ident,$d:expr,$lo:expr,$hi:expr) => {
                self.$f = finite(self.$f, $d, $lo, $hi);
            };
        }
        clamp!(metalness, 1., 0., 1.);
        clamp!(roughness, 0.3, 0., 1.);
        clamp!(blur_strength, 6., 0., 40.);
        clamp!(grayscale, 1., 0., 1.);
        clamp!(warp, 0.6, 0., 2.);
        clamp!(warp_scale, 1., 0.2, 4.);
        clamp!(shine, 1., 0., 3.);
        clamp!(bevel, 3., 0., 16.);
        clamp!(glare, 0.5, 0., 1.);
        clamp!(tilt_strength, 12., 0., 30.);
        clamp!(width, 320., 80., 1600.);
        clamp!(height, 500., 80., 1600.);
        clamp!(radius, 24., 0., 800.);
        self
    }
}
#[derive(Clone, Debug)]
pub struct ReflectiveCardError {
    pub message: SharedString,
}
type ErrorHandler = Rc<dyn Fn(&ReflectiveCardError, &mut Window, &mut App)>;
/// 外部视频/摄像头画面接口,RGBA8。revision变化才上传;摄像头帧可镜像。
#[derive(Clone)]
pub struct ReflectiveCardFrame {
    pub texture: ReflectiveTexture,
    pub revision: u64,
    pub mirrored: bool,
}
#[derive(IntoElement)]
pub struct ReflectiveCard {
    id: ElementId,
    config: ReflectiveCardConfig,
    frame: Option<ReflectiveCardFrame>,
    content_svg: Option<SharedString>,
    on_error: Option<ErrorHandler>,
    on_webcam_error: Option<ErrorHandler>,
    #[cfg(test)]
    probe: Option<Rc<std::cell::RefCell<Option<Entity<State>>>>>,
}
impl ReflectiveCard {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            config: Default::default(),
            frame: None,
            content_svg: None,
            on_error: None,
            on_webcam_error: None,
            #[cfg(test)]
            probe: None,
        }
    }
    pub fn config(mut self, config: ReflectiveCardConfig) -> Self {
        self.config = config;
        self
    }
    pub fn reflection_frame(mut self, frame: ReflectiveCardFrame) -> Self {
        self.frame = Some(frame);
        self
    }
    /// 原生内容插槽:透明SVG替换整层默认内容,与卡片一起投影;不执行脚本。
    pub fn content_svg(mut self, svg: impl Into<SharedString>) -> Self {
        self.content_svg = Some(svg.into());
        self
    }
    pub fn on_error(
        mut self,
        cb: impl Fn(&ReflectiveCardError, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_error = Some(Rc::new(cb));
        self
    }
    pub fn on_webcam_error(
        mut self,
        cb: impl Fn(&ReflectiveCardError, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_webcam_error = Some(Rc::new(cb));
        self
    }
}
struct State {
    target: [f32; 2],
    pointer: [f32; 2],
    hovered: bool,
    start: f64,
    light: ExponentialSmoother,
    renderer: Arc<Mutex<Option<Result<ReflectiveRenderer, String>>>>,
    busy: bool,
    image: Option<Arc<RenderImage>>,
    last: Option<(ReflectiveParams, u64, u64)>,
    ink_key: String,
    ink: Option<ReflectiveTexture>,
    ink_revision: u64,
    video: Option<VideoReader>,
    video_path: SharedString,
    video_polling: bool,
    webcam_reported: bool,
    error: Option<String>,
    reported: Option<String>,
}
fn xml(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}
fn color(c: Hsla) -> String {
    let c: gpui_kit::Rgba = c.into();
    format!(
        "rgb({},{},{})",
        (c.r * 255.).round(),
        (c.g * 255.).round(),
        (c.b * 255.).round()
    )
}
fn content(c: &ReflectiveCardConfig, w: f32, h: f32) -> String {
    let light = c.theme == ReflectiveCardTheme::Light;
    let ink = if light { "#18181b" } else { "#f4f4f5" };
    let tile = if light { "#fafafa" } else { "#302c3b" };
    let pad = (c.radius * 0.8).clamp(16., 22.).round();
    let tr = (c.radius * 0.5).clamp(8., 14.).round();
    let right = w - pad;
    let bottom = h - pad;
    let name_y = bottom - 98.;
    let badge = if c.badge.is_empty() {
        String::new()
    } else {
        format!(
            r#"<g transform="translate({pad},{pad})" fill="none" stroke="{ink}" stroke-width="1.5"><path d="M8 1l2 2 3 .5.5 3 2 2-2 2-.5 3-3 .5-2 2-2-2-3-.5-.5-3-2-2 2-2 .5-3 3-.5z"/><path d="M4.5 8l2.5 2.5 4-4"/></g><text x="{}" y="{}" font-size="13" font-weight="500">{}</text>"#,
            pad + 22.,
            pad + 13.,
            xml(&c.badge)
        )
    };
    let status = if c.status.is_empty() {
        String::new()
    } else {
        format!(
            r#"<circle cx="{}" cy="{}" r="3" fill="{}"/><text x="{right}" y="{}" text-anchor="end" opacity="0.6" font-size="13">{}</text>"#,
            right - 60.,
            pad + 9.,
            color(c.status_color),
            pad + 13.,
            xml(&c.status)
        )
    };
    let footer = if c.id_label.is_empty() && c.id_value.is_empty() {
        String::new()
    } else {
        format!(
            r#"<text x="{pad}" y="{}" font-size="12" opacity="0.6">{}</text><text x="{pad}" y="{}" font-size="15" font-family="monospace" letter-spacing="0.3">{}</text><g transform="translate({},{})"><rect width="44" height="44" rx="{tr}" fill="{tile}" stroke="{ink}" stroke-opacity="0.1"/><g transform="translate(11,10)" stroke="{ink}" opacity="0.6" fill="none" stroke-width="1.5" stroke-linecap="round"><path d="M3 9C3 0 19 0 19 9M0 9c0-12 22-12 22 0M7 10c0-5 8-5 8 0v6M3 12c0 8 4 11 8 11M7 14c0 5 4 6 4 6M11 10v5M19 12c0 4-1 7-3 9"/></g></g>"#,
            bottom - 29.,
            xml(&c.id_label),
            bottom - 5.,
            xml(&c.id_value),
            right - 44.,
            bottom - 44.
        )
    };
    format!(
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}"><defs><clipPath id="clip"><rect width="{w}" height="{h}" rx="{}"/></clipPath></defs><g clip-path="url(#clip)" fill="{ink}" font-family="sans-serif">{badge}{status}<text x="{pad}" y="{name_y}" font-size="24" font-weight="500" letter-spacing="-0.48">{}</text><text x="{pad}" y="{}" font-size="14" opacity="0.6">{}</text>{footer}</g></svg>"#,
        c.radius,
        xml(&c.name),
        name_y + 25.,
        xml(&c.role)
    )
}
fn rgba_texture(image: &RenderImage) -> Option<ReflectiveTexture> {
    let s = image.size(0);
    let mut bytes = image.as_bytes(0)?.to_vec();
    for p in bytes.chunks_exact_mut(4) {
        p.swap(0, 2);
    }
    ReflectiveTexture::new(s.width.0 as u32, s.height.0 as u32, bytes).ok()
}
fn poll_video(st: &Entity<State>, window: &mut Window, cx: &mut App) {
    if st.read(cx).video_polling {
        return;
    }
    st.update(cx, |s, _| s.video_polling = true);
    let weak = st.downgrade();
    window
        .spawn(cx, async move |cx| {
            loop {
                cx.background_executor()
                    .timer(Duration::from_millis(42))
                    .await;
                let keep = cx
                    .update(|window, cx| {
                        let Some(st) = weak.upgrade() else {
                            return false;
                        };
                        let keep = st.read(cx).video.as_ref().is_some_and(|v| {
                            !v.state.lock().unwrap_or_else(|e| e.into_inner()).ended
                        });
                        if !keep {
                            st.update(cx, |s, _| s.video_polling = false);
                        }
                        window.refresh();
                        keep
                    })
                    .unwrap_or(false);
                if !keep {
                    break;
                }
            }
        })
        .detach();
}
impl RenderOnce for ReflectiveCard {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let c = self.config.normalized();
        let now = motion_now(cx);
        let reduced = is_reduced_motion(cx);
        let intro = c.intro && !reduced;
        let st = window.use_keyed_state((self.id.clone(), "reflective-state"), cx, |window, cx| {
            cx.on_release_in(window, |s: &mut State, window, _| {
                if let Some(image) = s.image.take() {
                    let _ = window.drop_image(image);
                }
                s.video = None;
            })
            .detach();
            State {
                target: [0.; 2],
                pointer: [0.; 2],
                hovered: false,
                start: now,
                light: ExponentialSmoother::new(if intro { 1. } else { 0. }, now),
                renderer: Arc::new(Mutex::new(None)),
                busy: false,
                image: None,
                last: None,
                ink_key: String::new(),
                ink: None,
                ink_revision: 0,
                video: None,
                video_path: "".into(),
                video_polling: false,
                webcam_reported: false,
                error: None,
                reported: None,
            }
        });
        #[cfg(test)]
        if let Some(probe) = &self.probe {
            *probe.borrow_mut() = Some(st.clone());
        }
        let source = if reduced {
            "".into()
        } else {
            c.video_src.clone()
        };
        if st.read(cx).video_path != source {
            st.update(cx, |s, _| {
                s.video = None;
                s.video_path = source.clone();
                s.video = (!source.is_empty()).then(|| VideoReader::start(&source));
            });
        }
        if st
            .read(cx)
            .video
            .as_ref()
            .is_some_and(|video| !video.state.lock().unwrap_or_else(|e| e.into_inner()).ended)
        {
            poll_video(&st, window, cx);
        }
        if c.webcam && self.frame.is_none() && !st.read(cx).webcam_reported {
            st.update(cx, |s, _| s.webcam_reported = true);
            if let Some(cb) = self.on_webcam_error.clone() {
                window.defer(cx,move|window,cx|cb(&ReflectiveCardError{message:"原生摄像头采集未接入,请由宿主授权后通过 reflection_frame 提供镜像画面;当前回退视频/软棚".into()},window,cx));
            }
        }
        if !c.webcam {
            st.update(cx, |s, _| s.webcam_reported = false);
        }
        if let Some(error) = st.read(cx).error.clone()
            && st.read(cx).reported.as_ref() != Some(&error)
        {
            st.update(cx, |s, _| s.reported = Some(error.clone()));
            if let Some(cb) = self.on_error {
                window.defer(cx, move |window, cx| {
                    cb(
                        &ReflectiveCardError {
                            message: error.into(),
                        },
                        window,
                        cx,
                    )
                });
            }
        }
        let elapsed = (now - st.read(cx).start).max(0.);
        let slow = intro && elapsed < 1.4;
        let spring =
            SpringSpec::physics(if slow { 24. } else { 120. }, if slow { 9. } else { 16. });
        let mut axes = [0.; 2];
        for (i, channel) in ["reflective-x", "reflective-y"].into_iter().enumerate() {
            let target = if c.enable_tilt && !reduced {
                st.read(cx).target[i]
            } else {
                0.
            };
            let options = SpringOptions::new(spring)
                .with_initial_value(if intro {
                    if i == 0 { 0.62 } else { -0.55 }
                } else {
                    0.
                })
                .with_travel(!reduced);
            axes[i] =
                arc_spring_with_options((self.id.clone(), channel), target, options, window, cx)
                    .value;
        }
        let presence = if intro {
            1. - (1. - (elapsed as f32 / 0.65).clamp(0., 1.)).powi(3)
        } else {
            1.
        };
        let light = st.update(cx, |s, _| {
            let target = if s.hovered { 1. } else { 0. };
            let tau = if target > s.light.value() {
                180.
            } else if slow {
                900.
            } else {
                450.
            };
            s.light.advance(target, now, tau, reduced) as f32
        });
        if presence < 1. || (light - if st.read(cx).hovered { 1. } else { 0. }).abs() > 0.002 {
            window.request_animation_frame();
        }
        let s_down = st.clone();
        let s_hover = st.clone();
        let s_paint = st.clone();
        let external = self.frame;
        let svg = self.content_svg;
        div()
            .id(self.id)
            .test_support()
            .w(px(c.width))
            .max_w_full()
            .h(px(c.height))
            .flex_shrink_0()
            .relative()
            .role(Role::Group)
            .aria_label(format!(
                "{} · {} · {} · {}",
                c.name, c.role, c.status, c.id_value
            ))
            .on_hover(move |hovered, window, cx| {
                s_hover.update(cx, |s, _| {
                    s.hovered = *hovered;
                    if !hovered {
                        s.target = [0.; 2];
                    }
                });
                window.refresh();
            })
            .on_mouse_move(move |e: &MouseMoveEvent, window, cx| {
                s_down.update(cx, |s, _| {
                    if s.hovered {
                        s.pointer = [e.position.x.as_f32(), e.position.y.as_f32()];
                    }
                });
                window.refresh();
            })
            .child(
                canvas(
                    |b, _, _| b,
                    move |b: Bounds<Pixels>, _, window, cx| {
                        // pointer坐标以当前布局为准,resize不保留旧的归一化位置。
                        let w = b.size.width.as_f32().max(1.);
                        let h = b.size.height.as_f32().max(1.);
                        let (pointer, hovered) = {
                            let s = s_paint.read(cx);
                            (s.pointer, s.hovered)
                        };
                        let pointer = [
                            (pointer[0] - b.center().x.as_f32()).clamp(-w * 0.5, w * 0.5),
                            (pointer[1] - b.center().y.as_f32()).clamp(-h * 0.5, h * 0.5),
                        ];
                        if hovered {
                            let target = [pointer[0] / (w * 0.5), pointer[1] / (h * 0.5)];
                            if s_paint.read(cx).target != target {
                                s_paint.update(cx, |s, _| s.target = target);
                                window.request_animation_frame();
                            }
                        }
                        let svg = svg
                            .as_ref()
                            .map(|s| s.to_string())
                            .unwrap_or_else(|| content(&c, w, h));
                        let ink_key = format!("{w}|{h}|{svg}");
                        if s_paint.read(cx).ink_key != ink_key {
                            match cx.svg_renderer().render_single_frame(svg.as_bytes(), 1.) {
                                Ok(image) => {
                                    let texture = rgba_texture(&image);
                                    s_paint.update(cx, |s, _| {
                                        s.ink = texture;
                                        s.ink_key = ink_key;
                                        s.ink_revision += 1;
                                    });
                                }
                                Err(e) => {
                                    s_paint.update(cx, |s, _| {
                                        s.error = Some(format!("内容SVG无效:{e}"))
                                    });
                                }
                            }
                        }
                        let mut env = external.as_ref().map(|f| f.texture.clone());
                        let mut rev = external.as_ref().map_or(0, |f| f.revision);
                        let mut mirror = external.as_ref().is_some_and(|f| f.mirrored);
                        if env.is_none()
                            && let Some(video) = s_paint.read(cx).video.as_ref()
                        {
                            let source = video.state.lock().unwrap_or_else(|e| e.into_inner());
                            if source.error.is_some() {
                                let error = source.error.clone();
                                drop(source);
                                s_paint.update(cx, |s, _| s.error = error);
                            } else {
                                env = source.frame.clone();
                                rev = source.revision;
                                mirror = false;
                            }
                        }
                        let mut mean = 0.5;
                        if let Some(env) = &env {
                            let mut sum = 0.;
                            let mut n: f32 = 0.;
                            for p in env.rgba.chunks_exact(4).step_by(64) {
                                sum += 0.2126 * (p[0] as f32 / 255.).powf(2.2)
                                    + 0.7152 * (p[1] as f32 / 255.).powf(2.2)
                                    + 0.0722 * (p[2] as f32 / 255.).powf(2.2);
                                n += 1.;
                            }
                            mean = (sum / n.max(1.)).powf(1. / 2.2);
                        }
                        let tint: gpui_kit::Rgba = c.tint.into();
                        let pad = (w.max(h) * 0.25 + 24.).min(440.);
                        let angle = if c.enable_tilt && !reduced {
                            c.tilt_strength.to_radians()
                        } else {
                            0.
                        };
                        let p = ReflectiveParams {
                            size: [w, h, c.radius, pad],
                            pose: [
                                axes[1] * angle,
                                -axes[0] * angle,
                                presence,
                                (1. - presence) * 14.,
                            ],
                            material: [c.metalness, c.roughness, c.blur_strength, c.grayscale],
                            effects: [c.warp, c.warp_scale, c.shine, c.bevel],
                            light: [
                                c.glare * light,
                                pointer[0],
                                pointer[1],
                                if c.theme == ReflectiveCardTheme::Light {
                                    1.
                                } else {
                                    0.
                                },
                            ],
                            tint: [
                                tint.r.powf(2.2),
                                tint.g.powf(2.2),
                                tint.b.powf(2.2),
                                if env.is_some() { 1. } else { 0. },
                            ],
                            source: [
                                if mirror { 1. } else { 0. },
                                env.as_ref()
                                    .map_or(1., |e| e.width as f32 / e.height as f32),
                                mean,
                                window.scale_factor().min(2.),
                            ],
                        };
                        // 不同源可以从相同revision起步,合并像素Arc身份避免误复用旧视频。
                        if let Some(frame) = &env {
                            rev ^= Arc::as_ptr(&frame.rgba) as *const u8 as usize as u64;
                        }
                        let revisions = (s_paint.read(cx).ink_revision, rev);
                        let key = (p, revisions.0, revisions.1);
                        if !s_paint.read(cx).busy
                            && s_paint.read(cx).last != Some(key)
                            && let Some(ink) = s_paint.read(cx).ink.clone()
                        {
                            let renderer = s_paint.read(cx).renderer.clone();
                            let weak = s_paint.downgrade();
                            s_paint.update(cx, |s, _| s.busy = true);
                            window
                                .spawn(cx, async move |cx| {
                                    let result = cx
                                        .background_executor()
                                        .spawn(async move {
                                            let mut guard =
                                                renderer.lock().unwrap_or_else(|e| e.into_inner());
                                            let r =
                                                guard.get_or_insert_with(ReflectiveRenderer::new);
                                            match r {
                                                Ok(r) => r.render(p, &ink, env.as_ref(), revisions),
                                                Err(e) => Err(e.clone()),
                                            }
                                        })
                                        .await;
                                    let _ = cx.update(|window, cx| {
                                        if let Some(st) = weak.upgrade() {
                                            st.update(cx, |s, _| {
                                                s.busy = false;
                                                s.last = Some(key);
                                                match result {
                                                    Ok((bytes, w, h)) => {
                                                        if let Some(old) = s.image.take() {
                                                            let _ = window.drop_image(old);
                                                        }
                                                        s.image =
                                                            Some(Arc::new(RenderImage::new(vec![
                                                                image::Frame::new(
                                                                    image::RgbaImage::from_raw(
                                                                        w,
                                                                        h,
                                                                        bytes.to_vec(),
                                                                    )
                                                                    .expect("GPU帧尺寸已验证"),
                                                                ),
                                                            ])));
                                                    }
                                                    Err(e) => s.error = Some(e),
                                                }
                                            });
                                            window.refresh();
                                        }
                                    });
                                })
                                .detach();
                        }
                        let image = s_paint.read(cx).image.clone();
                        if let Some(image) = image {
                            let dest = bounds(
                                point(b.left() - px(pad), b.top() - px(pad)),
                                size(px(w + pad * 2.), px(h + pad * 2.)),
                            );
                            let _ =
                                window.paint_image(dest, dest, Default::default(), image, 0, false);
                        } else {
                            window.paint_quad(gpui_kit::fill(
                                b,
                                if c.theme == ReflectiveCardTheme::Light {
                                    gpui_kit::rgb(0xe7e7ea)
                                } else {
                                    gpui_kit::rgb(0x1d1c22)
                                },
                            ));
                        }
                    },
                )
                .size_full(),
            )
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, TestAppContext,
        test::{TestEventExt as _, TestWindowExt as _},
    };
    struct Host {
        config: ReflectiveCardConfig,
        probe: Rc<std::cell::RefCell<Option<Entity<State>>>>,
        errors: usize,
    }
    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let mut card = ReflectiveCard::new("rc-test");
            card.probe = Some(self.probe.clone());
            div()
                .w(px(400.))
                .h(px(600.))
                .child(
                    card.config(self.config.clone())
                        .on_webcam_error(cx.listener(|this, _, _, cx| {
                            this.errors += 1;
                            cx.notify();
                        })),
                )
        }
    }
    #[gpui_kit::test]
    fn reflective_card_hover_leave_reduced_and_camera_error(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| Host {
            config: ReflectiveCardConfig {
                webcam: true,
                ..Default::default()
            },
            probe: Default::default(),
            errors: 0,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
            assert_eq!(view.read(cx).errors, 1);
            let st = view.read(cx).probe.borrow().as_ref().unwrap().clone();
            assert!(st.read(cx).webcam_reported);
            assert!(st.read(cx).video.is_none());
            let rect = window.find("rc-test").bounds();
            assert_eq!(rect.size.width, px(320.));
            window.pointer_move(rect.center() + point(px(80.), px(80.)), None, cx);
            window.render_frame(cx);
            window.render_frame(cx);
            assert!(st.read(cx).hovered);
            assert!(st.read(cx).target[0] > 0.);
            window.pointer_move(point(px(1000.), px(1000.)), None, cx);
            window.render_frame(cx);
            assert_eq!(st.read(cx).target, [0.; 2]);
            view.update(cx, |v, cx| {
                v.config.webcam = false;
                v.config.theme = ReflectiveCardTheme::Light;
                v.config.width = 800.;
                cx.notify();
            });
            window.render_frame(cx);
            assert!(window.find("rc-test").bounds().size.width <= px(400.));
            assert!(!st.read(cx).webcam_reported);
        });
    }
    #[test]
    fn reflective_card_defaults_and_ranges() {
        let c = ReflectiveCardConfig::default();
        assert_eq!((c.width, c.height, c.radius), (320., 500., 24.));
        assert!(!c.webcam);
        let c = ReflectiveCardConfig {
            warp_scale: 0.,
            metalness: f32::NAN,
            tilt_strength: 99.,
            ..c
        }
        .normalized();
        assert_eq!((c.warp_scale, c.metalness, c.tilt_strength), (0.2, 1., 30.));
    }
    #[test]
    fn reflective_card_content_escaping_and_theme() {
        let c = ReflectiveCardConfig {
            name: "<Eighteen & Arc>".into(),
            ..Default::default()
        };
        let s = content(&c, 320., 500.);
        assert!(s.contains("&lt;Eighteen &amp; Arc&gt;"));
        assert!(s.contains("#f4f4f5"));
        assert!(s.contains("Verified"));
        let c = ReflectiveCardConfig {
            theme: ReflectiveCardTheme::Light,
            badge: "".into(),
            status: "".into(),
            ..c
        };
        let s = content(&c, 320., 500.);
        assert!(s.contains("#18181b"));
        assert!(!s.contains("Verified"));
    }
}