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