Skip to main content

crabshell_ui/
dnd.rs

1//! Drags that cross a window's edge: a button's drag going on as the
2//! platform's once the pointer leaves its window, and drags from other
3//! windows and programs dropped on buttons here. The platform carries
4//! them over `wl_data_device`; the window only finds targets and runs
5//! handlers.
6
7use std::any::{Any, TypeId};
8use std::cell::Cell;
9use std::rc::Rc;
10
11use crate::geometry::Point;
12use crate::input::{Action, DragPhase, PointerButton, run_all};
13use crate::tree::{NodeId, borrow};
14use crate::window::Window;
15
16/// What a drag carries to and from other programs:
17/// [`Button::drag_content`](crate::Button::drag_content) gives it, and
18/// [`Button::on_drop_content`](crate::Button::on_drop_content) takes it.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum DragContent {
21  /// Text, offered as `text/plain;charset=utf-8` and `UTF8_STRING`.
22  Text(String),
23  /// URIs, such as `file:///home/me/a.png`, offered as `text/uri-list`.
24  Uris(Vec<String>),
25}
26
27/// A drag that left its window, for the platform to carry on.
28#[derive(Clone, Debug, PartialEq)]
29pub struct DragOut {
30  /// The type of what it carries, which `on_drop` targets in other
31  /// windows are matched by.
32  pub carried: TypeId,
33  /// What other programs are offered, when it carries a [`DragContent`].
34  pub content: Option<DragContent>,
35}
36
37/// The button a drag from elsewhere was dropped on, which takes the
38/// value once it has come.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub struct DropSpot(NodeId);
41
42/// A drag from another window or program over this one, at a point in
43/// the window, carrying a value of a type.
44#[derive(Clone, Copy)]
45pub(crate) struct Incoming {
46  pub(crate) at: Point,
47  pub(crate) carried: TypeId,
48}
49
50impl Window {
51  /// The held left-button drag carrying a value, once the pointer has
52  /// gone past the window's edge. From then on it is the platform's: a
53  /// pointer leave doesn't end it, and [`end_drag_out`](Self::end_drag_out)
54  /// does. Returns it only once.
55  pub fn take_drag_out(&self) -> Option<DragOut> {
56    let mut tree = borrow(&self.tree);
57    let at = tree.pointer.position?;
58    let size = tree.size;
59    if at.x >= 0.0 && at.y >= 0.0 && at.x < size.width && at.y < size.height {
60      return None;
61    }
62    let press = tree
63      .pointer
64      .pressed
65      .filter(|press| press.dragging && !press.out && press.button == PointerButton::Left)?;
66    let value = tree.drag_value(press.id)?;
67    if let Some(press) = tree.pointer.pressed.as_mut() {
68      press.out = true;
69    }
70    tree.update_drop();
71    Some(DragOut {
72      carried: (*value).type_id(),
73      content: value.downcast_ref::<DragContent>().cloned(),
74    })
75  }
76
77  /// Whether a drag taken by [`take_drag_out`](Self::take_drag_out) is
78  /// still held: its button wasn't removed, hidden or turned off.
79  pub fn dragging_out(&self) -> bool {
80    let tree = borrow(&self.tree);
81    tree.pointer.pressed.is_some_and(|press| press.out)
82  }
83
84  /// The drag that went out moved to `at` over its own window, which
85  /// its `on_drag` hears as a `Move`.
86  pub fn drag_out_moved(&self, at: Point) {
87    let call = {
88      let mut tree = borrow(&self.tree);
89      let Some(press) = tree.pointer.pressed.as_mut().filter(|press| press.out) else {
90        return;
91      };
92      press.last = at;
93      let press = *press;
94      tree.drag_call(press, DragPhase::Move, at, None)
95    };
96    run_all(call.into_iter().collect());
97  }
98
99  /// Ends the drag that went out, as a release does: the button's
100  /// `on_release` runs, then `drop` with what it carries now, which says
101  /// whether a target's `on_drop` ran and returned, then its `End`. A
102  /// button that went meanwhile runs nothing and drops nothing.
103  pub fn end_drag_out(&self, drop: impl FnOnce(Rc<dyn Any>) -> bool) {
104    let (release, value) = {
105      let tree = borrow(&self.tree);
106      let Some(press) = tree.pointer.pressed.filter(|press| press.out) else {
107        return;
108      };
109      (
110        tree.call(press.id, Action::Release),
111        tree.drag_value(press.id),
112      )
113    };
114    run_all(release.into_iter().collect());
115    let landed = Rc::new(Cell::new(false));
116    if let Some(value) = value {
117      landed.set(drop(value));
118    }
119    let end = {
120      let mut tree = borrow(&self.tree);
121      match tree.pointer.pressed.is_some_and(|press| press.out) {
122        true => tree.end_press(Some(landed)),
123        false => None,
124      }
125    };
126    run_all(end.into_iter().collect());
127  }
128
129  /// A drag from elsewhere entered or moved to `at`, carrying a value of
130  /// type `carried`. Returns whether a button here would take it, which
131  /// that button's `drop_hovered` shows.
132  pub fn drag_over(&self, at: Point, carried: TypeId) -> bool {
133    let mut tree = borrow(&self.tree);
134    tree.pointer.incoming = Some(Incoming { at, carried });
135    tree.update_drop();
136    tree.pointer.drop_over.is_some()
137  }
138
139  /// Whether a button here takes the drag from elsewhere now, which a
140  /// layout or a hidden button may have changed under a still drag.
141  pub fn drag_takes(&self) -> bool {
142    let tree = borrow(&self.tree);
143    tree.pointer.incoming.is_some() && tree.pointer.drop_over.is_some()
144  }
145
146  /// The drag from elsewhere left the window.
147  pub fn drag_leave(&self) {
148    let mut tree = borrow(&self.tree);
149    if tree.pointer.incoming.take().is_some() {
150      tree.update_drop();
151    }
152  }
153
154  /// The drag from elsewhere was dropped where it last was. Forgets it,
155  /// and returns the button that takes it, if any.
156  pub fn drag_drop(&self) -> Option<DropSpot> {
157    let mut tree = borrow(&self.tree);
158    tree.pointer.incoming?;
159    let target = tree.drop_target();
160    tree.pointer.incoming = None;
161    tree.update_drop();
162    target.map(DropSpot)
163  }
164
165  /// Gives `value` to the `on_drop` of the button at `spot`, if it is
166  /// still shown, turned on and takes the value's type. Returns whether
167  /// the handler ran and returned.
168  pub fn drop_into(&self, spot: DropSpot, value: Rc<dyn Any>) -> bool {
169    let landed = Rc::new(Cell::new(false));
170    let call = {
171      let tree = borrow(&self.tree);
172      let carried = (*value).type_id();
173      // A hidden button's placed rectangle is forgotten.
174      let shown = tree.node(spot.0).is_some_and(|node| node.rect.is_some());
175      let takes = shown
176        && tree.enabled(spot.0)
177        && tree.has(spot.0, |h| {
178          h.drop
179            .as_ref()
180            .is_some_and(|target| target.accepts == carried && !target.handler.disabled())
181        });
182      takes
183        .then(|| tree.call(spot.0, Action::Drop(value, Rc::clone(&landed))))
184        .flatten()
185    };
186    run_all(call.into_iter().collect());
187    landed.get()
188  }
189}