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 Some(selection) = self.handler.selected_text_range(true, cx) else {
 594            return None;
 595        };
 596        self.handler.bounds_for_range(
 597            if selection.reversed {
 598                selection.range.start..selection.range.start
 599            } else {
 600                selection.range.end..selection.range.end
 601            },
 602            cx,
 603        )
 604    }
 605}
 606
 607/// A struct representing a selection in a text buffer, in UTF16 characters.
 608/// This is different from a range because the head may be before the tail.
 609pub struct UTF16Selection {
 610    /// The range of text in the document this selection corresponds to
 611    /// in UTF16 characters.
 612    pub range: Range<usize>,
 613    /// Whether the head of this selection is at the start (true), or end (false)
 614    /// of the range
 615    pub reversed: bool,
 616}
 617
 618/// Zed's interface for handling text input from the platform's IME system
 619/// This is currently a 1:1 exposure of the NSTextInputClient API:
 620///
 621/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 622pub trait InputHandler: 'static {
 623    /// Get the range of the user's currently selected text, if any
 624    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 625    ///
 626    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 627    fn selected_text_range(
 628        &mut self,
 629        ignore_disabled_input: bool,
 630        cx: &mut WindowContext,
 631    ) -> Option<UTF16Selection>;
 632
 633    /// Get the range of the currently marked text, if any
 634    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 635    ///
 636    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 637    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 638
 639    /// Get the text for the given document range in UTF-16 characters
 640    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 641    ///
 642    /// range_utf16 is in terms of UTF-16 characters
 643    fn text_for_range(
 644        &mut self,
 645        range_utf16: Range<usize>,
 646        cx: &mut WindowContext,
 647    ) -> Option<String>;
 648
 649    /// Replace the text in the given document range with the given text
 650    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 651    ///
 652    /// replacement_range is in terms of UTF-16 characters
 653    fn replace_text_in_range(
 654        &mut self,
 655        replacement_range: Option<Range<usize>>,
 656        text: &str,
 657        cx: &mut WindowContext,
 658    );
 659
 660    /// Replace the text in the given document range with the given text,
 661    /// and mark the given text as part of an IME 'composing' state
 662    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 663    ///
 664    /// range_utf16 is in terms of UTF-16 characters
 665    /// new_selected_range is in terms of UTF-16 characters
 666    fn replace_and_mark_text_in_range(
 667        &mut self,
 668        range_utf16: Option<Range<usize>>,
 669        new_text: &str,
 670        new_selected_range: Option<Range<usize>>,
 671        cx: &mut WindowContext,
 672    );
 673
 674    /// Remove the IME 'composing' state from the document
 675    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 676    fn unmark_text(&mut self, cx: &mut WindowContext);
 677
 678    /// Get the bounds of the given document range in screen coordinates
 679    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 680    ///
 681    /// This is used for positioning the IME candidate window
 682    fn bounds_for_range(
 683        &mut self,
 684        range_utf16: Range<usize>,
 685        cx: &mut WindowContext,
 686    ) -> Option<Bounds<Pixels>>;
 687}
 688
 689/// The variables that can be configured when creating a new window
 690#[derive(Debug)]
 691pub struct WindowOptions {
 692    /// Specifies the state and bounds of the window in screen coordinates.
 693    /// - `None`: Inherit the bounds.
 694    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 695    pub window_bounds: Option<WindowBounds>,
 696
 697    /// The titlebar configuration of the window
 698    pub titlebar: Option<TitlebarOptions>,
 699
 700    /// Whether the window should be focused when created
 701    pub focus: bool,
 702
 703    /// Whether the window should be shown when created
 704    pub show: bool,
 705
 706    /// The kind of window to create
 707    pub kind: WindowKind,
 708
 709    /// Whether the window should be movable by the user
 710    pub is_movable: bool,
 711
 712    /// The display to create the window on, if this is None,
 713    /// the window will be created on the main display
 714    pub display_id: Option<DisplayId>,
 715
 716    /// The appearance of the window background.
 717    pub window_background: WindowBackgroundAppearance,
 718
 719    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 720    pub app_id: Option<String>,
 721
 722    /// Window minimum size
 723    pub window_min_size: Option<Size<Pixels>>,
 724
 725    /// Whether to use client or server side decorations. Wayland only
 726    /// Note that this may be ignored.
 727    pub window_decorations: Option<WindowDecorations>,
 728}
 729
 730/// The variables that can be configured when creating a new window
 731#[derive(Debug)]
 732pub(crate) struct WindowParams {
 733    pub bounds: Bounds<Pixels>,
 734
 735    /// The titlebar configuration of the window
 736    pub titlebar: Option<TitlebarOptions>,
 737
 738    /// The kind of window to create
 739    #[cfg_attr(target_os = "linux", allow(dead_code))]
 740    pub kind: WindowKind,
 741
 742    /// Whether the window should be movable by the user
 743    #[cfg_attr(target_os = "linux", allow(dead_code))]
 744    pub is_movable: bool,
 745
 746    #[cfg_attr(target_os = "linux", allow(dead_code))]
 747    pub focus: bool,
 748
 749    #[cfg_attr(target_os = "linux", allow(dead_code))]
 750    pub show: bool,
 751
 752    pub display_id: Option<DisplayId>,
 753
 754    pub window_min_size: Option<Size<Pixels>>,
 755}
 756
 757/// Represents the status of how a window should be opened.
 758#[derive(Debug, Copy, Clone, PartialEq)]
 759pub enum WindowBounds {
 760    /// Indicates that the window should open in a windowed state with the given bounds.
 761    Windowed(Bounds<Pixels>),
 762    /// Indicates that the window should open in a maximized state.
 763    /// The bounds provided here represent the restore size of the window.
 764    Maximized(Bounds<Pixels>),
 765    /// Indicates that the window should open in fullscreen mode.
 766    /// The bounds provided here represent the restore size of the window.
 767    Fullscreen(Bounds<Pixels>),
 768}
 769
 770impl Default for WindowBounds {
 771    fn default() -> Self {
 772        WindowBounds::Windowed(Bounds::default())
 773    }
 774}
 775
 776impl WindowBounds {
 777    /// Retrieve the inner bounds
 778    pub fn get_bounds(&self) -> Bounds<Pixels> {
 779        match self {
 780            WindowBounds::Windowed(bounds) => *bounds,
 781            WindowBounds::Maximized(bounds) => *bounds,
 782            WindowBounds::Fullscreen(bounds) => *bounds,
 783        }
 784    }
 785}
 786
 787impl Default for WindowOptions {
 788    fn default() -> Self {
 789        Self {
 790            window_bounds: None,
 791            titlebar: Some(TitlebarOptions {
 792                title: Default::default(),
 793                appears_transparent: Default::default(),
 794                traffic_light_position: Default::default(),
 795            }),
 796            focus: true,
 797            show: true,
 798            kind: WindowKind::Normal,
 799            is_movable: true,
 800            display_id: None,
 801            window_background: WindowBackgroundAppearance::default(),
 802            app_id: None,
 803            window_min_size: None,
 804            window_decorations: None,
 805        }
 806    }
 807}
 808
 809/// The options that can be configured for a window's titlebar
 810#[derive(Debug, Default)]
 811pub struct TitlebarOptions {
 812    /// The initial title of the window
 813    pub title: Option<SharedString>,
 814
 815    /// Should the default system titlebar be hidden to allow for a custom-drawn titlebar? (macOS and Windows only)
 816    /// Refer to [`WindowOptions::window_decorations`] on Linux
 817    pub appears_transparent: bool,
 818
 819    /// The position of the macOS traffic light buttons
 820    pub traffic_light_position: Option<Point<Pixels>>,
 821}
 822
 823/// The kind of window to create
 824#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 825pub enum WindowKind {
 826    /// A normal application window
 827    Normal,
 828
 829    /// A window that appears above all other windows, usually used for alerts or popups
 830    /// use sparingly!
 831    PopUp,
 832}
 833
 834/// The appearance of the window, as defined by the operating system.
 835///
 836/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 837/// values.
 838#[derive(Copy, Clone, Debug)]
 839pub enum WindowAppearance {
 840    /// A light appearance.
 841    ///
 842    /// On macOS, this corresponds to the `aqua` appearance.
 843    Light,
 844
 845    /// A light appearance with vibrant colors.
 846    ///
 847    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 848    VibrantLight,
 849
 850    /// A dark appearance.
 851    ///
 852    /// On macOS, this corresponds to the `darkAqua` appearance.
 853    Dark,
 854
 855    /// A dark appearance with vibrant colors.
 856    ///
 857    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
 858    VibrantDark,
 859}
 860
 861impl Default for WindowAppearance {
 862    fn default() -> Self {
 863        Self::Light
 864    }
 865}
 866
 867/// The appearance of the background of the window itself, when there is
 868/// no content or the content is transparent.
 869#[derive(Copy, Clone, Debug, Default, PartialEq)]
 870pub enum WindowBackgroundAppearance {
 871    /// Opaque.
 872    ///
 873    /// This lets the window manager know that content behind this
 874    /// window does not need to be drawn.
 875    ///
 876    /// Actual color depends on the system and themes should define a fully
 877    /// opaque background color instead.
 878    #[default]
 879    Opaque,
 880    /// Plain alpha transparency.
 881    Transparent,
 882    /// Transparency, but the contents behind the window are blurred.
 883    ///
 884    /// Not always supported.
 885    Blurred,
 886}
 887
 888/// The options that can be configured for a file dialog prompt
 889#[derive(Copy, Clone, Debug)]
 890pub struct PathPromptOptions {
 891    /// Should the prompt allow files to be selected?
 892    pub files: bool,
 893    /// Should the prompt allow directories to be selected?
 894    pub directories: bool,
 895    /// Should the prompt allow multiple files to be selected?
 896    pub multiple: bool,
 897}
 898
 899/// What kind of prompt styling to show
 900#[derive(Copy, Clone, Debug, PartialEq)]
 901pub enum PromptLevel {
 902    /// A prompt that is shown when the user should be notified of something
 903    Info,
 904
 905    /// A prompt that is shown when the user needs to be warned of a potential problem
 906    Warning,
 907
 908    /// A prompt that is shown when a critical problem has occurred
 909    Critical,
 910}
 911
 912/// The style of the cursor (pointer)
 913#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 914pub enum CursorStyle {
 915    /// The default cursor
 916    Arrow,
 917
 918    /// A text input cursor
 919    /// corresponds to the CSS cursor value `text`
 920    IBeam,
 921
 922    /// A crosshair cursor
 923    /// corresponds to the CSS cursor value `crosshair`
 924    Crosshair,
 925
 926    /// A closed hand cursor
 927    /// corresponds to the CSS cursor value `grabbing`
 928    ClosedHand,
 929
 930    /// An open hand cursor
 931    /// corresponds to the CSS cursor value `grab`
 932    OpenHand,
 933
 934    /// A pointing hand cursor
 935    /// corresponds to the CSS cursor value `pointer`
 936    PointingHand,
 937
 938    /// A resize left cursor
 939    /// corresponds to the CSS cursor value `w-resize`
 940    ResizeLeft,
 941
 942    /// A resize right cursor
 943    /// corresponds to the CSS cursor value `e-resize`
 944    ResizeRight,
 945
 946    /// A resize cursor to the left and right
 947    /// corresponds to the CSS cursor value `ew-resize`
 948    ResizeLeftRight,
 949
 950    /// A resize up cursor
 951    /// corresponds to the CSS cursor value `n-resize`
 952    ResizeUp,
 953
 954    /// A resize down cursor
 955    /// corresponds to the CSS cursor value `s-resize`
 956    ResizeDown,
 957
 958    /// A resize cursor directing up and down
 959    /// corresponds to the CSS cursor value `ns-resize`
 960    ResizeUpDown,
 961
 962    /// A resize cursor directing up-left and down-right
 963    /// corresponds to the CSS cursor value `nesw-resize`
 964    ResizeUpLeftDownRight,
 965
 966    /// A resize cursor directing up-right and down-left
 967    /// corresponds to the CSS cursor value `nwse-resize`
 968    ResizeUpRightDownLeft,
 969
 970    /// A cursor indicating that the item/column can be resized horizontally.
 971    /// corresponds to the CSS cursor value `col-resize`
 972    ResizeColumn,
 973
 974    /// A cursor indicating that the item/row can be resized vertically.
 975    /// corresponds to the CSS cursor value `row-resize`
 976    ResizeRow,
 977
 978    /// A text input cursor for vertical layout
 979    /// corresponds to the CSS cursor value `vertical-text`
 980    IBeamCursorForVerticalLayout,
 981
 982    /// A cursor indicating that the operation is not allowed
 983    /// corresponds to the CSS cursor value `not-allowed`
 984    OperationNotAllowed,
 985
 986    /// A cursor indicating that the operation will result in a link
 987    /// corresponds to the CSS cursor value `alias`
 988    DragLink,
 989
 990    /// A cursor indicating that the operation will result in a copy
 991    /// corresponds to the CSS cursor value `copy`
 992    DragCopy,
 993
 994    /// A cursor indicating that the operation will result in a context menu
 995    /// corresponds to the CSS cursor value `context-menu`
 996    ContextualMenu,
 997}
 998
 999impl Default for CursorStyle {
1000    fn default() -> Self {
1001        Self::Arrow
1002    }
1003}
1004
1005/// A clipboard item that should be copied to the clipboard
1006#[derive(Clone, Debug, Eq, PartialEq)]
1007pub struct ClipboardItem {
1008    entries: Vec<ClipboardEntry>,
1009}
1010
1011/// Either a ClipboardString or a ClipboardImage
1012#[derive(Clone, Debug, Eq, PartialEq)]
1013pub enum ClipboardEntry {
1014    /// A string entry
1015    String(ClipboardString),
1016    /// An image entry
1017    Image(Image),
1018}
1019
1020impl ClipboardItem {
1021    /// Create a new ClipboardItem::String with no associated metadata
1022    pub fn new_string(text: String) -> Self {
1023        Self {
1024            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
1025        }
1026    }
1027
1028    /// Create a new ClipboardItem::String with the given text and associated metadata
1029    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1030        Self {
1031            entries: vec![ClipboardEntry::String(ClipboardString {
1032                text,
1033                metadata: Some(metadata),
1034            })],
1035        }
1036    }
1037
1038    /// Create a new ClipboardItem::String with the given text and associated metadata
1039    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1040        Self {
1041            entries: vec![ClipboardEntry::String(
1042                ClipboardString::new(text).with_json_metadata(metadata),
1043            )],
1044        }
1045    }
1046
1047    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1048    pub fn new_image(image: &Image) -> Self {
1049        Self {
1050            entries: vec![ClipboardEntry::Image(image.clone())],
1051        }
1052    }
1053
1054    /// Concatenates together all the ClipboardString entries in the item.
1055    /// Returns None if there were no ClipboardString entries.
1056    pub fn text(&self) -> Option<String> {
1057        let mut answer = String::new();
1058        let mut any_entries = false;
1059
1060        for entry in self.entries.iter() {
1061            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1062                answer.push_str(text);
1063                any_entries = true;
1064            }
1065        }
1066
1067        if any_entries {
1068            Some(answer)
1069        } else {
1070            None
1071        }
1072    }
1073
1074    /// If this item is one ClipboardEntry::String, returns its metadata.
1075    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1076    pub fn metadata(&self) -> Option<&String> {
1077        match self.entries().first() {
1078            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1079                clipboard_string.metadata.as_ref()
1080            }
1081            _ => None,
1082        }
1083    }
1084
1085    /// Get the item's entries
1086    pub fn entries(&self) -> &[ClipboardEntry] {
1087        &self.entries
1088    }
1089
1090    /// Get owned versions of the item's entries
1091    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1092        self.entries.into_iter()
1093    }
1094}
1095
1096/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1097#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1098pub enum ImageFormat {
1099    // Sorted from most to least likely to be pasted into an editor,
1100    // which matters when we iterate through them trying to see if
1101    // clipboard content matches them.
1102    /// .png
1103    Png,
1104    /// .jpeg or .jpg
1105    Jpeg,
1106    /// .webp
1107    Webp,
1108    /// .gif
1109    Gif,
1110    /// .svg
1111    Svg,
1112    /// .bmp
1113    Bmp,
1114    /// .tif or .tiff
1115    Tiff,
1116}
1117
1118/// An image, with a format and certain bytes
1119#[derive(Clone, Debug, PartialEq, Eq)]
1120pub struct Image {
1121    /// The image format the bytes represent (e.g. PNG)
1122    pub format: ImageFormat,
1123    /// The raw image bytes
1124    pub bytes: Vec<u8>,
1125    /// The unique ID for the image
1126    pub id: u64,
1127}
1128
1129impl Hash for Image {
1130    fn hash<H: Hasher>(&self, state: &mut H) {
1131        state.write_u64(self.id);
1132    }
1133}
1134
1135impl Image {
1136    /// Get this image's ID
1137    pub fn id(&self) -> u64 {
1138        self.id
1139    }
1140
1141    /// Use the GPUI `use_asset` API to make this image renderable
1142    pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1143        ImageSource::Image(self).use_data(cx)
1144    }
1145
1146    /// Convert the clipboard image to an `ImageData` object.
1147    pub fn to_image_data(&self, cx: &AppContext) -> Result<Arc<RenderImage>> {
1148        fn frames_for_image(
1149            bytes: &[u8],
1150            format: image::ImageFormat,
1151        ) -> Result<SmallVec<[Frame; 1]>> {
1152            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1153
1154            // Convert from RGBA to BGRA.
1155            for pixel in data.chunks_exact_mut(4) {
1156                pixel.swap(0, 2);
1157            }
1158
1159            Ok(SmallVec::from_elem(Frame::new(data), 1))
1160        }
1161
1162        let frames = match self.format {
1163            ImageFormat::Gif => {
1164                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1165                let mut frames = SmallVec::new();
1166
1167                for frame in decoder.into_frames() {
1168                    let mut frame = frame?;
1169                    // Convert from RGBA to BGRA.
1170                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1171                        pixel.swap(0, 2);
1172                    }
1173                    frames.push(frame);
1174                }
1175
1176                frames
1177            }
1178            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1179            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1180            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1181            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1182            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1183            ImageFormat::Svg => {
1184                // TODO: Fix this
1185                let pixmap = cx
1186                    .svg_renderer()
1187                    .render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1188
1189                let buffer =
1190                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1191                        .unwrap();
1192
1193                SmallVec::from_elem(Frame::new(buffer), 1)
1194            }
1195        };
1196
1197        Ok(Arc::new(RenderImage::new(frames)))
1198    }
1199
1200    /// Get the format of the clipboard image
1201    pub fn format(&self) -> ImageFormat {
1202        self.format
1203    }
1204
1205    /// Get the raw bytes of the clipboard image
1206    pub fn bytes(&self) -> &[u8] {
1207        self.bytes.as_slice()
1208    }
1209}
1210
1211/// A clipboard item that should be copied to the clipboard
1212#[derive(Clone, Debug, Eq, PartialEq)]
1213pub struct ClipboardString {
1214    pub(crate) text: String,
1215    pub(crate) metadata: Option<String>,
1216}
1217
1218impl ClipboardString {
1219    /// Create a new clipboard string with the given text
1220    pub fn new(text: String) -> Self {
1221        Self {
1222            text,
1223            metadata: None,
1224        }
1225    }
1226
1227    /// Return a new clipboard item with the metadata replaced by the given metadata,
1228    /// after serializing it as JSON.
1229    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1230        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1231        self
1232    }
1233
1234    /// Get the text of the clipboard string
1235    pub fn text(&self) -> &String {
1236        &self.text
1237    }
1238
1239    /// Get the owned text of the clipboard string
1240    pub fn into_text(self) -> String {
1241        self.text
1242    }
1243
1244    /// Get the metadata of the clipboard string, formatted as JSON
1245    pub fn metadata_json<T>(&self) -> Option<T>
1246    where
1247        T: for<'a> Deserialize<'a>,
1248    {
1249        self.metadata
1250            .as_ref()
1251            .and_then(|m| serde_json::from_str(m).ok())
1252    }
1253
1254    #[cfg_attr(target_os = "linux", allow(dead_code))]
1255    pub(crate) fn text_hash(text: &str) -> u64 {
1256        let mut hasher = SeaHasher::new();
1257        text.hash(&mut hasher);
1258        hasher.finish()
1259    }
1260}