window.rs

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