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