window.rs

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