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