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
 320                let t0 = std::time::Instant::now();
 321                let is_topmost_window =
 322                    cx.is_topmost_window_for_position(self.window_id, *position);
 323                println!("is_topmost_window => {:?}", t0.elapsed());
 324                if is_topmost_window {
 325                    let t1 = std::time::Instant::now();
 326                    cx.platform().set_cursor_style(style_to_assign);
 327                    println!("set_cursor_style => {:?}", t1.elapsed());
 328                }
 329
 330                if !event_reused {
 331                    if pressed_button.is_some() {
 332                        mouse_events.push(MouseEvent::Drag(MouseDrag {
 333                            region: Default::default(),
 334                            prev_mouse_position: self.mouse_position,
 335                            platform_event: e.clone(),
 336                        }));
 337                    } else if let Some(clicked_button) = self.clicked_button {
 338                        // Mouse up event happened outside the current window. Simulate mouse up button event
 339                        let button_event = e.to_button_event(clicked_button);
 340                        mouse_events.push(MouseEvent::Up(MouseUp {
 341                            region: Default::default(),
 342                            platform_event: button_event.clone(),
 343                        }));
 344                        mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 345                            region: Default::default(),
 346                            platform_event: button_event.clone(),
 347                        }));
 348                        mouse_events.push(MouseEvent::Click(MouseClick {
 349                            region: Default::default(),
 350                            platform_event: button_event.clone(),
 351                        }));
 352                    }
 353
 354                    mouse_events.push(MouseEvent::Move(MouseMove {
 355                        region: Default::default(),
 356                        platform_event: e.clone(),
 357                    }));
 358                }
 359
 360                mouse_events.push(MouseEvent::Hover(MouseHover {
 361                    region: Default::default(),
 362                    platform_event: e.clone(),
 363                    started: false,
 364                }));
 365                mouse_events.push(MouseEvent::MoveOut(MouseMoveOut {
 366                    region: Default::default(),
 367                }));
 368
 369                self.last_mouse_moved_event = Some(event.clone());
 370            }
 371
 372            Event::MouseExited(event) => {
 373                // When the platform sends a MouseExited event, synthesize
 374                // a MouseMoved event whose position is outside the window's
 375                // bounds so that hover and cursor state can be updated.
 376                return self.dispatch_event(
 377                    Event::MouseMoved(MouseMovedEvent {
 378                        position: event.position,
 379                        pressed_button: event.pressed_button,
 380                        modifiers: event.modifiers,
 381                    }),
 382                    event_reused,
 383                    cx,
 384                );
 385            }
 386
 387            Event::ScrollWheel(e) => mouse_events.push(MouseEvent::ScrollWheel(MouseScrollWheel {
 388                region: Default::default(),
 389                platform_event: e.clone(),
 390            })),
 391        }
 392
 393        if let Some(position) = event.position() {
 394            self.mouse_position = position;
 395        }
 396
 397        // 2. Dispatch mouse events on regions
 398        let mut any_event_handled = false;
 399        for mut mouse_event in mouse_events {
 400            let mut valid_regions = Vec::new();
 401
 402            // GPUI elements are arranged by z_index but sibling elements can register overlapping
 403            // mouse regions. As such, hover events are only fired on overlapping elements which
 404            // are at the same z-index as the topmost element which overlaps with the mouse.
 405            match &mouse_event {
 406                MouseEvent::Hover(_) => {
 407                    let mut highest_z_index = None;
 408                    let mouse_position = self.mouse_position.clone();
 409                    for (region, z_index) in self.mouse_regions.iter().rev() {
 410                        // Allow mouse regions to appear transparent to hovers
 411                        if !region.hoverable {
 412                            continue;
 413                        }
 414
 415                        let contains_mouse = region.bounds.contains_point(mouse_position);
 416
 417                        if contains_mouse && highest_z_index.is_none() {
 418                            highest_z_index = Some(z_index);
 419                        }
 420
 421                        // This unwrap relies on short circuiting boolean expressions
 422                        // The right side of the && is only executed when contains_mouse
 423                        // is true, and we know above that when contains_mouse is true
 424                        // highest_z_index is set.
 425                        if contains_mouse && z_index == highest_z_index.unwrap() {
 426                            //Ensure that hover entrance events aren't sent twice
 427                            if self.hovered_region_ids.insert(region.id()) {
 428                                valid_regions.push(region.clone());
 429                                if region.notify_on_hover {
 430                                    notified_views.insert(region.id().view_id());
 431                                }
 432                            }
 433                        } else {
 434                            // Ensure that hover exit events aren't sent twice
 435                            if self.hovered_region_ids.remove(&region.id()) {
 436                                valid_regions.push(region.clone());
 437                                if region.notify_on_hover {
 438                                    notified_views.insert(region.id().view_id());
 439                                }
 440                            }
 441                        }
 442                    }
 443                }
 444
 445                MouseEvent::Down(_) | MouseEvent::Up(_) => {
 446                    for (region, _) in self.mouse_regions.iter().rev() {
 447                        if region.bounds.contains_point(self.mouse_position) {
 448                            valid_regions.push(region.clone());
 449                            if region.notify_on_click {
 450                                notified_views.insert(region.id().view_id());
 451                            }
 452                        }
 453                    }
 454                }
 455
 456                MouseEvent::Click(e) => {
 457                    // Only raise click events if the released button is the same as the one stored
 458                    if self
 459                        .clicked_button
 460                        .map(|clicked_button| clicked_button == e.button)
 461                        .unwrap_or(false)
 462                    {
 463                        // Clear clicked regions and clicked button
 464                        let clicked_region_ids =
 465                            std::mem::replace(&mut self.clicked_region_ids, Default::default());
 466                        self.clicked_button = None;
 467
 468                        // Find regions which still overlap with the mouse since the last MouseDown happened
 469                        for (mouse_region, _) in self.mouse_regions.iter().rev() {
 470                            if clicked_region_ids.contains(&mouse_region.id()) {
 471                                if mouse_region.bounds.contains_point(self.mouse_position) {
 472                                    valid_regions.push(mouse_region.clone());
 473                                }
 474                            }
 475                        }
 476                    }
 477                }
 478
 479                MouseEvent::Drag(_) => {
 480                    for (mouse_region, _) in self.mouse_regions.iter().rev() {
 481                        if self.clicked_region_ids.contains(&mouse_region.id()) {
 482                            valid_regions.push(mouse_region.clone());
 483                        }
 484                    }
 485                }
 486
 487                MouseEvent::MoveOut(_) | MouseEvent::UpOut(_) | MouseEvent::DownOut(_) => {
 488                    for (mouse_region, _) in self.mouse_regions.iter().rev() {
 489                        // NOT contains
 490                        if !mouse_region.bounds.contains_point(self.mouse_position) {
 491                            valid_regions.push(mouse_region.clone());
 492                        }
 493                    }
 494                }
 495
 496                _ => {
 497                    for (mouse_region, _) in self.mouse_regions.iter().rev() {
 498                        // Contains
 499                        if mouse_region.bounds.contains_point(self.mouse_position) {
 500                            valid_regions.push(mouse_region.clone());
 501                        }
 502                    }
 503                }
 504            }
 505
 506            //3. Fire region events
 507            let hovered_region_ids = self.hovered_region_ids.clone();
 508            for valid_region in valid_regions.into_iter() {
 509                let mut event_cx = self.build_event_context(&mut notified_views, cx);
 510
 511                mouse_event.set_region(valid_region.bounds);
 512                if let MouseEvent::Hover(e) = &mut mouse_event {
 513                    e.started = hovered_region_ids.contains(&valid_region.id())
 514                }
 515                // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
 516                // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
 517                // This behavior can be overridden by adding a Down handler that calls cx.propogate_event
 518                if let MouseEvent::Down(e) = &mouse_event {
 519                    if valid_region
 520                        .handlers
 521                        .contains(MouseEvent::click_disc(), Some(e.button))
 522                        || valid_region
 523                            .handlers
 524                            .contains(MouseEvent::drag_disc(), Some(e.button))
 525                    {
 526                        event_cx.handled = true;
 527                    }
 528                }
 529
 530                // `event_consumed` should only be true if there are any handlers for this event.
 531                let mut event_consumed = event_cx.handled;
 532                if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
 533                    event_consumed = true;
 534                    for callback in callbacks {
 535                        event_cx.handled = true;
 536                        event_cx.with_current_view(valid_region.id().view_id(), {
 537                            let region_event = mouse_event.clone();
 538                            |cx| callback(region_event, cx)
 539                        });
 540                        event_consumed &= event_cx.handled;
 541                        any_event_handled |= event_cx.handled;
 542                    }
 543                }
 544
 545                any_event_handled |= event_cx.handled;
 546
 547                // For bubbling events, if the event was handled, don't continue dispatching.
 548                // This only makes sense for local events which return false from is_capturable.
 549                if event_consumed && mouse_event.is_capturable() {
 550                    break;
 551                }
 552            }
 553        }
 554
 555        for view_id in notified_views {
 556            cx.notify_view(self.window_id, view_id);
 557        }
 558
 559        any_event_handled
 560    }
 561
 562    pub fn build_event_context<'a>(
 563        &'a mut self,
 564        notified_views: &'a mut HashSet<usize>,
 565        cx: &'a mut MutableAppContext,
 566    ) -> EventContext<'a> {
 567        EventContext {
 568            font_cache: &self.font_cache,
 569            text_layout_cache: &self.text_layout_cache,
 570            view_stack: Default::default(),
 571            notified_views,
 572            notify_count: 0,
 573            handled: false,
 574            window_id: self.window_id,
 575            app: cx,
 576        }
 577    }
 578
 579    pub fn debug_elements(&self, cx: &AppContext) -> Option<json::Value> {
 580        let view = cx.root_view(self.window_id)?;
 581        Some(json!({
 582            "root_view": view.debug_json(cx),
 583            "root_element": self.rendered_views.get(&view.id())
 584                .map(|root_element| {
 585                    root_element.debug(&DebugContext {
 586                        rendered_views: &self.rendered_views,
 587                        font_cache: &self.font_cache,
 588                        app: cx,
 589                    })
 590                })
 591        }))
 592    }
 593}
 594
 595pub struct LayoutContext<'a> {
 596    window_id: usize,
 597    rendered_views: &'a mut HashMap<usize, ElementBox>,
 598    view_stack: Vec<usize>,
 599    pub font_cache: &'a Arc<FontCache>,
 600    pub font_system: Arc<dyn FontSystem>,
 601    pub text_layout_cache: &'a TextLayoutCache,
 602    pub asset_cache: &'a AssetCache,
 603    pub app: &'a mut MutableAppContext,
 604    pub refreshing: bool,
 605    pub window_size: Vector2F,
 606    titlebar_height: f32,
 607    appearance: Appearance,
 608    hovered_region_ids: HashSet<MouseRegionId>,
 609    clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
 610}
 611
 612impl<'a> LayoutContext<'a> {
 613    pub(crate) fn keystrokes_for_action(
 614        &mut self,
 615        action: &dyn Action,
 616    ) -> Option<SmallVec<[Keystroke; 2]>> {
 617        self.app
 618            .keystrokes_for_action(self.window_id, &self.view_stack, action)
 619    }
 620
 621    fn layout(&mut self, view_id: usize, constraint: SizeConstraint) -> Vector2F {
 622        let print_error = |view_id| {
 623            format!(
 624                "{} with id {}",
 625                self.app.name_for_view(self.window_id, view_id).unwrap(),
 626                view_id,
 627            )
 628        };
 629        match (
 630            self.view_stack.last(),
 631            self.app.parents.get(&(self.window_id, view_id)),
 632        ) {
 633            (Some(layout_parent), Some(ParentId::View(app_parent))) => {
 634                if layout_parent != app_parent {
 635                    panic!(
 636                        "View {} was laid out with parent {} when it was constructed with parent {}", 
 637                        print_error(view_id),
 638                        print_error(*layout_parent),
 639                        print_error(*app_parent))
 640                }
 641            }
 642            (None, Some(ParentId::View(app_parent))) => panic!(
 643                "View {} was laid out without a parent when it was constructed with parent {}",
 644                print_error(view_id),
 645                print_error(*app_parent)
 646            ),
 647            (Some(layout_parent), Some(ParentId::Root)) => panic!(
 648                "View {} was laid out with parent {} when it was constructed as a window root",
 649                print_error(view_id),
 650                print_error(*layout_parent),
 651            ),
 652            (_, None) => panic!(
 653                "View {} did not have a registered parent in the app context",
 654                print_error(view_id),
 655            ),
 656            _ => {}
 657        }
 658
 659        self.view_stack.push(view_id);
 660        let mut rendered_view = self.rendered_views.remove(&view_id).unwrap();
 661        let size = rendered_view.layout(constraint, self);
 662        self.rendered_views.insert(view_id, rendered_view);
 663        self.view_stack.pop();
 664        size
 665    }
 666
 667    pub fn render<F, V, T>(&mut self, handle: &ViewHandle<V>, f: F) -> T
 668    where
 669        F: FnOnce(&mut V, &mut RenderContext<V>) -> T,
 670        V: View,
 671    {
 672        handle.update(self.app, |view, cx| {
 673            let mut render_cx = RenderContext {
 674                app: cx,
 675                window_id: handle.window_id(),
 676                view_id: handle.id(),
 677                view_type: PhantomData,
 678                titlebar_height: self.titlebar_height,
 679                hovered_region_ids: self.hovered_region_ids.clone(),
 680                clicked_region_ids: self.clicked_region_ids.clone(),
 681                refreshing: self.refreshing,
 682                appearance: self.appearance,
 683            };
 684            f(view, &mut render_cx)
 685        })
 686    }
 687}
 688
 689impl<'a> Deref for LayoutContext<'a> {
 690    type Target = MutableAppContext;
 691
 692    fn deref(&self) -> &Self::Target {
 693        self.app
 694    }
 695}
 696
 697impl<'a> DerefMut for LayoutContext<'a> {
 698    fn deref_mut(&mut self) -> &mut Self::Target {
 699        self.app
 700    }
 701}
 702
 703impl<'a> ReadView for LayoutContext<'a> {
 704    fn read_view<T: View>(&self, handle: &ViewHandle<T>) -> &T {
 705        self.app.read_view(handle)
 706    }
 707}
 708
 709impl<'a> ReadModel for LayoutContext<'a> {
 710    fn read_model<T: Entity>(&self, handle: &ModelHandle<T>) -> &T {
 711        self.app.read_model(handle)
 712    }
 713}
 714
 715impl<'a> UpgradeModelHandle for LayoutContext<'a> {
 716    fn upgrade_model_handle<T: Entity>(
 717        &self,
 718        handle: &WeakModelHandle<T>,
 719    ) -> Option<ModelHandle<T>> {
 720        self.app.upgrade_model_handle(handle)
 721    }
 722
 723    fn model_handle_is_upgradable<T: Entity>(&self, handle: &WeakModelHandle<T>) -> bool {
 724        self.app.model_handle_is_upgradable(handle)
 725    }
 726
 727    fn upgrade_any_model_handle(&self, handle: &AnyWeakModelHandle) -> Option<AnyModelHandle> {
 728        self.app.upgrade_any_model_handle(handle)
 729    }
 730}
 731
 732impl<'a> UpgradeViewHandle for LayoutContext<'a> {
 733    fn upgrade_view_handle<T: View>(&self, handle: &WeakViewHandle<T>) -> Option<ViewHandle<T>> {
 734        self.app.upgrade_view_handle(handle)
 735    }
 736
 737    fn upgrade_any_view_handle(&self, handle: &crate::AnyWeakViewHandle) -> Option<AnyViewHandle> {
 738        self.app.upgrade_any_view_handle(handle)
 739    }
 740}
 741
 742pub struct PaintContext<'a> {
 743    rendered_views: &'a mut HashMap<usize, ElementBox>,
 744    view_stack: Vec<usize>,
 745    pub window_size: Vector2F,
 746    pub scene: &'a mut SceneBuilder,
 747    pub font_cache: &'a FontCache,
 748    pub text_layout_cache: &'a TextLayoutCache,
 749    pub app: &'a AppContext,
 750}
 751
 752impl<'a> PaintContext<'a> {
 753    fn paint(&mut self, view_id: usize, origin: Vector2F, visible_bounds: RectF) {
 754        if let Some(mut tree) = self.rendered_views.remove(&view_id) {
 755            self.view_stack.push(view_id);
 756            tree.paint(origin, visible_bounds, self);
 757            self.rendered_views.insert(view_id, tree);
 758            self.view_stack.pop();
 759        }
 760    }
 761
 762    #[inline]
 763    pub fn paint_stacking_context<F>(
 764        &mut self,
 765        clip_bounds: Option<RectF>,
 766        z_index: Option<usize>,
 767        f: F,
 768    ) where
 769        F: FnOnce(&mut Self),
 770    {
 771        self.scene.push_stacking_context(clip_bounds, z_index);
 772        f(self);
 773        self.scene.pop_stacking_context();
 774    }
 775
 776    #[inline]
 777    pub fn paint_layer<F>(&mut self, clip_bounds: Option<RectF>, f: F)
 778    where
 779        F: FnOnce(&mut Self),
 780    {
 781        self.scene.push_layer(clip_bounds);
 782        f(self);
 783        self.scene.pop_layer();
 784    }
 785
 786    pub fn current_view_id(&self) -> usize {
 787        *self.view_stack.last().unwrap()
 788    }
 789}
 790
 791impl<'a> Deref for PaintContext<'a> {
 792    type Target = AppContext;
 793
 794    fn deref(&self) -> &Self::Target {
 795        self.app
 796    }
 797}
 798
 799pub struct EventContext<'a> {
 800    pub font_cache: &'a FontCache,
 801    pub text_layout_cache: &'a TextLayoutCache,
 802    pub app: &'a mut MutableAppContext,
 803    pub window_id: usize,
 804    pub notify_count: usize,
 805    view_stack: Vec<usize>,
 806    handled: bool,
 807    notified_views: &'a mut HashSet<usize>,
 808}
 809
 810impl<'a> EventContext<'a> {
 811    fn with_current_view<F, T>(&mut self, view_id: usize, f: F) -> T
 812    where
 813        F: FnOnce(&mut Self) -> T,
 814    {
 815        self.view_stack.push(view_id);
 816        let result = f(self);
 817        self.view_stack.pop();
 818        result
 819    }
 820
 821    pub fn window_id(&self) -> usize {
 822        self.window_id
 823    }
 824
 825    pub fn view_id(&self) -> Option<usize> {
 826        self.view_stack.last().copied()
 827    }
 828
 829    pub fn is_parent_view_focused(&self) -> bool {
 830        if let Some(parent_view_id) = self.view_stack.last() {
 831            self.app.focused_view_id(self.window_id) == Some(*parent_view_id)
 832        } else {
 833            false
 834        }
 835    }
 836
 837    pub fn focus_parent_view(&mut self) {
 838        if let Some(parent_view_id) = self.view_stack.last() {
 839            self.app.focus(self.window_id, Some(*parent_view_id))
 840        }
 841    }
 842
 843    pub fn dispatch_any_action(&mut self, action: Box<dyn Action>) {
 844        self.app
 845            .dispatch_any_action_at(self.window_id, *self.view_stack.last().unwrap(), action)
 846    }
 847
 848    pub fn dispatch_action<A: Action>(&mut self, action: A) {
 849        self.dispatch_any_action(Box::new(action));
 850    }
 851
 852    pub fn notify(&mut self) {
 853        self.notify_count += 1;
 854        if let Some(view_id) = self.view_stack.last() {
 855            self.notified_views.insert(*view_id);
 856        }
 857    }
 858
 859    pub fn notify_count(&self) -> usize {
 860        self.notify_count
 861    }
 862
 863    pub fn propagate_event(&mut self) {
 864        self.handled = false;
 865    }
 866}
 867
 868impl<'a> Deref for EventContext<'a> {
 869    type Target = MutableAppContext;
 870
 871    fn deref(&self) -> &Self::Target {
 872        self.app
 873    }
 874}
 875
 876impl<'a> DerefMut for EventContext<'a> {
 877    fn deref_mut(&mut self) -> &mut Self::Target {
 878        self.app
 879    }
 880}
 881
 882pub struct MeasurementContext<'a> {
 883    app: &'a AppContext,
 884    rendered_views: &'a HashMap<usize, ElementBox>,
 885    pub window_id: usize,
 886}
 887
 888impl<'a> Deref for MeasurementContext<'a> {
 889    type Target = AppContext;
 890
 891    fn deref(&self) -> &Self::Target {
 892        self.app
 893    }
 894}
 895
 896impl<'a> MeasurementContext<'a> {
 897    fn rect_for_text_range(&self, view_id: usize, range_utf16: Range<usize>) -> Option<RectF> {
 898        let element = self.rendered_views.get(&view_id)?;
 899        element.rect_for_text_range(range_utf16, self)
 900    }
 901}
 902
 903pub struct DebugContext<'a> {
 904    rendered_views: &'a HashMap<usize, ElementBox>,
 905    pub font_cache: &'a FontCache,
 906    pub app: &'a AppContext,
 907}
 908
 909#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
 910pub enum Axis {
 911    #[default]
 912    Horizontal,
 913    Vertical,
 914}
 915
 916impl Axis {
 917    pub fn invert(self) -> Self {
 918        match self {
 919            Self::Horizontal => Self::Vertical,
 920            Self::Vertical => Self::Horizontal,
 921        }
 922    }
 923
 924    pub fn component(&self, point: Vector2F) -> f32 {
 925        match self {
 926            Self::Horizontal => point.x(),
 927            Self::Vertical => point.y(),
 928        }
 929    }
 930}
 931
 932impl ToJson for Axis {
 933    fn to_json(&self) -> serde_json::Value {
 934        match self {
 935            Axis::Horizontal => json!("horizontal"),
 936            Axis::Vertical => json!("vertical"),
 937        }
 938    }
 939}
 940
 941impl Bind for Axis {
 942    fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
 943        match self {
 944            Axis::Horizontal => "Horizontal",
 945            Axis::Vertical => "Vertical",
 946        }
 947        .bind(statement, start_index)
 948    }
 949}
 950
 951impl Column for Axis {
 952    fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
 953        String::column(statement, start_index).and_then(|(axis_text, next_index)| {
 954            Ok((
 955                match axis_text.as_str() {
 956                    "Horizontal" => Axis::Horizontal,
 957                    "Vertical" => Axis::Vertical,
 958                    _ => bail!("Stored serialized item kind is incorrect"),
 959                },
 960                next_index,
 961            ))
 962        })
 963    }
 964}
 965
 966pub trait Vector2FExt {
 967    fn along(self, axis: Axis) -> f32;
 968}
 969
 970impl Vector2FExt for Vector2F {
 971    fn along(self, axis: Axis) -> f32 {
 972        match axis {
 973            Axis::Horizontal => self.x(),
 974            Axis::Vertical => self.y(),
 975        }
 976    }
 977}
 978
 979#[derive(Copy, Clone, Debug)]
 980pub struct SizeConstraint {
 981    pub min: Vector2F,
 982    pub max: Vector2F,
 983}
 984
 985impl SizeConstraint {
 986    pub fn new(min: Vector2F, max: Vector2F) -> Self {
 987        Self { min, max }
 988    }
 989
 990    pub fn strict(size: Vector2F) -> Self {
 991        Self {
 992            min: size,
 993            max: size,
 994        }
 995    }
 996
 997    pub fn strict_along(axis: Axis, max: f32) -> Self {
 998        match axis {
 999            Axis::Horizontal => Self {
1000                min: vec2f(max, 0.0),
1001                max: vec2f(max, f32::INFINITY),
1002            },
1003            Axis::Vertical => Self {
1004                min: vec2f(0.0, max),
1005                max: vec2f(f32::INFINITY, max),
1006            },
1007        }
1008    }
1009
1010    pub fn max_along(&self, axis: Axis) -> f32 {
1011        match axis {
1012            Axis::Horizontal => self.max.x(),
1013            Axis::Vertical => self.max.y(),
1014        }
1015    }
1016
1017    pub fn min_along(&self, axis: Axis) -> f32 {
1018        match axis {
1019            Axis::Horizontal => self.min.x(),
1020            Axis::Vertical => self.min.y(),
1021        }
1022    }
1023
1024    pub fn constrain(&self, size: Vector2F) -> Vector2F {
1025        vec2f(
1026            size.x().min(self.max.x()).max(self.min.x()),
1027            size.y().min(self.max.y()).max(self.min.y()),
1028        )
1029    }
1030}
1031
1032impl Default for SizeConstraint {
1033    fn default() -> Self {
1034        SizeConstraint {
1035            min: Vector2F::zero(),
1036            max: Vector2F::splat(f32::INFINITY),
1037        }
1038    }
1039}
1040
1041impl ToJson for SizeConstraint {
1042    fn to_json(&self) -> serde_json::Value {
1043        json!({
1044            "min": self.min.to_json(),
1045            "max": self.max.to_json(),
1046        })
1047    }
1048}
1049
1050pub struct ChildView {
1051    view: AnyWeakViewHandle,
1052    view_name: &'static str,
1053}
1054
1055impl ChildView {
1056    pub fn new(view: impl Into<AnyViewHandle>, cx: &AppContext) -> Self {
1057        let view = view.into();
1058        let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
1059        Self {
1060            view: view.downgrade(),
1061            view_name,
1062        }
1063    }
1064}
1065
1066impl Element for ChildView {
1067    type LayoutState = bool;
1068    type PaintState = ();
1069
1070    fn layout(
1071        &mut self,
1072        constraint: SizeConstraint,
1073        cx: &mut LayoutContext,
1074    ) -> (Vector2F, Self::LayoutState) {
1075        if cx.rendered_views.contains_key(&self.view.id()) {
1076            let size = cx.layout(self.view.id(), constraint);
1077            (size, true)
1078        } else {
1079            log::error!(
1080                "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1081                self.view.id(),
1082                self.view_name
1083            );
1084            (Vector2F::zero(), false)
1085        }
1086    }
1087
1088    fn paint(
1089        &mut self,
1090        bounds: RectF,
1091        visible_bounds: RectF,
1092        view_is_valid: &mut Self::LayoutState,
1093        cx: &mut PaintContext,
1094    ) {
1095        if *view_is_valid {
1096            cx.paint(self.view.id(), bounds.origin(), visible_bounds);
1097        } else {
1098            log::error!(
1099                "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1100                self.view.id(),
1101                self.view_name
1102            );
1103        }
1104    }
1105
1106    fn rect_for_text_range(
1107        &self,
1108        range_utf16: Range<usize>,
1109        _: RectF,
1110        _: RectF,
1111        view_is_valid: &Self::LayoutState,
1112        _: &Self::PaintState,
1113        cx: &MeasurementContext,
1114    ) -> Option<RectF> {
1115        if *view_is_valid {
1116            cx.rect_for_text_range(self.view.id(), range_utf16)
1117        } else {
1118            log::error!(
1119                "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1120                self.view.id(),
1121                self.view_name
1122            );
1123            None
1124        }
1125    }
1126
1127    fn debug(
1128        &self,
1129        bounds: RectF,
1130        _: &Self::LayoutState,
1131        _: &Self::PaintState,
1132        cx: &DebugContext,
1133    ) -> serde_json::Value {
1134        json!({
1135            "type": "ChildView",
1136            "view_id": self.view.id(),
1137            "bounds": bounds.to_json(),
1138            "view": if let Some(view) = self.view.upgrade(cx.app) {
1139                view.debug_json(cx.app)
1140            } else {
1141                json!(null)
1142            },
1143            "child": if let Some(view) = cx.rendered_views.get(&self.view.id()) {
1144                view.debug(cx)
1145            } else {
1146                json!(null)
1147            }
1148        })
1149    }
1150}