Skip to main content

cranpose_ui/modifier/
long_press.rs

1use std::{
2    cell::{Cell, RefCell},
3    hash::{Hash, Hasher},
4    rc::{Rc, Weak},
5};
6
7use cranpose_core::{NodeId, current_runtime_handle, internal::FrameCallbackRegistration};
8use cranpose_foundation::{
9    DRAG_THRESHOLD, DelegatableNode, ModifierNode, ModifierNodeContext, ModifierNodeElement,
10    NodeCapabilities, NodeState, PointerEvent, PointerEventKind, PointerId, PointerInputNode,
11    gesture_constants::LONG_PRESS_TIMEOUT_NANOS, impl_pointer_input_node,
12};
13use cranpose_ui_graphics::Point;
14
15use super::{Modifier, inspector_metadata};
16use crate::render_state::{AppContext, current_app_context};
17
18impl Modifier {
19    /// Calls `action` when a press rests on this node for the long press
20    /// time without moving, and offers a screen reader the same action
21    /// under `label`, as Compose's `combinedClickable(onLongClick)` does.
22    ///
23    /// The press then belongs to this node: the controls inside it see the
24    /// press cancelled and do not click when it ends.
25    ///
26    /// Example: `Modifier::empty().on_long_press("Show tooltip", move || shown.set(true))`
27    pub fn on_long_press(self, label: impl Into<String>, action: impl Fn() + 'static) -> Self {
28        let action: Rc<dyn Fn()> = Rc::new(action);
29        let reader = Rc::clone(&action);
30        self.then(
31            Self::with_element(LongPressElement { action })
32                .with_inspector_metadata(inspector_metadata("longPress", |_| {})),
33        )
34        .on_long_click(label, move || {
35            reader();
36            true
37        })
38    }
39}
40
41#[derive(Clone)]
42struct LongPressElement {
43    action: Rc<dyn Fn()>,
44}
45
46impl std::fmt::Debug for LongPressElement {
47    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        formatter.write_str("LongPressElement")
49    }
50}
51
52impl PartialEq for LongPressElement {
53    fn eq(&self, other: &Self) -> bool {
54        Rc::ptr_eq(&self.action, &other.action)
55    }
56}
57
58impl Hash for LongPressElement {
59    fn hash<H: Hasher>(&self, state: &mut H) {
60        "longPress".hash(state);
61    }
62}
63
64impl ModifierNodeElement for LongPressElement {
65    type Node = LongPressNode;
66
67    fn create(&self) -> Self::Node {
68        let press = Rc::new(Press::new(Rc::clone(&self.action)));
69        let dispatch_press = Rc::clone(&press);
70        LongPressNode {
71            dispatch: Rc::new(move |event| Press::on_event(&dispatch_press, &event)),
72            press,
73            state: NodeState::new(),
74        }
75    }
76
77    fn update(&self, node: &mut Self::Node) {
78        *node.press.action.borrow_mut() = Rc::clone(&self.action);
79    }
80
81    fn always_update(&self) -> bool {
82        true
83    }
84
85    fn capabilities(&self) -> NodeCapabilities {
86        NodeCapabilities::POINTER_INPUT
87    }
88}
89
90/// One held press and the frame timer that turns it into a long press.
91struct Press {
92    action: RefCell<Rc<dyn Fn()>>,
93    node: Cell<Option<NodeId>>,
94    /// Where the press went down, while it is held and still a press.
95    origin: Cell<Option<Point>>,
96    /// The first frame time after the press went down: frames and events
97    /// keep different clocks.
98    started_nanos: Cell<Option<u64>>,
99    fired: Cell<bool>,
100    // The pointer that holds the press: the first one that went down. The others pass by until
101    // it lifts.
102    holder: Cell<Option<PointerId>>,
103    context: RefCell<Weak<AppContext>>,
104    timer: RefCell<Option<FrameCallbackRegistration>>,
105}
106
107impl Press {
108    fn new(action: Rc<dyn Fn()>) -> Self {
109        Self {
110            action: RefCell::new(action),
111            node: Cell::new(None),
112            origin: Cell::new(None),
113            started_nanos: Cell::new(None),
114            fired: Cell::new(false),
115            holder: Cell::new(None),
116            context: RefCell::new(Weak::new()),
117            timer: RefCell::new(None),
118        }
119    }
120
121    fn on_event(press: &Rc<Self>, event: &PointerEvent) {
122        if press.holder.get().is_some_and(|held| held != event.id) {
123            return;
124        }
125        match event.kind {
126            PointerEventKind::Down if !event.is_consumed() => Self::begin(press, event),
127            PointerEventKind::Move if press.fired.get() => event.consume(),
128            PointerEventKind::Move => {
129                let moved = press.origin.get().is_some_and(|origin| {
130                    let to = event.global_position;
131                    (to.x - origin.x).hypot(to.y - origin.y) > DRAG_THRESHOLD
132                });
133                if moved || event.is_consumed() {
134                    press.end();
135                }
136            }
137            PointerEventKind::Up => {
138                if press.fired.get() {
139                    event.consume();
140                }
141                press.end();
142            }
143            PointerEventKind::Cancel => press.end(),
144            _ => {}
145        }
146    }
147
148    fn begin(press: &Rc<Self>, event: &PointerEvent) {
149        press.end();
150        let Some(runtime) = current_runtime_handle() else {
151            return;
152        };
153        press.origin.set(Some(event.global_position));
154        press.holder.set(Some(event.id));
155        *press.context.borrow_mut() = current_app_context()
156            .as_ref()
157            .map_or_else(Weak::new, Rc::downgrade);
158        Self::watch(press, &runtime);
159    }
160
161    /// Checks on each frame whether the press has rested long enough.
162    fn watch(press: &Rc<Self>, runtime: &cranpose_core::RuntimeHandle) {
163        let weak = Rc::downgrade(press);
164        let next = runtime.clone();
165        let registration = runtime.frame_clock().with_frame_nanos(move |frame_nanos| {
166            let Some(press) = weak.upgrade() else {
167                return;
168            };
169            press.timer.borrow_mut().take();
170            if press.origin.get().is_none() {
171                return;
172            }
173            let started = press.started_nanos.get().unwrap_or(frame_nanos);
174            press.started_nanos.set(Some(started));
175            if frame_nanos.saturating_sub(started) < LONG_PRESS_TIMEOUT_NANOS {
176                Self::watch(&press, &next);
177                return;
178            }
179            press.fired.set(true);
180            if let (Some(context), Some(node), Some(holder)) = (
181                press.context.borrow().upgrade(),
182                press.node.get(),
183                press.holder.get(),
184            ) {
185                context.claim_pointer(node, holder);
186            }
187            let action = Rc::clone(&press.action.borrow());
188            action();
189        });
190        *press.timer.borrow_mut() = Some(registration);
191    }
192
193    fn end(&self) {
194        self.timer.borrow_mut().take();
195        self.origin.set(None);
196        self.started_nanos.set(None);
197        self.fired.set(false);
198        self.holder.set(None);
199    }
200}
201
202struct LongPressNode {
203    dispatch: Rc<dyn Fn(PointerEvent)>,
204    press: Rc<Press>,
205    state: NodeState,
206}
207
208impl ModifierNode for LongPressNode {
209    fn on_attach(&mut self, context: &mut dyn ModifierNodeContext) {
210        self.press.node.set(context.node_id());
211        context.invalidate(cranpose_foundation::InvalidationKind::PointerInput);
212    }
213
214    fn on_detach(&mut self) {
215        self.press.end();
216        self.press.node.set(None);
217    }
218
219    impl_pointer_input_node!();
220}
221
222impl DelegatableNode for LongPressNode {
223    fn node_state(&self) -> &NodeState {
224        &self.state
225    }
226}
227
228impl PointerInputNode for LongPressNode {
229    fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
230        Some(Rc::clone(&self.dispatch))
231    }
232}