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 /// Window minimum size
572 pub window_min_size: Option<Size<Pixels>>,
573}
574
575/// The variables that can be configured when creating a new window
576#[derive(Debug)]
577pub(crate) struct WindowParams {
578 pub bounds: Bounds<Pixels>,
579
580 /// The titlebar configuration of the window
581 pub titlebar: Option<TitlebarOptions>,
582
583 /// The kind of window to create
584 #[cfg_attr(target_os = "linux", allow(dead_code))]
585 pub kind: WindowKind,
586
587 /// Whether the window should be movable by the user
588 #[cfg_attr(target_os = "linux", allow(dead_code))]
589 pub is_movable: bool,
590
591 #[cfg_attr(target_os = "linux", allow(dead_code))]
592 pub focus: bool,
593
594 #[cfg_attr(target_os = "linux", allow(dead_code))]
595 pub show: bool,
596
597 pub display_id: Option<DisplayId>,
598
599 pub window_background: WindowBackgroundAppearance,
600
601 #[cfg_attr(target_os = "linux", allow(dead_code))]
602 pub window_min_size: Option<Size<Pixels>>,
603}
604
605/// Represents the status of how a window should be opened.
606#[derive(Debug, Copy, Clone, PartialEq)]
607pub enum WindowBounds {
608 /// Indicates that the window should open in a windowed state with the given bounds.
609 Windowed(Bounds<Pixels>),
610 /// Indicates that the window should open in a maximized state.
611 /// The bounds provided here represent the restore size of the window.
612 Maximized(Bounds<Pixels>),
613 /// Indicates that the window should open in fullscreen mode.
614 /// The bounds provided here represent the restore size of the window.
615 Fullscreen(Bounds<Pixels>),
616}
617
618impl Default for WindowBounds {
619 fn default() -> Self {
620 WindowBounds::Windowed(Bounds::default())
621 }
622}
623
624impl WindowBounds {
625 /// Retrieve the inner bounds
626 pub fn get_bounds(&self) -> Bounds<Pixels> {
627 match self {
628 WindowBounds::Windowed(bounds) => *bounds,
629 WindowBounds::Maximized(bounds) => *bounds,
630 WindowBounds::Fullscreen(bounds) => *bounds,
631 }
632 }
633}
634
635impl Default for WindowOptions {
636 fn default() -> Self {
637 Self {
638 window_bounds: None,
639 titlebar: Some(TitlebarOptions {
640 title: Default::default(),
641 appears_transparent: Default::default(),
642 traffic_light_position: Default::default(),
643 }),
644 focus: true,
645 show: true,
646 kind: WindowKind::Normal,
647 is_movable: true,
648 display_id: None,
649 window_background: WindowBackgroundAppearance::default(),
650 app_id: None,
651 window_min_size: None,
652 }
653 }
654}
655
656/// The options that can be configured for a window's titlebar
657#[derive(Debug, Default)]
658pub struct TitlebarOptions {
659 /// The initial title of the window
660 pub title: Option<SharedString>,
661
662 /// Whether the titlebar should appear transparent
663 pub appears_transparent: bool,
664
665 /// The position of the macOS traffic light buttons
666 pub traffic_light_position: Option<Point<Pixels>>,
667}
668
669/// The kind of window to create
670#[derive(Copy, Clone, Debug, PartialEq, Eq)]
671pub enum WindowKind {
672 /// A normal application window
673 Normal,
674
675 /// A window that appears above all other windows, usually used for alerts or popups
676 /// use sparingly!
677 PopUp,
678}
679
680/// The appearance of the window, as defined by the operating system.
681///
682/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
683/// values.
684#[derive(Copy, Clone, Debug)]
685pub enum WindowAppearance {
686 /// A light appearance.
687 ///
688 /// On macOS, this corresponds to the `aqua` appearance.
689 Light,
690
691 /// A light appearance with vibrant colors.
692 ///
693 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
694 VibrantLight,
695
696 /// A dark appearance.
697 ///
698 /// On macOS, this corresponds to the `darkAqua` appearance.
699 Dark,
700
701 /// A dark appearance with vibrant colors.
702 ///
703 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
704 VibrantDark,
705}
706
707impl Default for WindowAppearance {
708 fn default() -> Self {
709 Self::Light
710 }
711}
712
713/// The appearance of the background of the window itself, when there is
714/// no content or the content is transparent.
715#[derive(Copy, Clone, Debug, Default, PartialEq)]
716pub enum WindowBackgroundAppearance {
717 /// Opaque.
718 ///
719 /// This lets the window manager know that content behind this
720 /// window does not need to be drawn.
721 ///
722 /// Actual color depends on the system and themes should define a fully
723 /// opaque background color instead.
724 #[default]
725 Opaque,
726 /// Plain alpha transparency.
727 Transparent,
728 /// Transparency, but the contents behind the window are blurred.
729 ///
730 /// Not always supported.
731 Blurred,
732}
733
734/// The options that can be configured for a file dialog prompt
735#[derive(Copy, Clone, Debug)]
736pub struct PathPromptOptions {
737 /// Should the prompt allow files to be selected?
738 pub files: bool,
739 /// Should the prompt allow directories to be selected?
740 pub directories: bool,
741 /// Should the prompt allow multiple files to be selected?
742 pub multiple: bool,
743}
744
745/// What kind of prompt styling to show
746#[derive(Copy, Clone, Debug, PartialEq)]
747pub enum PromptLevel {
748 /// A prompt that is shown when the user should be notified of something
749 Info,
750
751 /// A prompt that is shown when the user needs to be warned of a potential problem
752 Warning,
753
754 /// A prompt that is shown when a critical problem has occurred
755 Critical,
756}
757
758/// The style of the cursor (pointer)
759#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
760pub enum CursorStyle {
761 /// The default cursor
762 Arrow,
763
764 /// A text input cursor
765 /// corresponds to the CSS cursor value `text`
766 IBeam,
767
768 /// A crosshair cursor
769 /// corresponds to the CSS cursor value `crosshair`
770 Crosshair,
771
772 /// A closed hand cursor
773 /// corresponds to the CSS cursor value `grabbing`
774 ClosedHand,
775
776 /// An open hand cursor
777 /// corresponds to the CSS cursor value `grab`
778 OpenHand,
779
780 /// A pointing hand cursor
781 /// corresponds to the CSS cursor value `pointer`
782 PointingHand,
783
784 /// A resize left cursor
785 /// corresponds to the CSS cursor value `w-resize`
786 ResizeLeft,
787
788 /// A resize right cursor
789 /// corresponds to the CSS cursor value `e-resize`
790 ResizeRight,
791
792 /// A resize cursor to the left and right
793 /// corresponds to the CSS cursor value `ew-resize`
794 ResizeLeftRight,
795
796 /// A resize up cursor
797 /// corresponds to the CSS cursor value `n-resize`
798 ResizeUp,
799
800 /// A resize down cursor
801 /// corresponds to the CSS cursor value `s-resize`
802 ResizeDown,
803
804 /// A resize cursor directing up and down
805 /// corresponds to the CSS cursor value `ns-resize`
806 ResizeUpDown,
807
808 /// A cursor indicating that the item/column can be resized horizontally.
809 /// corresponds to the CSS curosr value `col-resize`
810 ResizeColumn,
811
812 /// A cursor indicating that the item/row can be resized vertically.
813 /// corresponds to the CSS curosr value `row-resize`
814 ResizeRow,
815
816 /// A text input cursor for vertical layout
817 /// corresponds to the CSS cursor value `vertical-text`
818 IBeamCursorForVerticalLayout,
819
820 /// A cursor indicating that the operation is not allowed
821 /// corresponds to the CSS cursor value `not-allowed`
822 OperationNotAllowed,
823
824 /// A cursor indicating that the operation will result in a link
825 /// corresponds to the CSS cursor value `alias`
826 DragLink,
827
828 /// A cursor indicating that the operation will result in a copy
829 /// corresponds to the CSS cursor value `copy`
830 DragCopy,
831
832 /// A cursor indicating that the operation will result in a context menu
833 /// corresponds to the CSS cursor value `context-menu`
834 ContextualMenu,
835}
836
837impl Default for CursorStyle {
838 fn default() -> Self {
839 Self::Arrow
840 }
841}
842
843/// A clipboard item that should be copied to the clipboard
844#[derive(Clone, Debug, Eq, PartialEq)]
845pub struct ClipboardItem {
846 pub(crate) text: String,
847 pub(crate) metadata: Option<String>,
848}
849
850impl ClipboardItem {
851 /// Create a new clipboard item with the given text
852 pub fn new(text: String) -> Self {
853 Self {
854 text,
855 metadata: None,
856 }
857 }
858
859 /// Create a new clipboard item with the given text and metadata
860 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
861 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
862 self
863 }
864
865 /// Get the text of the clipboard item
866 pub fn text(&self) -> &String {
867 &self.text
868 }
869
870 /// Get the metadata of the clipboard item
871 pub fn metadata<T>(&self) -> Option<T>
872 where
873 T: for<'a> Deserialize<'a>,
874 {
875 self.metadata
876 .as_ref()
877 .and_then(|m| serde_json::from_str(m).ok())
878 }
879
880 #[cfg_attr(target_os = "linux", allow(dead_code))]
881 pub(crate) fn text_hash(text: &str) -> u64 {
882 let mut hasher = SeaHasher::new();
883 text.hash(&mut hasher);
884 hasher.finish()
885 }
886}