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