window.rs

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