window.rs

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