Skip to main content

mgui_core/
dnd.rs

1//! 应用内拖放(1.1 M2):类型化 payload + 显式会话管理。
2//!
3//! 范围(M0 决策 2026-11-30):
4//! - 只做应用内 DnD;OS 级 OLE 拖放不在本期。文件拖入/拖出继续走
5//!   `ShellEvent::FileDropped`,与本模块互不干扰。
6//! - 不造第二棵状态树:命中目标直接用 `ElementTree::hit_test` + 祖先链,
7//!   drop 回调写进应用自己的 Store/Signal。
8//! - 不读墙钟:会话不记时间;Agent replay 两遍走同一事件序列即逐字节一致。
9//!   组件侧 payload / accepts 闭包必须是纯确定性输入,写状态只放在 drop / hover 回调。
10//!
11//! 分层(与 OS 文件拖放同构):
12//! - 组件侧 `DragSource` 在 Pan 手势胜出时 [`DndManager::begin`] 开启会话;
13//! - **app 侧**在指针事件入口调 [`DndManager::update`] / [`DndManager::finish`]
14//!   / [`DndManager::cancel_with_tree`],由 manager 用 tree 做命中与 drop 投递;
15//! - `DropTarget` 的 State override `State::accepts_drag` / `drop_payload`,由 manager 沿命中祖先链探测;
16//! - `DragSourceState` 把 [`DragSession::semantic_label`] 暴露到语义树;hover 只标脏目标,
17//!   phase / 目标变化才更新 source 的语义版本。
18//!
19//! 会话 owner:`DragSession::source` 是发起拖拽的 `ElementId`。source 在会话
20//! 进行中被卸载 / 树重建失效时,下一次 `update` 自动 `cancel`,不会悬挂。
21
22use std::any::{Any, TypeId};
23use std::cell::RefCell;
24use std::fmt;
25use std::rc::Rc;
26
27use crate::element::ElementTree;
28use crate::ElementId;
29
30/// 应用内拖放 payload:类型键 + `Rc<dyn Any>`,不做 MIME 字符串。
31///
32/// 同一 `TypeId` 的 payload 才能被 `DropTarget` 接收;跨类型混淆在
33/// [`DndManager::update`] 阶段就被拒绝,不会派发到 drop 回调。
34#[derive(Clone)]
35pub struct DragPayload {
36    type_id: TypeId,
37    value: Rc<dyn Any>,
38    /// 稳定类型名,用于 trace / 日志(不参与匹配)。
39    type_name: &'static str,
40}
41
42impl DragPayload {
43    pub fn new<T: Any + 'static>(value: T) -> Self {
44        Self { type_id: TypeId::of::<T>(), value: Rc::new(value), type_name: std::any::type_name::<T>() }
45    }
46
47    /// 用显式类型名构造(trace 可读性优先时)。
48    pub fn new_named<T: Any + 'static>(value: T, type_name: &'static str) -> Self {
49        Self { type_id: TypeId::of::<T>(), value: Rc::new(value), type_name }
50    }
51
52    pub fn type_id(&self) -> TypeId {
53        self.type_id
54    }
55
56    pub fn type_name(&self) -> &'static str {
57        self.type_name
58    }
59
60    pub fn is<T: Any + 'static>(&self) -> bool {
61        self.type_id == TypeId::of::<T>()
62    }
63
64    pub fn downcast_ref<T: Any + 'static>(&self) -> Option<&T> {
65        if self.is::<T>() {
66            self.value.downcast_ref::<T>()
67        } else {
68            None
69        }
70    }
71}
72
73impl fmt::Debug for DragPayload {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.debug_struct("DragPayload").field("type", &self.type_name).finish_non_exhaustive()
76    }
77}
78
79/// 会话阶段。
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum DragPhase {
82    /// 已开始,尚未落到目标。
83    Dragging,
84    /// 已在某个 DropTarget 上方(hover 高亮)。
85    Over,
86    /// 已成功 drop(终态,下一次 begin 覆盖)。
87    Dropped,
88    /// 被取消 / owner 失效 / 类型不匹配(终态)。
89    Cancelled,
90}
91
92/// 一次拖拽会话。
93#[derive(Clone, Debug)]
94pub struct DragSession {
95    /// 发起拖拽的 element(owner);失效即视为取消。
96    pub source: ElementId,
97    pub payload: DragPayload,
98    pub phase: DragPhase,
99    /// 当前指针位置(应用每次 update 注入)。
100    pub position: crate::Point,
101    /// 当前 hover 的 DropTarget element(若有)。
102    pub target: Option<ElementId>,
103    /// 累计 step 数(审计用:replay 两遍必须一致)。
104    pub steps: u64,
105}
106
107impl DragSession {
108    /// 语义树 / 读屏器可播报的拖拽状态摘要。
109    /// 不含指针坐标(避免每帧改变语义树),只含阶段、payload 类型与目标存在性。
110    pub fn semantic_label(&self) -> String {
111        let phase = match self.phase {
112            DragPhase::Dragging => "拖拽中",
113            DragPhase::Over => "在可放置目标上",
114            DragPhase::Dropped => "已放置",
115            DragPhase::Cancelled => "已取消",
116        };
117        format!("{phase} · {} · {}", self.payload.type_name(), if self.target.is_some() { "有目标" } else { "无目标" })
118    }
119}
120
121/// 应用内拖放管理器。
122///
123/// `Rc<RefCell<_>>` 共享:source widget 持有一份用于 `begin`,app 持有一份用于
124/// `update`/`finish`/`cancel`。单线程、不读墙钟。
125#[derive(Clone)]
126pub struct DndManager {
127    inner: Rc<RefCell<Option<DragSession>>>,
128}
129
130impl DndManager {
131    pub fn new() -> Self {
132        Self { inner: Rc::new(RefCell::new(None)) }
133    }
134
135    pub fn session(&self) -> Option<DragSession> {
136        self.inner.borrow().clone()
137    }
138
139    pub fn is_active(&self) -> bool {
140        matches!(self.inner.borrow().as_ref().map(|s| s.phase), Some(DragPhase::Dragging | DragPhase::Over))
141    }
142
143    /// 开启会话。已有活跃会话时拒绝新会话(单指针应用内 DnD 的兜底),
144    /// 返回 `false` 表示未开启;终态会话可直接被下一次 begin 覆盖。
145    pub fn begin(&self, source: ElementId, payload: DragPayload, position: crate::Point) -> bool {
146        let mut guard = self.inner.borrow_mut();
147        if guard.as_ref().is_some_and(|s| matches!(s.phase, DragPhase::Dragging | DragPhase::Over)) {
148            return false;
149        }
150        *guard = Some(DragSession { source, payload, phase: DragPhase::Dragging, position, target: None, steps: 0 });
151        true
152    }
153
154    /// 指针移动时由 app 调用:用 tree 命中目标,沿祖先链找最近的 DropTarget。
155    ///
156    /// 返回当前 hover 的 target(若有),供 app 决定光标形态/重绘。
157    pub fn update(&self, tree: &mut ElementTree, position: crate::Point) -> Option<ElementId> {
158        let mut guard = self.inner.borrow_mut();
159        let session = guard.as_mut()?;
160        if !matches!(session.phase, DragPhase::Dragging | DragPhase::Over) {
161            return None;
162        }
163        // owner 失效(树重建 / 卸载)→ 自动取消,不悬挂。
164        if !tree.is_active(session.source) {
165            session.phase = DragPhase::Cancelled;
166            session.target = None;
167            return None;
168        }
169        session.position = position;
170        session.steps = session.steps.wrapping_add(1);
171
172        let previous = session.target;
173        let next = find_drop_target(tree, position, &session.payload);
174        if previous == next {
175            session.phase = if next.is_some() { DragPhase::Over } else { DragPhase::Dragging };
176            return next;
177        }
178
179        // 离开旧目标 / 进入新目标:downcast 到 DropTargetState 调回调。
180        if let Some(old) = previous {
181            with_drop_target(tree, old, |state| state.drag_leave());
182        }
183        if let Some(new) = next {
184            let payload = session.payload.clone();
185            with_drop_target(tree, new, |state| state.drag_enter(&payload));
186        }
187        session.target = next;
188        session.phase = if next.is_some() { DragPhase::Over } else { DragPhase::Dragging };
189        // hover 只影响绘制,不推进语义;但 source 的拖拽语义标签含“有目标/无目标”,
190        // 目标变化时必须让 source 的语义节点重新读取。
191        if previous != next {
192            if let Some(old) = previous {
193                tree.mark_element_dirty_with_semantics(old, false, false);
194            }
195            if let Some(new) = next {
196                tree.mark_element_dirty_with_semantics(new, false, false);
197            }
198            tree.mark_element_dirty_with_semantics(session.source, false, true);
199        }
200        next
201    }
202
203    /// 抬起时由 app 调用:命中目标并尝试 drop。返回是否消费成功。
204    pub fn finish(&self, tree: &mut ElementTree, position: crate::Point) -> bool {
205        let mut guard = self.inner.borrow_mut();
206        let Some(session) = guard.as_mut() else { return false };
207        if !matches!(session.phase, DragPhase::Dragging | DragPhase::Over) {
208            return false;
209        }
210        if !tree.is_active(session.source) {
211            session.phase = DragPhase::Cancelled;
212            session.target = None;
213            return false;
214        }
215        session.position = position;
216        session.steps = session.steps.wrapping_add(1);
217        let target = find_drop_target(tree, position, &session.payload);
218        let payload = session.payload.clone();
219        let accepted =
220            target.and_then(|id| with_drop_target(tree, id, |state| state.drop_payload(&payload))).unwrap_or(false);
221        if let Some(t) = target {
222            with_drop_target(tree, t, |state| state.drag_leave());
223            tree.mark_element_dirty_with_semantics(t, false, false);
224        }
225        session.target = None;
226        session.phase = if accepted { DragPhase::Dropped } else { DragPhase::Cancelled };
227        tree.mark_element_dirty_with_semantics(session.source, false, true);
228        accepted
229    }
230
231    /// 显式取消(窗口失焦 / Escape / PointerCancel)。
232    pub fn cancel(&self) {
233        let mut guard = self.inner.borrow_mut();
234        if let Some(session) = guard.as_mut() {
235            if matches!(session.phase, DragPhase::Dragging | DragPhase::Over) {
236                if let Some(target) = session.target.take() {
237                    // 目标不在此处传 tree:hover 高亮的回滚由目标自己在 drag_leave 后处理;
238                    // 无 tree 时可交给调用方用 cancel_with_tree。
239                    let _ = target;
240                }
241            }
242            session.phase = DragPhase::Cancelled;
243        }
244    }
245
246    /// 带 tree 的取消:会通知当前 hover 目标 `drag_leave`。
247    pub fn cancel_with_tree(&self, tree: &mut ElementTree) {
248        let mut guard = self.inner.borrow_mut();
249        if let Some(session) = guard.as_mut() {
250            if let Some(target) = session.target.take() {
251                with_drop_target(tree, target, |state| state.drag_leave());
252                tree.mark_element_dirty_with_semantics(target, false, false);
253            }
254            session.phase = DragPhase::Cancelled;
255            tree.mark_element_dirty_with_semantics(session.source, false, true);
256        }
257    }
258
259    /// 键盘等价「拾取」:为指定 source 开会话,位置为 source 的 element 原点。
260    ///
261    /// app 把 `KeyDown(Enter/Space)` 翻译为本调用;与鼠标 Pan 走同一个会话结构,
262    /// 因此后续命中/drop/replay 完全一致。
263    pub fn keyboard_pickup(&self, tree: &ElementTree, source: ElementId, payload: DragPayload) -> bool {
264        let Some(el) = tree.get(source) else { return false };
265        let position = el.layout_offset();
266        self.begin(source, payload, position)
267    }
268
269    /// 键盘等价「移动」:按 logical 像素步进更新指针位置并重新命中目标。
270    pub fn keyboard_move(&self, tree: &mut ElementTree, dx: f32, dy: f32) -> Option<ElementId> {
271        let position = self.inner.borrow().as_ref().map(|s| s.position)?;
272        self.update(tree, crate::Point::new(position.x + dx, position.y + dy))
273    }
274
275    /// 键盘等价「放下」:在当前位置完成 drop。
276    pub fn keyboard_drop(&self, tree: &mut ElementTree) -> bool {
277        let Some(position) = self.inner.borrow().as_ref().map(|s| s.position) else { return false };
278        self.finish(tree, position)
279    }
280
281    /// 清空会话(树重建 / 窗口关闭时调用)。
282    pub fn clear(&self) {
283        *self.inner.borrow_mut() = None;
284    }
285}
286
287impl Default for DndManager {
288    fn default() -> Self {
289        Self::new()
290    }
291}
292
293impl fmt::Debug for DndManager {
294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295        f.debug_struct("DndManager").field("session", &self.session()).finish()
296    }
297}
298
299/// 从命中点沿祖先链找最近的、接受该 payload 的 DropTarget。
300fn find_drop_target(tree: &ElementTree, position: crate::Point, payload: &DragPayload) -> Option<ElementId> {
301    let mut current = tree.hit_test(position);
302    while let Some(id) = current {
303        let accepts = tree.get(id).and_then(|el| el.state()).is_some_and(|state| state.accepts_drag(payload));
304        if accepts {
305            return Some(id);
306        }
307        current = tree.get(id).and_then(|el| el.parent());
308    }
309    None
310}
311
312/// 对指定 element 的 State 执行 DnD 回调。
313fn with_drop_target<R>(
314    tree: &mut ElementTree,
315    id: ElementId,
316    f: impl FnOnce(&mut dyn crate::widget::State) -> R,
317) -> Option<R> {
318    tree.get_mut(id).and_then(|el| el.state_mut()).map(f)
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    use crate::Point;
325
326    #[test]
327    fn payload_is_typed_not_string_based() {
328        let p = DragPayload::new(42_i32);
329        assert!(p.is::<i32>());
330        assert!(!p.is::<String>());
331        assert_eq!(p.downcast_ref::<i32>(), Some(&42));
332        assert!(p.downcast_ref::<String>().is_none());
333        assert!(format!("{p:?}").contains("DragPayload"));
334    }
335
336    #[test]
337    fn begin_rejects_concurrent_active_session() {
338        let manager = DndManager::new();
339        assert!(manager.begin(ElementId::default(), DragPayload::new(1_i32), Point::ZERO));
340        assert!(!manager.begin(ElementId::default(), DragPayload::new(2_i32), Point::ZERO));
341        assert_eq!(manager.session().unwrap().payload.downcast_ref::<i32>(), Some(&1));
342        manager.cancel();
343        assert!(manager.begin(ElementId::default(), DragPayload::new(3_i32), Point::ZERO));
344        assert_eq!(manager.session().unwrap().payload.downcast_ref::<i32>(), Some(&3));
345    }
346
347    #[test]
348    fn semantic_label_reports_phase_and_payload_type() {
349        let manager = DndManager::new();
350        // 无树也能测纯会话标签:直接经由一个最小会话构造。
351        manager.begin(ElementId::default(), DragPayload::new(7_i32), Point::ZERO);
352        let label = manager.session().unwrap().semantic_label();
353        assert!(label.contains("拖拽中"), "{label}");
354        assert!(label.contains("i32"), "{label}");
355        assert!(label.contains("无目标"), "{label}");
356        manager.cancel();
357        assert!(manager.session().unwrap().semantic_label().contains("已取消"));
358    }
359}