1use crate::{
2 div, point, px, Action, AnyDrag, AnyView, AppContext, BorrowWindow, Bounds, Component,
3 DispatchContext, DispatchPhase, Div, Element, ElementId, FocusHandle, KeyMatch, Keystroke,
4 Modifiers, Overflow, Pixels, Point, Render, SharedString, Size, Style, StyleRefinement, View,
5 ViewContext,
6};
7use collections::HashMap;
8use derive_more::{Deref, DerefMut};
9use parking_lot::Mutex;
10use refineable::Refineable;
11use smallvec::SmallVec;
12use std::{
13 any::{Any, TypeId},
14 fmt::Debug,
15 marker::PhantomData,
16 mem,
17 ops::Deref,
18 path::PathBuf,
19 sync::Arc,
20};
21
22const DRAG_THRESHOLD: f64 = 2.;
23
24pub trait StatelessInteractive<V: 'static>: Element<V> {
25 fn stateless_interaction(&mut self) -> &mut StatelessInteraction<V>;
26
27 fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
28 where
29 Self: Sized,
30 {
31 self.stateless_interaction().hover_style = f(StyleRefinement::default());
32 self
33 }
34
35 fn group_hover(
36 mut self,
37 group_name: impl Into<SharedString>,
38 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
39 ) -> Self
40 where
41 Self: Sized,
42 {
43 self.stateless_interaction().group_hover_style = Some(GroupStyle {
44 group: group_name.into(),
45 style: f(StyleRefinement::default()),
46 });
47 self
48 }
49
50 fn on_mouse_down(
51 mut self,
52 button: MouseButton,
53 handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
54 ) -> Self
55 where
56 Self: Sized,
57 {
58 self.stateless_interaction()
59 .mouse_down_listeners
60 .push(Box::new(move |view, event, bounds, phase, cx| {
61 if phase == DispatchPhase::Bubble
62 && event.button == button
63 && bounds.contains_point(&event.position)
64 {
65 handler(view, event, cx)
66 }
67 }));
68 self
69 }
70
71 fn on_mouse_up(
72 mut self,
73 button: MouseButton,
74 handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
75 ) -> Self
76 where
77 Self: Sized,
78 {
79 self.stateless_interaction()
80 .mouse_up_listeners
81 .push(Box::new(move |view, event, bounds, phase, cx| {
82 if phase == DispatchPhase::Bubble
83 && event.button == button
84 && bounds.contains_point(&event.position)
85 {
86 handler(view, event, cx)
87 }
88 }));
89 self
90 }
91
92 fn on_mouse_down_out(
93 mut self,
94 button: MouseButton,
95 handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
96 ) -> Self
97 where
98 Self: Sized,
99 {
100 self.stateless_interaction()
101 .mouse_down_listeners
102 .push(Box::new(move |view, event, bounds, phase, cx| {
103 if phase == DispatchPhase::Capture
104 && event.button == button
105 && !bounds.contains_point(&event.position)
106 {
107 handler(view, event, cx)
108 }
109 }));
110 self
111 }
112
113 fn on_mouse_up_out(
114 mut self,
115 button: MouseButton,
116 handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
117 ) -> Self
118 where
119 Self: Sized,
120 {
121 self.stateless_interaction()
122 .mouse_up_listeners
123 .push(Box::new(move |view, event, bounds, phase, cx| {
124 if phase == DispatchPhase::Capture
125 && event.button == button
126 && !bounds.contains_point(&event.position)
127 {
128 handler(view, event, cx);
129 }
130 }));
131 self
132 }
133
134 fn on_mouse_move(
135 mut self,
136 handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + 'static,
137 ) -> Self
138 where
139 Self: Sized,
140 {
141 self.stateless_interaction()
142 .mouse_move_listeners
143 .push(Box::new(move |view, event, bounds, phase, cx| {
144 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
145 handler(view, event, cx);
146 }
147 }));
148 self
149 }
150
151 fn on_scroll_wheel(
152 mut self,
153 handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + 'static,
154 ) -> Self
155 where
156 Self: Sized,
157 {
158 self.stateless_interaction()
159 .scroll_wheel_listeners
160 .push(Box::new(move |view, event, bounds, phase, cx| {
161 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
162 handler(view, event, cx);
163 }
164 }));
165 self
166 }
167
168 fn context<C>(mut self, context: C) -> Self
169 where
170 Self: Sized,
171 C: TryInto<DispatchContext>,
172 C::Error: Debug,
173 {
174 self.stateless_interaction().dispatch_context =
175 context.try_into().expect("invalid dispatch context");
176 self
177 }
178
179 fn on_action<A: 'static>(
180 mut self,
181 listener: impl Fn(&mut V, &A, DispatchPhase, &mut ViewContext<V>) + 'static,
182 ) -> Self
183 where
184 Self: Sized,
185 {
186 self.stateless_interaction().key_listeners.push((
187 TypeId::of::<A>(),
188 Box::new(move |view, event, _, phase, cx| {
189 let event = event.downcast_ref().unwrap();
190 listener(view, event, phase, cx);
191 None
192 }),
193 ));
194 self
195 }
196
197 fn on_key_down(
198 mut self,
199 listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
200 ) -> Self
201 where
202 Self: Sized,
203 {
204 self.stateless_interaction().key_listeners.push((
205 TypeId::of::<KeyDownEvent>(),
206 Box::new(move |view, event, _, phase, cx| {
207 let event = event.downcast_ref().unwrap();
208 listener(view, event, phase, cx);
209 None
210 }),
211 ));
212 self
213 }
214
215 fn on_key_up(
216 mut self,
217 listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
218 ) -> Self
219 where
220 Self: Sized,
221 {
222 self.stateless_interaction().key_listeners.push((
223 TypeId::of::<KeyUpEvent>(),
224 Box::new(move |view, event, _, phase, cx| {
225 let event = event.downcast_ref().unwrap();
226 listener(view, event, phase, cx);
227 None
228 }),
229 ));
230 self
231 }
232
233 fn drag_over<S: 'static>(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
234 where
235 Self: Sized,
236 {
237 self.stateless_interaction()
238 .drag_over_styles
239 .push((TypeId::of::<S>(), f(StyleRefinement::default())));
240 self
241 }
242
243 fn group_drag_over<S: 'static>(
244 mut self,
245 group_name: impl Into<SharedString>,
246 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
247 ) -> Self
248 where
249 Self: Sized,
250 {
251 self.stateless_interaction().group_drag_over_styles.push((
252 TypeId::of::<S>(),
253 GroupStyle {
254 group: group_name.into(),
255 style: f(StyleRefinement::default()),
256 },
257 ));
258 self
259 }
260
261 fn on_drop<W: 'static>(
262 mut self,
263 listener: impl Fn(&mut V, View<W>, &mut ViewContext<V>) + 'static,
264 ) -> Self
265 where
266 Self: Sized,
267 {
268 self.stateless_interaction().drop_listeners.push((
269 TypeId::of::<W>(),
270 Box::new(move |view, dragged_view, cx| {
271 listener(view, dragged_view.downcast().unwrap(), cx);
272 }),
273 ));
274 self
275 }
276}
277
278pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
279 fn stateful_interaction(&mut self) -> &mut StatefulInteraction<V>;
280
281 fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
282 where
283 Self: Sized,
284 {
285 self.stateful_interaction().active_style = f(StyleRefinement::default());
286 self
287 }
288
289 fn group_active(
290 mut self,
291 group_name: impl Into<SharedString>,
292 f: impl FnOnce(StyleRefinement) -> StyleRefinement,
293 ) -> Self
294 where
295 Self: Sized,
296 {
297 self.stateful_interaction().group_active_style = Some(GroupStyle {
298 group: group_name.into(),
299 style: f(StyleRefinement::default()),
300 });
301 self
302 }
303
304 fn on_click(
305 mut self,
306 listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static,
307 ) -> Self
308 where
309 Self: Sized,
310 {
311 self.stateful_interaction()
312 .click_listeners
313 .push(Box::new(move |view, event, cx| listener(view, event, cx)));
314 self
315 }
316
317 fn on_drag<W>(
318 mut self,
319 listener: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
320 ) -> Self
321 where
322 Self: Sized,
323 W: 'static + Render,
324 {
325 debug_assert!(
326 self.stateful_interaction().drag_listener.is_none(),
327 "calling on_drag more than once on the same element is not supported"
328 );
329 self.stateful_interaction().drag_listener =
330 Some(Box::new(move |view_state, cursor_offset, cx| AnyDrag {
331 view: listener(view_state, cx).into(),
332 cursor_offset,
333 }));
334 self
335 }
336
337 fn on_hover(mut self, listener: impl 'static + Fn(&mut V, bool, &mut ViewContext<V>)) -> Self
338 where
339 Self: Sized,
340 {
341 debug_assert!(
342 self.stateful_interaction().hover_listener.is_none(),
343 "calling on_hover more than once on the same element is not supported"
344 );
345 self.stateful_interaction().hover_listener = Some(Box::new(listener));
346 self
347 }
348
349 fn tooltip<W>(
350 mut self,
351 build_tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
352 ) -> Self
353 where
354 Self: Sized,
355 W: 'static + Render,
356 {
357 debug_assert!(
358 self.stateful_interaction().tooltip_builder.is_none(),
359 "calling tooltip more than once on the same element is not supported"
360 );
361 self.stateful_interaction().tooltip_builder = Some(Box::new(move |view_state, cx| {
362 build_tooltip(view_state, cx).into()
363 }));
364
365 self
366 }
367}
368
369pub trait ElementInteraction<V: 'static>: 'static {
370 fn as_stateless(&self) -> &StatelessInteraction<V>;
371 fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V>;
372 fn as_stateful(&self) -> Option<&StatefulInteraction<V>>;
373 fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>>;
374
375 fn initialize<R>(
376 &mut self,
377 cx: &mut ViewContext<V>,
378 f: impl FnOnce(&mut ViewContext<V>) -> R,
379 ) -> R {
380 if let Some(stateful) = self.as_stateful_mut() {
381 cx.with_element_id(stateful.id.clone(), |global_id, cx| {
382 stateful.key_listeners.push((
383 TypeId::of::<KeyDownEvent>(),
384 Box::new(move |_, key_down, context, phase, cx| {
385 if phase == DispatchPhase::Bubble {
386 let key_down = key_down.downcast_ref::<KeyDownEvent>().unwrap();
387 if let KeyMatch::Some(action) =
388 cx.match_keystroke(&global_id, &key_down.keystroke, context)
389 {
390 return Some(action);
391 }
392 }
393
394 None
395 }),
396 ));
397 let result = stateful.stateless.initialize(cx, f);
398 stateful.key_listeners.pop();
399 result
400 })
401 } else {
402 let stateless = self.as_stateless_mut();
403 cx.with_key_dispatch_context(stateless.dispatch_context.clone(), |cx| {
404 cx.with_key_listeners(mem::take(&mut stateless.key_listeners), f)
405 })
406 }
407 }
408
409 fn refine_style(
410 &self,
411 style: &mut Style,
412 bounds: Bounds<Pixels>,
413 element_state: &InteractiveElementState,
414 cx: &mut ViewContext<V>,
415 ) {
416 let mouse_position = cx.mouse_position();
417 let stateless = self.as_stateless();
418 if let Some(group_hover) = stateless.group_hover_style.as_ref() {
419 if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
420 if group_bounds.contains_point(&mouse_position) {
421 style.refine(&group_hover.style);
422 }
423 }
424 }
425 if bounds.contains_point(&mouse_position) {
426 style.refine(&stateless.hover_style);
427 }
428
429 if let Some(drag) = cx.active_drag.take() {
430 for (state_type, group_drag_style) in &self.as_stateless().group_drag_over_styles {
431 if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
432 if *state_type == drag.view.entity_type()
433 && group_bounds.contains_point(&mouse_position)
434 {
435 style.refine(&group_drag_style.style);
436 }
437 }
438 }
439
440 for (state_type, drag_over_style) in &self.as_stateless().drag_over_styles {
441 if *state_type == drag.view.entity_type() && bounds.contains_point(&mouse_position)
442 {
443 style.refine(drag_over_style);
444 }
445 }
446
447 cx.active_drag = Some(drag);
448 }
449
450 if let Some(stateful) = self.as_stateful() {
451 let active_state = element_state.active_state.lock();
452 if active_state.group {
453 if let Some(group_style) = stateful.group_active_style.as_ref() {
454 style.refine(&group_style.style);
455 }
456 }
457 if active_state.element {
458 style.refine(&stateful.active_style);
459 }
460 }
461 }
462
463 fn paint(
464 &mut self,
465 bounds: Bounds<Pixels>,
466 content_size: Size<Pixels>,
467 overflow: Point<Overflow>,
468 element_state: &mut InteractiveElementState,
469 cx: &mut ViewContext<V>,
470 ) {
471 let stateless = self.as_stateless_mut();
472 for listener in stateless.mouse_down_listeners.drain(..) {
473 cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
474 listener(state, event, &bounds, phase, cx);
475 })
476 }
477
478 for listener in stateless.mouse_up_listeners.drain(..) {
479 cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
480 listener(state, event, &bounds, phase, cx);
481 })
482 }
483
484 for listener in stateless.mouse_move_listeners.drain(..) {
485 cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
486 listener(state, event, &bounds, phase, cx);
487 })
488 }
489
490 for listener in stateless.scroll_wheel_listeners.drain(..) {
491 cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
492 listener(state, event, &bounds, phase, cx);
493 })
494 }
495
496 let hover_group_bounds = stateless
497 .group_hover_style
498 .as_ref()
499 .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
500
501 if let Some(group_bounds) = hover_group_bounds {
502 let hovered = group_bounds.contains_point(&cx.mouse_position());
503 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
504 if phase == DispatchPhase::Capture {
505 if group_bounds.contains_point(&event.position) != hovered {
506 cx.notify();
507 }
508 }
509 });
510 }
511
512 if stateless.hover_style.is_some()
513 || (cx.active_drag.is_some() && !stateless.drag_over_styles.is_empty())
514 {
515 let hovered = bounds.contains_point(&cx.mouse_position());
516 cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
517 if phase == DispatchPhase::Capture {
518 if bounds.contains_point(&event.position) != hovered {
519 cx.notify();
520 }
521 }
522 });
523 }
524
525 if cx.active_drag.is_some() {
526 let drop_listeners = mem::take(&mut stateless.drop_listeners);
527 cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
528 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
529 if let Some(drag_state_type) =
530 cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
531 {
532 for (drop_state_type, listener) in &drop_listeners {
533 if *drop_state_type == drag_state_type {
534 let drag = cx
535 .active_drag
536 .take()
537 .expect("checked for type drag state type above");
538 listener(view, drag.view.clone(), cx);
539 cx.notify();
540 cx.stop_propagation();
541 }
542 }
543 }
544 }
545 });
546 }
547
548 if let Some(stateful) = self.as_stateful_mut() {
549 let click_listeners = mem::take(&mut stateful.click_listeners);
550 let drag_listener = mem::take(&mut stateful.drag_listener);
551
552 if !click_listeners.is_empty() || drag_listener.is_some() {
553 let pending_mouse_down = element_state.pending_mouse_down.clone();
554 let mouse_down = pending_mouse_down.lock().clone();
555 if let Some(mouse_down) = mouse_down {
556 if let Some(drag_listener) = drag_listener {
557 let active_state = element_state.active_state.clone();
558
559 cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
560 if cx.active_drag.is_some() {
561 if phase == DispatchPhase::Capture {
562 cx.notify();
563 }
564 } else if phase == DispatchPhase::Bubble
565 && bounds.contains_point(&event.position)
566 && (event.position - mouse_down.position).magnitude()
567 > DRAG_THRESHOLD
568 {
569 *active_state.lock() = ActiveState::default();
570 let cursor_offset = event.position - bounds.origin;
571 let drag = drag_listener(view_state, cursor_offset, cx);
572 cx.active_drag = Some(drag);
573 cx.notify();
574 cx.stop_propagation();
575 }
576 });
577 }
578
579 cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
580 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
581 {
582 let mouse_click = ClickEvent {
583 down: mouse_down.clone(),
584 up: event.clone(),
585 };
586 for listener in &click_listeners {
587 listener(view_state, &mouse_click, cx);
588 }
589 }
590 *pending_mouse_down.lock() = None;
591 });
592 } else {
593 cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
594 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
595 {
596 *pending_mouse_down.lock() = Some(event.clone());
597 }
598 });
599 }
600 }
601
602 if let Some(hover_listener) = stateful.hover_listener.take() {
603 let was_hovered = element_state.hover_state.clone();
604 let has_mouse_down = element_state.pending_mouse_down.lock().is_some();
605 cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
606 if phase != DispatchPhase::Bubble {
607 return;
608 }
609 let is_hovered = bounds.contains_point(&event.position) && !has_mouse_down;
610 let mut was_hovered = was_hovered.lock();
611
612 if is_hovered != was_hovered.clone() {
613 *was_hovered = is_hovered;
614 drop(was_hovered);
615 hover_listener(view_state, is_hovered, cx);
616 }
617 });
618 }
619
620 let active_state = element_state.active_state.clone();
621 if active_state.lock().is_none() {
622 let active_group_bounds = stateful
623 .group_active_style
624 .as_ref()
625 .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
626 cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
627 if phase == DispatchPhase::Bubble {
628 let group = active_group_bounds
629 .map_or(false, |bounds| bounds.contains_point(&down.position));
630 let element = bounds.contains_point(&down.position);
631 if group || element {
632 *active_state.lock() = ActiveState { group, element };
633 cx.notify();
634 }
635 }
636 });
637 } else {
638 cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
639 if phase == DispatchPhase::Capture {
640 *active_state.lock() = ActiveState::default();
641 cx.notify();
642 }
643 });
644 }
645
646 if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
647 let scroll_offset = element_state
648 .scroll_offset
649 .get_or_insert_with(Arc::default)
650 .clone();
651 let line_height = cx.line_height();
652 let scroll_max = (content_size - bounds.size).max(&Size::default());
653
654 cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
655 if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
656 let mut scroll_offset = scroll_offset.lock();
657 let old_scroll_offset = *scroll_offset;
658 let delta = event.delta.pixel_delta(line_height);
659
660 if overflow.x == Overflow::Scroll {
661 scroll_offset.x =
662 (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
663 }
664
665 if overflow.y == Overflow::Scroll {
666 scroll_offset.y =
667 (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
668 }
669
670 if *scroll_offset != old_scroll_offset {
671 cx.notify();
672 cx.stop_propagation();
673 }
674 }
675 });
676 }
677 }
678 }
679}
680
681#[derive(Deref, DerefMut)]
682pub struct StatefulInteraction<V> {
683 pub id: ElementId,
684 #[deref]
685 #[deref_mut]
686 stateless: StatelessInteraction<V>,
687 click_listeners: SmallVec<[ClickListener<V>; 2]>,
688 active_style: StyleRefinement,
689 group_active_style: Option<GroupStyle>,
690 drag_listener: Option<DragListener<V>>,
691 hover_listener: Option<HoverListener<V>>,
692 tooltip_builder: Option<TooltipBuilder<V>>,
693}
694
695impl<V: 'static> ElementInteraction<V> for StatefulInteraction<V> {
696 fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
697 Some(self)
698 }
699
700 fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
701 Some(self)
702 }
703
704 fn as_stateless(&self) -> &StatelessInteraction<V> {
705 &self.stateless
706 }
707
708 fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
709 &mut self.stateless
710 }
711}
712
713impl<V> From<ElementId> for StatefulInteraction<V> {
714 fn from(id: ElementId) -> Self {
715 Self {
716 id,
717 stateless: StatelessInteraction::default(),
718 click_listeners: SmallVec::new(),
719 drag_listener: None,
720 hover_listener: None,
721 tooltip_builder: None,
722 active_style: StyleRefinement::default(),
723 group_active_style: None,
724 }
725 }
726}
727
728type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
729
730pub struct StatelessInteraction<V> {
731 pub dispatch_context: DispatchContext,
732 pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
733 pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
734 pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
735 pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
736 pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
737 pub hover_style: StyleRefinement,
738 pub group_hover_style: Option<GroupStyle>,
739 drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
740 group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
741 drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
742}
743
744impl<V> StatelessInteraction<V> {
745 pub fn into_stateful(self, id: impl Into<ElementId>) -> StatefulInteraction<V> {
746 StatefulInteraction {
747 id: id.into(),
748 stateless: self,
749 click_listeners: SmallVec::new(),
750 drag_listener: None,
751 hover_listener: None,
752 tooltip_builder: None,
753 active_style: StyleRefinement::default(),
754 group_active_style: None,
755 }
756 }
757}
758
759pub struct GroupStyle {
760 pub group: SharedString,
761 pub style: StyleRefinement,
762}
763
764#[derive(Default)]
765pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
766
767impl GroupBounds {
768 pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
769 cx.default_global::<Self>()
770 .0
771 .get(name)
772 .and_then(|bounds_stack| bounds_stack.last())
773 .cloned()
774 }
775
776 pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
777 cx.default_global::<Self>()
778 .0
779 .entry(name)
780 .or_default()
781 .push(bounds);
782 }
783
784 pub fn pop(name: &SharedString, cx: &mut AppContext) {
785 cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
786 }
787}
788
789#[derive(Copy, Clone, Default, Eq, PartialEq)]
790struct ActiveState {
791 pub group: bool,
792 pub element: bool,
793}
794
795impl ActiveState {
796 pub fn is_none(&self) -> bool {
797 !self.group && !self.element
798 }
799}
800
801#[derive(Default)]
802pub struct InteractiveElementState {
803 active_state: Arc<Mutex<ActiveState>>,
804 hover_state: Arc<Mutex<bool>>,
805 pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
806 scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
807}
808
809impl InteractiveElementState {
810 pub fn scroll_offset(&self) -> Option<Point<Pixels>> {
811 self.scroll_offset
812 .as_ref()
813 .map(|offset| offset.lock().clone())
814 }
815}
816
817impl<V> Default for StatelessInteraction<V> {
818 fn default() -> Self {
819 Self {
820 dispatch_context: DispatchContext::default(),
821 mouse_down_listeners: SmallVec::new(),
822 mouse_up_listeners: SmallVec::new(),
823 mouse_move_listeners: SmallVec::new(),
824 scroll_wheel_listeners: SmallVec::new(),
825 key_listeners: SmallVec::new(),
826 hover_style: StyleRefinement::default(),
827 group_hover_style: None,
828 drag_over_styles: SmallVec::new(),
829 group_drag_over_styles: SmallVec::new(),
830 drop_listeners: SmallVec::new(),
831 }
832 }
833}
834
835impl<V: 'static> ElementInteraction<V> for StatelessInteraction<V> {
836 fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
837 None
838 }
839
840 fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
841 None
842 }
843
844 fn as_stateless(&self) -> &StatelessInteraction<V> {
845 self
846 }
847
848 fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
849 self
850 }
851}
852
853#[derive(Clone, Debug, Eq, PartialEq)]
854pub struct KeyDownEvent {
855 pub keystroke: Keystroke,
856 pub is_held: bool,
857}
858
859#[derive(Clone, Debug)]
860pub struct KeyUpEvent {
861 pub keystroke: Keystroke,
862}
863
864#[derive(Clone, Debug, Default)]
865pub struct ModifiersChangedEvent {
866 pub modifiers: Modifiers,
867}
868
869impl Deref for ModifiersChangedEvent {
870 type Target = Modifiers;
871
872 fn deref(&self) -> &Self::Target {
873 &self.modifiers
874 }
875}
876
877/// The phase of a touch motion event.
878/// Based on the winit enum of the same name.
879#[derive(Clone, Copy, Debug)]
880pub enum TouchPhase {
881 Started,
882 Moved,
883 Ended,
884}
885
886#[derive(Clone, Debug, Default)]
887pub struct MouseDownEvent {
888 pub button: MouseButton,
889 pub position: Point<Pixels>,
890 pub modifiers: Modifiers,
891 pub click_count: usize,
892}
893
894#[derive(Clone, Debug, Default)]
895pub struct MouseUpEvent {
896 pub button: MouseButton,
897 pub position: Point<Pixels>,
898 pub modifiers: Modifiers,
899 pub click_count: usize,
900}
901
902#[derive(Clone, Debug, Default)]
903pub struct ClickEvent {
904 pub down: MouseDownEvent,
905 pub up: MouseUpEvent,
906}
907
908pub struct Drag<S, R, V, E>
909where
910 R: Fn(&mut V, &mut ViewContext<V>) -> E,
911 V: 'static,
912 E: Component<()>,
913{
914 pub state: S,
915 pub render_drag_handle: R,
916 view_type: PhantomData<V>,
917}
918
919impl<S, R, V, E> Drag<S, R, V, E>
920where
921 R: Fn(&mut V, &mut ViewContext<V>) -> E,
922 V: 'static,
923 E: Component<()>,
924{
925 pub fn new(state: S, render_drag_handle: R) -> Self {
926 Drag {
927 state,
928 render_drag_handle,
929 view_type: PhantomData,
930 }
931 }
932}
933
934// impl<S, R, V, E> Render for Drag<S, R, V, E> {
935// // fn render(&mut self, cx: ViewContext<Self>) ->
936// }
937
938#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
939pub enum MouseButton {
940 Left,
941 Right,
942 Middle,
943 Navigate(NavigationDirection),
944}
945
946impl MouseButton {
947 pub fn all() -> Vec<Self> {
948 vec![
949 MouseButton::Left,
950 MouseButton::Right,
951 MouseButton::Middle,
952 MouseButton::Navigate(NavigationDirection::Back),
953 MouseButton::Navigate(NavigationDirection::Forward),
954 ]
955 }
956}
957
958impl Default for MouseButton {
959 fn default() -> Self {
960 Self::Left
961 }
962}
963
964#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
965pub enum NavigationDirection {
966 Back,
967 Forward,
968}
969
970impl Default for NavigationDirection {
971 fn default() -> Self {
972 Self::Back
973 }
974}
975
976#[derive(Clone, Debug, Default)]
977pub struct MouseMoveEvent {
978 pub position: Point<Pixels>,
979 pub pressed_button: Option<MouseButton>,
980 pub modifiers: Modifiers,
981}
982
983#[derive(Clone, Debug)]
984pub struct ScrollWheelEvent {
985 pub position: Point<Pixels>,
986 pub delta: ScrollDelta,
987 pub modifiers: Modifiers,
988 pub touch_phase: TouchPhase,
989}
990
991impl Deref for ScrollWheelEvent {
992 type Target = Modifiers;
993
994 fn deref(&self) -> &Self::Target {
995 &self.modifiers
996 }
997}
998
999#[derive(Clone, Copy, Debug)]
1000pub enum ScrollDelta {
1001 Pixels(Point<Pixels>),
1002 Lines(Point<f32>),
1003}
1004
1005impl Default for ScrollDelta {
1006 fn default() -> Self {
1007 Self::Lines(Default::default())
1008 }
1009}
1010
1011impl ScrollDelta {
1012 pub fn precise(&self) -> bool {
1013 match self {
1014 ScrollDelta::Pixels(_) => true,
1015 ScrollDelta::Lines(_) => false,
1016 }
1017 }
1018
1019 pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
1020 match self {
1021 ScrollDelta::Pixels(delta) => *delta,
1022 ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
1023 }
1024 }
1025}
1026
1027#[derive(Clone, Debug, Default)]
1028pub struct MouseExitEvent {
1029 pub position: Point<Pixels>,
1030 pub pressed_button: Option<MouseButton>,
1031 pub modifiers: Modifiers,
1032}
1033
1034impl Deref for MouseExitEvent {
1035 type Target = Modifiers;
1036
1037 fn deref(&self) -> &Self::Target {
1038 &self.modifiers
1039 }
1040}
1041
1042#[derive(Debug, Clone, Default)]
1043pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
1044
1045impl Render for ExternalPaths {
1046 type Element = Div<Self>;
1047
1048 fn render(&mut self, _: &mut ViewContext<Self>) -> Self::Element {
1049 div() // Intentionally left empty because the platform will render icons for the dragged files
1050 }
1051}
1052
1053#[derive(Debug, Clone)]
1054pub enum FileDropEvent {
1055 Entered {
1056 position: Point<Pixels>,
1057 files: ExternalPaths,
1058 },
1059 Pending {
1060 position: Point<Pixels>,
1061 },
1062 Submit {
1063 position: Point<Pixels>,
1064 },
1065 Exited,
1066}
1067
1068#[derive(Clone, Debug)]
1069pub enum InputEvent {
1070 KeyDown(KeyDownEvent),
1071 KeyUp(KeyUpEvent),
1072 ModifiersChanged(ModifiersChangedEvent),
1073 MouseDown(MouseDownEvent),
1074 MouseUp(MouseUpEvent),
1075 MouseMove(MouseMoveEvent),
1076 MouseExited(MouseExitEvent),
1077 ScrollWheel(ScrollWheelEvent),
1078 FileDrop(FileDropEvent),
1079}
1080
1081impl InputEvent {
1082 pub fn position(&self) -> Option<Point<Pixels>> {
1083 match self {
1084 InputEvent::KeyDown { .. } => None,
1085 InputEvent::KeyUp { .. } => None,
1086 InputEvent::ModifiersChanged { .. } => None,
1087 InputEvent::MouseDown(event) => Some(event.position),
1088 InputEvent::MouseUp(event) => Some(event.position),
1089 InputEvent::MouseMove(event) => Some(event.position),
1090 InputEvent::MouseExited(event) => Some(event.position),
1091 InputEvent::ScrollWheel(event) => Some(event.position),
1092 InputEvent::FileDrop(FileDropEvent::Exited) => None,
1093 InputEvent::FileDrop(
1094 FileDropEvent::Entered { position, .. }
1095 | FileDropEvent::Pending { position, .. }
1096 | FileDropEvent::Submit { position, .. },
1097 ) => Some(*position),
1098 }
1099 }
1100
1101 pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
1102 match self {
1103 InputEvent::KeyDown { .. } => None,
1104 InputEvent::KeyUp { .. } => None,
1105 InputEvent::ModifiersChanged { .. } => None,
1106 InputEvent::MouseDown(event) => Some(event),
1107 InputEvent::MouseUp(event) => Some(event),
1108 InputEvent::MouseMove(event) => Some(event),
1109 InputEvent::MouseExited(event) => Some(event),
1110 InputEvent::ScrollWheel(event) => Some(event),
1111 InputEvent::FileDrop(event) => Some(event),
1112 }
1113 }
1114
1115 pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
1116 match self {
1117 InputEvent::KeyDown(event) => Some(event),
1118 InputEvent::KeyUp(event) => Some(event),
1119 InputEvent::ModifiersChanged(event) => Some(event),
1120 InputEvent::MouseDown(_) => None,
1121 InputEvent::MouseUp(_) => None,
1122 InputEvent::MouseMove(_) => None,
1123 InputEvent::MouseExited(_) => None,
1124 InputEvent::ScrollWheel(_) => None,
1125 InputEvent::FileDrop(_) => None,
1126 }
1127 }
1128}
1129
1130pub struct FocusEvent {
1131 pub blurred: Option<FocusHandle>,
1132 pub focused: Option<FocusHandle>,
1133}
1134
1135pub type MouseDownListener<V> = Box<
1136 dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1137>;
1138pub type MouseUpListener<V> = Box<
1139 dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1140>;
1141
1142pub type MouseMoveListener<V> = Box<
1143 dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1144>;
1145
1146pub type ScrollWheelListener<V> = Box<
1147 dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
1148 + 'static,
1149>;
1150
1151pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
1152
1153pub(crate) type DragListener<V> =
1154 Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
1155
1156pub(crate) type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
1157
1158pub(crate) type TooltipBuilder<V> = Box<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
1159
1160pub type KeyListener<V> = Box<
1161 dyn Fn(
1162 &mut V,
1163 &dyn Any,
1164 &[&DispatchContext],
1165 DispatchPhase,
1166 &mut ViewContext<V>,
1167 ) -> Option<Box<dyn Action>>
1168 + 'static,
1169>;