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