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                let result = stateful.stateless.initialize(cx, f);
 401                stateful.key_listeners.pop();
 402                result
 403            })
 404        } else {
 405            let stateless = self.as_stateless_mut();
 406            cx.with_key_dispatch_context(stateless.dispatch_context.clone(), |cx| {
 407                cx.with_key_listeners(mem::take(&mut stateless.key_listeners), f)
 408            })
 409        }
 410    }
 411
 412    fn refine_style(
 413        &self,
 414        style: &mut Style,
 415        bounds: Bounds<Pixels>,
 416        element_state: &InteractiveElementState,
 417        cx: &mut ViewContext<V>,
 418    ) {
 419        let mouse_position = cx.mouse_position();
 420        let stateless = self.as_stateless();
 421        if let Some(group_hover) = stateless.group_hover_style.as_ref() {
 422            if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
 423                if group_bounds.contains_point(&mouse_position) {
 424                    style.refine(&group_hover.style);
 425                }
 426            }
 427        }
 428        if bounds.contains_point(&mouse_position) {
 429            style.refine(&stateless.hover_style);
 430        }
 431
 432        if let Some(drag) = cx.active_drag.take() {
 433            for (state_type, group_drag_style) in &self.as_stateless().group_drag_over_styles {
 434                if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
 435                    if *state_type == drag.view.entity_type()
 436                        && group_bounds.contains_point(&mouse_position)
 437                    {
 438                        style.refine(&group_drag_style.style);
 439                    }
 440                }
 441            }
 442
 443            for (state_type, drag_over_style) in &self.as_stateless().drag_over_styles {
 444                if *state_type == drag.view.entity_type() && bounds.contains_point(&mouse_position)
 445                {
 446                    style.refine(drag_over_style);
 447                }
 448            }
 449
 450            cx.active_drag = Some(drag);
 451        }
 452
 453        if let Some(stateful) = self.as_stateful() {
 454            let active_state = element_state.active_state.lock();
 455            if active_state.group {
 456                if let Some(group_style) = stateful.group_active_style.as_ref() {
 457                    style.refine(&group_style.style);
 458                }
 459            }
 460            if active_state.element {
 461                style.refine(&stateful.active_style);
 462            }
 463        }
 464    }
 465
 466    fn paint(
 467        &mut self,
 468        bounds: Bounds<Pixels>,
 469        content_size: Size<Pixels>,
 470        overflow: Point<Overflow>,
 471        element_state: &mut InteractiveElementState,
 472        cx: &mut ViewContext<V>,
 473    ) {
 474        let stateless = self.as_stateless_mut();
 475        for listener in stateless.mouse_down_listeners.drain(..) {
 476            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
 477                listener(state, event, &bounds, phase, cx);
 478            })
 479        }
 480
 481        for listener in stateless.mouse_up_listeners.drain(..) {
 482            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
 483                listener(state, event, &bounds, phase, cx);
 484            })
 485        }
 486
 487        for listener in stateless.mouse_move_listeners.drain(..) {
 488            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
 489                listener(state, event, &bounds, phase, cx);
 490            })
 491        }
 492
 493        for listener in stateless.scroll_wheel_listeners.drain(..) {
 494            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
 495                listener(state, event, &bounds, phase, cx);
 496            })
 497        }
 498
 499        let hover_group_bounds = stateless
 500            .group_hover_style
 501            .as_ref()
 502            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
 503
 504        if let Some(group_bounds) = hover_group_bounds {
 505            let hovered = group_bounds.contains_point(&cx.mouse_position());
 506            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 507                if phase == DispatchPhase::Capture {
 508                    if group_bounds.contains_point(&event.position) != hovered {
 509                        cx.notify();
 510                    }
 511                }
 512            });
 513        }
 514
 515        if stateless.hover_style.is_some()
 516            || (cx.active_drag.is_some() && !stateless.drag_over_styles.is_empty())
 517        {
 518            let hovered = bounds.contains_point(&cx.mouse_position());
 519            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 520                if phase == DispatchPhase::Capture {
 521                    if bounds.contains_point(&event.position) != hovered {
 522                        cx.notify();
 523                    }
 524                }
 525            });
 526        }
 527
 528        if cx.active_drag.is_some() {
 529            let drop_listeners = mem::take(&mut stateless.drop_listeners);
 530            cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
 531                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 532                    if let Some(drag_state_type) =
 533                        cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
 534                    {
 535                        for (drop_state_type, listener) in &drop_listeners {
 536                            if *drop_state_type == drag_state_type {
 537                                let drag = cx
 538                                    .active_drag
 539                                    .take()
 540                                    .expect("checked for type drag state type above");
 541                                listener(view, drag.view.clone(), cx);
 542                                cx.notify();
 543                                cx.stop_propagation();
 544                            }
 545                        }
 546                    }
 547                }
 548            });
 549        }
 550
 551        if let Some(stateful) = self.as_stateful_mut() {
 552            let click_listeners = mem::take(&mut stateful.click_listeners);
 553            let drag_listener = mem::take(&mut stateful.drag_listener);
 554
 555            if !click_listeners.is_empty() || drag_listener.is_some() {
 556                let pending_mouse_down = element_state.pending_mouse_down.clone();
 557                let mouse_down = pending_mouse_down.lock().clone();
 558                if let Some(mouse_down) = mouse_down {
 559                    if let Some(drag_listener) = drag_listener {
 560                        let active_state = element_state.active_state.clone();
 561
 562                        cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 563                            if cx.active_drag.is_some() {
 564                                if phase == DispatchPhase::Capture {
 565                                    cx.notify();
 566                                }
 567                            } else if phase == DispatchPhase::Bubble
 568                                && bounds.contains_point(&event.position)
 569                                && (event.position - mouse_down.position).magnitude()
 570                                    > DRAG_THRESHOLD
 571                            {
 572                                *active_state.lock() = ActiveState::default();
 573                                let cursor_offset = event.position - bounds.origin;
 574                                let drag = drag_listener(view_state, cursor_offset, cx);
 575                                cx.active_drag = Some(drag);
 576                                cx.notify();
 577                                cx.stop_propagation();
 578                            }
 579                        });
 580                    }
 581
 582                    cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
 583                        if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
 584                        {
 585                            let mouse_click = ClickEvent {
 586                                down: mouse_down.clone(),
 587                                up: event.clone(),
 588                            };
 589                            for listener in &click_listeners {
 590                                listener(view_state, &mouse_click, cx);
 591                            }
 592                        }
 593                        *pending_mouse_down.lock() = None;
 594                    });
 595                } else {
 596                    cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
 597                        if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
 598                        {
 599                            *pending_mouse_down.lock() = Some(event.clone());
 600                        }
 601                    });
 602                }
 603            }
 604
 605            if let Some(hover_listener) = stateful.hover_listener.take() {
 606                let was_hovered = element_state.hover_state.clone();
 607                let has_mouse_down = element_state.pending_mouse_down.clone();
 608
 609                cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 610                    if phase != DispatchPhase::Bubble {
 611                        return;
 612                    }
 613                    let is_hovered =
 614                        bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
 615                    let mut was_hovered = was_hovered.lock();
 616
 617                    if is_hovered != was_hovered.clone() {
 618                        *was_hovered = is_hovered;
 619                        drop(was_hovered);
 620
 621                        hover_listener(view_state, is_hovered, cx);
 622                    }
 623                });
 624            }
 625
 626            if let Some(tooltip_builder) = stateful.tooltip_builder.take() {
 627                let active_tooltip = element_state.active_tooltip.clone();
 628                let pending_mouse_down = element_state.pending_mouse_down.clone();
 629
 630                cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 631                    if phase != DispatchPhase::Bubble {
 632                        return;
 633                    }
 634
 635                    let is_hovered = bounds.contains_point(&event.position)
 636                        && pending_mouse_down.lock().is_none();
 637                    if !is_hovered {
 638                        active_tooltip.lock().take();
 639                        return;
 640                    }
 641
 642                    if active_tooltip.lock().is_none() {
 643                        let task = cx.spawn({
 644                            let active_tooltip = active_tooltip.clone();
 645                            let tooltip_builder = tooltip_builder.clone();
 646
 647                            move |view, mut cx| async move {
 648                                cx.background_executor().timer(TOOLTIP_DELAY).await;
 649                                view.update(&mut cx, move |view_state, cx| {
 650                                    active_tooltip.lock().replace(ActiveTooltip {
 651                                        waiting: None,
 652                                        tooltip: Some(AnyTooltip {
 653                                            view: tooltip_builder(view_state, cx),
 654                                            cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
 655                                        }),
 656                                    });
 657                                    cx.notify();
 658                                })
 659                                .ok();
 660                            }
 661                        });
 662                        active_tooltip.lock().replace(ActiveTooltip {
 663                            waiting: Some(task),
 664                            tooltip: None,
 665                        });
 666                    }
 667                });
 668
 669                if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
 670                    if active_tooltip.tooltip.is_some() {
 671                        cx.active_tooltip = active_tooltip.tooltip.clone()
 672                    }
 673                }
 674            }
 675
 676            let active_state = element_state.active_state.clone();
 677            if active_state.lock().is_none() {
 678                let active_group_bounds = stateful
 679                    .group_active_style
 680                    .as_ref()
 681                    .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
 682                cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
 683                    if phase == DispatchPhase::Bubble {
 684                        let group = active_group_bounds
 685                            .map_or(false, |bounds| bounds.contains_point(&down.position));
 686                        let element = bounds.contains_point(&down.position);
 687                        if group || element {
 688                            *active_state.lock() = ActiveState { group, element };
 689                            cx.notify();
 690                        }
 691                    }
 692                });
 693            } else {
 694                cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
 695                    if phase == DispatchPhase::Capture {
 696                        *active_state.lock() = ActiveState::default();
 697                        cx.notify();
 698                    }
 699                });
 700            }
 701
 702            if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
 703                let scroll_offset = element_state
 704                    .scroll_offset
 705                    .get_or_insert_with(Arc::default)
 706                    .clone();
 707                let line_height = cx.line_height();
 708                let scroll_max = (content_size - bounds.size).max(&Size::default());
 709
 710                cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
 711                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 712                        let mut scroll_offset = scroll_offset.lock();
 713                        let old_scroll_offset = *scroll_offset;
 714                        let delta = event.delta.pixel_delta(line_height);
 715
 716                        if overflow.x == Overflow::Scroll {
 717                            scroll_offset.x =
 718                                (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
 719                        }
 720
 721                        if overflow.y == Overflow::Scroll {
 722                            scroll_offset.y =
 723                                (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
 724                        }
 725
 726                        if *scroll_offset != old_scroll_offset {
 727                            cx.notify();
 728                            cx.stop_propagation();
 729                        }
 730                    }
 731                });
 732            }
 733        }
 734    }
 735}
 736
 737#[derive(Deref, DerefMut)]
 738pub struct StatefulInteraction<V> {
 739    pub id: ElementId,
 740    #[deref]
 741    #[deref_mut]
 742    stateless: StatelessInteraction<V>,
 743    click_listeners: SmallVec<[ClickListener<V>; 2]>,
 744    active_style: StyleRefinement,
 745    group_active_style: Option<GroupStyle>,
 746    drag_listener: Option<DragListener<V>>,
 747    hover_listener: Option<HoverListener<V>>,
 748    tooltip_builder: Option<TooltipBuilder<V>>,
 749}
 750
 751impl<V: 'static> ElementInteraction<V> for StatefulInteraction<V> {
 752    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
 753        Some(self)
 754    }
 755
 756    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
 757        Some(self)
 758    }
 759
 760    fn as_stateless(&self) -> &StatelessInteraction<V> {
 761        &self.stateless
 762    }
 763
 764    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
 765        &mut self.stateless
 766    }
 767}
 768
 769impl<V> From<ElementId> for StatefulInteraction<V> {
 770    fn from(id: ElementId) -> Self {
 771        Self {
 772            id,
 773            stateless: StatelessInteraction::default(),
 774            click_listeners: SmallVec::new(),
 775            drag_listener: None,
 776            hover_listener: None,
 777            tooltip_builder: None,
 778            active_style: StyleRefinement::default(),
 779            group_active_style: None,
 780        }
 781    }
 782}
 783
 784type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
 785
 786pub struct StatelessInteraction<V> {
 787    pub dispatch_context: DispatchContext,
 788    pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
 789    pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
 790    pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
 791    pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
 792    pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
 793    pub hover_style: StyleRefinement,
 794    pub group_hover_style: Option<GroupStyle>,
 795    drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
 796    group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
 797    drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
 798}
 799
 800impl<V> StatelessInteraction<V> {
 801    pub fn into_stateful(self, id: impl Into<ElementId>) -> StatefulInteraction<V> {
 802        StatefulInteraction {
 803            id: id.into(),
 804            stateless: self,
 805            click_listeners: SmallVec::new(),
 806            drag_listener: None,
 807            hover_listener: None,
 808            tooltip_builder: None,
 809            active_style: StyleRefinement::default(),
 810            group_active_style: None,
 811        }
 812    }
 813}
 814
 815pub struct GroupStyle {
 816    pub group: SharedString,
 817    pub style: StyleRefinement,
 818}
 819
 820#[derive(Default)]
 821pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
 822
 823impl GroupBounds {
 824    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
 825        cx.default_global::<Self>()
 826            .0
 827            .get(name)
 828            .and_then(|bounds_stack| bounds_stack.last())
 829            .cloned()
 830    }
 831
 832    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
 833        cx.default_global::<Self>()
 834            .0
 835            .entry(name)
 836            .or_default()
 837            .push(bounds);
 838    }
 839
 840    pub fn pop(name: &SharedString, cx: &mut AppContext) {
 841        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
 842    }
 843}
 844
 845#[derive(Copy, Clone, Default, Eq, PartialEq)]
 846struct ActiveState {
 847    pub group: bool,
 848    pub element: bool,
 849}
 850
 851impl ActiveState {
 852    pub fn is_none(&self) -> bool {
 853        !self.group && !self.element
 854    }
 855}
 856
 857#[derive(Default)]
 858pub struct InteractiveElementState {
 859    active_state: Arc<Mutex<ActiveState>>,
 860    hover_state: Arc<Mutex<bool>>,
 861    pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
 862    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
 863    active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
 864}
 865
 866struct ActiveTooltip {
 867    #[allow(unused)] // used to drop the task
 868    waiting: Option<Task<()>>,
 869    tooltip: Option<AnyTooltip>,
 870}
 871
 872impl InteractiveElementState {
 873    pub fn scroll_offset(&self) -> Option<Point<Pixels>> {
 874        self.scroll_offset
 875            .as_ref()
 876            .map(|offset| offset.lock().clone())
 877    }
 878}
 879
 880impl<V> Default for StatelessInteraction<V> {
 881    fn default() -> Self {
 882        Self {
 883            dispatch_context: DispatchContext::default(),
 884            mouse_down_listeners: SmallVec::new(),
 885            mouse_up_listeners: SmallVec::new(),
 886            mouse_move_listeners: SmallVec::new(),
 887            scroll_wheel_listeners: SmallVec::new(),
 888            key_listeners: SmallVec::new(),
 889            hover_style: StyleRefinement::default(),
 890            group_hover_style: None,
 891            drag_over_styles: SmallVec::new(),
 892            group_drag_over_styles: SmallVec::new(),
 893            drop_listeners: SmallVec::new(),
 894        }
 895    }
 896}
 897
 898impl<V: 'static> ElementInteraction<V> for StatelessInteraction<V> {
 899    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
 900        None
 901    }
 902
 903    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
 904        None
 905    }
 906
 907    fn as_stateless(&self) -> &StatelessInteraction<V> {
 908        self
 909    }
 910
 911    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
 912        self
 913    }
 914}
 915
 916#[derive(Clone, Debug, Eq, PartialEq)]
 917pub struct KeyDownEvent {
 918    pub keystroke: Keystroke,
 919    pub is_held: bool,
 920}
 921
 922#[derive(Clone, Debug)]
 923pub struct KeyUpEvent {
 924    pub keystroke: Keystroke,
 925}
 926
 927#[derive(Clone, Debug, Default)]
 928pub struct ModifiersChangedEvent {
 929    pub modifiers: Modifiers,
 930}
 931
 932impl Deref for ModifiersChangedEvent {
 933    type Target = Modifiers;
 934
 935    fn deref(&self) -> &Self::Target {
 936        &self.modifiers
 937    }
 938}
 939
 940/// The phase of a touch motion event.
 941/// Based on the winit enum of the same name.
 942#[derive(Clone, Copy, Debug)]
 943pub enum TouchPhase {
 944    Started,
 945    Moved,
 946    Ended,
 947}
 948
 949#[derive(Clone, Debug, Default)]
 950pub struct MouseDownEvent {
 951    pub button: MouseButton,
 952    pub position: Point<Pixels>,
 953    pub modifiers: Modifiers,
 954    pub click_count: usize,
 955}
 956
 957#[derive(Clone, Debug, Default)]
 958pub struct MouseUpEvent {
 959    pub button: MouseButton,
 960    pub position: Point<Pixels>,
 961    pub modifiers: Modifiers,
 962    pub click_count: usize,
 963}
 964
 965#[derive(Clone, Debug, Default)]
 966pub struct ClickEvent {
 967    pub down: MouseDownEvent,
 968    pub up: MouseUpEvent,
 969}
 970
 971pub struct Drag<S, R, V, E>
 972where
 973    R: Fn(&mut V, &mut ViewContext<V>) -> E,
 974    V: 'static,
 975    E: Component<()>,
 976{
 977    pub state: S,
 978    pub render_drag_handle: R,
 979    view_type: PhantomData<V>,
 980}
 981
 982impl<S, R, V, E> Drag<S, R, V, E>
 983where
 984    R: Fn(&mut V, &mut ViewContext<V>) -> E,
 985    V: 'static,
 986    E: Component<()>,
 987{
 988    pub fn new(state: S, render_drag_handle: R) -> Self {
 989        Drag {
 990            state,
 991            render_drag_handle,
 992            view_type: PhantomData,
 993        }
 994    }
 995}
 996
 997// impl<S, R, V, E> Render for Drag<S, R, V, E> {
 998//     // fn render(&mut self, cx: ViewContext<Self>) ->
 999// }
1000
1001#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1002pub enum MouseButton {
1003    Left,
1004    Right,
1005    Middle,
1006    Navigate(NavigationDirection),
1007}
1008
1009impl MouseButton {
1010    pub fn all() -> Vec<Self> {
1011        vec![
1012            MouseButton::Left,
1013            MouseButton::Right,
1014            MouseButton::Middle,
1015            MouseButton::Navigate(NavigationDirection::Back),
1016            MouseButton::Navigate(NavigationDirection::Forward),
1017        ]
1018    }
1019}
1020
1021impl Default for MouseButton {
1022    fn default() -> Self {
1023        Self::Left
1024    }
1025}
1026
1027#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1028pub enum NavigationDirection {
1029    Back,
1030    Forward,
1031}
1032
1033impl Default for NavigationDirection {
1034    fn default() -> Self {
1035        Self::Back
1036    }
1037}
1038
1039#[derive(Clone, Debug, Default)]
1040pub struct MouseMoveEvent {
1041    pub position: Point<Pixels>,
1042    pub pressed_button: Option<MouseButton>,
1043    pub modifiers: Modifiers,
1044}
1045
1046#[derive(Clone, Debug)]
1047pub struct ScrollWheelEvent {
1048    pub position: Point<Pixels>,
1049    pub delta: ScrollDelta,
1050    pub modifiers: Modifiers,
1051    pub touch_phase: TouchPhase,
1052}
1053
1054impl Deref for ScrollWheelEvent {
1055    type Target = Modifiers;
1056
1057    fn deref(&self) -> &Self::Target {
1058        &self.modifiers
1059    }
1060}
1061
1062#[derive(Clone, Copy, Debug)]
1063pub enum ScrollDelta {
1064    Pixels(Point<Pixels>),
1065    Lines(Point<f32>),
1066}
1067
1068impl Default for ScrollDelta {
1069    fn default() -> Self {
1070        Self::Lines(Default::default())
1071    }
1072}
1073
1074impl ScrollDelta {
1075    pub fn precise(&self) -> bool {
1076        match self {
1077            ScrollDelta::Pixels(_) => true,
1078            ScrollDelta::Lines(_) => false,
1079        }
1080    }
1081
1082    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
1083        match self {
1084            ScrollDelta::Pixels(delta) => *delta,
1085            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
1086        }
1087    }
1088}
1089
1090#[derive(Clone, Debug, Default)]
1091pub struct MouseExitEvent {
1092    pub position: Point<Pixels>,
1093    pub pressed_button: Option<MouseButton>,
1094    pub modifiers: Modifiers,
1095}
1096
1097impl Deref for MouseExitEvent {
1098    type Target = Modifiers;
1099
1100    fn deref(&self) -> &Self::Target {
1101        &self.modifiers
1102    }
1103}
1104
1105#[derive(Debug, Clone, Default)]
1106pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
1107
1108impl Render for ExternalPaths {
1109    type Element = Div<Self>;
1110
1111    fn render(&mut self, _: &mut ViewContext<Self>) -> Self::Element {
1112        div() // Intentionally left empty because the platform will render icons for the dragged files
1113    }
1114}
1115
1116#[derive(Debug, Clone)]
1117pub enum FileDropEvent {
1118    Entered {
1119        position: Point<Pixels>,
1120        files: ExternalPaths,
1121    },
1122    Pending {
1123        position: Point<Pixels>,
1124    },
1125    Submit {
1126        position: Point<Pixels>,
1127    },
1128    Exited,
1129}
1130
1131#[derive(Clone, Debug)]
1132pub enum InputEvent {
1133    KeyDown(KeyDownEvent),
1134    KeyUp(KeyUpEvent),
1135    ModifiersChanged(ModifiersChangedEvent),
1136    MouseDown(MouseDownEvent),
1137    MouseUp(MouseUpEvent),
1138    MouseMove(MouseMoveEvent),
1139    MouseExited(MouseExitEvent),
1140    ScrollWheel(ScrollWheelEvent),
1141    FileDrop(FileDropEvent),
1142}
1143
1144impl InputEvent {
1145    pub fn position(&self) -> Option<Point<Pixels>> {
1146        match self {
1147            InputEvent::KeyDown { .. } => None,
1148            InputEvent::KeyUp { .. } => None,
1149            InputEvent::ModifiersChanged { .. } => None,
1150            InputEvent::MouseDown(event) => Some(event.position),
1151            InputEvent::MouseUp(event) => Some(event.position),
1152            InputEvent::MouseMove(event) => Some(event.position),
1153            InputEvent::MouseExited(event) => Some(event.position),
1154            InputEvent::ScrollWheel(event) => Some(event.position),
1155            InputEvent::FileDrop(FileDropEvent::Exited) => None,
1156            InputEvent::FileDrop(
1157                FileDropEvent::Entered { position, .. }
1158                | FileDropEvent::Pending { position, .. }
1159                | FileDropEvent::Submit { position, .. },
1160            ) => Some(*position),
1161        }
1162    }
1163
1164    pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
1165        match self {
1166            InputEvent::KeyDown { .. } => None,
1167            InputEvent::KeyUp { .. } => None,
1168            InputEvent::ModifiersChanged { .. } => None,
1169            InputEvent::MouseDown(event) => Some(event),
1170            InputEvent::MouseUp(event) => Some(event),
1171            InputEvent::MouseMove(event) => Some(event),
1172            InputEvent::MouseExited(event) => Some(event),
1173            InputEvent::ScrollWheel(event) => Some(event),
1174            InputEvent::FileDrop(event) => Some(event),
1175        }
1176    }
1177
1178    pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
1179        match self {
1180            InputEvent::KeyDown(event) => Some(event),
1181            InputEvent::KeyUp(event) => Some(event),
1182            InputEvent::ModifiersChanged(event) => Some(event),
1183            InputEvent::MouseDown(_) => None,
1184            InputEvent::MouseUp(_) => None,
1185            InputEvent::MouseMove(_) => None,
1186            InputEvent::MouseExited(_) => None,
1187            InputEvent::ScrollWheel(_) => None,
1188            InputEvent::FileDrop(_) => None,
1189        }
1190    }
1191}
1192
1193pub struct FocusEvent {
1194    pub blurred: Option<FocusHandle>,
1195    pub focused: Option<FocusHandle>,
1196}
1197
1198pub type MouseDownListener<V> = Box<
1199    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1200>;
1201pub type MouseUpListener<V> = Box<
1202    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1203>;
1204
1205pub type MouseMoveListener<V> = Box<
1206    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1207>;
1208
1209pub type ScrollWheelListener<V> = Box<
1210    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
1211        + 'static,
1212>;
1213
1214pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
1215
1216pub(crate) type DragListener<V> =
1217    Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
1218
1219pub(crate) type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
1220
1221pub(crate) type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
1222
1223pub type KeyListener<V> = Box<
1224    dyn Fn(
1225            &mut V,
1226            &dyn Any,
1227            &[&DispatchContext],
1228            DispatchPhase,
1229            &mut ViewContext<V>,
1230        ) -> Option<Box<dyn Action>>
1231        + 'static,
1232>;
1233
1234#[cfg(test)]
1235mod test {
1236    use crate::{
1237        self as gpui, div, Div, FocusHandle, KeyBinding, Keystroke, ParentElement, Render,
1238        StatefulInteraction, StatelessInteractive, TestAppContext, VisualContext,
1239    };
1240
1241    struct TestView {
1242        saw_key_down: bool,
1243        saw_action: bool,
1244        focus_handle: FocusHandle,
1245    }
1246
1247    actions!(TestAction);
1248
1249    impl Render for TestView {
1250        type Element = Div<Self, StatefulInteraction<Self>>;
1251
1252        fn render(&mut self, _: &mut gpui::ViewContext<Self>) -> Self::Element {
1253            div().id("testview").child(
1254                div()
1255                    .on_key_down(|this: &mut TestView, _, _, _| {
1256                        dbg!("ola!");
1257                        this.saw_key_down = true
1258                    })
1259                    .on_action(|this: &mut TestView, _: &TestAction, _, _| {
1260                        dbg!("ola!");
1261                        this.saw_action = true
1262                    })
1263                    .track_focus(&self.focus_handle),
1264            )
1265        }
1266    }
1267
1268    #[gpui::test]
1269    fn test_on_events(cx: &mut TestAppContext) {
1270        let window = cx.update(|cx| {
1271            cx.open_window(Default::default(), |cx| {
1272                cx.build_view(|cx| TestView {
1273                    saw_key_down: false,
1274                    saw_action: false,
1275                    focus_handle: cx.focus_handle(),
1276                })
1277            })
1278        });
1279
1280        cx.update(|cx| {
1281            cx.bind_keys(vec![KeyBinding::new("ctrl-g", TestAction, None)]);
1282        });
1283
1284        window
1285            .update(cx, |test_view, cx| cx.focus(&test_view.focus_handle))
1286            .unwrap();
1287
1288        cx.dispatch_keystroke(*window, Keystroke::parse("space").unwrap(), false);
1289        cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap(), false);
1290
1291        window
1292            .update(cx, |test_view, _| {
1293                assert!(test_view.saw_key_down || test_view.saw_action);
1294                assert!(test_view.saw_key_down);
1295                assert!(test_view.saw_action);
1296            })
1297            .unwrap();
1298    }
1299}