1use std::{any::Any, rc::Rc};
2
3use collections::HashSet;
4use gpui::{
5 elements::{MouseEventHandler, Overlay},
6 geometry::vector::Vector2F,
7 scene::MouseDrag,
8 CursorStyle, Element, ElementBox, EventContext, MouseButton, MutableAppContext, RenderContext,
9 View, WeakViewHandle,
10};
11
12struct State<V: View> {
13 window_id: usize,
14 position: Vector2F,
15 region_offset: Vector2F,
16 payload: Rc<dyn Any + 'static>,
17 render: Rc<dyn Fn(Rc<dyn Any>, &mut RenderContext<V>) -> ElementBox>,
18}
19
20impl<V: View> Clone for State<V> {
21 fn clone(&self) -> Self {
22 Self {
23 window_id: self.window_id.clone(),
24 position: self.position.clone(),
25 region_offset: self.region_offset.clone(),
26 payload: self.payload.clone(),
27 render: self.render.clone(),
28 }
29 }
30}
31
32pub struct DragAndDrop<V: View> {
33 containers: HashSet<WeakViewHandle<V>>,
34 currently_dragged: Option<State<V>>,
35}
36
37impl<V: View> Default for DragAndDrop<V> {
38 fn default() -> Self {
39 Self {
40 containers: Default::default(),
41 currently_dragged: Default::default(),
42 }
43 }
44}
45
46impl<V: View> DragAndDrop<V> {
47 pub fn register_container(&mut self, handle: WeakViewHandle<V>) {
48 self.containers.insert(handle);
49 }
50
51 pub fn currently_dragged<T: Any>(&self, window_id: usize) -> Option<(Vector2F, Rc<T>)> {
52 self.currently_dragged.as_ref().and_then(
53 |State {
54 position,
55 payload,
56 window_id: window_dragged_from,
57 ..
58 }| {
59 if &window_id != window_dragged_from {
60 return None;
61 }
62
63 payload
64 .clone()
65 .downcast::<T>()
66 .ok()
67 .map(|payload| (position.clone(), payload))
68 },
69 )
70 }
71
72 pub fn dragging<T: Any>(
73 event: MouseDrag,
74 payload: Rc<T>,
75 cx: &mut EventContext,
76 render: Rc<impl 'static + Fn(&T, &mut RenderContext<V>) -> ElementBox>,
77 ) {
78 let window_id = cx.window_id();
79 cx.update_global::<Self, _, _>(|this, cx| {
80 let region_offset = if let Some(previous_state) = this.currently_dragged.as_ref() {
81 previous_state.region_offset
82 } else {
83 event.region.origin() - event.prev_mouse_position
84 };
85
86 this.currently_dragged = Some(State {
87 window_id,
88 region_offset,
89 position: event.position,
90 payload,
91 render: Rc::new(move |payload, cx| {
92 render(payload.downcast_ref::<T>().unwrap(), cx)
93 }),
94 });
95
96 this.notify_containers_for_window(window_id, cx);
97 });
98 }
99
100 pub fn render(cx: &mut RenderContext<V>) -> Option<ElementBox> {
101 let currently_dragged = cx.global::<Self>().currently_dragged.clone();
102
103 currently_dragged.and_then(
104 |State {
105 window_id,
106 region_offset,
107 position,
108 payload,
109 render,
110 }| {
111 if cx.window_id() != window_id {
112 return None;
113 }
114
115 let position = position + region_offset;
116
117 enum DraggedElementHandler {}
118 Some(
119 Overlay::new(
120 MouseEventHandler::<DraggedElementHandler>::new(0, cx, |_, cx| {
121 render(payload, cx)
122 })
123 .with_cursor_style(CursorStyle::Arrow)
124 .on_up(MouseButton::Left, |_, cx| {
125 cx.defer(|cx| {
126 cx.update_global::<Self, _, _>(|this, cx| this.stop_dragging(cx));
127 });
128 cx.propagate_event();
129 })
130 .on_up_out(MouseButton::Left, |_, cx| {
131 cx.defer(|cx| {
132 cx.update_global::<Self, _, _>(|this, cx| this.stop_dragging(cx));
133 });
134 })
135 // Don't block hover events or invalidations
136 .with_hoverable(false)
137 .boxed(),
138 )
139 .with_anchor_position(position)
140 .boxed(),
141 )
142 },
143 )
144 }
145
146 fn stop_dragging(&mut self, cx: &mut MutableAppContext) {
147 if let Some(State { window_id, .. }) = self.currently_dragged.take() {
148 self.notify_containers_for_window(window_id, cx);
149 }
150 }
151
152 fn notify_containers_for_window(&mut self, window_id: usize, cx: &mut MutableAppContext) {
153 self.containers.retain(|container| {
154 if let Some(container) = container.upgrade(cx) {
155 if container.window_id() == window_id {
156 container.update(cx, |_, cx| cx.notify());
157 }
158 true
159 } else {
160 false
161 }
162 });
163 }
164}
165
166pub trait Draggable {
167 fn as_draggable<V: View, P: Any>(
168 self,
169 payload: P,
170 render: impl 'static + Fn(&P, &mut RenderContext<V>) -> ElementBox,
171 ) -> Self
172 where
173 Self: Sized;
174}
175
176impl<Tag> Draggable for MouseEventHandler<Tag> {
177 fn as_draggable<V: View, P: Any>(
178 self,
179 payload: P,
180 render: impl 'static + Fn(&P, &mut RenderContext<V>) -> ElementBox,
181 ) -> Self
182 where
183 Self: Sized,
184 {
185 let payload = Rc::new(payload);
186 let render = Rc::new(render);
187 self.on_drag(MouseButton::Left, move |e, cx| {
188 let payload = payload.clone();
189 let render = render.clone();
190 DragAndDrop::<V>::dragging(e, payload, cx, render)
191 })
192 }
193}