window.rs

   1use crate::{
   2    geometry::rect::RectF,
   3    json::{self, ToJson},
   4    keymap_matcher::{Keystroke, MatchResult},
   5    platform::{
   6        self, Appearance, CursorStyle, Event, KeyDownEvent, KeyUpEvent, ModifiersChangedEvent,
   7        MouseButton, MouseMovedEvent, PromptLevel, WindowBounds,
   8    },
   9    scene::{
  10        CursorRegion, MouseClick, MouseDown, MouseDownOut, MouseDrag, MouseEvent, MouseHover,
  11        MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut, Scene,
  12    },
  13    text_layout::TextLayoutCache,
  14    util::post_inc,
  15    AnyView, AnyViewHandle, AppContext, Element, ElementBox, Entity, ModelContext, ModelHandle,
  16    MouseRegion, MouseRegionId, ParentId, ReadView, RenderParams, SceneBuilder, UpdateModel, View,
  17    ViewContext, ViewHandle, WindowInvalidation,
  18};
  19use anyhow::bail;
  20use collections::{HashMap, HashSet};
  21use pathfinder_geometry::vector::{vec2f, Vector2F};
  22use postage::oneshot;
  23use serde_json::json;
  24use smallvec::SmallVec;
  25use sqlez::{
  26    bindable::{Bind, Column, StaticColumnCount},
  27    statement::Statement,
  28};
  29use std::ops::{Deref, DerefMut, Range};
  30use uuid::Uuid;
  31
  32pub struct Window {
  33    pub(crate) root_view: Option<AnyViewHandle>,
  34    pub(crate) focused_view_id: Option<usize>,
  35    pub(crate) is_active: bool,
  36    pub(crate) is_fullscreen: bool,
  37    pub(crate) invalidation: Option<WindowInvalidation>,
  38    pub(crate) platform_window: Box<dyn platform::Window>,
  39    pub(crate) rendered_views: HashMap<usize, Box<dyn RenderedView>>,
  40    titlebar_height: f32,
  41    appearance: Appearance,
  42    cursor_regions: Vec<CursorRegion>,
  43    mouse_regions: Vec<(MouseRegion, usize)>,
  44    last_mouse_moved_event: Option<Event>,
  45    pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
  46    pub(crate) clicked_region_ids: HashSet<MouseRegionId>,
  47    pub(crate) clicked_button: Option<MouseButton>,
  48    mouse_position: Vector2F,
  49    text_layout_cache: TextLayoutCache,
  50}
  51
  52impl Window {
  53    pub fn new<V, F>(
  54        window_id: usize,
  55        platform_window: Box<dyn platform::Window>,
  56        cx: &mut AppContext,
  57        build_view: F,
  58    ) -> Self
  59    where
  60        F: FnOnce(&mut ViewContext<V>) -> V,
  61        V: View,
  62    {
  63        let titlebar_height = platform_window.titlebar_height();
  64        let appearance = platform_window.appearance();
  65        let mut window = Self {
  66            root_view: None,
  67            focused_view_id: None,
  68            is_active: false,
  69            invalidation: None,
  70            is_fullscreen: false,
  71            platform_window,
  72            rendered_views: cx.render_views(window_id, titlebar_height, appearance),
  73            cursor_regions: Default::default(),
  74            mouse_regions: Default::default(),
  75            text_layout_cache: TextLayoutCache::new(cx.font_system.clone()),
  76            last_mouse_moved_event: None,
  77            hovered_region_ids: Default::default(),
  78            clicked_region_ids: Default::default(),
  79            clicked_button: None,
  80            mouse_position: vec2f(0., 0.),
  81            titlebar_height,
  82            appearance,
  83        };
  84
  85        let mut window_context = WindowContext::new(cx, &mut window, window_id);
  86        let root_view = window_context
  87            .build_and_insert_view(ParentId::Root, |cx| Some(build_view(cx)))
  88            .unwrap();
  89        window.focused_view_id = Some(root_view.id());
  90        window.root_view = Some(root_view.into_any());
  91        window
  92    }
  93
  94    pub fn root_view(&self) -> &AnyViewHandle {
  95        &self
  96            .root_view
  97            .as_ref()
  98            .expect("root_view called during window construction")
  99    }
 100}
 101
 102pub struct WindowContext<'a: 'b, 'b> {
 103    pub(crate) app_context: &'a mut AppContext,
 104    pub(crate) window: &'b mut Window, // TODO: make this private?
 105    pub(crate) window_id: usize,
 106    pub(crate) refreshing: bool,
 107}
 108
 109impl Deref for WindowContext<'_, '_> {
 110    type Target = AppContext;
 111
 112    fn deref(&self) -> &Self::Target {
 113        self.app_context
 114    }
 115}
 116
 117impl DerefMut for WindowContext<'_, '_> {
 118    fn deref_mut(&mut self) -> &mut Self::Target {
 119        &mut self.app_context
 120    }
 121}
 122
 123impl UpdateModel for WindowContext<'_, '_> {
 124    fn update_model<M: Entity, R>(
 125        &mut self,
 126        handle: &ModelHandle<M>,
 127        update: &mut dyn FnMut(&mut M, &mut ModelContext<M>) -> R,
 128    ) -> R {
 129        self.app_context.update_model(handle, update)
 130    }
 131}
 132
 133impl ReadView for WindowContext<'_, '_> {
 134    fn read_view<W: View>(&self, handle: &crate::ViewHandle<W>) -> &W {
 135        self.app_context.read_view(handle)
 136    }
 137}
 138
 139impl<'a: 'b, 'b> WindowContext<'a, 'b> {
 140    pub fn new(app_context: &'a mut AppContext, window: &'b mut Window, window_id: usize) -> Self {
 141        Self {
 142            app_context,
 143            window,
 144            window_id,
 145            refreshing: false,
 146        }
 147    }
 148
 149    pub fn window_id(&self) -> usize {
 150        self.window_id
 151    }
 152
 153    pub fn app_context(&mut self) -> &mut AppContext {
 154        self.app_context
 155    }
 156
 157    pub fn root_view(&self) -> &AnyViewHandle {
 158        self.window.root_view()
 159    }
 160
 161    pub fn window_size(&self) -> Vector2F {
 162        self.window.platform_window.content_size()
 163    }
 164
 165    pub fn text_layout_cache(&self) -> &TextLayoutCache {
 166        &self.window.text_layout_cache
 167    }
 168
 169    pub(crate) fn update_any_view<F, T>(&mut self, view_id: usize, f: F) -> Option<T>
 170    where
 171        F: FnOnce(&mut dyn AnyView, &mut Self) -> T,
 172    {
 173        let window_id = self.window_id;
 174        let mut view = self.views.remove(&(window_id, view_id))?;
 175        let result = f(view.as_mut(), self);
 176        self.views.insert((window_id, view_id), view);
 177        Some(result)
 178    }
 179
 180    pub fn dispatch_keystroke(&mut self, keystroke: &Keystroke) -> bool {
 181        let window_id = self.window_id;
 182        if let Some(focused_view_id) = self.focused_view_id() {
 183            let dispatch_path = self
 184                .ancestors(window_id, focused_view_id)
 185                .filter_map(|view_id| {
 186                    self.views
 187                        .get(&(window_id, view_id))
 188                        .map(|view| (view_id, view.keymap_context(self)))
 189                })
 190                .collect();
 191
 192            let match_result = self
 193                .keystroke_matcher
 194                .push_keystroke(keystroke.clone(), dispatch_path);
 195            let mut handled_by = None;
 196
 197            let keystroke_handled = match &match_result {
 198                MatchResult::None => false,
 199                MatchResult::Pending => true,
 200                MatchResult::Matches(matches) => {
 201                    for (view_id, action) in matches {
 202                        if self.handle_dispatch_action_from_effect(
 203                            window_id,
 204                            Some(*view_id),
 205                            action.as_ref(),
 206                        ) {
 207                            self.keystroke_matcher.clear_pending();
 208                            handled_by = Some(action.boxed_clone());
 209                            break;
 210                        }
 211                    }
 212                    handled_by.is_some()
 213                }
 214            };
 215
 216            self.keystroke(
 217                window_id,
 218                keystroke.clone(),
 219                handled_by,
 220                match_result.clone(),
 221            );
 222            keystroke_handled
 223        } else {
 224            self.keystroke(window_id, keystroke.clone(), None, MatchResult::None);
 225            false
 226        }
 227    }
 228
 229    pub fn dispatch_event(&mut self, event: Event, event_reused: bool) -> bool {
 230        let mut mouse_events = SmallVec::<[_; 2]>::new();
 231        let mut notified_views: HashSet<usize> = Default::default();
 232        let window_id = self.window_id;
 233
 234        // 1. Handle platform event. Keyboard events get dispatched immediately, while mouse events
 235        //    get mapped into the mouse-specific MouseEvent type.
 236        //  -> These are usually small: [Mouse Down] or [Mouse up, Click] or [Mouse Moved, Mouse Dragged?]
 237        //  -> Also updates mouse-related state
 238        match &event {
 239            Event::KeyDown(e) => return self.dispatch_key_down(window_id, e),
 240
 241            Event::KeyUp(e) => return self.dispatch_key_up(window_id, e),
 242
 243            Event::ModifiersChanged(e) => return self.dispatch_modifiers_changed(window_id, e),
 244
 245            Event::MouseDown(e) => {
 246                // Click events are weird because they can be fired after a drag event.
 247                // MDN says that browsers handle this by starting from 'the most
 248                // specific ancestor element that contained both [positions]'
 249                // So we need to store the overlapping regions on mouse down.
 250
 251                // If there is already clicked_button stored, don't replace it.
 252                if self.window.clicked_button.is_none() {
 253                    self.window.clicked_region_ids = self
 254                        .window
 255                        .mouse_regions
 256                        .iter()
 257                        .filter_map(|(region, _)| {
 258                            if region.bounds.contains_point(e.position) {
 259                                Some(region.id())
 260                            } else {
 261                                None
 262                            }
 263                        })
 264                        .collect();
 265
 266                    self.window.clicked_button = Some(e.button);
 267                }
 268
 269                mouse_events.push(MouseEvent::Down(MouseDown {
 270                    region: Default::default(),
 271                    platform_event: e.clone(),
 272                }));
 273                mouse_events.push(MouseEvent::DownOut(MouseDownOut {
 274                    region: Default::default(),
 275                    platform_event: e.clone(),
 276                }));
 277            }
 278
 279            Event::MouseUp(e) => {
 280                // NOTE: The order of event pushes is important! MouseUp events MUST be fired
 281                // before click events, and so the MouseUp events need to be pushed before
 282                // MouseClick events.
 283                mouse_events.push(MouseEvent::Up(MouseUp {
 284                    region: Default::default(),
 285                    platform_event: e.clone(),
 286                }));
 287                mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 288                    region: Default::default(),
 289                    platform_event: e.clone(),
 290                }));
 291                mouse_events.push(MouseEvent::Click(MouseClick {
 292                    region: Default::default(),
 293                    platform_event: e.clone(),
 294                }));
 295            }
 296
 297            Event::MouseMoved(
 298                e @ MouseMovedEvent {
 299                    position,
 300                    pressed_button,
 301                    ..
 302                },
 303            ) => {
 304                let mut style_to_assign = CursorStyle::Arrow;
 305                for region in self.window.cursor_regions.iter().rev() {
 306                    if region.bounds.contains_point(*position) {
 307                        style_to_assign = region.style;
 308                        break;
 309                    }
 310                }
 311
 312                if self
 313                    .window
 314                    .platform_window
 315                    .is_topmost_for_position(*position)
 316                {
 317                    self.platform().set_cursor_style(style_to_assign);
 318                }
 319
 320                if !event_reused {
 321                    if pressed_button.is_some() {
 322                        mouse_events.push(MouseEvent::Drag(MouseDrag {
 323                            region: Default::default(),
 324                            prev_mouse_position: self.window.mouse_position,
 325                            platform_event: e.clone(),
 326                        }));
 327                    } else if let Some(clicked_button) = self.window.clicked_button {
 328                        // Mouse up event happened outside the current window. Simulate mouse up button event
 329                        let button_event = e.to_button_event(clicked_button);
 330                        mouse_events.push(MouseEvent::Up(MouseUp {
 331                            region: Default::default(),
 332                            platform_event: button_event.clone(),
 333                        }));
 334                        mouse_events.push(MouseEvent::UpOut(MouseUpOut {
 335                            region: Default::default(),
 336                            platform_event: button_event.clone(),
 337                        }));
 338                        mouse_events.push(MouseEvent::Click(MouseClick {
 339                            region: Default::default(),
 340                            platform_event: button_event.clone(),
 341                        }));
 342                    }
 343
 344                    mouse_events.push(MouseEvent::Move(MouseMove {
 345                        region: Default::default(),
 346                        platform_event: e.clone(),
 347                    }));
 348                }
 349
 350                mouse_events.push(MouseEvent::Hover(MouseHover {
 351                    region: Default::default(),
 352                    platform_event: e.clone(),
 353                    started: false,
 354                }));
 355                mouse_events.push(MouseEvent::MoveOut(MouseMoveOut {
 356                    region: Default::default(),
 357                }));
 358
 359                self.window.last_mouse_moved_event = Some(event.clone());
 360            }
 361
 362            Event::MouseExited(event) => {
 363                // When the platform sends a MouseExited event, synthesize
 364                // a MouseMoved event whose position is outside the window's
 365                // bounds so that hover and cursor state can be updated.
 366                return self.dispatch_event(
 367                    Event::MouseMoved(MouseMovedEvent {
 368                        position: event.position,
 369                        pressed_button: event.pressed_button,
 370                        modifiers: event.modifiers,
 371                    }),
 372                    event_reused,
 373                );
 374            }
 375
 376            Event::ScrollWheel(e) => mouse_events.push(MouseEvent::ScrollWheel(MouseScrollWheel {
 377                region: Default::default(),
 378                platform_event: e.clone(),
 379            })),
 380        }
 381
 382        if let Some(position) = event.position() {
 383            self.window.mouse_position = position;
 384        }
 385
 386        // 2. Dispatch mouse events on regions
 387        let mut any_event_handled = false;
 388        for mut mouse_event in mouse_events {
 389            let mut valid_regions = Vec::new();
 390
 391            // GPUI elements are arranged by z_index but sibling elements can register overlapping
 392            // mouse regions. As such, hover events are only fired on overlapping elements which
 393            // are at the same z-index as the topmost element which overlaps with the mouse.
 394            match &mouse_event {
 395                MouseEvent::Hover(_) => {
 396                    let mut highest_z_index = None;
 397                    let mouse_position = self.window.mouse_position.clone();
 398                    for (region, z_index) in self.window.mouse_regions.iter().rev() {
 399                        // Allow mouse regions to appear transparent to hovers
 400                        if !region.hoverable {
 401                            continue;
 402                        }
 403
 404                        let contains_mouse = region.bounds.contains_point(mouse_position);
 405
 406                        if contains_mouse && highest_z_index.is_none() {
 407                            highest_z_index = Some(z_index);
 408                        }
 409
 410                        // This unwrap relies on short circuiting boolean expressions
 411                        // The right side of the && is only executed when contains_mouse
 412                        // is true, and we know above that when contains_mouse is true
 413                        // highest_z_index is set.
 414                        if contains_mouse && z_index == highest_z_index.unwrap() {
 415                            //Ensure that hover entrance events aren't sent twice
 416                            if self.window.hovered_region_ids.insert(region.id()) {
 417                                valid_regions.push(region.clone());
 418                                if region.notify_on_hover {
 419                                    notified_views.insert(region.id().view_id());
 420                                }
 421                            }
 422                        } else {
 423                            // Ensure that hover exit events aren't sent twice
 424                            if self.window.hovered_region_ids.remove(&region.id()) {
 425                                valid_regions.push(region.clone());
 426                                if region.notify_on_hover {
 427                                    notified_views.insert(region.id().view_id());
 428                                }
 429                            }
 430                        }
 431                    }
 432                }
 433
 434                MouseEvent::Down(_) | MouseEvent::Up(_) => {
 435                    for (region, _) in self.window.mouse_regions.iter().rev() {
 436                        if region.bounds.contains_point(self.window.mouse_position) {
 437                            valid_regions.push(region.clone());
 438                            if region.notify_on_click {
 439                                notified_views.insert(region.id().view_id());
 440                            }
 441                        }
 442                    }
 443                }
 444
 445                MouseEvent::Click(e) => {
 446                    // Only raise click events if the released button is the same as the one stored
 447                    if self
 448                        .window
 449                        .clicked_button
 450                        .map(|clicked_button| clicked_button == e.button)
 451                        .unwrap_or(false)
 452                    {
 453                        // Clear clicked regions and clicked button
 454                        let clicked_region_ids = std::mem::replace(
 455                            &mut self.window.clicked_region_ids,
 456                            Default::default(),
 457                        );
 458                        self.window.clicked_button = None;
 459
 460                        // Find regions which still overlap with the mouse since the last MouseDown happened
 461                        for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 462                            if clicked_region_ids.contains(&mouse_region.id()) {
 463                                if mouse_region
 464                                    .bounds
 465                                    .contains_point(self.window.mouse_position)
 466                                {
 467                                    valid_regions.push(mouse_region.clone());
 468                                }
 469                            }
 470                        }
 471                    }
 472                }
 473
 474                MouseEvent::Drag(_) => {
 475                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 476                        if self.window.clicked_region_ids.contains(&mouse_region.id()) {
 477                            valid_regions.push(mouse_region.clone());
 478                        }
 479                    }
 480                }
 481
 482                MouseEvent::MoveOut(_) | MouseEvent::UpOut(_) | MouseEvent::DownOut(_) => {
 483                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 484                        // NOT contains
 485                        if !mouse_region
 486                            .bounds
 487                            .contains_point(self.window.mouse_position)
 488                        {
 489                            valid_regions.push(mouse_region.clone());
 490                        }
 491                    }
 492                }
 493
 494                _ => {
 495                    for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
 496                        // Contains
 497                        if mouse_region
 498                            .bounds
 499                            .contains_point(self.window.mouse_position)
 500                        {
 501                            valid_regions.push(mouse_region.clone());
 502                        }
 503                    }
 504                }
 505            }
 506
 507            //3. Fire region events
 508            let hovered_region_ids = self.window.hovered_region_ids.clone();
 509            for valid_region in valid_regions.into_iter() {
 510                let mut handled = false;
 511                mouse_event.set_region(valid_region.bounds);
 512                if let MouseEvent::Hover(e) = &mut mouse_event {
 513                    e.started = hovered_region_ids.contains(&valid_region.id())
 514                }
 515                // Handle Down events if the MouseRegion has a Click or Drag handler. This makes the api more intuitive as you would
 516                // not expect a MouseRegion to be transparent to Down events if it also has a Click handler.
 517                // This behavior can be overridden by adding a Down handler
 518                if let MouseEvent::Down(e) = &mouse_event {
 519                    let has_click = valid_region
 520                        .handlers
 521                        .contains(MouseEvent::click_disc(), Some(e.button));
 522                    let has_drag = valid_region
 523                        .handlers
 524                        .contains(MouseEvent::drag_disc(), Some(e.button));
 525                    let has_down = valid_region
 526                        .handlers
 527                        .contains(MouseEvent::down_disc(), Some(e.button));
 528                    if !has_down && (has_click || has_drag) {
 529                        handled = true;
 530                    }
 531                }
 532
 533                // `event_consumed` should only be true if there are any handlers for this event.
 534                let mut event_consumed = handled;
 535                if let Some(callbacks) = valid_region.handlers.get(&mouse_event.handler_key()) {
 536                    for callback in callbacks {
 537                        handled = true;
 538                        let view_id = valid_region.id().view_id();
 539                        self.update_any_view(view_id, |view, cx| {
 540                            handled = callback(mouse_event.clone(), view.as_any_mut(), cx, view_id);
 541                        });
 542                        event_consumed |= handled;
 543                        any_event_handled |= handled;
 544                    }
 545                }
 546
 547                any_event_handled |= handled;
 548
 549                // For bubbling events, if the event was handled, don't continue dispatching.
 550                // This only makes sense for local events which return false from is_capturable.
 551                if event_consumed && mouse_event.is_capturable() {
 552                    break;
 553                }
 554            }
 555        }
 556
 557        for view_id in notified_views {
 558            self.notify_view(window_id, view_id);
 559        }
 560
 561        any_event_handled
 562    }
 563
 564    pub fn dispatch_key_down(&mut self, window_id: usize, event: &KeyDownEvent) -> bool {
 565        if let Some(focused_view_id) = self.window.focused_view_id {
 566            for view_id in self
 567                .ancestors(window_id, focused_view_id)
 568                .collect::<Vec<_>>()
 569            {
 570                if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
 571                    let handled = view.key_down(event, self, view_id);
 572                    self.views.insert((window_id, view_id), view);
 573                    if handled {
 574                        return true;
 575                    }
 576                } else {
 577                    log::error!("view {} does not exist", view_id)
 578                }
 579            }
 580        }
 581
 582        false
 583    }
 584
 585    pub fn dispatch_key_up(&mut self, window_id: usize, event: &KeyUpEvent) -> bool {
 586        if let Some(focused_view_id) = self.window.focused_view_id {
 587            for view_id in self
 588                .ancestors(window_id, focused_view_id)
 589                .collect::<Vec<_>>()
 590            {
 591                if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
 592                    let handled = view.key_up(event, self, view_id);
 593                    self.views.insert((window_id, view_id), view);
 594                    if handled {
 595                        return true;
 596                    }
 597                } else {
 598                    log::error!("view {} does not exist", view_id)
 599                }
 600            }
 601        }
 602
 603        false
 604    }
 605
 606    pub fn dispatch_modifiers_changed(
 607        &mut self,
 608        window_id: usize,
 609        event: &ModifiersChangedEvent,
 610    ) -> bool {
 611        if let Some(focused_view_id) = self.window.focused_view_id {
 612            for view_id in self
 613                .ancestors(window_id, focused_view_id)
 614                .collect::<Vec<_>>()
 615            {
 616                if let Some(mut view) = self.views.remove(&(window_id, view_id)) {
 617                    let handled = view.modifiers_changed(event, self, view_id);
 618                    self.views.insert((window_id, view_id), view);
 619                    if handled {
 620                        return true;
 621                    }
 622                } else {
 623                    log::error!("view {} does not exist", view_id)
 624                }
 625            }
 626        }
 627
 628        false
 629    }
 630
 631    pub fn invalidate(&mut self, invalidation: &mut WindowInvalidation, appearance: Appearance) {
 632        self.start_frame();
 633        self.window.appearance = appearance;
 634        for view_id in &invalidation.removed {
 635            invalidation.updated.remove(view_id);
 636            self.window.rendered_views.remove(view_id);
 637        }
 638        for view_id in &invalidation.updated {
 639            let window_id = self.window_id;
 640            let titlebar_height = self.window.titlebar_height;
 641            let hovered_region_ids = self.window.hovered_region_ids.clone();
 642            let clicked_region_ids = self
 643                .window
 644                .clicked_button
 645                .map(|button| (self.window.clicked_region_ids.clone(), button));
 646
 647            let element = self
 648                .render_view(RenderParams {
 649                    window_id,
 650                    view_id: *view_id,
 651                    titlebar_height,
 652                    hovered_region_ids,
 653                    clicked_region_ids,
 654                    refreshing: false,
 655                    appearance,
 656                })
 657                .unwrap();
 658            self.window.rendered_views.insert(*view_id, element);
 659        }
 660    }
 661
 662    pub fn refresh(&mut self, invalidation: &mut WindowInvalidation, appearance: Appearance) {
 663        self.invalidate(invalidation, appearance);
 664
 665        let view_ids = self
 666            .window
 667            .rendered_views
 668            .keys()
 669            .copied()
 670            .collect::<Vec<_>>();
 671
 672        for view_id in view_ids {
 673            if !invalidation.updated.contains(&view_id) {
 674                let window_id = self.window_id;
 675                let titlebar_height = self.window.titlebar_height;
 676                let hovered_region_ids = self.window.hovered_region_ids.clone();
 677                let clicked_region_ids = self
 678                    .window
 679                    .clicked_button
 680                    .map(|button| (self.window.clicked_region_ids.clone(), button));
 681                let element = self
 682                    .render_view(RenderParams {
 683                        window_id,
 684                        view_id,
 685                        titlebar_height,
 686                        hovered_region_ids,
 687                        clicked_region_ids,
 688                        refreshing: true,
 689                        appearance,
 690                    })
 691                    .unwrap();
 692                self.window.rendered_views.insert(view_id, element);
 693            }
 694        }
 695    }
 696
 697    pub fn build_scene(&mut self) -> Scene {
 698        let window_size = self.window.platform_window.content_size();
 699        let scale_factor = self.window.platform_window.scale_factor();
 700
 701        let root_view_id = self.window.root_view().id();
 702        let mut rendered_root = self.window.rendered_views.remove(&root_view_id).unwrap();
 703        rendered_root.layout(SizeConstraint::strict(window_size), self, root_view_id);
 704
 705        let mut scene_builder = SceneBuilder::new(scale_factor);
 706        rendered_root.paint(
 707            &mut scene_builder,
 708            Vector2F::zero(),
 709            RectF::from_points(Vector2F::zero(), window_size),
 710            self,
 711            root_view_id,
 712        );
 713
 714        self.window.text_layout_cache.finish_frame();
 715        let scene = scene_builder.build();
 716        self.window.cursor_regions = scene.cursor_regions();
 717        self.window.mouse_regions = scene.mouse_regions();
 718
 719        if self.window_is_active() {
 720            if let Some(event) = self.window.last_mouse_moved_event.clone() {
 721                self.dispatch_event(event, true);
 722            }
 723        }
 724
 725        scene
 726    }
 727
 728    pub fn rect_for_text_range(&self, range_utf16: Range<usize>) -> Option<RectF> {
 729        let root_view_id = self.window.root_view().id();
 730        self.window
 731            .rendered_views
 732            .get(&root_view_id)?
 733            .rect_for_text_range(range_utf16, self, root_view_id)
 734    }
 735
 736    pub fn debug_elements(&self) -> Option<json::Value> {
 737        let view = self.window.root_view();
 738        Some(json!({
 739            "root_view": view.debug_json(self),
 740            "root_element": self.window.rendered_views.get(&view.id())
 741                .map(|root_element| {
 742                    root_element.debug(self, view.id())
 743                })
 744        }))
 745    }
 746
 747    pub fn set_window_title(&mut self, title: &str) {
 748        self.window.platform_window.set_title(title);
 749    }
 750
 751    pub fn set_window_edited(&mut self, edited: bool) {
 752        self.window.platform_window.set_edited(edited);
 753    }
 754
 755    pub fn is_topmost_window_for_position(&self, position: Vector2F) -> bool {
 756        self.window
 757            .platform_window
 758            .is_topmost_for_position(position)
 759    }
 760
 761    pub fn activate_window(&self) {
 762        self.window.platform_window.activate();
 763    }
 764
 765    pub fn window_is_active(&self) -> bool {
 766        self.window.is_active
 767    }
 768
 769    pub fn window_is_fullscreen(&self) -> bool {
 770        self.window.is_fullscreen
 771    }
 772
 773    pub fn focused_view_id(&self) -> Option<usize> {
 774        self.window.focused_view_id
 775    }
 776
 777    pub fn window_bounds(&self) -> WindowBounds {
 778        self.window.platform_window.bounds()
 779    }
 780
 781    pub fn window_display_uuid(&self) -> Option<Uuid> {
 782        self.window.platform_window.screen().display_uuid()
 783    }
 784
 785    pub fn show_character_palette(&self) {
 786        self.window.platform_window.show_character_palette();
 787    }
 788
 789    pub fn minimize_window(&self) {
 790        self.window.platform_window.minimize();
 791    }
 792
 793    pub fn zoom_window(&self) {
 794        self.window.platform_window.zoom();
 795    }
 796
 797    pub fn toggle_window_full_screen(&self) {
 798        self.window.platform_window.toggle_full_screen();
 799    }
 800
 801    pub fn prompt(
 802        &self,
 803        level: PromptLevel,
 804        msg: &str,
 805        answers: &[&str],
 806    ) -> oneshot::Receiver<usize> {
 807        self.window.platform_window.prompt(level, msg, answers)
 808    }
 809
 810    fn add_view<T, F>(&mut self, parent: &AnyViewHandle, build_view: F) -> ViewHandle<T>
 811    where
 812        T: View,
 813        F: FnOnce(&mut ViewContext<T>) -> T,
 814    {
 815        if parent.window_id == self.window_id {
 816            self.build_and_insert_view(ParentId::View(parent.view_id), |cx| Some(build_view(cx)))
 817                .unwrap()
 818        } else {
 819            self.app_context.add_view(parent, build_view)
 820        }
 821    }
 822
 823    fn add_option_view<T, F>(
 824        &mut self,
 825        parent_handle: impl Into<AnyViewHandle>,
 826        build_view: F,
 827    ) -> Option<ViewHandle<T>>
 828    where
 829        T: View,
 830        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 831    {
 832        let parent_handle = parent_handle.into();
 833        self.build_and_insert_view(ParentId::View(parent_handle.view_id), build_view)
 834    }
 835
 836    pub fn replace_root_view<V, F>(&mut self, build_root_view: F) -> ViewHandle<V>
 837    where
 838        V: View,
 839        F: FnOnce(&mut ViewContext<V>) -> V,
 840    {
 841        let root_view = self
 842            .build_and_insert_view(ParentId::Root, |cx| Some(build_root_view(cx)))
 843            .unwrap();
 844        self.window.root_view = Some(root_view.clone().into_any());
 845        self.window.focused_view_id = Some(root_view.id());
 846        root_view
 847    }
 848
 849    pub(crate) fn build_and_insert_view<T, F>(
 850        &mut self,
 851        parent_id: ParentId,
 852        build_view: F,
 853    ) -> Option<ViewHandle<T>>
 854    where
 855        T: View,
 856        F: FnOnce(&mut ViewContext<T>) -> Option<T>,
 857    {
 858        let window_id = self.window_id;
 859        let view_id = post_inc(&mut self.next_entity_id);
 860        // Make sure we can tell child views about their parentu
 861        self.parents.insert((window_id, view_id), parent_id);
 862        let mut cx = ViewContext::mutable(self, view_id);
 863        let handle = if let Some(view) = build_view(&mut cx) {
 864            self.views.insert((window_id, view_id), Box::new(view));
 865            self.window
 866                .invalidation
 867                .get_or_insert_with(Default::default)
 868                .updated
 869                .insert(view_id);
 870            Some(ViewHandle::new(window_id, view_id, &self.ref_counts))
 871        } else {
 872            self.parents.remove(&(window_id, view_id));
 873            None
 874        };
 875        handle
 876    }
 877}
 878
 879pub trait RenderedView {
 880    fn layout(
 881        &mut self,
 882        constraint: SizeConstraint,
 883        cx: &mut WindowContext,
 884        view_id: usize,
 885    ) -> Vector2F;
 886    fn paint(
 887        &mut self,
 888        scene: &mut SceneBuilder,
 889        origin: Vector2F,
 890        visible_bounds: RectF,
 891        cx: &mut WindowContext,
 892        view_id: usize,
 893    );
 894    fn rect_for_text_range(
 895        &self,
 896        range_utf16: Range<usize>,
 897        cx: &WindowContext,
 898        view_id: usize,
 899    ) -> Option<RectF>;
 900    fn debug(&self, cx: &WindowContext, view_id: usize) -> serde_json::Value;
 901    fn name(&self) -> Option<&str>;
 902}
 903
 904impl<V: View> RenderedView for ElementBox<V> {
 905    fn layout(
 906        &mut self,
 907        constraint: SizeConstraint,
 908        cx: &mut WindowContext,
 909        view_id: usize,
 910    ) -> Vector2F {
 911        cx.update_any_view(view_id, |view, cx| {
 912            let view = view.as_any_mut().downcast_mut::<V>().unwrap();
 913            let mut cx = ViewContext::mutable(cx, view_id);
 914            ElementBox::layout(self, constraint, view, &mut cx)
 915        })
 916        .unwrap()
 917    }
 918
 919    fn paint(
 920        &mut self,
 921        scene: &mut SceneBuilder,
 922        origin: Vector2F,
 923        visible_bounds: RectF,
 924        cx: &mut WindowContext,
 925        view_id: usize,
 926    ) {
 927        cx.update_any_view(view_id, |view, cx| {
 928            let view = view.as_any_mut().downcast_mut::<V>().unwrap();
 929            let mut cx = ViewContext::mutable(cx, view_id);
 930            ElementBox::paint(self, scene, origin, visible_bounds, view, &mut cx)
 931        });
 932    }
 933
 934    fn rect_for_text_range(
 935        &self,
 936        range_utf16: Range<usize>,
 937        cx: &WindowContext,
 938        view_id: usize,
 939    ) -> Option<RectF> {
 940        let view = cx
 941            .views
 942            .get(&(cx.window_id, view_id))
 943            .unwrap()
 944            .as_any()
 945            .downcast_ref::<V>()
 946            .unwrap();
 947        let cx = ViewContext::immutable(cx, view_id);
 948        ElementBox::rect_for_text_range(self, range_utf16, view, &cx)
 949    }
 950
 951    fn debug(&self, cx: &WindowContext, view_id: usize) -> serde_json::Value {
 952        let view = cx
 953            .views
 954            .get(&(cx.window_id, view_id))
 955            .unwrap()
 956            .as_any()
 957            .downcast_ref::<V>()
 958            .unwrap();
 959        let cx = ViewContext::immutable(cx, view_id);
 960        ElementBox::debug(self, view, &cx)
 961    }
 962
 963    fn name(&self) -> Option<&str> {
 964        ElementBox::name(self)
 965    }
 966}
 967
 968#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
 969pub enum Axis {
 970    #[default]
 971    Horizontal,
 972    Vertical,
 973}
 974
 975impl Axis {
 976    pub fn invert(self) -> Self {
 977        match self {
 978            Self::Horizontal => Self::Vertical,
 979            Self::Vertical => Self::Horizontal,
 980        }
 981    }
 982
 983    pub fn component(&self, point: Vector2F) -> f32 {
 984        match self {
 985            Self::Horizontal => point.x(),
 986            Self::Vertical => point.y(),
 987        }
 988    }
 989}
 990
 991impl ToJson for Axis {
 992    fn to_json(&self) -> serde_json::Value {
 993        match self {
 994            Axis::Horizontal => json!("horizontal"),
 995            Axis::Vertical => json!("vertical"),
 996        }
 997    }
 998}
 999
1000impl StaticColumnCount for Axis {}
1001impl Bind for Axis {
1002    fn bind(&self, statement: &Statement, start_index: i32) -> anyhow::Result<i32> {
1003        match self {
1004            Axis::Horizontal => "Horizontal",
1005            Axis::Vertical => "Vertical",
1006        }
1007        .bind(statement, start_index)
1008    }
1009}
1010
1011impl Column for Axis {
1012    fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> {
1013        String::column(statement, start_index).and_then(|(axis_text, next_index)| {
1014            Ok((
1015                match axis_text.as_str() {
1016                    "Horizontal" => Axis::Horizontal,
1017                    "Vertical" => Axis::Vertical,
1018                    _ => bail!("Stored serialized item kind is incorrect"),
1019                },
1020                next_index,
1021            ))
1022        })
1023    }
1024}
1025
1026pub trait Vector2FExt {
1027    fn along(self, axis: Axis) -> f32;
1028}
1029
1030impl Vector2FExt for Vector2F {
1031    fn along(self, axis: Axis) -> f32 {
1032        match axis {
1033            Axis::Horizontal => self.x(),
1034            Axis::Vertical => self.y(),
1035        }
1036    }
1037}
1038
1039#[derive(Copy, Clone, Debug)]
1040pub struct SizeConstraint {
1041    pub min: Vector2F,
1042    pub max: Vector2F,
1043}
1044
1045impl SizeConstraint {
1046    pub fn new(min: Vector2F, max: Vector2F) -> Self {
1047        Self { min, max }
1048    }
1049
1050    pub fn strict(size: Vector2F) -> Self {
1051        Self {
1052            min: size,
1053            max: size,
1054        }
1055    }
1056
1057    pub fn strict_along(axis: Axis, max: f32) -> Self {
1058        match axis {
1059            Axis::Horizontal => Self {
1060                min: vec2f(max, 0.0),
1061                max: vec2f(max, f32::INFINITY),
1062            },
1063            Axis::Vertical => Self {
1064                min: vec2f(0.0, max),
1065                max: vec2f(f32::INFINITY, max),
1066            },
1067        }
1068    }
1069
1070    pub fn max_along(&self, axis: Axis) -> f32 {
1071        match axis {
1072            Axis::Horizontal => self.max.x(),
1073            Axis::Vertical => self.max.y(),
1074        }
1075    }
1076
1077    pub fn min_along(&self, axis: Axis) -> f32 {
1078        match axis {
1079            Axis::Horizontal => self.min.x(),
1080            Axis::Vertical => self.min.y(),
1081        }
1082    }
1083
1084    pub fn constrain(&self, size: Vector2F) -> Vector2F {
1085        vec2f(
1086            size.x().min(self.max.x()).max(self.min.x()),
1087            size.y().min(self.max.y()).max(self.min.y()),
1088        )
1089    }
1090}
1091
1092impl Default for SizeConstraint {
1093    fn default() -> Self {
1094        SizeConstraint {
1095            min: Vector2F::zero(),
1096            max: Vector2F::splat(f32::INFINITY),
1097        }
1098    }
1099}
1100
1101impl ToJson for SizeConstraint {
1102    fn to_json(&self) -> serde_json::Value {
1103        json!({
1104            "min": self.min.to_json(),
1105            "max": self.max.to_json(),
1106        })
1107    }
1108}
1109
1110pub struct ChildView {
1111    view_id: usize,
1112    view_name: &'static str,
1113}
1114
1115impl ChildView {
1116    pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
1117        let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
1118        Self {
1119            view_id: view.id(),
1120            view_name,
1121        }
1122    }
1123}
1124
1125impl<V: View> Element<V> for ChildView {
1126    type LayoutState = ();
1127    type PaintState = ();
1128
1129    fn layout(
1130        &mut self,
1131        constraint: SizeConstraint,
1132        _: &mut V,
1133        cx: &mut ViewContext<V>,
1134    ) -> (Vector2F, Self::LayoutState) {
1135        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1136            let size = rendered_view.layout(constraint, cx, self.view_id);
1137            cx.window.rendered_views.insert(self.view_id, rendered_view);
1138            (size, ())
1139        } else {
1140            log::error!(
1141                "layout called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1142                self.view_id,
1143                self.view_name
1144            );
1145            (Vector2F::zero(), ())
1146        }
1147    }
1148
1149    fn paint(
1150        &mut self,
1151        scene: &mut SceneBuilder,
1152        bounds: RectF,
1153        visible_bounds: RectF,
1154        _: &mut Self::LayoutState,
1155        _: &mut V,
1156        cx: &mut ViewContext<V>,
1157    ) {
1158        if let Some(mut rendered_view) = cx.window.rendered_views.remove(&self.view_id) {
1159            rendered_view.paint(scene, bounds.origin(), visible_bounds, cx, self.view_id);
1160            cx.window.rendered_views.insert(self.view_id, rendered_view);
1161        } else {
1162            log::error!(
1163                "paint called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1164                self.view_id,
1165                self.view_name
1166            );
1167        }
1168    }
1169
1170    fn rect_for_text_range(
1171        &self,
1172        range_utf16: Range<usize>,
1173        _: RectF,
1174        _: RectF,
1175        _: &Self::LayoutState,
1176        _: &Self::PaintState,
1177        _: &V,
1178        cx: &ViewContext<V>,
1179    ) -> Option<RectF> {
1180        if let Some(rendered_view) = cx.window.rendered_views.get(&self.view_id) {
1181            rendered_view.rect_for_text_range(range_utf16, &cx.window_context, self.view_id)
1182        } else {
1183            log::error!(
1184                "rect_for_text_range called on a ChildView element whose underlying view was dropped (view_id: {}, name: {:?})",
1185                self.view_id,
1186                self.view_name
1187            );
1188            None
1189        }
1190    }
1191
1192    fn debug(
1193        &self,
1194        bounds: RectF,
1195        _: &Self::LayoutState,
1196        _: &Self::PaintState,
1197        _: &V,
1198        cx: &ViewContext<V>,
1199    ) -> serde_json::Value {
1200        json!({
1201            "type": "ChildView",
1202            "view_id": self.view_id,
1203            "bounds": bounds.to_json(),
1204            "view": if let Some(view) = cx.views.get(&(cx.window_id, self.view_id))  {
1205                view.debug_json(cx)
1206            } else {
1207                json!(null)
1208            },
1209            "child": if let Some(element) = cx.window.rendered_views.get(&self.view_id) {
1210                element.debug(&cx.window_context, self.view_id)
1211            } else {
1212                json!(null)
1213            }
1214        })
1215    }
1216}