interactive.rs

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