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