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