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