window.rs

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