Skip to main content

sui_core/
drag.rs

1use std::{
2    any::Any,
3    cell::RefCell,
4    fmt,
5    rc::Rc,
6    sync::{
7        Arc,
8        atomic::{AtomicU64, Ordering},
9    },
10};
11
12use crate::{ImageHandle, Point, Rect, WidgetId};
13
14static NEXT_DRAG_SCOPE_ID: AtomicU64 = AtomicU64::new(1);
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
17pub struct DragScopeId(u64);
18
19impl DragScopeId {
20    pub const fn new(raw: u64) -> Self {
21        Self(raw)
22    }
23
24    pub const fn get(self) -> u64 {
25        self.0
26    }
27}
28
29impl From<u64> for DragScopeId {
30    fn from(value: u64) -> Self {
31        Self::new(value)
32    }
33}
34
35impl From<DragScopeId> for u64 {
36    fn from(value: DragScopeId) -> Self {
37        value.get()
38    }
39}
40
41impl fmt::Display for DragScopeId {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        write!(f, "{}", self.0)
44    }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
48pub struct DragSessionId(u64);
49
50impl DragSessionId {
51    pub const fn new(raw: u64) -> Self {
52        Self(raw)
53    }
54
55    pub const fn get(self) -> u64 {
56        self.0
57    }
58}
59
60impl From<u64> for DragSessionId {
61    fn from(value: u64) -> Self {
62        Self::new(value)
63    }
64}
65
66impl From<DragSessionId> for u64 {
67    fn from(value: DragSessionId) -> Self {
68        value.get()
69    }
70}
71
72impl fmt::Display for DragSessionId {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(f, "{}", self.0)
75    }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
79pub enum DropEffect {
80    #[default]
81    None,
82    Copy,
83    Move,
84    Link,
85}
86
87impl DropEffect {
88    pub const fn is_none(self) -> bool {
89        matches!(self, Self::None)
90    }
91
92    pub const fn is_some(self) -> bool {
93        !self.is_none()
94    }
95}
96
97#[derive(Clone)]
98pub enum DragPayload {
99    Text(String),
100    Image {
101        handle: ImageHandle,
102        region: Option<Rect>,
103    },
104    Custom {
105        kind: Arc<str>,
106        data: Arc<dyn Any + Send + Sync>,
107    },
108}
109
110impl DragPayload {
111    pub fn text(text: impl Into<String>) -> Self {
112        Self::Text(text.into())
113    }
114
115    pub fn image(handle: ImageHandle) -> Self {
116        Self::Image {
117            handle,
118            region: None,
119        }
120    }
121
122    pub fn image_region(handle: ImageHandle, region: Rect) -> Self {
123        Self::Image {
124            handle,
125            region: Some(region),
126        }
127    }
128
129    pub fn custom<T>(kind: impl Into<Arc<str>>, data: T) -> Self
130    where
131        T: Any + Send + Sync + 'static,
132    {
133        Self::Custom {
134            kind: kind.into(),
135            data: Arc::new(data),
136        }
137    }
138
139    pub fn as_text(&self) -> Option<&str> {
140        match self {
141            Self::Text(text) => Some(text),
142            Self::Image { .. } | Self::Custom { .. } => None,
143        }
144    }
145
146    pub fn custom_kind(&self) -> Option<&str> {
147        match self {
148            Self::Custom { kind, .. } => Some(kind.as_ref()),
149            Self::Text(_) | Self::Image { .. } => None,
150        }
151    }
152
153    pub fn custom_data<T>(&self) -> Option<&T>
154    where
155        T: Any + Send + Sync + 'static,
156    {
157        match self {
158            Self::Custom { data, .. } => data.downcast_ref(),
159            Self::Text(_) | Self::Image { .. } => None,
160        }
161    }
162}
163
164impl fmt::Debug for DragPayload {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        match self {
167            Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
168            Self::Image { handle, region } => f
169                .debug_struct("Image")
170                .field("handle", handle)
171                .field("region", region)
172                .finish(),
173            Self::Custom { kind, .. } => f
174                .debug_struct("Custom")
175                .field("kind", kind)
176                .finish_non_exhaustive(),
177        }
178    }
179}
180
181impl PartialEq for DragPayload {
182    fn eq(&self, other: &Self) -> bool {
183        match (self, other) {
184            (Self::Text(left), Self::Text(right)) => left == right,
185            (
186                Self::Image {
187                    handle: left_handle,
188                    region: left_region,
189                },
190                Self::Image {
191                    handle: right_handle,
192                    region: right_region,
193                },
194            ) => left_handle == right_handle && left_region == right_region,
195            (Self::Custom { kind: left, .. }, Self::Custom { kind: right, .. }) => left == right,
196            _ => false,
197        }
198    }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum DragOutcome {
203    Dropped {
204        target: WidgetId,
205        effect: DropEffect,
206    },
207    Cancelled,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211pub enum DragEventKind {
212    Enter,
213    Over,
214    Leave,
215    Drop,
216    End,
217}
218
219#[derive(Debug, Clone, PartialEq)]
220pub struct DragEvent {
221    pub kind: DragEventKind,
222    pub session_id: DragSessionId,
223    pub scope_id: DragScopeId,
224    pub pointer_id: u64,
225    pub source: WidgetId,
226    pub target: Option<WidgetId>,
227    pub position: Point,
228    pub start_position: Point,
229    pub payload: DragPayload,
230    pub allowed_effect: DropEffect,
231    pub accepted_effect: DropEffect,
232    pub preview_label: Option<Arc<str>>,
233    pub outcome: Option<DragOutcome>,
234}
235
236#[derive(Debug, Clone, PartialEq)]
237pub struct DragPreview {
238    pub session_id: DragSessionId,
239    pub scope_id: DragScopeId,
240    pub pointer_id: u64,
241    pub source: WidgetId,
242    pub position: Point,
243    pub start_position: Point,
244    pub payload: DragPayload,
245    pub allowed_effect: DropEffect,
246    pub preview_label: Option<Arc<str>>,
247}
248
249#[derive(Debug, Default)]
250struct DragDropState {
251    active: Option<DragPreview>,
252}
253
254#[derive(Clone, Debug)]
255pub struct DragDropScope {
256    id: DragScopeId,
257    inner: Rc<RefCell<DragDropState>>,
258}
259
260impl DragDropScope {
261    pub fn new() -> Self {
262        Self {
263            id: DragScopeId::new(NEXT_DRAG_SCOPE_ID.fetch_add(1, Ordering::Relaxed)),
264            inner: Rc::new(RefCell::new(DragDropState::default())),
265        }
266    }
267
268    pub const fn id(&self) -> DragScopeId {
269        self.id
270    }
271
272    pub fn active_drag(&self) -> Option<DragPreview> {
273        self.inner.borrow().active.clone()
274    }
275
276    pub fn set_active_drag(&self, active: DragPreview) {
277        self.inner.borrow_mut().active = Some(active);
278    }
279
280    pub fn update_drag_position(&self, session_id: DragSessionId, position: Point) -> bool {
281        let mut state = self.inner.borrow_mut();
282        let Some(active) = &mut state.active else {
283            return false;
284        };
285        if active.session_id != session_id {
286            return false;
287        }
288        active.position = position;
289        true
290    }
291
292    pub fn finish_drag(&self, session_id: DragSessionId) -> bool {
293        let mut state = self.inner.borrow_mut();
294        if state
295            .active
296            .as_ref()
297            .is_some_and(|active| active.session_id == session_id)
298        {
299            state.active = None;
300            true
301        } else {
302            false
303        }
304    }
305
306    pub fn clear(&self) {
307        self.inner.borrow_mut().active = None;
308    }
309}
310
311impl Default for DragDropScope {
312    fn default() -> Self {
313        Self::new()
314    }
315}