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