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: HashSet<MouseRegionId>,
  56    pub(crate) clicked_region_ids: HashSet<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                    for (region, z_index) in window.mouse_regions.iter().rev() {
 682                        // Allow mouse regions to appear transparent to hovers
 683                        if !region.hoverable {
 684                            continue;
 685                        }
 686
 687                        let contains_mouse = region.bounds.contains_point(mouse_position);
 688
 689                        if contains_mouse && highest_z_index.is_none() {
 690                            highest_z_index = Some(z_index);
 691                        }
 692
 693                        // This unwrap relies on short circuiting boolean expressions
 694                        // The right side of the && is only executed when contains_mouse
 695                        // is true, and we know above that when contains_mouse is true
 696                        // highest_z_index is set.
 697                        if contains_mouse && z_index == highest_z_index.unwrap() {
 698                            //Ensure that hover entrance events aren't sent twice
 699                            if window.hovered_region_ids.insert(region.id()) {
 700                                valid_regions.push(region.clone());
 701                                if region.notify_on_hover {
 702                                    notified_views.insert(region.id().view_id());
 703                                }
 704                            }
 705                        } else {
 706                            // Ensure that hover exit events aren't sent twice
 707                            if window.hovered_region_ids.remove(&region.id()) {
 708                                valid_regions.push(region.clone());
 709                                if region.notify_on_hover {
 710                                    notified_views.insert(region.id().view_id());
 711                                }
 712                            }
 713                        }
 714                    }
 715                }
 716
 717                MouseEvent::Down(_) | MouseEvent::Up(_) => {
 718                    for (region, _) in self.window.mouse_regions.iter().rev() {
 719                        if region.bounds.contains_point(self.window.mouse_position) {
 720                            valid_regions.push(region.clone());
 721                            if region.notify_on_click {
 722                                notified_views.insert(region.id().view_id());
 723                            }
 724                        }
 725                    }
 726                }
 727
 728                MouseEvent::Click(e) => {
 729                    // Only raise click events if the released button is the same as the one stored
 730                    if self
 731                        .window
 732                        .clicked_region
 733                        .map(|(_, clicked_button)| clicked_button == e.button)
 734                        .unwrap_or(false)
 735                    {
 736                        // Clear clicked regions and clicked button
 737                        let clicked_region_ids = std::mem::replace(
 738                            &mut self.window.clicked_region_ids,
 739                            Default::default(),
 740                        );
 741                        self.window.clicked_region = None;
 742
 743                        // Find regions which still overlap with the mouse since the last MouseDown happened
 744                        for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 745                            if clicked_region_ids.contains(&mouse_region.id()) {
 746                                if mouse_region
 747                                    .bounds
 748                                    .contains_point(self.window.mouse_position)
 749                                {
 750                                    valid_regions.push(mouse_region.clone());
 751                                }
 752                            }
 753                        }
 754                    }
 755                }
 756
 757                MouseEvent::Drag(_) => {
 758                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 759                        if self.window.clicked_region_ids.contains(&mouse_region.id()) {
 760                            valid_regions.push(mouse_region.clone());
 761                        }
 762                    }
 763                }
 764
 765                MouseEvent::MoveOut(_)
 766                | MouseEvent::UpOut(_)
 767                | MouseEvent::DownOut(_)
 768                | MouseEvent::ClickOut(_) => {
 769                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 770                        // NOT contains
 771                        if !mouse_region
 772                            .bounds
 773                            .contains_point(self.window.mouse_position)
 774                        {
 775                            valid_regions.push(mouse_region.clone());
 776                        }
 777                    }
 778                }
 779
 780                _ => {
 781                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 782                        // Contains
 783                        if mouse_region
 784                            .bounds
 785                            .contains_point(self.window.mouse_position)
 786                        {
 787                            valid_regions.push(mouse_region.clone());
 788                        }
 789                    }
 790                }
 791            }
 792
 793            //3. Fire region events
 794            let hovered_region_ids = self.window.hovered_region_ids.clone();
 795            for valid_region in valid_regions.into_iter() {
 796                let mut handled = false;
 797                mouse_event.set_region(valid_region.bounds);
 798                if let MouseEvent::Hover(e) = &mut mouse_event {
 799                    e.started = hovered_region_ids.contains(&valid_region.id())
 800                }
 801                // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
 802                // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
 803                // This behavior can be overridden by adding a Down handler
 804                if let MouseEvent::Down(e) = &mouse_event {
 805                    let has_click = valid_region
 806                        .handlers
 807                        .contains(MouseEvent::click_disc(), Some(e.button));
 808                    let has_drag = valid_region
 809                        .handlers
 810                        .contains(MouseEvent::drag_disc(), Some(e.button));
 811                    let has_down = valid_region
 812                        .handlers
 813                        .contains(MouseEvent::down_disc(), Some(e.button));
 814                    if !has_down && (has_click || has_drag) {
 815                        handled = true;
 816                    }
 817                }
 818
 819                // `event_consumed` should only be true if there are any handlers for this event.
 820                let mut event_consumed = handled;
 821                if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
 822                    for callback in callbacks {
 823                        handled = true;
 824                        let view_id = valid_region.id().view_id();
 825                        self.update_any_view(view_id, |view, cx| {
 826                            handled = callback(mouse_event.clone(), view.as_any_mut(), cx, view_id);
 827                        });
 828                        event_consumed |= handled;
 829                        any_event_handled |= handled;
 830                    }
 831                }
 832
 833                any_event_handled |= handled;
 834
 835                // For bubbling events, if the event was handled, don't continue dispatching.
 836                // This only makes sense for local events which return false from is_capturable.
 837                if event_consumed && mouse_event.is_capturable() {
 838                    break;
 839                }
 840            }
 841        }
 842
 843        for view_id in notified_views {
 844            self.notify_view(handle, view_id);
 845        }
 846
 847        any_event_handled
 848    }
 849
 850    pub(crate) fn dispatch_key_down(&mut self, event: &KeyDownEvent) -> bool {
 851        let handle = self.window_handle;
 852        if let Some(focused_view_id) = self.window.focused_view_id {
 853            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 854                if let Some(mut view) = self.views.remove(&(handle, view_id)) {
 855                    let handled = view.key_down(event, self, view_id);
 856                    self.views.insert((handle, view_id), view);
 857                    if handled {
 858                        return true;
 859                    }
 860                } else {
 861                    log::error!("view {} does not exist", view_id)
 862                }
 863            }
 864        }
 865
 866        false
 867    }
 868
 869    pub(crate) fn dispatch_key_up(&mut self, event: &KeyUpEvent) -> bool {
 870        let handle = self.window_handle;
 871        if let Some(focused_view_id) = self.window.focused_view_id {
 872            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 873                if let Some(mut view) = self.views.remove(&(handle, view_id)) {
 874                    let handled = view.key_up(event, self, view_id);
 875                    self.views.insert((handle, view_id), view);
 876                    if handled {
 877                        return true;
 878                    }
 879                } else {
 880                    log::error!("view {} does not exist", view_id)
 881                }
 882            }
 883        }
 884
 885        false
 886    }
 887
 888    pub(crate) fn dispatch_modifiers_changed(&mut self, event: &ModifiersChangedEvent) -> bool {
 889        let handle = self.window_handle;
 890        if let Some(focused_view_id) = self.window.focused_view_id {
 891            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 892                if let Some(mut view) = self.views.remove(&(handle, view_id)) {
 893                    let handled = view.modifiers_changed(event, self, view_id);
 894                    self.views.insert((handle, view_id), view);
 895                    if handled {
 896                        return true;
 897                    }
 898                } else {
 899                    log::error!("view {} does not exist", view_id)
 900                }
 901            }
 902        }
 903
 904        false
 905    }
 906
 907    pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, appearance: Appearance) {
 908        self.start_frame();
 909        self.window.appearance = appearance;
 910        for view_id in &invalidation.removed {
 911            invalidation.updated.remove(view_id);
 912            self.window.rendered_views.remove(view_id);
 913        }
 914        for view_id in &invalidation.updated {
 915            let titlebar_height = self.window.titlebar_height;
 916            let element = self
 917                .render_view(RenderParams {
 918                    view_id: *view_id,
 919                    titlebar_height,
 920                    refreshing: false,
 921                    appearance,
 922                })
 923                .unwrap();
 924            self.window.rendered_views.insert(*view_id, element);
 925        }
 926    }
 927
 928    pub fn render_view(&mut self, params: RenderParams) -> Result<Box<dyn AnyRootElement>> {
 929        let handle = self.window_handle;
 930        let view_id = params.view_id;
 931        let mut view = self
 932            .views
 933            .remove(&(handle, view_id))
 934            .ok_or_else(|| anyhow!("view not found"))?;
 935        let element = view.render(self, view_id);
 936        self.views.insert((handle, view_id), view);
 937        Ok(element)
 938    }
 939
 940    pub(crate) fn layout(&mut self, refreshing: bool) -> Result<HashMap<usize, usize>> {
 941        let window_size = self.window.platform_window.content_size();
 942        let root_view_id = self.window.root_view().id();
 943        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
 944        let mut new_parents = HashMap::default();
 945        let mut views_to_notify_if_ancestors_change = HashMap::default();
 946        rendered_root.layout(
 947            SizeConstraint::strict(window_size),
 948            &mut new_parents,
 949            &mut views_to_notify_if_ancestors_change,
 950            refreshing,
 951            self,
 952        )?;
 953
 954        for (view_id, view_ids_to_notify) in views_to_notify_if_ancestors_change {
 955            let mut current_view_id = view_id;
 956            loop {
 957                let old_parent_id = self.window.parents.get(&current_view_id);
 958                let new_parent_id = new_parents.get(&current_view_id);
 959                if old_parent_id.is_none() && new_parent_id.is_none() {
 960                    break;
 961                } else if old_parent_id == new_parent_id {
 962                    current_view_id = *old_parent_id.unwrap();
 963                } else {
 964                    let handle = self.window_handle;
 965                    for view_id_to_notify in view_ids_to_notify {
 966                        self.notify_view(handle, view_id_to_notify);
 967                    }
 968                    break;
 969                }
 970            }
 971        }
 972
 973        let old_parents = mem::replace(&mut self.window.parents, new_parents);
 974        self.window
 975            .rendered_views
 976            .insert(root_view_id, rendered_root);
 977        Ok(old_parents)
 978    }
 979
 980    pub(crate) fn paint(&mut self) -> Result<Scene> {
 981        let window_size = self.window.platform_window.content_size();
 982        let scale_factor = self.window.platform_window.scale_factor();
 983
 984        let root_view_id = self.window.root_view().id();
 985        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
 986
 987        let mut scene_builder = SceneBuilder::new(scale_factor);
 988        rendered_root.paint(
 989            &mut scene_builder,
 990            Vector2F::zero(),
 991            RectF::from_points(Vector2F::zero(), window_size),
 992            self,
 993        )?;
 994        self.window
 995            .rendered_views
 996            .insert(root_view_id, rendered_root);
 997
 998        self.window.text_layout_cache.finish_frame();
 999        let scene = scene_builder.build();
1000        self.window.cursor_regions = scene.cursor_regions();
1001        self.window.mouse_regions = scene.mouse_regions();
1002
1003        if self.window_is_active() {
1004            if let Some(event) = self.window.last_mouse_moved_event.clone() {
1005                self.dispatch_event(event, true);
1006            }
1007        }
1008
1009        Ok(scene)
1010    }
1011
1012    pub fn rect_for_text_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
1013        let focused_view_id = self.window.focused_view_id?;
1014        self.window
1015            .rendered_views
1016            .get(&focused_view_id)?
1017            .rect_for_text_range(range_utf16, self)
1018            .log_err()
1019            .flatten()
1020    }
1021
1022    pub fn set_window_title(&mut self, title: &str) {
1023        self.window.platform_window.set_title(title);
1024    }
1025
1026    pub fn set_window_edited(&mut self, edited: bool) {
1027        self.window.platform_window.set_edited(edited);
1028    }
1029
1030    pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
1031        self.window
1032            .platform_window
1033            .is_topmost_for_position(position)
1034    }
1035
1036    pub fn activate_window(&self) {
1037        self.window.platform_window.activate();
1038    }
1039
1040    pub fn window_is_active(&self) -> bool {
1041        self.window.is_active
1042    }
1043
1044    pub fn window_is_fullscreen(&self) -> bool {
1045        self.window.is_fullscreen
1046    }
1047
1048    pub(crate) fn dispatch_action(&mut self, view_id: Option<usize>, action: &dyn Action) -> bool {
1049        if let Some(view_id) = view_id {
1050            self.halt_action_dispatch = false;
1051            self.visit_dispatch_path(view_id, |view_id, capture_phase, cx| {
1052                cx.update_any_view(view_id, |view, cx| {
1053                    let type_id = view.as_any().type_id();
1054                    if let Some((name, mut handlers)) = cx
1055                        .actions_mut(capture_phase)
1056                        .get_mut(&type_id)
1057                        .and_then(|h| h.remove_entry(&action.id()))
1058                    {
1059                        for handler in handlers.iter_mut().rev() {
1060                            cx.halt_action_dispatch = true;
1061                            handler(view, action, cx, view_id);
1062                            if cx.halt_action_dispatch {
1063                                break;
1064                            }
1065                        }
1066                        cx.actions_mut(capture_phase)
1067                            .get_mut(&type_id)
1068                            .unwrap()
1069                            .insert(name, handlers);
1070                    }
1071                });
1072
1073                !cx.halt_action_dispatch
1074            });
1075        }
1076
1077        if !self.halt_action_dispatch {
1078            self.halt_action_dispatch = self.dispatch_global_action_any(action);
1079        }
1080
1081        self.pending_effects
1082            .push_back(Effect::ActionDispatchNotification {
1083                action_id: action.id(),
1084            });
1085        self.halt_action_dispatch
1086    }
1087
1088    /// Returns an iterator over all of the view ids from the passed view up to the root of the window
1089    /// Includes the passed view itself
1090    pub(crate) fn ancestors(&self, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1091        std::iter::once(view_id)
1092            .into_iter()
1093            .chain(std::iter::from_fn(move || {
1094                if let Some(parent_id) = self.window.parents.get(&view_id) {
1095                    view_id = *parent_id;
1096                    Some(view_id)
1097                } else {
1098                    None
1099                }
1100            }))
1101    }
1102
1103    // Traverses the parent tree. Walks down the tree toward the passed
1104    // view calling visit with true. Then walks back up the tree calling visit with false.
1105    // If `visit` returns false this function will immediately return.
1106    fn visit_dispatch_path(
1107        &mut self,
1108        view_id: usize,
1109        mut visit: impl FnMut(usize, bool, &mut WindowContext) -> bool,
1110    ) {
1111        // List of view ids from the leaf to the root of the window
1112        let path = self.ancestors(view_id).collect::<Vec<_>>();
1113
1114        // Walk down from the root to the leaf calling visit with capture_phase = true
1115        for view_id in path.iter().rev() {
1116            if !visit(*view_id, true, self) {
1117                return;
1118            }
1119        }
1120
1121        // Walk up from the leaf to the root calling visit with capture_phase = false
1122        for view_id in path.iter() {
1123            if !visit(*view_id, false, self) {
1124                return;
1125            }
1126        }
1127    }
1128
1129    pub fn focused_view_id(&self) -> Option<usize> {
1130        self.window.focused_view_id
1131    }
1132
1133    pub fn focus(&mut self, view_id: Option<usize>) {
1134        self.app_context.focus(self.window_handle, view_id);
1135    }
1136
1137    pub fn window_bounds(&self) -> WindowBounds {
1138        self.window.platform_window.bounds()
1139    }
1140
1141    pub fn window_appearance(&self) -> Appearance {
1142        self.window.appearance
1143    }
1144
1145    pub fn window_display_uuid(&self) -> Option<Uuid> {
1146        self.window.platform_window.screen().display_uuid()
1147    }
1148
1149    pub fn show_character_palette(&self) {
1150        self.window.platform_window.show_character_palette();
1151    }
1152
1153    pub fn minimize_window(&self) {
1154        self.window.platform_window.minimize();
1155    }
1156
1157    pub fn zoom_window(&self) {
1158        self.window.platform_window.zoom();
1159    }
1160
1161    pub fn toggle_full_screen(&self) {
1162        self.window.platform_window.toggle_full_screen();
1163    }
1164
1165    pub fn prompt(
1166        &self,
1167        level: PromptLevel,
1168        msg: &str,
1169        answers: &[&str],
1170    ) -> oneshot::Receiver<usize> {
1171        self.window.platform_window.prompt(level, msg, answers)
1172    }
1173
1174    pub fn add_view<T, F>(&mut self, build_view: F) -> ViewHandle<T>
1175    where
1176        T: View,
1177        F: FnOnce(&mut ViewContext<T>) -> T,
1178    {
1179        self.add_option_view(|cx| Some(build_view(cx))).unwrap()
1180    }
1181
1182    pub fn add_option_view<T, F>(&mut self, build_view: F) -> Option<ViewHandle<T>>
1183    where
1184        T: View,
1185        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1186    {
1187        let handle = self.window_handle;
1188        let view_id = post_inc(&mut self.next_id);
1189        let mut cx = ViewContext::mutable(self, view_id);
1190        let handle = if let Some(view) = build_view(&mut cx) {
1191            let mut keymap_context = KeymapContext::default();
1192            view.update_keymap_context(&mut keymap_context, cx.app_context());
1193            self.views_metadata.insert(
1194                (handle, view_id),
1195                ViewMetadata {
1196                    type_id: TypeId::of::<T>(),
1197                    keymap_context,
1198                },
1199            );
1200            self.views.insert((handle, view_id), Box::new(view));
1201            self.window
1202                .invalidation
1203                .get_or_insert_with(Default::default)
1204                .updated
1205                .insert(view_id);
1206            Some(ViewHandle::new(handle, view_id, &self.ref_counts))
1207        } else {
1208            None
1209        };
1210        handle
1211    }
1212}
1213
1214pub struct RenderParams {
1215    pub view_id: usize,
1216    pub titlebar_height: f32,
1217    pub refreshing: bool,
1218    pub appearance: Appearance,
1219}
1220
1221#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1222pub enum Axis {
1223    #[default]
1224    Horizontal,
1225    Vertical,
1226}
1227
1228impl Axis {
1229    pub fn invert(self) -> Self {
1230        match self {
1231            Self::Horizontal => Self::Vertical,
1232            Self::Vertical => Self::Horizontal,
1233        }
1234    }
1235
1236    pub fn component(&self, point: Vector2F) -> f32 {
1237        match self {
1238            Self::Horizontal => point.x(),
1239            Self::Vertical => point.y(),
1240        }
1241    }
1242}
1243
1244impl ToJson for Axis {
1245    fn to_json(&self) -> serde_json::Value {
1246        match self {
1247            Axis::Horizontal => json!("horizontal"),
1248            Axis::Vertical => json!("vertical"),
1249        }
1250    }
1251}
1252
1253impl StaticColumnCount for Axis {}
1254impl Bind for Axis {
1255    fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1256        match self {
1257            Axis::Horizontal => "Horizontal",
1258            Axis::Vertical => "Vertical",
1259        }
1260        .bind(statement, start_index)
1261    }
1262}
1263
1264impl Column for Axis {
1265    fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1266        String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1267            Ok((
1268                match axis_text.as_str() {
1269                    "Horizontal" => Axis::Horizontal,
1270                    "Vertical" => Axis::Vertical,
1271                    _ => bail!("Stored serialized item kind is incorrect"),
1272                },
1273                next_index,
1274            ))
1275        })
1276    }
1277}
1278
1279pub trait Vector2FExt {
1280    fn along(self, axis: Axis) -> f32;
1281}
1282
1283impl Vector2FExt for Vector2F {
1284    fn along(self, axis: Axis) -> f32 {
1285        match axis {
1286            Axis::Horizontal => self.x(),
1287            Axis::Vertical => self.y(),
1288        }
1289    }
1290}
1291
1292pub trait RectFExt {
1293    fn length_along(self, axis: Axis) -> f32;
1294}
1295
1296impl RectFExt for RectF {
1297    fn length_along(self, axis: Axis) -> f32 {
1298        match axis {
1299            Axis::Horizontal => self.width(),
1300            Axis::Vertical => self.height(),
1301        }
1302    }
1303}
1304
1305#[derive(Copy, Clone, Debug)]
1306pub struct SizeConstraint {
1307    pub min: Vector2F,
1308    pub max: Vector2F,
1309}
1310
1311impl SizeConstraint {
1312    pub fn new(min: Vector2F, max: Vector2F) -> Self {
1313        Self { min, max }
1314    }
1315
1316    pub fn strict(size: Vector2F) -> Self {
1317        Self {
1318            min: size,
1319            max: size,
1320        }
1321    }
1322
1323    pub fn strict_along(axis: Axis, max: f32) -> Self {
1324        match axis {
1325            Axis::Horizontal => Self {
1326                min: vec2f(max, 0.0),
1327                max: vec2f(max, f32::INFINITY),
1328            },
1329            Axis::Vertical => Self {
1330                min: vec2f(0.0, max),
1331                max: vec2f(f32::INFINITY, max),
1332            },
1333        }
1334    }
1335
1336    pub fn max_along(&self, axis: Axis) -> f32 {
1337        match axis {
1338            Axis::Horizontal => self.max.x(),
1339            Axis::Vertical => self.max.y(),
1340        }
1341    }
1342
1343    pub fn min_along(&self, axis: Axis) -> f32 {
1344        match axis {
1345            Axis::Horizontal => self.min.x(),
1346            Axis::Vertical => self.min.y(),
1347        }
1348    }
1349
1350    pub fn constrain(&self, size: Vector2F) -> Vector2F {
1351        vec2f(
1352            size.x().min(self.max.x()).max(self.min.x()),
1353            size.y().min(self.max.y()).max(self.min.y()),
1354        )
1355    }
1356}
1357
1358impl Default for SizeConstraint {
1359    fn default() -> Self {
1360        SizeConstraint {
1361            min: Vector2F::zero(),
1362            max: Vector2F::splat(f32::INFINITY),
1363        }
1364    }
1365}
1366
1367impl ToJson for SizeConstraint {
1368    fn to_json(&self) -> serde_json::Value {
1369        json!({
1370            "min": self.min.to_json(),
1371            "max": self.max.to_json(),
1372        })
1373    }
1374}
1375
1376pub struct ChildView {
1377    view_id: usize,
1378    view_name: &'static str,
1379}
1380
1381impl ChildView {
1382    pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1383        let view_name = cx.view_ui_name(view.window, view.id()).unwrap();
1384        Self {
1385            view_id: view.id(),
1386            view_name,
1387        }
1388    }
1389}
1390
1391impl<V: View> Element<V> for ChildView {
1392    type LayoutState = ();
1393    type PaintState = ();
1394
1395    fn layout(
1396        &mut self,
1397        constraint: SizeConstraint,
1398        _: &mut V,
1399        cx: &mut LayoutContext<V>,
1400    ) -> (Vector2F, Self::LayoutState) {
1401        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1402            cx.new_parents.insert(self.view_id, cx.view_id());
1403            let size = rendered_view
1404                .layout(
1405                    constraint,
1406                    cx.new_parents,
1407                    cx.views_to_notify_if_ancestors_change,
1408                    cx.refreshing,
1409                    cx.view_context,
1410                )
1411                .log_err()
1412                .unwrap_or(Vector2F::zero());
1413            cx.window.rendered_views.insert(self.view_id, rendered_view);
1414            (size, ())
1415        } else {
1416            log::error!(
1417                "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1418                self.view_id,
1419                self.view_name
1420            );
1421            (Vector2F::zero(), ())
1422        }
1423    }
1424
1425    fn paint(
1426        &mut self,
1427        scene: &mut SceneBuilder,
1428        bounds: RectF,
1429        visible_bounds: RectF,
1430        _: &mut Self::LayoutState,
1431        _: &mut V,
1432        cx: &mut PaintContext<V>,
1433    ) {
1434        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1435            rendered_view
1436                .paint(scene, bounds.origin(), visible_bounds, cx)
1437                .log_err();
1438            cx.window.rendered_views.insert(self.view_id, rendered_view);
1439        } else {
1440            log::error!(
1441                "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1442                self.view_id,
1443                self.view_name
1444            );
1445        }
1446    }
1447
1448    fn rect_for_text_range(
1449        &self,
1450        range_utf16: Range<usize>,
1451        _: RectF,
1452        _: RectF,
1453        _: &Self::LayoutState,
1454        _: &Self::PaintState,
1455        _: &V,
1456        cx: &ViewContext<V>,
1457    ) -> Option<RectF> {
1458        if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1459            rendered_view
1460                .rect_for_text_range(range_utf16, &cx.window_context)
1461                .log_err()
1462                .flatten()
1463        } else {
1464            log::error!(
1465                "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1466                self.view_id,
1467                self.view_name
1468            );
1469            None
1470        }
1471    }
1472
1473    fn debug(
1474        &self,
1475        bounds: RectF,
1476        _: &Self::LayoutState,
1477        _: &Self::PaintState,
1478        _: &V,
1479        cx: &ViewContext<V>,
1480    ) -> serde_json::Value {
1481        json!({
1482            "type": "ChildView",
1483            "bounds": bounds.to_json(),
1484            "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1485                element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1486            } else {
1487                json!(null)
1488            }
1489        })
1490    }
1491}