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
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
367 #[cfg(any(test, feature = "test-support"))]
368 fn as_test(&mut self) -> Option<&mut TestWindow> {
369 None
370 }
371}
372
373/// This type is public so that our test macro can generate and use it, but it should not
374/// be considered part of our public API.
375#[doc(hidden)]
376pub trait PlatformDispatcher: Send + Sync {
377 fn is_main_thread(&self) -> bool;
378 fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
379 fn dispatch_on_main_thread(&self, runnable: Runnable);
380 fn dispatch_after(&self, duration: Duration, runnable: Runnable);
381 fn park(&self, timeout: Option<Duration>) -> bool;
382 fn unparker(&self) -> Unparker;
383 fn now(&self) -> Instant {
384 Instant::now()
385 }
386
387 #[cfg(any(test, feature = "test-support"))]
388 fn as_test(&self) -> Option<&TestDispatcher> {
389 None
390 }
391}
392
393pub(crate) trait PlatformTextSystem: Send + Sync {
394 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
395 fn all_font_names(&self) -> Vec<String>;
396 fn all_font_families(&self) -> Vec<String>;
397 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
398 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
399 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
400 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
401 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
402 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
403 fn rasterize_glyph(
404 &self,
405 params: &RenderGlyphParams,
406 raster_bounds: Bounds<DevicePixels>,
407 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
408 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
409}
410
411#[derive(PartialEq, Eq, Hash, Clone)]
412pub(crate) enum AtlasKey {
413 Glyph(RenderGlyphParams),
414 Svg(RenderSvgParams),
415 Image(RenderImageParams),
416}
417
418impl AtlasKey {
419 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
420 match self {
421 AtlasKey::Glyph(params) => {
422 if params.is_emoji {
423 AtlasTextureKind::Polychrome
424 } else {
425 AtlasTextureKind::Monochrome
426 }
427 }
428 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
429 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
430 }
431 }
432}
433
434impl From<RenderGlyphParams> for AtlasKey {
435 fn from(params: RenderGlyphParams) -> Self {
436 Self::Glyph(params)
437 }
438}
439
440impl From<RenderSvgParams> for AtlasKey {
441 fn from(params: RenderSvgParams) -> Self {
442 Self::Svg(params)
443 }
444}
445
446impl From<RenderImageParams> for AtlasKey {
447 fn from(params: RenderImageParams) -> Self {
448 Self::Image(params)
449 }
450}
451
452pub(crate) trait PlatformAtlas: Send + Sync {
453 fn get_or_insert_with<'a>(
454 &self,
455 key: &AtlasKey,
456 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
457 ) -> Result<Option<AtlasTile>>;
458}
459
460#[derive(Clone, Debug, PartialEq, Eq)]
461#[repr(C)]
462pub(crate) struct AtlasTile {
463 pub(crate) texture_id: AtlasTextureId,
464 pub(crate) tile_id: TileId,
465 pub(crate) padding: u32,
466 pub(crate) bounds: Bounds<DevicePixels>,
467}
468
469#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
470#[repr(C)]
471pub(crate) struct AtlasTextureId {
472 // We use u32 instead of usize for Metal Shader Language compatibility
473 pub(crate) index: u32,
474 pub(crate) kind: AtlasTextureKind,
475}
476
477#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
478#[repr(C)]
479pub(crate) enum AtlasTextureKind {
480 Monochrome = 0,
481 Polychrome = 1,
482 Path = 2,
483}
484
485#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
486#[repr(C)]
487pub(crate) struct TileId(pub(crate) u32);
488
489impl From<etagere::AllocId> for TileId {
490 fn from(id: etagere::AllocId) -> Self {
491 Self(id.serialize())
492 }
493}
494
495impl From<TileId> for etagere::AllocId {
496 fn from(id: TileId) -> Self {
497 Self::deserialize(id.0)
498 }
499}
500
501pub(crate) struct PlatformInputHandler {
502 cx: AsyncWindowContext,
503 handler: Box<dyn InputHandler>,
504}
505
506impl PlatformInputHandler {
507 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
508 Self { cx, handler }
509 }
510
511 fn selected_text_range(&mut self) -> Option<Range<usize>> {
512 self.cx
513 .update(|cx| self.handler.selected_text_range(cx))
514 .ok()
515 .flatten()
516 }
517
518 fn marked_text_range(&mut self) -> Option<Range<usize>> {
519 self.cx
520 .update(|cx| self.handler.marked_text_range(cx))
521 .ok()
522 .flatten()
523 }
524
525 #[cfg_attr(target_os = "linux", allow(dead_code))]
526 fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
527 self.cx
528 .update(|cx| self.handler.text_for_range(range_utf16, cx))
529 .ok()
530 .flatten()
531 }
532
533 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
534 self.cx
535 .update(|cx| {
536 self.handler
537 .replace_text_in_range(replacement_range, text, cx);
538 })
539 .ok();
540 }
541
542 fn replace_and_mark_text_in_range(
543 &mut self,
544 range_utf16: Option<Range<usize>>,
545 new_text: &str,
546 new_selected_range: Option<Range<usize>>,
547 ) {
548 self.cx
549 .update(|cx| {
550 self.handler.replace_and_mark_text_in_range(
551 range_utf16,
552 new_text,
553 new_selected_range,
554 cx,
555 )
556 })
557 .ok();
558 }
559
560 fn unmark_text(&mut self) {
561 self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
562 }
563
564 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
565 self.cx
566 .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
567 .ok()
568 .flatten()
569 }
570
571 pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
572 self.handler.replace_text_in_range(None, input, cx);
573 }
574}
575
576/// Zed's interface for handling text input from the platform's IME system
577/// This is currently a 1:1 exposure of the NSTextInputClient API:
578///
579/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
580pub trait InputHandler: 'static {
581 /// Get the range of the user's currently selected text, if any
582 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
583 ///
584 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
585 fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
586
587 /// Get the range of the currently marked text, if any
588 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
589 ///
590 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
591 fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
592
593 /// Get the text for the given document range in UTF-16 characters
594 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
595 ///
596 /// range_utf16 is in terms of UTF-16 characters
597 fn text_for_range(
598 &mut self,
599 range_utf16: Range<usize>,
600 cx: &mut WindowContext,
601 ) -> Option<String>;
602
603 /// Replace the text in the given document range with the given text
604 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
605 ///
606 /// replacement_range is in terms of UTF-16 characters
607 fn replace_text_in_range(
608 &mut self,
609 replacement_range: Option<Range<usize>>,
610 text: &str,
611 cx: &mut WindowContext,
612 );
613
614 /// Replace the text in the given document range with the given text,
615 /// and mark the given text as part of of an IME 'composing' state
616 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
617 ///
618 /// range_utf16 is in terms of UTF-16 characters
619 /// new_selected_range is in terms of UTF-16 characters
620 fn replace_and_mark_text_in_range(
621 &mut self,
622 range_utf16: Option<Range<usize>>,
623 new_text: &str,
624 new_selected_range: Option<Range<usize>>,
625 cx: &mut WindowContext,
626 );
627
628 /// Remove the IME 'composing' state from the document
629 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
630 fn unmark_text(&mut self, cx: &mut WindowContext);
631
632 /// Get the bounds of the given document range in screen coordinates
633 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
634 ///
635 /// This is used for positioning the IME candidate window
636 fn bounds_for_range(
637 &mut self,
638 range_utf16: Range<usize>,
639 cx: &mut WindowContext,
640 ) -> Option<Bounds<Pixels>>;
641}
642
643/// The variables that can be configured when creating a new window
644#[derive(Debug)]
645pub struct WindowOptions {
646 /// Specifies the state and bounds of the window in screen coordinates.
647 /// - `None`: Inherit the bounds.
648 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
649 pub window_bounds: Option<WindowBounds>,
650
651 /// The titlebar configuration of the window
652 pub titlebar: Option<TitlebarOptions>,
653
654 /// Whether the window should be focused when created
655 pub focus: bool,
656
657 /// Whether the window should be shown when created
658 pub show: bool,
659
660 /// The kind of window to create
661 pub kind: WindowKind,
662
663 /// Whether the window should be movable by the user
664 pub is_movable: bool,
665
666 /// The display to create the window on, if this is None,
667 /// the window will be created on the main display
668 pub display_id: Option<DisplayId>,
669
670 /// The appearance of the window background.
671 pub window_background: WindowBackgroundAppearance,
672
673 /// Application identifier of the window. Can by used by desktop environments to group applications together.
674 pub app_id: Option<String>,
675
676 /// Window minimum size
677 pub window_min_size: Option<Size<Pixels>>,
678
679 /// Whether to use client or server side decorations. Wayland only
680 /// Note that this may be ignored.
681 pub window_decorations: Option<WindowDecorations>,
682}
683
684/// The variables that can be configured when creating a new window
685#[derive(Debug)]
686pub(crate) struct WindowParams {
687 pub bounds: Bounds<Pixels>,
688
689 /// The titlebar configuration of the window
690 pub titlebar: Option<TitlebarOptions>,
691
692 /// The kind of window to create
693 #[cfg_attr(target_os = "linux", allow(dead_code))]
694 pub kind: WindowKind,
695
696 /// Whether the window should be movable by the user
697 #[cfg_attr(target_os = "linux", allow(dead_code))]
698 pub is_movable: bool,
699
700 #[cfg_attr(target_os = "linux", allow(dead_code))]
701 pub focus: bool,
702
703 #[cfg_attr(target_os = "linux", allow(dead_code))]
704 pub show: bool,
705
706 pub display_id: Option<DisplayId>,
707
708 #[cfg_attr(target_os = "linux", allow(dead_code))]
709 pub window_min_size: Option<Size<Pixels>>,
710}
711
712/// Represents the status of how a window should be opened.
713#[derive(Debug, Copy, Clone, PartialEq)]
714pub enum WindowBounds {
715 /// Indicates that the window should open in a windowed state with the given bounds.
716 Windowed(Bounds<Pixels>),
717 /// Indicates that the window should open in a maximized state.
718 /// The bounds provided here represent the restore size of the window.
719 Maximized(Bounds<Pixels>),
720 /// Indicates that the window should open in fullscreen mode.
721 /// The bounds provided here represent the restore size of the window.
722 Fullscreen(Bounds<Pixels>),
723}
724
725impl Default for WindowBounds {
726 fn default() -> Self {
727 WindowBounds::Windowed(Bounds::default())
728 }
729}
730
731impl WindowBounds {
732 /// Retrieve the inner bounds
733 pub fn get_bounds(&self) -> Bounds<Pixels> {
734 match self {
735 WindowBounds::Windowed(bounds) => *bounds,
736 WindowBounds::Maximized(bounds) => *bounds,
737 WindowBounds::Fullscreen(bounds) => *bounds,
738 }
739 }
740}
741
742impl Default for WindowOptions {
743 fn default() -> Self {
744 Self {
745 window_bounds: None,
746 titlebar: Some(TitlebarOptions {
747 title: Default::default(),
748 appears_transparent: Default::default(),
749 traffic_light_position: Default::default(),
750 }),
751 focus: true,
752 show: true,
753 kind: WindowKind::Normal,
754 is_movable: true,
755 display_id: None,
756 window_background: WindowBackgroundAppearance::default(),
757 app_id: None,
758 window_min_size: None,
759 window_decorations: None,
760 }
761 }
762}
763
764/// The options that can be configured for a window's titlebar
765#[derive(Debug, Default)]
766pub struct TitlebarOptions {
767 /// The initial title of the window
768 pub title: Option<SharedString>,
769
770 /// Whether the titlebar should appear transparent (macOS only)
771 pub appears_transparent: bool,
772
773 /// The position of the macOS traffic light buttons
774 pub traffic_light_position: Option<Point<Pixels>>,
775}
776
777/// The kind of window to create
778#[derive(Copy, Clone, Debug, PartialEq, Eq)]
779pub enum WindowKind {
780 /// A normal application window
781 Normal,
782
783 /// A window that appears above all other windows, usually used for alerts or popups
784 /// use sparingly!
785 PopUp,
786}
787
788/// The appearance of the window, as defined by the operating system.
789///
790/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
791/// values.
792#[derive(Copy, Clone, Debug)]
793pub enum WindowAppearance {
794 /// A light appearance.
795 ///
796 /// On macOS, this corresponds to the `aqua` appearance.
797 Light,
798
799 /// A light appearance with vibrant colors.
800 ///
801 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
802 VibrantLight,
803
804 /// A dark appearance.
805 ///
806 /// On macOS, this corresponds to the `darkAqua` appearance.
807 Dark,
808
809 /// A dark appearance with vibrant colors.
810 ///
811 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
812 VibrantDark,
813}
814
815impl Default for WindowAppearance {
816 fn default() -> Self {
817 Self::Light
818 }
819}
820
821/// The appearance of the background of the window itself, when there is
822/// no content or the content is transparent.
823#[derive(Copy, Clone, Debug, Default, PartialEq)]
824pub enum WindowBackgroundAppearance {
825 /// Opaque.
826 ///
827 /// This lets the window manager know that content behind this
828 /// window does not need to be drawn.
829 ///
830 /// Actual color depends on the system and themes should define a fully
831 /// opaque background color instead.
832 #[default]
833 Opaque,
834 /// Plain alpha transparency.
835 Transparent,
836 /// Transparency, but the contents behind the window are blurred.
837 ///
838 /// Not always supported.
839 Blurred,
840}
841
842/// The options that can be configured for a file dialog prompt
843#[derive(Copy, Clone, Debug)]
844pub struct PathPromptOptions {
845 /// Should the prompt allow files to be selected?
846 pub files: bool,
847 /// Should the prompt allow directories to be selected?
848 pub directories: bool,
849 /// Should the prompt allow multiple files to be selected?
850 pub multiple: bool,
851}
852
853/// What kind of prompt styling to show
854#[derive(Copy, Clone, Debug, PartialEq)]
855pub enum PromptLevel {
856 /// A prompt that is shown when the user should be notified of something
857 Info,
858
859 /// A prompt that is shown when the user needs to be warned of a potential problem
860 Warning,
861
862 /// A prompt that is shown when a critical problem has occurred
863 Critical,
864}
865
866/// The style of the cursor (pointer)
867#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
868pub enum CursorStyle {
869 /// The default cursor
870 Arrow,
871
872 /// A text input cursor
873 /// corresponds to the CSS cursor value `text`
874 IBeam,
875
876 /// A crosshair cursor
877 /// corresponds to the CSS cursor value `crosshair`
878 Crosshair,
879
880 /// A closed hand cursor
881 /// corresponds to the CSS cursor value `grabbing`
882 ClosedHand,
883
884 /// An open hand cursor
885 /// corresponds to the CSS cursor value `grab`
886 OpenHand,
887
888 /// A pointing hand cursor
889 /// corresponds to the CSS cursor value `pointer`
890 PointingHand,
891
892 /// A resize left cursor
893 /// corresponds to the CSS cursor value `w-resize`
894 ResizeLeft,
895
896 /// A resize right cursor
897 /// corresponds to the CSS cursor value `e-resize`
898 ResizeRight,
899
900 /// A resize cursor to the left and right
901 /// corresponds to the CSS cursor value `ew-resize`
902 ResizeLeftRight,
903
904 /// A resize up cursor
905 /// corresponds to the CSS cursor value `n-resize`
906 ResizeUp,
907
908 /// A resize down cursor
909 /// corresponds to the CSS cursor value `s-resize`
910 ResizeDown,
911
912 /// A resize cursor directing up and down
913 /// corresponds to the CSS cursor value `ns-resize`
914 ResizeUpDown,
915
916 /// A resize cursor directing up-left and down-right
917 /// corresponds to the CSS cursor value `nesw-resize`
918 ResizeUpLeftDownRight,
919
920 /// A resize cursor directing up-right and down-left
921 /// corresponds to the CSS cursor value `nwse-resize`
922 ResizeUpRightDownLeft,
923
924 /// A cursor indicating that the item/column can be resized horizontally.
925 /// corresponds to the CSS curosr value `col-resize`
926 ResizeColumn,
927
928 /// A cursor indicating that the item/row can be resized vertically.
929 /// corresponds to the CSS curosr value `row-resize`
930 ResizeRow,
931
932 /// A text input cursor for vertical layout
933 /// corresponds to the CSS cursor value `vertical-text`
934 IBeamCursorForVerticalLayout,
935
936 /// A cursor indicating that the operation is not allowed
937 /// corresponds to the CSS cursor value `not-allowed`
938 OperationNotAllowed,
939
940 /// A cursor indicating that the operation will result in a link
941 /// corresponds to the CSS cursor value `alias`
942 DragLink,
943
944 /// A cursor indicating that the operation will result in a copy
945 /// corresponds to the CSS cursor value `copy`
946 DragCopy,
947
948 /// A cursor indicating that the operation will result in a context menu
949 /// corresponds to the CSS cursor value `context-menu`
950 ContextualMenu,
951}
952
953impl Default for CursorStyle {
954 fn default() -> Self {
955 Self::Arrow
956 }
957}
958
959/// A clipboard item that should be copied to the clipboard
960#[derive(Clone, Debug, Eq, PartialEq)]
961pub struct ClipboardItem {
962 pub(crate) text: String,
963 pub(crate) metadata: Option<String>,
964}
965
966impl ClipboardItem {
967 /// Create a new clipboard item with the given text
968 pub fn new(text: String) -> Self {
969 Self {
970 text,
971 metadata: None,
972 }
973 }
974
975 /// Create a new clipboard item with the given text and metadata
976 pub fn with_metadata<T: Serialize>(mut self, metadata: T) -> Self {
977 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
978 self
979 }
980
981 /// Get the text of the clipboard item
982 pub fn text(&self) -> &String {
983 &self.text
984 }
985
986 /// Get the metadata of the clipboard item
987 pub fn metadata<T>(&self) -> Option<T>
988 where
989 T: for<'a> Deserialize<'a>,
990 {
991 self.metadata
992 .as_ref()
993 .and_then(|m| serde_json::from_str(m).ok())
994 }
995
996 #[cfg_attr(target_os = "linux", allow(dead_code))]
997 pub(crate) fn text_hash(text: &str) -> u64 {
998 let mut hasher = SeaHasher::new();
999 text.hash(&mut hasher);
1000 hasher.finish()
1001 }
1002}