presenter.rs

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