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