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<Option<Vec<PathBuf>>>;
 141    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<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 set_title(&mut self, title: &str);
 322    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
 323    fn minimize(&self);
 324    fn zoom(&self);
 325    fn toggle_fullscreen(&self);
 326    fn is_fullscreen(&self) -> bool;
 327    fn on_request_frame(&self, callback: Box<dyn FnMut()>);
 328    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
 329    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
 330    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
 331    fn on_moved(&self, callback: Box<dyn FnMut()>);
 332    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
 333    fn on_close(&self, callback: Box<dyn FnOnce()>);
 334    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
 335    fn draw(&self, scene: &Scene);
 336    fn completed_frame(&self) {}
 337    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
 338
 339    // macOS specific methods
 340    fn set_edited(&mut self, _edited: bool) {}
 341    fn show_character_palette(&self) {}
 342
 343    #[cfg(target_os = "windows")]
 344    fn get_raw_handle(&self) -> windows::HWND;
 345
 346    // Linux specific methods
 347    fn request_decorations(&self, _decorations: WindowDecorations) {}
 348    fn show_window_menu(&self, _position: Point<Pixels>) {}
 349    fn start_window_move(&self) {}
 350    fn start_window_resize(&self, _edge: ResizeEdge) {}
 351    fn window_decorations(&self) -> Decorations {
 352        Decorations::Server
 353    }
 354    fn set_app_id(&mut self, _app_id: &str) {}
 355    fn window_controls(&self) -> WindowControls {
 356        WindowControls {
 357            fullscreen: true,
 358            maximize: true,
 359            minimize: true,
 360            window_menu: false,
 361        }
 362    }
 363    fn set_client_inset(&self, _inset: Pixels) {}
 364
 365    #[cfg(any(test, feature = "test-support"))]
 366    fn as_test(&mut self) -> Option<&mut TestWindow> {
 367        None
 368    }
 369}
 370
 371/// This type is public so that our test macro can generate and use it, but it should not
 372/// be considered part of our public API.
 373#[doc(hidden)]
 374pub trait PlatformDispatcher: Send + Sync {
 375    fn is_main_thread(&self) -> bool;
 376    fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
 377    fn dispatch_on_main_thread(&self, runnable: Runnable);
 378    fn dispatch_after(&self, duration: Duration, runnable: Runnable);
 379    fn park(&self, timeout: Option<Duration>) -> bool;
 380    fn unparker(&self) -> Unparker;
 381    fn now(&self) -> Instant {
 382        Instant::now()
 383    }
 384
 385    #[cfg(any(test, feature = "test-support"))]
 386    fn as_test(&self) -> Option<&TestDispatcher> {
 387        None
 388    }
 389}
 390
 391pub(crate) trait PlatformTextSystem: Send + Sync {
 392    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
 393    fn all_font_names(&self) -> Vec<String>;
 394    fn all_font_families(&self) -> Vec<String>;
 395    fn font_id(&self, descriptor: &Font) -> Result<FontId>;
 396    fn font_metrics(&self, font_id: FontId) -> FontMetrics;
 397    fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
 398    fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
 399    fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
 400    fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
 401    fn rasterize_glyph(
 402        &self,
 403        params: &RenderGlyphParams,
 404        raster_bounds: Bounds<DevicePixels>,
 405    ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
 406    fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
 407}
 408
 409#[derive(PartialEq, Eq, Hash, Clone)]
 410pub(crate) enum AtlasKey {
 411    Glyph(RenderGlyphParams),
 412    Svg(RenderSvgParams),
 413    Image(RenderImageParams),
 414}
 415
 416impl AtlasKey {
 417    pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
 418        match self {
 419            AtlasKey::Glyph(params) => {
 420                if params.is_emoji {
 421                    AtlasTextureKind::Polychrome
 422                } else {
 423                    AtlasTextureKind::Monochrome
 424                }
 425            }
 426            AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
 427            AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
 428        }
 429    }
 430}
 431
 432impl From<RenderGlyphParams> for AtlasKey {
 433    fn from(params: RenderGlyphParams) -> Self {
 434        Self::Glyph(params)
 435    }
 436}
 437
 438impl From<RenderSvgParams> for AtlasKey {
 439    fn from(params: RenderSvgParams) -> Self {
 440        Self::Svg(params)
 441    }
 442}
 443
 444impl From<RenderImageParams> for AtlasKey {
 445    fn from(params: RenderImageParams) -> Self {
 446        Self::Image(params)
 447    }
 448}
 449
 450pub(crate) trait PlatformAtlas: Send + Sync {
 451    fn get_or_insert_with<'a>(
 452        &self,
 453        key: &AtlasKey,
 454        build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
 455    ) -> Result<Option<AtlasTile>>;
 456}
 457
 458#[derive(Clone, Debug, PartialEq, Eq)]
 459#[repr(C)]
 460pub(crate) struct AtlasTile {
 461    pub(crate) texture_id: AtlasTextureId,
 462    pub(crate) tile_id: TileId,
 463    pub(crate) padding: u32,
 464    pub(crate) bounds: Bounds<DevicePixels>,
 465}
 466
 467#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 468#[repr(C)]
 469pub(crate) struct AtlasTextureId {
 470    // We use u32 instead of usize for Metal Shader Language compatibility
 471    pub(crate) index: u32,
 472    pub(crate) kind: AtlasTextureKind,
 473}
 474
 475#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 476#[repr(C)]
 477pub(crate) enum AtlasTextureKind {
 478    Monochrome = 0,
 479    Polychrome = 1,
 480    Path = 2,
 481}
 482
 483#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
 484#[repr(C)]
 485pub(crate) struct TileId(pub(crate) u32);
 486
 487impl From<etagere::AllocId> for TileId {
 488    fn from(id: etagere::AllocId) -> Self {
 489        Self(id.serialize())
 490    }
 491}
 492
 493impl From<TileId> for etagere::AllocId {
 494    fn from(id: TileId) -> Self {
 495        Self::deserialize(id.0)
 496    }
 497}
 498
 499pub(crate) struct PlatformInputHandler {
 500    cx: AsyncWindowContext,
 501    handler: Box<dyn InputHandler>,
 502}
 503
 504impl PlatformInputHandler {
 505    pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
 506        Self { cx, handler }
 507    }
 508
 509    fn selected_text_range(&mut self) -> Option<Range<usize>> {
 510        self.cx
 511            .update(|cx| self.handler.selected_text_range(cx))
 512            .ok()
 513            .flatten()
 514    }
 515
 516    fn marked_text_range(&mut self) -> Option<Range<usize>> {
 517        self.cx
 518            .update(|cx| self.handler.marked_text_range(cx))
 519            .ok()
 520            .flatten()
 521    }
 522
 523    #[cfg_attr(target_os = "linux", allow(dead_code))]
 524    fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
 525        self.cx
 526            .update(|cx| self.handler.text_for_range(range_utf16, cx))
 527            .ok()
 528            .flatten()
 529    }
 530
 531    fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
 532        self.cx
 533            .update(|cx| {
 534                self.handler
 535                    .replace_text_in_range(replacement_range, text, cx);
 536            })
 537            .ok();
 538    }
 539
 540    fn replace_and_mark_text_in_range(
 541        &mut self,
 542        range_utf16: Option<Range<usize>>,
 543        new_text: &str,
 544        new_selected_range: Option<Range<usize>>,
 545    ) {
 546        self.cx
 547            .update(|cx| {
 548                self.handler.replace_and_mark_text_in_range(
 549                    range_utf16,
 550                    new_text,
 551                    new_selected_range,
 552                    cx,
 553                )
 554            })
 555            .ok();
 556    }
 557
 558    fn unmark_text(&mut self) {
 559        self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
 560    }
 561
 562    fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
 563        self.cx
 564            .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
 565            .ok()
 566            .flatten()
 567    }
 568
 569    pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
 570        self.handler.replace_text_in_range(None, input, cx);
 571    }
 572}
 573
 574/// Zed's interface for handling text input from the platform's IME system
 575/// This is currently a 1:1 exposure of the NSTextInputClient API:
 576///
 577/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
 578pub trait InputHandler: 'static {
 579    /// Get the range of the user's currently selected text, if any
 580    /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
 581    ///
 582    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 583    fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 584
 585    /// Get the range of the currently marked text, if any
 586    /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
 587    ///
 588    /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
 589    fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
 590
 591    /// Get the text for the given document range in UTF-16 characters
 592    /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
 593    ///
 594    /// range_utf16 is in terms of UTF-16 characters
 595    fn text_for_range(
 596        &mut self,
 597        range_utf16: Range<usize>,
 598        cx: &mut WindowContext,
 599    ) -> Option<String>;
 600
 601    /// Replace the text in the given document range with the given text
 602    /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
 603    ///
 604    /// replacement_range is in terms of UTF-16 characters
 605    fn replace_text_in_range(
 606        &mut self,
 607        replacement_range: Option<Range<usize>>,
 608        text: &str,
 609        cx: &mut WindowContext,
 610    );
 611
 612    /// Replace the text in the given document range with the given text,
 613    /// and mark the given text as part of of an IME 'composing' state
 614    /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
 615    ///
 616    /// range_utf16 is in terms of UTF-16 characters
 617    /// new_selected_range is in terms of UTF-16 characters
 618    fn replace_and_mark_text_in_range(
 619        &mut self,
 620        range_utf16: Option<Range<usize>>,
 621        new_text: &str,
 622        new_selected_range: Option<Range<usize>>,
 623        cx: &mut WindowContext,
 624    );
 625
 626    /// Remove the IME 'composing' state from the document
 627    /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
 628    fn unmark_text(&mut self, cx: &mut WindowContext);
 629
 630    /// Get the bounds of the given document range in screen coordinates
 631    /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
 632    ///
 633    /// This is used for positioning the IME candidate window
 634    fn bounds_for_range(
 635        &mut self,
 636        range_utf16: Range<usize>,
 637        cx: &mut WindowContext,
 638    ) -> Option<Bounds<Pixels>>;
 639}
 640
 641/// The variables that can be configured when creating a new window
 642#[derive(Debug)]
 643pub struct WindowOptions {
 644    /// Specifies the state and bounds of the window in screen coordinates.
 645    /// - `None`: Inherit the bounds.
 646    /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
 647    pub window_bounds: Option<WindowBounds>,
 648
 649    /// The titlebar configuration of the window
 650    pub titlebar: Option<TitlebarOptions>,
 651
 652    /// Whether the window should be focused when created
 653    pub focus: bool,
 654
 655    /// Whether the window should be shown when created
 656    pub show: bool,
 657
 658    /// The kind of window to create
 659    pub kind: WindowKind,
 660
 661    /// Whether the window should be movable by the user
 662    pub is_movable: bool,
 663
 664    /// The display to create the window on, if this is None,
 665    /// the window will be created on the main display
 666    pub display_id: Option<DisplayId>,
 667
 668    /// The appearance of the window background.
 669    pub window_background: WindowBackgroundAppearance,
 670
 671    /// Application identifier of the window. Can by used by desktop environments to group applications together.
 672    pub app_id: Option<String>,
 673
 674    /// Window minimum size
 675    pub window_min_size: Option<Size<Pixels>>,
 676
 677    /// Whether to use client or server side decorations. Wayland only
 678    /// Note that this may be ignored.
 679    pub window_decorations: Option<WindowDecorations>,
 680}
 681
 682/// The variables that can be configured when creating a new window
 683#[derive(Debug)]
 684pub(crate) struct WindowParams {
 685    pub bounds: Bounds<Pixels>,
 686
 687    /// The titlebar configuration of the window
 688    pub titlebar: Option<TitlebarOptions>,
 689
 690    /// The kind of window to create
 691    #[cfg_attr(target_os = "linux", allow(dead_code))]
 692    pub kind: WindowKind,
 693
 694    /// Whether the window should be movable by the user
 695    #[cfg_attr(target_os = "linux", allow(dead_code))]
 696    pub is_movable: bool,
 697
 698    #[cfg_attr(target_os = "linux", allow(dead_code))]
 699    pub focus: bool,
 700
 701    #[cfg_attr(target_os = "linux", allow(dead_code))]
 702    pub show: bool,
 703
 704    pub display_id: Option<DisplayId>,
 705
 706    #[cfg_attr(target_os = "linux", allow(dead_code))]
 707    pub window_min_size: Option<Size<Pixels>>,
 708}
 709
 710/// Represents the status of how a window should be opened.
 711#[derive(Debug, Copy, Clone, PartialEq)]
 712pub enum WindowBounds {
 713    /// Indicates that the window should open in a windowed state with the given bounds.
 714    Windowed(Bounds<Pixels>),
 715    /// Indicates that the window should open in a maximized state.
 716    /// The bounds provided here represent the restore size of the window.
 717    Maximized(Bounds<Pixels>),
 718    /// Indicates that the window should open in fullscreen mode.
 719    /// The bounds provided here represent the restore size of the window.
 720    Fullscreen(Bounds<Pixels>),
 721}
 722
 723impl Default for WindowBounds {
 724    fn default() -> Self {
 725        WindowBounds::Windowed(Bounds::default())
 726    }
 727}
 728
 729impl WindowBounds {
 730    /// Retrieve the inner bounds
 731    pub fn get_bounds(&self) -> Bounds<Pixels> {
 732        match self {
 733            WindowBounds::Windowed(bounds) => *bounds,
 734            WindowBounds::Maximized(bounds) => *bounds,
 735            WindowBounds::Fullscreen(bounds) => *bounds,
 736        }
 737    }
 738}
 739
 740impl Default for WindowOptions {
 741    fn default() -> Self {
 742        Self {
 743            window_bounds: None,
 744            titlebar: Some(TitlebarOptions {
 745                title: Default::default(),
 746                appears_transparent: Default::default(),
 747                traffic_light_position: Default::default(),
 748            }),
 749            focus: true,
 750            show: true,
 751            kind: WindowKind::Normal,
 752            is_movable: true,
 753            display_id: None,
 754            window_background: WindowBackgroundAppearance::default(),
 755            app_id: None,
 756            window_min_size: None,
 757            window_decorations: None,
 758        }
 759    }
 760}
 761
 762/// The options that can be configured for a window's titlebar
 763#[derive(Debug, Default)]
 764pub struct TitlebarOptions {
 765    /// The initial title of the window
 766    pub title: Option<SharedString>,
 767
 768    /// Whether the titlebar should appear transparent (macOS only)
 769    pub appears_transparent: bool,
 770
 771    /// The position of the macOS traffic light buttons
 772    pub traffic_light_position: Option<Point<Pixels>>,
 773}
 774
 775/// The kind of window to create
 776#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 777pub enum WindowKind {
 778    /// A normal application window
 779    Normal,
 780
 781    /// A window that appears above all other windows, usually used for alerts or popups
 782    /// use sparingly!
 783    PopUp,
 784}
 785
 786/// The appearance of the window, as defined by the operating system.
 787///
 788/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
 789/// values.
 790#[derive(Copy, Clone, Debug)]
 791pub enum WindowAppearance {
 792    /// A light appearance.
 793    ///
 794    /// On macOS, this corresponds to the `aqua` appearance.
 795    Light,
 796
 797    /// A light appearance with vibrant colors.
 798    ///
 799    /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
 800    VibrantLight,
 801
 802    /// A dark appearance.
 803    ///
 804    /// On macOS, this corresponds to the `darkAqua` appearance.
 805    Dark,
 806
 807    /// A dark appearance with vibrant colors.
 808    ///
 809    /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
 810    VibrantDark,
 811}
 812
 813impl Default for WindowAppearance {
 814    fn default() -> Self {
 815        Self::Light
 816    }
 817}
 818
 819/// The appearance of the background of the window itself, when there is
 820/// no content or the content is transparent.
 821#[derive(Copy, Clone, Debug, Default, PartialEq)]
 822pub enum WindowBackgroundAppearance {
 823    /// Opaque.
 824    ///
 825    /// This lets the window manager know that content behind this
 826    /// window does not need to be drawn.
 827    ///
 828    /// Actual color depends on the system and themes should define a fully
 829    /// opaque background color instead.
 830    #[default]
 831    Opaque,
 832    /// Plain alpha transparency.
 833    Transparent,
 834    /// Transparency, but the contents behind the window are blurred.
 835    ///
 836    /// Not always supported.
 837    Blurred,
 838}
 839
 840/// The options that can be configured for a file dialog prompt
 841#[derive(Copy, Clone, Debug)]
 842pub struct PathPromptOptions {
 843    /// Should the prompt allow files to be selected?
 844    pub files: bool,
 845    /// Should the prompt allow directories to be selected?
 846    pub directories: bool,
 847    /// Should the prompt allow multiple files to be selected?
 848    pub multiple: bool,
 849}
 850
 851/// What kind of prompt styling to show
 852#[derive(Copy, Clone, Debug, PartialEq)]
 853pub enum PromptLevel {
 854    /// A prompt that is shown when the user should be notified of something
 855    Info,
 856
 857    /// A prompt that is shown when the user needs to be warned of a potential problem
 858    Warning,
 859
 860    /// A prompt that is shown when a critical problem has occurred
 861    Critical,
 862}
 863
 864/// The style of the cursor (pointer)
 865#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 866pub enum CursorStyle {
 867    /// The default cursor
 868    Arrow,
 869
 870    /// A text input cursor
 871    /// corresponds to the CSS cursor value `text`
 872    IBeam,
 873
 874    /// A crosshair cursor
 875    /// corresponds to the CSS cursor value `crosshair`
 876    Crosshair,
 877
 878    /// A closed hand cursor
 879    /// corresponds to the CSS cursor value `grabbing`
 880    ClosedHand,
 881
 882    /// An open hand cursor
 883    /// corresponds to the CSS cursor value `grab`
 884    OpenHand,
 885
 886    /// A pointing hand cursor
 887    /// corresponds to the CSS cursor value `pointer`
 888    PointingHand,
 889
 890    /// A resize left cursor
 891    /// corresponds to the CSS cursor value `w-resize`
 892    ResizeLeft,
 893
 894    /// A resize right cursor
 895    /// corresponds to the CSS cursor value `e-resize`
 896    ResizeRight,
 897
 898    /// A resize cursor to the left and right
 899    /// corresponds to the CSS cursor value `ew-resize`
 900    ResizeLeftRight,
 901
 902    /// A resize up cursor
 903    /// corresponds to the CSS cursor value `n-resize`
 904    ResizeUp,
 905
 906    /// A resize down cursor
 907    /// corresponds to the CSS cursor value `s-resize`
 908    ResizeDown,
 909
 910    /// A resize cursor directing up and down
 911    /// corresponds to the CSS cursor value `ns-resize`
 912    ResizeUpDown,
 913
 914    /// A resize cursor directing up-left and down-right
 915    /// corresponds to the CSS cursor value `nesw-resize`
 916    ResizeUpLeftDownRight,
 917
 918    /// A resize cursor directing up-right and down-left
 919    /// corresponds to the CSS cursor value `nwse-resize`
 920    ResizeUpRightDownLeft,
 921
 922    /// A cursor indicating that the item/column can be resized horizontally.
 923    /// corresponds to the CSS curosr value `col-resize`
 924    ResizeColumn,
 925
 926    /// A cursor indicating that the item/row can be resized vertically.
 927    /// corresponds to the CSS curosr value `row-resize`
 928    ResizeRow,
 929
 930    /// A text input cursor for vertical layout
 931    /// corresponds to the CSS cursor value `vertical-text`
 932    IBeamCursorForVerticalLayout,
 933
 934    /// A cursor indicating that the operation is not allowed
 935    /// corresponds to the CSS cursor value `not-allowed`
 936    OperationNotAllowed,
 937
 938    /// A cursor indicating that the operation will result in a link
 939    /// corresponds to the CSS cursor value `alias`
 940    DragLink,
 941
 942    /// A cursor indicating that the operation will result in a copy
 943    /// corresponds to the CSS cursor value `copy`
 944    DragCopy,
 945
 946    /// A cursor indicating that the operation will result in a context menu
 947    /// corresponds to the CSS cursor value `context-menu`
 948    ContextualMenu,
 949}
 950
 951impl Default for CursorStyle {
 952    fn default() -> Self {
 953        Self::Arrow
 954    }
 955}
 956
 957/// A clipboard item that should be copied to the clipboard
 958#[derive(Clone, Debug, Eq, PartialEq)]
 959pub struct ClipboardItem {
 960    pub(crate) text: String,
 961    pub(crate) metadata: Option<String>,
 962}
 963
 964impl ClipboardItem {
 965    /// Create a new clipboard item with the given text
 966    pub fn new(text: String) -> Self {
 967        Self {
 968            text,
 969            metadata: None,
 970        }
 971    }
 972
 973    /// Create a new clipboard item with the given text and metadata
 974    pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
 975        self.metadata = Some(serde_json::to_string(&metadata).unwrap());
 976        self
 977    }
 978
 979    /// Get the text of the clipboard item
 980    pub fn text(&self) -> &String {
 981        &self.text
 982    }
 983
 984    /// Get the metadata of the clipboard item
 985    pub fn metadata<T>(&self) -> Option<T>
 986    where
 987        T: for<'a> Deserialize<'a>,
 988    {
 989        self.metadata
 990            .as_ref()
 991            .and_then(|m| serde_json::from_str(m).ok())
 992    }
 993
 994    #[cfg_attr(target_os = "linux", allow(dead_code))]
 995    pub(crate) fn text_hash(text: &str) -> u64 {
 996        let mut hasher = SeaHasher::new();
 997        text.hash(&mut hasher);
 998        hasher.finish()
 999    }
1000}