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