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