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    #[cfg(any(test, feature = "test-support"))]
 384    fn as_test(&mut self) -> Option<&mut TestWindow> {
 385        None
 386    }
 387}
 388
 389/// This type is public so that our test macro can generate and use it, but it should not
 390/// be considered part of our public API.
 391#[doc(hidden)]
 392pub trait PlatformDispatcher: Send + Sync {
 393    fn is_main_thread(&self) -> bool;
 394    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 395    fn dispatch_on_main_thread(&self, runnable: Runnable);
 396    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 397    fn park(&self, timeout: Option<Duration>) -> bool;
 398    fn unparker(&self) -> Unparker;
 399    fn now(&self) -> Instant {
 400        Instant::now()
 401    }
 402
 403    #[cfg(any(test, feature = "test-support"))]
 404    fn as_test(&self) -> Option<&TestDispatcher> {
 405        None
 406    }
 407}
 408
 409pub(crate) trait PlatformTextSystem: Send + Sync {
 410    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 411    fn all_font_names(&self) -> Vec<String>;
 412    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 413    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 414    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 415    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 416    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 417    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 418    fn rasterize_glyph(
 419        &self,
 420        params: &RenderGlyphParams,
 421        raster_bounds: Bounds<DevicePixels>,
 422    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 423    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 424}
 425
 426#[derive(PartialEq, Eq, Hash, Clone)]
 427pub(crate) enum AtlasKey {
 428    Glyph(RenderGlyphParams),
 429    Svg(RenderSvgParams),
 430    Image(RenderImageParams),
 431}
 432
 433impl AtlasKey {
 434    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 435        match self {
 436            AtlasKey::Glyph(params) => {
 437                if params.is_emoji {
 438                    AtlasTextureKind::Polychrome
 439                } else {
 440                    AtlasTextureKind::Monochrome
 441                }
 442            }
 443            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 444            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 445        }
 446    }
 447}
 448
 449impl From<RenderGlyphParams> for AtlasKey {
 450    fn from(params: RenderGlyphParams) -> Self {
 451        Self::Glyph(params)
 452    }
 453}
 454
 455impl From<RenderSvgParams> for AtlasKey {
 456    fn from(params: RenderSvgParams) -> Self {
 457        Self::Svg(params)
 458    }
 459}
 460
 461impl From<RenderImageParams> for AtlasKey {
 462    fn from(params: RenderImageParams) -> Self {
 463        Self::Image(params)
 464    }
 465}
 466
 467pub(crate) trait PlatformAtlas: Send + Sync {
 468    fn get_or_insert_with<'a>(
 469        &self,
 470        key: &AtlasKey,
 471        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 472    ) -> Result<Option<AtlasTile>>;
 473}
 474
 475#[derive(Clone, Debug, PartialEq, Eq)]
 476#[repr(C)]
 477pub(crate) struct AtlasTile {
 478    pub(crate) texture_id: AtlasTextureId,
 479    pub(crate) tile_id: TileId,
 480    pub(crate) padding: u32,
 481    pub(crate) bounds: Bounds<DevicePixels>,
 482}
 483
 484#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 485#[repr(C)]
 486pub(crate) struct AtlasTextureId {
 487    // We use u32 instead of usize for Metal Shader Language compatibility
 488    pub(crate) index: u32,
 489    pub(crate) kind: AtlasTextureKind,
 490}
 491
 492#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 493#[repr(C)]
 494pub(crate) enum AtlasTextureKind {
 495    Monochrome = 0,
 496    Polychrome = 1,
 497    Path = 2,
 498}
 499
 500#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 501#[repr(C)]
 502pub(crate) struct TileId(pub(crate) u32);
 503
 504impl From<etagere::AllocId> for TileId {
 505    fn from(id: etagere::AllocId) -> Self {
 506        Self(id.serialize())
 507    }
 508}
 509
 510impl From<TileId> for etagere::AllocId {
 511    fn from(id: TileId) -> Self {
 512        Self::deserialize(id.0)
 513    }
 514}
 515
 516pub(crate) struct PlatformInputHandler {
 517    cx: AsyncWindowContext,
 518    handler: Box<dyn InputHandler>,
 519}
 520
 521impl PlatformInputHandler {
 522    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 523        Self { cx, handler }
 524    }
 525
 526    fn selected_text_range(&mut self) -> Option<Range<usize>> {
 527        self.cx
 528            .update(|cx| self.handler.selected_text_range(cx))
 529            .ok()
 530            .flatten()
 531    }
 532
 533    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 534        self.cx
 535            .update(|cx| self.handler.marked_text_range(cx))
 536            .ok()
 537            .flatten()
 538    }
 539
 540    #[cfg_attr(target_os = "linux", allow(dead_code))]
 541    fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
 542        self.cx
 543            .update(|cx| self.handler.text_for_range(range_utf16, cx))
 544            .ok()
 545            .flatten()
 546    }
 547
 548    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 549        self.cx
 550            .update(|cx| {
 551                self.handler
 552                    .replace_text_in_range(replacement_range, text, cx);
 553            })
 554            .ok();
 555    }
 556
 557    fn replace_and_mark_text_in_range(
 558        &mut self,
 559        range_utf16: Option<Range<usize>>,
 560        new_text: &str,
 561        new_selected_range: Option<Range<usize>>,
 562    ) {
 563        self.cx
 564            .update(|cx| {
 565                self.handler.replace_and_mark_text_in_range(
 566                    range_utf16,
 567                    new_text,
 568                    new_selected_range,
 569                    cx,
 570                )
 571            })
 572            .ok();
 573    }
 574
 575    fn unmark_text(&mut self) {
 576        self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
 577    }
 578
 579    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 580        self.cx
 581            .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
 582            .ok()
 583            .flatten()
 584    }
 585
 586    pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
 587        self.handler.replace_text_in_range(None, input, cx);
 588    }
 589}
 590
 591/// Zed's interface for handling text input from the platform's IME system
 592/// This is currently a 1:1 exposure of the NSTextInputClient API:
 593///
 594/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 595pub trait InputHandler: 'static {
 596    /// Get the range of the user's currently selected text, if any
 597    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 598    ///
 599    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 600    fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 601
 602    /// Get the range of the currently marked text, if any
 603    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 604    ///
 605    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 606    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 607
 608    /// Get the text for the given document range in UTF-16 characters
 609    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 610    ///
 611    /// range_utf16 is in terms of UTF-16 characters
 612    fn text_for_range(
 613        &mut self,
 614        range_utf16: Range<usize>,
 615        cx: &mut WindowContext,
 616    ) -> Option<String>;
 617
 618    /// Replace the text in the given document range with the given text
 619    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 620    ///
 621    /// replacement_range is in terms of UTF-16 characters
 622    fn replace_text_in_range(
 623        &mut self,
 624        replacement_range: Option<Range<usize>>,
 625        text: &str,
 626        cx: &mut WindowContext,
 627    );
 628
 629    /// Replace the text in the given document range with the given text,
 630    /// and mark the given text as part of an IME 'composing' state
 631    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 632    ///
 633    /// range_utf16 is in terms of UTF-16 characters
 634    /// new_selected_range is in terms of UTF-16 characters
 635    fn replace_and_mark_text_in_range(
 636        &mut self,
 637        range_utf16: Option<Range<usize>>,
 638        new_text: &str,
 639        new_selected_range: Option<Range<usize>>,
 640        cx: &mut WindowContext,
 641    );
 642
 643    /// Remove the IME 'composing' state from the document
 644    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 645    fn unmark_text(&mut self, cx: &mut WindowContext);
 646
 647    /// Get the bounds of the given document range in screen coordinates
 648    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 649    ///
 650    /// This is used for positioning the IME candidate window
 651    fn bounds_for_range(
 652        &mut self,
 653        range_utf16: Range<usize>,
 654        cx: &mut WindowContext,
 655    ) -> Option<Bounds<Pixels>>;
 656}
 657
 658/// The variables that can be configured when creating a new window
 659#[derive(Debug)]
 660pub struct WindowOptions {
 661    /// Specifies the state and bounds of the window in screen coordinates.
 662    /// - `None`: Inherit the bounds.
 663    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 664    pub window_bounds: Option<WindowBounds>,
 665
 666    /// The titlebar configuration of the window
 667    pub titlebar: Option<TitlebarOptions>,
 668
 669    /// Whether the window should be focused when created
 670    pub focus: bool,
 671
 672    /// Whether the window should be shown when created
 673    pub show: bool,
 674
 675    /// The kind of window to create
 676    pub kind: WindowKind,
 677
 678    /// Whether the window should be movable by the user
 679    pub is_movable: bool,
 680
 681    /// The display to create the window on, if this is None,
 682    /// the window will be created on the main display
 683    pub display_id: Option<DisplayId>,
 684
 685    /// The appearance of the window background.
 686    pub window_background: WindowBackgroundAppearance,
 687
 688    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 689    pub app_id: Option<String>,
 690
 691    /// Window minimum size
 692    pub window_min_size: Option<Size<Pixels>>,
 693
 694    /// Whether to use client or server side decorations. Wayland only
 695    /// Note that this may be ignored.
 696    pub window_decorations: Option<WindowDecorations>,
 697}
 698
 699/// The variables that can be configured when creating a new window
 700#[derive(Debug)]
 701pub(crate) struct WindowParams {
 702    pub bounds: Bounds<Pixels>,
 703
 704    /// The titlebar configuration of the window
 705    pub titlebar: Option<TitlebarOptions>,
 706
 707    /// The kind of window to create
 708    #[cfg_attr(target_os = "linux", allow(dead_code))]
 709    pub kind: WindowKind,
 710
 711    /// Whether the window should be movable by the user
 712    #[cfg_attr(target_os = "linux", allow(dead_code))]
 713    pub is_movable: bool,
 714
 715    #[cfg_attr(target_os = "linux", allow(dead_code))]
 716    pub focus: bool,
 717
 718    #[cfg_attr(target_os = "linux", allow(dead_code))]
 719    pub show: bool,
 720
 721    pub display_id: Option<DisplayId>,
 722
 723    pub window_min_size: Option<Size<Pixels>>,
 724}
 725
 726/// Represents the status of how a window should be opened.
 727#[derive(Debug, Copy, Clone, PartialEq)]
 728pub enum WindowBounds {
 729    /// Indicates that the window should open in a windowed state with the given bounds.
 730    Windowed(Bounds<Pixels>),
 731    /// Indicates that the window should open in a maximized state.
 732    /// The bounds provided here represent the restore size of the window.
 733    Maximized(Bounds<Pixels>),
 734    /// Indicates that the window should open in fullscreen mode.
 735    /// The bounds provided here represent the restore size of the window.
 736    Fullscreen(Bounds<Pixels>),
 737}
 738
 739impl Default for WindowBounds {
 740    fn default() -> Self {
 741        WindowBounds::Windowed(Bounds::default())
 742    }
 743}
 744
 745impl WindowBounds {
 746    /// Retrieve the inner bounds
 747    pub fn get_bounds(&self) -> Bounds<Pixels> {
 748        match self {
 749            WindowBounds::Windowed(bounds) => *bounds,
 750            WindowBounds::Maximized(bounds) => *bounds,
 751            WindowBounds::Fullscreen(bounds) => *bounds,
 752        }
 753    }
 754}
 755
 756impl Default for WindowOptions {
 757    fn default() -> Self {
 758        Self {
 759            window_bounds: None,
 760            titlebar: Some(TitlebarOptions {
 761                title: Default::default(),
 762                appears_transparent: Default::default(),
 763                traffic_light_position: Default::default(),
 764            }),
 765            focus: true,
 766            show: true,
 767            kind: WindowKind::Normal,
 768            is_movable: true,
 769            display_id: None,
 770            window_background: WindowBackgroundAppearance::default(),
 771            app_id: None,
 772            window_min_size: None,
 773            window_decorations: None,
 774        }
 775    }
 776}
 777
 778/// The options that can be configured for a window's titlebar
 779#[derive(Debug, Default)]
 780pub struct TitlebarOptions {
 781    /// The initial title of the window
 782    pub title: Option<SharedString>,
 783
 784    /// Whether the titlebar should appear transparent (macOS only)
 785    pub appears_transparent: bool,
 786
 787    /// The position of the macOS traffic light buttons
 788    pub traffic_light_position: Option<Point<Pixels>>,
 789}
 790
 791/// The kind of window to create
 792#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 793pub enum WindowKind {
 794    /// A normal application window
 795    Normal,
 796
 797    /// A window that appears above all other windows, usually used for alerts or popups
 798    /// use sparingly!
 799    PopUp,
 800}
 801
 802/// The appearance of the window, as defined by the operating system.
 803///
 804/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 805/// values.
 806#[derive(Copy, Clone, Debug)]
 807pub enum WindowAppearance {
 808    /// A light appearance.
 809    ///
 810    /// On macOS, this corresponds to the `aqua` appearance.
 811    Light,
 812
 813    /// A light appearance with vibrant colors.
 814    ///
 815    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 816    VibrantLight,
 817
 818    /// A dark appearance.
 819    ///
 820    /// On macOS, this corresponds to the `darkAqua` appearance.
 821    Dark,
 822
 823    /// A dark appearance with vibrant colors.
 824    ///
 825    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
 826    VibrantDark,
 827}
 828
 829impl Default for WindowAppearance {
 830    fn default() -> Self {
 831        Self::Light
 832    }
 833}
 834
 835/// The appearance of the background of the window itself, when there is
 836/// no content or the content is transparent.
 837#[derive(Copy, Clone, Debug, Default, PartialEq)]
 838pub enum WindowBackgroundAppearance {
 839    /// Opaque.
 840    ///
 841    /// This lets the window manager know that content behind this
 842    /// window does not need to be drawn.
 843    ///
 844    /// Actual color depends on the system and themes should define a fully
 845    /// opaque background color instead.
 846    #[default]
 847    Opaque,
 848    /// Plain alpha transparency.
 849    Transparent,
 850    /// Transparency, but the contents behind the window are blurred.
 851    ///
 852    /// Not always supported.
 853    Blurred,
 854}
 855
 856/// The options that can be configured for a file dialog prompt
 857#[derive(Copy, Clone, Debug)]
 858pub struct PathPromptOptions {
 859    /// Should the prompt allow files to be selected?
 860    pub files: bool,
 861    /// Should the prompt allow directories to be selected?
 862    pub directories: bool,
 863    /// Should the prompt allow multiple files to be selected?
 864    pub multiple: bool,
 865}
 866
 867/// What kind of prompt styling to show
 868#[derive(Copy, Clone, Debug, PartialEq)]
 869pub enum PromptLevel {
 870    /// A prompt that is shown when the user should be notified of something
 871    Info,
 872
 873    /// A prompt that is shown when the user needs to be warned of a potential problem
 874    Warning,
 875
 876    /// A prompt that is shown when a critical problem has occurred
 877    Critical,
 878}
 879
 880/// The style of the cursor (pointer)
 881#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 882pub enum CursorStyle {
 883    /// The default cursor
 884    Arrow,
 885
 886    /// A text input cursor
 887    /// corresponds to the CSS cursor value `text`
 888    IBeam,
 889
 890    /// A crosshair cursor
 891    /// corresponds to the CSS cursor value `crosshair`
 892    Crosshair,
 893
 894    /// A closed hand cursor
 895    /// corresponds to the CSS cursor value `grabbing`
 896    ClosedHand,
 897
 898    /// An open hand cursor
 899    /// corresponds to the CSS cursor value `grab`
 900    OpenHand,
 901
 902    /// A pointing hand cursor
 903    /// corresponds to the CSS cursor value `pointer`
 904    PointingHand,
 905
 906    /// A resize left cursor
 907    /// corresponds to the CSS cursor value `w-resize`
 908    ResizeLeft,
 909
 910    /// A resize right cursor
 911    /// corresponds to the CSS cursor value `e-resize`
 912    ResizeRight,
 913
 914    /// A resize cursor to the left and right
 915    /// corresponds to the CSS cursor value `ew-resize`
 916    ResizeLeftRight,
 917
 918    /// A resize up cursor
 919    /// corresponds to the CSS cursor value `n-resize`
 920    ResizeUp,
 921
 922    /// A resize down cursor
 923    /// corresponds to the CSS cursor value `s-resize`
 924    ResizeDown,
 925
 926    /// A resize cursor directing up and down
 927    /// corresponds to the CSS cursor value `ns-resize`
 928    ResizeUpDown,
 929
 930    /// A resize cursor directing up-left and down-right
 931    /// corresponds to the CSS cursor value `nesw-resize`
 932    ResizeUpLeftDownRight,
 933
 934    /// A resize cursor directing up-right and down-left
 935    /// corresponds to the CSS cursor value `nwse-resize`
 936    ResizeUpRightDownLeft,
 937
 938    /// A cursor indicating that the item/column can be resized horizontally.
 939    /// corresponds to the CSS cursor value `col-resize`
 940    ResizeColumn,
 941
 942    /// A cursor indicating that the item/row can be resized vertically.
 943    /// corresponds to the CSS cursor value `row-resize`
 944    ResizeRow,
 945
 946    /// A text input cursor for vertical layout
 947    /// corresponds to the CSS cursor value `vertical-text`
 948    IBeamCursorForVerticalLayout,
 949
 950    /// A cursor indicating that the operation is not allowed
 951    /// corresponds to the CSS cursor value `not-allowed`
 952    OperationNotAllowed,
 953
 954    /// A cursor indicating that the operation will result in a link
 955    /// corresponds to the CSS cursor value `alias`
 956    DragLink,
 957
 958    /// A cursor indicating that the operation will result in a copy
 959    /// corresponds to the CSS cursor value `copy`
 960    DragCopy,
 961
 962    /// A cursor indicating that the operation will result in a context menu
 963    /// corresponds to the CSS cursor value `context-menu`
 964    ContextualMenu,
 965}
 966
 967impl Default for CursorStyle {
 968    fn default() -> Self {
 969        Self::Arrow
 970    }
 971}
 972
 973/// A clipboard item that should be copied to the clipboard
 974#[derive(Clone, Debug, Eq, PartialEq)]
 975pub struct ClipboardItem {
 976    entries: Vec<ClipboardEntry>,
 977}
 978
 979/// Either a ClipboardString or a ClipboardImage
 980#[derive(Clone, Debug, Eq, PartialEq)]
 981pub enum ClipboardEntry {
 982    /// A string entry
 983    String(ClipboardString),
 984    /// An image entry
 985    Image(Image),
 986}
 987
 988impl ClipboardItem {
 989    /// Create a new ClipboardItem::String with no associated metadata
 990    pub fn new_string(text: String) -> Self {
 991        Self {
 992            entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
 993        }
 994    }
 995
 996    /// Create a new ClipboardItem::String with the given text and associated metadata
 997    pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
 998        Self {
 999            entries: vec![ClipboardEntry::String(ClipboardString {
1000                text,
1001                metadata: Some(metadata),
1002            })],
1003        }
1004    }
1005
1006    /// Create a new ClipboardItem::String with the given text and associated metadata
1007    pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1008        Self {
1009            entries: vec![ClipboardEntry::String(
1010                ClipboardString::new(text).with_json_metadata(metadata),
1011            )],
1012        }
1013    }
1014
1015    /// Create a new ClipboardItem::Image with the given image with no associated metadata
1016    pub fn new_image(image: &Image) -> Self {
1017        Self {
1018            entries: vec![ClipboardEntry::Image(image.clone())],
1019        }
1020    }
1021
1022    /// Concatenates together all the ClipboardString entries in the item.
1023    /// Returns None if there were no ClipboardString entries.
1024    pub fn text(&self) -> Option<String> {
1025        let mut answer = String::new();
1026        let mut any_entries = false;
1027
1028        for entry in self.entries.iter() {
1029            if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1030                answer.push_str(text);
1031                any_entries = true;
1032            }
1033        }
1034
1035        if any_entries {
1036            Some(answer)
1037        } else {
1038            None
1039        }
1040    }
1041
1042    /// If this item is one ClipboardEntry::String, returns its metadata.
1043    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1044    pub fn metadata(&self) -> Option<&String> {
1045        match self.entries().first() {
1046            Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1047                clipboard_string.metadata.as_ref()
1048            }
1049            _ => None,
1050        }
1051    }
1052
1053    /// Get the item's entries
1054    pub fn entries(&self) -> &[ClipboardEntry] {
1055        &self.entries
1056    }
1057
1058    /// Get owned versions of the item's entries
1059    pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1060        self.entries.into_iter()
1061    }
1062}
1063
1064/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1065#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1066pub enum ImageFormat {
1067    // Sorted from most to least likely to be pasted into an editor,
1068    // which matters when we iterate through them trying to see if
1069    // clipboard content matches them.
1070    /// .png
1071    Png,
1072    /// .jpeg or .jpg
1073    Jpeg,
1074    /// .webp
1075    Webp,
1076    /// .gif
1077    Gif,
1078    /// .svg
1079    Svg,
1080    /// .bmp
1081    Bmp,
1082    /// .tif or .tiff
1083    Tiff,
1084}
1085
1086/// An image, with a format and certain bytes
1087#[derive(Clone, Debug, PartialEq, Eq)]
1088pub struct Image {
1089    /// The image format the bytes represent (e.g. PNG)
1090    pub format: ImageFormat,
1091    /// The raw image bytes
1092    pub bytes: Vec<u8>,
1093    /// The unique ID for the image
1094    pub id: u64,
1095}
1096
1097impl Hash for Image {
1098    fn hash<H: Hasher>(&self, state: &mut H) {
1099        state.write_u64(self.id);
1100    }
1101}
1102
1103impl Image {
1104    /// Get this image's ID
1105    pub fn id(&self) -> u64 {
1106        self.id
1107    }
1108
1109    /// Use the GPUI `use_asset` API to make this image renderable
1110    pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1111        ImageSource::Image(self).use_data(cx)
1112    }
1113
1114    /// Convert the clipboard image to an `ImageData` object.
1115    pub fn to_image_data(&self, cx: &AppContext) -> Result<Arc<RenderImage>> {
1116        fn frames_for_image(
1117            bytes: &[u8],
1118            format: image::ImageFormat,
1119        ) -> Result<SmallVec<[Frame; 1]>> {
1120            let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1121
1122            // Convert from RGBA to BGRA.
1123            for pixel in data.chunks_exact_mut(4) {
1124                pixel.swap(0, 2);
1125            }
1126
1127            Ok(SmallVec::from_elem(Frame::new(data), 1))
1128        }
1129
1130        let frames = match self.format {
1131            ImageFormat::Gif => {
1132                let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1133                let mut frames = SmallVec::new();
1134
1135                for frame in decoder.into_frames() {
1136                    let mut frame = frame?;
1137                    // Convert from RGBA to BGRA.
1138                    for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1139                        pixel.swap(0, 2);
1140                    }
1141                    frames.push(frame);
1142                }
1143
1144                frames
1145            }
1146            ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1147            ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1148            ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1149            ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1150            ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1151            ImageFormat::Svg => {
1152                // TODO: Fix this
1153                let pixmap = cx
1154                    .svg_renderer()
1155                    .render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1156
1157                let buffer =
1158                    image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1159                        .unwrap();
1160
1161                SmallVec::from_elem(Frame::new(buffer), 1)
1162            }
1163        };
1164
1165        Ok(Arc::new(RenderImage::new(frames)))
1166    }
1167
1168    /// Get the format of the clipboard image
1169    pub fn format(&self) -> ImageFormat {
1170        self.format
1171    }
1172
1173    /// Get the raw bytes of the clipboard image
1174    pub fn bytes(&self) -> &[u8] {
1175        self.bytes.as_slice()
1176    }
1177}
1178
1179/// A clipboard item that should be copied to the clipboard
1180#[derive(Clone, Debug, Eq, PartialEq)]
1181pub struct ClipboardString {
1182    pub(crate) text: String,
1183    pub(crate) metadata: Option<String>,
1184}
1185
1186impl ClipboardString {
1187    /// Create a new clipboard string with the given text
1188    pub fn new(text: String) -> Self {
1189        Self {
1190            text,
1191            metadata: None,
1192        }
1193    }
1194
1195    /// Return a new clipboard item with the metadata replaced by the given metadata,
1196    /// after serializing it as JSON.
1197    pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1198        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1199        self
1200    }
1201
1202    /// Get the text of the clipboard string
1203    pub fn text(&self) -> &String {
1204        &self.text
1205    }
1206
1207    /// Get the owned text of the clipboard string
1208    pub fn into_text(self) -> String {
1209        self.text
1210    }
1211
1212    /// Get the metadata of the clipboard string, formatted as JSON
1213    pub fn metadata_json<T>(&self) -> Option<T>
1214    where
1215        T: for<'a> Deserialize<'a>,
1216    {
1217        self.metadata
1218            .as_ref()
1219            .and_then(|m| serde_json::from_str(m).ok())
1220    }
1221
1222    #[cfg_attr(target_os = "linux", allow(dead_code))]
1223    pub(crate) fn text_hash(text: &str) -> u64 {
1224        let mut hasher = SeaHasher::new();
1225        text.hash(&mut hasher);
1226        hasher.finish()
1227    }
1228}