platform.rs

   1// todo(windows): remove
   2#![cfg_attr(windows, allow(dead_code))]
   3
   4mod app_menu;
   5mod keystroke;
   6
   7#[cfg(target_os = "linux")]
   8mod linux;
   9
  10#[cfg(target_os = "macos")]
  11mod mac;
  12
  13#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-blade"))]
  14mod blade;
  15
  16#[cfg(any(test, feature = "test-support"))]
  17mod test;
  18
  19#[cfg(target_os = "windows")]
  20mod windows;
  21
  22use crate::{
  23    point, Action, AnyWindowHandle, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds,
  24    DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor,
  25    GPUSpecs, GlyphId, ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point,
  26    RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, SharedString, Size,
  27    SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
  28};
  29use anyhow::Result;
  30use async_task::Runnable;
  31use futures::channel::oneshot;
  32use image::codecs::gif::GifDecoder;
  33use image::{AnimationDecoder as _, Frame};
  34use parking::Unparker;
  35use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
  36use seahash::SeaHasher;
  37use serde::{Deserialize, Serialize};
  38use smallvec::SmallVec;
  39use std::borrow::Cow;
  40use std::hash::{Hash, Hasher};
  41use std::io::Cursor;
  42use std::time::{Duration, Instant};
  43use std::{
  44    fmt::{self, Debug},
  45    ops::Range,
  46    path::{Path, PathBuf},
  47    rc::Rc,
  48    sync::Arc,
  49};
  50use strum::EnumIter;
  51use uuid::Uuid;
  52
  53pub use app_menu::*;
  54pub use keystroke::*;
  55
  56#[cfg(target_os = "linux")]
  57pub(crate) use linux::*;
  58#[cfg(target_os = "macos")]
  59pub(crate) use mac::*;
  60pub use semantic_version::SemanticVersion;
  61#[cfg(any(test, feature = "test-support"))]
  62pub(crate) use test::*;
  63#[cfg(target_os = "windows")]
  64pub(crate) use windows::*;
  65
  66#[cfg(target_os = "macos")]
  67pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
  68    Rc::new(MacPlatform::new(headless))
  69}
  70
  71#[cfg(target_os = "linux")]
  72pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
  73    if headless {
  74        return Rc::new(HeadlessClient::new());
  75    }
  76
  77    match guess_compositor() {
  78        "Wayland" => Rc::new(WaylandClient::new()),
  79        "X11" => Rc::new(X11Client::new()),
  80        "Headless" => Rc::new(HeadlessClient::new()),
  81        _ => unreachable!(),
  82    }
  83}
  84
  85/// Return which compositor we're guessing we'll use.
  86/// Does not attempt to connect to the given compositor
  87#[cfg(target_os = "linux")]
  88#[inline]
  89pub fn guess_compositor() -> &'static str {
  90    if std::env::var_os("ZED_HEADLESS").is_some() {
  91        return "Headless";
  92    }
  93    let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
  94    let x11_display = std::env::var_os("DISPLAY");
  95
  96    let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
  97    let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
  98
  99    if use_wayland {
 100        "Wayland"
 101    } else if use_x11 {
 102        "X11"
 103    } else {
 104        "Headless"
 105    }
 106}
 107
 108#[cfg(target_os = "windows")]
 109pub(crate) fn current_platform(_headless: bool) -> Rc<dyn Platform> {
 110    Rc::new(WindowsPlatform::new())
 111}
 112
 113pub(crate) trait Platform: 'static {
 114    fn background_executor(&self) -> BackgroundExecutor;
 115    fn foreground_executor(&self) -> ForegroundExecutor;
 116    fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
 117
 118    fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
 119    fn quit(&self);
 120    fn restart(&self, binary_path: Option<PathBuf>);
 121    fn activate(&self, ignoring_other_apps: bool);
 122    fn hide(&self);
 123    fn hide_other_apps(&self);
 124    fn unhide_other_apps(&self);
 125
 126    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 127    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 128    fn active_window(&self) -> Option<AnyWindowHandle>;
 129    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 130        None
 131    }
 132
 133    fn open_window(
 134        &self,
 135        handle: AnyWindowHandle,
 136        options: WindowParams,
 137    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
 138
 139    /// Returns the appearance of the application's windows.
 140    fn window_appearance(&self) -> WindowAppearance;
 141
 142    fn open_url(&self, url: &str);
 143    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
 144    fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
 145
 146    fn prompt_for_paths(
 147        &self,
 148        options: PathPromptOptions,
 149    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
 150    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>>;
 151    fn reveal_path(&self, path: &Path);
 152
 153    fn on_quit(&self, callback: Box<dyn FnMut()>);
 154    fn on_reopen(&self, callback: Box<dyn FnMut()>);
 155
 156    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
 157    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 158        None
 159    }
 160
 161    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
 162    fn add_recent_document(&self, _path: &Path) {}
 163    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
 164    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
 165    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
 166
 167    fn compositor_name(&self) -> &'static str {
 168        ""
 169    }
 170    fn app_path(&self) -> Result<PathBuf>;
 171    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
 172
 173    fn set_cursor_style(&self, style: CursorStyle);
 174    fn should_auto_hide_scrollbars(&self) -> bool;
 175
 176    #[cfg(target_os = "linux")]
 177    fn write_to_primary(&self, item: ClipboardItem);
 178    fn write_to_clipboard(&self, item: ClipboardItem);
 179    #[cfg(target_os = "linux")]
 180    fn read_from_primary(&self) -> Option<ClipboardItem>;
 181    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 182
 183    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
 184    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
 185    fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
 186}
 187
 188/// A handle to a platform's display, e.g. a monitor or laptop screen.
 189pub trait PlatformDisplay: Send + Sync + Debug {
 190    /// Get the ID for this display
 191    fn id(&self) -> DisplayId;
 192
 193    /// Returns a stable identifier for this display that can be persisted and used
 194    /// across system restarts.
 195    fn uuid(&self) -> Result<Uuid>;
 196
 197    /// Get the bounds for this display
 198    fn bounds(&self) -> Bounds<Pixels>;
 199
 200    /// Get the default bounds for this display to place a window
 201    fn default_bounds(&self) -> Bounds<Pixels> {
 202        let center = self.bounds().center();
 203        let offset = DEFAULT_WINDOW_SIZE / 2.0;
 204        let origin = point(center.x - offset.width, center.y - offset.height);
 205        Bounds::new(origin, DEFAULT_WINDOW_SIZE)
 206    }
 207}
 208
 209/// An opaque identifier for a hardware display
 210#[derive(PartialEq, Eq, Hash, Copy, Clone)]
 211pub struct DisplayId(pub(crate) u32);
 212
 213impl Debug for DisplayId {
 214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 215        write!(f, "DisplayId({})", self.0)
 216    }
 217}
 218
 219unsafe impl Send for DisplayId {}
 220
 221/// Which part of the window to resize
 222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 223pub enum ResizeEdge {
 224    /// The top edge
 225    Top,
 226    /// The top right corner
 227    TopRight,
 228    /// The right edge
 229    Right,
 230    /// The bottom right corner
 231    BottomRight,
 232    /// The bottom edge
 233    Bottom,
 234    /// The bottom left corner
 235    BottomLeft,
 236    /// The left edge
 237    Left,
 238    /// The top left corner
 239    TopLeft,
 240}
 241
 242/// A type to describe the appearance of a window
 243#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 244pub enum WindowDecorations {
 245    #[default]
 246    /// Server side decorations
 247    Server,
 248    /// Client side decorations
 249    Client,
 250}
 251
 252/// A type to describe how this window is currently configured
 253#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 254pub enum Decorations {
 255    /// The window is configured to use server side decorations
 256    #[default]
 257    Server,
 258    /// The window is configured to use client side decorations
 259    Client {
 260        /// The edge tiling state
 261        tiling: Tiling,
 262    },
 263}
 264
 265/// What window controls this platform supports
 266#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
 267pub struct WindowControls {
 268    /// Whether this platform supports fullscreen
 269    pub fullscreen: bool,
 270    /// Whether this platform supports maximize
 271    pub maximize: bool,
 272    /// Whether this platform supports minimize
 273    pub minimize: bool,
 274    /// Whether this platform supports a window menu
 275    pub window_menu: bool,
 276}
 277
 278impl Default for WindowControls {
 279    fn default() -> Self {
 280        // Assume that we can do anything, unless told otherwise
 281        Self {
 282            fullscreen: true,
 283            maximize: true,
 284            minimize: true,
 285            window_menu: true,
 286        }
 287    }
 288}
 289
 290/// A type to describe which sides of the window are currently tiled in some way
 291#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
 292pub struct Tiling {
 293    /// Whether the top edge is tiled
 294    pub top: bool,
 295    /// Whether the left edge is tiled
 296    pub left: bool,
 297    /// Whether the right edge is tiled
 298    pub right: bool,
 299    /// Whether the bottom edge is tiled
 300    pub bottom: bool,
 301}
 302
 303impl Tiling {
 304    /// Initializes a [`Tiling`] type with all sides tiled
 305    pub fn tiled() -> Self {
 306        Self {
 307            top: true,
 308            left: true,
 309            right: true,
 310            bottom: true,
 311        }
 312    }
 313
 314    /// Whether any edge is tiled
 315    pub fn is_tiled(&self) -> bool {
 316        self.top || self.left || self.right || self.bottom
 317    }
 318}
 319
 320pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
 321    fn bounds(&self) -> Bounds<Pixels>;
 322    fn is_maximized(&self) -> bool;
 323    fn window_bounds(&self) -> WindowBounds;
 324    fn content_size(&self) -> Size<Pixels>;
 325    fn scale_factor(&self) -> f32;
 326    fn appearance(&self) -> WindowAppearance;
 327    fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 328    fn mouse_position(&self) -> Point<Pixels>;
 329    fn modifiers(&self) -> Modifiers;
 330    fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
 331    fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
 332    fn prompt(
 333        &self,
 334        level: PromptLevel,
 335        msg: &str,
 336        detail: Option<&str>,
 337        answers: &[&str],
 338    ) -> Option<oneshot::Receiver<usize>>;
 339    fn activate(&self);
 340    fn is_active(&self) -> bool;
 341    fn is_hovered(&self) -> bool;
 342    fn set_title(&mut self, title: &str);
 343    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
 344    fn minimize(&self);
 345    fn zoom(&self);
 346    fn toggle_fullscreen(&self);
 347    fn is_fullscreen(&self) -> bool;
 348    fn on_request_frame(&self, callback: Box<dyn FnMut()>);
 349    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
 350    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
 351    fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
 352    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
 353    fn on_moved(&self, callback: Box<dyn FnMut()>);
 354    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
 355    fn on_close(&self, callback: Box<dyn FnOnce()>);
 356    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
 357    fn draw(&self, scene: &Scene);
 358    fn completed_frame(&self) {}
 359    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
 360
 361    // macOS specific methods
 362    fn set_edited(&mut self, _edited: bool) {}
 363    fn show_character_palette(&self) {}
 364
 365    #[cfg(target_os = "windows")]
 366    fn get_raw_handle(&self) -> windows::HWND;
 367
 368    // Linux specific methods
 369    fn request_decorations(&self, _decorations: WindowDecorations) {}
 370    fn show_window_menu(&self, _position: Point<Pixels>) {}
 371    fn start_window_move(&self) {}
 372    fn start_window_resize(&self, _edge: ResizeEdge) {}
 373    fn window_decorations(&self) -> Decorations {
 374        Decorations::Server
 375    }
 376    fn set_app_id(&mut self, _app_id: &str) {}
 377    fn window_controls(&self) -> WindowControls {
 378        WindowControls::default()
 379    }
 380    fn set_client_inset(&self, _inset: Pixels) {}
 381    fn gpu_specs(&self) -> Option<GPUSpecs>;
 382
 383    fn update_ime_position(&self, _bounds: Bounds<Pixels>);
 384
 385    #[cfg(any(test, feature = "test-support"))]
 386    fn as_test(&mut self) -> Option<&mut TestWindow> {
 387        None
 388    }
 389}
 390
 391/// This type is public so that our test macro can generate and use it, but it should not
 392/// be considered part of our public API.
 393#[doc(hidden)]
 394pub trait PlatformDispatcher: Send + Sync {
 395    fn is_main_thread(&self) -> bool;
 396    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 397    fn dispatch_on_main_thread(&self, runnable: Runnable);
 398    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 399    fn park(&self, timeout: Option<Duration>) -> bool;
 400    fn unparker(&self) -> Unparker;
 401    fn now(&self) -> Instant {
 402        Instant::now()
 403    }
 404
 405    #[cfg(any(test, feature = "test-support"))]
 406    fn as_test(&self) -> Option<&TestDispatcher> {
 407        None
 408    }
 409}
 410
 411pub(crate) trait PlatformTextSystem: Send + Sync {
 412    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 413    fn all_font_names(&self) -> Vec<String>;
 414    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 415    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 416    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 417    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 418    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 419    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 420    fn rasterize_glyph(
 421        &self,
 422        params: &RenderGlyphParams,
 423        raster_bounds: Bounds<DevicePixels>,
 424    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 425    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 426}
 427
 428#[derive(PartialEq, Eq, Hash, Clone)]
 429pub(crate) enum AtlasKey {
 430    Glyph(RenderGlyphParams),
 431    Svg(RenderSvgParams),
 432    Image(RenderImageParams),
 433}
 434
 435impl AtlasKey {
 436    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 437        match self {
 438            AtlasKey::Glyph(params) => {
 439                if params.is_emoji {
 440                    AtlasTextureKind::Polychrome
 441                } else {
 442                    AtlasTextureKind::Monochrome
 443                }
 444            }
 445            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 446            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 447        }
 448    }
 449}
 450
 451impl From<RenderGlyphParams> for AtlasKey {
 452    fn from(params: RenderGlyphParams) -> Self {
 453        Self::Glyph(params)
 454    }
 455}
 456
 457impl From<RenderSvgParams> for AtlasKey {
 458    fn from(params: RenderSvgParams) -> Self {
 459        Self::Svg(params)
 460    }
 461}
 462
 463impl From<RenderImageParams> for AtlasKey {
 464    fn from(params: RenderImageParams) -> Self {
 465        Self::Image(params)
 466    }
 467}
 468
 469pub(crate) trait PlatformAtlas: Send + Sync {
 470    fn get_or_insert_with<'a>(
 471        &self,
 472        key: &AtlasKey,
 473        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 474    ) -> Result<Option<AtlasTile>>;
 475}
 476
 477#[derive(Clone, Debug, PartialEq, Eq)]
 478#[repr(C)]
 479pub(crate) struct AtlasTile {
 480    pub(crate) texture_id: AtlasTextureId,
 481    pub(crate) tile_id: TileId,
 482    pub(crate) padding: u32,
 483    pub(crate) bounds: Bounds<DevicePixels>,
 484}
 485
 486#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 487#[repr(C)]
 488pub(crate) struct AtlasTextureId {
 489    // We use u32 instead of usize for Metal Shader Language compatibility
 490    pub(crate) index: u32,
 491    pub(crate) kind: AtlasTextureKind,
 492}
 493
 494#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 495#[repr(C)]
 496pub(crate) enum AtlasTextureKind {
 497    Monochrome = 0,
 498    Polychrome = 1,
 499    Path = 2,
 500}
 501
 502#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 503#[repr(C)]
 504pub(crate) struct TileId(pub(crate) u32);
 505
 506impl From<etagere::AllocId> for TileId {
 507    fn from(id: etagere::AllocId) -> Self {
 508        Self(id.serialize())
 509    }
 510}
 511
 512impl From<TileId> for etagere::AllocId {
 513    fn from(id: TileId) -> Self {
 514        Self::deserialize(id.0)
 515    }
 516}
 517
 518pub(crate) struct PlatformInputHandler {
 519    cx: AsyncWindowContext,
 520    handler: Box<dyn InputHandler>,
 521}
 522
 523impl PlatformInputHandler {
 524    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 525        Self { cx, handler }
 526    }
 527
 528    fn selected_text_range(&mut self, ignore_disabled_input: bool) -> Option<UTF16Selection> {
 529        self.cx
 530            .update(|cx| self.handler.selected_text_range(ignore_disabled_input, cx))
 531            .ok()
 532            .flatten()
 533    }
 534
 535    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 536        self.cx
 537            .update(|cx| self.handler.marked_text_range(cx))
 538            .ok()
 539            .flatten()
 540    }
 541
 542    #[cfg_attr(target_os = "linux", allow(dead_code))]
 543    fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
 544        self.cx
 545            .update(|cx| self.handler.text_for_range(range_utf16, cx))
 546            .ok()
 547            .flatten()
 548    }
 549
 550    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 551        self.cx
 552            .update(|cx| {
 553                self.handler
 554                    .replace_text_in_range(replacement_range, text, cx);
 555            })
 556            .ok();
 557    }
 558
 559    fn replace_and_mark_text_in_range(
 560        &mut self,
 561        range_utf16: Option<Range<usize>>,
 562        new_text: &str,
 563        new_selected_range: Option<Range<usize>>,
 564    ) {
 565        self.cx
 566            .update(|cx| {
 567                self.handler.replace_and_mark_text_in_range(
 568                    range_utf16,
 569                    new_text,
 570                    new_selected_range,
 571                    cx,
 572                )
 573            })
 574            .ok();
 575    }
 576
 577    fn unmark_text(&mut self) {
 578        self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
 579    }
 580
 581    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 582        self.cx
 583            .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
 584            .ok()
 585            .flatten()
 586    }
 587
 588    pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
 589        self.handler.replace_text_in_range(None, input, cx);
 590    }
 591
 592    pub fn selected_bounds(&mut self, cx: &mut WindowContext) -> Option<Bounds<Pixels>> {
 593        let selection = self.handler.selected_text_range(true, cx)?;
 594        self.handler.bounds_for_range(
 595            if selection.reversed {
 596                selection.range.start..selection.range.start
 597            } else {
 598                selection.range.end..selection.range.end
 599            },
 600            cx,
 601        )
 602    }
 603}
 604
 605/// A struct representing a selection in a text buffer, in UTF16 characters.
 606/// This is different from a range because the head may be before the tail.
 607pub struct UTF16Selection {
 608    /// The range of text in the document this selection corresponds to
 609    /// in UTF16 characters.
 610    pub range: Range<usize>,
 611    /// Whether the head of this selection is at the start (true), or end (false)
 612    /// of the range
 613    pub reversed: bool,
 614}
 615
 616/// Zed's interface for handling text input from the platform's IME system
 617/// This is currently a 1:1 exposure of the NSTextInputClient API:
 618///
 619/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 620pub trait InputHandler: 'static {
 621    /// Get the range of the user's currently selected text, if any
 622    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 623    ///
 624    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 625    fn selected_text_range(
 626        &mut self,
 627        ignore_disabled_input: bool,
 628        cx: &mut WindowContext,
 629    ) -> Option<UTF16Selection>;
 630
 631    /// Get the range of the currently marked text, if any
 632    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 633    ///
 634    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 635    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 636
 637    /// Get the text for the given document range in UTF-16 characters
 638    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 639    ///
 640    /// range_utf16 is in terms of UTF-16 characters
 641    fn text_for_range(
 642        &mut self,
 643        range_utf16: Range<usize>,
 644        cx: &mut WindowContext,
 645    ) -> Option<String>;
 646
 647    /// Replace the text in the given document range with the given text
 648    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 649    ///
 650    /// replacement_range is in terms of UTF-16 characters
 651    fn replace_text_in_range(
 652        &mut self,
 653        replacement_range: Option<Range<usize>>,
 654        text: &str,
 655        cx: &mut WindowContext,
 656    );
 657
 658    /// Replace the text in the given document range with the given text,
 659    /// and mark the given text as part of an IME 'composing' state
 660    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 661    ///
 662    /// range_utf16 is in terms of UTF-16 characters
 663    /// new_selected_range is in terms of UTF-16 characters
 664    fn replace_and_mark_text_in_range(
 665        &mut self,
 666        range_utf16: Option<Range<usize>>,
 667        new_text: &str,
 668        new_selected_range: Option<Range<usize>>,
 669        cx: &mut WindowContext,
 670    );
 671
 672    /// Remove the IME 'composing' state from the document
 673    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 674    fn unmark_text(&mut self, cx: &mut WindowContext);
 675
 676    /// Get the bounds of the given document range in screen coordinates
 677    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 678    ///
 679    /// This is used for positioning the IME candidate window
 680    fn bounds_for_range(
 681        &mut self,
 682        range_utf16: Range<usize>,
 683        cx: &mut WindowContext,
 684    ) -> Option<Bounds<Pixels>>;
 685}
 686
 687/// The variables that can be configured when creating a new window
 688#[derive(Debug)]
 689pub struct WindowOptions {
 690    /// Specifies the state and bounds of the window in screen coordinates.
 691    /// - `None`: Inherit the bounds.
 692    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 693    pub window_bounds: Option<WindowBounds>,
 694
 695    /// The titlebar configuration of the window
 696    pub titlebar: Option<TitlebarOptions>,
 697
 698    /// Whether the window should be focused when created
 699    pub focus: bool,
 700
 701    /// Whether the window should be shown when created
 702    pub show: bool,
 703
 704    /// The kind of window to create
 705    pub kind: WindowKind,
 706
 707    /// Whether the window should be movable by the user
 708    pub is_movable: bool,
 709
 710    /// The display to create the window on, if this is None,
 711    /// the window will be created on the main display
 712    pub display_id: Option<DisplayId>,
 713
 714    /// The appearance of the window background.
 715    pub window_background: WindowBackgroundAppearance,
 716
 717    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 718    pub app_id: Option<String>,
 719
 720    /// Window minimum size
 721    pub window_min_size: Option<Size<Pixels>>,
 722
 723    /// Whether to use client or server side decorations. Wayland only
 724    /// Note that this may be ignored.
 725    pub window_decorations: Option<WindowDecorations>,
 726}
 727
 728/// The variables that can be configured when creating a new window
 729#[derive(Debug)]
 730pub(crate) struct WindowParams {
 731    pub bounds: Bounds<Pixels>,
 732
 733    /// The titlebar configuration of the window
 734    pub titlebar: Option<TitlebarOptions>,
 735
 736    /// The kind of window to create
 737    #[cfg_attr(target_os = "linux", allow(dead_code))]
 738    pub kind: WindowKind,
 739
 740    /// Whether the window should be movable by the user
 741    #[cfg_attr(target_os = "linux", allow(dead_code))]
 742    pub is_movable: bool,
 743
 744    #[cfg_attr(target_os = "linux", allow(dead_code))]
 745    pub focus: bool,
 746
 747    #[cfg_attr(target_os = "linux", allow(dead_code))]
 748    pub show: bool,
 749
 750    pub display_id: Option<DisplayId>,
 751
 752    pub window_min_size: Option<Size<Pixels>>,
 753}
 754
 755/// Represents the status of how a window should be opened.
 756#[derive(Debug, Copy, Clone, PartialEq)]
 757pub enum WindowBounds {
 758    /// Indicates that the window should open in a windowed state with the given bounds.
 759    Windowed(Bounds<Pixels>),
 760    /// Indicates that the window should open in a maximized state.
 761    /// The bounds provided here represent the restore size of the window.
 762    Maximized(Bounds<Pixels>),
 763    /// Indicates that the window should open in fullscreen mode.
 764    /// The bounds provided here represent the restore size of the window.
 765    Fullscreen(Bounds<Pixels>),
 766}
 767
 768impl Default for WindowBounds {
 769    fn default() -> Self {
 770        WindowBounds::Windowed(Bounds::default())
 771    }
 772}
 773
 774impl WindowBounds {
 775    /// Retrieve the inner bounds
 776    pub fn get_bounds(&self) -> Bounds<Pixels> {
 777        match self {
 778            WindowBounds::Windowed(bounds) => *bounds,
 779            WindowBounds::Maximized(bounds) => *bounds,
 780            WindowBounds::Fullscreen(bounds) => *bounds,
 781        }
 782    }
 783}
 784
 785impl Default for WindowOptions {
 786    fn default() -> Self {
 787        Self {
 788            window_bounds: None,
 789            titlebar: Some(TitlebarOptions {
 790                title: Default::default(),
 791                appears_transparent: Default::default(),
 792                traffic_light_position: Default::default(),
 793            }),
 794            focus: true,
 795            show: true,
 796            kind: WindowKind::Normal,
 797            is_movable: true,
 798            display_id: None,
 799            window_background: WindowBackgroundAppearance::default(),
 800            app_id: None,
 801            window_min_size: None,
 802            window_decorations: None,
 803        }
 804    }
 805}
 806
 807/// The options that can be configured for a window's titlebar
 808#[derive(Debug, Default)]
 809pub struct TitlebarOptions {
 810    /// The initial title of the window
 811    pub title: Option<SharedString>,
 812
 813    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
 814    /// Refer to [`WindowOptions::window_decorations`] on Linux
 815    pub appears_transparent: bool,
 816
 817    /// The position of the macOS traffic light buttons
 818    pub traffic_light_position: Option<Point<Pixels>>,
 819}
 820
 821/// The kind of window to create
 822#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 823pub enum WindowKind {
 824    /// A normal application window
 825    Normal,
 826
 827    /// A window that appears above all other windows, usually used for alerts or popups
 828    /// use sparingly!
 829    PopUp,
 830}
 831
 832/// The appearance of the window, as defined by the operating system.
 833///
 834/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 835/// values.
 836#[derive(Copy, Clone, Debug)]
 837pub enum WindowAppearance {
 838    /// A light appearance.
 839    ///
 840    /// On macOS, this corresponds to the `aqua` appearance.
 841    Light,
 842
 843    /// A light appearance with vibrant colors.
 844    ///
 845    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 846    VibrantLight,
 847
 848    /// A dark appearance.
 849    ///
 850    /// On macOS, this corresponds to the `darkAqua` appearance.
 851    Dark,
 852
 853    /// A dark appearance with vibrant colors.
 854    ///
 855    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
 856    VibrantDark,
 857}
 858
 859impl Default for WindowAppearance {
 860    fn default() -> Self {
 861        Self::Light
 862    }
 863}
 864
 865/// The appearance of the background of the window itself, when there is
 866/// no content or the content is transparent.
 867#[derive(Copy, Clone, Debug, Default, PartialEq)]
 868pub enum WindowBackgroundAppearance {
 869    /// Opaque.
 870    ///
 871    /// This lets the window manager know that content behind this
 872    /// window does not need to be drawn.
 873    ///
 874    /// Actual color depends on the system and themes should define a fully
 875    /// opaque background color instead.
 876    #[default]
 877    Opaque,
 878    /// Plain alpha transparency.
 879    Transparent,
 880    /// Transparency, but the contents behind the window are blurred.
 881    ///
 882    /// Not always supported.
 883    Blurred,
 884}
 885
 886/// The options that can be configured for a file dialog prompt
 887#[derive(Copy, Clone, Debug)]
 888pub struct PathPromptOptions {
 889    /// Should the prompt allow files to be selected?
 890    pub files: bool,
 891    /// Should the prompt allow directories to be selected?
 892    pub directories: bool,
 893    /// Should the prompt allow multiple files to be selected?
 894    pub multiple: bool,
 895}
 896
 897/// What kind of prompt styling to show
 898#[derive(Copy, Clone, Debug, PartialEq)]
 899pub enum PromptLevel {
 900    /// A prompt that is shown when the user should be notified of something
 901    Info,
 902
 903    /// A prompt that is shown when the user needs to be warned of a potential problem
 904    Warning,
 905
 906    /// A prompt that is shown when a critical problem has occurred
 907    Critical,
 908}
 909
 910/// The style of the cursor (pointer)
 911#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 912pub enum CursorStyle {
 913    /// The default cursor
 914    Arrow,
 915
 916    /// A text input cursor
 917    /// corresponds to the CSS cursor value `text`
 918    IBeam,
 919
 920    /// A crosshair cursor
 921    /// corresponds to the CSS cursor value `crosshair`
 922    Crosshair,
 923
 924    /// A closed hand cursor
 925    /// corresponds to the CSS cursor value `grabbing`
 926    ClosedHand,
 927
 928    /// An open hand cursor
 929    /// corresponds to the CSS cursor value `grab`
 930    OpenHand,
 931
 932    /// A pointing hand cursor
 933    /// corresponds to the CSS cursor value `pointer`
 934    PointingHand,
 935
 936    /// A resize left cursor
 937    /// corresponds to the CSS cursor value `w-resize`
 938    ResizeLeft,
 939
 940    /// A resize right cursor
 941    /// corresponds to the CSS cursor value `e-resize`
 942    ResizeRight,
 943
 944    /// A resize cursor to the left and right
 945    /// corresponds to the CSS cursor value `ew-resize`
 946    ResizeLeftRight,
 947
 948    /// A resize up cursor
 949    /// corresponds to the CSS cursor value `n-resize`
 950    ResizeUp,
 951
 952    /// A resize down cursor
 953    /// corresponds to the CSS cursor value `s-resize`
 954    ResizeDown,
 955
 956    /// A resize cursor directing up and down
 957    /// corresponds to the CSS cursor value `ns-resize`
 958    ResizeUpDown,
 959
 960    /// A resize cursor directing up-left and down-right
 961    /// corresponds to the CSS cursor value `nesw-resize`
 962    ResizeUpLeftDownRight,
 963
 964    /// A resize cursor directing up-right and down-left
 965    /// corresponds to the CSS cursor value `nwse-resize`
 966    ResizeUpRightDownLeft,
 967
 968    /// A cursor indicating that the item/column can be resized horizontally.
 969    /// corresponds to the CSS cursor value `col-resize`
 970    ResizeColumn,
 971
 972    /// A cursor indicating that the item/row can be resized vertically.
 973    /// corresponds to the CSS cursor value `row-resize`
 974    ResizeRow,
 975
 976    /// A text input cursor for vertical layout
 977    /// corresponds to the CSS cursor value `vertical-text`
 978    IBeamCursorForVerticalLayout,
 979
 980    /// A cursor indicating that the operation is not allowed
 981    /// corresponds to the CSS cursor value `not-allowed`
 982    OperationNotAllowed,
 983
 984    /// A cursor indicating that the operation will result in a link
 985    /// corresponds to the CSS cursor value `alias`
 986    DragLink,
 987
 988    /// A cursor indicating that the operation will result in a copy
 989    /// corresponds to the CSS cursor value `copy`
 990    DragCopy,
 991
 992    /// A cursor indicating that the operation will result in a context menu
 993    /// corresponds to the CSS cursor value `context-menu`
 994    ContextualMenu,
 995}
 996
 997impl Default for CursorStyle {
 998    fn default() -> Self {
 999        Self::Arrow
1000    }
1001}
1002
1003/// A clipboard item that should be copied to the clipboard
1004#[derive(Clone, Debug, Eq, PartialEq)]
1005pub struct ClipboardItem {
1006    entries: Vec<ClipboardEntry>,
1007}
1008
1009/// Either a ClipboardString or a ClipboardImage
1010#[derive(Clone, Debug, Eq, PartialEq)]
1011pub enum ClipboardEntry {
1012    /// A string entry
1013    String(ClipboardString),
1014    /// An image entry
1015    Image(Image),
1016}
1017
1018impl ClipboardItem {
1019    /// Create a new ClipboardItem::String with no associated metadata
1020    pub fn new_string(text: String) -> Self {
1021        Self {
1022            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1023        }
1024    }
1025
1026    /// Create a new ClipboardItem::String with the given text and associated metadata
1027    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1028        Self {
1029            entries: vec![ClipboardEntry::String(ClipboardString {
1030                text,
1031                metadata: Some(metadata),
1032            })],
1033        }
1034    }
1035
1036    /// Create a new ClipboardItem::String with the given text and associated metadata
1037    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1038        Self {
1039            entries: vec![ClipboardEntry::String(
1040                ClipboardString::new(text).with_json_metadata(metadata),
1041            )],
1042        }
1043    }
1044
1045    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1046    pub fn new_image(image: &Image) -> Self {
1047        Self {
1048            entries: vec![ClipboardEntry::Image(image.clone())],
1049        }
1050    }
1051
1052    /// Concatenates together all the ClipboardString entries in the item.
1053    /// Returns None if there were no ClipboardString entries.
1054    pub fn text(&self) -> Option<String> {
1055        let mut answer = String::new();
1056        let mut any_entries = false;
1057
1058        for entry in self.entries.iter() {
1059            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1060                answer.push_str(text);
1061                any_entries = true;
1062            }
1063        }
1064
1065        if any_entries {
1066            Some(answer)
1067        } else {
1068            None
1069        }
1070    }
1071
1072    /// If this item is one ClipboardEntry::String, returns its metadata.
1073    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1074    pub fn metadata(&self) -> Option<&String> {
1075        match self.entries().first() {
1076            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1077                clipboard_string.metadata.as_ref()
1078            }
1079            _ => None,
1080        }
1081    }
1082
1083    /// Get the item's entries
1084    pub fn entries(&self) -> &[ClipboardEntry] {
1085        &self.entries
1086    }
1087
1088    /// Get owned versions of the item's entries
1089    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1090        self.entries.into_iter()
1091    }
1092}
1093
1094/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1095#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1096pub enum ImageFormat {
1097    // Sorted from most to least likely to be pasted into an editor,
1098    // which matters when we iterate through them trying to see if
1099    // clipboard content matches them.
1100    /// .png
1101    Png,
1102    /// .jpeg or .jpg
1103    Jpeg,
1104    /// .webp
1105    Webp,
1106    /// .gif
1107    Gif,
1108    /// .svg
1109    Svg,
1110    /// .bmp
1111    Bmp,
1112    /// .tif or .tiff
1113    Tiff,
1114}
1115
1116/// An image, with a format and certain bytes
1117#[derive(Clone, Debug, PartialEq, Eq)]
1118pub struct Image {
1119    /// The image format the bytes represent (e.g. PNG)
1120    pub format: ImageFormat,
1121    /// The raw image bytes
1122    pub bytes: Vec<u8>,
1123    /// The unique ID for the image
1124    pub id: u64,
1125}
1126
1127impl Hash for Image {
1128    fn hash<H: Hasher>(&self, state: &mut H) {
1129        state.write_u64(self.id);
1130    }
1131}
1132
1133impl Image {
1134    /// Get this image's ID
1135    pub fn id(&self) -> u64 {
1136        self.id
1137    }
1138
1139    /// Use the GPUI `use_asset` API to make this image renderable
1140    pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1141        ImageSource::Image(self).use_data(cx)
1142    }
1143
1144    /// Convert the clipboard image to an `ImageData` object.
1145    pub fn to_image_data(&self, cx: &AppContext) -> Result<Arc<RenderImage>> {
1146        fn frames_for_image(
1147            bytes: &[u8],
1148            format: image::ImageFormat,
1149        ) -> Result<SmallVec<[Frame; 1]>> {
1150            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1151
1152            // Convert from RGBA to BGRA.
1153            for pixel in data.chunks_exact_mut(4) {
1154                pixel.swap(0, 2);
1155            }
1156
1157            Ok(SmallVec::from_elem(Frame::new(data), 1))
1158        }
1159
1160        let frames = match self.format {
1161            ImageFormat::Gif => {
1162                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1163                let mut frames = SmallVec::new();
1164
1165                for frame in decoder.into_frames() {
1166                    let mut frame = frame?;
1167                    // Convert from RGBA to BGRA.
1168                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1169                        pixel.swap(0, 2);
1170                    }
1171                    frames.push(frame);
1172                }
1173
1174                frames
1175            }
1176            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1177            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1178            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1179            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1180            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1181            ImageFormat::Svg => {
1182                // TODO: Fix this
1183                let pixmap = cx
1184                    .svg_renderer()
1185                    .render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1186
1187                let buffer =
1188                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1189                        .unwrap();
1190
1191                SmallVec::from_elem(Frame::new(buffer), 1)
1192            }
1193        };
1194
1195        Ok(Arc::new(RenderImage::new(frames)))
1196    }
1197
1198    /// Get the format of the clipboard image
1199    pub fn format(&self) -> ImageFormat {
1200        self.format
1201    }
1202
1203    /// Get the raw bytes of the clipboard image
1204    pub fn bytes(&self) -> &[u8] {
1205        self.bytes.as_slice()
1206    }
1207}
1208
1209/// A clipboard item that should be copied to the clipboard
1210#[derive(Clone, Debug, Eq, PartialEq)]
1211pub struct ClipboardString {
1212    pub(crate) text: String,
1213    pub(crate) metadata: Option<String>,
1214}
1215
1216impl ClipboardString {
1217    /// Create a new clipboard string with the given text
1218    pub fn new(text: String) -> Self {
1219        Self {
1220            text,
1221            metadata: None,
1222        }
1223    }
1224
1225    /// Return a new clipboard item with the metadata replaced by the given metadata,
1226    /// after serializing it as JSON.
1227    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1228        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1229        self
1230    }
1231
1232    /// Get the text of the clipboard string
1233    pub fn text(&self) -> &String {
1234        &self.text
1235    }
1236
1237    /// Get the owned text of the clipboard string
1238    pub fn into_text(self) -> String {
1239        self.text
1240    }
1241
1242    /// Get the metadata of the clipboard string, formatted as JSON
1243    pub fn metadata_json<T>(&self) -> Option<T>
1244    where
1245        T: for<'a> Deserialize<'a>,
1246    {
1247        self.metadata
1248            .as_ref()
1249            .and_then(|m| serde_json::from_str(m).ok())
1250    }
1251
1252    #[cfg_attr(target_os = "linux", allow(dead_code))]
1253    pub(crate) fn text_hash(text: &str) -> u64 {
1254        let mut hasher = SeaHasher::new();
1255        text.hash(&mut hasher);
1256        hasher.finish()
1257    }
1258}