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