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