platform.rs

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