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