window.rs

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