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