window.rs

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