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_new_event_handlers(&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_new_event_handlers(&mut self, event: &Event) {
 890        if let Some(mouse_event) = event.mouse_event() {
 891            let event_handlers = self.window.take_event_handlers();
 892            for event_handler in event_handlers.iter().rev() {
 893                if event_handler.event_type == mouse_event.type_id() {
 894                    (event_handler.handler)(mouse_event, self);
 895                }
 896            }
 897            self.window.event_handlers = event_handlers;
 898        }
 899    }
 900
 901    pub(crate) fn dispatch_key_down(&mut self, event: &KeyDownEvent) -> bool {
 902        let handle = self.window_handle;
 903        if let Some(focused_view_id) = self.window.focused_view_id {
 904            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 905                if let Some(mut view) = self.views.remove(&(handle, view_id)) {
 906                    let handled = view.key_down(event, self, view_id);
 907                    self.views.insert((handle, view_id), view);
 908                    if handled {
 909                        return true;
 910                    }
 911                } else {
 912                    log::error!("view {} does not exist", view_id)
 913                }
 914            }
 915        }
 916
 917        false
 918    }
 919
 920    pub(crate) fn dispatch_key_up(&mut self, event: &KeyUpEvent) -> bool {
 921        let handle = self.window_handle;
 922        if let Some(focused_view_id) = self.window.focused_view_id {
 923            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 924                if let Some(mut view) = self.views.remove(&(handle, view_id)) {
 925                    let handled = view.key_up(event, self, view_id);
 926                    self.views.insert((handle, view_id), view);
 927                    if handled {
 928                        return true;
 929                    }
 930                } else {
 931                    log::error!("view {} does not exist", view_id)
 932                }
 933            }
 934        }
 935
 936        false
 937    }
 938
 939    pub(crate) fn dispatch_modifiers_changed(&mut self, event: &ModifiersChangedEvent) -> bool {
 940        let handle = self.window_handle;
 941        if let Some(focused_view_id) = self.window.focused_view_id {
 942            for view_id in self.ancestors(focused_view_id).collect::<Vec<_>>() {
 943                if let Some(mut view) = self.views.remove(&(handle, view_id)) {
 944                    let handled = view.modifiers_changed(event, self, view_id);
 945                    self.views.insert((handle, view_id), view);
 946                    if handled {
 947                        return true;
 948                    }
 949                } else {
 950                    log::error!("view {} does not exist", view_id)
 951                }
 952            }
 953        }
 954
 955        false
 956    }
 957
 958    pub fn invalidate(&mut self, mut invalidation: WindowInvalidation, appearance: Appearance) {
 959        self.start_frame();
 960        self.window.appearance = appearance;
 961        for view_id in &invalidation.removed {
 962            invalidation.updated.remove(view_id);
 963            self.window.rendered_views.remove(view_id);
 964        }
 965        for view_id in &invalidation.updated {
 966            let titlebar_height = self.window.titlebar_height;
 967            let element = self
 968                .render_view(RenderParams {
 969                    view_id: *view_id,
 970                    titlebar_height,
 971                    refreshing: false,
 972                    appearance,
 973                })
 974                .unwrap();
 975            self.window.rendered_views.insert(*view_id, element);
 976        }
 977    }
 978
 979    pub fn render_view(&mut self, params: RenderParams) -> Result<Box<dyn AnyRootElement>> {
 980        let handle = self.window_handle;
 981        let view_id = params.view_id;
 982        let mut view = self
 983            .views
 984            .remove(&(handle, view_id))
 985            .ok_or_else(|| anyhow!("view not found"))?;
 986        let element = view.render(self, view_id);
 987        self.views.insert((handle, view_id), view);
 988        Ok(element)
 989    }
 990
 991    pub fn layout(&mut self, refreshing: bool) -> Result<HashMap<usize, usize>> {
 992        let window_size = self.window.platform_window.content_size();
 993        let root_view_id = self.window.root_view().id();
 994
 995        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
 996
 997        let mut new_parents = HashMap::default();
 998        let mut views_to_notify_if_ancestors_change = HashMap::default();
 999        rendered_root.layout(
1000            SizeConstraint::new(window_size, window_size),
1001            &mut new_parents,
1002            &mut views_to_notify_if_ancestors_change,
1003            refreshing,
1004            self,
1005        )?;
1006
1007        for (view_id, view_ids_to_notify) in views_to_notify_if_ancestors_change {
1008            let mut current_view_id = view_id;
1009            loop {
1010                let old_parent_id = self.window.parents.get(&current_view_id);
1011                let new_parent_id = new_parents.get(&current_view_id);
1012                if old_parent_id.is_none() && new_parent_id.is_none() {
1013                    break;
1014                } else if old_parent_id == new_parent_id {
1015                    current_view_id = *old_parent_id.unwrap();
1016                } else {
1017                    let handle = self.window_handle;
1018                    for view_id_to_notify in view_ids_to_notify {
1019                        self.notify_view(handle, view_id_to_notify);
1020                    }
1021                    break;
1022                }
1023            }
1024        }
1025
1026        let old_parents = mem::replace(&mut self.window.parents, new_parents);
1027        self.window
1028            .rendered_views
1029            .insert(root_view_id, rendered_root);
1030        Ok(old_parents)
1031    }
1032
1033    pub fn paint(&mut self) -> Result<Scene> {
1034        let window_size = self.window.platform_window.content_size();
1035        let scale_factor = self.window.platform_window.scale_factor();
1036
1037        let root_view_id = self.window.root_view().id();
1038        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
1039
1040        let mut scene_builder = SceneBuilder::new(scale_factor);
1041        rendered_root.paint(
1042            &mut scene_builder,
1043            Vector2F::zero(),
1044            RectF::from_points(Vector2F::zero(), window_size),
1045            self,
1046        )?;
1047        self.window
1048            .rendered_views
1049            .insert(root_view_id, rendered_root);
1050
1051        self.window.text_layout_cache.finish_frame();
1052        let mut scene = scene_builder.build();
1053        self.window.cursor_regions = scene.cursor_regions();
1054        self.window.mouse_regions = scene.mouse_regions();
1055        self.window.event_handlers = scene.take_event_handlers();
1056
1057        if self.window_is_active() {
1058            if let Some(event) = self.window.last_mouse_moved_event.clone() {
1059                self.dispatch_event(event, true);
1060            }
1061        }
1062
1063        Ok(scene)
1064    }
1065
1066    pub fn root_element(&self) -> &Box<dyn AnyRootElement> {
1067        let view_id = self.window.root_view().id();
1068        self.window.rendered_views.get(&view_id).unwrap()
1069    }
1070
1071    pub fn rect_for_text_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
1072        let focused_view_id = self.window.focused_view_id?;
1073        self.window
1074            .rendered_views
1075            .get(&focused_view_id)?
1076            .rect_for_text_range(range_utf16, self)
1077            .log_err()
1078            .flatten()
1079    }
1080
1081    pub fn set_window_title(&mut self, title: &str) {
1082        self.window.platform_window.set_title(title);
1083    }
1084
1085    pub fn set_window_edited(&mut self, edited: bool) {
1086        self.window.platform_window.set_edited(edited);
1087    }
1088
1089    pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
1090        self.window
1091            .platform_window
1092            .is_topmost_for_position(position)
1093    }
1094
1095    pub fn activate_window(&self) {
1096        self.window.platform_window.activate();
1097    }
1098
1099    pub fn window_is_active(&self) -> bool {
1100        self.window.is_active
1101    }
1102
1103    pub fn window_is_fullscreen(&self) -> bool {
1104        self.window.is_fullscreen
1105    }
1106
1107    pub(crate) fn dispatch_action(&mut self, view_id: Option<usize>, action: &dyn Action) -> bool {
1108        if let Some(view_id) = view_id {
1109            self.halt_action_dispatch = false;
1110            self.visit_dispatch_path(view_id, |view_id, capture_phase, cx| {
1111                cx.update_any_view(view_id, |view, cx| {
1112                    let type_id = view.as_any().type_id();
1113                    if let Some((name, mut handlers)) = cx
1114                        .actions_mut(capture_phase)
1115                        .get_mut(&type_id)
1116                        .and_then(|h| h.remove_entry(&action.id()))
1117                    {
1118                        for handler in handlers.iter_mut().rev() {
1119                            cx.halt_action_dispatch = true;
1120                            handler(view, action, cx, view_id);
1121                            if cx.halt_action_dispatch {
1122                                break;
1123                            }
1124                        }
1125                        cx.actions_mut(capture_phase)
1126                            .get_mut(&type_id)
1127                            .unwrap()
1128                            .insert(name, handlers);
1129                    }
1130                });
1131
1132                !cx.halt_action_dispatch
1133            });
1134        }
1135
1136        if !self.halt_action_dispatch {
1137            self.halt_action_dispatch = self.dispatch_global_action_any(action);
1138        }
1139
1140        self.pending_effects
1141            .push_back(Effect::ActionDispatchNotification {
1142                action_id: action.id(),
1143            });
1144        self.halt_action_dispatch
1145    }
1146
1147    /// Returns an iterator over all of the view ids from the passed view up to the root of the window
1148    /// Includes the passed view itself
1149    pub(crate) fn ancestors(&self, mut view_id: usize) -> impl Iterator<Item = usize> + '_ {
1150        std::iter::once(view_id)
1151            .into_iter()
1152            .chain(std::iter::from_fn(move || {
1153                if let Some(parent_id) = self.window.parents.get(&view_id) {
1154                    view_id = *parent_id;
1155                    Some(view_id)
1156                } else {
1157                    None
1158                }
1159            }))
1160    }
1161
1162    // Traverses the parent tree. Walks down the tree toward the passed
1163    // view calling visit with true. Then walks back up the tree calling visit with false.
1164    // If `visit` returns false this function will immediately return.
1165    fn visit_dispatch_path(
1166        &mut self,
1167        view_id: usize,
1168        mut visit: impl FnMut(usize, bool, &mut WindowContext) -> bool,
1169    ) {
1170        // List of view ids from the leaf to the root of the window
1171        let path = self.ancestors(view_id).collect::<Vec<_>>();
1172
1173        // Walk down from the root to the leaf calling visit with capture_phase = true
1174        for view_id in path.iter().rev() {
1175            if !visit(*view_id, true, self) {
1176                return;
1177            }
1178        }
1179
1180        // Walk up from the leaf to the root calling visit with capture_phase = false
1181        for view_id in path.iter() {
1182            if !visit(*view_id, false, self) {
1183                return;
1184            }
1185        }
1186    }
1187
1188    pub fn focused_view_id(&self) -> Option<usize> {
1189        self.window.focused_view_id
1190    }
1191
1192    pub fn focus(&mut self, view_id: Option<usize>) {
1193        self.app_context.focus(self.window_handle, view_id);
1194    }
1195
1196    pub fn window_bounds(&self) -> WindowBounds {
1197        self.window.platform_window.bounds()
1198    }
1199
1200    pub fn window_appearance(&self) -> Appearance {
1201        self.window.appearance
1202    }
1203
1204    pub fn window_display_uuid(&self) -> Option<Uuid> {
1205        self.window.platform_window.screen().display_uuid()
1206    }
1207
1208    pub fn show_character_palette(&self) {
1209        self.window.platform_window.show_character_palette();
1210    }
1211
1212    pub fn minimize_window(&self) {
1213        self.window.platform_window.minimize();
1214    }
1215
1216    pub fn zoom_window(&self) {
1217        self.window.platform_window.zoom();
1218    }
1219
1220    pub fn toggle_full_screen(&self) {
1221        self.window.platform_window.toggle_full_screen();
1222    }
1223
1224    pub fn prompt(
1225        &self,
1226        level: PromptLevel,
1227        msg: &str,
1228        answers: &[&str],
1229    ) -> oneshot::Receiver<usize> {
1230        self.window.platform_window.prompt(level, msg, answers)
1231    }
1232
1233    pub fn add_view<T, F>(&mut self, build_view: F) -> ViewHandle<T>
1234    where
1235        T: View,
1236        F: FnOnce(&mut ViewContext<T>) -> T,
1237    {
1238        self.add_option_view(|cx| Some(build_view(cx))).unwrap()
1239    }
1240
1241    pub fn add_option_view<T, F>(&mut self, build_view: F) -> Option<ViewHandle<T>>
1242    where
1243        T: View,
1244        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
1245    {
1246        let handle = self.window_handle;
1247        let view_id = post_inc(&mut self.next_id);
1248        let mut cx = ViewContext::mutable(self, view_id);
1249        let handle = if let Some(view) = build_view(&mut cx) {
1250            let mut keymap_context = KeymapContext::default();
1251            view.update_keymap_context(&mut keymap_context, cx.app_context());
1252            self.views_metadata.insert(
1253                (handle, view_id),
1254                ViewMetadata {
1255                    type_id: TypeId::of::<T>(),
1256                    keymap_context,
1257                },
1258            );
1259            self.views.insert((handle, view_id), Box::new(view));
1260            self.window
1261                .invalidation
1262                .get_or_insert_with(Default::default)
1263                .updated
1264                .insert(view_id);
1265            Some(ViewHandle::new(handle, view_id, &self.ref_counts))
1266        } else {
1267            None
1268        };
1269        handle
1270    }
1271}
1272
1273#[derive(Default)]
1274pub struct LayoutEngine(Taffy);
1275pub use taffy::style::Style as LayoutStyle;
1276
1277impl LayoutEngine {
1278    pub fn new() -> Self {
1279        Default::default()
1280    }
1281
1282    pub fn add_node<C>(&mut self, style: LayoutStyle, children: C) -> Result<LayoutId>
1283    where
1284        C: IntoIterator<Item = LayoutId>,
1285    {
1286        Ok(self
1287            .0
1288            .new_with_children(style, &children.into_iter().collect::<Vec<_>>())?)
1289    }
1290
1291    pub fn add_measured_node<F>(&mut self, style: LayoutStyle, measure: F) -> Result<LayoutId>
1292    where
1293        F: Fn(MeasureParams) -> Size<f32> + Sync + Send + 'static,
1294    {
1295        Ok(self
1296            .0
1297            .new_leaf_with_measure(style, MeasureFunc::Boxed(Box::new(MeasureFn(measure))))?)
1298    }
1299
1300    pub fn compute_layout(&mut self, root: LayoutId, available_space: Vector2F) -> Result<()> {
1301        self.0.compute_layout(
1302            root,
1303            taffy::geometry::Size {
1304                width: available_space.x().into(),
1305                height: available_space.y().into(),
1306            },
1307        )?;
1308        Ok(())
1309    }
1310
1311    pub fn computed_layout(&mut self, node: LayoutId) -> Result<EngineLayout> {
1312        Ok(self.0.layout(node)?.into())
1313    }
1314}
1315
1316pub struct MeasureFn<F>(F);
1317
1318impl<F: Send + Sync> Measurable for MeasureFn<F>
1319where
1320    F: Fn(MeasureParams) -> Size<f32>,
1321{
1322    fn measure(
1323        &self,
1324        known_dimensions: taffy::prelude::Size<Option<f32>>,
1325        available_space: taffy::prelude::Size<taffy::style::AvailableSpace>,
1326    ) -> taffy::prelude::Size<f32> {
1327        (self.0)(MeasureParams {
1328            known_dimensions: known_dimensions.into(),
1329            available_space: available_space.into(),
1330        })
1331        .into()
1332    }
1333}
1334
1335#[derive(Debug, Clone, Default)]
1336pub struct EngineLayout {
1337    pub bounds: RectF,
1338    pub order: u32,
1339}
1340
1341pub struct MeasureParams {
1342    pub known_dimensions: Size<Option<f32>>,
1343    pub available_space: Size<AvailableSpace>,
1344}
1345
1346#[derive(Clone)]
1347pub enum AvailableSpace {
1348    /// The amount of space available is the specified number of pixels
1349    Pixels(f32),
1350    /// The amount of space available is indefinite and the node should be laid out under a min-content constraint
1351    MinContent,
1352    /// The amount of space available is indefinite and the node should be laid out under a max-content constraint
1353    MaxContent,
1354}
1355
1356impl Default for AvailableSpace {
1357    fn default() -> Self {
1358        Self::Pixels(0.)
1359    }
1360}
1361
1362impl From<taffy::prelude::AvailableSpace> for AvailableSpace {
1363    fn from(value: taffy::prelude::AvailableSpace) -> Self {
1364        match value {
1365            taffy::prelude::AvailableSpace::Definite(pixels) => Self::Pixels(pixels),
1366            taffy::prelude::AvailableSpace::MinContent => Self::MinContent,
1367            taffy::prelude::AvailableSpace::MaxContent => Self::MaxContent,
1368        }
1369    }
1370}
1371
1372impl From<&taffy::tree::Layout> for EngineLayout {
1373    fn from(value: &taffy::tree::Layout) -> Self {
1374        Self {
1375            bounds: RectF::new(
1376                vec2f(value.location.x, value.location.y),
1377                vec2f(value.size.width, value.size.height),
1378            ),
1379            order: value.order,
1380        }
1381    }
1382}
1383
1384pub type LayoutId = taffy::prelude::NodeId;
1385
1386pub struct RenderParams {
1387    pub view_id: usize,
1388    pub titlebar_height: f32,
1389    pub refreshing: bool,
1390    pub appearance: Appearance,
1391}
1392
1393#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1394pub enum Axis {
1395    #[default]
1396    Horizontal,
1397    Vertical,
1398}
1399
1400impl Axis {
1401    pub fn invert(self) -> Self {
1402        match self {
1403            Self::Horizontal => Self::Vertical,
1404            Self::Vertical => Self::Horizontal,
1405        }
1406    }
1407
1408    pub fn component(&self, point: Vector2F) -> f32 {
1409        match self {
1410            Self::Horizontal => point.x(),
1411            Self::Vertical => point.y(),
1412        }
1413    }
1414}
1415
1416impl ToJson for Axis {
1417    fn to_json(&self) -> serde_json::Value {
1418        match self {
1419            Axis::Horizontal => json!("horizontal"),
1420            Axis::Vertical => json!("vertical"),
1421        }
1422    }
1423}
1424
1425impl StaticColumnCount for Axis {}
1426impl Bind for Axis {
1427    fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1428        match self {
1429            Axis::Horizontal => "Horizontal",
1430            Axis::Vertical => "Vertical",
1431        }
1432        .bind(statement, start_index)
1433    }
1434}
1435
1436impl Column for Axis {
1437    fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1438        String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1439            Ok((
1440                match axis_text.as_str() {
1441                    "Horizontal" => Axis::Horizontal,
1442                    "Vertical" => Axis::Vertical,
1443                    _ => bail!("Stored serialized item kind is incorrect"),
1444                },
1445                next_index,
1446            ))
1447        })
1448    }
1449}
1450
1451pub trait Vector2FExt {
1452    fn along(self, axis: Axis) -> f32;
1453}
1454
1455impl Vector2FExt for Vector2F {
1456    fn along(self, axis: Axis) -> f32 {
1457        match axis {
1458            Axis::Horizontal => self.x(),
1459            Axis::Vertical => self.y(),
1460        }
1461    }
1462}
1463
1464pub trait RectFExt {
1465    fn length_along(self, axis: Axis) -> f32;
1466}
1467
1468impl RectFExt for RectF {
1469    fn length_along(self, axis: Axis) -> f32 {
1470        match axis {
1471            Axis::Horizontal => self.width(),
1472            Axis::Vertical => self.height(),
1473        }
1474    }
1475}
1476
1477#[derive(Copy, Clone, Debug)]
1478pub struct SizeConstraint {
1479    pub min: Vector2F,
1480    pub max: Vector2F,
1481}
1482
1483impl SizeConstraint {
1484    pub fn new(min: Vector2F, max: Vector2F) -> Self {
1485        Self { min, max }
1486    }
1487
1488    pub fn strict(size: Vector2F) -> Self {
1489        Self {
1490            min: size,
1491            max: size,
1492        }
1493    }
1494    pub fn loose(max: Vector2F) -> Self {
1495        Self {
1496            min: Vector2F::zero(),
1497            max,
1498        }
1499    }
1500
1501    pub fn strict_along(axis: Axis, max: f32) -> Self {
1502        match axis {
1503            Axis::Horizontal => Self {
1504                min: vec2f(max, 0.0),
1505                max: vec2f(max, f32::INFINITY),
1506            },
1507            Axis::Vertical => Self {
1508                min: vec2f(0.0, max),
1509                max: vec2f(f32::INFINITY, max),
1510            },
1511        }
1512    }
1513
1514    pub fn max_along(&self, axis: Axis) -> f32 {
1515        match axis {
1516            Axis::Horizontal => self.max.x(),
1517            Axis::Vertical => self.max.y(),
1518        }
1519    }
1520
1521    pub fn min_along(&self, axis: Axis) -> f32 {
1522        match axis {
1523            Axis::Horizontal => self.min.x(),
1524            Axis::Vertical => self.min.y(),
1525        }
1526    }
1527
1528    pub fn constrain(&self, size: Vector2F) -> Vector2F {
1529        vec2f(
1530            size.x().min(self.max.x()).max(self.min.x()),
1531            size.y().min(self.max.y()).max(self.min.y()),
1532        )
1533    }
1534}
1535
1536impl Sub<Vector2F> for SizeConstraint {
1537    type Output = SizeConstraint;
1538
1539    fn sub(self, rhs: Vector2F) -> SizeConstraint {
1540        SizeConstraint {
1541            min: self.min - rhs,
1542            max: self.max - rhs,
1543        }
1544    }
1545}
1546
1547impl Default for SizeConstraint {
1548    fn default() -> Self {
1549        SizeConstraint {
1550            min: Vector2F::zero(),
1551            max: Vector2F::splat(f32::INFINITY),
1552        }
1553    }
1554}
1555
1556impl ToJson for SizeConstraint {
1557    fn to_json(&self) -> serde_json::Value {
1558        json!({
1559            "min": self.min.to_json(),
1560            "max": self.max.to_json(),
1561        })
1562    }
1563}
1564
1565#[derive(Clone)]
1566pub struct ChildView {
1567    view_id: usize,
1568    view_name: &'static str,
1569}
1570
1571impl ChildView {
1572    pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1573        let view_name = cx.view_ui_name(view.window, view.id()).unwrap();
1574        Self {
1575            view_id: view.id(),
1576            view_name,
1577        }
1578    }
1579}
1580
1581impl<V: 'static> Element<V> for ChildView {
1582    type LayoutState = ();
1583    type PaintState = ();
1584
1585    fn layout(
1586        &mut self,
1587        constraint: SizeConstraint,
1588        _: &mut V,
1589        cx: &mut LayoutContext<V>,
1590    ) -> (Vector2F, Self::LayoutState) {
1591        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1592            cx.new_parents.insert(self.view_id, cx.view_id());
1593            let size = rendered_view
1594                .layout(
1595                    constraint,
1596                    cx.new_parents,
1597                    cx.views_to_notify_if_ancestors_change,
1598                    cx.refreshing,
1599                    cx.view_context,
1600                )
1601                .log_err()
1602                .unwrap_or(Vector2F::zero());
1603            cx.window.rendered_views.insert(self.view_id, rendered_view);
1604            (size, ())
1605        } else {
1606            log::error!(
1607                "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1608                self.view_id,
1609                self.view_name
1610            );
1611            (Vector2F::zero(), ())
1612        }
1613    }
1614
1615    fn paint(
1616        &mut self,
1617        scene: &mut SceneBuilder,
1618        bounds: RectF,
1619        visible_bounds: RectF,
1620        _: &mut Self::LayoutState,
1621        _: &mut V,
1622        cx: &mut PaintContext<V>,
1623    ) {
1624        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1625            rendered_view
1626                .paint(scene, bounds.origin(), visible_bounds, cx)
1627                .log_err();
1628            cx.window.rendered_views.insert(self.view_id, rendered_view);
1629        } else {
1630            log::error!(
1631                "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1632                self.view_id,
1633                self.view_name
1634            );
1635        }
1636    }
1637
1638    fn rect_for_text_range(
1639        &self,
1640        range_utf16: Range<usize>,
1641        _: RectF,
1642        _: RectF,
1643        _: &Self::LayoutState,
1644        _: &Self::PaintState,
1645        _: &V,
1646        cx: &ViewContext<V>,
1647    ) -> Option<RectF> {
1648        if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1649            rendered_view
1650                .rect_for_text_range(range_utf16, &cx.window_context)
1651                .log_err()
1652                .flatten()
1653        } else {
1654            log::error!(
1655                "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1656                self.view_id,
1657                self.view_name
1658            );
1659            None
1660        }
1661    }
1662
1663    fn debug(
1664        &self,
1665        bounds: RectF,
1666        _: &Self::LayoutState,
1667        _: &Self::PaintState,
1668        _: &V,
1669        cx: &ViewContext<V>,
1670    ) -> serde_json::Value {
1671        json!({
1672            "type": "ChildView",
1673            "bounds": bounds.to_json(),
1674            "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1675                element.debug(&cx.window_context).log_err().unwrap_or_else(|| json!(null))
1676            } else {
1677                json!(null)
1678            }
1679        })
1680    }
1681}