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