window.rs

   1use crate::{
   2    build_action_from_type, px, size, Action, AnyBox, AnyDrag, AnyView, AppContext,
   3    AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
   4    DevicePixels, DispatchContext, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
   5    FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId, Hsla, ImageData, InputEvent,
   6    IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId, Model, ModelContext, Modifiers,
   7    MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
   8    PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
   9    PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels,
  10    SceneBuilder, Shadow, SharedString, Size, Style, SubscriberSet, Subscription,
  11    TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakView,
  12    WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
  13};
  14use anyhow::{anyhow, Result};
  15use collections::HashMap;
  16use derive_more::{Deref, DerefMut};
  17use futures::{
  18    channel::{mpsc, oneshot},
  19    StreamExt,
  20};
  21use parking_lot::RwLock;
  22use slotmap::SlotMap;
  23use smallvec::SmallVec;
  24use std::{
  25    any::{Any, TypeId},
  26    borrow::{Borrow, BorrowMut, Cow},
  27    fmt::Debug,
  28    future::Future,
  29    hash::{Hash, Hasher},
  30    marker::PhantomData,
  31    mem,
  32    rc::Rc,
  33    sync::{
  34        atomic::{AtomicUsize, Ordering::SeqCst},
  35        Arc,
  36    },
  37};
  38use util::ResultExt;
  39
  40/// A global stacking order, which is created by stacking successive z-index values.
  41/// Each z-index will always be interpreted in the context of its parent z-index.
  42#[derive(Deref, DerefMut, Ord, PartialOrd, Eq, PartialEq, Clone, Default)]
  43pub(crate) struct StackingOrder(pub(crate) SmallVec<[u32; 16]>);
  44
  45/// Represents the two different phases when dispatching events.
  46#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
  47pub enum DispatchPhase {
  48    /// After the capture phase comes the bubble phase, in which mouse event listeners are
  49    /// invoked front to back and keyboard event listeners are invoked from the focused element
  50    /// to the root of the element tree. This is the phase you'll most commonly want to use when
  51    /// registering event listeners.
  52    #[default]
  53    Bubble,
  54    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
  55    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
  56    /// is used for special purposes such as clearing the "pressed" state for click events. If
  57    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
  58    /// outside of the immediate region may rely on detecting non-local events during this phase.
  59    Capture,
  60}
  61
  62type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
  63type AnyListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
  64type AnyKeyListener = Box<
  65    dyn Fn(
  66            &dyn Any,
  67            &[&DispatchContext],
  68            DispatchPhase,
  69            &mut WindowContext,
  70        ) -> Option<Box<dyn Action>>
  71        + 'static,
  72>;
  73type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
  74type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
  75
  76slotmap::new_key_type! { pub struct FocusId; }
  77
  78impl FocusId {
  79    /// Obtains whether the element associated with this handle is currently focused.
  80    pub fn is_focused(&self, cx: &WindowContext) -> bool {
  81        cx.window.focus == Some(*self)
  82    }
  83
  84    /// Obtains whether the element associated with this handle contains the focused
  85    /// element or is itself focused.
  86    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
  87        cx.focused()
  88            .map_or(false, |focused| self.contains(focused.id, cx))
  89    }
  90
  91    /// Obtains whether the element associated with this handle is contained within the
  92    /// focused element or is itself focused.
  93    pub fn within_focused(&self, cx: &WindowContext) -> bool {
  94        let focused = cx.focused();
  95        focused.map_or(false, |focused| focused.id.contains(*self, cx))
  96    }
  97
  98    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
  99    pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
 100        let mut ancestor = Some(other);
 101        while let Some(ancestor_id) = ancestor {
 102            if *self == ancestor_id {
 103                return true;
 104            } else {
 105                ancestor = cx
 106                    .window
 107                    .current_frame
 108                    .focus_parents_by_child
 109                    .get(&ancestor_id)
 110                    .copied();
 111            }
 112        }
 113        false
 114    }
 115}
 116
 117/// A handle which can be used to track and manipulate the focused element in a window.
 118pub struct FocusHandle {
 119    pub(crate) id: FocusId,
 120    handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 121}
 122
 123impl FocusHandle {
 124    pub(crate) fn new(handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>) -> Self {
 125        let id = handles.write().insert(AtomicUsize::new(1));
 126        Self {
 127            id,
 128            handles: handles.clone(),
 129        }
 130    }
 131
 132    pub(crate) fn for_id(
 133        id: FocusId,
 134        handles: &Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 135    ) -> Option<Self> {
 136        let lock = handles.read();
 137        let ref_count = lock.get(id)?;
 138        if ref_count.load(SeqCst) == 0 {
 139            None
 140        } else {
 141            ref_count.fetch_add(1, SeqCst);
 142            Some(Self {
 143                id,
 144                handles: handles.clone(),
 145            })
 146        }
 147    }
 148
 149    /// Moves the focus to the element associated with this handle.
 150    pub fn focus(&self, cx: &mut WindowContext) {
 151        cx.focus(self)
 152    }
 153
 154    /// Obtains whether the element associated with this handle is currently focused.
 155    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 156        self.id.is_focused(cx)
 157    }
 158
 159    /// Obtains whether the element associated with this handle contains the focused
 160    /// element or is itself focused.
 161    pub fn contains_focused(&self, cx: &WindowContext) -> bool {
 162        self.id.contains_focused(cx)
 163    }
 164
 165    /// Obtains whether the element associated with this handle is contained within the
 166    /// focused element or is itself focused.
 167    pub fn within_focused(&self, cx: &WindowContext) -> bool {
 168        self.id.within_focused(cx)
 169    }
 170
 171    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
 172    pub(crate) fn contains(&self, other: &Self, cx: &WindowContext) -> bool {
 173        self.id.contains(other.id, cx)
 174    }
 175}
 176
 177impl Clone for FocusHandle {
 178    fn clone(&self) -> Self {
 179        Self::for_id(self.id, &self.handles).unwrap()
 180    }
 181}
 182
 183impl PartialEq for FocusHandle {
 184    fn eq(&self, other: &Self) -> bool {
 185        self.id == other.id
 186    }
 187}
 188
 189impl Eq for FocusHandle {}
 190
 191impl Drop for FocusHandle {
 192    fn drop(&mut self) {
 193        self.handles
 194            .read()
 195            .get(self.id)
 196            .unwrap()
 197            .fetch_sub(1, SeqCst);
 198    }
 199}
 200
 201// Holds the state for a specific window.
 202pub struct Window {
 203    pub(crate) handle: AnyWindowHandle,
 204    pub(crate) removed: bool,
 205    platform_window: Box<dyn PlatformWindow>,
 206    display_id: DisplayId,
 207    sprite_atlas: Arc<dyn PlatformAtlas>,
 208    rem_size: Pixels,
 209    content_size: Size<Pixels>,
 210    pub(crate) layout_engine: TaffyLayoutEngine,
 211    pub(crate) root_view: Option<AnyView>,
 212    pub(crate) element_id_stack: GlobalElementId,
 213    pub(crate) previous_frame: Frame,
 214    pub(crate) current_frame: Frame,
 215    pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
 216    pub(crate) focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
 217    default_prevented: bool,
 218    mouse_position: Point<Pixels>,
 219    requested_cursor_style: Option<CursorStyle>,
 220    scale_factor: f32,
 221    bounds: WindowBounds,
 222    bounds_observers: SubscriberSet<(), AnyObserver>,
 223    active: bool,
 224    activation_observers: SubscriberSet<(), AnyObserver>,
 225    pub(crate) dirty: bool,
 226    pub(crate) last_blur: Option<Option<FocusId>>,
 227    pub(crate) focus: Option<FocusId>,
 228}
 229
 230#[derive(Default)]
 231pub(crate) struct Frame {
 232    element_states: HashMap<GlobalElementId, AnyBox>,
 233    key_matchers: HashMap<GlobalElementId, KeyMatcher>,
 234    mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
 235    pub(crate) focus_listeners: Vec<AnyFocusListener>,
 236    pub(crate) key_dispatch_stack: Vec<KeyDispatchStackFrame>,
 237    freeze_key_dispatch_stack: bool,
 238    focus_parents_by_child: HashMap<FocusId, FocusId>,
 239    pub(crate) scene_builder: SceneBuilder,
 240    z_index_stack: StackingOrder,
 241    content_mask_stack: Vec<ContentMask<Pixels>>,
 242    element_offset_stack: Vec<Point<Pixels>>,
 243    focus_stack: Vec<FocusId>,
 244}
 245
 246impl Window {
 247    pub(crate) fn new(
 248        handle: AnyWindowHandle,
 249        options: WindowOptions,
 250        cx: &mut AppContext,
 251    ) -> Self {
 252        let platform_window = cx.platform.open_window(handle, options);
 253        let display_id = platform_window.display().id();
 254        let sprite_atlas = platform_window.sprite_atlas();
 255        let mouse_position = platform_window.mouse_position();
 256        let content_size = platform_window.content_size();
 257        let scale_factor = platform_window.scale_factor();
 258        let bounds = platform_window.bounds();
 259
 260        platform_window.on_resize(Box::new({
 261            let mut cx = cx.to_async();
 262            move |_, _| {
 263                handle
 264                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 265                    .log_err();
 266            }
 267        }));
 268        platform_window.on_moved(Box::new({
 269            let mut cx = cx.to_async();
 270            move || {
 271                handle
 272                    .update(&mut cx, |_, cx| cx.window_bounds_changed())
 273                    .log_err();
 274            }
 275        }));
 276        platform_window.on_active_status_change(Box::new({
 277            let mut cx = cx.to_async();
 278            move |active| {
 279                handle
 280                    .update(&mut cx, |_, cx| {
 281                        cx.window.active = active;
 282                        cx.window
 283                            .activation_observers
 284                            .clone()
 285                            .retain(&(), |callback| callback(cx));
 286                    })
 287                    .log_err();
 288            }
 289        }));
 290
 291        platform_window.on_input({
 292            let mut cx = cx.to_async();
 293            Box::new(move |event| {
 294                handle
 295                    .update(&mut cx, |_, cx| cx.dispatch_event(event))
 296                    .log_err()
 297                    .unwrap_or(false)
 298            })
 299        });
 300
 301        Window {
 302            handle,
 303            removed: false,
 304            platform_window,
 305            display_id,
 306            sprite_atlas,
 307            rem_size: px(16.),
 308            content_size,
 309            layout_engine: TaffyLayoutEngine::new(),
 310            root_view: None,
 311            element_id_stack: GlobalElementId::default(),
 312            previous_frame: Frame::default(),
 313            current_frame: Frame::default(),
 314            focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
 315            focus_listeners: SubscriberSet::new(),
 316            default_prevented: true,
 317            mouse_position,
 318            requested_cursor_style: None,
 319            scale_factor,
 320            bounds,
 321            bounds_observers: SubscriberSet::new(),
 322            active: false,
 323            activation_observers: SubscriberSet::new(),
 324            dirty: true,
 325            last_blur: None,
 326            focus: None,
 327        }
 328    }
 329}
 330
 331/// When constructing the element tree, we maintain a stack of key dispatch frames until we
 332/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
 333/// contexts when matching key events against the keymap. A key listener can be either an action
 334/// handler or a [KeyDown] / [KeyUp] event listener.
 335pub(crate) enum KeyDispatchStackFrame {
 336    Listener {
 337        event_type: TypeId,
 338        listener: AnyKeyListener,
 339    },
 340    Context(DispatchContext),
 341}
 342
 343/// Indicates which region of the window is visible. Content falling outside of this mask will not be
 344/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
 345/// to leave room to support more complex shapes in the future.
 346#[derive(Clone, Debug, Default, PartialEq, Eq)]
 347#[repr(C)]
 348pub struct ContentMask<P: Clone + Default + Debug> {
 349    pub bounds: Bounds<P>,
 350}
 351
 352impl ContentMask<Pixels> {
 353    /// Scale the content mask's pixel units by the given scaling factor.
 354    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
 355        ContentMask {
 356            bounds: self.bounds.scale(factor),
 357        }
 358    }
 359
 360    /// Intersect the content mask with the given content mask.
 361    pub fn intersect(&self, other: &Self) -> Self {
 362        let bounds = self.bounds.intersect(&other.bounds);
 363        ContentMask { bounds }
 364    }
 365}
 366
 367/// Provides access to application state in the context of a single window. Derefs
 368/// to an `AppContext`, so you can also pass a `WindowContext` to any method that takes
 369/// an `AppContext` and call any `AppContext` methods.
 370pub struct WindowContext<'a> {
 371    pub(crate) app: &'a mut AppContext,
 372    pub(crate) window: &'a mut Window,
 373}
 374
 375impl<'a> WindowContext<'a> {
 376    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window) -> Self {
 377        Self { app, window }
 378    }
 379
 380    /// Obtain a handle to the window that belongs to this context.
 381    pub fn window_handle(&self) -> AnyWindowHandle {
 382        self.window.handle
 383    }
 384
 385    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
 386    pub fn notify(&mut self) {
 387        self.window.dirty = true;
 388    }
 389
 390    /// Close this window.
 391    pub fn remove_window(&mut self) {
 392        self.window.removed = true;
 393    }
 394
 395    /// Obtain a new `FocusHandle`, which allows you to track and manipulate the keyboard focus
 396    /// for elements rendered within this window.
 397    pub fn focus_handle(&mut self) -> FocusHandle {
 398        FocusHandle::new(&self.window.focus_handles)
 399    }
 400
 401    /// Obtain the currently focused `FocusHandle`. If no elements are focused, returns `None`.
 402    pub fn focused(&self) -> Option<FocusHandle> {
 403        self.window
 404            .focus
 405            .and_then(|id| FocusHandle::for_id(id, &self.window.focus_handles))
 406    }
 407
 408    /// Move focus to the element associated with the given `FocusHandle`.
 409    pub fn focus(&mut self, handle: &FocusHandle) {
 410        if self.window.last_blur.is_none() {
 411            self.window.last_blur = Some(self.window.focus);
 412        }
 413
 414        self.window.focus = Some(handle.id);
 415
 416        // self.window.current_frame.key_dispatch_stack.clear()
 417        // self.window.root_view.initialize()
 418        self.app.push_effect(Effect::FocusChanged {
 419            window_handle: self.window.handle,
 420            focused: Some(handle.id),
 421        });
 422        self.notify();
 423    }
 424
 425    /// Remove focus from all elements within this context's window.
 426    pub fn blur(&mut self) {
 427        if self.window.last_blur.is_none() {
 428            self.window.last_blur = Some(self.window.focus);
 429        }
 430
 431        self.window.focus = None;
 432        self.app.push_effect(Effect::FocusChanged {
 433            window_handle: self.window.handle,
 434            focused: None,
 435        });
 436        self.notify();
 437    }
 438
 439    pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
 440        self.defer(|cx| {
 441            cx.app.propagate_event = true;
 442            let stack = cx.dispatch_stack();
 443            cx.dispatch_action_internal(action, &stack[..])
 444        })
 445    }
 446
 447    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
 448    /// that are currently on the stack to be returned to the app.
 449    pub fn defer(&mut self, f: impl FnOnce(&mut WindowContext) + 'static) {
 450        let handle = self.window.handle;
 451        self.app.defer(move |cx| {
 452            handle.update(cx, |_, cx| f(cx)).ok();
 453        });
 454    }
 455
 456    pub fn subscribe<Emitter, E, Evt>(
 457        &mut self,
 458        entity: &E,
 459        mut on_event: impl FnMut(E, &Evt, &mut WindowContext<'_>) + 'static,
 460    ) -> Subscription
 461    where
 462        Emitter: EventEmitter<Evt>,
 463        E: Entity<Emitter>,
 464        Evt: 'static,
 465    {
 466        let entity_id = entity.entity_id();
 467        let entity = entity.downgrade();
 468        let window_handle = self.window.handle;
 469        self.app.event_listeners.insert(
 470            entity_id,
 471            (
 472                TypeId::of::<Evt>(),
 473                Box::new(move |event, cx| {
 474                    window_handle
 475                        .update(cx, |_, cx| {
 476                            if let Some(handle) = E::upgrade_from(&entity) {
 477                                let event = event.downcast_ref().expect("invalid event type");
 478                                on_event(handle, event, cx);
 479                                true
 480                            } else {
 481                                false
 482                            }
 483                        })
 484                        .unwrap_or(false)
 485                }),
 486            ),
 487        )
 488    }
 489
 490    /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
 491    /// await points in async code.
 492    pub fn to_async(&self) -> AsyncWindowContext {
 493        AsyncWindowContext::new(self.app.to_async(), self.window.handle)
 494    }
 495
 496    /// Schedule the given closure to be run directly after the current frame is rendered.
 497    pub fn on_next_frame(&mut self, callback: impl FnOnce(&mut WindowContext) + 'static) {
 498        let handle = self.window.handle;
 499        let display_id = self.window.display_id;
 500
 501        if !self.frame_consumers.contains_key(&display_id) {
 502            let (tx, mut rx) = mpsc::unbounded::<()>();
 503            self.platform.set_display_link_output_callback(
 504                display_id,
 505                Box::new(move |_current_time, _output_time| _ = tx.unbounded_send(())),
 506            );
 507
 508            let consumer_task = self.app.spawn(|cx| async move {
 509                while rx.next().await.is_some() {
 510                    cx.update(|cx| {
 511                        for callback in cx
 512                            .next_frame_callbacks
 513                            .get_mut(&display_id)
 514                            .unwrap()
 515                            .drain(..)
 516                            .collect::<SmallVec<[_; 32]>>()
 517                        {
 518                            callback(cx);
 519                        }
 520                    })
 521                    .ok();
 522
 523                    // Flush effects, then stop the display link if no new next_frame_callbacks have been added.
 524
 525                    cx.update(|cx| {
 526                        if cx.next_frame_callbacks.is_empty() {
 527                            cx.platform.stop_display_link(display_id);
 528                        }
 529                    })
 530                    .ok();
 531                }
 532            });
 533            self.frame_consumers.insert(display_id, consumer_task);
 534        }
 535
 536        if self.next_frame_callbacks.is_empty() {
 537            self.platform.start_display_link(display_id);
 538        }
 539
 540        self.next_frame_callbacks
 541            .entry(display_id)
 542            .or_default()
 543            .push(Box::new(move |cx: &mut AppContext| {
 544                cx.update_window(handle, |_root_view, cx| callback(cx)).ok();
 545            }));
 546    }
 547
 548    /// Spawn the future returned by the given closure on the application thread pool.
 549    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
 550    /// use within your future.
 551    pub fn spawn<Fut, R>(&mut self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
 552    where
 553        R: 'static,
 554        Fut: Future<Output = R> + 'static,
 555    {
 556        self.app
 557            .spawn(|app| f(AsyncWindowContext::new(app, self.window.handle)))
 558    }
 559
 560    /// Update the global of the given type. The given closure is given simultaneous mutable
 561    /// access both to the global and the context.
 562    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
 563    where
 564        G: 'static,
 565    {
 566        let mut global = self.app.lease_global::<G>();
 567        let result = f(&mut global, self);
 568        self.app.end_global_lease(global);
 569        result
 570    }
 571
 572    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
 573    /// layout is being requested, along with the layout ids of any children. This method is called during
 574    /// calls to the `Element::layout` trait method and enables any element to participate in layout.
 575    pub fn request_layout(
 576        &mut self,
 577        style: &Style,
 578        children: impl IntoIterator<Item = LayoutId>,
 579    ) -> LayoutId {
 580        self.app.layout_id_buffer.clear();
 581        self.app.layout_id_buffer.extend(children.into_iter());
 582        let rem_size = self.rem_size();
 583
 584        self.window
 585            .layout_engine
 586            .request_layout(style, rem_size, &self.app.layout_id_buffer)
 587    }
 588
 589    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
 590    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
 591    /// determine the element's size. One place this is used internally is when measuring text.
 592    ///
 593    /// The given closure is invoked at layout time with the known dimensions and available space and
 594    /// returns a `Size`.
 595    pub fn request_measured_layout<
 596        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>) -> Size<Pixels> + Send + Sync + 'static,
 597    >(
 598        &mut self,
 599        style: Style,
 600        rem_size: Pixels,
 601        measure: F,
 602    ) -> LayoutId {
 603        self.window
 604            .layout_engine
 605            .request_measured_layout(style, rem_size, measure)
 606    }
 607
 608    pub fn compute_layout(&mut self, layout_id: LayoutId, available_space: Size<AvailableSpace>) {
 609        self.window
 610            .layout_engine
 611            .compute_layout(layout_id, available_space)
 612    }
 613
 614    /// Obtain the bounds computed for the given LayoutId relative to the window. This method should not
 615    /// be invoked until the paint phase begins, and will usually be invoked by GPUI itself automatically
 616    /// in order to pass your element its `Bounds` automatically.
 617    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
 618        let mut bounds = self
 619            .window
 620            .layout_engine
 621            .layout_bounds(layout_id)
 622            .map(Into::into);
 623        bounds.origin += self.element_offset();
 624        bounds
 625    }
 626
 627    fn window_bounds_changed(&mut self) {
 628        self.window.scale_factor = self.window.platform_window.scale_factor();
 629        self.window.content_size = self.window.platform_window.content_size();
 630        self.window.bounds = self.window.platform_window.bounds();
 631        self.window.display_id = self.window.platform_window.display().id();
 632        self.window.dirty = true;
 633
 634        self.window
 635            .bounds_observers
 636            .clone()
 637            .retain(&(), |callback| callback(self));
 638    }
 639
 640    pub fn window_bounds(&self) -> WindowBounds {
 641        self.window.bounds
 642    }
 643
 644    pub fn is_window_active(&self) -> bool {
 645        self.window.active
 646    }
 647
 648    pub fn zoom_window(&self) {
 649        self.window.platform_window.zoom();
 650    }
 651
 652    pub fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 653        self.platform
 654            .displays()
 655            .into_iter()
 656            .find(|display| display.id() == self.window.display_id)
 657    }
 658
 659    pub fn show_character_palette(&self) {
 660        self.window.platform_window.show_character_palette();
 661    }
 662
 663    /// The scale factor of the display associated with the window. For example, it could
 664    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
 665    /// be rendered as two pixels on screen.
 666    pub fn scale_factor(&self) -> f32 {
 667        self.window.scale_factor
 668    }
 669
 670    /// The size of an em for the base font of the application. Adjusting this value allows the
 671    /// UI to scale, just like zooming a web page.
 672    pub fn rem_size(&self) -> Pixels {
 673        self.window.rem_size
 674    }
 675
 676    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
 677    /// UI to scale, just like zooming a web page.
 678    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
 679        self.window.rem_size = rem_size.into();
 680    }
 681
 682    /// The line height associated with the current text style.
 683    pub fn line_height(&self) -> Pixels {
 684        let rem_size = self.rem_size();
 685        let text_style = self.text_style();
 686        text_style
 687            .line_height
 688            .to_pixels(text_style.font_size.into(), rem_size)
 689    }
 690
 691    /// Call to prevent the default action of an event. Currently only used to prevent
 692    /// parent elements from becoming focused on mouse down.
 693    pub fn prevent_default(&mut self) {
 694        self.window.default_prevented = true;
 695    }
 696
 697    /// Obtain whether default has been prevented for the event currently being dispatched.
 698    pub fn default_prevented(&self) -> bool {
 699        self.window.default_prevented
 700    }
 701
 702    /// Register a mouse event listener on the window for the current frame. The type of event
 703    /// is determined by the first parameter of the given listener. When the next frame is rendered
 704    /// the listener will be cleared.
 705    ///
 706    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
 707    /// a specific need to register a global listener.
 708    pub fn on_mouse_event<Event: 'static>(
 709        &mut self,
 710        handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
 711    ) {
 712        let order = self.window.current_frame.z_index_stack.clone();
 713        self.window
 714            .current_frame
 715            .mouse_listeners
 716            .entry(TypeId::of::<Event>())
 717            .or_default()
 718            .push((
 719                order,
 720                Box::new(move |event: &dyn Any, phase, cx| {
 721                    handler(event.downcast_ref().unwrap(), phase, cx)
 722                }),
 723            ))
 724    }
 725
 726    /// The position of the mouse relative to the window.
 727    pub fn mouse_position(&self) -> Point<Pixels> {
 728        self.window.mouse_position
 729    }
 730
 731    pub fn set_cursor_style(&mut self, style: CursorStyle) {
 732        self.window.requested_cursor_style = Some(style)
 733    }
 734
 735    /// Called during painting to invoke the given closure in a new stacking context. The given
 736    /// z-index is interpreted relative to the previous call to `stack`.
 737    pub fn stack<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
 738        self.window.current_frame.z_index_stack.push(z_index);
 739        let result = f(self);
 740        self.window.current_frame.z_index_stack.pop();
 741        result
 742    }
 743
 744    /// Paint one or more drop shadows into the scene for the current frame at the current z-index.
 745    pub fn paint_shadows(
 746        &mut self,
 747        bounds: Bounds<Pixels>,
 748        corner_radii: Corners<Pixels>,
 749        shadows: &[BoxShadow],
 750    ) {
 751        let scale_factor = self.scale_factor();
 752        let content_mask = self.content_mask();
 753        let window = &mut *self.window;
 754        for shadow in shadows {
 755            let mut shadow_bounds = bounds;
 756            shadow_bounds.origin += shadow.offset;
 757            shadow_bounds.dilate(shadow.spread_radius);
 758            window.current_frame.scene_builder.insert(
 759                &window.current_frame.z_index_stack,
 760                Shadow {
 761                    order: 0,
 762                    bounds: shadow_bounds.scale(scale_factor),
 763                    content_mask: content_mask.scale(scale_factor),
 764                    corner_radii: corner_radii.scale(scale_factor),
 765                    color: shadow.color,
 766                    blur_radius: shadow.blur_radius.scale(scale_factor),
 767                },
 768            );
 769        }
 770    }
 771
 772    /// Paint one or more quads into the scene for the current frame at the current stacking context.
 773    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
 774    pub fn paint_quad(
 775        &mut self,
 776        bounds: Bounds<Pixels>,
 777        corner_radii: Corners<Pixels>,
 778        background: impl Into<Hsla>,
 779        border_widths: Edges<Pixels>,
 780        border_color: impl Into<Hsla>,
 781    ) {
 782        let scale_factor = self.scale_factor();
 783        let content_mask = self.content_mask();
 784
 785        let window = &mut *self.window;
 786        window.current_frame.scene_builder.insert(
 787            &window.current_frame.z_index_stack,
 788            Quad {
 789                order: 0,
 790                bounds: bounds.scale(scale_factor),
 791                content_mask: content_mask.scale(scale_factor),
 792                background: background.into(),
 793                border_color: border_color.into(),
 794                corner_radii: corner_radii.scale(scale_factor),
 795                border_widths: border_widths.scale(scale_factor),
 796            },
 797        );
 798    }
 799
 800    /// Paint the given `Path` into the scene for the current frame at the current z-index.
 801    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Hsla>) {
 802        let scale_factor = self.scale_factor();
 803        let content_mask = self.content_mask();
 804        path.content_mask = content_mask;
 805        path.color = color.into();
 806        let window = &mut *self.window;
 807        window.current_frame.scene_builder.insert(
 808            &window.current_frame.z_index_stack,
 809            path.scale(scale_factor),
 810        );
 811    }
 812
 813    /// Paint an underline into the scene for the current frame at the current z-index.
 814    pub fn paint_underline(
 815        &mut self,
 816        origin: Point<Pixels>,
 817        width: Pixels,
 818        style: &UnderlineStyle,
 819    ) -> Result<()> {
 820        let scale_factor = self.scale_factor();
 821        let height = if style.wavy {
 822            style.thickness * 3.
 823        } else {
 824            style.thickness
 825        };
 826        let bounds = Bounds {
 827            origin,
 828            size: size(width, height),
 829        };
 830        let content_mask = self.content_mask();
 831        let window = &mut *self.window;
 832        window.current_frame.scene_builder.insert(
 833            &window.current_frame.z_index_stack,
 834            Underline {
 835                order: 0,
 836                bounds: bounds.scale(scale_factor),
 837                content_mask: content_mask.scale(scale_factor),
 838                thickness: style.thickness.scale(scale_factor),
 839                color: style.color.unwrap_or_default(),
 840                wavy: style.wavy,
 841            },
 842        );
 843        Ok(())
 844    }
 845
 846    /// Paint a monochrome (non-emoji) glyph into the scene for the current frame at the current z-index.
 847    /// The y component of the origin is the baseline of the glyph.
 848    pub fn paint_glyph(
 849        &mut self,
 850        origin: Point<Pixels>,
 851        font_id: FontId,
 852        glyph_id: GlyphId,
 853        font_size: Pixels,
 854        color: Hsla,
 855    ) -> Result<()> {
 856        let scale_factor = self.scale_factor();
 857        let glyph_origin = origin.scale(scale_factor);
 858        let subpixel_variant = Point {
 859            x: (glyph_origin.x.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 860            y: (glyph_origin.y.0.fract() * SUBPIXEL_VARIANTS as f32).floor() as u8,
 861        };
 862        let params = RenderGlyphParams {
 863            font_id,
 864            glyph_id,
 865            font_size,
 866            subpixel_variant,
 867            scale_factor,
 868            is_emoji: false,
 869        };
 870
 871        let raster_bounds = self.text_system().raster_bounds(&params)?;
 872        if !raster_bounds.is_zero() {
 873            let tile =
 874                self.window
 875                    .sprite_atlas
 876                    .get_or_insert_with(&params.clone().into(), &mut || {
 877                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 878                        Ok((size, Cow::Owned(bytes)))
 879                    })?;
 880            let bounds = Bounds {
 881                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 882                size: tile.bounds.size.map(Into::into),
 883            };
 884            let content_mask = self.content_mask().scale(scale_factor);
 885            let window = &mut *self.window;
 886            window.current_frame.scene_builder.insert(
 887                &window.current_frame.z_index_stack,
 888                MonochromeSprite {
 889                    order: 0,
 890                    bounds,
 891                    content_mask,
 892                    color,
 893                    tile,
 894                },
 895            );
 896        }
 897        Ok(())
 898    }
 899
 900    /// Paint an emoji glyph into the scene for the current frame at the current z-index.
 901    /// The y component of the origin is the baseline of the glyph.
 902    pub fn paint_emoji(
 903        &mut self,
 904        origin: Point<Pixels>,
 905        font_id: FontId,
 906        glyph_id: GlyphId,
 907        font_size: Pixels,
 908    ) -> Result<()> {
 909        let scale_factor = self.scale_factor();
 910        let glyph_origin = origin.scale(scale_factor);
 911        let params = RenderGlyphParams {
 912            font_id,
 913            glyph_id,
 914            font_size,
 915            // We don't render emojis with subpixel variants.
 916            subpixel_variant: Default::default(),
 917            scale_factor,
 918            is_emoji: true,
 919        };
 920
 921        let raster_bounds = self.text_system().raster_bounds(&params)?;
 922        if !raster_bounds.is_zero() {
 923            let tile =
 924                self.window
 925                    .sprite_atlas
 926                    .get_or_insert_with(&params.clone().into(), &mut || {
 927                        let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
 928                        Ok((size, Cow::Owned(bytes)))
 929                    })?;
 930            let bounds = Bounds {
 931                origin: glyph_origin.map(|px| px.floor()) + raster_bounds.origin.map(Into::into),
 932                size: tile.bounds.size.map(Into::into),
 933            };
 934            let content_mask = self.content_mask().scale(scale_factor);
 935            let window = &mut *self.window;
 936
 937            window.current_frame.scene_builder.insert(
 938                &window.current_frame.z_index_stack,
 939                PolychromeSprite {
 940                    order: 0,
 941                    bounds,
 942                    corner_radii: Default::default(),
 943                    content_mask,
 944                    tile,
 945                    grayscale: false,
 946                },
 947            );
 948        }
 949        Ok(())
 950    }
 951
 952    /// Paint a monochrome SVG into the scene for the current frame at the current stacking context.
 953    pub fn paint_svg(
 954        &mut self,
 955        bounds: Bounds<Pixels>,
 956        path: SharedString,
 957        color: Hsla,
 958    ) -> Result<()> {
 959        let scale_factor = self.scale_factor();
 960        let bounds = bounds.scale(scale_factor);
 961        // Render the SVG at twice the size to get a higher quality result.
 962        let params = RenderSvgParams {
 963            path,
 964            size: bounds
 965                .size
 966                .map(|pixels| DevicePixels::from((pixels.0 * 2.).ceil() as i32)),
 967        };
 968
 969        let tile =
 970            self.window
 971                .sprite_atlas
 972                .get_or_insert_with(&params.clone().into(), &mut || {
 973                    let bytes = self.svg_renderer.render(&params)?;
 974                    Ok((params.size, Cow::Owned(bytes)))
 975                })?;
 976        let content_mask = self.content_mask().scale(scale_factor);
 977
 978        let window = &mut *self.window;
 979        window.current_frame.scene_builder.insert(
 980            &window.current_frame.z_index_stack,
 981            MonochromeSprite {
 982                order: 0,
 983                bounds,
 984                content_mask,
 985                color,
 986                tile,
 987            },
 988        );
 989
 990        Ok(())
 991    }
 992
 993    /// Paint an image into the scene for the current frame at the current z-index.
 994    pub fn paint_image(
 995        &mut self,
 996        bounds: Bounds<Pixels>,
 997        corner_radii: Corners<Pixels>,
 998        data: Arc<ImageData>,
 999        grayscale: bool,
1000    ) -> Result<()> {
1001        let scale_factor = self.scale_factor();
1002        let bounds = bounds.scale(scale_factor);
1003        let params = RenderImageParams { image_id: data.id };
1004
1005        let tile = self
1006            .window
1007            .sprite_atlas
1008            .get_or_insert_with(&params.clone().into(), &mut || {
1009                Ok((data.size(), Cow::Borrowed(data.as_bytes())))
1010            })?;
1011        let content_mask = self.content_mask().scale(scale_factor);
1012        let corner_radii = corner_radii.scale(scale_factor);
1013
1014        let window = &mut *self.window;
1015        window.current_frame.scene_builder.insert(
1016            &window.current_frame.z_index_stack,
1017            PolychromeSprite {
1018                order: 0,
1019                bounds,
1020                content_mask,
1021                corner_radii,
1022                tile,
1023                grayscale,
1024            },
1025        );
1026        Ok(())
1027    }
1028
1029    /// Draw pixels to the display for this window based on the contents of its scene.
1030    pub(crate) fn draw(&mut self) {
1031        let root_view = self.window.root_view.take().unwrap();
1032
1033        self.start_frame();
1034
1035        self.stack(0, |cx| {
1036            let available_space = cx.window.content_size.map(Into::into);
1037            root_view.draw(available_space, cx);
1038        });
1039
1040        if let Some(active_drag) = self.app.active_drag.take() {
1041            self.stack(1, |cx| {
1042                let offset = cx.mouse_position() - active_drag.cursor_offset;
1043                cx.with_element_offset(Some(offset), |cx| {
1044                    let available_space =
1045                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1046                    active_drag.view.draw(available_space, cx);
1047                    cx.active_drag = Some(active_drag);
1048                });
1049            });
1050        } else if let Some(active_tooltip) = self.app.active_tooltip.take() {
1051            self.stack(1, |cx| {
1052                cx.with_element_offset(Some(active_tooltip.cursor_offset), |cx| {
1053                    let available_space =
1054                        size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1055                    active_tooltip.view.draw(available_space, cx);
1056                });
1057            });
1058        }
1059
1060        self.window.root_view = Some(root_view);
1061        let scene = self.window.current_frame.scene_builder.build();
1062
1063        self.window.platform_window.draw(scene);
1064        let cursor_style = self
1065            .window
1066            .requested_cursor_style
1067            .take()
1068            .unwrap_or(CursorStyle::Arrow);
1069        self.platform.set_cursor_style(cursor_style);
1070
1071        self.window.dirty = false;
1072    }
1073
1074    pub(crate) fn dispatch_stack(&mut self) -> Vec<KeyDispatchStackFrame> {
1075        let root_view = self.window.root_view.take().unwrap();
1076        let window = &mut *self.window;
1077        let mut spare_frame = Frame::default();
1078        mem::swap(&mut spare_frame, &mut window.previous_frame);
1079
1080        self.start_frame();
1081
1082        root_view.draw_dispatch_stack(self);
1083
1084        let window = &mut *self.window;
1085        // restore the old values of current and previous frame,
1086        // putting the new frame into spare_frame.
1087        mem::swap(&mut window.current_frame, &mut window.previous_frame);
1088        mem::swap(&mut spare_frame, &mut window.previous_frame);
1089        self.window.root_view = Some(root_view);
1090
1091        spare_frame.key_dispatch_stack
1092    }
1093
1094    /// Rotate the current frame and the previous frame, then clear the current frame.
1095    /// We repopulate all state in the current frame during each paint.
1096    fn start_frame(&mut self) {
1097        self.text_system().start_frame();
1098
1099        let window = &mut *self.window;
1100        mem::swap(&mut window.previous_frame, &mut window.current_frame);
1101        let frame = &mut window.current_frame;
1102        frame.element_states.clear();
1103        frame.key_matchers.clear();
1104        frame.mouse_listeners.values_mut().for_each(Vec::clear);
1105        frame.focus_listeners.clear();
1106        frame.key_dispatch_stack.clear();
1107        frame.focus_parents_by_child.clear();
1108        frame.freeze_key_dispatch_stack = false;
1109    }
1110
1111    /// Dispatch a mouse or keyboard event on the window.
1112    pub fn dispatch_event(&mut self, event: InputEvent) -> bool {
1113        // Handlers may set this to false by calling `stop_propagation`
1114        self.app.propagate_event = true;
1115        self.window.default_prevented = false;
1116
1117        let event = match event {
1118            // Track the mouse position with our own state, since accessing the platform
1119            // API for the mouse position can only occur on the main thread.
1120            InputEvent::MouseMove(mouse_move) => {
1121                self.window.mouse_position = mouse_move.position;
1122                InputEvent::MouseMove(mouse_move)
1123            }
1124            // Translate dragging and dropping of external files from the operating system
1125            // to internal drag and drop events.
1126            InputEvent::FileDrop(file_drop) => match file_drop {
1127                FileDropEvent::Entered { position, files } => {
1128                    self.window.mouse_position = position;
1129                    if self.active_drag.is_none() {
1130                        self.active_drag = Some(AnyDrag {
1131                            view: self.build_view(|_| files).into(),
1132                            cursor_offset: position,
1133                        });
1134                    }
1135                    InputEvent::MouseDown(MouseDownEvent {
1136                        position,
1137                        button: MouseButton::Left,
1138                        click_count: 1,
1139                        modifiers: Modifiers::default(),
1140                    })
1141                }
1142                FileDropEvent::Pending { position } => {
1143                    self.window.mouse_position = position;
1144                    InputEvent::MouseMove(MouseMoveEvent {
1145                        position,
1146                        pressed_button: Some(MouseButton::Left),
1147                        modifiers: Modifiers::default(),
1148                    })
1149                }
1150                FileDropEvent::Submit { position } => {
1151                    self.window.mouse_position = position;
1152                    InputEvent::MouseUp(MouseUpEvent {
1153                        button: MouseButton::Left,
1154                        position,
1155                        modifiers: Modifiers::default(),
1156                        click_count: 1,
1157                    })
1158                }
1159                FileDropEvent::Exited => InputEvent::MouseUp(MouseUpEvent {
1160                    button: MouseButton::Left,
1161                    position: Point::default(),
1162                    modifiers: Modifiers::default(),
1163                    click_count: 1,
1164                }),
1165            },
1166            _ => event,
1167        };
1168
1169        if let Some(any_mouse_event) = event.mouse_event() {
1170            if let Some(mut handlers) = self
1171                .window
1172                .current_frame
1173                .mouse_listeners
1174                .remove(&any_mouse_event.type_id())
1175            {
1176                // Because handlers may add other handlers, we sort every time.
1177                handlers.sort_by(|(a, _), (b, _)| a.cmp(b));
1178
1179                // Capture phase, events bubble from back to front. Handlers for this phase are used for
1180                // special purposes, such as detecting events outside of a given Bounds.
1181                for (_, handler) in &mut handlers {
1182                    handler(any_mouse_event, DispatchPhase::Capture, self);
1183                    if !self.app.propagate_event {
1184                        break;
1185                    }
1186                }
1187
1188                // Bubble phase, where most normal handlers do their work.
1189                if self.app.propagate_event {
1190                    for (_, handler) in handlers.iter_mut().rev() {
1191                        handler(any_mouse_event, DispatchPhase::Bubble, self);
1192                        if !self.app.propagate_event {
1193                            break;
1194                        }
1195                    }
1196                }
1197
1198                if self.app.propagate_event
1199                    && any_mouse_event.downcast_ref::<MouseUpEvent>().is_some()
1200                {
1201                    self.active_drag = None;
1202                }
1203
1204                // Just in case any handlers added new handlers, which is weird, but possible.
1205                handlers.extend(
1206                    self.window
1207                        .current_frame
1208                        .mouse_listeners
1209                        .get_mut(&any_mouse_event.type_id())
1210                        .into_iter()
1211                        .flat_map(|handlers| handlers.drain(..)),
1212                );
1213                self.window
1214                    .current_frame
1215                    .mouse_listeners
1216                    .insert(any_mouse_event.type_id(), handlers);
1217            }
1218        } else if let Some(any_key_event) = event.keyboard_event() {
1219            let key_dispatch_stack = mem::take(&mut self.window.current_frame.key_dispatch_stack);
1220            let key_event_type = any_key_event.type_id();
1221            let mut context_stack = SmallVec::<[&DispatchContext; 16]>::new();
1222
1223            for (ix, frame) in key_dispatch_stack.iter().enumerate() {
1224                match frame {
1225                    KeyDispatchStackFrame::Listener {
1226                        event_type,
1227                        listener,
1228                    } => {
1229                        if key_event_type == *event_type {
1230                            if let Some(action) = listener(
1231                                any_key_event,
1232                                &context_stack,
1233                                DispatchPhase::Capture,
1234                                self,
1235                            ) {
1236                                self.dispatch_action_internal(action, &key_dispatch_stack[..ix]);
1237                            }
1238                            if !self.app.propagate_event {
1239                                break;
1240                            }
1241                        }
1242                    }
1243                    KeyDispatchStackFrame::Context(context) => {
1244                        context_stack.push(&context);
1245                    }
1246                }
1247            }
1248
1249            if self.app.propagate_event {
1250                for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
1251                    match frame {
1252                        KeyDispatchStackFrame::Listener {
1253                            event_type,
1254                            listener,
1255                        } => {
1256                            if key_event_type == *event_type {
1257                                if let Some(action) = listener(
1258                                    any_key_event,
1259                                    &context_stack,
1260                                    DispatchPhase::Bubble,
1261                                    self,
1262                                ) {
1263                                    self.dispatch_action_internal(
1264                                        action,
1265                                        &key_dispatch_stack[..ix],
1266                                    );
1267                                }
1268
1269                                if !self.app.propagate_event {
1270                                    break;
1271                                }
1272                            }
1273                        }
1274                        KeyDispatchStackFrame::Context(_) => {
1275                            context_stack.pop();
1276                        }
1277                    }
1278                }
1279            }
1280
1281            drop(context_stack);
1282            self.window.current_frame.key_dispatch_stack = key_dispatch_stack;
1283        }
1284
1285        !self.app.propagate_event
1286    }
1287
1288    /// Attempt to map a keystroke to an action based on the keymap.
1289    pub fn match_keystroke(
1290        &mut self,
1291        element_id: &GlobalElementId,
1292        keystroke: &Keystroke,
1293        context_stack: &[&DispatchContext],
1294    ) -> KeyMatch {
1295        let key_match = self
1296            .window
1297            .current_frame
1298            .key_matchers
1299            .get_mut(element_id)
1300            .unwrap()
1301            .match_keystroke(keystroke, context_stack);
1302
1303        if key_match.is_some() {
1304            for matcher in self.window.current_frame.key_matchers.values_mut() {
1305                matcher.clear_pending();
1306            }
1307        }
1308
1309        key_match
1310    }
1311
1312    /// Register the given handler to be invoked whenever the global of the given type
1313    /// is updated.
1314    pub fn observe_global<G: 'static>(
1315        &mut self,
1316        f: impl Fn(&mut WindowContext<'_>) + 'static,
1317    ) -> Subscription {
1318        let window_handle = self.window.handle;
1319        self.global_observers.insert(
1320            TypeId::of::<G>(),
1321            Box::new(move |cx| window_handle.update(cx, |_, cx| f(cx)).is_ok()),
1322        )
1323    }
1324
1325    pub fn activate_window(&self) {
1326        self.window.platform_window.activate();
1327    }
1328
1329    pub fn prompt(
1330        &self,
1331        level: PromptLevel,
1332        msg: &str,
1333        answers: &[&str],
1334    ) -> oneshot::Receiver<usize> {
1335        self.window.platform_window.prompt(level, msg, answers)
1336    }
1337
1338    pub fn available_actions(&self) -> impl Iterator<Item = Box<dyn Action>> + '_ {
1339        let key_dispatch_stack = &self.window.previous_frame.key_dispatch_stack;
1340        key_dispatch_stack.iter().filter_map(|frame| {
1341            match frame {
1342                // todo!factor out a KeyDispatchStackFrame::Action
1343                KeyDispatchStackFrame::Listener {
1344                    event_type,
1345                    listener: _,
1346                } => {
1347                    match build_action_from_type(event_type) {
1348                        Ok(action) => Some(action),
1349                        Err(err) => {
1350                            dbg!(err);
1351                            None
1352                        } // we'll hit his if TypeId == KeyDown
1353                    }
1354                }
1355                KeyDispatchStackFrame::Context(_) => None,
1356            }
1357        })
1358    }
1359
1360    pub(crate) fn dispatch_action_internal(
1361        &mut self,
1362        action: Box<dyn Action>,
1363        dispatch_stack: &[KeyDispatchStackFrame],
1364    ) {
1365        let action_type = action.as_any().type_id();
1366
1367        if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
1368            for listener in &global_listeners {
1369                listener(action.as_ref(), DispatchPhase::Capture, self);
1370                if !self.app.propagate_event {
1371                    break;
1372                }
1373            }
1374            global_listeners.extend(
1375                self.global_action_listeners
1376                    .remove(&action_type)
1377                    .unwrap_or_default(),
1378            );
1379            self.global_action_listeners
1380                .insert(action_type, global_listeners);
1381        }
1382
1383        if self.app.propagate_event {
1384            for stack_frame in dispatch_stack {
1385                if let KeyDispatchStackFrame::Listener {
1386                    event_type,
1387                    listener,
1388                } = stack_frame
1389                {
1390                    if action_type == *event_type {
1391                        listener(action.as_any(), &[], DispatchPhase::Capture, self);
1392                        if !self.app.propagate_event {
1393                            break;
1394                        }
1395                    }
1396                }
1397            }
1398        }
1399
1400        if self.app.propagate_event {
1401            for stack_frame in dispatch_stack.iter().rev() {
1402                if let KeyDispatchStackFrame::Listener {
1403                    event_type,
1404                    listener,
1405                } = stack_frame
1406                {
1407                    if action_type == *event_type {
1408                        self.app.propagate_event = false;
1409                        listener(action.as_any(), &[], DispatchPhase::Bubble, self);
1410                        if !self.app.propagate_event {
1411                            break;
1412                        }
1413                    }
1414                }
1415            }
1416        }
1417
1418        if self.app.propagate_event {
1419            if let Some(mut global_listeners) =
1420                self.app.global_action_listeners.remove(&action_type)
1421            {
1422                for listener in global_listeners.iter().rev() {
1423                    self.app.propagate_event = false;
1424                    listener(action.as_ref(), DispatchPhase::Bubble, self);
1425                    if !self.app.propagate_event {
1426                        break;
1427                    }
1428                }
1429                global_listeners.extend(
1430                    self.global_action_listeners
1431                        .remove(&action_type)
1432                        .unwrap_or_default(),
1433                );
1434                self.global_action_listeners
1435                    .insert(action_type, global_listeners);
1436            }
1437        }
1438    }
1439}
1440
1441impl Context for WindowContext<'_> {
1442    type Result<T> = T;
1443
1444    fn build_model<T>(
1445        &mut self,
1446        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1447    ) -> Model<T>
1448    where
1449        T: 'static,
1450    {
1451        let slot = self.app.entities.reserve();
1452        let model = build_model(&mut ModelContext::new(&mut *self.app, slot.downgrade()));
1453        self.entities.insert(slot, model)
1454    }
1455
1456    fn update_model<T: 'static, R>(
1457        &mut self,
1458        model: &Model<T>,
1459        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1460    ) -> R {
1461        let mut entity = self.entities.lease(model);
1462        let result = update(
1463            &mut *entity,
1464            &mut ModelContext::new(&mut *self.app, model.downgrade()),
1465        );
1466        self.entities.end_lease(entity);
1467        result
1468    }
1469
1470    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
1471    where
1472        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1473    {
1474        if window == self.window.handle {
1475            let root_view = self.window.root_view.clone().unwrap();
1476            Ok(update(root_view, self))
1477        } else {
1478            window.update(self.app, update)
1479        }
1480    }
1481
1482    fn read_model<T, R>(
1483        &self,
1484        handle: &Model<T>,
1485        read: impl FnOnce(&T, &AppContext) -> R,
1486    ) -> Self::Result<R>
1487    where
1488        T: 'static,
1489    {
1490        let entity = self.entities.read(handle);
1491        read(&*entity, &*self.app)
1492    }
1493}
1494
1495impl VisualContext for WindowContext<'_> {
1496    fn build_view<V>(
1497        &mut self,
1498        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1499    ) -> Self::Result<View<V>>
1500    where
1501        V: 'static + Render,
1502    {
1503        let slot = self.app.entities.reserve();
1504        let view = View {
1505            model: slot.clone(),
1506        };
1507        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1508        let entity = build_view_state(&mut cx);
1509        cx.entities.insert(slot, entity);
1510
1511        cx.new_view_observers
1512            .clone()
1513            .retain(&TypeId::of::<V>(), |observer| {
1514                let any_view = AnyView::from(view.clone());
1515                (observer)(any_view, self);
1516                true
1517            });
1518
1519        view
1520    }
1521
1522    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1523    fn update_view<T: 'static, R>(
1524        &mut self,
1525        view: &View<T>,
1526        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1527    ) -> Self::Result<R> {
1528        let mut lease = self.app.entities.lease(&view.model);
1529        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1530        let result = update(&mut *lease, &mut cx);
1531        cx.app.entities.end_lease(lease);
1532        result
1533    }
1534
1535    fn replace_root_view<V>(
1536        &mut self,
1537        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1538    ) -> Self::Result<View<V>>
1539    where
1540        V: Render,
1541    {
1542        let slot = self.app.entities.reserve();
1543        let view = View {
1544            model: slot.clone(),
1545        };
1546        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1547        let entity = build_view(&mut cx);
1548        self.entities.insert(slot, entity);
1549        self.window.root_view = Some(view.clone().into());
1550        view
1551    }
1552}
1553
1554impl<'a> std::ops::Deref for WindowContext<'a> {
1555    type Target = AppContext;
1556
1557    fn deref(&self) -> &Self::Target {
1558        &self.app
1559    }
1560}
1561
1562impl<'a> std::ops::DerefMut for WindowContext<'a> {
1563    fn deref_mut(&mut self) -> &mut Self::Target {
1564        &mut self.app
1565    }
1566}
1567
1568impl<'a> Borrow<AppContext> for WindowContext<'a> {
1569    fn borrow(&self) -> &AppContext {
1570        &self.app
1571    }
1572}
1573
1574impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1575    fn borrow_mut(&mut self) -> &mut AppContext {
1576        &mut self.app
1577    }
1578}
1579
1580pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1581    fn app_mut(&mut self) -> &mut AppContext {
1582        self.borrow_mut()
1583    }
1584
1585    fn window(&self) -> &Window {
1586        self.borrow()
1587    }
1588
1589    fn window_mut(&mut self) -> &mut Window {
1590        self.borrow_mut()
1591    }
1592
1593    /// Pushes the given element id onto the global stack and invokes the given closure
1594    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1595    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1596    /// used to associate state with identified elements across separate frames.
1597    fn with_element_id<R>(
1598        &mut self,
1599        id: impl Into<ElementId>,
1600        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1601    ) -> R {
1602        let keymap = self.app_mut().keymap.clone();
1603        let window = self.window_mut();
1604        window.element_id_stack.push(id.into());
1605        let global_id = window.element_id_stack.clone();
1606
1607        if window.current_frame.key_matchers.get(&global_id).is_none() {
1608            window.current_frame.key_matchers.insert(
1609                global_id.clone(),
1610                window
1611                    .previous_frame
1612                    .key_matchers
1613                    .remove(&global_id)
1614                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1615            );
1616        }
1617
1618        let result = f(global_id, self);
1619        let window: &mut Window = self.borrow_mut();
1620        window.element_id_stack.pop();
1621        result
1622    }
1623
1624    /// Invoke the given function with the given content mask after intersecting it
1625    /// with the current mask.
1626    fn with_content_mask<R>(
1627        &mut self,
1628        mask: ContentMask<Pixels>,
1629        f: impl FnOnce(&mut Self) -> R,
1630    ) -> R {
1631        let mask = mask.intersect(&self.content_mask());
1632        self.window_mut()
1633            .current_frame
1634            .content_mask_stack
1635            .push(mask);
1636        let result = f(self);
1637        self.window_mut().current_frame.content_mask_stack.pop();
1638        result
1639    }
1640
1641    /// Update the global element offset based on the given offset. This is used to implement
1642    /// scrolling and position drag handles.
1643    fn with_element_offset<R>(
1644        &mut self,
1645        offset: Option<Point<Pixels>>,
1646        f: impl FnOnce(&mut Self) -> R,
1647    ) -> R {
1648        let Some(offset) = offset else {
1649            return f(self);
1650        };
1651
1652        let offset = self.element_offset() + offset;
1653        self.window_mut()
1654            .current_frame
1655            .element_offset_stack
1656            .push(offset);
1657        let result = f(self);
1658        self.window_mut().current_frame.element_offset_stack.pop();
1659        result
1660    }
1661
1662    /// Obtain the current element offset.
1663    fn element_offset(&self) -> Point<Pixels> {
1664        self.window()
1665            .current_frame
1666            .element_offset_stack
1667            .last()
1668            .copied()
1669            .unwrap_or_default()
1670    }
1671
1672    /// Update or intialize state for an element with the given id that lives across multiple
1673    /// frames. If an element with this id existed in the previous frame, its state will be passed
1674    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1675    /// when drawing the next frame.
1676    fn with_element_state<S, R>(
1677        &mut self,
1678        id: ElementId,
1679        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1680    ) -> R
1681    where
1682        S: 'static,
1683    {
1684        self.with_element_id(id, |global_id, cx| {
1685            if let Some(any) = cx
1686                .window_mut()
1687                .current_frame
1688                .element_states
1689                .remove(&global_id)
1690                .or_else(|| {
1691                    cx.window_mut()
1692                        .previous_frame
1693                        .element_states
1694                        .remove(&global_id)
1695                })
1696            {
1697                // Using the extra inner option to avoid needing to reallocate a new box.
1698                let mut state_box = any
1699                    .downcast::<Option<S>>()
1700                    .expect("invalid element state type for id");
1701                let state = state_box
1702                    .take()
1703                    .expect("element state is already on the stack");
1704                let (result, state) = f(Some(state), cx);
1705                state_box.replace(state);
1706                cx.window_mut()
1707                    .current_frame
1708                    .element_states
1709                    .insert(global_id, state_box);
1710                result
1711            } else {
1712                let (result, state) = f(None, cx);
1713                cx.window_mut()
1714                    .current_frame
1715                    .element_states
1716                    .insert(global_id, Box::new(Some(state)));
1717                result
1718            }
1719        })
1720    }
1721
1722    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1723    /// id is `None`, no state will be retrieved or stored.
1724    fn with_optional_element_state<S, R>(
1725        &mut self,
1726        element_id: Option<ElementId>,
1727        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1728    ) -> R
1729    where
1730        S: 'static,
1731    {
1732        if let Some(element_id) = element_id {
1733            self.with_element_state(element_id, f)
1734        } else {
1735            f(None, self).0
1736        }
1737    }
1738
1739    /// Obtain the current content mask.
1740    fn content_mask(&self) -> ContentMask<Pixels> {
1741        self.window()
1742            .current_frame
1743            .content_mask_stack
1744            .last()
1745            .cloned()
1746            .unwrap_or_else(|| ContentMask {
1747                bounds: Bounds {
1748                    origin: Point::default(),
1749                    size: self.window().content_size,
1750                },
1751            })
1752    }
1753
1754    /// The size of an em for the base font of the application. Adjusting this value allows the
1755    /// UI to scale, just like zooming a web page.
1756    fn rem_size(&self) -> Pixels {
1757        self.window().rem_size
1758    }
1759}
1760
1761impl Borrow<Window> for WindowContext<'_> {
1762    fn borrow(&self) -> &Window {
1763        &self.window
1764    }
1765}
1766
1767impl BorrowMut<Window> for WindowContext<'_> {
1768    fn borrow_mut(&mut self) -> &mut Window {
1769        &mut self.window
1770    }
1771}
1772
1773impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1774
1775pub struct ViewContext<'a, V> {
1776    window_cx: WindowContext<'a>,
1777    view: &'a View<V>,
1778}
1779
1780impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1781    fn borrow(&self) -> &AppContext {
1782        &*self.window_cx.app
1783    }
1784}
1785
1786impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1787    fn borrow_mut(&mut self) -> &mut AppContext {
1788        &mut *self.window_cx.app
1789    }
1790}
1791
1792impl<V> Borrow<Window> for ViewContext<'_, V> {
1793    fn borrow(&self) -> &Window {
1794        &*self.window_cx.window
1795    }
1796}
1797
1798impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1799    fn borrow_mut(&mut self) -> &mut Window {
1800        &mut *self.window_cx.window
1801    }
1802}
1803
1804impl<'a, V: 'static> ViewContext<'a, V> {
1805    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1806        Self {
1807            window_cx: WindowContext::new(app, window),
1808            view,
1809        }
1810    }
1811
1812    // todo!("change this to return a reference");
1813    pub fn view(&self) -> View<V> {
1814        self.view.clone()
1815    }
1816
1817    pub fn model(&self) -> Model<V> {
1818        self.view.model.clone()
1819    }
1820
1821    /// Access the underlying window context.
1822    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1823        &mut self.window_cx
1824    }
1825
1826    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1827        self.window.current_frame.z_index_stack.push(z_index);
1828        let result = f(self);
1829        self.window.current_frame.z_index_stack.pop();
1830        result
1831    }
1832
1833    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1834    where
1835        V: 'static,
1836    {
1837        let view = self.view();
1838        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1839    }
1840
1841    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1842    /// that are currently on the stack to be returned to the app.
1843    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1844        let view = self.view().downgrade();
1845        self.window_cx.defer(move |cx| {
1846            view.update(cx, f).ok();
1847        });
1848    }
1849
1850    pub fn observe<V2, E>(
1851        &mut self,
1852        entity: &E,
1853        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1854    ) -> Subscription
1855    where
1856        V2: 'static,
1857        V: 'static,
1858        E: Entity<V2>,
1859    {
1860        let view = self.view().downgrade();
1861        let entity_id = entity.entity_id();
1862        let entity = entity.downgrade();
1863        let window_handle = self.window.handle;
1864        self.app.observers.insert(
1865            entity_id,
1866            Box::new(move |cx| {
1867                window_handle
1868                    .update(cx, |_, cx| {
1869                        if let Some(handle) = E::upgrade_from(&entity) {
1870                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1871                                .is_ok()
1872                        } else {
1873                            false
1874                        }
1875                    })
1876                    .unwrap_or(false)
1877            }),
1878        )
1879    }
1880
1881    pub fn subscribe<V2, E, Evt>(
1882        &mut self,
1883        entity: &E,
1884        mut on_event: impl FnMut(&mut V, E, &Evt, &mut ViewContext<'_, V>) + 'static,
1885    ) -> Subscription
1886    where
1887        V2: EventEmitter<Evt>,
1888        E: Entity<V2>,
1889        Evt: 'static,
1890    {
1891        let view = self.view().downgrade();
1892        let entity_id = entity.entity_id();
1893        let handle = entity.downgrade();
1894        let window_handle = self.window.handle;
1895        self.app.event_listeners.insert(
1896            entity_id,
1897            (
1898                TypeId::of::<Evt>(),
1899                Box::new(move |event, cx| {
1900                    window_handle
1901                        .update(cx, |_, cx| {
1902                            if let Some(handle) = E::upgrade_from(&handle) {
1903                                let event = event.downcast_ref().expect("invalid event type");
1904                                view.update(cx, |this, cx| on_event(this, handle, event, cx))
1905                                    .is_ok()
1906                            } else {
1907                                false
1908                            }
1909                        })
1910                        .unwrap_or(false)
1911                }),
1912            ),
1913        )
1914    }
1915
1916    pub fn on_release(
1917        &mut self,
1918        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1919    ) -> Subscription {
1920        let window_handle = self.window.handle;
1921        self.app.release_listeners.insert(
1922            self.view.model.entity_id,
1923            Box::new(move |this, cx| {
1924                let this = this.downcast_mut().expect("invalid entity type");
1925                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1926            }),
1927        )
1928    }
1929
1930    pub fn observe_release<V2, E>(
1931        &mut self,
1932        entity: &E,
1933        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1934    ) -> Subscription
1935    where
1936        V: 'static,
1937        V2: 'static,
1938        E: Entity<V2>,
1939    {
1940        let view = self.view().downgrade();
1941        let entity_id = entity.entity_id();
1942        let window_handle = self.window.handle;
1943        self.app.release_listeners.insert(
1944            entity_id,
1945            Box::new(move |entity, cx| {
1946                let entity = entity.downcast_mut().expect("invalid entity type");
1947                let _ = window_handle.update(cx, |_, cx| {
1948                    view.update(cx, |this, cx| on_release(this, entity, cx))
1949                });
1950            }),
1951        )
1952    }
1953
1954    pub fn notify(&mut self) {
1955        self.window_cx.notify();
1956        self.window_cx.app.push_effect(Effect::Notify {
1957            emitter: self.view.model.entity_id,
1958        });
1959    }
1960
1961    pub fn observe_window_bounds(
1962        &mut self,
1963        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1964    ) -> Subscription {
1965        let view = self.view.downgrade();
1966        self.window.bounds_observers.insert(
1967            (),
1968            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1969        )
1970    }
1971
1972    pub fn observe_window_activation(
1973        &mut self,
1974        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1975    ) -> Subscription {
1976        let view = self.view.downgrade();
1977        self.window.activation_observers.insert(
1978            (),
1979            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1980        )
1981    }
1982
1983    /// Register a listener to be called when the given focus handle receives focus.
1984    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
1985    /// is dropped.
1986    pub fn on_focus(
1987        &mut self,
1988        handle: &FocusHandle,
1989        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1990    ) -> Subscription {
1991        let view = self.view.downgrade();
1992        let focus_id = handle.id;
1993        self.window.focus_listeners.insert(
1994            (),
1995            Box::new(move |event, cx| {
1996                view.update(cx, |view, cx| {
1997                    if event.focused.as_ref().map(|focused| focused.id) == Some(focus_id) {
1998                        listener(view, cx)
1999                    }
2000                })
2001                .is_ok()
2002            }),
2003        )
2004    }
2005
2006    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
2007    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2008    /// is dropped.
2009    pub fn on_focus_in(
2010        &mut self,
2011        handle: &FocusHandle,
2012        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2013    ) -> Subscription {
2014        let view = self.view.downgrade();
2015        let focus_id = handle.id;
2016        self.window.focus_listeners.insert(
2017            (),
2018            Box::new(move |event, cx| {
2019                view.update(cx, |view, cx| {
2020                    if event
2021                        .focused
2022                        .as_ref()
2023                        .map_or(false, |focused| focus_id.contains(focused.id, cx))
2024                    {
2025                        listener(view, cx)
2026                    }
2027                })
2028                .is_ok()
2029            }),
2030        )
2031    }
2032
2033    /// Register a listener to be called when the given focus handle loses focus.
2034    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2035    /// is dropped.
2036    pub fn on_blur(
2037        &mut self,
2038        handle: &FocusHandle,
2039        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2040    ) -> Subscription {
2041        let view = self.view.downgrade();
2042        let focus_id = handle.id;
2043        self.window.focus_listeners.insert(
2044            (),
2045            Box::new(move |event, cx| {
2046                view.update(cx, |view, cx| {
2047                    if event.blurred.as_ref().map(|blurred| blurred.id) == Some(focus_id) {
2048                        listener(view, cx)
2049                    }
2050                })
2051                .is_ok()
2052            }),
2053        )
2054    }
2055
2056    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
2057    /// Unlike [on_focus_changed], returns a subscription and persists until the subscription
2058    /// is dropped.
2059    pub fn on_focus_out(
2060        &mut self,
2061        handle: &FocusHandle,
2062        mut listener: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
2063    ) -> Subscription {
2064        let view = self.view.downgrade();
2065        let focus_id = handle.id;
2066        self.window.focus_listeners.insert(
2067            (),
2068            Box::new(move |event, cx| {
2069                view.update(cx, |view, cx| {
2070                    if event
2071                        .blurred
2072                        .as_ref()
2073                        .map_or(false, |blurred| focus_id.contains(blurred.id, cx))
2074                    {
2075                        listener(view, cx)
2076                    }
2077                })
2078                .is_ok()
2079            }),
2080        )
2081    }
2082
2083    /// Register a focus listener for the current frame only. It will be cleared
2084    /// on the next frame render. You should use this method only from within elements,
2085    /// and we may want to enforce that better via a different context type.
2086    // todo!() Move this to `FrameContext` to emphasize its individuality?
2087    pub fn on_focus_changed(
2088        &mut self,
2089        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
2090    ) {
2091        let handle = self.view().downgrade();
2092        self.window
2093            .current_frame
2094            .focus_listeners
2095            .push(Box::new(move |event, cx| {
2096                handle
2097                    .update(cx, |view, cx| listener(view, event, cx))
2098                    .log_err();
2099            }));
2100    }
2101
2102    pub fn with_key_listeners<R>(
2103        &mut self,
2104        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
2105        f: impl FnOnce(&mut Self) -> R,
2106    ) -> R {
2107        let old_stack_len = self.window.current_frame.key_dispatch_stack.len();
2108        if !self.window.current_frame.freeze_key_dispatch_stack {
2109            for (event_type, listener) in key_listeners {
2110                let handle = self.view().downgrade();
2111                let listener = Box::new(
2112                    move |event: &dyn Any,
2113                          context_stack: &[&DispatchContext],
2114                          phase: DispatchPhase,
2115                          cx: &mut WindowContext<'_>| {
2116                        handle
2117                            .update(cx, |view, cx| {
2118                                listener(view, event, context_stack, phase, cx)
2119                            })
2120                            .log_err()
2121                            .flatten()
2122                    },
2123                );
2124                self.window.current_frame.key_dispatch_stack.push(
2125                    KeyDispatchStackFrame::Listener {
2126                        event_type,
2127                        listener,
2128                    },
2129                );
2130            }
2131        }
2132
2133        let result = f(self);
2134
2135        if !self.window.current_frame.freeze_key_dispatch_stack {
2136            self.window
2137                .current_frame
2138                .key_dispatch_stack
2139                .truncate(old_stack_len);
2140        }
2141
2142        result
2143    }
2144
2145    pub fn with_key_dispatch_context<R>(
2146        &mut self,
2147        context: DispatchContext,
2148        f: impl FnOnce(&mut Self) -> R,
2149    ) -> R {
2150        if context.is_empty() {
2151            return f(self);
2152        }
2153
2154        if !self.window.current_frame.freeze_key_dispatch_stack {
2155            self.window
2156                .current_frame
2157                .key_dispatch_stack
2158                .push(KeyDispatchStackFrame::Context(context));
2159        }
2160
2161        let result = f(self);
2162
2163        if !self.window.previous_frame.freeze_key_dispatch_stack {
2164            self.window.previous_frame.key_dispatch_stack.pop();
2165        }
2166
2167        result
2168    }
2169
2170    pub fn with_focus<R>(
2171        &mut self,
2172        focus_handle: FocusHandle,
2173        f: impl FnOnce(&mut Self) -> R,
2174    ) -> R {
2175        if let Some(parent_focus_id) = self.window.current_frame.focus_stack.last().copied() {
2176            self.window
2177                .current_frame
2178                .focus_parents_by_child
2179                .insert(focus_handle.id, parent_focus_id);
2180        }
2181        self.window.current_frame.focus_stack.push(focus_handle.id);
2182
2183        if Some(focus_handle.id) == self.window.focus {
2184            self.window.current_frame.freeze_key_dispatch_stack = true;
2185        }
2186
2187        let result = f(self);
2188
2189        self.window.current_frame.focus_stack.pop();
2190        result
2191    }
2192
2193    pub fn spawn<Fut, R>(
2194        &mut self,
2195        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
2196    ) -> Task<R>
2197    where
2198        R: 'static,
2199        Fut: Future<Output = R> + 'static,
2200    {
2201        let view = self.view().downgrade();
2202        self.window_cx.spawn(|cx| f(view, cx))
2203    }
2204
2205    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
2206    where
2207        G: 'static,
2208    {
2209        let mut global = self.app.lease_global::<G>();
2210        let result = f(&mut global, self);
2211        self.app.end_global_lease(global);
2212        result
2213    }
2214
2215    pub fn observe_global<G: 'static>(
2216        &mut self,
2217        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2218    ) -> Subscription {
2219        let window_handle = self.window.handle;
2220        let view = self.view().downgrade();
2221        self.global_observers.insert(
2222            TypeId::of::<G>(),
2223            Box::new(move |cx| {
2224                window_handle
2225                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2226                    .unwrap_or(false)
2227            }),
2228        )
2229    }
2230
2231    pub fn on_mouse_event<Event: 'static>(
2232        &mut self,
2233        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2234    ) {
2235        let handle = self.view();
2236        self.window_cx.on_mouse_event(move |event, phase, cx| {
2237            handle.update(cx, |view, cx| {
2238                handler(view, event, phase, cx);
2239            })
2240        });
2241    }
2242
2243    /// Set an input handler, such as [ElementInputHandler], which interfaces with the
2244    /// platform to receive textual input with proper integration with concerns such
2245    /// as IME interactions.
2246    pub fn handle_input(
2247        &mut self,
2248        focus_handle: &FocusHandle,
2249        input_handler: impl PlatformInputHandler,
2250    ) {
2251        if focus_handle.is_focused(self) {
2252            self.window
2253                .platform_window
2254                .set_input_handler(Box::new(input_handler));
2255        }
2256    }
2257}
2258
2259impl<V> ViewContext<'_, V> {
2260    pub fn emit<Evt>(&mut self, event: Evt)
2261    where
2262        Evt: 'static,
2263        V: EventEmitter<Evt>,
2264    {
2265        let emitter = self.view.model.entity_id;
2266        self.app.push_effect(Effect::Emit {
2267            emitter,
2268            event_type: TypeId::of::<Evt>(),
2269            event: Box::new(event),
2270        });
2271    }
2272}
2273
2274impl<V> Context for ViewContext<'_, V> {
2275    type Result<U> = U;
2276
2277    fn build_model<T: 'static>(
2278        &mut self,
2279        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2280    ) -> Model<T> {
2281        self.window_cx.build_model(build_model)
2282    }
2283
2284    fn update_model<T: 'static, R>(
2285        &mut self,
2286        model: &Model<T>,
2287        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2288    ) -> R {
2289        self.window_cx.update_model(model, update)
2290    }
2291
2292    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2293    where
2294        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2295    {
2296        self.window_cx.update_window(window, update)
2297    }
2298
2299    fn read_model<T, R>(
2300        &self,
2301        handle: &Model<T>,
2302        read: impl FnOnce(&T, &AppContext) -> R,
2303    ) -> Self::Result<R>
2304    where
2305        T: 'static,
2306    {
2307        self.window_cx.read_model(handle, read)
2308    }
2309}
2310
2311impl<V: 'static> VisualContext for ViewContext<'_, V> {
2312    fn build_view<W: Render + 'static>(
2313        &mut self,
2314        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2315    ) -> Self::Result<View<W>> {
2316        self.window_cx.build_view(build_view_state)
2317    }
2318
2319    fn update_view<V2: 'static, R>(
2320        &mut self,
2321        view: &View<V2>,
2322        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2323    ) -> Self::Result<R> {
2324        self.window_cx.update_view(view, update)
2325    }
2326
2327    fn replace_root_view<W>(
2328        &mut self,
2329        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2330    ) -> Self::Result<View<W>>
2331    where
2332        W: Render,
2333    {
2334        self.window_cx.replace_root_view(build_view)
2335    }
2336}
2337
2338impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2339    type Target = WindowContext<'a>;
2340
2341    fn deref(&self) -> &Self::Target {
2342        &self.window_cx
2343    }
2344}
2345
2346impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2347    fn deref_mut(&mut self) -> &mut Self::Target {
2348        &mut self.window_cx
2349    }
2350}
2351
2352// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2353slotmap::new_key_type! { pub struct WindowId; }
2354
2355impl WindowId {
2356    pub fn as_u64(&self) -> u64 {
2357        self.0.as_ffi()
2358    }
2359}
2360
2361#[derive(Deref, DerefMut)]
2362pub struct WindowHandle<V> {
2363    #[deref]
2364    #[deref_mut]
2365    pub(crate) any_handle: AnyWindowHandle,
2366    state_type: PhantomData<V>,
2367}
2368
2369impl<V: 'static + Render> WindowHandle<V> {
2370    pub fn new(id: WindowId) -> Self {
2371        WindowHandle {
2372            any_handle: AnyWindowHandle {
2373                id,
2374                state_type: TypeId::of::<V>(),
2375            },
2376            state_type: PhantomData,
2377        }
2378    }
2379
2380    pub fn update<C, R>(
2381        self,
2382        cx: &mut C,
2383        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2384    ) -> Result<R>
2385    where
2386        C: Context,
2387    {
2388        cx.update_window(self.any_handle, |root_view, cx| {
2389            let view = root_view
2390                .downcast::<V>()
2391                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2392            Ok(cx.update_view(&view, update))
2393        })?
2394    }
2395}
2396
2397impl<V> Copy for WindowHandle<V> {}
2398
2399impl<V> Clone for WindowHandle<V> {
2400    fn clone(&self) -> Self {
2401        WindowHandle {
2402            any_handle: self.any_handle,
2403            state_type: PhantomData,
2404        }
2405    }
2406}
2407
2408impl<V> PartialEq for WindowHandle<V> {
2409    fn eq(&self, other: &Self) -> bool {
2410        self.any_handle == other.any_handle
2411    }
2412}
2413
2414impl<V> Eq for WindowHandle<V> {}
2415
2416impl<V> Hash for WindowHandle<V> {
2417    fn hash<H: Hasher>(&self, state: &mut H) {
2418        self.any_handle.hash(state);
2419    }
2420}
2421
2422impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2423    fn into(self) -> AnyWindowHandle {
2424        self.any_handle
2425    }
2426}
2427
2428#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2429pub struct AnyWindowHandle {
2430    pub(crate) id: WindowId,
2431    state_type: TypeId,
2432}
2433
2434impl AnyWindowHandle {
2435    pub fn window_id(&self) -> WindowId {
2436        self.id
2437    }
2438
2439    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2440        if TypeId::of::<T>() == self.state_type {
2441            Some(WindowHandle {
2442                any_handle: *self,
2443                state_type: PhantomData,
2444            })
2445        } else {
2446            None
2447        }
2448    }
2449
2450    pub fn update<C, R>(
2451        self,
2452        cx: &mut C,
2453        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2454    ) -> Result<R>
2455    where
2456        C: Context,
2457    {
2458        cx.update_window(self, update)
2459    }
2460}
2461
2462#[cfg(any(test, feature = "test-support"))]
2463impl From<SmallVec<[u32; 16]>> for StackingOrder {
2464    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2465        StackingOrder(small_vec)
2466    }
2467}
2468
2469#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2470pub enum ElementId {
2471    View(EntityId),
2472    Number(usize),
2473    Name(SharedString),
2474    FocusHandle(FocusId),
2475}
2476
2477impl From<EntityId> for ElementId {
2478    fn from(id: EntityId) -> Self {
2479        ElementId::View(id)
2480    }
2481}
2482
2483impl From<usize> for ElementId {
2484    fn from(id: usize) -> Self {
2485        ElementId::Number(id)
2486    }
2487}
2488
2489impl From<i32> for ElementId {
2490    fn from(id: i32) -> Self {
2491        Self::Number(id as usize)
2492    }
2493}
2494
2495impl From<SharedString> for ElementId {
2496    fn from(name: SharedString) -> Self {
2497        ElementId::Name(name)
2498    }
2499}
2500
2501impl From<&'static str> for ElementId {
2502    fn from(name: &'static str) -> Self {
2503        ElementId::Name(name.into())
2504    }
2505}
2506
2507impl<'a> From<&'a FocusHandle> for ElementId {
2508    fn from(handle: &'a FocusHandle) -> Self {
2509        ElementId::FocusHandle(handle.id)
2510    }
2511}