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
1396impl VisualContext for WindowContext<'_> {
1397    fn build_view<V>(
1398        &mut self,
1399        build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1400    ) -> Self::Result<View<V>>
1401    where
1402        V: 'static,
1403    {
1404        let slot = self.app.entities.reserve();
1405        let view = View {
1406            model: slot.clone(),
1407        };
1408        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1409        let entity = build_view_state(&mut cx);
1410        self.entities.insert(slot, entity);
1411        view
1412    }
1413
1414    /// Update the given view. Prefer calling `View::update` instead, which calls this method.
1415    fn update_view<T: 'static, R>(
1416        &mut self,
1417        view: &View<T>,
1418        update: impl FnOnce(&mut T, &mut ViewContext<'_, T>) -> R,
1419    ) -> Self::Result<R> {
1420        let mut lease = self.app.entities.lease(&view.model);
1421        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1422        let result = update(&mut *lease, &mut cx);
1423        cx.app.entities.end_lease(lease);
1424        result
1425    }
1426
1427    fn replace_root_view<V>(
1428        &mut self,
1429        build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
1430    ) -> Self::Result<View<V>>
1431    where
1432        V: Render,
1433    {
1434        let slot = self.app.entities.reserve();
1435        let view = View {
1436            model: slot.clone(),
1437        };
1438        let mut cx = ViewContext::new(&mut *self.app, &mut *self.window, &view);
1439        let entity = build_view(&mut cx);
1440        self.entities.insert(slot, entity);
1441        self.window.root_view = Some(view.clone().into());
1442        view
1443    }
1444}
1445
1446impl<'a> std::ops::Deref for WindowContext<'a> {
1447    type Target = AppContext;
1448
1449    fn deref(&self) -> &Self::Target {
1450        &self.app
1451    }
1452}
1453
1454impl<'a> std::ops::DerefMut for WindowContext<'a> {
1455    fn deref_mut(&mut self) -> &mut Self::Target {
1456        &mut self.app
1457    }
1458}
1459
1460impl<'a> Borrow<AppContext> for WindowContext<'a> {
1461    fn borrow(&self) -> &AppContext {
1462        &self.app
1463    }
1464}
1465
1466impl<'a> BorrowMut<AppContext> for WindowContext<'a> {
1467    fn borrow_mut(&mut self) -> &mut AppContext {
1468        &mut self.app
1469    }
1470}
1471
1472pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
1473    fn app_mut(&mut self) -> &mut AppContext {
1474        self.borrow_mut()
1475    }
1476
1477    fn window(&self) -> &Window {
1478        self.borrow()
1479    }
1480
1481    fn window_mut(&mut self) -> &mut Window {
1482        self.borrow_mut()
1483    }
1484
1485    /// Pushes the given element id onto the global stack and invokes the given closure
1486    /// with a `GlobalElementId`, which disambiguates the given id in the context of its ancestor
1487    /// ids. Because elements are discarded and recreated on each frame, the `GlobalElementId` is
1488    /// used to associate state with identified elements across separate frames.
1489    fn with_element_id<R>(
1490        &mut self,
1491        id: impl Into<ElementId>,
1492        f: impl FnOnce(GlobalElementId, &mut Self) -> R,
1493    ) -> R {
1494        let keymap = self.app_mut().keymap.clone();
1495        let window = self.window_mut();
1496        window.element_id_stack.push(id.into());
1497        let global_id = window.element_id_stack.clone();
1498
1499        if window.current_frame.key_matchers.get(&global_id).is_none() {
1500            window.current_frame.key_matchers.insert(
1501                global_id.clone(),
1502                window
1503                    .previous_frame
1504                    .key_matchers
1505                    .remove(&global_id)
1506                    .unwrap_or_else(|| KeyMatcher::new(keymap)),
1507            );
1508        }
1509
1510        let result = f(global_id, self);
1511        let window: &mut Window = self.borrow_mut();
1512        window.element_id_stack.pop();
1513        result
1514    }
1515
1516    /// Invoke the given function with the given content mask after intersecting it
1517    /// with the current mask.
1518    fn with_content_mask<R>(
1519        &mut self,
1520        mask: ContentMask<Pixels>,
1521        f: impl FnOnce(&mut Self) -> R,
1522    ) -> R {
1523        let mask = mask.intersect(&self.content_mask());
1524        self.window_mut()
1525            .current_frame
1526            .content_mask_stack
1527            .push(mask);
1528        let result = f(self);
1529        self.window_mut().current_frame.content_mask_stack.pop();
1530        result
1531    }
1532
1533    /// Update the global element offset based on the given offset. This is used to implement
1534    /// scrolling and position drag handles.
1535    fn with_element_offset<R>(
1536        &mut self,
1537        offset: Option<Point<Pixels>>,
1538        f: impl FnOnce(&mut Self) -> R,
1539    ) -> R {
1540        let Some(offset) = offset else {
1541            return f(self);
1542        };
1543
1544        let offset = self.element_offset() + offset;
1545        self.window_mut()
1546            .current_frame
1547            .element_offset_stack
1548            .push(offset);
1549        let result = f(self);
1550        self.window_mut().current_frame.element_offset_stack.pop();
1551        result
1552    }
1553
1554    /// Obtain the current element offset.
1555    fn element_offset(&self) -> Point<Pixels> {
1556        self.window()
1557            .current_frame
1558            .element_offset_stack
1559            .last()
1560            .copied()
1561            .unwrap_or_default()
1562    }
1563
1564    /// Update or intialize state for an element with the given id that lives across multiple
1565    /// frames. If an element with this id existed in the previous frame, its state will be passed
1566    /// to the given closure. The state returned by the closure will be stored so it can be referenced
1567    /// when drawing the next frame.
1568    fn with_element_state<S, R>(
1569        &mut self,
1570        id: ElementId,
1571        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1572    ) -> R
1573    where
1574        S: 'static,
1575    {
1576        self.with_element_id(id, |global_id, cx| {
1577            if let Some(any) = cx
1578                .window_mut()
1579                .current_frame
1580                .element_states
1581                .remove(&global_id)
1582                .or_else(|| {
1583                    cx.window_mut()
1584                        .previous_frame
1585                        .element_states
1586                        .remove(&global_id)
1587                })
1588            {
1589                // Using the extra inner option to avoid needing to reallocate a new box.
1590                let mut state_box = any
1591                    .downcast::<Option<S>>()
1592                    .expect("invalid element state type for id");
1593                let state = state_box
1594                    .take()
1595                    .expect("element state is already on the stack");
1596                let (result, state) = f(Some(state), cx);
1597                state_box.replace(state);
1598                cx.window_mut()
1599                    .current_frame
1600                    .element_states
1601                    .insert(global_id, state_box);
1602                result
1603            } else {
1604                let (result, state) = f(None, cx);
1605                cx.window_mut()
1606                    .current_frame
1607                    .element_states
1608                    .insert(global_id, Box::new(Some(state)));
1609                result
1610            }
1611        })
1612    }
1613
1614    /// Like `with_element_state`, but for situations where the element_id is optional. If the
1615    /// id is `None`, no state will be retrieved or stored.
1616    fn with_optional_element_state<S, R>(
1617        &mut self,
1618        element_id: Option<ElementId>,
1619        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
1620    ) -> R
1621    where
1622        S: 'static,
1623    {
1624        if let Some(element_id) = element_id {
1625            self.with_element_state(element_id, f)
1626        } else {
1627            f(None, self).0
1628        }
1629    }
1630
1631    /// Obtain the current content mask.
1632    fn content_mask(&self) -> ContentMask<Pixels> {
1633        self.window()
1634            .current_frame
1635            .content_mask_stack
1636            .last()
1637            .cloned()
1638            .unwrap_or_else(|| ContentMask {
1639                bounds: Bounds {
1640                    origin: Point::default(),
1641                    size: self.window().content_size,
1642                },
1643            })
1644    }
1645
1646    /// The size of an em for the base font of the application. Adjusting this value allows the
1647    /// UI to scale, just like zooming a web page.
1648    fn rem_size(&self) -> Pixels {
1649        self.window().rem_size
1650    }
1651}
1652
1653impl Borrow<Window> for WindowContext<'_> {
1654    fn borrow(&self) -> &Window {
1655        &self.window
1656    }
1657}
1658
1659impl BorrowMut<Window> for WindowContext<'_> {
1660    fn borrow_mut(&mut self) -> &mut Window {
1661        &mut self.window
1662    }
1663}
1664
1665impl<T> BorrowWindow for T where T: BorrowMut<AppContext> + BorrowMut<Window> {}
1666
1667pub struct ViewContext<'a, V> {
1668    window_cx: WindowContext<'a>,
1669    view: &'a View<V>,
1670}
1671
1672impl<V> Borrow<AppContext> for ViewContext<'_, V> {
1673    fn borrow(&self) -> &AppContext {
1674        &*self.window_cx.app
1675    }
1676}
1677
1678impl<V> BorrowMut<AppContext> for ViewContext<'_, V> {
1679    fn borrow_mut(&mut self) -> &mut AppContext {
1680        &mut *self.window_cx.app
1681    }
1682}
1683
1684impl<V> Borrow<Window> for ViewContext<'_, V> {
1685    fn borrow(&self) -> &Window {
1686        &*self.window_cx.window
1687    }
1688}
1689
1690impl<V> BorrowMut<Window> for ViewContext<'_, V> {
1691    fn borrow_mut(&mut self) -> &mut Window {
1692        &mut *self.window_cx.window
1693    }
1694}
1695
1696impl<'a, V: 'static> ViewContext<'a, V> {
1697    pub(crate) fn new(app: &'a mut AppContext, window: &'a mut Window, view: &'a View<V>) -> Self {
1698        Self {
1699            window_cx: WindowContext::new(app, window),
1700            view,
1701        }
1702    }
1703
1704    // todo!("change this to return a reference");
1705    pub fn view(&self) -> View<V> {
1706        self.view.clone()
1707    }
1708
1709    pub fn model(&self) -> Model<V> {
1710        self.view.model.clone()
1711    }
1712
1713    /// Access the underlying window context.
1714    pub fn window_context(&mut self) -> &mut WindowContext<'a> {
1715        &mut self.window_cx
1716    }
1717
1718    pub fn with_z_index<R>(&mut self, z_index: u32, f: impl FnOnce(&mut Self) -> R) -> R {
1719        self.window.current_frame.z_index_stack.push(z_index);
1720        let result = f(self);
1721        self.window.current_frame.z_index_stack.pop();
1722        result
1723    }
1724
1725    pub fn on_next_frame(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static)
1726    where
1727        V: 'static,
1728    {
1729        let view = self.view();
1730        self.window_cx.on_next_frame(move |cx| view.update(cx, f));
1731    }
1732
1733    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1734    /// that are currently on the stack to be returned to the app.
1735    pub fn defer(&mut self, f: impl FnOnce(&mut V, &mut ViewContext<V>) + 'static) {
1736        let view = self.view().downgrade();
1737        self.window_cx.defer(move |cx| {
1738            view.update(cx, f).ok();
1739        });
1740    }
1741
1742    pub fn observe<V2, E>(
1743        &mut self,
1744        entity: &E,
1745        mut on_notify: impl FnMut(&mut V, E, &mut ViewContext<'_, V>) + 'static,
1746    ) -> Subscription
1747    where
1748        V2: 'static,
1749        V: 'static,
1750        E: Entity<V2>,
1751    {
1752        let view = self.view().downgrade();
1753        let entity_id = entity.entity_id();
1754        let entity = entity.downgrade();
1755        let window_handle = self.window.handle;
1756        self.app.observers.insert(
1757            entity_id,
1758            Box::new(move |cx| {
1759                window_handle
1760                    .update(cx, |_, cx| {
1761                        if let Some(handle) = E::upgrade_from(&entity) {
1762                            view.update(cx, |this, cx| on_notify(this, handle, cx))
1763                                .is_ok()
1764                        } else {
1765                            false
1766                        }
1767                    })
1768                    .unwrap_or(false)
1769            }),
1770        )
1771    }
1772
1773    pub fn subscribe<V2, E>(
1774        &mut self,
1775        entity: &E,
1776        mut on_event: impl FnMut(&mut V, E, &V2::Event, &mut ViewContext<'_, V>) + 'static,
1777    ) -> Subscription
1778    where
1779        V2: EventEmitter,
1780        E: Entity<V2>,
1781    {
1782        let view = self.view().downgrade();
1783        let entity_id = entity.entity_id();
1784        let handle = entity.downgrade();
1785        let window_handle = self.window.handle;
1786        self.app.event_listeners.insert(
1787            entity_id,
1788            Box::new(move |event, cx| {
1789                window_handle
1790                    .update(cx, |_, cx| {
1791                        if let Some(handle) = E::upgrade_from(&handle) {
1792                            let event = event.downcast_ref().expect("invalid event type");
1793                            view.update(cx, |this, cx| on_event(this, handle, event, cx))
1794                                .is_ok()
1795                        } else {
1796                            false
1797                        }
1798                    })
1799                    .unwrap_or(false)
1800            }),
1801        )
1802    }
1803
1804    pub fn on_release(
1805        &mut self,
1806        on_release: impl FnOnce(&mut V, &mut WindowContext) + 'static,
1807    ) -> Subscription {
1808        let window_handle = self.window.handle;
1809        self.app.release_listeners.insert(
1810            self.view.model.entity_id,
1811            Box::new(move |this, cx| {
1812                let this = this.downcast_mut().expect("invalid entity type");
1813                let _ = window_handle.update(cx, |_, cx| on_release(this, cx));
1814            }),
1815        )
1816    }
1817
1818    pub fn observe_release<V2, E>(
1819        &mut self,
1820        entity: &E,
1821        mut on_release: impl FnMut(&mut V, &mut V2, &mut ViewContext<'_, V>) + 'static,
1822    ) -> Subscription
1823    where
1824        V: 'static,
1825        V2: 'static,
1826        E: Entity<V2>,
1827    {
1828        let view = self.view().downgrade();
1829        let entity_id = entity.entity_id();
1830        let window_handle = self.window.handle;
1831        self.app.release_listeners.insert(
1832            entity_id,
1833            Box::new(move |entity, cx| {
1834                let entity = entity.downcast_mut().expect("invalid entity type");
1835                let _ = window_handle.update(cx, |_, cx| {
1836                    view.update(cx, |this, cx| on_release(this, entity, cx))
1837                });
1838            }),
1839        )
1840    }
1841
1842    pub fn notify(&mut self) {
1843        self.window_cx.notify();
1844        self.window_cx.app.push_effect(Effect::Notify {
1845            emitter: self.view.model.entity_id,
1846        });
1847    }
1848
1849    pub fn observe_window_bounds(
1850        &mut self,
1851        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1852    ) -> Subscription {
1853        let view = self.view.downgrade();
1854        self.window.bounds_observers.insert(
1855            (),
1856            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1857        )
1858    }
1859
1860    pub fn observe_window_activation(
1861        &mut self,
1862        mut callback: impl FnMut(&mut V, &mut ViewContext<V>) + 'static,
1863    ) -> Subscription {
1864        let view = self.view.downgrade();
1865        self.window.activation_observers.insert(
1866            (),
1867            Box::new(move |cx| view.update(cx, |view, cx| callback(view, cx)).is_ok()),
1868        )
1869    }
1870
1871    pub fn on_focus_changed(
1872        &mut self,
1873        listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
1874    ) {
1875        let handle = self.view().downgrade();
1876        self.window
1877            .current_frame
1878            .focus_listeners
1879            .push(Box::new(move |event, cx| {
1880                handle
1881                    .update(cx, |view, cx| listener(view, event, cx))
1882                    .log_err();
1883            }));
1884    }
1885
1886    pub fn with_key_listeners<R>(
1887        &mut self,
1888        key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
1889        f: impl FnOnce(&mut Self) -> R,
1890    ) -> R {
1891        let old_stack_len = self.window.current_frame.key_dispatch_stack.len();
1892        if !self.window.current_frame.freeze_key_dispatch_stack {
1893            for (event_type, listener) in key_listeners {
1894                let handle = self.view().downgrade();
1895                let listener = Box::new(
1896                    move |event: &dyn Any,
1897                          context_stack: &[&DispatchContext],
1898                          phase: DispatchPhase,
1899                          cx: &mut WindowContext<'_>| {
1900                        handle
1901                            .update(cx, |view, cx| {
1902                                listener(view, event, context_stack, phase, cx)
1903                            })
1904                            .log_err()
1905                            .flatten()
1906                    },
1907                );
1908                self.window.current_frame.key_dispatch_stack.push(
1909                    KeyDispatchStackFrame::Listener {
1910                        event_type,
1911                        listener,
1912                    },
1913                );
1914            }
1915        }
1916
1917        let result = f(self);
1918
1919        if !self.window.current_frame.freeze_key_dispatch_stack {
1920            self.window
1921                .current_frame
1922                .key_dispatch_stack
1923                .truncate(old_stack_len);
1924        }
1925
1926        result
1927    }
1928
1929    pub fn with_key_dispatch_context<R>(
1930        &mut self,
1931        context: DispatchContext,
1932        f: impl FnOnce(&mut Self) -> R,
1933    ) -> R {
1934        if context.is_empty() {
1935            return f(self);
1936        }
1937
1938        if !self.window.current_frame.freeze_key_dispatch_stack {
1939            self.window
1940                .current_frame
1941                .key_dispatch_stack
1942                .push(KeyDispatchStackFrame::Context(context));
1943        }
1944
1945        let result = f(self);
1946
1947        if !self.window.previous_frame.freeze_key_dispatch_stack {
1948            self.window.previous_frame.key_dispatch_stack.pop();
1949        }
1950
1951        result
1952    }
1953
1954    pub fn with_focus<R>(
1955        &mut self,
1956        focus_handle: FocusHandle,
1957        f: impl FnOnce(&mut Self) -> R,
1958    ) -> R {
1959        if let Some(parent_focus_id) = self.window.current_frame.focus_stack.last().copied() {
1960            self.window
1961                .current_frame
1962                .focus_parents_by_child
1963                .insert(focus_handle.id, parent_focus_id);
1964        }
1965        self.window.current_frame.focus_stack.push(focus_handle.id);
1966
1967        if Some(focus_handle.id) == self.window.focus {
1968            self.window.current_frame.freeze_key_dispatch_stack = true;
1969        }
1970
1971        let result = f(self);
1972
1973        self.window.current_frame.focus_stack.pop();
1974        result
1975    }
1976
1977    pub fn spawn<Fut, R>(
1978        &mut self,
1979        f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
1980    ) -> Task<R>
1981    where
1982        R: 'static,
1983        Fut: Future<Output = R> + 'static,
1984    {
1985        let view = self.view().downgrade();
1986        self.window_cx.spawn(|cx| f(view, cx))
1987    }
1988
1989    pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
1990    where
1991        G: 'static,
1992    {
1993        let mut global = self.app.lease_global::<G>();
1994        let result = f(&mut global, self);
1995        self.app.end_global_lease(global);
1996        result
1997    }
1998
1999    pub fn observe_global<G: 'static>(
2000        &mut self,
2001        f: impl Fn(&mut V, &mut ViewContext<'_, V>) + 'static,
2002    ) -> Subscription {
2003        let window_handle = self.window.handle;
2004        let view = self.view().downgrade();
2005        self.global_observers.insert(
2006            TypeId::of::<G>(),
2007            Box::new(move |cx| {
2008                window_handle
2009                    .update(cx, |_, cx| view.update(cx, |view, cx| f(view, cx)).is_ok())
2010                    .unwrap_or(false)
2011            }),
2012        )
2013    }
2014
2015    pub fn on_mouse_event<Event: 'static>(
2016        &mut self,
2017        handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
2018    ) {
2019        let handle = self.view();
2020        self.window_cx.on_mouse_event(move |event, phase, cx| {
2021            handle.update(cx, |view, cx| {
2022                handler(view, event, phase, cx);
2023            })
2024        });
2025    }
2026}
2027
2028impl<V> ViewContext<'_, V>
2029where
2030    V: InputHandler + 'static,
2031{
2032    pub fn handle_text_input(&mut self) {
2033        self.window.requested_input_handler = Some(Box::new(WindowInputHandler {
2034            cx: self.app.this.clone(),
2035            window: self.window_handle(),
2036            handler: self.view().downgrade(),
2037        }));
2038    }
2039}
2040
2041impl<V> ViewContext<'_, V>
2042where
2043    V: EventEmitter,
2044    V::Event: 'static,
2045{
2046    pub fn emit(&mut self, event: V::Event) {
2047        let emitter = self.view.model.entity_id;
2048        self.app.push_effect(Effect::Emit {
2049            emitter,
2050            event: Box::new(event),
2051        });
2052    }
2053}
2054
2055impl<V> Context for ViewContext<'_, V> {
2056    type Result<U> = U;
2057
2058    fn build_model<T: 'static>(
2059        &mut self,
2060        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
2061    ) -> Model<T> {
2062        self.window_cx.build_model(build_model)
2063    }
2064
2065    fn update_model<T: 'static, R>(
2066        &mut self,
2067        model: &Model<T>,
2068        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
2069    ) -> R {
2070        self.window_cx.update_model(model, update)
2071    }
2072
2073    fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
2074    where
2075        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
2076    {
2077        self.window_cx.update_window(window, update)
2078    }
2079}
2080
2081impl<V: 'static> VisualContext for ViewContext<'_, V> {
2082    fn build_view<W: 'static>(
2083        &mut self,
2084        build_view_state: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2085    ) -> Self::Result<View<W>> {
2086        self.window_cx.build_view(build_view_state)
2087    }
2088
2089    fn update_view<V2: 'static, R>(
2090        &mut self,
2091        view: &View<V2>,
2092        update: impl FnOnce(&mut V2, &mut ViewContext<'_, V2>) -> R,
2093    ) -> Self::Result<R> {
2094        self.window_cx.update_view(view, update)
2095    }
2096
2097    fn replace_root_view<W>(
2098        &mut self,
2099        build_view: impl FnOnce(&mut ViewContext<'_, W>) -> W,
2100    ) -> Self::Result<View<W>>
2101    where
2102        W: Render,
2103    {
2104        self.window_cx.replace_root_view(build_view)
2105    }
2106}
2107
2108impl<'a, V> std::ops::Deref for ViewContext<'a, V> {
2109    type Target = WindowContext<'a>;
2110
2111    fn deref(&self) -> &Self::Target {
2112        &self.window_cx
2113    }
2114}
2115
2116impl<'a, V> std::ops::DerefMut for ViewContext<'a, V> {
2117    fn deref_mut(&mut self) -> &mut Self::Target {
2118        &mut self.window_cx
2119    }
2120}
2121
2122// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
2123slotmap::new_key_type! { pub struct WindowId; }
2124
2125impl WindowId {
2126    pub fn as_u64(&self) -> u64 {
2127        self.0.as_ffi()
2128    }
2129}
2130
2131#[derive(Deref, DerefMut)]
2132pub struct WindowHandle<V> {
2133    #[deref]
2134    #[deref_mut]
2135    pub(crate) any_handle: AnyWindowHandle,
2136    state_type: PhantomData<V>,
2137}
2138
2139impl<V: 'static + Render> WindowHandle<V> {
2140    pub fn new(id: WindowId) -> Self {
2141        WindowHandle {
2142            any_handle: AnyWindowHandle {
2143                id,
2144                state_type: TypeId::of::<V>(),
2145            },
2146            state_type: PhantomData,
2147        }
2148    }
2149
2150    pub fn update<C, R>(
2151        self,
2152        cx: &mut C,
2153        update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
2154    ) -> Result<R>
2155    where
2156        C: Context,
2157    {
2158        cx.update_window(self.any_handle, |root_view, cx| {
2159            let view = root_view
2160                .downcast::<V>()
2161                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
2162            Ok(cx.update_view(&view, update))
2163        })?
2164    }
2165}
2166
2167impl<V> Copy for WindowHandle<V> {}
2168
2169impl<V> Clone for WindowHandle<V> {
2170    fn clone(&self) -> Self {
2171        WindowHandle {
2172            any_handle: self.any_handle,
2173            state_type: PhantomData,
2174        }
2175    }
2176}
2177
2178impl<V> PartialEq for WindowHandle<V> {
2179    fn eq(&self, other: &Self) -> bool {
2180        self.any_handle == other.any_handle
2181    }
2182}
2183
2184impl<V> Eq for WindowHandle<V> {}
2185
2186impl<V> Hash for WindowHandle<V> {
2187    fn hash<H: Hasher>(&self, state: &mut H) {
2188        self.any_handle.hash(state);
2189    }
2190}
2191
2192impl<V: 'static> Into<AnyWindowHandle> for WindowHandle<V> {
2193    fn into(self) -> AnyWindowHandle {
2194        self.any_handle
2195    }
2196}
2197
2198#[derive(Copy, Clone, PartialEq, Eq, Hash)]
2199pub struct AnyWindowHandle {
2200    pub(crate) id: WindowId,
2201    state_type: TypeId,
2202}
2203
2204impl AnyWindowHandle {
2205    pub fn window_id(&self) -> WindowId {
2206        self.id
2207    }
2208
2209    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
2210        if TypeId::of::<T>() == self.state_type {
2211            Some(WindowHandle {
2212                any_handle: *self,
2213                state_type: PhantomData,
2214            })
2215        } else {
2216            None
2217        }
2218    }
2219
2220    pub fn update<C, R>(
2221        self,
2222        cx: &mut C,
2223        update: impl FnOnce(AnyView, &mut WindowContext<'_>) -> R,
2224    ) -> Result<R>
2225    where
2226        C: Context,
2227    {
2228        cx.update_window(self, update)
2229    }
2230}
2231
2232#[cfg(any(test, feature = "test-support"))]
2233impl From<SmallVec<[u32; 16]>> for StackingOrder {
2234    fn from(small_vec: SmallVec<[u32; 16]>) -> Self {
2235        StackingOrder(small_vec)
2236    }
2237}
2238
2239#[derive(Clone, Debug, Eq, PartialEq, Hash)]
2240pub enum ElementId {
2241    View(EntityId),
2242    Number(usize),
2243    Name(SharedString),
2244    FocusHandle(FocusId),
2245}
2246
2247impl From<EntityId> for ElementId {
2248    fn from(id: EntityId) -> Self {
2249        ElementId::View(id)
2250    }
2251}
2252
2253impl From<usize> for ElementId {
2254    fn from(id: usize) -> Self {
2255        ElementId::Number(id)
2256    }
2257}
2258
2259impl From<i32> for ElementId {
2260    fn from(id: i32) -> Self {
2261        Self::Number(id as usize)
2262    }
2263}
2264
2265impl From<SharedString> for ElementId {
2266    fn from(name: SharedString) -> Self {
2267        ElementId::Name(name)
2268    }
2269}
2270
2271impl From<&'static str> for ElementId {
2272    fn from(name: &'static str) -> Self {
2273        ElementId::Name(name.into())
2274    }
2275}
2276
2277impl<'a> From<&'a FocusHandle> for ElementId {
2278    fn from(handle: &'a FocusHandle) -> Self {
2279        ElementId::FocusHandle(handle.id)
2280    }
2281}