presenter.rs

   1use crate::{
   2    app::{AppContext, MutableAppContext, WindowInvalidation},
   3    elements::Element,
   4    font_cache::FontCache,
   5    geometry::rect::RectF,
   6    json::{self, ToJson},
   7    keymap::Keystroke,
   8    platform::{CursorStyle, Event},
   9    scene::{
  10        CursorRegion, MouseClick, MouseDown, MouseDownOut, MouseDrag, MouseEvent, MouseHover,
  11        MouseMove, MouseScrollWheel, MouseUp, MouseUpOut,
  12    },
  13    text_layout::TextLayoutCache,
  14    Action, AnyModelHandle, AnyViewHandle, AnyWeakModelHandle, AnyWeakViewHandle, Appearance,
  15    AssetCache, ElementBox, Entity, FontSystem, ModelHandle, MouseButton, MouseMovedEvent,
  16    MouseRegion, MouseRegionId, ParentId, ReadModel, ReadView, RenderContext, RenderParams, Scene,
  17    UpgradeModelHandle, UpgradeViewHandle, View, ViewHandle, WeakModelHandle, WeakViewHandle,
  18};
  19use collections::{HashMap, HashSet};
  20use pathfinder_geometry::vector::{vec2f, Vector2F};
  21use serde_json::json;
  22use smallvec::SmallVec;
  23use std::{
  24    marker::PhantomData,
  25    ops::{Deref, DerefMut, Range},
  26    sync::Arc,
  27};
  28
  29pub struct Presenter {
  30    window_id: usize,
  31    pub(crate) rendered_views: HashMap<usize, ElementBox>,
  32    cursor_regions: Vec<CursorRegion>,
  33    mouse_regions: Vec<(MouseRegion, usize)>,
  34    font_cache: Arc<FontCache>,
  35    text_layout_cache: TextLayoutCache,
  36    asset_cache: Arc<AssetCache>,
  37    last_mouse_moved_event: Option<Event>,
  38    hovered_region_ids: HashSet<MouseRegionId>,
  39    clicked_region_ids: HashSet<MouseRegionId>,
  40    clicked_button: Option<MouseButton>,
  41    mouse_position: Vector2F,
  42    titlebar_height: f32,
  43    appearance: Appearance,
  44}
  45
  46impl Presenter {
  47    pub fn new(
  48        window_id: usize,
  49        titlebar_height: f32,
  50        appearance: Appearance,
  51        font_cache: Arc<FontCache>,
  52        text_layout_cache: TextLayoutCache,
  53        asset_cache: Arc<AssetCache>,
  54        cx: &mut MutableAppContext,
  55    ) -> Self {
  56        Self {
  57            window_id,
  58            rendered_views: cx.render_views(window_id, titlebar_height, appearance),
  59            cursor_regions: Default::default(),
  60            mouse_regions: Default::default(),
  61            font_cache,
  62            text_layout_cache,
  63            asset_cache,
  64            last_mouse_moved_event: None,
  65            hovered_region_ids: Default::default(),
  66            clicked_region_ids: Default::default(),
  67            clicked_button: None,
  68            mouse_position: vec2f(0., 0.),
  69            titlebar_height,
  70            appearance,
  71        }
  72    }
  73
  74    pub fn invalidate(
  75        &mut self,
  76        invalidation: &mut WindowInvalidation,
  77        appearance: Appearance,
  78        cx: &mut MutableAppContext,
  79    ) {
  80        cx.start_frame();
  81        self.appearance = appearance;
  82        for view_id in &invalidation.removed {
  83            invalidation.updated.remove(view_id);
  84            self.rendered_views.remove(view_id);
  85        }
  86        for view_id in &invalidation.updated {
  87            self.rendered_views.insert(
  88                *view_id,
  89                cx.render_view(RenderParams {
  90                    window_id: self.window_id,
  91                    view_id: *view_id,
  92                    titlebar_height: self.titlebar_height,
  93                    hovered_region_ids: self.hovered_region_ids.clone(),
  94                    clicked_region_ids: self
  95                        .clicked_button
  96                        .map(|button| (self.clicked_region_ids.clone(), button)),
  97                    refreshing: false,
  98                    appearance,
  99                })
 100                .unwrap(),
 101            );
 102        }
 103    }
 104
 105    pub fn refresh(
 106        &mut self,
 107        invalidation: &mut WindowInvalidation,
 108        appearance: Appearance,
 109        cx: &mut MutableAppContext,
 110    ) {
 111        self.invalidate(invalidation, appearance, cx);
 112        for (view_id, view) in &mut self.rendered_views {
 113            if !invalidation.updated.contains(view_id) {
 114                *view = cx
 115                    .render_view(RenderParams {
 116                        window_id: self.window_id,
 117                        view_id: *view_id,
 118                        titlebar_height: self.titlebar_height,
 119                        hovered_region_ids: self.hovered_region_ids.clone(),
 120                        clicked_region_ids: self
 121                            .clicked_button
 122                            .map(|button| (self.clicked_region_ids.clone(), button)),
 123                        refreshing: true,
 124                        appearance,
 125                    })
 126                    .unwrap();
 127            }
 128        }
 129    }
 130
 131    pub fn build_scene(
 132        &mut self,
 133        window_size: Vector2F,
 134        scale_factor: f32,
 135        refreshing: bool,
 136        cx: &mut MutableAppContext,
 137    ) -> Scene {
 138        let mut scene = Scene::new(scale_factor);
 139
 140        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
 141            self.layout(window_size, refreshing, cx);
 142            let mut paint_cx = self.build_paint_context(&mut scene, window_size, cx);
 143            paint_cx.paint(
 144                root_view_id,
 145                Vector2F::zero(),
 146                RectF::new(Vector2F::zero(), window_size),
 147            );
 148            self.text_layout_cache.finish_frame();
 149            self.cursor_regions = scene.cursor_regions();
 150            self.mouse_regions = scene.mouse_regions();
 151
 152            if cx.window_is_active(self.window_id) {
 153                if let Some(event) = self.last_mouse_moved_event.clone() {
 154                    self.dispatch_event(event, true, cx);
 155                }
 156            }
 157        } else {
 158            log::error!("could not find root_view_id for window {}", self.window_id);
 159        }
 160
 161        scene
 162    }
 163
 164    fn layout(&mut self, window_size: Vector2F, refreshing: bool, cx: &mut MutableAppContext) {
 165        if let Some(root_view_id) = cx.root_view_id(self.window_id) {
 166            self.build_layout_context(window_size, refreshing, cx)
 167                .layout(root_view_id, SizeConstraint::strict(window_size));
 168        }
 169    }
 170
 171    pub fn build_layout_context<'a>(
 172        &'a mut self,
 173        window_size: Vector2F,
 174        refreshing: bool,
 175        cx: &'a mut MutableAppContext,
 176    ) -> LayoutContext<'a> {
 177        LayoutContext {
 178            window_id: self.window_id,
 179            rendered_views: &mut self.rendered_views,
 180            font_cache: &self.font_cache,
 181            font_system: cx.platform().fonts(),
 182            text_layout_cache: &self.text_layout_cache,
 183            asset_cache: &self.asset_cache,
 184            view_stack: Vec::new(),
 185            refreshing,
 186            hovered_region_ids: self.hovered_region_ids.clone(),
 187            clicked_region_ids: self
 188                .clicked_button
 189                .map(|button| (self.clicked_region_ids.clone(), button)),
 190            titlebar_height: self.titlebar_height,
 191            appearance: self.appearance,
 192            window_size,
 193            app: cx,
 194        }
 195    }
 196
 197    pub fn build_paint_context<'a>(
 198        &'a mut self,
 199        scene: &'a mut Scene,
 200        window_size: Vector2F,
 201        cx: &'a mut MutableAppContext,
 202    ) -> PaintContext {
 203        PaintContext {
 204            scene,
 205            window_size,
 206            font_cache: &self.font_cache,
 207            text_layout_cache: &self.text_layout_cache,
 208            rendered_views: &mut self.rendered_views,
 209            view_stack: Vec::new(),
 210            app: cx,
 211        }
 212    }
 213
 214    pub fn rect_for_text_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<RectF> {
 215        cx.focused_view_id(self.window_id).and_then(|view_id| {
 216            let cx = MeasurementContext {
 217                app: cx,
 218                rendered_views: &self.rendered_views,
 219                window_id: self.window_id,
 220            };
 221            cx.rect_for_text_range(view_id, range_utf16)
 222        })
 223    }
 224
 225    pub fn dispatch_event(
 226        &mut self,
 227        event: Event,
 228        event_reused: bool,
 229        cx: &mut MutableAppContext,
 230    ) -> bool {
 231        let mut mouse_events = SmallVec::<[_; 2]>::new();
 232        let mut notified_views: HashSet<usize> = Default::default();
 233
 234        // 1. Handle platform event. Keyboard events get dispatched immediately, while mouse events
 235        //    get mapped into the mouse-specific MouseEvent type.
 236        //  -> These are usually small: [Mouse Down] or [Mouse up, Click] or [Mouse Moved, Mouse Dragged?]
 237        //  -> Also updates mouse-related state
 238        match &event {
 239            Event::KeyDown(e) => return cx.dispatch_key_down(self.window_id, e),
 240            Event::KeyUp(e) => return cx.dispatch_key_up(self.window_id, e),
 241            Event::ModifiersChanged(e) => return cx.dispatch_modifiers_changed(self.window_id, e),
 242            Event::MouseDown(e) => {
 243                // Click events are weird because they can be fired after a drag event.
 244                // MDN says that browsers handle this by starting from 'the most
 245                // specific ancestor element that contained both [positions]'
 246                // So we need to store the overlapping regions on mouse down.
 247
 248                // If there is already clicked_button stored, don't replace it.
 249                if self.clicked_button.is_none() {
 250                    self.clicked_region_ids = self
 251                        .mouse_regions
 252                        .iter()
 253                        .filter_map(|(region, _)| {
 254                            if region.bounds.contains_point(e.position) {
 255                                Some(region.id())
 256                            } else {
 257                                None
 258                            }
 259                        })
 260                        .collect();
 261
 262                    self.clicked_button = Some(e.button);
 263                }
 264
 265                mouse_events.push(MouseEvent::Down(MouseDown {
 266                    region: Default::default(),
 267                    platform_event: e.clone(),
 268                }));
 269                mouse_events.push(MouseEvent::DownOut(MouseDownOut {
 270                    region: Default::default(),
 271                    platform_event: e.clone(),
 272                }));
 273            }
 274            Event::MouseUp(e) => {
 275                // NOTE: The order of event pushes is important! MouseUp events MUST be fired
 276                // before click events, and so the MouseUp events need to be pushed before
 277                // MouseClick events.
 278                mouse_events.push(MouseEvent::Up(MouseUp {
 279                    region: Default::default(),
 280                    platform_event: e.clone(),
 281                }));
 282                mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 283                    region: Default::default(),
 284                    platform_event: e.clone(),
 285                }));
 286                mouse_events.push(MouseEvent::Click(MouseClick {
 287                    region: Default::default(),
 288                    platform_event: e.clone(),
 289                }));
 290            }
 291            Event::MouseMoved(
 292                e @ MouseMovedEvent {
 293                    position,
 294                    pressed_button,
 295                    ..
 296                },
 297            ) => {
 298                let mut style_to_assign = CursorStyle::Arrow;
 299                for region in self.cursor_regions.iter().rev() {
 300                    if region.bounds.contains_point(*position) {
 301                        style_to_assign = region.style;
 302                        break;
 303                    }
 304                }
 305                cx.platform().set_cursor_style(style_to_assign);
 306
 307                if !event_reused {
 308                    if pressed_button.is_some() {
 309                        mouse_events.push(MouseEvent::Drag(MouseDrag {
 310                            region: Default::default(),
 311                            prev_mouse_position: self.mouse_position,
 312                            platform_event: e.clone(),
 313                        }));
 314                    } else if let Some(clicked_button) = self.clicked_button {
 315                        // Mouse up event happened outside the current window. Simulate mouse up button event
 316                        let button_event = e.to_button_event(clicked_button);
 317                        mouse_events.push(MouseEvent::Up(MouseUp {
 318                            region: Default::default(),
 319                            platform_event: button_event.clone(),
 320                        }));
 321                        mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 322                            region: Default::default(),
 323                            platform_event: button_event.clone(),
 324                        }));
 325                        mouse_events.push(MouseEvent::Click(MouseClick {
 326                            region: Default::default(),
 327                            platform_event: button_event.clone(),
 328                        }));
 329                    }
 330
 331                    mouse_events.push(MouseEvent::Move(MouseMove {
 332                        region: Default::default(),
 333                        platform_event: e.clone(),
 334                    }));
 335                }
 336
 337                mouse_events.push(MouseEvent::Hover(MouseHover {
 338                    region: Default::default(),
 339                    platform_event: e.clone(),
 340                    started: false,
 341                }));
 342
 343                self.last_mouse_moved_event = Some(event.clone());
 344            }
 345            Event::ScrollWheel(e) => mouse_events.push(MouseEvent::ScrollWheel(MouseScrollWheel {
 346                region: Default::default(),
 347                platform_event: e.clone(),
 348            })),
 349        }
 350
 351        if let Some(position) = event.position() {
 352            self.mouse_position = position;
 353        }
 354
 355        // 2. Dispatch mouse events on regions
 356        let mut any_event_handled = false;
 357        for mut mouse_event in mouse_events {
 358            let mut valid_regions = Vec::new();
 359
 360            // GPUI elements are arranged by depth but sibling elements can register overlapping
 361            // mouse regions. As such, hover events are only fired on overlapping elements which
 362            // are at the same depth as the topmost element which overlaps with the mouse.
 363            match &mouse_event {
 364                MouseEvent::Hover(_) => {
 365                    let mut top_most_depth = None;
 366                    let mouse_position = self.mouse_position.clone();
 367                    for (region, depth) in self.mouse_regions.iter().rev() {
 368                        // Allow mouse regions to appear transparent to hovers
 369                        if !region.hoverable {
 370                            continue;
 371                        }
 372
 373                        let contains_mouse = region.bounds.contains_point(mouse_position);
 374
 375                        if contains_mouse && top_most_depth.is_none() {
 376                            top_most_depth = Some(depth);
 377                        }
 378
 379                        // This unwrap relies on short circuiting boolean expressions
 380                        // The right side of the && is only executed when contains_mouse
 381                        // is true, and we know above that when contains_mouse is true
 382                        // top_most_depth is set
 383                        if contains_mouse && depth == top_most_depth.unwrap() {
 384                            //Ensure that hover entrance events aren't sent twice
 385                            if self.hovered_region_ids.insert(region.id()) {
 386                                valid_regions.push(region.clone());
 387                                if region.notify_on_hover {
 388                                    notified_views.insert(region.id().view_id());
 389                                }
 390                            }
 391                        } else {
 392                            // Ensure that hover exit events aren't sent twice
 393                            if self.hovered_region_ids.remove(&region.id()) {
 394                                valid_regions.push(region.clone());
 395                                if region.notify_on_hover {
 396                                    notified_views.insert(region.id().view_id());
 397                                }
 398                            }
 399                        }
 400                    }
 401                }
 402                MouseEvent::Down(_) | MouseEvent::Up(_) => {
 403                    for (region, _) in self.mouse_regions.iter().rev() {
 404                        if region.bounds.contains_point(self.mouse_position) {
 405                            if region.notify_on_click {
 406                                notified_views.insert(region.id().view_id());
 407                            }
 408                            valid_regions.push(region.clone());
 409                        }
 410                    }
 411                }
 412                MouseEvent::Click(e) => {
 413                    // Only raise click events if the released button is the same as the one stored
 414                    if self
 415                        .clicked_button
 416                        .map(|clicked_button| clicked_button == e.button)
 417                        .unwrap_or(false)
 418                    {
 419                        // Clear clicked regions and clicked button
 420                        let clicked_region_ids =
 421                            std::mem::replace(&mut self.clicked_region_ids, Default::default());
 422                        self.clicked_button = None;
 423
 424                        // Find regions which still overlap with the mouse since the last MouseDown happened
 425                        for (mouse_region, _) in self.mouse_regions.iter().rev() {
 426                            if clicked_region_ids.contains(&mouse_region.id()) {
 427                                if mouse_region.bounds.contains_point(self.mouse_position) {
 428                                    valid_regions.push(mouse_region.clone());
 429                                }
 430                            }
 431                        }
 432                    }
 433                }
 434                MouseEvent::Drag(_) => {
 435                    for (mouse_region, _) in self.mouse_regions.iter().rev() {
 436                        if self.clicked_region_ids.contains(&mouse_region.id()) {
 437                            valid_regions.push(mouse_region.clone());
 438                        }
 439                    }
 440                }
 441
 442                MouseEvent::UpOut(_) | MouseEvent::DownOut(_) => {
 443                    for (mouse_region, _) in self.mouse_regions.iter().rev() {
 444                        // NOT contains
 445                        if !mouse_region.bounds.contains_point(self.mouse_position) {
 446                            valid_regions.push(mouse_region.clone());
 447                        }
 448                    }
 449                }
 450                _ => {
 451                    for (mouse_region, _) in self.mouse_regions.iter().rev() {
 452                        // Contains
 453                        if mouse_region.bounds.contains_point(self.mouse_position) {
 454                            valid_regions.push(mouse_region.clone());
 455                        }
 456                    }
 457                }
 458            }
 459
 460            //3. Fire region events
 461            let hovered_region_ids = self.hovered_region_ids.clone();
 462            for valid_region in valid_regions.into_iter() {
 463                let mut event_cx = self.build_event_context(&mut notified_views, cx);
 464
 465                mouse_event.set_region(valid_region.bounds);
 466                if let MouseEvent::Hover(e) = &mut mouse_event {
 467                    e.started = hovered_region_ids.contains(&valid_region.id())
 468                }
 469                // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
 470                // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
 471                // This behavior can be overridden by adding a Down handler that calls cx.propogate_event
 472                if let MouseEvent::Down(e) = &mouse_event {
 473                    if valid_region
 474                        .handlers
 475                        .contains_handler(MouseEvent::click_disc(), Some(e.button))
 476                        || valid_region
 477                            .handlers
 478                            .contains_handler(MouseEvent::drag_disc(), Some(e.button))
 479                    {
 480                        event_cx.handled = true;
 481                    }
 482                }
 483
 484                if let Some(callback) = valid_region.handlers.get(&mouse_event.handler_key()) {
 485                    event_cx.handled = true;
 486                    event_cx.with_current_view(valid_region.id().view_id(), {
 487                        let region_event = mouse_event.clone();
 488                        |cx| callback(region_event, cx)
 489                    });
 490                }
 491
 492                any_event_handled = any_event_handled || event_cx.handled;
 493                // For bubbling events, if the event was handled, don't continue dispatching
 494                // This only makes sense for local events.
 495                if event_cx.handled && mouse_event.is_capturable() {
 496                    break;
 497                }
 498            }
 499        }
 500
 501        for view_id in notified_views {
 502            cx.notify_view(self.window_id, view_id);
 503        }
 504
 505        any_event_handled
 506    }
 507
 508    pub fn build_event_context<'a>(
 509        &'a mut self,
 510        notified_views: &'a mut HashSet<usize>,
 511        cx: &'a mut MutableAppContext,
 512    ) -> EventContext<'a> {
 513        EventContext {
 514            font_cache: &self.font_cache,
 515            text_layout_cache: &self.text_layout_cache,
 516            view_stack: Default::default(),
 517            notified_views,
 518            notify_count: 0,
 519            handled: false,
 520            window_id: self.window_id,
 521            app: cx,
 522        }
 523    }
 524
 525    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
 526        let view = cx.root_view(self.window_id)?;
 527        Some(json!({
 528            "root_view": view.debug_json(cx),
 529            "root_element": self.rendered_views.get(&view.id())
 530                .map(|root_element| {
 531                    root_element.debug(&DebugContext {
 532                        rendered_views: &self.rendered_views,
 533                        font_cache: &self.font_cache,
 534                        app: cx,
 535                    })
 536                })
 537        }))
 538    }
 539}
 540
 541pub struct LayoutContext<'a> {
 542    window_id: usize,
 543    rendered_views: &'a mut HashMap<usize, ElementBox>,
 544    view_stack: Vec<usize>,
 545    pub font_cache: &'a Arc<FontCache>,
 546    pub font_system: Arc<dyn FontSystem>,
 547    pub text_layout_cache: &'a TextLayoutCache,
 548    pub asset_cache: &'a AssetCache,
 549    pub app: &'a mut MutableAppContext,
 550    pub refreshing: bool,
 551    pub window_size: Vector2F,
 552    titlebar_height: f32,
 553    appearance: Appearance,
 554    hovered_region_ids: HashSet<MouseRegionId>,
 555    clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
 556}
 557
 558impl<'a> LayoutContext<'a> {
 559    pub(crate) fn keystrokes_for_action(
 560        &self,
 561        action: &dyn Action,
 562    ) -> Option<SmallVec<[Keystroke; 2]>> {
 563        self.app
 564            .keystrokes_for_action(self.window_id, &self.view_stack, action)
 565    }
 566
 567    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
 568        let print_error = |view_id| {
 569            format!(
 570                "{} with id {}",
 571                self.app.name_for_view(self.window_id, view_id).unwrap(),
 572                view_id,
 573            )
 574        };
 575        match (
 576            self.view_stack.last(),
 577            self.app.parents.get(&(self.window_id, view_id)),
 578        ) {
 579            (Some(layout_parent), Some(ParentId::View(app_parent))) => {
 580                if layout_parent != app_parent {
 581                    panic!(
 582                        "View {} was laid out with parent {} when it was constructed with parent {}", 
 583                        print_error(view_id),
 584                        print_error(*layout_parent),
 585                        print_error(*app_parent))
 586                }
 587            }
 588            (None, Some(ParentId::View(app_parent))) => panic!(
 589                "View {} was laid out without a parent when it was constructed with parent {}",
 590                print_error(view_id),
 591                print_error(*app_parent)
 592            ),
 593            (Some(layout_parent), Some(ParentId::Root)) => panic!(
 594                "View {} was laid out with parent {} when it was constructed as a window root",
 595                print_error(view_id),
 596                print_error(*layout_parent),
 597            ),
 598            (_, None) => panic!(
 599                "View {} did not have a registered parent in the app context",
 600                print_error(view_id),
 601            ),
 602            _ => {}
 603        }
 604
 605        self.view_stack.push(view_id);
 606        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
 607        let size = rendered_view.layout(constraint, self);
 608        self.rendered_views.insert(view_id, rendered_view);
 609        self.view_stack.pop();
 610        size
 611    }
 612
 613    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
 614    where
 615        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
 616        V: View,
 617    {
 618        handle.update(self.app, |view, cx| {
 619            let mut render_cx = RenderContext {
 620                app: cx,
 621                window_id: handle.window_id(),
 622                view_id: handle.id(),
 623                view_type: PhantomData,
 624                titlebar_height: self.titlebar_height,
 625                hovered_region_ids: self.hovered_region_ids.clone(),
 626                clicked_region_ids: self.clicked_region_ids.clone(),
 627                refreshing: self.refreshing,
 628                appearance: self.appearance,
 629            };
 630            f(view, &mut render_cx)
 631        })
 632    }
 633}
 634
 635impl<'a> Deref for LayoutContext<'a> {
 636    type Target = MutableAppContext;
 637
 638    fn deref(&self) -> &Self::Target {
 639        self.app
 640    }
 641}
 642
 643impl<'a> DerefMut for LayoutContext<'a> {
 644    fn deref_mut(&mut self) -> &mut Self::Target {
 645        self.app
 646    }
 647}
 648
 649impl<'a> ReadView for LayoutContext<'a> {
 650    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
 651        self.app.read_view(handle)
 652    }
 653}
 654
 655impl<'a> ReadModel for LayoutContext<'a> {
 656    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
 657        self.app.read_model(handle)
 658    }
 659}
 660
 661impl<'a> UpgradeModelHandle for LayoutContext<'a> {
 662    fn upgrade_model_handle<T: Entity>(
 663        &self,
 664        handle: &WeakModelHandle<T>,
 665    ) -> Option<ModelHandle<T>> {
 666        self.app.upgrade_model_handle(handle)
 667    }
 668
 669    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 670        self.app.model_handle_is_upgradable(handle)
 671    }
 672
 673    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 674        self.app.upgrade_any_model_handle(handle)
 675    }
 676}
 677
 678impl<'a> UpgradeViewHandle for LayoutContext<'a> {
 679    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 680        self.app.upgrade_view_handle(handle)
 681    }
 682
 683    fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
 684        self.app.upgrade_any_view_handle(handle)
 685    }
 686}
 687
 688pub struct PaintContext<'a> {
 689    rendered_views: &'a mut HashMap<usize, ElementBox>,
 690    view_stack: Vec<usize>,
 691    pub window_size: Vector2F,
 692    pub scene: &'a mut Scene,
 693    pub font_cache: &'a FontCache,
 694    pub text_layout_cache: &'a TextLayoutCache,
 695    pub app: &'a AppContext,
 696}
 697
 698impl<'a> PaintContext<'a> {
 699    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
 700        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
 701            self.view_stack.push(view_id);
 702            tree.paint(origin, visible_bounds, self);
 703            self.rendered_views.insert(view_id, tree);
 704            self.view_stack.pop();
 705        }
 706    }
 707
 708    #[inline]
 709    pub fn paint_stacking_context<F>(&mut self, clip_bounds: Option<RectF>, f: F)
 710    where
 711        F: FnOnce(&mut Self),
 712    {
 713        self.scene.push_stacking_context(clip_bounds);
 714        f(self);
 715        self.scene.pop_stacking_context();
 716    }
 717
 718    #[inline]
 719    pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
 720    where
 721        F: FnOnce(&mut Self),
 722    {
 723        self.scene.push_layer(clip_bounds);
 724        f(self);
 725        self.scene.pop_layer();
 726    }
 727
 728    pub fn current_view_id(&self) -> usize {
 729        *self.view_stack.last().unwrap()
 730    }
 731}
 732
 733impl<'a> Deref for PaintContext<'a> {
 734    type Target = AppContext;
 735
 736    fn deref(&self) -> &Self::Target {
 737        self.app
 738    }
 739}
 740
 741pub struct EventContext<'a> {
 742    pub font_cache: &'a FontCache,
 743    pub text_layout_cache: &'a TextLayoutCache,
 744    pub app: &'a mut MutableAppContext,
 745    pub window_id: usize,
 746    pub notify_count: usize,
 747    view_stack: Vec<usize>,
 748    handled: bool,
 749    notified_views: &'a mut HashSet<usize>,
 750}
 751
 752impl<'a> EventContext<'a> {
 753    fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
 754    where
 755        F: FnOnce(&mut Self) -> T,
 756    {
 757        self.view_stack.push(view_id);
 758        let result = f(self);
 759        self.view_stack.pop();
 760        result
 761    }
 762
 763    pub fn window_id(&self) -> usize {
 764        self.window_id
 765    }
 766
 767    pub fn view_id(&self) -> Option<usize> {
 768        self.view_stack.last().copied()
 769    }
 770
 771    pub fn is_parent_view_focused(&self) -> bool {
 772        if let Some(parent_view_id) = self.view_stack.last() {
 773            self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
 774        } else {
 775            false
 776        }
 777    }
 778
 779    pub fn focus_parent_view(&mut self) {
 780        if let Some(parent_view_id) = self.view_stack.last() {
 781            self.app.focus(self.window_id, Some(*parent_view_id))
 782        }
 783    }
 784
 785    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
 786        self.app
 787            .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
 788    }
 789
 790    pub fn dispatch_action<A: Action>(&mut self, action: A) {
 791        self.dispatch_any_action(Box::new(action));
 792    }
 793
 794    pub fn notify(&mut self) {
 795        self.notify_count += 1;
 796        if let Some(view_id) = self.view_stack.last() {
 797            self.notified_views.insert(*view_id);
 798        }
 799    }
 800
 801    pub fn notify_count(&self) -> usize {
 802        self.notify_count
 803    }
 804
 805    pub fn propagate_event(&mut self) {
 806        self.handled = false;
 807    }
 808}
 809
 810impl<'a> Deref for EventContext<'a> {
 811    type Target = MutableAppContext;
 812
 813    fn deref(&self) -> &Self::Target {
 814        self.app
 815    }
 816}
 817
 818impl<'a> DerefMut for EventContext<'a> {
 819    fn deref_mut(&mut self) -> &mut Self::Target {
 820        self.app
 821    }
 822}
 823
 824pub struct MeasurementContext<'a> {
 825    app: &'a AppContext,
 826    rendered_views: &'a HashMap<usize, ElementBox>,
 827    pub window_id: usize,
 828}
 829
 830impl<'a> Deref for MeasurementContext<'a> {
 831    type Target = AppContext;
 832
 833    fn deref(&self) -> &Self::Target {
 834        self.app
 835    }
 836}
 837
 838impl<'a> MeasurementContext<'a> {
 839    fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
 840        let element = self.rendered_views.get(&view_id)?;
 841        element.rect_for_text_range(range_utf16, self)
 842    }
 843}
 844
 845pub struct DebugContext<'a> {
 846    rendered_views: &'a HashMap<usize, ElementBox>,
 847    pub font_cache: &'a FontCache,
 848    pub app: &'a AppContext,
 849}
 850
 851#[derive(Clone, Copy, Debug, Eq, PartialEq)]
 852pub enum Axis {
 853    Horizontal,
 854    Vertical,
 855}
 856
 857impl Axis {
 858    pub fn invert(self) -> Self {
 859        match self {
 860            Self::Horizontal => Self::Vertical,
 861            Self::Vertical => Self::Horizontal,
 862        }
 863    }
 864}
 865
 866impl ToJson for Axis {
 867    fn to_json(&self) -> serde_json::Value {
 868        match self {
 869            Axis::Horizontal => json!("horizontal"),
 870            Axis::Vertical => json!("vertical"),
 871        }
 872    }
 873}
 874
 875pub trait Vector2FExt {
 876    fn along(self, axis: Axis) -> f32;
 877}
 878
 879impl Vector2FExt for Vector2F {
 880    fn along(self, axis: Axis) -> f32 {
 881        match axis {
 882            Axis::Horizontal => self.x(),
 883            Axis::Vertical => self.y(),
 884        }
 885    }
 886}
 887
 888#[derive(Copy, Clone, Debug)]
 889pub struct SizeConstraint {
 890    pub min: Vector2F,
 891    pub max: Vector2F,
 892}
 893
 894impl SizeConstraint {
 895    pub fn new(min: Vector2F, max: Vector2F) -> Self {
 896        Self { min, max }
 897    }
 898
 899    pub fn strict(size: Vector2F) -> Self {
 900        Self {
 901            min: size,
 902            max: size,
 903        }
 904    }
 905
 906    pub fn strict_along(axis: Axis, max: f32) -> Self {
 907        match axis {
 908            Axis::Horizontal => Self {
 909                min: vec2f(max, 0.0),
 910                max: vec2f(max, f32::INFINITY),
 911            },
 912            Axis::Vertical => Self {
 913                min: vec2f(0.0, max),
 914                max: vec2f(f32::INFINITY, max),
 915            },
 916        }
 917    }
 918
 919    pub fn max_along(&self, axis: Axis) -> f32 {
 920        match axis {
 921            Axis::Horizontal => self.max.x(),
 922            Axis::Vertical => self.max.y(),
 923        }
 924    }
 925
 926    pub fn min_along(&self, axis: Axis) -> f32 {
 927        match axis {
 928            Axis::Horizontal => self.min.x(),
 929            Axis::Vertical => self.min.y(),
 930        }
 931    }
 932
 933    pub fn constrain(&self, size: Vector2F) -> Vector2F {
 934        vec2f(
 935            size.x().min(self.max.x()).max(self.min.x()),
 936            size.y().min(self.max.y()).max(self.min.y()),
 937        )
 938    }
 939}
 940
 941impl Default for SizeConstraint {
 942    fn default() -> Self {
 943        SizeConstraint {
 944            min: Vector2F::zero(),
 945            max: Vector2F::splat(f32::INFINITY),
 946        }
 947    }
 948}
 949
 950impl ToJson for SizeConstraint {
 951    fn to_json(&self) -> serde_json::Value {
 952        json!({
 953            "min": self.min.to_json(),
 954            "max": self.max.to_json(),
 955        })
 956    }
 957}
 958
 959pub struct ChildView {
 960    view: AnyWeakViewHandle,
 961    view_name: &'static str,
 962}
 963
 964impl ChildView {
 965    pub fn new(view: impl Into<AnyViewHandle>, cx: &AppContext) -> Self {
 966        let view = view.into();
 967        let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
 968        Self {
 969            view: view.downgrade(),
 970            view_name,
 971        }
 972    }
 973}
 974
 975impl Element for ChildView {
 976    type LayoutState = bool;
 977    type PaintState = ();
 978
 979    fn layout(
 980        &mut self,
 981        constraint: SizeConstraint,
 982        cx: &mut LayoutContext,
 983    ) -> (Vector2F, Self::LayoutState) {
 984        if cx.rendered_views.contains_key(&self.view.id()) {
 985            let size = cx.layout(self.view.id(), constraint);
 986            (size, true)
 987        } else {
 988            log::error!(
 989                "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
 990                self.view.id(),
 991                self.view_name
 992            );
 993            (Vector2F::zero(), false)
 994        }
 995    }
 996
 997    fn paint(
 998        &mut self,
 999        bounds: RectF,
1000        visible_bounds: RectF,
1001        view_is_valid: &mut Self::LayoutState,
1002        cx: &mut PaintContext,
1003    ) {
1004        if *view_is_valid {
1005            cx.paint(self.view.id(), bounds.origin(), visible_bounds);
1006        } else {
1007            log::error!(
1008                "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1009                self.view.id(),
1010                self.view_name
1011            );
1012        }
1013    }
1014
1015    fn rect_for_text_range(
1016        &self,
1017        range_utf16: Range<usize>,
1018        _: RectF,
1019        _: RectF,
1020        view_is_valid: &Self::LayoutState,
1021        _: &Self::PaintState,
1022        cx: &MeasurementContext,
1023    ) -> Option<RectF> {
1024        if *view_is_valid {
1025            cx.rect_for_text_range(self.view.id(), range_utf16)
1026        } else {
1027            log::error!(
1028                "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1029                self.view.id(),
1030                self.view_name
1031            );
1032            None
1033        }
1034    }
1035
1036    fn debug(
1037        &self,
1038        bounds: RectF,
1039        _: &Self::LayoutState,
1040        _: &Self::PaintState,
1041        cx: &DebugContext,
1042    ) -> serde_json::Value {
1043        json!({
1044            "type": "ChildView",
1045            "view_id": self.view.id(),
1046            "bounds": bounds.to_json(),
1047            "view": if let Some(view) = self.view.upgrade(cx.app) {
1048                view.debug_json(cx.app)
1049            } else {
1050                json!(null)
1051            },
1052            "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
1053                view.debug(cx)
1054            } else {
1055                json!(null)
1056            }
1057        })
1058    }
1059}