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