window.rs

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