egui_pop_core/pointer/drag.rs
1//! Drag cursors: the cursor a draggable shows, hovered and while it is
2//! dragged, keyed by what the drag means ([`DragKind`]) rather than by
3//! widget.
4//!
5//! egui resets the cursor every pass, and the pointer leaves a widget
6//! while it drags it: a cursor set only when the widget is hovered, or
7//! only where the pointer is over it, comes back to the arrow mid-drag.
8//! [`drag_cursor`] asks the drag's cursor every pass the response is
9//! dragged, wherever the pointer is, and the hover cursor only while
10//! nothing else is dragged.
11//!
12//! **The hover rule.** By default a draggable shows its hover cursor
13//! only when dragging is its only action ([`HoverPolicy::OnlyAction`]):
14//! a splitter, a resize grip, an item's handle. Where a click or a
15//! double click does something (select, set a value, move the playhead),
16//! the arrow stays until the drag starts. Whether a response clicks is
17//! read from its sense, unless the widget says ([`DragCursorFor::clicks`]).
18//!
19//! **Three levels**, the most specific winning: the widget
20//! ([`DragCursorFor::hover`], [`DragCursorFor::dragging`],
21//! [`DragCursorFor::hover_policy`]), the pointer profile
22//! ([`PointerMap::drag_cursor_over`](egui_pop_model::pointer::PointerMap::drag_cursor_over)),
23//! the kit (`drag-cursor.<kind>.hover`, `.drag`, `.policy`:
24//! [`DragCursorKit`](crate::kit::DragCursorKit)), over the kind's own
25//! ([`DragKind::cursors`]).
26//!
27//! ```
28//! use egui_pop_core::pointer::{self, DragKind, HoverPolicy};
29//!
30//! let ctx = egui::Context::default();
31//! let mut out = ctx.run_ui(Default::default(), |ui| {
32//! let (_, splitter) = ui.allocate_exact_size(egui::vec2(4.0, 100.0), egui::Sense::drag());
33//! pointer::drag_cursor(&splitter, DragKind::SplitColumns);
34//! // A click selects it: the arrow until it is dragged, unless asked.
35//! let (_, clip) = ui.allocate_exact_size(egui::vec2(100.0, 20.0), egui::Sense::click_and_drag());
36//! pointer::drag_cursor(&clip, DragKind::Move).hover_policy(HoverPolicy::Always);
37//! });
38//! out.textures_delta.clear();
39//! assert_eq!(
40//! pointer::drag_cursor_icons(&ctx, DragKind::Pan),
41//! (egui::CursorIcon::Grab, egui::CursorIcon::Grabbing)
42//! );
43//! ```
44
45use egui::{Context, CursorIcon, Response};
46
47pub use egui_pop_model::pointer::{CURSOR_NAMES, DragCursor, DragKind, HoverPolicy};
48
49/// egui's cursor of a CSS cursor name ([`CURSOR_NAMES`]).
50pub fn cursor_icon(name: &str) -> Option<CursorIcon> {
51 Some(match name {
52 "alias" => CursorIcon::Alias,
53 "all-scroll" => CursorIcon::AllScroll,
54 "cell" => CursorIcon::Cell,
55 "context-menu" => CursorIcon::ContextMenu,
56 "copy" => CursorIcon::Copy,
57 "crosshair" => CursorIcon::Crosshair,
58 "default" => CursorIcon::Default,
59 "grab" => CursorIcon::Grab,
60 "grabbing" => CursorIcon::Grabbing,
61 "help" => CursorIcon::Help,
62 "move" => CursorIcon::Move,
63 "no-drop" => CursorIcon::NoDrop,
64 "none" => CursorIcon::None,
65 "not-allowed" => CursorIcon::NotAllowed,
66 "pointer" => CursorIcon::PointingHand,
67 "progress" => CursorIcon::Progress,
68 "ew-resize" => CursorIcon::ResizeHorizontal,
69 "nesw-resize" => CursorIcon::ResizeNeSw,
70 "nwse-resize" => CursorIcon::ResizeNwSe,
71 "ns-resize" => CursorIcon::ResizeVertical,
72 "e-resize" => CursorIcon::ResizeEast,
73 "se-resize" => CursorIcon::ResizeSouthEast,
74 "s-resize" => CursorIcon::ResizeSouth,
75 "sw-resize" => CursorIcon::ResizeSouthWest,
76 "w-resize" => CursorIcon::ResizeWest,
77 "nw-resize" => CursorIcon::ResizeNorthWest,
78 "n-resize" => CursorIcon::ResizeNorth,
79 "ne-resize" => CursorIcon::ResizeNorthEast,
80 "col-resize" => CursorIcon::ResizeColumn,
81 "row-resize" => CursorIcon::ResizeRow,
82 "text" => CursorIcon::Text,
83 "vertical-text" => CursorIcon::VerticalText,
84 "wait" => CursorIcon::Wait,
85 "zoom-in" => CursorIcon::ZoomIn,
86 "zoom-out" => CursorIcon::ZoomOut,
87 _ => return None,
88 })
89}
90
91/// A drag kind's cursors in a context, with its hover policy: the
92/// kit's ([`DragCursorKit`](crate::kit::DragCursorKit)), under the
93/// pointer map's ([`super::map`]).
94pub fn resolve_drag_cursor(ctx: &Context, kind: DragKind) -> DragCursor {
95 let kit = crate::kit::Kit::of(ctx).drag_cursors.get(kind);
96 super::map(ctx).drag_cursor_over(kind, kit)
97}
98
99/// A drag kind's cursors in a context, hovered and dragged: the kit's
100/// under the pointer map's ([`resolve_drag_cursor`]).
101pub fn drag_cursor_icons(ctx: &Context, kind: DragKind) -> (CursorIcon, CursorIcon) {
102 let c = resolve_drag_cursor(ctx, kind);
103 (
104 cursor_icon(&c.hover).unwrap_or_default(),
105 cursor_icon(&c.drag).unwrap_or_default(),
106 )
107}
108
109/// Shows the cursor of a drag of `kind` for a response: its drag cursor
110/// every pass it is dragged, wherever the pointer is; its hover cursor
111/// while it is hovered and nothing is dragged, as the hover policy says
112/// ([`HoverPolicy`]). Called each pass the widget is drawn, after
113/// anything else that sets the cursor for it.
114///
115/// It returns what to show, applied when dropped (at the end of the
116/// statement): the widget may change it first.
117///
118/// ```
119/// # use egui_pop_core::pointer::{self, DragKind, HoverPolicy};
120/// # let ctx = egui::Context::default();
121/// # let mut out = ctx.run_ui(Default::default(), |ui| {
122/// # let (_, response) = ui.allocate_exact_size(egui::vec2(100.0, 20.0), egui::Sense::click_and_drag());
123/// // The response senses clicks only to take the focus: dragging is
124/// // its only action.
125/// pointer::drag_cursor(&response, DragKind::SplitRows).clicks(false);
126/// # });
127/// # out.textures_delta.clear();
128/// ```
129pub fn drag_cursor(response: &Response, kind: DragKind) -> DragCursorFor<'_> {
130 DragCursorFor {
131 response,
132 kind,
133 clicks: None,
134 hover: None,
135 dragging: None,
136 policy: None,
137 }
138}
139
140/// The cursor a draggable asks for ([`drag_cursor`]), shown when it is
141/// dropped. Its settings are the most specific level: they win over the
142/// pointer profile's and the kit's.
143#[derive(Debug)]
144pub struct DragCursorFor<'a> {
145 response: &'a Response,
146 kind: DragKind,
147 clicks: Option<bool>,
148 hover: Option<CursorIcon>,
149 dragging: Option<CursorIcon>,
150 policy: Option<HoverPolicy>,
151}
152
153impl DragCursorFor<'_> {
154 /// Whether a click or a double click on it does something (by
155 /// default, whether the response senses clicks): with
156 /// [`HoverPolicy::OnlyAction`], the hover cursor shows only when it
157 /// does not.
158 pub fn clicks(mut self, clicks: bool) -> Self {
159 self.clicks = Some(clicks);
160 self
161 }
162
163 /// The cursor shown hovered, when the policy shows one.
164 pub fn hover(mut self, cursor: CursorIcon) -> Self {
165 self.hover = Some(cursor);
166 self
167 }
168
169 /// The cursor shown while it is dragged.
170 pub fn dragging(mut self, cursor: CursorIcon) -> Self {
171 self.dragging = Some(cursor);
172 self
173 }
174
175 /// When the hover cursor shows.
176 pub fn hover_policy(mut self, policy: HoverPolicy) -> Self {
177 self.policy = Some(policy);
178 self
179 }
180}
181
182impl Drop for DragCursorFor<'_> {
183 fn drop(&mut self) {
184 let r = self.response;
185 let ctx = &r.ctx;
186 if r.dragged() {
187 let icon = self
188 .dragging
189 .unwrap_or_else(|| drag_cursor_icons(ctx, self.kind).1);
190 ctx.set_cursor_icon(icon);
191 } else if r.hovered() && ctx.dragged_id().is_none() {
192 let c = resolve_drag_cursor(ctx, self.kind);
193 let policy = self.policy.unwrap_or_else(|| c.hover_policy());
194 let clicks = self.clicks.unwrap_or_else(|| r.sense.senses_click());
195 if policy.shows(clicks) {
196 let icon = self
197 .hover
198 .unwrap_or_else(|| cursor_icon(&c.hover).unwrap_or_default());
199 if icon != CursorIcon::Default {
200 ctx.set_cursor_icon(icon);
201 }
202 }
203 }
204 }
205}
206
207/// Whether a drag's ghost goes under the pointer: the application API's
208/// drag session says so when its source gave it one, and a view that
209/// would show how many items it carries beside the pointer leaves that
210/// to the ghost.
211///
212/// <div class="warning">Experimental: may change in any release
213/// (docs/stability.md).</div>
214pub fn ghost_shown(ctx: &Context) -> bool {
215 ctx.data(|d| d.get_temp::<bool>(ghost_id()).unwrap_or(false))
216}
217
218/// Says whether a drag's ghost goes under the pointer ([`ghost_shown`]).
219///
220/// <div class="warning">Experimental: may change in any release
221/// (docs/stability.md).</div>
222pub fn set_ghost_shown(ctx: &Context, shown: bool) {
223 ctx.data_mut(|d| d.insert_temp(ghost_id(), shown));
224}
225
226fn ghost_id() -> egui::Id {
227 egui::Id::unique("egui_pop.drag.ghost_shown")
228}
229
230/// Shows the drag cursor of `kind` this pass: for a drag a widget
231/// follows itself (a state of its own rather than one response).
232pub fn hold_drag_cursor(ctx: &Context, kind: DragKind) {
233 ctx.set_cursor_icon(drag_cursor_icons(ctx, kind).1);
234}
235
236/// Shows the hover cursor of `kind` this pass over what a widget hovers
237/// itself, if the hover policy in force shows it for an element that
238/// does something on a click (`clicks`) or not, and unless it is the
239/// arrow (which leaves the cursor to whatever asked for one).
240pub fn hover_drag_cursor(ctx: &Context, kind: DragKind, clicks: bool) {
241 let c = resolve_drag_cursor(ctx, kind);
242 if !c.hover_policy().shows(clicks) {
243 return;
244 }
245 let hover = cursor_icon(&c.hover).unwrap_or_default();
246 if hover != CursorIcon::Default {
247 ctx.set_cursor_icon(hover);
248 }
249}