use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use crate::element::ElementTree;
use crate::ElementId;
#[derive(Clone)]
pub struct DragPayload {
type_id: TypeId,
value: Rc<dyn Any>,
type_name: &'static str,
}
impl DragPayload {
pub fn new<T: Any + 'static>(value: T) -> Self {
Self { type_id: TypeId::of::<T>(), value: Rc::new(value), type_name: std::any::type_name::<T>() }
}
pub fn new_named<T: Any + 'static>(value: T, type_name: &'static str) -> Self {
Self { type_id: TypeId::of::<T>(), value: Rc::new(value), type_name }
}
pub fn type_id(&self) -> TypeId {
self.type_id
}
pub fn type_name(&self) -> &'static str {
self.type_name
}
pub fn is<T: Any + 'static>(&self) -> bool {
self.type_id == TypeId::of::<T>()
}
pub fn downcast_ref<T: Any + 'static>(&self) -> Option<&T> {
if self.is::<T>() {
self.value.downcast_ref::<T>()
} else {
None
}
}
}
impl fmt::Debug for DragPayload {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DragPayload").field("type", &self.type_name).finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DragPhase {
Dragging,
Over,
Dropped,
Cancelled,
}
#[derive(Clone, Debug)]
pub struct DragSession {
pub source: ElementId,
pub payload: DragPayload,
pub phase: DragPhase,
pub position: crate::Point,
pub target: Option<ElementId>,
pub steps: u64,
}
impl DragSession {
pub fn semantic_label(&self) -> String {
let phase = match self.phase {
DragPhase::Dragging => "拖拽中",
DragPhase::Over => "在可放置目标上",
DragPhase::Dropped => "已放置",
DragPhase::Cancelled => "已取消",
};
format!("{phase} · {} · {}", self.payload.type_name(), if self.target.is_some() { "有目标" } else { "无目标" })
}
}
#[derive(Clone)]
pub struct DndManager {
inner: Rc<RefCell<Option<DragSession>>>,
}
impl DndManager {
pub fn new() -> Self {
Self { inner: Rc::new(RefCell::new(None)) }
}
pub fn session(&self) -> Option<DragSession> {
self.inner.borrow().clone()
}
pub fn is_active(&self) -> bool {
matches!(self.inner.borrow().as_ref().map(|s| s.phase), Some(DragPhase::Dragging | DragPhase::Over))
}
pub fn begin(&self, source: ElementId, payload: DragPayload, position: crate::Point) -> bool {
let mut guard = self.inner.borrow_mut();
if guard.as_ref().is_some_and(|s| matches!(s.phase, DragPhase::Dragging | DragPhase::Over)) {
return false;
}
*guard = Some(DragSession { source, payload, phase: DragPhase::Dragging, position, target: None, steps: 0 });
true
}
pub fn update(&self, tree: &mut ElementTree, position: crate::Point) -> Option<ElementId> {
let mut guard = self.inner.borrow_mut();
let session = guard.as_mut()?;
if !matches!(session.phase, DragPhase::Dragging | DragPhase::Over) {
return None;
}
if !tree.is_active(session.source) {
session.phase = DragPhase::Cancelled;
session.target = None;
return None;
}
session.position = position;
session.steps = session.steps.wrapping_add(1);
let previous = session.target;
let next = find_drop_target(tree, position, &session.payload);
if previous == next {
session.phase = if next.is_some() { DragPhase::Over } else { DragPhase::Dragging };
return next;
}
if let Some(old) = previous {
with_drop_target(tree, old, |state| state.drag_leave());
}
if let Some(new) = next {
let payload = session.payload.clone();
with_drop_target(tree, new, |state| state.drag_enter(&payload));
}
session.target = next;
session.phase = if next.is_some() { DragPhase::Over } else { DragPhase::Dragging };
if previous != next {
if let Some(old) = previous {
tree.mark_element_dirty_with_semantics(old, false, false);
}
if let Some(new) = next {
tree.mark_element_dirty_with_semantics(new, false, false);
}
tree.mark_element_dirty_with_semantics(session.source, false, true);
}
next
}
pub fn finish(&self, tree: &mut ElementTree, position: crate::Point) -> bool {
let mut guard = self.inner.borrow_mut();
let Some(session) = guard.as_mut() else { return false };
if !matches!(session.phase, DragPhase::Dragging | DragPhase::Over) {
return false;
}
if !tree.is_active(session.source) {
session.phase = DragPhase::Cancelled;
session.target = None;
return false;
}
session.position = position;
session.steps = session.steps.wrapping_add(1);
let target = find_drop_target(tree, position, &session.payload);
let payload = session.payload.clone();
let accepted =
target.and_then(|id| with_drop_target(tree, id, |state| state.drop_payload(&payload))).unwrap_or(false);
if let Some(t) = target {
with_drop_target(tree, t, |state| state.drag_leave());
tree.mark_element_dirty_with_semantics(t, false, false);
}
session.target = None;
session.phase = if accepted { DragPhase::Dropped } else { DragPhase::Cancelled };
tree.mark_element_dirty_with_semantics(session.source, false, true);
accepted
}
pub fn cancel(&self) {
let mut guard = self.inner.borrow_mut();
if let Some(session) = guard.as_mut() {
if matches!(session.phase, DragPhase::Dragging | DragPhase::Over) {
if let Some(target) = session.target.take() {
let _ = target;
}
}
session.phase = DragPhase::Cancelled;
}
}
pub fn cancel_with_tree(&self, tree: &mut ElementTree) {
let mut guard = self.inner.borrow_mut();
if let Some(session) = guard.as_mut() {
if let Some(target) = session.target.take() {
with_drop_target(tree, target, |state| state.drag_leave());
tree.mark_element_dirty_with_semantics(target, false, false);
}
session.phase = DragPhase::Cancelled;
tree.mark_element_dirty_with_semantics(session.source, false, true);
}
}
pub fn keyboard_pickup(&self, tree: &ElementTree, source: ElementId, payload: DragPayload) -> bool {
let Some(el) = tree.get(source) else { return false };
let position = el.layout_offset();
self.begin(source, payload, position)
}
pub fn keyboard_move(&self, tree: &mut ElementTree, dx: f32, dy: f32) -> Option<ElementId> {
let position = self.inner.borrow().as_ref().map(|s| s.position)?;
self.update(tree, crate::Point::new(position.x + dx, position.y + dy))
}
pub fn keyboard_drop(&self, tree: &mut ElementTree) -> bool {
let Some(position) = self.inner.borrow().as_ref().map(|s| s.position) else { return false };
self.finish(tree, position)
}
pub fn clear(&self) {
*self.inner.borrow_mut() = None;
}
}
impl Default for DndManager {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for DndManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DndManager").field("session", &self.session()).finish()
}
}
fn find_drop_target(tree: &ElementTree, position: crate::Point, payload: &DragPayload) -> Option<ElementId> {
let mut current = tree.hit_test(position);
while let Some(id) = current {
let accepts = tree.get(id).and_then(|el| el.state()).is_some_and(|state| state.accepts_drag(payload));
if accepts {
return Some(id);
}
current = tree.get(id).and_then(|el| el.parent());
}
None
}
fn with_drop_target<R>(
tree: &mut ElementTree,
id: ElementId,
f: impl FnOnce(&mut dyn crate::widget::State) -> R,
) -> Option<R> {
tree.get_mut(id).and_then(|el| el.state_mut()).map(f)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Point;
#[test]
fn payload_is_typed_not_string_based() {
let p = DragPayload::new(42_i32);
assert!(p.is::<i32>());
assert!(!p.is::<String>());
assert_eq!(p.downcast_ref::<i32>(), Some(&42));
assert!(p.downcast_ref::<String>().is_none());
assert!(format!("{p:?}").contains("DragPayload"));
}
#[test]
fn begin_rejects_concurrent_active_session() {
let manager = DndManager::new();
assert!(manager.begin(ElementId::default(), DragPayload::new(1_i32), Point::ZERO));
assert!(!manager.begin(ElementId::default(), DragPayload::new(2_i32), Point::ZERO));
assert_eq!(manager.session().unwrap().payload.downcast_ref::<i32>(), Some(&1));
manager.cancel();
assert!(manager.begin(ElementId::default(), DragPayload::new(3_i32), Point::ZERO));
assert_eq!(manager.session().unwrap().payload.downcast_ref::<i32>(), Some(&3));
}
#[test]
fn semantic_label_reports_phase_and_payload_type() {
let manager = DndManager::new();
manager.begin(ElementId::default(), DragPayload::new(7_i32), Point::ZERO);
let label = manager.session().unwrap().semantic_label();
assert!(label.contains("拖拽中"), "{label}");
assert!(label.contains("i32"), "{label}");
assert!(label.contains("无目标"), "{label}");
manager.cancel();
assert!(manager.session().unwrap().semantic_label().contains("已取消"));
}
}