window.rs

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