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