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