window.rs

   1use crate::{
   2    elements::AnyRootElement,
   3    geometry::rect::RectF,
   4    json::ToJson,
   5    keymap_matcher::{Binding, KeymapContext, Keystroke, MatchResult},
   6    platform::{
   7        self, Appearance, CursorStyle, Event, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent,
   8        MouseButton, MouseMovedEvent, PromptLevel, WindowBounds,
   9    },
  10    scene::{
  11        CursorRegion, MouseClick, MouseClickOut, MouseDown, MouseDownOut, MouseDrag, MouseEvent,
  12        MouseHover, MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut, Scene,
  13    },
  14    text_layout::TextLayoutCache,
  15    util::post_inc,
  16    Action, AnyView, AnyViewHandle, AppContext, BorrowAppContext, BorrowWindowContext, Effect,
  17    Element, Entity, Handle, LayoutContext, MouseRegion, MouseRegionId, SceneBuilder, Subscription,
  18    View, ViewContext, ViewHandle, WindowInvalidation,
  19};
  20use anyhow::{anyhow, bail, Result};
  21use collections::{HashMap, HashSet};
  22use pathfinder_geometry::vector::{vec2f, Vector2F};
  23use postage::oneshot;
  24use serde_json::json;
  25use smallvec::SmallVec;
  26use sqlez::{
  27    bindable::{Bind, Column, StaticColumnCount},
  28    statement::Statement,
  29};
  30use std::{
  31    any::TypeId,
  32    mem,
  33    ops::{Deref, DerefMut, Range},
  34};
  35use util::ResultExt;
  36use uuid::Uuid;
  37
  38use super::{Reference, ViewMetadata};
  39
  40pub struct Window {
  41    pub(crate) root_view: Option<AnyViewHandle>,
  42    pub(crate) focused_view_id: Option<usize>,
  43    pub(crate) parents: HashMap<usize, usize>,
  44    pub(crate) is_active: bool,
  45    pub(crate) is_fullscreen: bool,
  46    pub(crate) invalidation: Option<WindowInvalidation>,
  47    pub(crate) platform_window: Box<dyn platform::Window>,
  48    pub(crate) rendered_views: HashMap<usize, Box<dyn AnyRootElement>>,
  49    titlebar_height: f32,
  50    appearance: Appearance,
  51    cursor_regions: Vec<CursorRegion>,
  52    mouse_regions: Vec<(MouseRegion, usize)>,
  53    last_mouse_moved_event: Option<Event>,
  54    pub(crate) hovered_region_ids: Vec<MouseRegionId>,
  55    pub(crate) clicked_region_ids: Vec<MouseRegionId>,
  56    pub(crate) clicked_region: Option<(MouseRegionId, MouseButton)>,
  57    mouse_position: Vector2F,
  58    text_layout_cache: TextLayoutCache,
  59}
  60
  61impl Window {
  62    pub fn new<V, F>(
  63        window_id: usize,
  64        platform_window: Box<dyn platform::Window>,
  65        cx: &mut AppContext,
  66        build_view: F,
  67    ) -> Self
  68    where
  69        F: FnOnce(&mut ViewContext<V>) -> V,
  70        V: View,
  71    {
  72        let titlebar_height = platform_window.titlebar_height();
  73        let appearance = platform_window.appearance();
  74        let mut window = Self {
  75            root_view: None,
  76            focused_view_id: None,
  77            parents: Default::default(),
  78            is_active: false,
  79            invalidation: None,
  80            is_fullscreen: false,
  81            platform_window,
  82            rendered_views: Default::default(),
  83            cursor_regions: Default::default(),
  84            mouse_regions: Default::default(),
  85            text_layout_cache: TextLayoutCache::new(cx.font_system.clone()),
  86            last_mouse_moved_event: None,
  87            hovered_region_ids: Default::default(),
  88            clicked_region_ids: Default::default(),
  89            clicked_region: None,
  90            mouse_position: vec2f(0., 0.),
  91            titlebar_height,
  92            appearance,
  93        };
  94
  95        let mut window_context = WindowContext::mutable(cx, &mut window, window_id);
  96        let root_view = window_context.add_view(|cx| build_view(cx));
  97        if let Some(invalidation) = window_context.window.invalidation.take() {
  98            window_context.invalidate(invalidation, appearance);
  99        }
 100        window.focused_view_id = Some(root_view.id());
 101        window.root_view = Some(root_view.into_any());
 102        window
 103    }
 104
 105    pub fn root_view(&self) -> &AnyViewHandle {
 106        &self
 107            .root_view
 108            .as_ref()
 109            .expect("root_view called during window construction")
 110    }
 111}
 112
 113pub struct WindowContext<'a> {
 114    pub(crate) app_context: Reference<'a, AppContext>,
 115    pub(crate) window: Reference<'a, Window>,
 116    pub(crate) window_id: usize,
 117    pub(crate) removed: bool,
 118}
 119
 120impl Deref for WindowContext<'_> {
 121    type Target = AppContext;
 122
 123    fn deref(&self) -> &Self::Target {
 124        &self.app_context
 125    }
 126}
 127
 128impl DerefMut for WindowContext<'_> {
 129    fn deref_mut(&mut self) -> &mut Self::Target {
 130        &mut self.app_context
 131    }
 132}
 133
 134impl BorrowAppContext for WindowContext<'_> {
 135    fn read_with<T, F: FnOnce(&AppContext) -> T>(&self, f: F) -> T {
 136        self.app_context.read_with(f)
 137    }
 138
 139    fn update<T, F: FnOnce(&mut AppContext) -> T>(&mut self, f: F) -> T {
 140        self.app_context.update(f)
 141    }
 142}
 143
 144impl BorrowWindowContext for WindowContext<'_> {
 145    fn read_with<T, F: FnOnce(&WindowContext) -> T>(&self, window_id: usize, f: F) -> T {
 146        if self.window_id == window_id {
 147            f(self)
 148        } else {
 149            panic!("read_with called with id of window that does not belong to this context")
 150        }
 151    }
 152
 153    fn update<T, F: FnOnce(&mut WindowContext) -> T>(&mut self, window_id: usize, f: F) -> T {
 154        if self.window_id == window_id {
 155            f(self)
 156        } else {
 157            panic!("update called with id of window that does not belong to this context")
 158        }
 159    }
 160}
 161
 162impl<'a> WindowContext<'a> {
 163    pub fn mutable(
 164        app_context: &'a mut AppContext,
 165        window: &'a mut Window,
 166        window_id: usize,
 167    ) -> Self {
 168        Self {
 169            app_context: Reference::Mutable(app_context),
 170            window: Reference::Mutable(window),
 171            window_id,
 172            removed: false,
 173        }
 174    }
 175
 176    pub fn immutable(app_context: &'a AppContext, window: &'a Window, window_id: usize) -> Self {
 177        Self {
 178            app_context: Reference::Immutable(app_context),
 179            window: Reference::Immutable(window),
 180            window_id,
 181            removed: false,
 182        }
 183    }
 184
 185    pub fn remove_window(&mut self) {
 186        self.removed = true;
 187    }
 188
 189    pub fn window_id(&self) -> usize {
 190        self.window_id
 191    }
 192
 193    pub fn app_context(&mut self) -> &mut AppContext {
 194        &mut self.app_context
 195    }
 196
 197    pub fn root_view(&self) -> &AnyViewHandle {
 198        self.window.root_view()
 199    }
 200
 201    pub fn window_size(&self) -> Vector2F {
 202        self.window.platform_window.content_size()
 203    }
 204
 205    pub fn text_layout_cache(&self) -> &TextLayoutCache {
 206        &self.window.text_layout_cache
 207    }
 208
 209    pub(crate) fn update_any_view<F, T>(&mut self, view_id: usize, f: F) -> Option<T>
 210    where
 211        F: FnOnce(&mut dyn AnyView, &mut Self) -> T,
 212    {
 213        let window_id = self.window_id;
 214        let mut view = self.views.remove(&(window_id, view_id))?;
 215        let result = f(view.as_mut(), self);
 216        self.views.insert((window_id, view_id), view);
 217        Some(result)
 218    }
 219
 220    pub(crate) fn update_view<T, S>(
 221        &mut self,
 222        handle: &ViewHandle<T>,
 223        update: &mut dyn FnMut(&mut T, &mut ViewContext<T>) -> S,
 224    ) -> S
 225    where
 226        T: View,
 227    {
 228        self.update_any_view(handle.view_id, |view, cx| {
 229            let mut cx = ViewContext::mutable(cx, handle.view_id);
 230            update(
 231                view.as_any_mut()
 232                    .downcast_mut()
 233                    .expect("downcast is type safe"),
 234                &mut cx,
 235            )
 236        })
 237        .expect("view is already on the stack")
 238    }
 239
 240    pub fn defer(&mut self, callback: impl 'static + FnOnce(&mut WindowContext)) {
 241        let window_id = self.window_id;
 242        self.app_context.defer(move |cx| {
 243            cx.update_window(window_id, |cx| callback(cx));
 244        })
 245    }
 246
 247    pub fn update_global<T, F, U>(&mut self, update: F) -> U
 248    where
 249        T: 'static,
 250        F: FnOnce(&mut T, &mut Self) -> U,
 251    {
 252        AppContext::update_global_internal(self, |global, cx| update(global, cx))
 253    }
 254
 255    pub fn update_default_global<T, F, U>(&mut self, update: F) -> U
 256    where
 257        T: 'static + Default,
 258        F: FnOnce(&mut T, &mut Self) -> U,
 259    {
 260        AppContext::update_default_global_internal(self, |global, cx| update(global, cx))
 261    }
 262
 263    pub fn subscribe<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 264    where
 265        E: Entity,
 266        E::Event: 'static,
 267        H: Handle<E>,
 268        F: 'static + FnMut(H, &E::Event, &mut WindowContext),
 269    {
 270        self.subscribe_internal(handle, move |emitter, event, cx| {
 271            callback(emitter, event, cx);
 272            true
 273        })
 274    }
 275
 276    pub fn subscribe_internal<E, H, F>(&mut self, handle: &H, mut callback: F) -> Subscription
 277    where
 278        E: Entity,
 279        E::Event: 'static,
 280        H: Handle<E>,
 281        F: 'static + FnMut(H, &E::Event, &mut WindowContext) -> bool,
 282    {
 283        let window_id = self.window_id;
 284        self.app_context
 285            .subscribe_internal(handle, move |emitter, event, cx| {
 286                cx.update_window(window_id, |cx| callback(emitter, event, cx))
 287                    .unwrap_or(false)
 288            })
 289    }
 290
 291    pub(crate) fn observe_window_activation<F>(&mut self, callback: F) -> Subscription
 292    where
 293        F: 'static + FnMut(bool, &mut WindowContext) -> bool,
 294    {
 295        let window_id = self.window_id;
 296        let subscription_id = post_inc(&mut self.next_subscription_id);
 297        self.pending_effects
 298            .push_back(Effect::WindowActivationObservation {
 299                window_id,
 300                subscription_id,
 301                callback: Box::new(callback),
 302            });
 303        Subscription::WindowActivationObservation(
 304            self.window_activation_observations
 305                .subscribe(window_id, subscription_id),
 306        )
 307    }
 308
 309    pub(crate) fn observe_fullscreen<F>(&mut self, callback: F) -> Subscription
 310    where
 311        F: 'static + FnMut(bool, &mut WindowContext) -> bool,
 312    {
 313        let window_id = self.window_id;
 314        let subscription_id = post_inc(&mut self.next_subscription_id);
 315        self.pending_effects
 316            .push_back(Effect::WindowFullscreenObservation {
 317                window_id,
 318                subscription_id,
 319                callback: Box::new(callback),
 320            });
 321        Subscription::WindowActivationObservation(
 322            self.window_activation_observations
 323                .subscribe(window_id, subscription_id),
 324        )
 325    }
 326
 327    pub(crate) fn observe_window_bounds<F>(&mut self, callback: F) -> Subscription
 328    where
 329        F: 'static + FnMut(WindowBounds, Uuid, &mut WindowContext) -> bool,
 330    {
 331        let window_id = self.window_id;
 332        let subscription_id = post_inc(&mut self.next_subscription_id);
 333        self.pending_effects
 334            .push_back(Effect::WindowBoundsObservation {
 335                window_id,
 336                subscription_id,
 337                callback: Box::new(callback),
 338            });
 339        Subscription::WindowBoundsObservation(
 340            self.window_bounds_observations
 341                .subscribe(window_id, subscription_id),
 342        )
 343    }
 344
 345    pub fn observe_keystrokes<F>(&mut self, callback: F) -> Subscription
 346    where
 347        F: 'static
 348            + FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut WindowContext) -> bool,
 349    {
 350        let window_id = self.window_id;
 351        let subscription_id = post_inc(&mut self.next_subscription_id);
 352        self.keystroke_observations
 353            .add_callback(window_id, subscription_id, Box::new(callback));
 354        Subscription::KeystrokeObservation(
 355            self.keystroke_observations
 356                .subscribe(window_id, subscription_id),
 357        )
 358    }
 359
 360    pub(crate) fn available_actions(
 361        &self,
 362        view_id: usize,
 363    ) -> Vec<(&'static str, Box<dyn Action>, SmallVec<[Binding; 1]>)> {
 364        let window_id = self.window_id;
 365        let mut contexts = Vec::new();
 366        let mut handler_depths_by_action_id = HashMap::<TypeId, usize>::default();
 367        for (depth, view_id) in self.ancestors(view_id).enumerate() {
 368            if let Some(view_metadata) = self.views_metadata.get(&(window_id, view_id)) {
 369                contexts.push(view_metadata.keymap_context.clone());
 370                if let Some(actions) = self.actions.get(&view_metadata.type_id) {
 371                    handler_depths_by_action_id
 372                        .extend(actions.keys().copied().map(|action_id| (action_id, depth)));
 373                }
 374            } else {
 375                log::error!(
 376                    "view {} not found when computing available actions",
 377                    view_id
 378                );
 379            }
 380        }
 381
 382        handler_depths_by_action_id.extend(
 383            self.global_actions
 384                .keys()
 385                .copied()
 386                .map(|action_id| (action_id, contexts.len())),
 387        );
 388
 389        self.action_deserializers
 390            .iter()
 391            .filter_map(move |(name, (action_id, deserialize))| {
 392                if let Some(action_depth) = handler_depths_by_action_id.get(action_id).copied() {
 393                    let action = deserialize(serde_json::Value::Object(Default::default())).ok()?;
 394                    let bindings = self
 395                        .keystroke_matcher
 396                        .bindings_for_action(*action_id)
 397                        .filter(|b| {
 398                            action.eq(b.action())
 399                                && (0..=action_depth)
 400                                    .any(|depth| b.match_context(&contexts[depth..]))
 401                        })
 402                        .cloned()
 403                        .collect();
 404                    Some((*name, action, bindings))
 405                } else {
 406                    None
 407                }
 408            })
 409            .collect()
 410    }
 411
 412    pub(crate) fn dispatch_keystroke(&mut self, keystroke: &Keystroke) -> bool {
 413        let window_id = self.window_id;
 414        if let Some(focused_view_id) = self.focused_view_id() {
 415            let dispatch_path = self
 416                .ancestors(focused_view_id)
 417                .filter_map(|view_id| {
 418                    self.views_metadata
 419                        .get(&(window_id, view_id))
 420                        .map(|view| (view_id, view.keymap_context.clone()))
 421                })
 422                .collect();
 423
 424            let match_result = self
 425                .keystroke_matcher
 426                .push_keystroke(keystroke.clone(), dispatch_path);
 427            let mut handled_by = None;
 428
 429            let keystroke_handled = match &match_result {
 430                MatchResult::None => false,
 431                MatchResult::Pending => true,
 432                MatchResult::Matches(matches) => {
 433                    for (view_id, action) in matches {
 434                        if self.dispatch_action(Some(*view_id), action.as_ref()) {
 435                            self.keystroke_matcher.clear_pending();
 436                            handled_by = Some(action.boxed_clone());
 437                            break;
 438                        }
 439                    }
 440                    handled_by.is_some()
 441                }
 442            };
 443
 444            self.keystroke(
 445                window_id,
 446                keystroke.clone(),
 447                handled_by,
 448                match_result.clone(),
 449            );
 450            keystroke_handled
 451        } else {
 452            self.keystroke(window_id, keystroke.clone(), None, MatchResult::None);
 453            false
 454        }
 455    }
 456
 457    pub(crate) fn dispatch_event(&mut self, event: Event, event_reused: bool) -> bool {
 458        let mut mouse_events = SmallVec::<[_; 2]>::new();
 459        let mut notified_views: HashSet<usize> = Default::default();
 460        let window_id = self.window_id;
 461
 462        // 1. Handle platform event. Keyboard events get dispatched immediately, while mouse events
 463        //    get mapped into the mouse-specific MouseEvent type.
 464        //  -> These are usually small: [Mouse Down] or [Mouse up, Click] or [Mouse Moved, Mouse Dragged?]
 465        //  -> Also updates mouse-related state
 466        match &event {
 467            Event::KeyDown(e) => return self.dispatch_key_down(e),
 468
 469            Event::KeyUp(e) => return self.dispatch_key_up(e),
 470
 471            Event::ModifiersChanged(e) => return self.dispatch_modifiers_changed(e),
 472
 473            Event::MouseDown(e) => {
 474                // Click events are weird because they can be fired after a drag event.
 475                // MDN says that browsers handle this by starting from 'the most
 476                // specific ancestor element that contained both [positions]'
 477                // So we need to store the overlapping regions on mouse down.
 478
 479                // If there is already region being clicked, don't replace it.
 480                if self.window.clicked_region.is_none() {
 481                    self.window.clicked_region_ids = self
 482                        .window
 483                        .mouse_regions
 484                        .iter()
 485                        .filter_map(|(region, _)| {
 486                            if region.bounds.contains_point(e.position) {
 487                                Some(region.id())
 488                            } else {
 489                                None
 490                            }
 491                        })
 492                        .collect();
 493
 494                    let mut highest_z_index = 0;
 495                    let mut clicked_region_id = None;
 496                    for (region, z_index) in self.window.mouse_regions.iter() {
 497                        if region.bounds.contains_point(e.position) && *z_index >= highest_z_index {
 498                            highest_z_index = *z_index;
 499                            clicked_region_id = Some(region.id());
 500                        }
 501                    }
 502
 503                    self.window.clicked_region =
 504                        clicked_region_id.map(|region_id| (region_id, e.button));
 505                }
 506
 507                mouse_events.push(MouseEvent::Down(MouseDown {
 508                    region: Default::default(),
 509                    platform_event: e.clone(),
 510                }));
 511                mouse_events.push(MouseEvent::DownOut(MouseDownOut {
 512                    region: Default::default(),
 513                    platform_event: e.clone(),
 514                }));
 515            }
 516
 517            Event::MouseUp(e) => {
 518                // NOTE: The order of event pushes is important! MouseUp events MUST be fired
 519                // before click events, and so the MouseUp events need to be pushed before
 520                // MouseClick events.
 521
 522                // Synthesize one last drag event to end the drag
 523                mouse_events.push(MouseEvent::Drag(MouseDrag {
 524                    region: Default::default(),
 525                    prev_mouse_position: self.window.mouse_position,
 526                    platform_event: MouseMovedEvent {
 527                        position: e.position,
 528                        pressed_button: Some(e.button),
 529                        modifiers: e.modifiers,
 530                    },
 531                    end: true,
 532                }));
 533                mouse_events.push(MouseEvent::Up(MouseUp {
 534                    region: Default::default(),
 535                    platform_event: e.clone(),
 536                }));
 537                mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 538                    region: Default::default(),
 539                    platform_event: e.clone(),
 540                }));
 541                mouse_events.push(MouseEvent::Click(MouseClick {
 542                    region: Default::default(),
 543                    platform_event: e.clone(),
 544                }));
 545                mouse_events.push(MouseEvent::ClickOut(MouseClickOut {
 546                    region: Default::default(),
 547                    platform_event: e.clone(),
 548                }));
 549            }
 550
 551            Event::MouseMoved(
 552                e @ MouseMovedEvent {
 553                    position,
 554                    pressed_button,
 555                    ..
 556                },
 557            ) => {
 558                let mut style_to_assign = CursorStyle::Arrow;
 559                for region in self.window.cursor_regions.iter().rev() {
 560                    if region.bounds.contains_point(*position) {
 561                        style_to_assign = region.style;
 562                        break;
 563                    }
 564                }
 565
 566                if self
 567                    .window
 568                    .platform_window
 569                    .is_topmost_for_position(*position)
 570                {
 571                    self.platform().set_cursor_style(style_to_assign);
 572                }
 573
 574                if !event_reused {
 575                    if pressed_button.is_some() {
 576                        mouse_events.push(MouseEvent::Drag(MouseDrag {
 577                            region: Default::default(),
 578                            prev_mouse_position: self.window.mouse_position,
 579                            platform_event: e.clone(),
 580                            end: false,
 581                        }));
 582                    } else if let Some((_, clicked_button)) = self.window.clicked_region {
 583                        mouse_events.push(MouseEvent::Drag(MouseDrag {
 584                            region: Default::default(),
 585                            prev_mouse_position: self.window.mouse_position,
 586                            platform_event: e.clone(),
 587                            end: true,
 588                        }));
 589
 590                        // Mouse up event happened outside the current window. Simulate mouse up button event
 591                        let button_event = e.to_button_event(clicked_button);
 592                        mouse_events.push(MouseEvent::Up(MouseUp {
 593                            region: Default::default(),
 594                            platform_event: button_event.clone(),
 595                        }));
 596                        mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 597                            region: Default::default(),
 598                            platform_event: button_event.clone(),
 599                        }));
 600                        mouse_events.push(MouseEvent::Click(MouseClick {
 601                            region: Default::default(),
 602                            platform_event: button_event.clone(),
 603                        }));
 604                    }
 605
 606                    mouse_events.push(MouseEvent::Move(MouseMove {
 607                        region: Default::default(),
 608                        platform_event: e.clone(),
 609                    }));
 610                }
 611
 612                mouse_events.push(MouseEvent::Hover(MouseHover {
 613                    region: Default::default(),
 614                    platform_event: e.clone(),
 615                    started: false,
 616                }));
 617                mouse_events.push(MouseEvent::MoveOut(MouseMoveOut {
 618                    region: Default::default(),
 619                }));
 620
 621                self.window.last_mouse_moved_event = Some(event.clone());
 622            }
 623
 624            Event::MouseExited(event) => {
 625                // When the platform sends a MouseExited event, synthesize
 626                // a MouseMoved event whose position is outside the window's
 627                // bounds so that hover and cursor state can be updated.
 628                return self.dispatch_event(
 629                    Event::MouseMoved(MouseMovedEvent {
 630                        position: event.position,
 631                        pressed_button: event.pressed_button,
 632                        modifiers: event.modifiers,
 633                    }),
 634                    event_reused,
 635                );
 636            }
 637
 638            Event::ScrollWheel(e) => mouse_events.push(MouseEvent::ScrollWheel(MouseScrollWheel {
 639                region: Default::default(),
 640                platform_event: e.clone(),
 641            })),
 642        }
 643
 644        if let Some(position) = event.position() {
 645            self.window.mouse_position = position;
 646        }
 647
 648        // 2. Dispatch mouse events on regions
 649        let mut any_event_handled = false;
 650        for mut mouse_event in mouse_events {
 651            let mut valid_regions = Vec::new();
 652
 653            // GPUI elements are arranged by z_index but sibling elements can register overlapping
 654            // mouse regions. As such, hover events are only fired on overlapping elements which
 655            // are at the same z-index as the topmost element which overlaps with the mouse.
 656            match &mouse_event {
 657                MouseEvent::Hover(_) => {
 658                    let mut highest_z_index = None;
 659                    let mouse_position = self.window.mouse_position.clone();
 660                    let window = &mut *self.window;
 661                    let prev_hovered_regions = mem::take(&mut window.hovered_region_ids);
 662                    for (region, z_index) in window.mouse_regions.iter().rev() {
 663                        // Allow mouse regions to appear transparent to hovers
 664                        if !region.hoverable {
 665                            continue;
 666                        }
 667
 668                        let contains_mouse = region.bounds.contains_point(mouse_position);
 669
 670                        if contains_mouse && highest_z_index.is_none() {
 671                            highest_z_index = Some(z_index);
 672                        }
 673
 674                        // This unwrap relies on short circuiting boolean expressions
 675                        // The right side of the && is only executed when contains_mouse
 676                        // is true, and we know above that when contains_mouse is true
 677                        // highest_z_index is set.
 678                        if contains_mouse && z_index == highest_z_index.unwrap() {
 679                            //Ensure that hover entrance events aren't sent twice
 680                            if let Err(ix) = window.hovered_region_ids.binary_search(&region.id()) {
 681                                window.hovered_region_ids.insert(ix, region.id());
 682                            }
 683                            // window.hovered_region_ids.insert(region.id());
 684                            if !prev_hovered_regions.contains(&region.id()) {
 685                                valid_regions.push(region.clone());
 686                                if region.notify_on_hover {
 687                                    notified_views.insert(region.id().view_id());
 688                                }
 689                            }
 690                        } else {
 691                            // Ensure that hover exit events aren't sent twice
 692                            if prev_hovered_regions.contains(&region.id()) {
 693                                valid_regions.push(region.clone());
 694                                if region.notify_on_hover {
 695                                    notified_views.insert(region.id().view_id());
 696                                }
 697                            }
 698                        }
 699                    }
 700                }
 701
 702                MouseEvent::Down(_) | MouseEvent::Up(_) => {
 703                    for (region, _) in self.window.mouse_regions.iter().rev() {
 704                        if region.bounds.contains_point(self.window.mouse_position) {
 705                            valid_regions.push(region.clone());
 706                            if region.notify_on_click {
 707                                notified_views.insert(region.id().view_id());
 708                            }
 709                        }
 710                    }
 711                }
 712
 713                MouseEvent::Click(e) => {
 714                    // Only raise click events if the released button is the same as the one stored
 715                    if self
 716                        .window
 717                        .clicked_region
 718                        .map(|(_, clicked_button)| clicked_button == e.button)
 719                        .unwrap_or(false)
 720                    {
 721                        // Clear clicked regions and clicked button
 722                        let clicked_region_ids = std::mem::replace(
 723                            &mut self.window.clicked_region_ids,
 724                            Default::default(),
 725                        );
 726                        self.window.clicked_region = None;
 727
 728                        // Find regions which still overlap with the mouse since the last MouseDown happened
 729                        for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 730                            if clicked_region_ids.contains(&mouse_region.id()) {
 731                                if mouse_region
 732                                    .bounds
 733                                    .contains_point(self.window.mouse_position)
 734                                {
 735                                    valid_regions.push(mouse_region.clone());
 736                                }
 737                            }
 738                        }
 739                    }
 740                }
 741
 742                MouseEvent::Drag(_) => {
 743                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 744                        if self.window.clicked_region_ids.contains(&mouse_region.id()) {
 745                            valid_regions.push(mouse_region.clone());
 746                        }
 747                    }
 748                }
 749
 750                MouseEvent::MoveOut(_)
 751                | MouseEvent::UpOut(_)
 752                | MouseEvent::DownOut(_)
 753                | MouseEvent::ClickOut(_) => {
 754                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 755                        // NOT contains
 756                        if !mouse_region
 757                            .bounds
 758                            .contains_point(self.window.mouse_position)
 759                        {
 760                            valid_regions.push(mouse_region.clone());
 761                        }
 762                    }
 763                }
 764
 765                _ => {
 766                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 767                        // Contains
 768                        if mouse_region
 769                            .bounds
 770                            .contains_point(self.window.mouse_position)
 771                        {
 772                            valid_regions.push(mouse_region.clone());
 773                        }
 774                    }
 775                }
 776            }
 777
 778            //3. Fire region events
 779            let hovered_region_ids = self.window.hovered_region_ids.clone();
 780            for valid_region in valid_regions.into_iter() {
 781                let mut handled = false;
 782                mouse_event.set_region(valid_region.bounds);
 783                if let MouseEvent::Hover(e) = &mut mouse_event {
 784                    e.started = hovered_region_ids.contains(&valid_region.id())
 785                }
 786                // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
 787                // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
 788                // This behavior can be overridden by adding a Down handler
 789                if let MouseEvent::Down(e) = &mouse_event {
 790                    let has_click = valid_region
 791                        .handlers
 792                        .contains(MouseEvent::click_disc(), Some(e.button));
 793                    let has_drag = valid_region
 794                        .handlers
 795                        .contains(MouseEvent::drag_disc(), Some(e.button));
 796                    let has_down = valid_region
 797                        .handlers
 798                        .contains(MouseEvent::down_disc(), Some(e.button));
 799                    if !has_down && (has_click || has_drag) {
 800                        handled = true;
 801                    }
 802                }
 803
 804                // `event_consumed` should only be true if there are any handlers for this event.
 805                let mut event_consumed = handled;
 806                if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
 807                    for callback in callbacks {
 808                        handled = true;
 809                        let view_id = valid_region.id().view_id();
 810                        self.update_any_view(view_id, |view, cx| {
 811                            handled = callback(mouse_event.clone(), view.as_any_mut(), cx, view_id);
 812                        });
 813                        event_consumed |= handled;
 814                        any_event_handled |= handled;
 815                    }
 816                }
 817
 818                any_event_handled |= handled;
 819
 820                // For bubbling events, if the event was handled, don't continue dispatching.
 821                // This only makes sense for local events which return false from is_capturable.
 822                if event_consumed && mouse_event.is_capturable() {
 823                    break;
 824                }
 825            }
 826        }
 827
 828        for view_id in notified_views {
 829            self.notify_view(window_id, view_id);
 830        }
 831
 832        any_event_handled
 833    }
 834
 835    pub(crate) fn dispatch_key_down(&mut self, event: &KeyDownEvent) -> bool {
 836        let window_id = self.window_id;
 837        if let Some(focused_view_id) = self.window.focused_view_id {
 838            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 839                if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
 840                    let handled = view.key_down(event, self, view_id);
 841                    self.views.insert((window_id, view_id), view);
 842                    if handled {
 843                        return true;
 844                    }
 845                } else {
 846                    log::error!("view {} does not exist", view_id)
 847                }
 848            }
 849        }
 850
 851        false
 852    }
 853
 854    pub(crate) fn dispatch_key_up(&mut self, event: &KeyUpEvent) -> bool {
 855        let window_id = self.window_id;
 856        if let Some(focused_view_id) = self.window.focused_view_id {
 857            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 858                if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
 859                    let handled = view.key_up(event, self, view_id);
 860                    self.views.insert((window_id, view_id), view);
 861                    if handled {
 862                        return true;
 863                    }
 864                } else {
 865                    log::error!("view {} does not exist", view_id)
 866                }
 867            }
 868        }
 869
 870        false
 871    }
 872
 873    pub(crate) fn dispatch_modifiers_changed(&mut self, event: &ModifiersChangedEvent) -> bool {
 874        let window_id = self.window_id;
 875        if let Some(focused_view_id) = self.window.focused_view_id {
 876            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 877                if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
 878                    let handled = view.modifiers_changed(event, self, view_id);
 879                    self.views.insert((window_id, view_id), view);
 880                    if handled {
 881                        return true;
 882                    }
 883                } else {
 884                    log::error!("view {} does not exist", view_id)
 885                }
 886            }
 887        }
 888
 889        false
 890    }
 891
 892    pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, appearance: Appearance) {
 893        self.start_frame();
 894        self.window.appearance = appearance;
 895        for view_id in &invalidation.removed {
 896            invalidation.updated.remove(view_id);
 897            self.window.rendered_views.remove(view_id);
 898        }
 899        for view_id in &invalidation.updated {
 900            let titlebar_height = self.window.titlebar_height;
 901            let element = self
 902                .render_view(RenderParams {
 903                    view_id: *view_id,
 904                    titlebar_height,
 905                    refreshing: false,
 906                    appearance,
 907                })
 908                .unwrap();
 909            self.window.rendered_views.insert(*view_id, element);
 910        }
 911    }
 912
 913    pub fn render_view(&mut self, params: RenderParams) -> Result<Box<dyn AnyRootElement>> {
 914        let window_id = self.window_id;
 915        let view_id = params.view_id;
 916        let mut view = self
 917            .views
 918            .remove(&(window_id, view_id))
 919            .ok_or_else(|| anyhow!("view not found"))?;
 920        let element = view.render(self, view_id);
 921        self.views.insert((window_id, view_id), view);
 922        Ok(element)
 923    }
 924
 925    pub(crate) fn layout(&mut self, refreshing: bool) -> Result<HashMap<usize, usize>> {
 926        let window_size = self.window.platform_window.content_size();
 927        let root_view_id = self.window.root_view().id();
 928        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
 929        let mut new_parents = HashMap::default();
 930        let mut views_to_notify_if_ancestors_change = HashMap::default();
 931        rendered_root.layout(
 932            SizeConstraint::strict(window_size),
 933            &mut new_parents,
 934            &mut views_to_notify_if_ancestors_change,
 935            refreshing,
 936            self,
 937        )?;
 938
 939        for (view_id, view_ids_to_notify) in views_to_notify_if_ancestors_change {
 940            let mut current_view_id = view_id;
 941            loop {
 942                let old_parent_id = self.window.parents.get(&current_view_id);
 943                let new_parent_id = new_parents.get(&current_view_id);
 944                if old_parent_id.is_none() && new_parent_id.is_none() {
 945                    break;
 946                } else if old_parent_id == new_parent_id {
 947                    current_view_id = *old_parent_id.unwrap();
 948                } else {
 949                    let window_id = self.window_id;
 950                    for view_id_to_notify in view_ids_to_notify {
 951                        self.notify_view(window_id, view_id_to_notify);
 952                    }
 953                    break;
 954                }
 955            }
 956        }
 957
 958        let old_parents = mem::replace(&mut self.window.parents, new_parents);
 959        self.window
 960            .rendered_views
 961            .insert(root_view_id, rendered_root);
 962        Ok(old_parents)
 963    }
 964
 965    pub(crate) fn paint(&mut self) -> Result<Scene> {
 966        let window_size = self.window.platform_window.content_size();
 967        let scale_factor = self.window.platform_window.scale_factor();
 968
 969        let root_view_id = self.window.root_view().id();
 970        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
 971
 972        let mut scene_builder = SceneBuilder::new(scale_factor);
 973        rendered_root.paint(
 974            &mut scene_builder,
 975            Vector2F::zero(),
 976            RectF::from_points(Vector2F::zero(), window_size),
 977            self,
 978        )?;
 979        self.window
 980            .rendered_views
 981            .insert(root_view_id, rendered_root);
 982
 983        self.window.text_layout_cache.finish_frame();
 984        let scene = scene_builder.build();
 985        self.window.cursor_regions = scene.cursor_regions();
 986        self.window.mouse_regions = scene.mouse_regions();
 987
 988        if self.window_is_active() {
 989            if let Some(event) = self.window.last_mouse_moved_event.clone() {
 990                self.dispatch_event(event, true);
 991            }
 992        }
 993
 994        Ok(scene)
 995    }
 996
 997    pub fn rect_for_text_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
 998        let focused_view_id = self.window.focused_view_id?;
 999        self.window
1000            .rendered_views
1001            .get(&focused_view_id)?
1002            .rect_for_text_range(range_utf16, self)
1003            .log_err()
1004            .flatten()
1005    }
1006
1007    pub fn set_window_title(&mut self, title: &str) {
1008        self.window.platform_window.set_title(title);
1009    }
1010
1011    pub fn set_window_edited(&mut self, edited: bool) {
1012        self.window.platform_window.set_edited(edited);
1013    }
1014
1015    pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
1016        self.window
1017            .platform_window
1018            .is_topmost_for_position(position)
1019    }
1020
1021    pub fn activate_window(&self) {
1022        self.window.platform_window.activate();
1023    }
1024
1025    pub fn window_is_active(&self) -> bool {
1026        self.window.is_active
1027    }
1028
1029    pub fn window_is_fullscreen(&self) -> bool {
1030        self.window.is_fullscreen
1031    }
1032
1033    pub(crate) fn dispatch_action(&mut self, view_id: Option<usize>, action: &dyn Action) -> bool {
1034        if let Some(view_id) = view_id {
1035            self.halt_action_dispatch = false;
1036            self.visit_dispatch_path(view_id, |view_id, capture_phase, cx| {
1037                cx.update_any_view(view_id, |view, cx| {
1038                    let type_id = view.as_any().type_id();
1039                    if let Some((name, mut handlers)) = cx
1040                        .actions_mut(capture_phase)
1041                        .get_mut(&type_id)
1042                        .and_then(|h| h.remove_entry(&action.id()))
1043                    {
1044                        for handler in handlers.iter_mut().rev() {
1045                            cx.halt_action_dispatch = true;
1046                            handler(view, action, cx, view_id);
1047                            if cx.halt_action_dispatch {
1048                                break;
1049                            }
1050                        }
1051                        cx.actions_mut(capture_phase)
1052                            .get_mut(&type_id)
1053                            .unwrap()
1054                            .insert(name, handlers);
1055                    }
1056                });
1057
1058                !cx.halt_action_dispatch
1059            });
1060        }
1061
1062        if !self.halt_action_dispatch {
1063            self.halt_action_dispatch = self.dispatch_global_action_any(action);
1064        }
1065
1066        self.pending_effects
1067            .push_back(Effect::ActionDispatchNotification {
1068                action_id: action.id(),
1069            });
1070        self.halt_action_dispatch
1071    }
1072
1073    /// Returns an iterator over all of the view ids from the passed view up to the root of the window
1074    /// Includes the passed view itself
1075    pub(crate) fn ancestors(&self, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1076        std::iter::once(view_id)
1077            .into_iter()
1078            .chain(std::iter::from_fn(move || {
1079                if let Some(parent_id) = self.window.parents.get(&view_id) {
1080                    view_id = *parent_id;
1081                    Some(view_id)
1082                } else {
1083                    None
1084                }
1085            }))
1086    }
1087
1088    // Traverses the parent tree. Walks down the tree toward the passed
1089    // view calling visit with true. Then walks back up the tree calling visit with false.
1090    // If `visit` returns false this function will immediately return.
1091    fn visit_dispatch_path(
1092        &mut self,
1093        view_id: usize,
1094        mut visit: impl FnMut(usize, bool, &mut WindowContext) -> bool,
1095    ) {
1096        // List of view ids from the leaf to the root of the window
1097        let path = self.ancestors(view_id).collect::<Vec<_>>();
1098
1099        // Walk down from the root to the leaf calling visit with capture_phase = true
1100        for view_id in path.iter().rev() {
1101            if !visit(*view_id, true, self) {
1102                return;
1103            }
1104        }
1105
1106        // Walk up from the leaf to the root calling visit with capture_phase = false
1107        for view_id in path.iter() {
1108            if !visit(*view_id, false, self) {
1109                return;
1110            }
1111        }
1112    }
1113
1114    pub fn focused_view_id(&self) -> Option<usize> {
1115        self.window.focused_view_id
1116    }
1117
1118    pub fn focus(&mut self, view_id: Option<usize>) {
1119        self.app_context.focus(self.window_id, view_id);
1120    }
1121
1122    pub fn window_bounds(&self) -> WindowBounds {
1123        self.window.platform_window.bounds()
1124    }
1125
1126    pub fn window_appearance(&self) -> Appearance {
1127        self.window.appearance
1128    }
1129
1130    pub fn window_display_uuid(&self) -> Option<Uuid> {
1131        self.window.platform_window.screen().display_uuid()
1132    }
1133
1134    pub fn show_character_palette(&self) {
1135        self.window.platform_window.show_character_palette();
1136    }
1137
1138    pub fn minimize_window(&self) {
1139        self.window.platform_window.minimize();
1140    }
1141
1142    pub fn zoom_window(&self) {
1143        self.window.platform_window.zoom();
1144    }
1145
1146    pub fn toggle_full_screen(&self) {
1147        self.window.platform_window.toggle_full_screen();
1148    }
1149
1150    pub fn prompt(
1151        &self,
1152        level: PromptLevel,
1153        msg: &str,
1154        answers: &[&str],
1155    ) -> oneshot::Receiver<usize> {
1156        self.window.platform_window.prompt(level, msg, answers)
1157    }
1158
1159    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
1160    where
1161        V: View,
1162        F: FnOnce(&mut ViewContext<V>) -> V,
1163    {
1164        let root_view = self.add_view(|cx| build_root_view(cx));
1165        self.window.root_view = Some(root_view.clone().into_any());
1166        self.window.focused_view_id = Some(root_view.id());
1167        root_view
1168    }
1169
1170    pub fn add_view<T, F>(&mut self, build_view: F) -> ViewHandle<T>
1171    where
1172        T: View,
1173        F: FnOnce(&mut ViewContext<T>) -> T,
1174    {
1175        self.add_option_view(|cx| Some(build_view(cx))).unwrap()
1176    }
1177
1178    pub fn add_option_view<T, F>(&mut self, build_view: F) -> Option<ViewHandle<T>>
1179    where
1180        T: View,
1181        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1182    {
1183        let window_id = self.window_id;
1184        let view_id = post_inc(&mut self.next_entity_id);
1185        let mut cx = ViewContext::mutable(self, view_id);
1186        let handle = if let Some(view) = build_view(&mut cx) {
1187            let mut keymap_context = KeymapContext::default();
1188            view.update_keymap_context(&mut keymap_context, cx.app_context());
1189            self.views_metadata.insert(
1190                (window_id, view_id),
1191                ViewMetadata {
1192                    type_id: TypeId::of::<T>(),
1193                    keymap_context,
1194                },
1195            );
1196            self.views.insert((window_id, view_id), Box::new(view));
1197            self.window
1198                .invalidation
1199                .get_or_insert_with(Default::default)
1200                .updated
1201                .insert(view_id);
1202            Some(ViewHandle::new(window_id, view_id, &self.ref_counts))
1203        } else {
1204            None
1205        };
1206        handle
1207    }
1208}
1209
1210pub struct RenderParams {
1211    pub view_id: usize,
1212    pub titlebar_height: f32,
1213    pub refreshing: bool,
1214    pub appearance: Appearance,
1215}
1216
1217#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1218pub enum Axis {
1219    #[default]
1220    Horizontal,
1221    Vertical,
1222}
1223
1224impl Axis {
1225    pub fn invert(self) -> Self {
1226        match self {
1227            Self::Horizontal => Self::Vertical,
1228            Self::Vertical => Self::Horizontal,
1229        }
1230    }
1231
1232    pub fn component(&self, point: Vector2F) -> f32 {
1233        match self {
1234            Self::Horizontal => point.x(),
1235            Self::Vertical => point.y(),
1236        }
1237    }
1238}
1239
1240impl ToJson for Axis {
1241    fn to_json(&self) -> serde_json::Value {
1242        match self {
1243            Axis::Horizontal => json!("horizontal"),
1244            Axis::Vertical => json!("vertical"),
1245        }
1246    }
1247}
1248
1249impl StaticColumnCount for Axis {}
1250impl Bind for Axis {
1251    fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1252        match self {
1253            Axis::Horizontal => "Horizontal",
1254            Axis::Vertical => "Vertical",
1255        }
1256        .bind(statement, start_index)
1257    }
1258}
1259
1260impl Column for Axis {
1261    fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1262        String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1263            Ok((
1264                match axis_text.as_str() {
1265                    "Horizontal" => Axis::Horizontal,
1266                    "Vertical" => Axis::Vertical,
1267                    _ => bail!("Stored serialized item kind is incorrect"),
1268                },
1269                next_index,
1270            ))
1271        })
1272    }
1273}
1274
1275pub trait Vector2FExt {
1276    fn along(self, axis: Axis) -> f32;
1277}
1278
1279impl Vector2FExt for Vector2F {
1280    fn along(self, axis: Axis) -> f32 {
1281        match axis {
1282            Axis::Horizontal => self.x(),
1283            Axis::Vertical => self.y(),
1284        }
1285    }
1286}
1287
1288pub trait RectFExt {
1289    fn length_along(self, axis: Axis) -> f32;
1290}
1291
1292impl RectFExt for RectF {
1293    fn length_along(self, axis: Axis) -> f32 {
1294        match axis {
1295            Axis::Horizontal => self.width(),
1296            Axis::Vertical => self.height(),
1297        }
1298    }
1299}
1300
1301#[derive(Copy, Clone, Debug)]
1302pub struct SizeConstraint {
1303    pub min: Vector2F,
1304    pub max: Vector2F,
1305}
1306
1307impl SizeConstraint {
1308    pub fn new(min: Vector2F, max: Vector2F) -> Self {
1309        Self { min, max }
1310    }
1311
1312    pub fn strict(size: Vector2F) -> Self {
1313        Self {
1314            min: size,
1315            max: size,
1316        }
1317    }
1318
1319    pub fn strict_along(axis: Axis, max: f32) -> Self {
1320        match axis {
1321            Axis::Horizontal => Self {
1322                min: vec2f(max, 0.0),
1323                max: vec2f(max, f32::INFINITY),
1324            },
1325            Axis::Vertical => Self {
1326                min: vec2f(0.0, max),
1327                max: vec2f(f32::INFINITY, max),
1328            },
1329        }
1330    }
1331
1332    pub fn max_along(&self, axis: Axis) -> f32 {
1333        match axis {
1334            Axis::Horizontal => self.max.x(),
1335            Axis::Vertical => self.max.y(),
1336        }
1337    }
1338
1339    pub fn min_along(&self, axis: Axis) -> f32 {
1340        match axis {
1341            Axis::Horizontal => self.min.x(),
1342            Axis::Vertical => self.min.y(),
1343        }
1344    }
1345
1346    pub fn constrain(&self, size: Vector2F) -> Vector2F {
1347        vec2f(
1348            size.x().min(self.max.x()).max(self.min.x()),
1349            size.y().min(self.max.y()).max(self.min.y()),
1350        )
1351    }
1352}
1353
1354impl Default for SizeConstraint {
1355    fn default() -> Self {
1356        SizeConstraint {
1357            min: Vector2F::zero(),
1358            max: Vector2F::splat(f32::INFINITY),
1359        }
1360    }
1361}
1362
1363impl ToJson for SizeConstraint {
1364    fn to_json(&self) -> serde_json::Value {
1365        json!({
1366            "min": self.min.to_json(),
1367            "max": self.max.to_json(),
1368        })
1369    }
1370}
1371
1372pub struct ChildView {
1373    view_id: usize,
1374    view_name: &'static str,
1375}
1376
1377impl ChildView {
1378    pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1379        let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
1380        Self {
1381            view_id: view.id(),
1382            view_name,
1383        }
1384    }
1385}
1386
1387impl<V: View> Element<V> for ChildView {
1388    type LayoutState = ();
1389    type PaintState = ();
1390
1391    fn layout(
1392        &mut self,
1393        constraint: SizeConstraint,
1394        _: &mut V,
1395        cx: &mut LayoutContext<V>,
1396    ) -> (Vector2F, Self::LayoutState) {
1397        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1398            cx.new_parents.insert(self.view_id, cx.view_id());
1399            let size = rendered_view
1400                .layout(
1401                    constraint,
1402                    cx.new_parents,
1403                    cx.views_to_notify_if_ancestors_change,
1404                    cx.refreshing,
1405                    cx.view_context,
1406                )
1407                .log_err()
1408                .unwrap_or(Vector2F::zero());
1409            cx.window.rendered_views.insert(self.view_id, rendered_view);
1410            (size, ())
1411        } else {
1412            log::error!(
1413                "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1414                self.view_id,
1415                self.view_name
1416            );
1417            (Vector2F::zero(), ())
1418        }
1419    }
1420
1421    fn paint(
1422        &mut self,
1423        scene: &mut SceneBuilder,
1424        bounds: RectF,
1425        visible_bounds: RectF,
1426        _: &mut Self::LayoutState,
1427        _: &mut V,
1428        cx: &mut ViewContext<V>,
1429    ) {
1430        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1431            rendered_view
1432                .paint(scene, bounds.origin(), visible_bounds, cx)
1433                .log_err();
1434            cx.window.rendered_views.insert(self.view_id, rendered_view);
1435        } else {
1436            log::error!(
1437                "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1438                self.view_id,
1439                self.view_name
1440            );
1441        }
1442    }
1443
1444    fn rect_for_text_range(
1445        &self,
1446        range_utf16: Range<usize>,
1447        _: RectF,
1448        _: RectF,
1449        _: &Self::LayoutState,
1450        _: &Self::PaintState,
1451        _: &V,
1452        cx: &ViewContext<V>,
1453    ) -> Option<RectF> {
1454        if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1455            rendered_view
1456                .rect_for_text_range(range_utf16, &cx.window_context)
1457                .log_err()
1458                .flatten()
1459        } else {
1460            log::error!(
1461                "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1462                self.view_id,
1463                self.view_name
1464            );
1465            None
1466        }
1467    }
1468
1469    fn debug(
1470        &self,
1471        bounds: RectF,
1472        _: &Self::LayoutState,
1473        _: &Self::PaintState,
1474        _: &V,
1475        cx: &ViewContext<V>,
1476    ) -> serde_json::Value {
1477        json!({
1478            "type": "ChildView",
1479            "bounds": bounds.to_json(),
1480            "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1481                element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1482            } else {
1483                json!(null)
1484            }
1485        })
1486    }
1487}