window.rs

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