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