1use std::{
2 any::Any,
3 fmt,
4 sync::{
5 Arc, Mutex,
6 atomic::{AtomicU64, Ordering},
7 },
8};
9
10use crate::{ImageHandle, Modifiers, 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 pub const fn for_modifiers(modifiers: Modifiers) -> Option<Self> {
99 let (copy, moving) = if cfg!(target_os = "macos") {
100 (modifiers.alt, modifiers.meta)
101 } else {
102 (modifiers.control, modifiers.shift)
103 };
104 match (copy, moving) {
105 (true, true) => Some(Self::Link),
106 (true, false) => Some(Self::Copy),
107 (false, true) => Some(Self::Move),
108 (false, false) => None,
109 }
110 }
111
112 const fn bit(self) -> u8 {
113 match self {
114 Self::None => 0,
115 Self::Copy => 1,
116 Self::Move => 2,
117 Self::Link => 4,
118 }
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
124pub struct DropEffects(u8);
125
126impl DropEffects {
127 pub const NONE: Self = Self(0);
128 pub const COPY: Self = Self(1);
129 pub const MOVE: Self = Self(2);
130 pub const LINK: Self = Self(4);
131 pub const ALL: Self = Self(7);
132
133 pub const fn contains(self, effect: DropEffect) -> bool {
134 effect.is_some() && self.0 & effect.bit() != 0
135 }
136
137 pub const fn is_empty(self) -> bool {
138 self.0 == 0
139 }
140
141 pub const fn with(self, effect: DropEffect) -> Self {
143 Self(self.0 | effect.bit())
144 }
145
146 pub const fn default_effect(self) -> DropEffect {
149 if self.contains(DropEffect::Move) {
150 DropEffect::Move
151 } else if self.contains(DropEffect::Copy) {
152 DropEffect::Copy
153 } else if self.contains(DropEffect::Link) {
154 DropEffect::Link
155 } else {
156 DropEffect::None
157 }
158 }
159}
160
161impl From<DropEffect> for DropEffects {
162 fn from(effect: DropEffect) -> Self {
163 Self::NONE.with(effect)
164 }
165}
166
167impl std::ops::BitOr for DropEffects {
168 type Output = Self;
169
170 fn bitor(self, other: Self) -> Self {
171 Self(self.0 | other.0)
172 }
173}
174
175#[derive(Clone)]
176pub enum DragPayload {
177 Text(String),
178 Image {
179 handle: ImageHandle,
180 region: Option<Rect>,
181 },
182 Custom {
183 kind: Arc<str>,
184 data: Arc<dyn Any + Send + Sync>,
185 },
186}
187
188impl DragPayload {
189 pub fn text(text: impl Into<String>) -> Self {
190 Self::Text(text.into())
191 }
192
193 pub fn image(handle: ImageHandle) -> Self {
194 Self::Image {
195 handle,
196 region: None,
197 }
198 }
199
200 pub fn image_region(handle: ImageHandle, region: Rect) -> Self {
201 Self::Image {
202 handle,
203 region: Some(region),
204 }
205 }
206
207 pub fn custom<T>(kind: impl Into<Arc<str>>, data: T) -> Self
208 where
209 T: Any + Send + Sync + 'static,
210 {
211 Self::Custom {
212 kind: kind.into(),
213 data: Arc::new(data),
214 }
215 }
216
217 pub fn as_text(&self) -> Option<&str> {
218 match self {
219 Self::Text(text) => Some(text),
220 Self::Image { .. } | Self::Custom { .. } => None,
221 }
222 }
223
224 pub fn custom_kind(&self) -> Option<&str> {
225 match self {
226 Self::Custom { kind, .. } => Some(kind.as_ref()),
227 Self::Text(_) | Self::Image { .. } => None,
228 }
229 }
230
231 pub fn custom_data<T>(&self) -> Option<&T>
232 where
233 T: Any + Send + Sync + 'static,
234 {
235 match self {
236 Self::Custom { data, .. } => data.downcast_ref(),
237 Self::Text(_) | Self::Image { .. } => None,
238 }
239 }
240}
241
242impl fmt::Debug for DragPayload {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 match self {
245 Self::Text(text) => f.debug_tuple("Text").field(text).finish(),
246 Self::Image { handle, region } => f
247 .debug_struct("Image")
248 .field("handle", handle)
249 .field("region", region)
250 .finish(),
251 Self::Custom { kind, .. } => f
252 .debug_struct("Custom")
253 .field("kind", kind)
254 .finish_non_exhaustive(),
255 }
256 }
257}
258
259impl PartialEq for DragPayload {
260 fn eq(&self, other: &Self) -> bool {
261 match (self, other) {
262 (Self::Text(left), Self::Text(right)) => left == right,
263 (
264 Self::Image {
265 handle: left_handle,
266 region: left_region,
267 },
268 Self::Image {
269 handle: right_handle,
270 region: right_region,
271 },
272 ) => left_handle == right_handle && left_region == right_region,
273 (Self::Custom { kind: left, .. }, Self::Custom { kind: right, .. }) => left == right,
274 _ => false,
275 }
276 }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum DragOutcome {
281 Dropped {
282 target: WidgetId,
283 effect: DropEffect,
284 },
285 Cancelled,
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum DragEventKind {
290 Enter,
291 Over,
292 Leave,
293 Drop,
294 End,
295}
296
297#[derive(Debug, Clone, PartialEq)]
298pub struct DragEvent {
299 pub kind: DragEventKind,
300 pub session_id: DragSessionId,
301 pub scope_id: DragScopeId,
302 pub pointer_id: u64,
303 pub source: WidgetId,
304 pub target: Option<WidgetId>,
305 pub position: Point,
306 pub start_position: Point,
307 pub payload: DragPayload,
308 pub allowed_effect: DropEffect,
310 pub allowed_effects: DropEffects,
312 pub accepted_effect: DropEffect,
313 pub preview_label: Option<Arc<str>>,
314 pub outcome: Option<DragOutcome>,
315 pub modifiers: Modifiers,
319}
320
321impl DragEvent {
322 pub const fn requested_effect(&self) -> Option<DropEffect> {
325 DropEffect::for_modifiers(self.modifiers)
326 }
327
328 pub fn preferred_effect(&self) -> DropEffect {
331 self.requested_effect()
332 .filter(|effect| self.allowed_effects.contains(*effect))
333 .unwrap_or(self.allowed_effect)
334 }
335}
336
337#[derive(Debug, Clone, PartialEq)]
338pub struct DragPreview {
339 pub session_id: DragSessionId,
340 pub scope_id: DragScopeId,
341 pub pointer_id: u64,
342 pub source: WidgetId,
343 pub position: Point,
344 pub start_position: Point,
345 pub payload: DragPayload,
346 pub allowed_effect: DropEffect,
347 pub allowed_effects: DropEffects,
348 pub preview_label: Option<Arc<str>>,
349}
350
351#[derive(Debug, Default)]
352struct DragDropState {
353 active: Option<DragPreview>,
354}
355
356#[derive(Clone, Debug)]
357pub struct DragDropScope {
358 id: DragScopeId,
359 inner: Arc<Mutex<DragDropState>>,
360}
361
362impl DragDropScope {
363 pub fn new() -> Self {
364 Self {
365 id: DragScopeId::new(NEXT_DRAG_SCOPE_ID.fetch_add(1, Ordering::Relaxed)),
366 inner: Arc::new(Mutex::new(DragDropState::default())),
367 }
368 }
369
370 pub const fn id(&self) -> DragScopeId {
371 self.id
372 }
373
374 pub fn active_drag(&self) -> Option<DragPreview> {
375 self.inner
376 .lock()
377 .unwrap_or_else(std::sync::PoisonError::into_inner)
378 .active
379 .clone()
380 }
381
382 pub fn set_active_drag(&self, active: DragPreview) {
383 self.inner
384 .lock()
385 .unwrap_or_else(std::sync::PoisonError::into_inner)
386 .active = Some(active);
387 }
388
389 pub fn update_drag_position(&self, session_id: DragSessionId, position: Point) -> bool {
390 let mut state = self
391 .inner
392 .lock()
393 .unwrap_or_else(std::sync::PoisonError::into_inner);
394 let Some(active) = &mut state.active else {
395 return false;
396 };
397 if active.session_id != session_id {
398 return false;
399 }
400 active.position = position;
401 true
402 }
403
404 pub fn finish_drag(&self, session_id: DragSessionId) -> bool {
405 let mut state = self
406 .inner
407 .lock()
408 .unwrap_or_else(std::sync::PoisonError::into_inner);
409 if state
410 .active
411 .as_ref()
412 .is_some_and(|active| active.session_id == session_id)
413 {
414 state.active = None;
415 true
416 } else {
417 false
418 }
419 }
420
421 pub fn clear(&self) {
422 self.inner
423 .lock()
424 .unwrap_or_else(std::sync::PoisonError::into_inner)
425 .active = None;
426 }
427}
428
429impl Default for DragDropScope {
430 fn default() -> Self {
431 Self::new()
432 }
433}