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, 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 |view_state, 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                    let mut tooltip_lock = active_tooltip.lock();
 638
 639                    if is_hovered {
 640                        if tooltip_lock.is_none() {
 641                            *tooltip_lock = Some(ActiveTooltip {
 642                                view: tooltip_builder(view_state, cx),
 643                                visible: false,
 644                                coordinates: event.position,
 645                            });
 646
 647                            let active_tooltip = active_tooltip.clone();
 648                            cx.spawn(move |view, mut cx| async move {
 649                                cx.background_executor().timer(TOOLTIP_DELAY).await;
 650
 651                                view.update(&mut cx, |_, cx| {
 652                                    if let Some(active_tooltip) = active_tooltip.lock().as_mut() {
 653                                        active_tooltip.visible = true;
 654                                        active_tooltip.coordinates =
 655                                            cx.mouse_position() + TOOLTIP_OFFSET;
 656                                    }
 657                                    cx.notify();
 658                                })
 659                                .ok()
 660                            })
 661                            .detach();
 662                        }
 663                    } else {
 664                        tooltip_lock.take();
 665                    }
 666                });
 667
 668                if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
 669                    if active_tooltip.visible {
 670                        cx.active_tooltip = Some(AnyTooltip {
 671                            view: active_tooltip.view.clone(),
 672                            cursor_offset: active_tooltip.coordinates,
 673                        });
 674                    }
 675                }
 676            }
 677
 678            let active_state = element_state.active_state.clone();
 679            if active_state.lock().is_none() {
 680                let active_group_bounds = stateful
 681                    .group_active_style
 682                    .as_ref()
 683                    .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
 684                cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
 685                    if phase == DispatchPhase::Bubble {
 686                        let group = active_group_bounds
 687                            .map_or(false, |bounds| bounds.contains_point(&down.position));
 688                        let element = bounds.contains_point(&down.position);
 689                        if group || element {
 690                            *active_state.lock() = ActiveState { group, element };
 691                            cx.notify();
 692                        }
 693                    }
 694                });
 695            } else {
 696                cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
 697                    if phase == DispatchPhase::Capture {
 698                        *active_state.lock() = ActiveState::default();
 699                        cx.notify();
 700                    }
 701                });
 702            }
 703
 704            if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
 705                let scroll_offset = element_state
 706                    .scroll_offset
 707                    .get_or_insert_with(Arc::default)
 708                    .clone();
 709                let line_height = cx.line_height();
 710                let scroll_max = (content_size - bounds.size).max(&Size::default());
 711
 712                cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
 713                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 714                        let mut scroll_offset = scroll_offset.lock();
 715                        let old_scroll_offset = *scroll_offset;
 716                        let delta = event.delta.pixel_delta(line_height);
 717
 718                        if overflow.x == Overflow::Scroll {
 719                            scroll_offset.x =
 720                                (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
 721                        }
 722
 723                        if overflow.y == Overflow::Scroll {
 724                            scroll_offset.y =
 725                                (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
 726                        }
 727
 728                        if *scroll_offset != old_scroll_offset {
 729                            cx.notify();
 730                            cx.stop_propagation();
 731                        }
 732                    }
 733                });
 734            }
 735        }
 736    }
 737}
 738
 739#[derive(Deref, DerefMut)]
 740pub struct StatefulInteraction<V> {
 741    pub id: ElementId,
 742    #[deref]
 743    #[deref_mut]
 744    stateless: StatelessInteraction<V>,
 745    click_listeners: SmallVec<[ClickListener<V>; 2]>,
 746    active_style: StyleRefinement,
 747    group_active_style: Option<GroupStyle>,
 748    drag_listener: Option<DragListener<V>>,
 749    hover_listener: Option<HoverListener<V>>,
 750    tooltip_builder: Option<TooltipBuilder<V>>,
 751}
 752
 753impl<V: 'static> ElementInteraction<V> for StatefulInteraction<V> {
 754    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
 755        Some(self)
 756    }
 757
 758    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
 759        Some(self)
 760    }
 761
 762    fn as_stateless(&self) -> &StatelessInteraction<V> {
 763        &self.stateless
 764    }
 765
 766    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
 767        &mut self.stateless
 768    }
 769}
 770
 771impl<V> From<ElementId> for StatefulInteraction<V> {
 772    fn from(id: ElementId) -> Self {
 773        Self {
 774            id,
 775            stateless: StatelessInteraction::default(),
 776            click_listeners: SmallVec::new(),
 777            drag_listener: None,
 778            hover_listener: None,
 779            tooltip_builder: None,
 780            active_style: StyleRefinement::default(),
 781            group_active_style: None,
 782        }
 783    }
 784}
 785
 786type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
 787
 788pub struct StatelessInteraction<V> {
 789    pub dispatch_context: DispatchContext,
 790    pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
 791    pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
 792    pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
 793    pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
 794    pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
 795    pub hover_style: StyleRefinement,
 796    pub group_hover_style: Option<GroupStyle>,
 797    drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
 798    group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
 799    drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
 800}
 801
 802impl<V> StatelessInteraction<V> {
 803    pub fn into_stateful(self, id: impl Into<ElementId>) -> StatefulInteraction<V> {
 804        StatefulInteraction {
 805            id: id.into(),
 806            stateless: self,
 807            click_listeners: SmallVec::new(),
 808            drag_listener: None,
 809            hover_listener: None,
 810            tooltip_builder: None,
 811            active_style: StyleRefinement::default(),
 812            group_active_style: None,
 813        }
 814    }
 815}
 816
 817pub struct GroupStyle {
 818    pub group: SharedString,
 819    pub style: StyleRefinement,
 820}
 821
 822#[derive(Default)]
 823pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
 824
 825impl GroupBounds {
 826    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
 827        cx.default_global::<Self>()
 828            .0
 829            .get(name)
 830            .and_then(|bounds_stack| bounds_stack.last())
 831            .cloned()
 832    }
 833
 834    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
 835        cx.default_global::<Self>()
 836            .0
 837            .entry(name)
 838            .or_default()
 839            .push(bounds);
 840    }
 841
 842    pub fn pop(name: &SharedString, cx: &mut AppContext) {
 843        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
 844    }
 845}
 846
 847#[derive(Copy, Clone, Default, Eq, PartialEq)]
 848struct ActiveState {
 849    pub group: bool,
 850    pub element: bool,
 851}
 852
 853impl ActiveState {
 854    pub fn is_none(&self) -> bool {
 855        !self.group && !self.element
 856    }
 857}
 858
 859#[derive(Default)]
 860pub struct InteractiveElementState {
 861    active_state: Arc<Mutex<ActiveState>>,
 862    hover_state: Arc<Mutex<bool>>,
 863    pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
 864    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
 865    active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
 866}
 867
 868struct ActiveTooltip {
 869    view: AnyView,
 870    visible: bool,
 871    coordinates: Point<Pixels>,
 872}
 873
 874impl InteractiveElementState {
 875    pub fn scroll_offset(&self) -> Option<Point<Pixels>> {
 876        self.scroll_offset
 877            .as_ref()
 878            .map(|offset| offset.lock().clone())
 879    }
 880}
 881
 882impl<V> Default for StatelessInteraction<V> {
 883    fn default() -> Self {
 884        Self {
 885            dispatch_context: DispatchContext::default(),
 886            mouse_down_listeners: SmallVec::new(),
 887            mouse_up_listeners: SmallVec::new(),
 888            mouse_move_listeners: SmallVec::new(),
 889            scroll_wheel_listeners: SmallVec::new(),
 890            key_listeners: SmallVec::new(),
 891            hover_style: StyleRefinement::default(),
 892            group_hover_style: None,
 893            drag_over_styles: SmallVec::new(),
 894            group_drag_over_styles: SmallVec::new(),
 895            drop_listeners: SmallVec::new(),
 896        }
 897    }
 898}
 899
 900impl<V: 'static> ElementInteraction<V> for StatelessInteraction<V> {
 901    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
 902        None
 903    }
 904
 905    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
 906        None
 907    }
 908
 909    fn as_stateless(&self) -> &StatelessInteraction<V> {
 910        self
 911    }
 912
 913    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
 914        self
 915    }
 916}
 917
 918#[derive(Clone, Debug, Eq, PartialEq)]
 919pub struct KeyDownEvent {
 920    pub keystroke: Keystroke,
 921    pub is_held: bool,
 922}
 923
 924#[derive(Clone, Debug)]
 925pub struct KeyUpEvent {
 926    pub keystroke: Keystroke,
 927}
 928
 929#[derive(Clone, Debug, Default)]
 930pub struct ModifiersChangedEvent {
 931    pub modifiers: Modifiers,
 932}
 933
 934impl Deref for ModifiersChangedEvent {
 935    type Target = Modifiers;
 936
 937    fn deref(&self) -> &Self::Target {
 938        &self.modifiers
 939    }
 940}
 941
 942/// The phase of a touch motion event.
 943/// Based on the winit enum of the same name.
 944#[derive(Clone, Copy, Debug)]
 945pub enum TouchPhase {
 946    Started,
 947    Moved,
 948    Ended,
 949}
 950
 951#[derive(Clone, Debug, Default)]
 952pub struct MouseDownEvent {
 953    pub button: MouseButton,
 954    pub position: Point<Pixels>,
 955    pub modifiers: Modifiers,
 956    pub click_count: usize,
 957}
 958
 959#[derive(Clone, Debug, Default)]
 960pub struct MouseUpEvent {
 961    pub button: MouseButton,
 962    pub position: Point<Pixels>,
 963    pub modifiers: Modifiers,
 964    pub click_count: usize,
 965}
 966
 967#[derive(Clone, Debug, Default)]
 968pub struct ClickEvent {
 969    pub down: MouseDownEvent,
 970    pub up: MouseUpEvent,
 971}
 972
 973pub struct Drag<S, R, V, E>
 974where
 975    R: Fn(&mut V, &mut ViewContext<V>) -> E,
 976    V: 'static,
 977    E: Component<()>,
 978{
 979    pub state: S,
 980    pub render_drag_handle: R,
 981    view_type: PhantomData<V>,
 982}
 983
 984impl<S, R, V, E> Drag<S, R, V, E>
 985where
 986    R: Fn(&mut V, &mut ViewContext<V>) -> E,
 987    V: 'static,
 988    E: Component<()>,
 989{
 990    pub fn new(state: S, render_drag_handle: R) -> Self {
 991        Drag {
 992            state,
 993            render_drag_handle,
 994            view_type: PhantomData,
 995        }
 996    }
 997}
 998
 999// impl<S, R, V, E> Render for Drag<S, R, V, E> {
1000//     // fn render(&mut self, cx: ViewContext<Self>) ->
1001// }
1002
1003#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1004pub enum MouseButton {
1005    Left,
1006    Right,
1007    Middle,
1008    Navigate(NavigationDirection),
1009}
1010
1011impl MouseButton {
1012    pub fn all() -> Vec<Self> {
1013        vec![
1014            MouseButton::Left,
1015            MouseButton::Right,
1016            MouseButton::Middle,
1017            MouseButton::Navigate(NavigationDirection::Back),
1018            MouseButton::Navigate(NavigationDirection::Forward),
1019        ]
1020    }
1021}
1022
1023impl Default for MouseButton {
1024    fn default() -> Self {
1025        Self::Left
1026    }
1027}
1028
1029#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1030pub enum NavigationDirection {
1031    Back,
1032    Forward,
1033}
1034
1035impl Default for NavigationDirection {
1036    fn default() -> Self {
1037        Self::Back
1038    }
1039}
1040
1041#[derive(Clone, Debug, Default)]
1042pub struct MouseMoveEvent {
1043    pub position: Point<Pixels>,
1044    pub pressed_button: Option<MouseButton>,
1045    pub modifiers: Modifiers,
1046}
1047
1048#[derive(Clone, Debug)]
1049pub struct ScrollWheelEvent {
1050    pub position: Point<Pixels>,
1051    pub delta: ScrollDelta,
1052    pub modifiers: Modifiers,
1053    pub touch_phase: TouchPhase,
1054}
1055
1056impl Deref for ScrollWheelEvent {
1057    type Target = Modifiers;
1058
1059    fn deref(&self) -> &Self::Target {
1060        &self.modifiers
1061    }
1062}
1063
1064#[derive(Clone, Copy, Debug)]
1065pub enum ScrollDelta {
1066    Pixels(Point<Pixels>),
1067    Lines(Point<f32>),
1068}
1069
1070impl Default for ScrollDelta {
1071    fn default() -> Self {
1072        Self::Lines(Default::default())
1073    }
1074}
1075
1076impl ScrollDelta {
1077    pub fn precise(&self) -> bool {
1078        match self {
1079            ScrollDelta::Pixels(_) => true,
1080            ScrollDelta::Lines(_) => false,
1081        }
1082    }
1083
1084    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
1085        match self {
1086            ScrollDelta::Pixels(delta) => *delta,
1087            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
1088        }
1089    }
1090}
1091
1092#[derive(Clone, Debug, Default)]
1093pub struct MouseExitEvent {
1094    pub position: Point<Pixels>,
1095    pub pressed_button: Option<MouseButton>,
1096    pub modifiers: Modifiers,
1097}
1098
1099impl Deref for MouseExitEvent {
1100    type Target = Modifiers;
1101
1102    fn deref(&self) -> &Self::Target {
1103        &self.modifiers
1104    }
1105}
1106
1107#[derive(Debug, Clone, Default)]
1108pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
1109
1110impl Render for ExternalPaths {
1111    type Element = Div<Self>;
1112
1113    fn render(&mut self, _: &mut ViewContext<Self>) -> Self::Element {
1114        div() // Intentionally left empty because the platform will render icons for the dragged files
1115    }
1116}
1117
1118#[derive(Debug, Clone)]
1119pub enum FileDropEvent {
1120    Entered {
1121        position: Point<Pixels>,
1122        files: ExternalPaths,
1123    },
1124    Pending {
1125        position: Point<Pixels>,
1126    },
1127    Submit {
1128        position: Point<Pixels>,
1129    },
1130    Exited,
1131}
1132
1133#[derive(Clone, Debug)]
1134pub enum InputEvent {
1135    KeyDown(KeyDownEvent),
1136    KeyUp(KeyUpEvent),
1137    ModifiersChanged(ModifiersChangedEvent),
1138    MouseDown(MouseDownEvent),
1139    MouseUp(MouseUpEvent),
1140    MouseMove(MouseMoveEvent),
1141    MouseExited(MouseExitEvent),
1142    ScrollWheel(ScrollWheelEvent),
1143    FileDrop(FileDropEvent),
1144}
1145
1146impl InputEvent {
1147    pub fn position(&self) -> Option<Point<Pixels>> {
1148        match self {
1149            InputEvent::KeyDown { .. } => None,
1150            InputEvent::KeyUp { .. } => None,
1151            InputEvent::ModifiersChanged { .. } => None,
1152            InputEvent::MouseDown(event) => Some(event.position),
1153            InputEvent::MouseUp(event) => Some(event.position),
1154            InputEvent::MouseMove(event) => Some(event.position),
1155            InputEvent::MouseExited(event) => Some(event.position),
1156            InputEvent::ScrollWheel(event) => Some(event.position),
1157            InputEvent::FileDrop(FileDropEvent::Exited) => None,
1158            InputEvent::FileDrop(
1159                FileDropEvent::Entered { position, .. }
1160                | FileDropEvent::Pending { position, .. }
1161                | FileDropEvent::Submit { position, .. },
1162            ) => Some(*position),
1163        }
1164    }
1165
1166    pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
1167        match self {
1168            InputEvent::KeyDown { .. } => None,
1169            InputEvent::KeyUp { .. } => None,
1170            InputEvent::ModifiersChanged { .. } => None,
1171            InputEvent::MouseDown(event) => Some(event),
1172            InputEvent::MouseUp(event) => Some(event),
1173            InputEvent::MouseMove(event) => Some(event),
1174            InputEvent::MouseExited(event) => Some(event),
1175            InputEvent::ScrollWheel(event) => Some(event),
1176            InputEvent::FileDrop(event) => Some(event),
1177        }
1178    }
1179
1180    pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
1181        match self {
1182            InputEvent::KeyDown(event) => Some(event),
1183            InputEvent::KeyUp(event) => Some(event),
1184            InputEvent::ModifiersChanged(event) => Some(event),
1185            InputEvent::MouseDown(_) => None,
1186            InputEvent::MouseUp(_) => None,
1187            InputEvent::MouseMove(_) => None,
1188            InputEvent::MouseExited(_) => None,
1189            InputEvent::ScrollWheel(_) => None,
1190            InputEvent::FileDrop(_) => None,
1191        }
1192    }
1193}
1194
1195pub struct FocusEvent {
1196    pub blurred: Option<FocusHandle>,
1197    pub focused: Option<FocusHandle>,
1198}
1199
1200pub type MouseDownListener<V> = Box<
1201    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1202>;
1203pub type MouseUpListener<V> = Box<
1204    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1205>;
1206
1207pub type MouseMoveListener<V> = Box<
1208    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1209>;
1210
1211pub type ScrollWheelListener<V> = Box<
1212    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
1213        + 'static,
1214>;
1215
1216pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
1217
1218pub(crate) type DragListener<V> =
1219    Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
1220
1221pub(crate) type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
1222
1223pub(crate) type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
1224
1225pub type KeyListener<V> = Box<
1226    dyn Fn(
1227            &mut V,
1228            &dyn Any,
1229            &[&DispatchContext],
1230            DispatchPhase,
1231            &mut ViewContext<V>,
1232        ) -> Option<Box<dyn Action>>
1233        + 'static,
1234>;