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