window.rs

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