window.rs

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