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