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