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