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