mgui-core 0.6.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! 属性轨道的 widget/state 接线 —— 体系:同一套 widget 吃任意轨道实现。
//!
//! 轨道实现有两种([`PropertyTrack`] 时长+曲线、[`SpringTrack`] 带速度可过冲),
//! 但 widget/state 只持有统一的 [`SharedTrack`] 句柄,不为每种轨道复制一套
//! `AnimatedXxxWidget` —— 避免"轨道类型 × 属性"的 N×M 样板。工厂函数决定底层:
//! `opacity_track()` 建曲线轨道、`spring_opacity_track()` 建弹簧轨道,返回的
//! 都是同一个 `SharedTrack<f32>`,可传给同一个 `AnimatedOpacityWidget`。
//!
//! 关键(为什么不是 `AnimationController`):
//! - `AnimationController` 走 Signal → mark_dirty → rebuild,违反"不逐帧重建 Widget"。
//! - 本 widget 的 track 存在 State 里,`State::tick` 推进;RO 通过 `apply_state`
//!   就地读 presented 值。全程不 mount/update、不 create_render_object。

use super::{State, Widget, WidgetNode};
use crate::render_object::{
    OpacityRenderObject, PositionedRenderObject, RRectRenderObject, RenderObject, StateApply, TransformRenderObject,
};
use crate::{Color, Curve, Point, PropertyTrack, SharedTrack, Spring, SpringTrack, Transform2D};
use std::any::Any;
use std::cell::RefCell;
use std::rc::Rc;

/// 可共享轨道句柄(兼容别名):统一到 [`SharedTrack`],底层可为曲线或弹簧轨道。
pub type SharedPropertyTrack<T> = SharedTrack<T>;
/// 弹簧轨道句柄(兼容别名):与 [`SharedPropertyTrack`] 是同一类型。
pub type SharedSpringTrack<T> = SharedTrack<T>;

/// 建一条弹簧 opacity 轨道(初始 1.0,弹簧参数)。
pub fn spring_opacity_track(initial: f32, spring: Spring) -> SharedTrack<f32> {
    Rc::new(RefCell::new(SpringTrack::new(initial, spring)))
}

/// 建一条弹簧 scale 轨道(初始 1.0,弹簧参数)。
pub fn spring_scale_track(initial: f32, spring: Spring) -> SharedTrack<f32> {
    Rc::new(RefCell::new(SpringTrack::new(initial, spring)))
}

/// 建一条 opacity 轨道(初始 1.0,时长 ms,曲线)。
pub fn opacity_track(initial: f32, duration_ms: u64, curve: Curve) -> SharedTrack<f32> {
    Rc::new(RefCell::new(PropertyTrack::new(initial, duration_ms).with_curve(curve)))
}

/// 在 `now_ms` 时刻把轨道目标改为 `target`(曲线轨道从当前值续接;弹簧轨道保留速度)。
pub fn retarget<T: crate::Lerp>(track: &SharedTrack<T>, target: T, now_ms: u64) {
    track.borrow_mut().retarget(target, now_ms);
}

///  opacity 属性动画容器:stateful + repaint boundary。
///
/// 用法:
/// ```ignore
/// let track = opacity_track(1.0, 300, Curve::EaseInOut);
/// let node = WidgetNode::new(AnimatedOpacityWidget::new(track, my_child));
/// retarget(&track, 0.0, now_ms); // 外部驱动
/// ```
#[derive(Clone)]
pub struct AnimatedOpacityWidget {
    pub child: Option<WidgetNode>,
    track: SharedPropertyTrack<f32>,
}

impl std::fmt::Debug for AnimatedOpacityWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AnimatedOpacityWidget")
            .field("track_presented", &self.track.borrow().presented())
            .field("child", &self.child)
            .finish()
    }
}

impl AnimatedOpacityWidget {
    pub fn new(track: SharedPropertyTrack<f32>, child: impl Widget) -> Self {
        Self { child: Some(WidgetNode::new(child)), track }
    }

    pub fn empty(track: SharedPropertyTrack<f32>) -> Self {
        Self { child: None, track }
    }

    pub fn track(&self) -> &SharedPropertyTrack<f32> {
        &self.track
    }
}

impl Widget for AnimatedOpacityWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn is_stateful(&self) -> bool {
        true
    }

    fn is_repaint_boundary(&self) -> bool {
        true // 独立 layer,opacity 作为 layer effect 每帧实时读
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let opacity = self.track.borrow().presented();
        match &self.child {
            Some(c) => Box::new(OpacityRenderObject::new(c.0.create_render_object(), opacity)),
            None => Box::new(OpacityRenderObject::empty(opacity)),
        }
    }

    fn create_state(&self) -> Option<Box<dyn State>> {
        Some(Box::new(AnimatedOpacityState { current: None, track: self.track.clone() }))
    }

    fn children(&self) -> Vec<WidgetNode> {
        self.child.iter().cloned().collect()
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<AnimatedOpacityWidget>().is_some_and(|o| {
            Rc::ptr_eq(&self.track, &o.track) && super::optional_child_equivalent(&self.child, &o.child)
        })
    }
}

/// 持久化 state:持有 track,tick 推进,apply_to_ro 就地写 RO。
pub struct AnimatedOpacityState {
    current: Option<WidgetNode>,
    track: SharedPropertyTrack<f32>,
}

impl AnimatedOpacityState {
    /// 供 `OpacityRenderObject::apply_state` downcast 后读当前呈现值。
    pub fn presented_opacity(&self) -> f32 {
        self.track.borrow().presented()
    }
}

impl State for AnimatedOpacityState {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn widget(&self) -> &WidgetNode {
        self.current.as_ref().expect("AnimatedOpacityState: widget not set")
    }

    fn set_widget(&mut self, widget: WidgetNode) {
        self.current = Some(widget);
    }

    fn tick(&mut self, now_ms: u64) {
        self.track.borrow_mut().tick(now_ms);
    }

    fn is_animating(&self) -> bool {
        self.track.borrow().is_animating()
    }

    // 持续式动画:收敛帧 tick 把 presented 结算到终值,必须补一次 mark_dirty
    // 让 apply_to_ro 把终值写进 RO(否则 opacity 永远停在倒数第二帧)。
    fn tick_settles_with_repaint(&self) -> bool {
        true
    }

    // 纯视觉动画:opacity 不改语义结构,不要每帧 bump a11y 版本。
    fn tick_changes_semantics(&self) -> bool {
        false
    }

    fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
        ro.apply_state(self.as_any_mut())
    }
}

// =====================================================================
// Scale —— 几何型但走 layer effect(TransformRenderObject 是 repaint boundary)
// =====================================================================

/// 建一条 f32 轨道(通用:scale / 未来其他标量属性)。
pub fn scalar_track(initial: f32, duration_ms: u64, curve: Curve) -> SharedPropertyTrack<f32> {
    Rc::new(RefCell::new(PropertyTrack::new(initial, duration_ms).with_curve(curve)))
}

/// 建一条 Point 轨道(offset 用)。
pub fn point_track(initial: Point, duration_ms: u64, curve: Curve) -> SharedPropertyTrack<Point> {
    Rc::new(RefCell::new(PropertyTrack::new(initial, duration_ms).with_curve(curve)))
}

/// scale 动画容器:stateful + repaint boundary(Transform 自带 layer,screen-space effect)。
///
/// `base` 是 widget 原有的 `Transform2D`(rotation/translation),track 只驱动
/// scale_x/scale_y,apply 时写回 base 的 scale 分量。
#[derive(Clone)]
pub struct AnimatedScaleWidget {
    pub child: Option<WidgetNode>,
    base: Transform2D,
    track: SharedPropertyTrack<f32>,
}

impl std::fmt::Debug for AnimatedScaleWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AnimatedScaleWidget")
            .field("track_presented", &self.track.borrow().presented())
            .field("base", &self.base)
            .field("child", &self.child)
            .finish()
    }
}

impl AnimatedScaleWidget {
    pub fn new(track: SharedPropertyTrack<f32>, child: impl Widget) -> Self {
        Self { child: Some(WidgetNode::new(child)), base: Transform2D::IDENTITY, track }
    }

    /// 带基础变换(rotation/translation 固定,只有 scale 被动画覆盖)。
    pub fn with_base(track: SharedPropertyTrack<f32>, base: Transform2D, child: impl Widget) -> Self {
        Self { child: Some(WidgetNode::new(child)), base, track }
    }

    pub fn track(&self) -> &SharedPropertyTrack<f32> {
        &self.track
    }

    fn transform_now(&self) -> Transform2D {
        let mut t = self.base;
        let s = self.track.borrow().presented();
        t.scale_x = s;
        t.scale_y = s;
        t
    }
}

impl Widget for AnimatedScaleWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn is_stateful(&self) -> bool {
        true
    }

    fn is_repaint_boundary(&self) -> bool {
        true
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let t = self.transform_now();
        match &self.child {
            Some(c) => Box::new(TransformRenderObject::new(c.0.create_render_object(), t)),
            None => Box::new(TransformRenderObject::empty(t)),
        }
    }

    fn create_state(&self) -> Option<Box<dyn State>> {
        Some(Box::new(AnimatedScaleState { current: None, base: self.base, track: self.track.clone() }))
    }

    fn children(&self) -> Vec<WidgetNode> {
        self.child.iter().cloned().collect()
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<AnimatedScaleWidget>().is_some_and(|o| {
            Rc::ptr_eq(&self.track, &o.track) && super::optional_child_equivalent(&self.child, &o.child)
        })
    }
}

pub struct AnimatedScaleState {
    current: Option<WidgetNode>,
    base: Transform2D,
    track: SharedPropertyTrack<f32>,
}

impl AnimatedScaleState {
    /// 供 `TransformRenderObject::apply_state` downcast 后读当前 scale。
    pub fn presented_scale(&self) -> (f32, f32) {
        let s = self.track.borrow().presented();
        let _ = self.base; // base 固定,scale 由 track 覆盖
        (s, s)
    }
}

impl State for AnimatedScaleState {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn widget(&self) -> &WidgetNode {
        self.current.as_ref().expect("AnimatedScaleState: widget not set")
    }

    fn set_widget(&mut self, widget: WidgetNode) {
        self.current = Some(widget);
    }

    fn tick(&mut self, now_ms: u64) {
        self.track.borrow_mut().tick(now_ms);
    }

    fn is_animating(&self) -> bool {
        self.track.borrow().is_animating()
    }

    // 持续式动画:收敛帧必须补一次重画把 scale 终值写进 RO(实测 0.625→0.5)。
    fn tick_settles_with_repaint(&self) -> bool {
        true
    }

    // scale 是 screen-space effect,child_slots 恒 ZERO,origin 不受影响。
    fn tick_changes_semantics(&self) -> bool {
        false
    }

    fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
        ro.apply_state(self.as_any_mut())
    }
}

// =====================================================================
// Offset —— 几何型,PositionedRenderObject 非 boundary,必须失效 origin_cache
// =====================================================================

/// offset 动画容器:stateful,**非** repaint boundary(Positioned 本就是父 layer 内的 RO)。
#[derive(Clone)]
pub struct AnimatedOffsetWidget {
    pub child: Option<WidgetNode>,
    track: SharedPropertyTrack<Point>,
}

impl std::fmt::Debug for AnimatedOffsetWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AnimatedOffsetWidget")
            .field("track_presented", &self.track.borrow().presented())
            .field("child", &self.child)
            .finish()
    }
}

impl AnimatedOffsetWidget {
    pub fn new(track: SharedPropertyTrack<Point>, child: impl Widget) -> Self {
        Self { child: Some(WidgetNode::new(child)), track }
    }

    pub fn track(&self) -> &SharedPropertyTrack<Point> {
        &self.track
    }
}

impl Widget for AnimatedOffsetWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn is_stateful(&self) -> bool {
        true
    }

    // 不设 repaint boundary:Positioned 的 offset 在父 layer 的 paint list 内生效。
    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let off = self.track.borrow().presented();
        match &self.child {
            Some(c) => Box::new(PositionedRenderObject::new(off, c.0.create_render_object())),
            None => {
                // 无 child 时用空 LayerProxy 占位,保持 Positioned 容器语义
                Box::new(PositionedRenderObject::new(off, crate::render_object::LayerProxyRenderObject::empty()))
            }
        }
    }

    fn create_state(&self) -> Option<Box<dyn State>> {
        Some(Box::new(AnimatedOffsetState { current: None, track: self.track.clone() }))
    }

    fn children(&self) -> Vec<WidgetNode> {
        self.child.iter().cloned().collect()
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<AnimatedOffsetWidget>().is_some_and(|o| {
            Rc::ptr_eq(&self.track, &o.track) && super::optional_child_equivalent(&self.child, &o.child)
        })
    }
}

pub struct AnimatedOffsetState {
    current: Option<WidgetNode>,
    track: SharedPropertyTrack<Point>,
}

impl AnimatedOffsetState {
    pub fn presented_offset(&self) -> Point {
        self.track.borrow().presented()
    }
}

impl State for AnimatedOffsetState {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn widget(&self) -> &WidgetNode {
        self.current.as_ref().expect("AnimatedOffsetState: widget not set")
    }

    fn set_widget(&mut self, widget: WidgetNode) {
        self.current = Some(widget);
    }

    fn tick(&mut self, now_ms: u64) {
        self.track.borrow_mut().tick(now_ms);
    }

    fn is_animating(&self) -> bool {
        self.track.borrow().is_animating()
    }

    // 持续式动画:收敛帧必须补一次重画把 offset 终值写进 RO。
    fn tick_settles_with_repaint(&self) -> bool {
        true
    }

    // offset 改变 child 的摆放位置 → a11y bounds 会跟着动(collect_semantics 实时读
    // for_each_child)。但语义结构不变,不推进版本以免读屏每帧重建。
    fn tick_changes_semantics(&self) -> bool {
        false
    }

    // 关键:child_slots 偏移变了,必须让框架失效 origin_cache。
    fn tick_changes_geometry(&self) -> bool {
        true
    }

    fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
        ro.apply_state(self.as_any_mut())
    }
}

// =====================================================================
// Color + Corner + Bounds —— 绘制属性型(都是 PaintCommand::Rect 的字段,
// 必须让所在 layer 重新 paint;但与 opacity 一样 rebuilt==false)
// =====================================================================

/// 建一条 color 轨道(初始色、时长 ms、曲线)。
pub fn color_track(initial: Color, duration_ms: u64, curve: Curve) -> SharedPropertyTrack<Color> {
    Rc::new(RefCell::new(PropertyTrack::new(initial, duration_ms).with_curve(curve)))
}

/// 建一条圆角半径轨道(复用 f32 scalar 轨道,语义命名便于调用方对齐)。
pub fn corner_track(initial: f32, duration_ms: u64, curve: Curve) -> SharedPropertyTrack<f32> {
    scalar_track(initial, duration_ms, curve)
}

/// 建一条 bounds(size)轨道。
///
/// 语义:**只改自身内容盒、不触发父容器重排**。呈现值直接写进 RRect 的 `size`,
/// paint/hit_test/content_size/a11y bounds 同源读它;父的 `slot.cached_size` 与
/// 兄弟偏移不动(父重排属二期布局动画)。静态 size 用 `size_track(s, 1, curve)`
/// 占位即可,不会推进。
pub fn size_track(initial: crate::Size, duration_ms: u64, curve: Curve) -> SharedPropertyTrack<crate::Size> {
    Rc::new(RefCell::new(PropertyTrack::new(initial, duration_ms).with_curve(curve)))
}

/// 动画化圆角矩形:color / corner / bounds(size)都是 `PaintCommand::Rect` 的字段/尺寸。
///
/// 与 opacity/scale(走 `LayerEffect` 实时读、不必重画)的本质差异:这三类变化后
/// 必须让 RO 所在 layer 重新 paint 才会生成新的绘制命令。这里走
/// `State.tick → apply_to_ro` 就地写 RO 字段 → 框架把所在 layer 标 dirty 重画 ——
/// 只重画这一个 layer 的 PaintList,不 mount/update/layout → `rebuilt==false`。
///
/// **bounds 的额外语义**:size 是 `content_size()` / hit_test / a11y bounds 的来源,
/// 所以 size 推进时必须 bump 语义版本(与纯视觉的 color/corner 相反);但 `apply_state`
/// 只写 RO 的 `size` 字段、不失效 layout 缓存 —— 一旦失效,`layout_cached` 会用布局
/// 约束 `constrain()` 二次 clamp 掉呈现值,呈现(presented)优先于布局约束。
///
/// 叶子 widget(无 child),不是 repaint boundary:画进所在祖先 layer。
#[derive(Clone)]
pub struct AnimatedRRectWidget {
    size: SharedPropertyTrack<crate::Size>,
    color: SharedPropertyTrack<Color>,
    corner: SharedPropertyTrack<f32>,
}

impl std::fmt::Debug for AnimatedRRectWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AnimatedRRectWidget")
            .field("size", &self.size.borrow().presented())
            .field("color", &self.color.borrow().presented())
            .field("corner", &self.corner.borrow().presented())
            .finish()
    }
}

impl AnimatedRRectWidget {
    /// size 静态(用一条静止轨道占位),color/corner 可各自带轨道。
    pub fn new(size: crate::Size, color: SharedPropertyTrack<Color>, corner: SharedPropertyTrack<f32>) -> Self {
        Self::with_size(size_track(size, 1, Curve::Linear), color, corner)
    }

    /// size 也由轨道驱动(bounds 动画);color/corner 各自带轨道。
    pub fn with_size(
        size: SharedPropertyTrack<crate::Size>,
        color: SharedPropertyTrack<Color>,
        corner: SharedPropertyTrack<f32>,
    ) -> Self {
        Self { size, color, corner }
    }

    /// 只动画 color:corner 与 size 固定。
    pub fn with_color(size: crate::Size, color: SharedPropertyTrack<Color>, radius: f32) -> Self {
        Self::new(size, color, corner_track(radius, 1, Curve::Linear))
    }

    /// 只动画 corner:color 与 size 固定。
    pub fn with_corner(size: crate::Size, color: Color, corner: SharedPropertyTrack<f32>) -> Self {
        Self::new(size, color_track(color, 1, Curve::Linear), corner)
    }

    /// 只动画 bounds(size):color 与 corner 固定。
    pub fn with_bounds(size: SharedPropertyTrack<crate::Size>, color: Color, radius: f32) -> Self {
        Self::with_size(size, color_track(color, 1, Curve::Linear), corner_track(radius, 1, Curve::Linear))
    }

    pub fn size_track(&self) -> &SharedPropertyTrack<crate::Size> {
        &self.size
    }

    pub fn color_track(&self) -> &SharedPropertyTrack<Color> {
        &self.color
    }

    pub fn corner_track(&self) -> &SharedPropertyTrack<f32> {
        &self.corner
    }
}

impl Widget for AnimatedRRectWidget {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn is_stateful(&self) -> bool {
        true
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        let size = self.size.borrow().presented();
        let color = self.color.borrow().presented();
        let radius = self.corner.borrow().presented();
        Box::new(RRectRenderObject::new(size, color, radius))
    }

    fn create_state(&self) -> Option<Box<dyn State>> {
        Some(Box::new(AnimatedRRectState {
            current: None,
            size: self.size.clone(),
            color: self.color.clone(),
            corner: self.corner.clone(),
            size_changed_this_tick: false,
        }))
    }

    fn is_equivalent(&self, old: &dyn Widget) -> bool {
        old.as_any().downcast_ref::<AnimatedRRectWidget>().is_some_and(|o| {
            Rc::ptr_eq(&self.size, &o.size) && Rc::ptr_eq(&self.color, &o.color) && Rc::ptr_eq(&self.corner, &o.corner)
        })
    }
}

/// 持久化 state:三条轨道各自推进,apply_to_ro 就地写 RRect 的尺寸/颜色/圆角。
pub struct AnimatedRRectState {
    current: Option<WidgetNode>,
    size: SharedPropertyTrack<crate::Size>,
    color: SharedPropertyTrack<Color>,
    corner: SharedPropertyTrack<f32>,
    /// 本 tick 内 size 是否推进过(含收敛帧)。用于 `tick_changes_semantics`:
    /// size 影响 a11y bounds,收敛帧 `is_animating()` 已 false 但终值刚落地,
    /// 必须 bump 语义版本让读屏刷新;只看 `is_animating()` 会漏掉这一帧。
    size_changed_this_tick: bool,
}

impl AnimatedRRectState {
    /// 供 `RRectRenderObject::apply_state` downcast 后读当前呈现值。
    pub fn presented_size(&self) -> crate::Size {
        self.size.borrow().presented()
    }

    pub fn presented_color(&self) -> Color {
        self.color.borrow().presented()
    }

    pub fn presented_corner(&self) -> f32 {
        self.corner.borrow().presented()
    }
}

impl State for AnimatedRRectState {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn widget(&self) -> &WidgetNode {
        self.current.as_ref().expect("AnimatedRRectState: widget not set")
    }

    fn set_widget(&mut self, widget: WidgetNode) {
        self.current = Some(widget);
    }

    fn tick(&mut self, now_ms: u64) {
        // tick 前记录 size 是否在动 —— 收敛帧 tick 后 is_animating() 会变 false,
        // 但那一帧 presented 结算到终值,bounds 变了,仍需 bump 语义版本。
        let size_was_animating = self.size.borrow().is_animating();
        self.size.borrow_mut().tick(now_ms);
        self.color.borrow_mut().tick(now_ms);
        self.corner.borrow_mut().tick(now_ms);
        self.size_changed_this_tick = size_was_animating;
    }

    fn is_animating(&self) -> bool {
        self.size.borrow().is_animating() || self.color.borrow().is_animating() || self.corner.borrow().is_animating()
    }

    // 持续式动画:收敛帧 tick 把 presented 结算到终值,必须补一次 mark_dirty,
    // 让 RRect 所在 layer 重新 paint,把终值写进 PaintCommand::Rect。
    fn tick_settles_with_repaint(&self) -> bool {
        true
    }

    // size(bounds)会改变 content_size → a11y bounds 读它,推进必须 bump 版本;
    // color/corner 是纯视觉,保持 false 以免读屏每帧重建语义树。
    fn tick_changes_semantics(&self) -> bool {
        self.size_changed_this_tick
    }

    fn apply_to_ro(&mut self, ro: &mut dyn RenderObject) -> StateApply {
        ro.apply_state(self.as_any_mut())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render_object::RRectRenderObject;
    use crate::widget::RRectWidget;
    use crate::{Color, Curve, Size};

    fn host_tick(state: &mut AnimatedOpacityState, ro: &mut OpacityRenderObject, now_ms: u64) -> StateApply {
        state.tick(now_ms);
        ro.apply_state(state.as_any_mut())
    }

    #[test]
    fn opacity_track_writes_ro_without_rebuild() {
        let track = opacity_track(1.0, 1000, Curve::Linear);
        let w = AnimatedOpacityWidget::new(track.clone(), RRectWidget::new(Size::new(10.0, 10.0), Color::WHITE, 2.0));
        let mut state = AnimatedOpacityState { current: Some(WidgetNode::new(w)), track: track.clone() };
        let mut ro = OpacityRenderObject::empty(1.0);

        retarget(&track, 0.0, 0);
        assert!(state.is_animating());
        assert_eq!(host_tick(&mut state, &mut ro, 0), StateApply::Unchanged, "首帧 t=0 无变化");
        assert!((ro.opacity - 1.0).abs() < 1e-6);
        assert_eq!(host_tick(&mut state, &mut ro, 500), StateApply::Updated);
        assert!((ro.opacity - 0.5).abs() < 1e-6, "paint 读的 RO 字段已是动画中间值");
        host_tick(&mut state, &mut ro, 1000);
        assert!((ro.opacity - 0.0).abs() < 1e-6);
        assert!(!state.is_animating(), "收敛后必须停,驱动空闲");
        assert_eq!(host_tick(&mut state, &mut ro, 1200), StateApply::Unchanged, "收敛后幂等");
    }

    #[test]
    fn opacity_retarget_midflight_is_continuous_on_ro() {
        let track = opacity_track(1.0, 1000, Curve::Linear);
        let mut state = AnimatedOpacityState { current: None, track: track.clone() };
        let mut ro = OpacityRenderObject::empty(1.0);

        retarget(&track, 0.0, 0);
        host_tick(&mut state, &mut ro, 500); // opacity = 0.5
        let before = ro.opacity;
        retarget(&track, 1.0, 500); // 反向
        host_tick(&mut state, &mut ro, 500);
        assert!((ro.opacity - before).abs() < 1e-6, "反向瞬间 RO 不跳变");
        host_tick(&mut state, &mut ro, 750);
        assert!(ro.opacity > before, "反向后 opacity 回升");
    }

    #[test]
    fn opacity_layer_effect_reflects_presented() {
        use crate::render_object::RenderObject;
        let track = opacity_track(1.0, 1000, Curve::Linear);
        let mut state = AnimatedOpacityState { current: None, track: track.clone() };
        let mut ro = OpacityRenderObject::empty(1.0);
        retarget(&track, 0.0, 0);
        host_tick(&mut state, &mut ro, 400);
        match ro.layer_effect() {
            crate::paint::LayerEffect::Opacity(v) => assert!((v - 0.6).abs() < 1e-6),
            other => panic!("期望 Opacity effect,得到 {other:?}"),
        }
    }

    #[test]
    fn semantics_not_changed_by_opacity_tick() {
        let track = opacity_track(1.0, 1000, Curve::Linear);
        let state = AnimatedOpacityState { current: None, track };
        assert!(!state.tick_changes_semantics(), "纯视觉动画不得推进 a11y 版本");
    }

    #[test]
    fn opaque_ro_rejects_foreign_state() {
        let mut ro = OpacityRenderObject::empty(1.0);
        struct Foreign;
        impl State for Foreign {
            fn as_any(&self) -> &dyn Any {
                self
            }
            fn as_any_mut(&mut self) -> &mut dyn Any {
                self
            }
            fn widget(&self) -> &WidgetNode {
                unreachable!()
            }
            fn set_widget(&mut self, _: WidgetNode) {}
        }
        let mut f = Foreign;
        assert_eq!(ro.apply_state(f.as_any_mut()), StateApply::Unsupported);
    }

    // ---------- Scale ----------

    fn scale_tick(state: &mut AnimatedScaleState, ro: &mut TransformRenderObject, now_ms: u64) -> StateApply {
        state.tick(now_ms);
        ro.apply_state(state.as_any_mut())
    }

    #[test]
    fn scale_track_writes_transform_effect() {
        let track = scalar_track(1.0, 1000, Curve::Linear);
        let mut state = AnimatedScaleState { current: None, base: Transform2D::IDENTITY, track: track.clone() };
        let mut ro = TransformRenderObject::empty(Transform2D::IDENTITY);
        retarget(&track, 0.5, 0);
        assert_eq!(scale_tick(&mut state, &mut ro, 0), StateApply::Unchanged);
        assert_eq!(scale_tick(&mut state, &mut ro, 500), StateApply::Updated);
        assert!((ro.transform.scale_x - 0.75).abs() < 1e-6);
        assert!((ro.transform.scale_y - 0.75).abs() < 1e-6);
        match ro.layer_effect() {
            crate::paint::LayerEffect::Transform(t) => assert!((t.scale_x - 0.75).abs() < 1e-6),
            other => panic!("期望 Transform effect,得到 {other:?}"),
        }
        assert_eq!(scale_tick(&mut state, &mut ro, 1000), StateApply::Updated);
        assert_eq!(scale_tick(&mut state, &mut ro, 1200), StateApply::Unchanged, "收敛后幂等");
    }

    #[test]
    fn scale_preserves_base_rotation_and_translation() {
        let base = Transform2D { rotation: 0.7, scale_x: 1.0, scale_y: 1.0, translate: Point::new(12.0, -8.0) };
        let track = scalar_track(1.0, 1000, Curve::Linear);
        let w = AnimatedScaleWidget::with_base(
            track.clone(),
            base,
            RRectWidget::new(Size::new(8.0, 8.0), Color::WHITE, 0.0),
        );
        let mut state = AnimatedScaleState { current: Some(WidgetNode::new(w)), base, track: track.clone() };
        let mut ro = TransformRenderObject::empty(base);
        retarget(&track, 0.5, 0);
        scale_tick(&mut state, &mut ro, 1000);
        assert!((ro.transform.rotation - 0.7).abs() < 1e-6, "rotation 不被 scale 覆盖");
        assert!((ro.transform.translate.x - 12.0).abs() < 1e-6, "translate 不被 scale 覆盖");
        assert!((ro.transform.scale_x - 0.5).abs() < 1e-6);
    }

    #[test]
    fn scale_state_is_pure_visual_for_origin() {
        let track = scalar_track(1.0, 1000, Curve::Linear);
        let state = AnimatedScaleState { current: None, base: Transform2D::IDENTITY, track };
        assert!(!state.tick_changes_geometry(), "scale 不改 child_slots,无需失效 origin_cache");
        assert!(!state.tick_changes_semantics());
    }

    // ---------- Offset ----------

    fn offset_tick(state: &mut AnimatedOffsetState, ro: &mut PositionedRenderObject, now_ms: u64) -> StateApply {
        state.tick(now_ms);
        ro.apply_state(state.as_any_mut())
    }

    #[test]
    fn offset_track_writes_position() {
        let track = point_track(Point::new(0.0, 0.0), 1000, Curve::Linear);
        let w = AnimatedOffsetWidget::new(track.clone(), RRectWidget::new(Size::new(10.0, 10.0), Color::WHITE, 0.0));
        let mut state = AnimatedOffsetState { current: Some(WidgetNode::new(w)), track: track.clone() };
        let child = RRectRenderObject::new(Size::new(10.0, 10.0), Color::WHITE, 0.0);
        let mut ro = PositionedRenderObject::new(Point::ZERO, child);
        retarget(&track, Point::new(100.0, 50.0), 0);
        assert_eq!(offset_tick(&mut state, &mut ro, 0), StateApply::Unchanged);
        assert_eq!(offset_tick(&mut state, &mut ro, 500), StateApply::Updated);
        assert!((ro.offset.x - 50.0).abs() < 1e-6 && (ro.offset.y - 25.0).abs() < 1e-6);
        // child_slots 读 current_offset() —— 语义 origin 与 paint 同源
        let slots = ro.child_slots();
        assert!((slots[0].0.x - 50.0).abs() < 1e-6, "child_slots 必须反映动画中的 offset");
    }

    #[test]
    fn offset_state_requires_origin_cache_invalidation() {
        let track = point_track(Point::ZERO, 1000, Curve::Linear);
        let state = AnimatedOffsetState { current: None, track };
        assert!(state.tick_changes_geometry(), "offset 改 child_slots,必须触发 origin_cache 失效");
        assert!(!state.tick_changes_semantics());
    }

    #[test]
    fn offset_retarget_midflight_is_continuous() {
        let track = point_track(Point::ZERO, 1000, Curve::Linear);
        let mut state = AnimatedOffsetState { current: None, track: track.clone() };
        let child = RRectRenderObject::new(Size::new(10.0, 10.0), Color::WHITE, 0.0);
        let mut ro = PositionedRenderObject::new(Point::ZERO, child);
        retarget(&track, Point::new(100.0, 0.0), 0);
        offset_tick(&mut state, &mut ro, 500); // x=50
        let before = ro.offset;
        retarget(&track, Point::ZERO, 500); // 反向
        offset_tick(&mut state, &mut ro, 500);
        assert!((ro.offset.x - before.x).abs() < 1e-6, "反向瞬间 offset 不跳变");
        offset_tick(&mut state, &mut ro, 750);
        assert!(ro.offset.x < before.x, "反向后 offset 持续回落");
    }
}