platform.rs

   1mod app_menu;
   2mod keyboard;
   3mod keystroke;
   4
   5#[cfg(any(target_os = "linux", target_os = "freebsd"))]
   6mod linux;
   7
   8#[cfg(target_os = "macos")]
   9mod mac;
  10
  11#[cfg(any(
  12    all(
  13        any(target_os = "linux", target_os = "freebsd"),
  14        any(feature = "x11", feature = "wayland")
  15    ),
  16    all(target_os = "macos", feature = "macos-blade")
  17))]
  18mod blade;
  19
  20#[cfg(any(test, feature = "test-support"))]
  21mod test;
  22
  23#[cfg(target_os = "windows")]
  24mod windows;
  25
  26#[cfg(all(
  27    feature = "screen-capture",
  28    any(
  29        target_os = "windows",
  30        all(
  31            any(target_os = "linux", target_os = "freebsd"),
  32            any(feature = "wayland", feature = "x11"),
  33        )
  34    )
  35))]
  36pub(crate) mod scap_screen_capture;
  37
  38use crate::{
  39    Action, AnyWindowHandle, App, AsyncWindowContext, BackgroundExecutor, Bounds,
  40    DEFAULT_WINDOW_SIZE, DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun,
  41    ForegroundExecutor, GlyphId, GpuSpecs, ImageSource, Keymap, LineLayout, Pixels, PlatformInput,
  42    Point, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, ShapedGlyph,
  43    ShapedRun, SharedString, Size, SvgRenderer, SystemWindowTab, Task, TaskLabel, TaskTiming,
  44    ThreadTaskTimings, Window, WindowControlArea, hash, point, px, size,
  45};
  46use anyhow::Result;
  47use async_task::Runnable;
  48use futures::channel::oneshot;
  49use image::codecs::gif::GifDecoder;
  50use image::{AnimationDecoder as _, Frame};
  51use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
  52use schemars::JsonSchema;
  53use seahash::SeaHasher;
  54use serde::{Deserialize, Serialize};
  55use smallvec::SmallVec;
  56use std::borrow::Cow;
  57use std::hash::{Hash, Hasher};
  58use std::io::Cursor;
  59use std::ops;
  60use std::time::{Duration, Instant};
  61use std::{
  62    fmt::{self, Debug},
  63    ops::Range,
  64    path::{Path, PathBuf},
  65    rc::Rc,
  66    sync::Arc,
  67};
  68use strum::EnumIter;
  69use uuid::Uuid;
  70
  71pub use app_menu::*;
  72pub use keyboard::*;
  73pub use keystroke::*;
  74
  75#[cfg(any(target_os = "linux", target_os = "freebsd"))]
  76pub(crate) use linux::*;
  77#[cfg(target_os = "macos")]
  78pub(crate) use mac::*;
  79#[cfg(any(test, feature = "test-support"))]
  80pub(crate) use test::*;
  81#[cfg(target_os = "windows")]
  82pub(crate) use windows::*;
  83
  84#[cfg(all(target_os = "linux", feature = "wayland"))]
  85pub use linux::layer_shell;
  86
  87#[cfg(any(test, feature = "test-support"))]
  88pub use test::{TestDispatcher, TestScreenCaptureSource, TestScreenCaptureStream};
  89
  90/// Returns a background executor for the current platform.
  91pub fn background_executor() -> BackgroundExecutor {
  92    current_platform(true).background_executor()
  93}
  94
  95#[cfg(target_os = "macos")]
  96pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
  97    Rc::new(MacPlatform::new(headless))
  98}
  99
 100#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 101pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
 102    #[cfg(feature = "x11")]
 103    use anyhow::Context as _;
 104
 105    if headless {
 106        return Rc::new(HeadlessClient::new());
 107    }
 108
 109    match guess_compositor() {
 110        #[cfg(feature = "wayland")]
 111        "Wayland" => Rc::new(WaylandClient::new()),
 112
 113        #[cfg(feature = "x11")]
 114        "X11" => Rc::new(
 115            X11Client::new()
 116                .context("Failed to initialize X11 client.")
 117                .unwrap(),
 118        ),
 119
 120        "Headless" => Rc::new(HeadlessClient::new()),
 121        _ => unreachable!(),
 122    }
 123}
 124
 125#[cfg(target_os = "windows")]
 126pub(crate) fn current_platform(_headless: bool) -> Rc<dyn Platform> {
 127    Rc::new(
 128        WindowsPlatform::new()
 129            .inspect_err(|err| show_error("Failed to launch", err.to_string()))
 130            .unwrap(),
 131    )
 132}
 133
 134/// Return which compositor we're guessing we'll use.
 135/// Does not attempt to connect to the given compositor
 136#[cfg(any(target_os = "linux", target_os = "freebsd"))]
 137#[inline]
 138pub fn guess_compositor() -> &'static str {
 139    if std::env::var_os("ZED_HEADLESS").is_some() {
 140        return "Headless";
 141    }
 142
 143    #[cfg(feature = "wayland")]
 144    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
 145    #[cfg(not(feature = "wayland"))]
 146    let wayland_display: Option<std::ffi::OsString> = None;
 147
 148    #[cfg(feature = "x11")]
 149    let x11_display = std::env::var_os("DISPLAY");
 150    #[cfg(not(feature = "x11"))]
 151    let x11_display: Option<std::ffi::OsString> = None;
 152
 153    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
 154    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
 155
 156    if use_wayland {
 157        "Wayland"
 158    } else if use_x11 {
 159        "X11"
 160    } else {
 161        "Headless"
 162    }
 163}
 164
 165pub(crate) trait Platform: 'static {
 166    fn background_executor(&self) -> BackgroundExecutor;
 167    fn foreground_executor(&self) -> ForegroundExecutor;
 168    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 169
 170    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 171    fn quit(&self);
 172    fn restart(&self, binary_path: Option<PathBuf>);
 173    fn activate(&self, ignoring_other_apps: bool);
 174    fn hide(&self);
 175    fn hide_other_apps(&self);
 176    fn unhide_other_apps(&self);
 177
 178    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 179    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 180    fn active_window(&self) -> Option<AnyWindowHandle>;
 181    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 182        None
 183    }
 184
 185    #[cfg(feature = "screen-capture")]
 186    fn is_screen_capture_supported(&self) -> bool;
 187    #[cfg(not(feature = "screen-capture"))]
 188    fn is_screen_capture_supported(&self) -> bool {
 189        false
 190    }
 191    #[cfg(feature = "screen-capture")]
 192    fn screen_capture_sources(&self)
 193    -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>>;
 194    #[cfg(not(feature = "screen-capture"))]
 195    fn screen_capture_sources(
 196        &self,
 197    ) -> oneshot::Receiver<anyhow::Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
 198        let (sources_tx, sources_rx) = oneshot::channel();
 199        sources_tx
 200            .send(Err(anyhow::anyhow!(
 201                "gpui was compiled without the screen-capture feature"
 202            )))
 203            .ok();
 204        sources_rx
 205    }
 206
 207    fn open_window(
 208        &self,
 209        handle: AnyWindowHandle,
 210        options: WindowParams,
 211    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
 212
 213    /// Returns the appearance of the application's windows.
 214    fn window_appearance(&self) -> WindowAppearance;
 215
 216    fn open_url(&self, url: &str);
 217    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 218    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
 219
 220    fn prompt_for_paths(
 221        &self,
 222        options: PathPromptOptions,
 223    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
 224    fn prompt_for_new_path(
 225        &self,
 226        directory: &Path,
 227        suggested_name: Option<&str>,
 228    ) -> oneshot::Receiver<Result<Option<PathBuf>>>;
 229    fn can_select_mixed_files_and_dirs(&self) -> bool;
 230    fn reveal_path(&self, path: &Path);
 231    fn open_with_system(&self, path: &Path);
 232
 233    fn on_quit(&self, callback: Box<dyn FnMut()>);
 234    fn on_reopen(&self, callback: Box<dyn FnMut()>);
 235
 236    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
 237    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 238        None
 239    }
 240
 241    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
 242    fn perform_dock_menu_action(&self, _action: usize) {}
 243    fn add_recent_document(&self, _path: &Path) {}
 244    fn update_jump_list(
 245        &self,
 246        _menus: Vec<MenuItem>,
 247        _entries: Vec<SmallVec<[PathBuf; 2]>>,
 248    ) -> Vec<SmallVec<[PathBuf; 2]>> {
 249        Vec::new()
 250    }
 251    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
 252    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
 253    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
 254
 255    fn compositor_name(&self) -> &'static str {
 256        ""
 257    }
 258    fn app_path(&self) -> Result<PathBuf>;
 259    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 260
 261    fn set_cursor_style(&self, style: CursorStyle);
 262    fn should_auto_hide_scrollbars(&self) -> bool;
 263
 264    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 265    fn write_to_primary(&self, item: ClipboardItem);
 266    fn write_to_clipboard(&self, item: ClipboardItem);
 267    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 268    fn read_from_primary(&self) -> Option<ClipboardItem>;
 269    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 270
 271    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
 272    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
 273    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
 274
 275    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
 276    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper>;
 277    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>);
 278}
 279
 280/// A handle to a platform's display, e.g. a monitor or laptop screen.
 281pub trait PlatformDisplay: Send + Sync + Debug {
 282    /// Get the ID for this display
 283    fn id(&self) -> DisplayId;
 284
 285    /// Returns a stable identifier for this display that can be persisted and used
 286    /// across system restarts.
 287    fn uuid(&self) -> Result<Uuid>;
 288
 289    /// Get the bounds for this display
 290    fn bounds(&self) -> Bounds<Pixels>;
 291
 292    /// Get the default bounds for this display to place a window
 293    fn default_bounds(&self) -> Bounds<Pixels> {
 294        let bounds = self.bounds();
 295        let center = bounds.center();
 296        let clipped_window_size = DEFAULT_WINDOW_SIZE.min(&bounds.size);
 297
 298        let offset = clipped_window_size / 2.0;
 299        let origin = point(center.x - offset.width, center.y - offset.height);
 300        Bounds::new(origin, clipped_window_size)
 301    }
 302}
 303
 304/// Metadata for a given [ScreenCaptureSource]
 305#[derive(Clone)]
 306pub struct SourceMetadata {
 307    /// Opaque identifier of this screen.
 308    pub id: u64,
 309    /// Human-readable label for this source.
 310    pub label: Option<SharedString>,
 311    /// Whether this source is the main display.
 312    pub is_main: Option<bool>,
 313    /// Video resolution of this source.
 314    pub resolution: Size<DevicePixels>,
 315}
 316
 317/// A source of on-screen video content that can be captured.
 318pub trait ScreenCaptureSource {
 319    /// Returns metadata for this source.
 320    fn metadata(&self) -> Result<SourceMetadata>;
 321
 322    /// Start capture video from this source, invoking the given callback
 323    /// with each frame.
 324    fn stream(
 325        &self,
 326        foreground_executor: &ForegroundExecutor,
 327        frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,
 328    ) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>>;
 329}
 330
 331/// A video stream captured from a screen.
 332pub trait ScreenCaptureStream {
 333    /// Returns metadata for this source.
 334    fn metadata(&self) -> Result<SourceMetadata>;
 335}
 336
 337/// A frame of video captured from a screen.
 338pub struct ScreenCaptureFrame(pub PlatformScreenCaptureFrame);
 339
 340/// An opaque identifier for a hardware display
 341#[derive(PartialEq, Eq, Hash, Copy, Clone)]
 342pub struct DisplayId(pub(crate) u32);
 343
 344impl From<DisplayId> for u32 {
 345    fn from(id: DisplayId) -> Self {
 346        id.0
 347    }
 348}
 349
 350impl Debug for DisplayId {
 351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 352        write!(f, "DisplayId({})", self.0)
 353    }
 354}
 355
 356/// Which part of the window to resize
 357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 358pub enum ResizeEdge {
 359    /// The top edge
 360    Top,
 361    /// The top right corner
 362    TopRight,
 363    /// The right edge
 364    Right,
 365    /// The bottom right corner
 366    BottomRight,
 367    /// The bottom edge
 368    Bottom,
 369    /// The bottom left corner
 370    BottomLeft,
 371    /// The left edge
 372    Left,
 373    /// The top left corner
 374    TopLeft,
 375}
 376
 377/// A type to describe the appearance of a window
 378#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 379pub enum WindowDecorations {
 380    #[default]
 381    /// Server side decorations
 382    Server,
 383    /// Client side decorations
 384    Client,
 385}
 386
 387/// A type to describe how this window is currently configured
 388#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 389pub enum Decorations {
 390    /// The window is configured to use server side decorations
 391    #[default]
 392    Server,
 393    /// The window is configured to use client side decorations
 394    Client {
 395        /// The edge tiling state
 396        tiling: Tiling,
 397    },
 398}
 399
 400/// What window controls this platform supports
 401#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
 402pub struct WindowControls {
 403    /// Whether this platform supports fullscreen
 404    pub fullscreen: bool,
 405    /// Whether this platform supports maximize
 406    pub maximize: bool,
 407    /// Whether this platform supports minimize
 408    pub minimize: bool,
 409    /// Whether this platform supports a window menu
 410    pub window_menu: bool,
 411}
 412
 413impl Default for WindowControls {
 414    fn default() -> Self {
 415        // Assume that we can do anything, unless told otherwise
 416        Self {
 417            fullscreen: true,
 418            maximize: true,
 419            minimize: true,
 420            window_menu: true,
 421        }
 422    }
 423}
 424
 425/// A type to describe which sides of the window are currently tiled in some way
 426#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 427pub struct Tiling {
 428    /// Whether the top edge is tiled
 429    pub top: bool,
 430    /// Whether the left edge is tiled
 431    pub left: bool,
 432    /// Whether the right edge is tiled
 433    pub right: bool,
 434    /// Whether the bottom edge is tiled
 435    pub bottom: bool,
 436}
 437
 438impl Tiling {
 439    /// Initializes a [`Tiling`] type with all sides tiled
 440    pub fn tiled() -> Self {
 441        Self {
 442            top: true,
 443            left: true,
 444            right: true,
 445            bottom: true,
 446        }
 447    }
 448
 449    /// Whether any edge is tiled
 450    pub fn is_tiled(&self) -> bool {
 451        self.top || self.left || self.right || self.bottom
 452    }
 453}
 454
 455#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
 456pub(crate) struct RequestFrameOptions {
 457    pub(crate) require_presentation: bool,
 458    /// Force refresh of all rendering states when true
 459    pub(crate) force_render: bool,
 460}
 461
 462pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
 463    fn bounds(&self) -> Bounds<Pixels>;
 464    fn is_maximized(&self) -> bool;
 465    fn window_bounds(&self) -> WindowBounds;
 466    fn content_size(&self) -> Size<Pixels>;
 467    fn resize(&mut self, size: Size<Pixels>);
 468    fn scale_factor(&self) -> f32;
 469    fn appearance(&self) -> WindowAppearance;
 470    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 471    fn mouse_position(&self) -> Point<Pixels>;
 472    fn modifiers(&self) -> Modifiers;
 473    fn capslock(&self) -> Capslock;
 474    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
 475    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
 476    fn prompt(
 477        &self,
 478        level: PromptLevel,
 479        msg: &str,
 480        detail: Option<&str>,
 481        answers: &[PromptButton],
 482    ) -> Option<oneshot::Receiver<usize>>;
 483    fn activate(&self);
 484    fn is_active(&self) -> bool;
 485    fn is_hovered(&self) -> bool;
 486    fn set_title(&mut self, title: &str);
 487    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
 488    fn minimize(&self);
 489    fn zoom(&self);
 490    fn toggle_fullscreen(&self);
 491    fn is_fullscreen(&self) -> bool;
 492    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>);
 493    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
 494    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
 495    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
 496    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
 497    fn on_moved(&self, callback: Box<dyn FnMut()>);
 498    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
 499    fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
 500    fn on_close(&self, callback: Box<dyn FnOnce()>);
 501    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
 502    fn draw(&self, scene: &Scene);
 503    fn completed_frame(&self) {}
 504    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
 505
 506    // macOS specific methods
 507    fn get_title(&self) -> String {
 508        String::new()
 509    }
 510    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
 511        None
 512    }
 513    fn tab_bar_visible(&self) -> bool {
 514        false
 515    }
 516    fn set_edited(&mut self, _edited: bool) {}
 517    fn show_character_palette(&self) {}
 518    fn titlebar_double_click(&self) {}
 519    fn on_move_tab_to_new_window(&self, _callback: Box<dyn FnMut()>) {}
 520    fn on_merge_all_windows(&self, _callback: Box<dyn FnMut()>) {}
 521    fn on_select_previous_tab(&self, _callback: Box<dyn FnMut()>) {}
 522    fn on_select_next_tab(&self, _callback: Box<dyn FnMut()>) {}
 523    fn on_toggle_tab_bar(&self, _callback: Box<dyn FnMut()>) {}
 524    fn merge_all_windows(&self) {}
 525    fn move_tab_to_new_window(&self) {}
 526    fn toggle_window_tab_overview(&self) {}
 527    fn set_tabbing_identifier(&self, _identifier: Option<String>) {}
 528
 529    #[cfg(target_os = "windows")]
 530    fn get_raw_handle(&self) -> windows::HWND;
 531
 532    // Linux specific methods
 533    fn inner_window_bounds(&self) -> WindowBounds {
 534        self.window_bounds()
 535    }
 536    fn request_decorations(&self, _decorations: WindowDecorations) {}
 537    fn show_window_menu(&self, _position: Point<Pixels>) {}
 538    fn start_window_move(&self) {}
 539    fn start_window_resize(&self, _edge: ResizeEdge) {}
 540    fn window_decorations(&self) -> Decorations {
 541        Decorations::Server
 542    }
 543    fn set_app_id(&mut self, _app_id: &str) {}
 544    fn map_window(&mut self) -> anyhow::Result<()> {
 545        Ok(())
 546    }
 547    fn window_controls(&self) -> WindowControls {
 548        WindowControls::default()
 549    }
 550    fn set_client_inset(&self, _inset: Pixels) {}
 551    fn gpu_specs(&self) -> Option<GpuSpecs>;
 552
 553    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
 554
 555    #[cfg(any(test, feature = "test-support"))]
 556    fn as_test(&mut self) -> Option<&mut TestWindow> {
 557        None
 558    }
 559}
 560
 561/// This type is public so that our test macro can generate and use it, but it should not
 562/// be considered part of our public API.
 563#[doc(hidden)]
 564#[derive(Debug)]
 565pub struct RunnableMeta {
 566    /// Location of the runnable
 567    pub location: &'static core::panic::Location<'static>,
 568}
 569
 570#[doc(hidden)]
 571pub enum RunnableVariant {
 572    Meta(Runnable<RunnableMeta>),
 573    Compat(Runnable),
 574}
 575
 576/// This type is public so that our test macro can generate and use it, but it should not
 577/// be considered part of our public API.
 578#[doc(hidden)]
 579pub trait PlatformDispatcher: Send + Sync {
 580    fn get_all_timings(&self) -> Vec<ThreadTaskTimings>;
 581    fn get_current_thread_timings(&self) -> Vec<TaskTiming>;
 582    fn is_main_thread(&self) -> bool;
 583    fn dispatch(&self, runnable: RunnableVariant, label: Option<TaskLabel>);
 584    fn dispatch_on_main_thread(&self, runnable: RunnableVariant);
 585    fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant);
 586
 587    fn now(&self) -> Instant {
 588        Instant::now()
 589    }
 590
 591    #[cfg(any(test, feature = "test-support"))]
 592    fn as_test(&self) -> Option<&TestDispatcher> {
 593        None
 594    }
 595}
 596
 597pub(crate) trait PlatformTextSystem: Send + Sync {
 598    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 599    fn all_font_names(&self) -> Vec<String>;
 600    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 601    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 602    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 603    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 604    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 605    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 606    fn rasterize_glyph(
 607        &self,
 608        params: &RenderGlyphParams,
 609        raster_bounds: Bounds<DevicePixels>,
 610    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 611    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 612}
 613
 614pub(crate) struct NoopTextSystem;
 615
 616impl NoopTextSystem {
 617    #[allow(dead_code)]
 618    pub fn new() -> Self {
 619        Self
 620    }
 621}
 622
 623impl PlatformTextSystem for NoopTextSystem {
 624    fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
 625        Ok(())
 626    }
 627
 628    fn all_font_names(&self) -> Vec<String> {
 629        Vec::new()
 630    }
 631
 632    fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
 633        Ok(FontId(1))
 634    }
 635
 636    fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
 637        FontMetrics {
 638            units_per_em: 1000,
 639            ascent: 1025.0,
 640            descent: -275.0,
 641            line_gap: 0.0,
 642            underline_position: -95.0,
 643            underline_thickness: 60.0,
 644            cap_height: 698.0,
 645            x_height: 516.0,
 646            bounding_box: Bounds {
 647                origin: Point {
 648                    x: -260.0,
 649                    y: -245.0,
 650                },
 651                size: Size {
 652                    width: 1501.0,
 653                    height: 1364.0,
 654                },
 655            },
 656        }
 657    }
 658
 659    fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
 660        Ok(Bounds {
 661            origin: Point { x: 54.0, y: 0.0 },
 662            size: size(392.0, 528.0),
 663        })
 664    }
 665
 666    fn advance(&self, _font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {
 667        Ok(size(600.0 * glyph_id.0 as f32, 0.0))
 668    }
 669
 670    fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
 671        Some(GlyphId(ch.len_utf16() as u32))
 672    }
 673
 674    fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
 675        Ok(Default::default())
 676    }
 677
 678    fn rasterize_glyph(
 679        &self,
 680        _params: &RenderGlyphParams,
 681        raster_bounds: Bounds<DevicePixels>,
 682    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
 683        Ok((raster_bounds.size, Vec::new()))
 684    }
 685
 686    fn layout_line(&self, text: &str, font_size: Pixels, _runs: &[FontRun]) -> LineLayout {
 687        let mut position = px(0.);
 688        let metrics = self.font_metrics(FontId(0));
 689        let em_width = font_size
 690            * self
 691                .advance(FontId(0), self.glyph_for_char(FontId(0), 'm').unwrap())
 692                .unwrap()
 693                .width
 694            / metrics.units_per_em as f32;
 695        let mut glyphs = Vec::new();
 696        for (ix, c) in text.char_indices() {
 697            if let Some(glyph) = self.glyph_for_char(FontId(0), c) {
 698                glyphs.push(ShapedGlyph {
 699                    id: glyph,
 700                    position: point(position, px(0.)),
 701                    index: ix,
 702                    is_emoji: glyph.0 == 2,
 703                });
 704                if glyph.0 == 2 {
 705                    position += em_width * 2.0;
 706                } else {
 707                    position += em_width;
 708                }
 709            } else {
 710                position += em_width
 711            }
 712        }
 713        let mut runs = Vec::default();
 714        if !glyphs.is_empty() {
 715            runs.push(ShapedRun {
 716                font_id: FontId(0),
 717                glyphs,
 718            });
 719        } else {
 720            position = px(0.);
 721        }
 722
 723        LineLayout {
 724            font_size,
 725            width: position,
 726            ascent: font_size * (metrics.ascent / metrics.units_per_em as f32),
 727            descent: font_size * (metrics.descent / metrics.units_per_em as f32),
 728            runs,
 729            len: text.len(),
 730        }
 731    }
 732}
 733
 734// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.cpp
 735// Copyright (c) Microsoft Corporation.
 736// Licensed under the MIT license.
 737#[allow(dead_code)]
 738pub(crate) fn get_gamma_correction_ratios(gamma: f32) -> [f32; 4] {
 739    const GAMMA_INCORRECT_TARGET_RATIOS: [[f32; 4]; 13] = [
 740        [0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0, 0.0000 / 4.0], // gamma = 1.0
 741        [0.0166 / 4.0, -0.0807 / 4.0, 0.2227 / 4.0, -0.0751 / 4.0], // gamma = 1.1
 742        [0.0350 / 4.0, -0.1760 / 4.0, 0.4325 / 4.0, -0.1370 / 4.0], // gamma = 1.2
 743        [0.0543 / 4.0, -0.2821 / 4.0, 0.6302 / 4.0, -0.1876 / 4.0], // gamma = 1.3
 744        [0.0739 / 4.0, -0.3963 / 4.0, 0.8167 / 4.0, -0.2287 / 4.0], // gamma = 1.4
 745        [0.0933 / 4.0, -0.5161 / 4.0, 0.9926 / 4.0, -0.2616 / 4.0], // gamma = 1.5
 746        [0.1121 / 4.0, -0.6395 / 4.0, 1.1588 / 4.0, -0.2877 / 4.0], // gamma = 1.6
 747        [0.1300 / 4.0, -0.7649 / 4.0, 1.3159 / 4.0, -0.3080 / 4.0], // gamma = 1.7
 748        [0.1469 / 4.0, -0.8911 / 4.0, 1.4644 / 4.0, -0.3234 / 4.0], // gamma = 1.8
 749        [0.1627 / 4.0, -1.0170 / 4.0, 1.6051 / 4.0, -0.3347 / 4.0], // gamma = 1.9
 750        [0.1773 / 4.0, -1.1420 / 4.0, 1.7385 / 4.0, -0.3426 / 4.0], // gamma = 2.0
 751        [0.1908 / 4.0, -1.2652 / 4.0, 1.8650 / 4.0, -0.3476 / 4.0], // gamma = 2.1
 752        [0.2031 / 4.0, -1.3864 / 4.0, 1.9851 / 4.0, -0.3501 / 4.0], // gamma = 2.2
 753    ];
 754
 755    const NORM13: f32 = ((0x10000 as f64) / (255.0 * 255.0) * 4.0) as f32;
 756    const NORM24: f32 = ((0x100 as f64) / (255.0) * 4.0) as f32;
 757
 758    let index = ((gamma * 10.0).round() as usize).clamp(10, 22) - 10;
 759    let ratios = GAMMA_INCORRECT_TARGET_RATIOS[index];
 760
 761    [
 762        ratios[0] * NORM13,
 763        ratios[1] * NORM24,
 764        ratios[2] * NORM13,
 765        ratios[3] * NORM24,
 766    ]
 767}
 768
 769#[derive(PartialEq, Eq, Hash, Clone)]
 770pub(crate) enum AtlasKey {
 771    Glyph(RenderGlyphParams),
 772    Svg(RenderSvgParams),
 773    Image(RenderImageParams),
 774}
 775
 776impl AtlasKey {
 777    #[cfg_attr(
 778        all(
 779            any(target_os = "linux", target_os = "freebsd"),
 780            not(any(feature = "x11", feature = "wayland"))
 781        ),
 782        allow(dead_code)
 783    )]
 784    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 785        match self {
 786            AtlasKey::Glyph(params) => {
 787                if params.is_emoji {
 788                    AtlasTextureKind::Polychrome
 789                } else {
 790                    AtlasTextureKind::Monochrome
 791                }
 792            }
 793            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 794            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 795        }
 796    }
 797}
 798
 799impl From<RenderGlyphParams> for AtlasKey {
 800    fn from(params: RenderGlyphParams) -> Self {
 801        Self::Glyph(params)
 802    }
 803}
 804
 805impl From<RenderSvgParams> for AtlasKey {
 806    fn from(params: RenderSvgParams) -> Self {
 807        Self::Svg(params)
 808    }
 809}
 810
 811impl From<RenderImageParams> for AtlasKey {
 812    fn from(params: RenderImageParams) -> Self {
 813        Self::Image(params)
 814    }
 815}
 816
 817pub(crate) trait PlatformAtlas: Send + Sync {
 818    fn get_or_insert_with<'a>(
 819        &self,
 820        key: &AtlasKey,
 821        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 822    ) -> Result<Option<AtlasTile>>;
 823    fn remove(&self, key: &AtlasKey);
 824}
 825
 826struct AtlasTextureList<T> {
 827    textures: Vec<Option<T>>,
 828    free_list: Vec<usize>,
 829}
 830
 831impl<T> Default for AtlasTextureList<T> {
 832    fn default() -> Self {
 833        Self {
 834            textures: Vec::default(),
 835            free_list: Vec::default(),
 836        }
 837    }
 838}
 839
 840impl<T> ops::Index<usize> for AtlasTextureList<T> {
 841    type Output = Option<T>;
 842
 843    fn index(&self, index: usize) -> &Self::Output {
 844        &self.textures[index]
 845    }
 846}
 847
 848impl<T> AtlasTextureList<T> {
 849    #[allow(unused)]
 850    fn drain(&mut self) -> std::vec::Drain<'_, Option<T>> {
 851        self.free_list.clear();
 852        self.textures.drain(..)
 853    }
 854
 855    #[allow(dead_code)]
 856    fn iter_mut(&mut self) -> impl DoubleEndedIterator<Item = &mut T> {
 857        self.textures.iter_mut().flatten()
 858    }
 859}
 860
 861#[derive(Clone, Debug, PartialEq, Eq)]
 862#[repr(C)]
 863pub(crate) struct AtlasTile {
 864    pub(crate) texture_id: AtlasTextureId,
 865    pub(crate) tile_id: TileId,
 866    pub(crate) padding: u32,
 867    pub(crate) bounds: Bounds<DevicePixels>,
 868}
 869
 870#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 871#[repr(C)]
 872pub(crate) struct AtlasTextureId {
 873    // We use u32 instead of usize for Metal Shader Language compatibility
 874    pub(crate) index: u32,
 875    pub(crate) kind: AtlasTextureKind,
 876}
 877
 878#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 879#[repr(C)]
 880#[cfg_attr(
 881    all(
 882        any(target_os = "linux", target_os = "freebsd"),
 883        not(any(feature = "x11", feature = "wayland"))
 884    ),
 885    allow(dead_code)
 886)]
 887pub(crate) enum AtlasTextureKind {
 888    Monochrome = 0,
 889    Polychrome = 1,
 890}
 891
 892#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 893#[repr(C)]
 894pub(crate) struct TileId(pub(crate) u32);
 895
 896impl From<etagere::AllocId> for TileId {
 897    fn from(id: etagere::AllocId) -> Self {
 898        Self(id.serialize())
 899    }
 900}
 901
 902impl From<TileId> for etagere::AllocId {
 903    fn from(id: TileId) -> Self {
 904        Self::deserialize(id.0)
 905    }
 906}
 907
 908pub(crate) struct PlatformInputHandler {
 909    cx: AsyncWindowContext,
 910    handler: Box<dyn InputHandler>,
 911}
 912
 913#[cfg_attr(
 914    all(
 915        any(target_os = "linux", target_os = "freebsd"),
 916        not(any(feature = "x11", feature = "wayland"))
 917    ),
 918    allow(dead_code)
 919)]
 920impl PlatformInputHandler {
 921    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 922        Self { cx, handler }
 923    }
 924
 925    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 926        self.cx
 927            .update(|window, cx| {
 928                self.handler
 929                    .selected_text_range(ignore_disabled_input, window, cx)
 930            })
 931            .ok()
 932            .flatten()
 933    }
 934
 935    #[cfg_attr(target_os = "windows", allow(dead_code))]
 936    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 937        self.cx
 938            .update(|window, cx| self.handler.marked_text_range(window, cx))
 939            .ok()
 940            .flatten()
 941    }
 942
 943    #[cfg_attr(
 944        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
 945        allow(dead_code)
 946    )]
 947    fn text_for_range(
 948        &mut self,
 949        range_utf16: Range<usize>,
 950        adjusted: &mut Option<Range<usize>>,
 951    ) -> Option<String> {
 952        self.cx
 953            .update(|window, cx| {
 954                self.handler
 955                    .text_for_range(range_utf16, adjusted, window, cx)
 956            })
 957            .ok()
 958            .flatten()
 959    }
 960
 961    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 962        self.cx
 963            .update(|window, cx| {
 964                self.handler
 965                    .replace_text_in_range(replacement_range, text, window, cx);
 966            })
 967            .ok();
 968    }
 969
 970    pub fn replace_and_mark_text_in_range(
 971        &mut self,
 972        range_utf16: Option<Range<usize>>,
 973        new_text: &str,
 974        new_selected_range: Option<Range<usize>>,
 975    ) {
 976        self.cx
 977            .update(|window, cx| {
 978                self.handler.replace_and_mark_text_in_range(
 979                    range_utf16,
 980                    new_text,
 981                    new_selected_range,
 982                    window,
 983                    cx,
 984                )
 985            })
 986            .ok();
 987    }
 988
 989    #[cfg_attr(target_os = "windows", allow(dead_code))]
 990    fn unmark_text(&mut self) {
 991        self.cx
 992            .update(|window, cx| self.handler.unmark_text(window, cx))
 993            .ok();
 994    }
 995
 996    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 997        self.cx
 998            .update(|window, cx| self.handler.bounds_for_range(range_utf16, window, cx))
 999            .ok()
1000            .flatten()
1001    }
1002
1003    #[allow(dead_code)]
1004    fn apple_press_and_hold_enabled(&mut self) -> bool {
1005        self.handler.apple_press_and_hold_enabled()
1006    }
1007
1008    pub(crate) fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) {
1009        self.handler.replace_text_in_range(None, input, window, cx);
1010    }
1011
1012    pub fn selected_bounds(&mut self, window: &mut Window, cx: &mut App) -> Option<Bounds<Pixels>> {
1013        let selection = self.handler.selected_text_range(true, window, cx)?;
1014        self.handler.bounds_for_range(
1015            if selection.reversed {
1016                selection.range.start..selection.range.start
1017            } else {
1018                selection.range.end..selection.range.end
1019            },
1020            window,
1021            cx,
1022        )
1023    }
1024
1025    #[allow(unused)]
1026    pub fn character_index_for_point(&mut self, point: Point<Pixels>) -> Option<usize> {
1027        self.cx
1028            .update(|window, cx| self.handler.character_index_for_point(point, window, cx))
1029            .ok()
1030            .flatten()
1031    }
1032
1033    #[allow(dead_code)]
1034    pub(crate) fn accepts_text_input(&mut self, window: &mut Window, cx: &mut App) -> bool {
1035        self.handler.accepts_text_input(window, cx)
1036    }
1037}
1038
1039/// A struct representing a selection in a text buffer, in UTF16 characters.
1040/// This is different from a range because the head may be before the tail.
1041#[derive(Debug)]
1042pub struct UTF16Selection {
1043    /// The range of text in the document this selection corresponds to
1044    /// in UTF16 characters.
1045    pub range: Range<usize>,
1046    /// Whether the head of this selection is at the start (true), or end (false)
1047    /// of the range
1048    pub reversed: bool,
1049}
1050
1051/// Zed's interface for handling text input from the platform's IME system
1052/// This is currently a 1:1 exposure of the NSTextInputClient API:
1053///
1054/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
1055pub trait InputHandler: 'static {
1056    /// Get the range of the user's currently selected text, if any
1057    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
1058    ///
1059    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1060    fn selected_text_range(
1061        &mut self,
1062        ignore_disabled_input: bool,
1063        window: &mut Window,
1064        cx: &mut App,
1065    ) -> Option<UTF16Selection>;
1066
1067    /// Get the range of the currently marked text, if any
1068    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
1069    ///
1070    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
1071    fn marked_text_range(&mut self, window: &mut Window, cx: &mut App) -> Option<Range<usize>>;
1072
1073    /// Get the text for the given document range in UTF-16 characters
1074    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
1075    ///
1076    /// range_utf16 is in terms of UTF-16 characters
1077    fn text_for_range(
1078        &mut self,
1079        range_utf16: Range<usize>,
1080        adjusted_range: &mut Option<Range<usize>>,
1081        window: &mut Window,
1082        cx: &mut App,
1083    ) -> Option<String>;
1084
1085    /// Replace the text in the given document range with the given text
1086    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
1087    ///
1088    /// replacement_range is in terms of UTF-16 characters
1089    fn replace_text_in_range(
1090        &mut self,
1091        replacement_range: Option<Range<usize>>,
1092        text: &str,
1093        window: &mut Window,
1094        cx: &mut App,
1095    );
1096
1097    /// Replace the text in the given document range with the given text,
1098    /// and mark the given text as part of an IME 'composing' state
1099    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
1100    ///
1101    /// range_utf16 is in terms of UTF-16 characters
1102    /// new_selected_range is in terms of UTF-16 characters
1103    fn replace_and_mark_text_in_range(
1104        &mut self,
1105        range_utf16: Option<Range<usize>>,
1106        new_text: &str,
1107        new_selected_range: Option<Range<usize>>,
1108        window: &mut Window,
1109        cx: &mut App,
1110    );
1111
1112    /// Remove the IME 'composing' state from the document
1113    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
1114    fn unmark_text(&mut self, window: &mut Window, cx: &mut App);
1115
1116    /// Get the bounds of the given document range in screen coordinates
1117    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
1118    ///
1119    /// This is used for positioning the IME candidate window
1120    fn bounds_for_range(
1121        &mut self,
1122        range_utf16: Range<usize>,
1123        window: &mut Window,
1124        cx: &mut App,
1125    ) -> Option<Bounds<Pixels>>;
1126
1127    /// Get the character offset for the given point in terms of UTF16 characters
1128    ///
1129    /// Corresponds to [characterIndexForPoint:](https://developer.apple.com/documentation/appkit/nstextinputclient/characterindex(for:))
1130    fn character_index_for_point(
1131        &mut self,
1132        point: Point<Pixels>,
1133        window: &mut Window,
1134        cx: &mut App,
1135    ) -> Option<usize>;
1136
1137    /// Allows a given input context to opt into getting raw key repeats instead of
1138    /// sending these to the platform.
1139    /// TODO: Ideally we should be able to set ApplePressAndHoldEnabled in NSUserDefaults
1140    /// (which is how iTerm does it) but it doesn't seem to work for me.
1141    #[allow(dead_code)]
1142    fn apple_press_and_hold_enabled(&mut self) -> bool {
1143        true
1144    }
1145
1146    /// Returns whether this handler is accepting text input to be inserted.
1147    fn accepts_text_input(&mut self, _window: &mut Window, _cx: &mut App) -> bool {
1148        true
1149    }
1150}
1151
1152/// The variables that can be configured when creating a new window
1153#[derive(Debug)]
1154pub struct WindowOptions {
1155    /// Specifies the state and bounds of the window in screen coordinates.
1156    /// - `None`: Inherit the bounds.
1157    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
1158    pub window_bounds: Option<WindowBounds>,
1159
1160    /// The titlebar configuration of the window
1161    pub titlebar: Option<TitlebarOptions>,
1162
1163    /// Whether the window should be focused when created
1164    pub focus: bool,
1165
1166    /// Whether the window should be shown when created
1167    pub show: bool,
1168
1169    /// The kind of window to create
1170    pub kind: WindowKind,
1171
1172    /// Whether the window should be movable by the user
1173    pub is_movable: bool,
1174
1175    /// Whether the window should be resizable by the user
1176    pub is_resizable: bool,
1177
1178    /// Whether the window should be minimized by the user
1179    pub is_minimizable: bool,
1180
1181    /// The display to create the window on, if this is None,
1182    /// the window will be created on the main display
1183    pub display_id: Option<DisplayId>,
1184
1185    /// The appearance of the window background.
1186    pub window_background: WindowBackgroundAppearance,
1187
1188    /// Application identifier of the window. Can by used by desktop environments to group applications together.
1189    pub app_id: Option<String>,
1190
1191    /// Window minimum size
1192    pub window_min_size: Option<Size<Pixels>>,
1193
1194    /// Whether to use client or server side decorations. Wayland only
1195    /// Note that this may be ignored.
1196    pub window_decorations: Option<WindowDecorations>,
1197
1198    /// Tab group name, allows opening the window as a native tab on macOS 10.12+. Windows with the same tabbing identifier will be grouped together.
1199    pub tabbing_identifier: Option<String>,
1200}
1201
1202/// The variables that can be configured when creating a new window
1203#[derive(Debug)]
1204#[cfg_attr(
1205    all(
1206        any(target_os = "linux", target_os = "freebsd"),
1207        not(any(feature = "x11", feature = "wayland"))
1208    ),
1209    allow(dead_code)
1210)]
1211pub(crate) struct WindowParams {
1212    pub bounds: Bounds<Pixels>,
1213
1214    /// The titlebar configuration of the window
1215    #[cfg_attr(feature = "wayland", allow(dead_code))]
1216    pub titlebar: Option<TitlebarOptions>,
1217
1218    /// The kind of window to create
1219    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1220    pub kind: WindowKind,
1221
1222    /// Whether the window should be movable by the user
1223    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1224    pub is_movable: bool,
1225
1226    /// Whether the window should be resizable by the user
1227    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1228    pub is_resizable: bool,
1229
1230    /// Whether the window should be minimized by the user
1231    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1232    pub is_minimizable: bool,
1233
1234    #[cfg_attr(
1235        any(target_os = "linux", target_os = "freebsd", target_os = "windows"),
1236        allow(dead_code)
1237    )]
1238    pub focus: bool,
1239
1240    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1241    pub show: bool,
1242
1243    #[cfg_attr(feature = "wayland", allow(dead_code))]
1244    pub display_id: Option<DisplayId>,
1245
1246    pub window_min_size: Option<Size<Pixels>>,
1247    #[cfg(target_os = "macos")]
1248    pub tabbing_identifier: Option<String>,
1249}
1250
1251/// Represents the status of how a window should be opened.
1252#[derive(Debug, Copy, Clone, PartialEq)]
1253pub enum WindowBounds {
1254    /// Indicates that the window should open in a windowed state with the given bounds.
1255    Windowed(Bounds<Pixels>),
1256    /// Indicates that the window should open in a maximized state.
1257    /// The bounds provided here represent the restore size of the window.
1258    Maximized(Bounds<Pixels>),
1259    /// Indicates that the window should open in fullscreen mode.
1260    /// The bounds provided here represent the restore size of the window.
1261    Fullscreen(Bounds<Pixels>),
1262}
1263
1264impl Default for WindowBounds {
1265    fn default() -> Self {
1266        WindowBounds::Windowed(Bounds::default())
1267    }
1268}
1269
1270impl WindowBounds {
1271    /// Retrieve the inner bounds
1272    pub fn get_bounds(&self) -> Bounds<Pixels> {
1273        match self {
1274            WindowBounds::Windowed(bounds) => *bounds,
1275            WindowBounds::Maximized(bounds) => *bounds,
1276            WindowBounds::Fullscreen(bounds) => *bounds,
1277        }
1278    }
1279
1280    /// Creates a new window bounds that centers the window on the screen.
1281    pub fn centered(size: Size<Pixels>, cx: &App) -> Self {
1282        WindowBounds::Windowed(Bounds::centered(None, size, cx))
1283    }
1284}
1285
1286impl Default for WindowOptions {
1287    fn default() -> Self {
1288        Self {
1289            window_bounds: None,
1290            titlebar: Some(TitlebarOptions {
1291                title: Default::default(),
1292                appears_transparent: Default::default(),
1293                traffic_light_position: Default::default(),
1294            }),
1295            focus: true,
1296            show: true,
1297            kind: WindowKind::Normal,
1298            is_movable: true,
1299            is_resizable: true,
1300            is_minimizable: true,
1301            display_id: None,
1302            window_background: WindowBackgroundAppearance::default(),
1303            app_id: None,
1304            window_min_size: None,
1305            window_decorations: None,
1306            tabbing_identifier: None,
1307        }
1308    }
1309}
1310
1311/// The options that can be configured for a window's titlebar
1312#[derive(Debug, Default)]
1313pub struct TitlebarOptions {
1314    /// The initial title of the window
1315    pub title: Option<SharedString>,
1316
1317    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
1318    /// Refer to [`WindowOptions::window_decorations`] on Linux
1319    pub appears_transparent: bool,
1320
1321    /// The position of the macOS traffic light buttons
1322    pub traffic_light_position: Option<Point<Pixels>>,
1323}
1324
1325/// The kind of window to create
1326#[derive(Clone, Debug, PartialEq, Eq)]
1327pub enum WindowKind {
1328    /// A normal application window
1329    Normal,
1330
1331    /// A window that appears above all other windows, usually used for alerts or popups
1332    /// use sparingly!
1333    PopUp,
1334
1335    /// A floating window that appears on top of its parent window
1336    Floating,
1337
1338    /// A Wayland LayerShell window, used to draw overlays or backgrounds for applications such as
1339    /// docks, notifications or wallpapers.
1340    #[cfg(all(target_os = "linux", feature = "wayland"))]
1341    LayerShell(layer_shell::LayerShellOptions),
1342}
1343
1344/// The appearance of the window, as defined by the operating system.
1345///
1346/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
1347/// values.
1348#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1349pub enum WindowAppearance {
1350    /// A light appearance.
1351    ///
1352    /// On macOS, this corresponds to the `aqua` appearance.
1353    #[default]
1354    Light,
1355
1356    /// A light appearance with vibrant colors.
1357    ///
1358    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
1359    VibrantLight,
1360
1361    /// A dark appearance.
1362    ///
1363    /// On macOS, this corresponds to the `darkAqua` appearance.
1364    Dark,
1365
1366    /// A dark appearance with vibrant colors.
1367    ///
1368    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
1369    VibrantDark,
1370}
1371
1372/// The appearance of the background of the window itself, when there is
1373/// no content or the content is transparent.
1374#[derive(Copy, Clone, Debug, Default, PartialEq)]
1375pub enum WindowBackgroundAppearance {
1376    /// Opaque.
1377    ///
1378    /// This lets the window manager know that content behind this
1379    /// window does not need to be drawn.
1380    ///
1381    /// Actual color depends on the system and themes should define a fully
1382    /// opaque background color instead.
1383    #[default]
1384    Opaque,
1385    /// Plain alpha transparency.
1386    Transparent,
1387    /// Transparency, but the contents behind the window are blurred.
1388    ///
1389    /// Not always supported.
1390    Blurred,
1391    /// The Mica backdrop material, supported on Windows 11.
1392    MicaBackdrop,
1393    /// The Mica Alt backdrop material, supported on Windows 11.
1394    MicaAltBackdrop,
1395}
1396
1397/// The options that can be configured for a file dialog prompt
1398#[derive(Clone, Debug)]
1399pub struct PathPromptOptions {
1400    /// Should the prompt allow files to be selected?
1401    pub files: bool,
1402    /// Should the prompt allow directories to be selected?
1403    pub directories: bool,
1404    /// Should the prompt allow multiple files to be selected?
1405    pub multiple: bool,
1406    /// The prompt to show to a user when selecting a path
1407    pub prompt: Option<SharedString>,
1408}
1409
1410/// What kind of prompt styling to show
1411#[derive(Copy, Clone, Debug, PartialEq)]
1412pub enum PromptLevel {
1413    /// A prompt that is shown when the user should be notified of something
1414    Info,
1415
1416    /// A prompt that is shown when the user needs to be warned of a potential problem
1417    Warning,
1418
1419    /// A prompt that is shown when a critical problem has occurred
1420    Critical,
1421}
1422
1423/// Prompt Button
1424#[derive(Clone, Debug, PartialEq)]
1425pub enum PromptButton {
1426    /// Ok button
1427    Ok(SharedString),
1428    /// Cancel button
1429    Cancel(SharedString),
1430    /// Other button
1431    Other(SharedString),
1432}
1433
1434impl PromptButton {
1435    /// Create a button with label
1436    pub fn new(label: impl Into<SharedString>) -> Self {
1437        PromptButton::Other(label.into())
1438    }
1439
1440    /// Create an Ok button
1441    pub fn ok(label: impl Into<SharedString>) -> Self {
1442        PromptButton::Ok(label.into())
1443    }
1444
1445    /// Create a Cancel button
1446    pub fn cancel(label: impl Into<SharedString>) -> Self {
1447        PromptButton::Cancel(label.into())
1448    }
1449
1450    #[allow(dead_code)]
1451    pub(crate) fn is_cancel(&self) -> bool {
1452        matches!(self, PromptButton::Cancel(_))
1453    }
1454
1455    /// Returns the label of the button
1456    pub fn label(&self) -> &SharedString {
1457        match self {
1458            PromptButton::Ok(label) => label,
1459            PromptButton::Cancel(label) => label,
1460            PromptButton::Other(label) => label,
1461        }
1462    }
1463}
1464
1465impl From<&str> for PromptButton {
1466    fn from(value: &str) -> Self {
1467        match value.to_lowercase().as_str() {
1468            "ok" => PromptButton::Ok("Ok".into()),
1469            "cancel" => PromptButton::Cancel("Cancel".into()),
1470            _ => PromptButton::Other(SharedString::from(value.to_owned())),
1471        }
1472    }
1473}
1474
1475/// The style of the cursor (pointer)
1476#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
1477pub enum CursorStyle {
1478    /// The default cursor
1479    #[default]
1480    Arrow,
1481
1482    /// A text input cursor
1483    /// corresponds to the CSS cursor value `text`
1484    IBeam,
1485
1486    /// A crosshair cursor
1487    /// corresponds to the CSS cursor value `crosshair`
1488    Crosshair,
1489
1490    /// A closed hand cursor
1491    /// corresponds to the CSS cursor value `grabbing`
1492    ClosedHand,
1493
1494    /// An open hand cursor
1495    /// corresponds to the CSS cursor value `grab`
1496    OpenHand,
1497
1498    /// A pointing hand cursor
1499    /// corresponds to the CSS cursor value `pointer`
1500    PointingHand,
1501
1502    /// A resize left cursor
1503    /// corresponds to the CSS cursor value `w-resize`
1504    ResizeLeft,
1505
1506    /// A resize right cursor
1507    /// corresponds to the CSS cursor value `e-resize`
1508    ResizeRight,
1509
1510    /// A resize cursor to the left and right
1511    /// corresponds to the CSS cursor value `ew-resize`
1512    ResizeLeftRight,
1513
1514    /// A resize up cursor
1515    /// corresponds to the CSS cursor value `n-resize`
1516    ResizeUp,
1517
1518    /// A resize down cursor
1519    /// corresponds to the CSS cursor value `s-resize`
1520    ResizeDown,
1521
1522    /// A resize cursor directing up and down
1523    /// corresponds to the CSS cursor value `ns-resize`
1524    ResizeUpDown,
1525
1526    /// A resize cursor directing up-left and down-right
1527    /// corresponds to the CSS cursor value `nesw-resize`
1528    ResizeUpLeftDownRight,
1529
1530    /// A resize cursor directing up-right and down-left
1531    /// corresponds to the CSS cursor value `nwse-resize`
1532    ResizeUpRightDownLeft,
1533
1534    /// A cursor indicating that the item/column can be resized horizontally.
1535    /// corresponds to the CSS cursor value `col-resize`
1536    ResizeColumn,
1537
1538    /// A cursor indicating that the item/row can be resized vertically.
1539    /// corresponds to the CSS cursor value `row-resize`
1540    ResizeRow,
1541
1542    /// A text input cursor for vertical layout
1543    /// corresponds to the CSS cursor value `vertical-text`
1544    IBeamCursorForVerticalLayout,
1545
1546    /// A cursor indicating that the operation is not allowed
1547    /// corresponds to the CSS cursor value `not-allowed`
1548    OperationNotAllowed,
1549
1550    /// A cursor indicating that the operation will result in a link
1551    /// corresponds to the CSS cursor value `alias`
1552    DragLink,
1553
1554    /// A cursor indicating that the operation will result in a copy
1555    /// corresponds to the CSS cursor value `copy`
1556    DragCopy,
1557
1558    /// A cursor indicating that the operation will result in a context menu
1559    /// corresponds to the CSS cursor value `context-menu`
1560    ContextualMenu,
1561
1562    /// Hide the cursor
1563    None,
1564}
1565
1566/// A clipboard item that should be copied to the clipboard
1567#[derive(Clone, Debug, Eq, PartialEq)]
1568pub struct ClipboardItem {
1569    entries: Vec<ClipboardEntry>,
1570}
1571
1572/// Either a ClipboardString or a ClipboardImage
1573#[derive(Clone, Debug, Eq, PartialEq)]
1574pub enum ClipboardEntry {
1575    /// A string entry
1576    String(ClipboardString),
1577    /// An image entry
1578    Image(Image),
1579    /// A file entry
1580    ExternalPaths(crate::ExternalPaths),
1581}
1582
1583impl ClipboardItem {
1584    /// Create a new ClipboardItem::String with no associated metadata
1585    pub fn new_string(text: String) -> Self {
1586        Self {
1587            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1588        }
1589    }
1590
1591    /// Create a new ClipboardItem::String with the given text and associated metadata
1592    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1593        Self {
1594            entries: vec![ClipboardEntry::String(ClipboardString {
1595                text,
1596                metadata: Some(metadata),
1597            })],
1598        }
1599    }
1600
1601    /// Create a new ClipboardItem::String with the given text and associated metadata
1602    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1603        Self {
1604            entries: vec![ClipboardEntry::String(
1605                ClipboardString::new(text).with_json_metadata(metadata),
1606            )],
1607        }
1608    }
1609
1610    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1611    pub fn new_image(image: &Image) -> Self {
1612        Self {
1613            entries: vec![ClipboardEntry::Image(image.clone())],
1614        }
1615    }
1616
1617    /// Concatenates together all the ClipboardString entries in the item.
1618    /// Returns None if there were no ClipboardString entries.
1619    pub fn text(&self) -> Option<String> {
1620        let mut answer = String::new();
1621
1622        for entry in self.entries.iter() {
1623            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1624                answer.push_str(text);
1625            }
1626        }
1627
1628        if answer.is_empty() {
1629            for entry in self.entries.iter() {
1630                if let ClipboardEntry::ExternalPaths(paths) = entry {
1631                    for path in &paths.0 {
1632                        use std::fmt::Write as _;
1633                        _ = write!(answer, "{}", path.display());
1634                    }
1635                }
1636            }
1637        }
1638
1639        if !answer.is_empty() {
1640            Some(answer)
1641        } else {
1642            None
1643        }
1644    }
1645
1646    /// If this item is one ClipboardEntry::String, returns its metadata.
1647    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1648    pub fn metadata(&self) -> Option<&String> {
1649        match self.entries().first() {
1650            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1651                clipboard_string.metadata.as_ref()
1652            }
1653            _ => None,
1654        }
1655    }
1656
1657    /// Get the item's entries
1658    pub fn entries(&self) -> &[ClipboardEntry] {
1659        &self.entries
1660    }
1661
1662    /// Get owned versions of the item's entries
1663    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1664        self.entries.into_iter()
1665    }
1666}
1667
1668impl From<ClipboardString> for ClipboardEntry {
1669    fn from(value: ClipboardString) -> Self {
1670        Self::String(value)
1671    }
1672}
1673
1674impl From<String> for ClipboardEntry {
1675    fn from(value: String) -> Self {
1676        Self::from(ClipboardString::from(value))
1677    }
1678}
1679
1680impl From<Image> for ClipboardEntry {
1681    fn from(value: Image) -> Self {
1682        Self::Image(value)
1683    }
1684}
1685
1686impl From<ClipboardEntry> for ClipboardItem {
1687    fn from(value: ClipboardEntry) -> Self {
1688        Self {
1689            entries: vec![value],
1690        }
1691    }
1692}
1693
1694impl From<String> for ClipboardItem {
1695    fn from(value: String) -> Self {
1696        Self::from(ClipboardEntry::from(value))
1697    }
1698}
1699
1700impl From<Image> for ClipboardItem {
1701    fn from(value: Image) -> Self {
1702        Self::from(ClipboardEntry::from(value))
1703    }
1704}
1705
1706/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1707#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1708pub enum ImageFormat {
1709    // Sorted from most to least likely to be pasted into an editor,
1710    // which matters when we iterate through them trying to see if
1711    // clipboard content matches them.
1712    /// .png
1713    Png,
1714    /// .jpeg or .jpg
1715    Jpeg,
1716    /// .webp
1717    Webp,
1718    /// .gif
1719    Gif,
1720    /// .svg
1721    Svg,
1722    /// .bmp
1723    Bmp,
1724    /// .tif or .tiff
1725    Tiff,
1726    /// .ico
1727    Ico,
1728}
1729
1730impl ImageFormat {
1731    /// Returns the mime type for the ImageFormat
1732    pub const fn mime_type(self) -> &'static str {
1733        match self {
1734            ImageFormat::Png => "image/png",
1735            ImageFormat::Jpeg => "image/jpeg",
1736            ImageFormat::Webp => "image/webp",
1737            ImageFormat::Gif => "image/gif",
1738            ImageFormat::Svg => "image/svg+xml",
1739            ImageFormat::Bmp => "image/bmp",
1740            ImageFormat::Tiff => "image/tiff",
1741            ImageFormat::Ico => "image/ico",
1742        }
1743    }
1744
1745    /// Returns the ImageFormat for the given mime type
1746    pub fn from_mime_type(mime_type: &str) -> Option<Self> {
1747        match mime_type {
1748            "image/png" => Some(Self::Png),
1749            "image/jpeg" | "image/jpg" => Some(Self::Jpeg),
1750            "image/webp" => Some(Self::Webp),
1751            "image/gif" => Some(Self::Gif),
1752            "image/svg+xml" => Some(Self::Svg),
1753            "image/bmp" => Some(Self::Bmp),
1754            "image/tiff" | "image/tif" => Some(Self::Tiff),
1755            "image/ico" => Some(Self::Ico),
1756            _ => None,
1757        }
1758    }
1759}
1760
1761/// An image, with a format and certain bytes
1762#[derive(Clone, Debug, PartialEq, Eq)]
1763pub struct Image {
1764    /// The image format the bytes represent (e.g. PNG)
1765    pub format: ImageFormat,
1766    /// The raw image bytes
1767    pub bytes: Vec<u8>,
1768    /// The unique ID for the image
1769    id: u64,
1770}
1771
1772impl Hash for Image {
1773    fn hash<H: Hasher>(&self, state: &mut H) {
1774        state.write_u64(self.id);
1775    }
1776}
1777
1778impl Image {
1779    /// An empty image containing no data
1780    pub fn empty() -> Self {
1781        Self::from_bytes(ImageFormat::Png, Vec::new())
1782    }
1783
1784    /// Create an image from a format and bytes
1785    pub fn from_bytes(format: ImageFormat, bytes: Vec<u8>) -> Self {
1786        Self {
1787            id: hash(&bytes),
1788            format,
1789            bytes,
1790        }
1791    }
1792
1793    /// Get this image's ID
1794    pub fn id(&self) -> u64 {
1795        self.id
1796    }
1797
1798    /// Use the GPUI `use_asset` API to make this image renderable
1799    pub fn use_render_image(
1800        self: Arc<Self>,
1801        window: &mut Window,
1802        cx: &mut App,
1803    ) -> Option<Arc<RenderImage>> {
1804        ImageSource::Image(self)
1805            .use_data(None, window, cx)
1806            .and_then(|result| result.ok())
1807    }
1808
1809    /// Use the GPUI `get_asset` API to make this image renderable
1810    pub fn get_render_image(
1811        self: Arc<Self>,
1812        window: &mut Window,
1813        cx: &mut App,
1814    ) -> Option<Arc<RenderImage>> {
1815        ImageSource::Image(self)
1816            .get_data(None, window, cx)
1817            .and_then(|result| result.ok())
1818    }
1819
1820    /// Use the GPUI `remove_asset` API to drop this image, if possible.
1821    pub fn remove_asset(self: Arc<Self>, cx: &mut App) {
1822        ImageSource::Image(self).remove_asset(cx);
1823    }
1824
1825    /// Convert the clipboard image to an `ImageData` object.
1826    pub fn to_image_data(&self, svg_renderer: SvgRenderer) -> Result<Arc<RenderImage>> {
1827        fn frames_for_image(
1828            bytes: &[u8],
1829            format: image::ImageFormat,
1830        ) -> Result<SmallVec<[Frame; 1]>> {
1831            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1832
1833            // Convert from RGBA to BGRA.
1834            for pixel in data.chunks_exact_mut(4) {
1835                pixel.swap(0, 2);
1836            }
1837
1838            Ok(SmallVec::from_elem(Frame::new(data), 1))
1839        }
1840
1841        let frames = match self.format {
1842            ImageFormat::Gif => {
1843                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1844                let mut frames = SmallVec::new();
1845
1846                for frame in decoder.into_frames() {
1847                    let mut frame = frame?;
1848                    // Convert from RGBA to BGRA.
1849                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1850                        pixel.swap(0, 2);
1851                    }
1852                    frames.push(frame);
1853                }
1854
1855                frames
1856            }
1857            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1858            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1859            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1860            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1861            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1862            ImageFormat::Ico => frames_for_image(&self.bytes, image::ImageFormat::Ico)?,
1863            ImageFormat::Svg => {
1864                return svg_renderer
1865                    .render_single_frame(&self.bytes, 1.0, false)
1866                    .map_err(Into::into);
1867            }
1868        };
1869
1870        Ok(Arc::new(RenderImage::new(frames)))
1871    }
1872
1873    /// Get the format of the clipboard image
1874    pub fn format(&self) -> ImageFormat {
1875        self.format
1876    }
1877
1878    /// Get the raw bytes of the clipboard image
1879    pub fn bytes(&self) -> &[u8] {
1880        self.bytes.as_slice()
1881    }
1882}
1883
1884/// A clipboard item that should be copied to the clipboard
1885#[derive(Clone, Debug, Eq, PartialEq)]
1886pub struct ClipboardString {
1887    pub(crate) text: String,
1888    pub(crate) metadata: Option<String>,
1889}
1890
1891impl ClipboardString {
1892    /// Create a new clipboard string with the given text
1893    pub fn new(text: String) -> Self {
1894        Self {
1895            text,
1896            metadata: None,
1897        }
1898    }
1899
1900    /// Return a new clipboard item with the metadata replaced by the given metadata,
1901    /// after serializing it as JSON.
1902    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1903        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1904        self
1905    }
1906
1907    /// Get the text of the clipboard string
1908    pub fn text(&self) -> &String {
1909        &self.text
1910    }
1911
1912    /// Get the owned text of the clipboard string
1913    pub fn into_text(self) -> String {
1914        self.text
1915    }
1916
1917    /// Get the metadata of the clipboard string, formatted as JSON
1918    pub fn metadata_json<T>(&self) -> Option<T>
1919    where
1920        T: for<'a> Deserialize<'a>,
1921    {
1922        self.metadata
1923            .as_ref()
1924            .and_then(|m| serde_json::from_str(m).ok())
1925    }
1926
1927    #[cfg_attr(any(target_os = "linux", target_os = "freebsd"), allow(dead_code))]
1928    pub(crate) fn text_hash(text: &str) -> u64 {
1929        let mut hasher = SeaHasher::new();
1930        text.hash(&mut hasher);
1931        hasher.finish()
1932    }
1933}
1934
1935impl From<String> for ClipboardString {
1936    fn from(value: String) -> Self {
1937        Self {
1938            text: value,
1939            metadata: None,
1940        }
1941    }
1942}