window.rs

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