window.rs

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