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