1use 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#[derive(Clone)]
35pub struct DragPayload {
36 type_id: TypeId,
37 value: Rc<dyn Any>,
38 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum DragPhase {
82 Dragging,
84 Over,
86 Dropped,
88 Cancelled,
90}
91
92#[derive(Clone, Debug)]
94pub struct DragSession {
95 pub source: ElementId,
97 pub payload: DragPayload,
98 pub phase: DragPhase,
99 pub position: crate::Point,
101 pub target: Option<ElementId>,
103 pub steps: u64,
105}
106
107impl DragSession {
108 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#[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 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 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 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 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 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 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 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 let _ = target;
240 }
241 }
242 session.phase = DragPhase::Cancelled;
243 }
244 }
245
246 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 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 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 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 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
299fn 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
312fn 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 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}