window.rs

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