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