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