Skip to main content

mgui_core/layout/
rotated_box.rs

1//! RotatedBox — 在**布局阶段**按 90° 整数倍旋转 child(旋转影响尺寸)
2//!
3//! 与 `TransformWidget` 的关键差异:RotatedBox 的旋转参与**布局** —— 父容器看到的
4//! 是旋转后的外接盒(奇数个 90° 时宽高互换);Transform 只在绘制阶段变换、不影响尺寸。
5//!
6//! 实现复用框架 layer 机制(与 `FittedBox` 同范式):本 RO 是 **layer 边界**
7//! (`is_repaint_boundary() = true`),`content_size()` 返回**未旋转**的 child 尺寸
8//! (层纹理必须装下未旋转的 child),`layer_effect()` 返回「绕层中心旋转 + 平移」的
9//! `Transform2D`,由 renderer 的 blit 阶段在 GPU 完成旋转。因此不需要在 paint 阶段
10//! 改写几何命令,core ↔ runtime 边界保持干净。
11
12use std::f32::consts::FRAC_PI_2;
13
14use crate::id::ElementId;
15use crate::paint::{LayerEffect, PaintList};
16use crate::render_object::{
17    inverse_apply_transform, make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO,
18};
19use crate::widget::{Widget, WidgetNode};
20use crate::{Color, Point, Size, Transform2D};
21
22/// RotatedBox RenderObject
23///
24/// 语义(对齐 Flutter `RenderRotatedBox`):
25/// - `quarter_turns` 为顺时针 90° 的整数倍(负值按 `rem_euclid(4)` 归一)
26/// - 奇数个 90°:child 用**交换后的宽高约束**布局,容器尺寸 = child 尺寸交换
27/// - 偶数个 90°:child 用原约束布局,容器尺寸 = child 尺寸
28pub struct RotatedBoxRenderObject {
29    pub quarter_turns: i32,
30    child: Option<SharedRO>,
31    /// 容器尺寸(父容器看到的布局尺寸)
32    cached_size: Size,
33    /// child 未旋转尺寸(层纹理尺寸 / content_size)
34    child_size: Size,
35    /// 旋转 + 摆位平移(layer blit 用)
36    pub transform: Transform2D,
37}
38
39impl RotatedBoxRenderObject {
40    pub fn new(quarter_turns: i32, child: Option<Box<dyn RenderObject>>) -> Self {
41        Self {
42            quarter_turns,
43            child: child.map(make_ro_shared),
44            cached_size: Size::ZERO,
45            child_size: Size::ZERO,
46            transform: Transform2D::IDENTITY,
47        }
48    }
49}
50
51impl RenderObject for RotatedBoxRenderObject {
52    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
53        let odd = self.quarter_turns.rem_euclid(2) == 1;
54
55        // 1. 奇数 turns:交换约束的宽高轴(child 在旋转后的坐标域内布局)
56        let child_constraints = if odd {
57            BoxConstraints {
58                min_width: constraints.min_height,
59                max_width: constraints.max_height,
60                min_height: constraints.min_width,
61                max_height: constraints.max_width,
62            }
63        } else {
64            constraints
65        };
66        self.child_size =
67            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };
68
69        // 2. 候选容器尺寸 = 旋转后的外接盒
70        let candidate = if odd { Size::new(self.child_size.height, self.child_size.width) } else { self.child_size };
71
72        // 无界重排 guard(与 FittedBox 同):`paint_layer_recursive` 会把 layer root
73        // 用 UNBOUNDED 再 layout 一次,若此时用 `constrain(candidate)` 会覆盖此前按父
74        // 容器算出的尺寸/平移。故仅父给**有界**约束时更新容器尺寸;无界(层根重排)时
75        // 沿用上一次已知容器尺寸。
76        let bounded = constraints.max_width.is_finite() || constraints.max_height.is_finite();
77        if bounded {
78            self.cached_size = constraints.constrain(candidate);
79        } else if self.cached_size.width <= 0.0 || self.cached_size.height <= 0.0 {
80            self.cached_size = candidate;
81        }
82
83        // 3. 绕 child(层)中心旋转后,把旋转外接盒中心对齐到容器中心:
84        //    translate = 容器中心 − child 中心 = (self − child) / 2
85        let rotation = (self.quarter_turns.rem_euclid(4) as f32) * FRAC_PI_2;
86        self.transform = Transform2D {
87            rotation,
88            scale_x: 1.0,
89            scale_y: 1.0,
90            translate: Point::new(
91                (self.cached_size.width - self.child_size.width) * 0.5,
92                (self.cached_size.height - self.child_size.height) * 0.5,
93            ),
94        };
95
96        self.cached_size
97    }
98
99    fn paint(&self, _offset: Point, _painter: &mut PaintList) {
100        // layer 边界 — paint noop,内容由本层纹理经 blit 旋转后画
101    }
102
103    fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
104        // 本层内容 = child 未旋转的绘制命令(child 在层内的原点即层原点)
105        if let Some(c) = &self.child {
106            c.borrow().paint(offset, painter);
107        }
108    }
109
110    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
111        let child = self.child.as_ref()?;
112        let s = self.child_size;
113        if s.width <= 0.0 || s.height <= 0.0 {
114            return child.borrow().hit_test(position, offset);
115        }
116        // 反向变换:把世界坐标转回 child 未旋转坐标后再判命中(center = 层中心)
117        let cx = offset.x + s.width * 0.5;
118        let cy = offset.y + s.height * 0.5;
119        let local = inverse_apply_transform(position, self.transform, cx, cy);
120        child.borrow().hit_test(local, offset)
121    }
122
123    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
124        if let (Some(child), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
125            if let Some(new_ro) = stateful_ros.first_mut() {
126                *child = new_ro.clone();
127            }
128            child.borrow_mut().set_element_id(cid);
129        }
130    }
131
132    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
133        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
134    }
135
136    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
137        if let Some(c) = &self.child {
138            f(Point::ZERO, c);
139        }
140    }
141
142    fn children_count(&self) -> usize {
143        if self.child.is_some() {
144            1
145        } else {
146            0
147        }
148    }
149
150    /// 层纹理尺寸 = child **未旋转**尺寸(必须装下旋转前的 child,旋转交给 blit)
151    fn content_size(&self) -> Size {
152        self.child_size
153    }
154
155    fn layer_layout_size(&self) -> Option<Size> {
156        Some(self.cached_size)
157    }
158
159    fn layer_effect(&self) -> LayerEffect {
160        LayerEffect::Transform(self.transform)
161    }
162}
163
164/// RotatedBox(布局阶段旋转子节点)
165#[derive(Debug)]
166pub struct RotatedBoxWidget {
167    pub quarter_turns: i32,
168    pub child: Option<WidgetNode>,
169}
170
171impl RotatedBoxWidget {
172    /// `quarter_turns`:顺时针 90° 的整数倍(如 1 = 顺时针 90°,2 = 180°)
173    pub fn new(quarter_turns: i32, child: impl Widget) -> Self {
174        Self { quarter_turns, child: Some(WidgetNode::new(child)) }
175    }
176
177    pub fn quarter_turns(mut self, turns: i32) -> Self {
178        self.quarter_turns = turns;
179        self
180    }
181}
182
183impl Widget for RotatedBoxWidget {
184    fn as_any(&self) -> &dyn std::any::Any {
185        self
186    }
187
188    /// 旋转依赖独立 layer:child 画进本层纹理,再由 blit 阶段旋转
189    fn is_repaint_boundary(&self) -> bool {
190        true
191    }
192
193    fn create_render_object(&self) -> Box<dyn RenderObject> {
194        let child_ro = match &self.child {
195            Some(c) => c.0.create_render_object(),
196            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
197        };
198        Box::new(RotatedBoxRenderObject::new(self.quarter_turns, Some(child_ro)))
199    }
200
201    fn children(&self) -> Vec<WidgetNode> {
202        match &self.child {
203            Some(c) => vec![c.clone()],
204            None => vec![],
205        }
206    }
207}