window.rs

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