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