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