1// todo(windows): remove
2#![cfg_attr(windows, allow(dead_code))]
3
4mod app_menu;
5mod keystroke;
6
7#[cfg(target_os = "linux")]
8mod linux;
9
10#[cfg(target_os = "macos")]
11mod mac;
12
13#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-blade"))]
14mod blade;
15
16#[cfg(any(test, feature = "test-support"))]
17mod test;
18
19mod fps;
20#[cfg(target_os = "windows")]
21mod windows;
22
23use crate::{
24 point, Action, AnyWindowHandle, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds,
25 DevicePixels, DispatchEventResult, Font, FontId, FontMetrics, FontRun, ForegroundExecutor,
26 GPUSpecs, GlyphId, ImageSource, Keymap, LineLayout, Pixels, PlatformInput, Point,
27 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Scene, SharedString, Size,
28 SvgSize, Task, TaskLabel, WindowContext, DEFAULT_WINDOW_SIZE,
29};
30use anyhow::Result;
31use async_task::Runnable;
32use futures::channel::oneshot;
33use image::codecs::gif::GifDecoder;
34use image::{AnimationDecoder as _, Frame};
35use parking::Unparker;
36use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
37use seahash::SeaHasher;
38use serde::{Deserialize, Serialize};
39use smallvec::SmallVec;
40use std::borrow::Cow;
41use std::hash::{Hash, Hasher};
42use std::io::Cursor;
43use std::time::{Duration, Instant};
44use std::{
45 fmt::{self, Debug},
46 ops::Range,
47 path::{Path, PathBuf},
48 rc::Rc,
49 sync::Arc,
50};
51use strum::EnumIter;
52use uuid::Uuid;
53
54pub use app_menu::*;
55pub use fps::*;
56pub use keystroke::*;
57
58#[cfg(target_os = "linux")]
59pub(crate) use linux::*;
60#[cfg(target_os = "macos")]
61pub(crate) use mac::*;
62pub use semantic_version::SemanticVersion;
63#[cfg(any(test, feature = "test-support"))]
64pub(crate) use test::*;
65#[cfg(target_os = "windows")]
66pub(crate) use windows::*;
67
68#[cfg(target_os = "macos")]
69pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
70 Rc::new(MacPlatform::new(headless))
71}
72
73#[cfg(target_os = "linux")]
74pub(crate) fn current_platform(headless: bool) -> Rc<dyn Platform> {
75 if headless {
76 return Rc::new(HeadlessClient::new());
77 }
78
79 match guess_compositor() {
80 "Wayland" => Rc::new(WaylandClient::new()),
81 "X11" => Rc::new(X11Client::new()),
82 "Headless" => Rc::new(HeadlessClient::new()),
83 _ => unreachable!(),
84 }
85}
86
87/// Return which compositor we're guessing we'll use.
88/// Does not attempt to connect to the given compositor
89#[cfg(target_os = "linux")]
90#[inline]
91pub fn guess_compositor() -> &'static str {
92 if std::env::var_os("ZED_HEADLESS").is_some() {
93 return "Headless";
94 }
95 let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
96 let x11_display = std::env::var_os("DISPLAY");
97
98 let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
99 let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
100
101 if use_wayland {
102 "Wayland"
103 } else if use_x11 {
104 "X11"
105 } else {
106 "Headless"
107 }
108}
109
110#[cfg(target_os = "windows")]
111pub(crate) fn current_platform(_headless: bool) -> Rc<dyn Platform> {
112 Rc::new(WindowsPlatform::new())
113}
114
115pub(crate) trait Platform: 'static {
116 fn background_executor(&self) -> BackgroundExecutor;
117 fn foreground_executor(&self) -> ForegroundExecutor;
118 fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
119
120 fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
121 fn quit(&self);
122 fn restart(&self, binary_path: Option<PathBuf>);
123 fn activate(&self, ignoring_other_apps: bool);
124 fn hide(&self);
125 fn hide_other_apps(&self);
126 fn unhide_other_apps(&self);
127
128 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
129 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
130 fn active_window(&self) -> Option<AnyWindowHandle>;
131 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
132 None
133 }
134
135 fn open_window(
136 &self,
137 handle: AnyWindowHandle,
138 options: WindowParams,
139 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
140
141 /// Returns the appearance of the application's windows.
142 fn window_appearance(&self) -> WindowAppearance;
143
144 fn open_url(&self, url: &str);
145 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>);
146 fn register_url_scheme(&self, url: &str) -> Task<Result<()>>;
147
148 fn prompt_for_paths(
149 &self,
150 options: PathPromptOptions,
151 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>>;
152 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>>;
153 fn reveal_path(&self, path: &Path);
154
155 fn on_quit(&self, callback: Box<dyn FnMut()>);
156 fn on_reopen(&self, callback: Box<dyn FnMut()>);
157
158 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap);
159 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
160 None
161 }
162
163 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap);
164 fn add_recent_document(&self, _path: &Path) {}
165 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>);
166 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>);
167 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>);
168
169 fn compositor_name(&self) -> &'static str {
170 ""
171 }
172 fn app_path(&self) -> Result<PathBuf>;
173 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
174
175 fn set_cursor_style(&self, style: CursorStyle);
176 fn should_auto_hide_scrollbars(&self) -> bool;
177
178 #[cfg(target_os = "linux")]
179 fn write_to_primary(&self, item: ClipboardItem);
180 fn write_to_clipboard(&self, item: ClipboardItem);
181 #[cfg(target_os = "linux")]
182 fn read_from_primary(&self) -> Option<ClipboardItem>;
183 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
184
185 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;
186 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;
187 fn delete_credentials(&self, url: &str) -> Task<Result<()>>;
188}
189
190/// A handle to a platform's display, e.g. a monitor or laptop screen.
191pub trait PlatformDisplay: Send + Sync + Debug {
192 /// Get the ID for this display
193 fn id(&self) -> DisplayId;
194
195 /// Returns a stable identifier for this display that can be persisted and used
196 /// across system restarts.
197 fn uuid(&self) -> Result<Uuid>;
198
199 /// Get the bounds for this display
200 fn bounds(&self) -> Bounds<Pixels>;
201
202 /// Get the default bounds for this display to place a window
203 fn default_bounds(&self) -> Bounds<Pixels> {
204 let center = self.bounds().center();
205 let offset = DEFAULT_WINDOW_SIZE / 2.0;
206 let origin = point(center.x - offset.width, center.y - offset.height);
207 Bounds::new(origin, DEFAULT_WINDOW_SIZE)
208 }
209}
210
211/// An opaque identifier for a hardware display
212#[derive(PartialEq, Eq, Hash, Copy, Clone)]
213pub struct DisplayId(pub(crate) u32);
214
215impl Debug for DisplayId {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 write!(f, "DisplayId({})", self.0)
218 }
219}
220
221unsafe impl Send for DisplayId {}
222
223/// Which part of the window to resize
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum ResizeEdge {
226 /// The top edge
227 Top,
228 /// The top right corner
229 TopRight,
230 /// The right edge
231 Right,
232 /// The bottom right corner
233 BottomRight,
234 /// The bottom edge
235 Bottom,
236 /// The bottom left corner
237 BottomLeft,
238 /// The left edge
239 Left,
240 /// The top left corner
241 TopLeft,
242}
243
244/// A type to describe the appearance of a window
245#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
246pub enum WindowDecorations {
247 #[default]
248 /// Server side decorations
249 Server,
250 /// Client side decorations
251 Client,
252}
253
254/// A type to describe how this window is currently configured
255#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
256pub enum Decorations {
257 /// The window is configured to use server side decorations
258 #[default]
259 Server,
260 /// The window is configured to use client side decorations
261 Client {
262 /// The edge tiling state
263 tiling: Tiling,
264 },
265}
266
267/// What window controls this platform supports
268#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
269pub struct WindowControls {
270 /// Whether this platform supports fullscreen
271 pub fullscreen: bool,
272 /// Whether this platform supports maximize
273 pub maximize: bool,
274 /// Whether this platform supports minimize
275 pub minimize: bool,
276 /// Whether this platform supports a window menu
277 pub window_menu: bool,
278}
279
280impl Default for WindowControls {
281 fn default() -> Self {
282 // Assume that we can do anything, unless told otherwise
283 Self {
284 fullscreen: true,
285 maximize: true,
286 minimize: true,
287 window_menu: true,
288 }
289 }
290}
291
292/// A type to describe which sides of the window are currently tiled in some way
293#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Default)]
294pub struct Tiling {
295 /// Whether the top edge is tiled
296 pub top: bool,
297 /// Whether the left edge is tiled
298 pub left: bool,
299 /// Whether the right edge is tiled
300 pub right: bool,
301 /// Whether the bottom edge is tiled
302 pub bottom: bool,
303}
304
305impl Tiling {
306 /// Initializes a [`Tiling`] type with all sides tiled
307 pub fn tiled() -> Self {
308 Self {
309 top: true,
310 left: true,
311 right: true,
312 bottom: true,
313 }
314 }
315
316 /// Whether any edge is tiled
317 pub fn is_tiled(&self) -> bool {
318 self.top || self.left || self.right || self.bottom
319 }
320}
321
322pub(crate) trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
323 fn bounds(&self) -> Bounds<Pixels>;
324 fn is_maximized(&self) -> bool;
325 fn window_bounds(&self) -> WindowBounds;
326 fn content_size(&self) -> Size<Pixels>;
327 fn scale_factor(&self) -> f32;
328 fn appearance(&self) -> WindowAppearance;
329 fn display(&self) -> Option<Rc<dyn PlatformDisplay>>;
330 fn mouse_position(&self) -> Point<Pixels>;
331 fn modifiers(&self) -> Modifiers;
332 fn set_input_handler(&mut self, input_handler: PlatformInputHandler);
333 fn take_input_handler(&mut self) -> Option<PlatformInputHandler>;
334 fn prompt(
335 &self,
336 level: PromptLevel,
337 msg: &str,
338 detail: Option<&str>,
339 answers: &[&str],
340 ) -> Option<oneshot::Receiver<usize>>;
341 fn activate(&self);
342 fn is_active(&self) -> bool;
343 fn is_hovered(&self) -> bool;
344 fn set_title(&mut self, title: &str);
345 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance);
346 fn minimize(&self);
347 fn zoom(&self);
348 fn toggle_fullscreen(&self);
349 fn is_fullscreen(&self) -> bool;
350 fn on_request_frame(&self, callback: Box<dyn FnMut()>);
351 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>);
352 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>);
353 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>);
354 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>);
355 fn on_moved(&self, callback: Box<dyn FnMut()>);
356 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
357 fn on_close(&self, callback: Box<dyn FnOnce()>);
358 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
359 fn draw(&self, scene: &Scene, on_complete: Option<oneshot::Sender<()>>);
360 fn completed_frame(&self) {}
361 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas>;
362
363 // macOS specific methods
364 fn set_edited(&mut self, _edited: bool) {}
365 fn show_character_palette(&self) {}
366
367 #[cfg(target_os = "windows")]
368 fn get_raw_handle(&self) -> windows::HWND;
369
370 // Linux specific methods
371 fn request_decorations(&self, _decorations: WindowDecorations) {}
372 fn show_window_menu(&self, _position: Point<Pixels>) {}
373 fn start_window_move(&self) {}
374 fn start_window_resize(&self, _edge: ResizeEdge) {}
375 fn window_decorations(&self) -> Decorations {
376 Decorations::Server
377 }
378 fn set_app_id(&mut self, _app_id: &str) {}
379 fn window_controls(&self) -> WindowControls {
380 WindowControls::default()
381 }
382 fn set_client_inset(&self, _inset: Pixels) {}
383 fn gpu_specs(&self) -> Option<GPUSpecs>;
384 fn fps(&self) -> Option<f32>;
385
386 #[cfg(any(test, feature = "test-support"))]
387 fn as_test(&mut self) -> Option<&mut TestWindow> {
388 None
389 }
390}
391
392/// This type is public so that our test macro can generate and use it, but it should not
393/// be considered part of our public API.
394#[doc(hidden)]
395pub trait PlatformDispatcher: Send + Sync {
396 fn is_main_thread(&self) -> bool;
397 fn dispatch(&self, runnable: Runnable, label: Option<TaskLabel>);
398 fn dispatch_on_main_thread(&self, runnable: Runnable);
399 fn dispatch_after(&self, duration: Duration, runnable: Runnable);
400 fn park(&self, timeout: Option<Duration>) -> bool;
401 fn unparker(&self) -> Unparker;
402 fn now(&self) -> Instant {
403 Instant::now()
404 }
405
406 #[cfg(any(test, feature = "test-support"))]
407 fn as_test(&self) -> Option<&TestDispatcher> {
408 None
409 }
410}
411
412pub(crate) trait PlatformTextSystem: Send + Sync {
413 fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()>;
414 fn all_font_names(&self) -> Vec<String>;
415 fn font_id(&self, descriptor: &Font) -> Result<FontId>;
416 fn font_metrics(&self, font_id: FontId) -> FontMetrics;
417 fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>>;
418 fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
419 fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
420 fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
421 fn rasterize_glyph(
422 &self,
423 params: &RenderGlyphParams,
424 raster_bounds: Bounds<DevicePixels>,
425 ) -> Result<(Size<DevicePixels>, Vec<u8>)>;
426 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
427}
428
429#[derive(PartialEq, Eq, Hash, Clone)]
430pub(crate) enum AtlasKey {
431 Glyph(RenderGlyphParams),
432 Svg(RenderSvgParams),
433 Image(RenderImageParams),
434}
435
436impl AtlasKey {
437 pub(crate) fn texture_kind(&self) -> AtlasTextureKind {
438 match self {
439 AtlasKey::Glyph(params) => {
440 if params.is_emoji {
441 AtlasTextureKind::Polychrome
442 } else {
443 AtlasTextureKind::Monochrome
444 }
445 }
446 AtlasKey::Svg(_) => AtlasTextureKind::Monochrome,
447 AtlasKey::Image(_) => AtlasTextureKind::Polychrome,
448 }
449 }
450}
451
452impl From<RenderGlyphParams> for AtlasKey {
453 fn from(params: RenderGlyphParams) -> Self {
454 Self::Glyph(params)
455 }
456}
457
458impl From<RenderSvgParams> for AtlasKey {
459 fn from(params: RenderSvgParams) -> Self {
460 Self::Svg(params)
461 }
462}
463
464impl From<RenderImageParams> for AtlasKey {
465 fn from(params: RenderImageParams) -> Self {
466 Self::Image(params)
467 }
468}
469
470pub(crate) trait PlatformAtlas: Send + Sync {
471 fn get_or_insert_with<'a>(
472 &self,
473 key: &AtlasKey,
474 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
475 ) -> Result<Option<AtlasTile>>;
476}
477
478#[derive(Clone, Debug, PartialEq, Eq)]
479#[repr(C)]
480pub(crate) struct AtlasTile {
481 pub(crate) texture_id: AtlasTextureId,
482 pub(crate) tile_id: TileId,
483 pub(crate) padding: u32,
484 pub(crate) bounds: Bounds<DevicePixels>,
485}
486
487#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
488#[repr(C)]
489pub(crate) struct AtlasTextureId {
490 // We use u32 instead of usize for Metal Shader Language compatibility
491 pub(crate) index: u32,
492 pub(crate) kind: AtlasTextureKind,
493}
494
495#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
496#[repr(C)]
497pub(crate) enum AtlasTextureKind {
498 Monochrome = 0,
499 Polychrome = 1,
500 Path = 2,
501}
502
503#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
504#[repr(C)]
505pub(crate) struct TileId(pub(crate) u32);
506
507impl From<etagere::AllocId> for TileId {
508 fn from(id: etagere::AllocId) -> Self {
509 Self(id.serialize())
510 }
511}
512
513impl From<TileId> for etagere::AllocId {
514 fn from(id: TileId) -> Self {
515 Self::deserialize(id.0)
516 }
517}
518
519pub(crate) struct PlatformInputHandler {
520 cx: AsyncWindowContext,
521 handler: Box<dyn InputHandler>,
522}
523
524impl PlatformInputHandler {
525 pub fn new(cx: AsyncWindowContext, handler: Box<dyn InputHandler>) -> Self {
526 Self { cx, handler }
527 }
528
529 fn selected_text_range(&mut self) -> Option<Range<usize>> {
530 self.cx
531 .update(|cx| self.handler.selected_text_range(cx))
532 .ok()
533 .flatten()
534 }
535
536 fn marked_text_range(&mut self) -> Option<Range<usize>> {
537 self.cx
538 .update(|cx| self.handler.marked_text_range(cx))
539 .ok()
540 .flatten()
541 }
542
543 #[cfg_attr(target_os = "linux", allow(dead_code))]
544 fn text_for_range(&mut self, range_utf16: Range<usize>) -> Option<String> {
545 self.cx
546 .update(|cx| self.handler.text_for_range(range_utf16, cx))
547 .ok()
548 .flatten()
549 }
550
551 fn replace_text_in_range(&mut self, replacement_range: Option<Range<usize>>, text: &str) {
552 self.cx
553 .update(|cx| {
554 self.handler
555 .replace_text_in_range(replacement_range, text, cx);
556 })
557 .ok();
558 }
559
560 fn replace_and_mark_text_in_range(
561 &mut self,
562 range_utf16: Option<Range<usize>>,
563 new_text: &str,
564 new_selected_range: Option<Range<usize>>,
565 ) {
566 self.cx
567 .update(|cx| {
568 self.handler.replace_and_mark_text_in_range(
569 range_utf16,
570 new_text,
571 new_selected_range,
572 cx,
573 )
574 })
575 .ok();
576 }
577
578 fn unmark_text(&mut self) {
579 self.cx.update(|cx| self.handler.unmark_text(cx)).ok();
580 }
581
582 fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<Pixels>> {
583 self.cx
584 .update(|cx| self.handler.bounds_for_range(range_utf16, cx))
585 .ok()
586 .flatten()
587 }
588
589 pub(crate) fn dispatch_input(&mut self, input: &str, cx: &mut WindowContext) {
590 self.handler.replace_text_in_range(None, input, cx);
591 }
592}
593
594/// Zed's interface for handling text input from the platform's IME system
595/// This is currently a 1:1 exposure of the NSTextInputClient API:
596///
597/// <https://developer.apple.com/documentation/appkit/nstextinputclient>
598pub trait InputHandler: 'static {
599 /// Get the range of the user's currently selected text, if any
600 /// Corresponds to [selectedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438242-selectedrange)
601 ///
602 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
603 fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
604
605 /// Get the range of the currently marked text, if any
606 /// Corresponds to [markedRange()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438250-markedrange)
607 ///
608 /// Return value is in terms of UTF-16 characters, from 0 to the length of the document
609 fn marked_text_range(&mut self, cx: &mut WindowContext) -> Option<Range<usize>>;
610
611 /// Get the text for the given document range in UTF-16 characters
612 /// Corresponds to [attributedSubstring(forProposedRange: actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438238-attributedsubstring)
613 ///
614 /// range_utf16 is in terms of UTF-16 characters
615 fn text_for_range(
616 &mut self,
617 range_utf16: Range<usize>,
618 cx: &mut WindowContext,
619 ) -> Option<String>;
620
621 /// Replace the text in the given document range with the given text
622 /// Corresponds to [insertText(_:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438258-inserttext)
623 ///
624 /// replacement_range is in terms of UTF-16 characters
625 fn replace_text_in_range(
626 &mut self,
627 replacement_range: Option<Range<usize>>,
628 text: &str,
629 cx: &mut WindowContext,
630 );
631
632 /// Replace the text in the given document range with the given text,
633 /// and mark the given text as part of an IME 'composing' state
634 /// Corresponds to [setMarkedText(_:selectedRange:replacementRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438246-setmarkedtext)
635 ///
636 /// range_utf16 is in terms of UTF-16 characters
637 /// new_selected_range is in terms of UTF-16 characters
638 fn replace_and_mark_text_in_range(
639 &mut self,
640 range_utf16: Option<Range<usize>>,
641 new_text: &str,
642 new_selected_range: Option<Range<usize>>,
643 cx: &mut WindowContext,
644 );
645
646 /// Remove the IME 'composing' state from the document
647 /// Corresponds to [unmarkText()](https://developer.apple.com/documentation/appkit/nstextinputclient/1438239-unmarktext)
648 fn unmark_text(&mut self, cx: &mut WindowContext);
649
650 /// Get the bounds of the given document range in screen coordinates
651 /// Corresponds to [firstRect(forCharacterRange:actualRange:)](https://developer.apple.com/documentation/appkit/nstextinputclient/1438240-firstrect)
652 ///
653 /// This is used for positioning the IME candidate window
654 fn bounds_for_range(
655 &mut self,
656 range_utf16: Range<usize>,
657 cx: &mut WindowContext,
658 ) -> Option<Bounds<Pixels>>;
659}
660
661/// The variables that can be configured when creating a new window
662#[derive(Debug)]
663pub struct WindowOptions {
664 /// Specifies the state and bounds of the window in screen coordinates.
665 /// - `None`: Inherit the bounds.
666 /// - `Some(WindowBounds)`: Open a window with corresponding state and its restore size.
667 pub window_bounds: Option<WindowBounds>,
668
669 /// The titlebar configuration of the window
670 pub titlebar: Option<TitlebarOptions>,
671
672 /// Whether the window should be focused when created
673 pub focus: bool,
674
675 /// Whether the window should be shown when created
676 pub show: bool,
677
678 /// The kind of window to create
679 pub kind: WindowKind,
680
681 /// Whether the window should be movable by the user
682 pub is_movable: bool,
683
684 /// The display to create the window on, if this is None,
685 /// the window will be created on the main display
686 pub display_id: Option<DisplayId>,
687
688 /// The appearance of the window background.
689 pub window_background: WindowBackgroundAppearance,
690
691 /// Application identifier of the window. Can by used by desktop environments to group applications together.
692 pub app_id: Option<String>,
693
694 /// Window minimum size
695 pub window_min_size: Option<Size<Pixels>>,
696
697 /// Whether to use client or server side decorations. Wayland only
698 /// Note that this may be ignored.
699 pub window_decorations: Option<WindowDecorations>,
700}
701
702/// The variables that can be configured when creating a new window
703#[derive(Debug)]
704pub(crate) struct WindowParams {
705 pub bounds: Bounds<Pixels>,
706
707 /// The titlebar configuration of the window
708 pub titlebar: Option<TitlebarOptions>,
709
710 /// The kind of window to create
711 #[cfg_attr(target_os = "linux", allow(dead_code))]
712 pub kind: WindowKind,
713
714 /// Whether the window should be movable by the user
715 #[cfg_attr(target_os = "linux", allow(dead_code))]
716 pub is_movable: bool,
717
718 #[cfg_attr(target_os = "linux", allow(dead_code))]
719 pub focus: bool,
720
721 #[cfg_attr(target_os = "linux", allow(dead_code))]
722 pub show: bool,
723
724 pub display_id: Option<DisplayId>,
725
726 pub window_min_size: Option<Size<Pixels>>,
727}
728
729/// Represents the status of how a window should be opened.
730#[derive(Debug, Copy, Clone, PartialEq)]
731pub enum WindowBounds {
732 /// Indicates that the window should open in a windowed state with the given bounds.
733 Windowed(Bounds<Pixels>),
734 /// Indicates that the window should open in a maximized state.
735 /// The bounds provided here represent the restore size of the window.
736 Maximized(Bounds<Pixels>),
737 /// Indicates that the window should open in fullscreen mode.
738 /// The bounds provided here represent the restore size of the window.
739 Fullscreen(Bounds<Pixels>),
740}
741
742impl Default for WindowBounds {
743 fn default() -> Self {
744 WindowBounds::Windowed(Bounds::default())
745 }
746}
747
748impl WindowBounds {
749 /// Retrieve the inner bounds
750 pub fn get_bounds(&self) -> Bounds<Pixels> {
751 match self {
752 WindowBounds::Windowed(bounds) => *bounds,
753 WindowBounds::Maximized(bounds) => *bounds,
754 WindowBounds::Fullscreen(bounds) => *bounds,
755 }
756 }
757}
758
759impl Default for WindowOptions {
760 fn default() -> Self {
761 Self {
762 window_bounds: None,
763 titlebar: Some(TitlebarOptions {
764 title: Default::default(),
765 appears_transparent: Default::default(),
766 traffic_light_position: Default::default(),
767 }),
768 focus: true,
769 show: true,
770 kind: WindowKind::Normal,
771 is_movable: true,
772 display_id: None,
773 window_background: WindowBackgroundAppearance::default(),
774 app_id: None,
775 window_min_size: None,
776 window_decorations: None,
777 }
778 }
779}
780
781/// The options that can be configured for a window's titlebar
782#[derive(Debug, Default)]
783pub struct TitlebarOptions {
784 /// The initial title of the window
785 pub title: Option<SharedString>,
786
787 /// Whether the titlebar should appear transparent (macOS only)
788 pub appears_transparent: bool,
789
790 /// The position of the macOS traffic light buttons
791 pub traffic_light_position: Option<Point<Pixels>>,
792}
793
794/// The kind of window to create
795#[derive(Copy, Clone, Debug, PartialEq, Eq)]
796pub enum WindowKind {
797 /// A normal application window
798 Normal,
799
800 /// A window that appears above all other windows, usually used for alerts or popups
801 /// use sparingly!
802 PopUp,
803}
804
805/// The appearance of the window, as defined by the operating system.
806///
807/// On macOS, this corresponds to named [`NSAppearance`](https://developer.apple.com/documentation/appkit/nsappearance)
808/// values.
809#[derive(Copy, Clone, Debug)]
810pub enum WindowAppearance {
811 /// A light appearance.
812 ///
813 /// On macOS, this corresponds to the `aqua` appearance.
814 Light,
815
816 /// A light appearance with vibrant colors.
817 ///
818 /// On macOS, this corresponds to the `NSAppearanceNameVibrantLight` appearance.
819 VibrantLight,
820
821 /// A dark appearance.
822 ///
823 /// On macOS, this corresponds to the `darkAqua` appearance.
824 Dark,
825
826 /// A dark appearance with vibrant colors.
827 ///
828 /// On macOS, this corresponds to the `NSAppearanceNameVibrantDark` appearance.
829 VibrantDark,
830}
831
832impl Default for WindowAppearance {
833 fn default() -> Self {
834 Self::Light
835 }
836}
837
838/// The appearance of the background of the window itself, when there is
839/// no content or the content is transparent.
840#[derive(Copy, Clone, Debug, Default, PartialEq)]
841pub enum WindowBackgroundAppearance {
842 /// Opaque.
843 ///
844 /// This lets the window manager know that content behind this
845 /// window does not need to be drawn.
846 ///
847 /// Actual color depends on the system and themes should define a fully
848 /// opaque background color instead.
849 #[default]
850 Opaque,
851 /// Plain alpha transparency.
852 Transparent,
853 /// Transparency, but the contents behind the window are blurred.
854 ///
855 /// Not always supported.
856 Blurred,
857}
858
859/// The options that can be configured for a file dialog prompt
860#[derive(Copy, Clone, Debug)]
861pub struct PathPromptOptions {
862 /// Should the prompt allow files to be selected?
863 pub files: bool,
864 /// Should the prompt allow directories to be selected?
865 pub directories: bool,
866 /// Should the prompt allow multiple files to be selected?
867 pub multiple: bool,
868}
869
870/// What kind of prompt styling to show
871#[derive(Copy, Clone, Debug, PartialEq)]
872pub enum PromptLevel {
873 /// A prompt that is shown when the user should be notified of something
874 Info,
875
876 /// A prompt that is shown when the user needs to be warned of a potential problem
877 Warning,
878
879 /// A prompt that is shown when a critical problem has occurred
880 Critical,
881}
882
883/// The style of the cursor (pointer)
884#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
885pub enum CursorStyle {
886 /// The default cursor
887 Arrow,
888
889 /// A text input cursor
890 /// corresponds to the CSS cursor value `text`
891 IBeam,
892
893 /// A crosshair cursor
894 /// corresponds to the CSS cursor value `crosshair`
895 Crosshair,
896
897 /// A closed hand cursor
898 /// corresponds to the CSS cursor value `grabbing`
899 ClosedHand,
900
901 /// An open hand cursor
902 /// corresponds to the CSS cursor value `grab`
903 OpenHand,
904
905 /// A pointing hand cursor
906 /// corresponds to the CSS cursor value `pointer`
907 PointingHand,
908
909 /// A resize left cursor
910 /// corresponds to the CSS cursor value `w-resize`
911 ResizeLeft,
912
913 /// A resize right cursor
914 /// corresponds to the CSS cursor value `e-resize`
915 ResizeRight,
916
917 /// A resize cursor to the left and right
918 /// corresponds to the CSS cursor value `ew-resize`
919 ResizeLeftRight,
920
921 /// A resize up cursor
922 /// corresponds to the CSS cursor value `n-resize`
923 ResizeUp,
924
925 /// A resize down cursor
926 /// corresponds to the CSS cursor value `s-resize`
927 ResizeDown,
928
929 /// A resize cursor directing up and down
930 /// corresponds to the CSS cursor value `ns-resize`
931 ResizeUpDown,
932
933 /// A resize cursor directing up-left and down-right
934 /// corresponds to the CSS cursor value `nesw-resize`
935 ResizeUpLeftDownRight,
936
937 /// A resize cursor directing up-right and down-left
938 /// corresponds to the CSS cursor value `nwse-resize`
939 ResizeUpRightDownLeft,
940
941 /// A cursor indicating that the item/column can be resized horizontally.
942 /// corresponds to the CSS cursor value `col-resize`
943 ResizeColumn,
944
945 /// A cursor indicating that the item/row can be resized vertically.
946 /// corresponds to the CSS cursor value `row-resize`
947 ResizeRow,
948
949 /// A text input cursor for vertical layout
950 /// corresponds to the CSS cursor value `vertical-text`
951 IBeamCursorForVerticalLayout,
952
953 /// A cursor indicating that the operation is not allowed
954 /// corresponds to the CSS cursor value `not-allowed`
955 OperationNotAllowed,
956
957 /// A cursor indicating that the operation will result in a link
958 /// corresponds to the CSS cursor value `alias`
959 DragLink,
960
961 /// A cursor indicating that the operation will result in a copy
962 /// corresponds to the CSS cursor value `copy`
963 DragCopy,
964
965 /// A cursor indicating that the operation will result in a context menu
966 /// corresponds to the CSS cursor value `context-menu`
967 ContextualMenu,
968}
969
970impl Default for CursorStyle {
971 fn default() -> Self {
972 Self::Arrow
973 }
974}
975
976/// A clipboard item that should be copied to the clipboard
977#[derive(Clone, Debug, Eq, PartialEq)]
978pub struct ClipboardItem {
979 entries: Vec<ClipboardEntry>,
980}
981
982/// Either a ClipboardString or a ClipboardImage
983#[derive(Clone, Debug, Eq, PartialEq)]
984pub enum ClipboardEntry {
985 /// A string entry
986 String(ClipboardString),
987 /// An image entry
988 Image(Image),
989}
990
991impl ClipboardItem {
992 /// Create a new ClipboardItem::String with no associated metadata
993 pub fn new_string(text: String) -> Self {
994 Self {
995 entries: vec![ClipboardEntry::String(ClipboardString::new(text))],
996 }
997 }
998
999 /// Create a new ClipboardItem::String with the given text and associated metadata
1000 pub fn new_string_with_metadata(text: String, metadata: String) -> Self {
1001 Self {
1002 entries: vec![ClipboardEntry::String(ClipboardString {
1003 text,
1004 metadata: Some(metadata),
1005 })],
1006 }
1007 }
1008
1009 /// Create a new ClipboardItem::String with the given text and associated metadata
1010 pub fn new_string_with_json_metadata<T: Serialize>(text: String, metadata: T) -> Self {
1011 Self {
1012 entries: vec![ClipboardEntry::String(
1013 ClipboardString::new(text).with_json_metadata(metadata),
1014 )],
1015 }
1016 }
1017
1018 /// Create a new ClipboardItem::Image with the given image with no associated metadata
1019 pub fn new_image(image: &Image) -> Self {
1020 Self {
1021 entries: vec![ClipboardEntry::Image(image.clone())],
1022 }
1023 }
1024
1025 /// Concatenates together all the ClipboardString entries in the item.
1026 /// Returns None if there were no ClipboardString entries.
1027 pub fn text(&self) -> Option<String> {
1028 let mut answer = String::new();
1029 let mut any_entries = false;
1030
1031 for entry in self.entries.iter() {
1032 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry {
1033 answer.push_str(text);
1034 any_entries = true;
1035 }
1036 }
1037
1038 if any_entries {
1039 Some(answer)
1040 } else {
1041 None
1042 }
1043 }
1044
1045 /// If this item is one ClipboardEntry::String, returns its metadata.
1046 #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
1047 pub fn metadata(&self) -> Option<&String> {
1048 match self.entries().first() {
1049 Some(ClipboardEntry::String(clipboard_string)) if self.entries.len() == 1 => {
1050 clipboard_string.metadata.as_ref()
1051 }
1052 _ => None,
1053 }
1054 }
1055
1056 /// Get the item's entries
1057 pub fn entries(&self) -> &[ClipboardEntry] {
1058 &self.entries
1059 }
1060
1061 /// Get owned versions of the item's entries
1062 pub fn into_entries(self) -> impl Iterator<Item = ClipboardEntry> {
1063 self.entries.into_iter()
1064 }
1065}
1066
1067/// One of the editor's supported image formats (e.g. PNG, JPEG) - used when dealing with images in the clipboard
1068#[derive(Clone, Copy, Debug, Eq, PartialEq, EnumIter, Hash)]
1069pub enum ImageFormat {
1070 // Sorted from most to least likely to be pasted into an editor,
1071 // which matters when we iterate through them trying to see if
1072 // clipboard content matches them.
1073 /// .png
1074 Png,
1075 /// .jpeg or .jpg
1076 Jpeg,
1077 /// .webp
1078 Webp,
1079 /// .gif
1080 Gif,
1081 /// .svg
1082 Svg,
1083 /// .bmp
1084 Bmp,
1085 /// .tif or .tiff
1086 Tiff,
1087}
1088
1089/// An image, with a format and certain bytes
1090#[derive(Clone, Debug, PartialEq, Eq)]
1091pub struct Image {
1092 /// The image format the bytes represent (e.g. PNG)
1093 pub format: ImageFormat,
1094 /// The raw image bytes
1095 pub bytes: Vec<u8>,
1096 /// The unique ID for the image
1097 pub id: u64,
1098}
1099
1100impl Hash for Image {
1101 fn hash<H: Hasher>(&self, state: &mut H) {
1102 state.write_u64(self.id);
1103 }
1104}
1105
1106impl Image {
1107 /// Get this image's ID
1108 pub fn id(&self) -> u64 {
1109 self.id
1110 }
1111
1112 /// Use the GPUI `use_asset` API to make this image renderable
1113 pub fn use_render_image(self: Arc<Self>, cx: &mut WindowContext) -> Option<Arc<RenderImage>> {
1114 ImageSource::Image(self).use_data(cx)
1115 }
1116
1117 /// Convert the clipboard image to an `ImageData` object.
1118 pub fn to_image_data(&self, cx: &AppContext) -> Result<Arc<RenderImage>> {
1119 fn frames_for_image(
1120 bytes: &[u8],
1121 format: image::ImageFormat,
1122 ) -> Result<SmallVec<[Frame; 1]>> {
1123 let mut data = image::load_from_memory_with_format(bytes, format)?.into_rgba8();
1124
1125 // Convert from RGBA to BGRA.
1126 for pixel in data.chunks_exact_mut(4) {
1127 pixel.swap(0, 2);
1128 }
1129
1130 Ok(SmallVec::from_elem(Frame::new(data), 1))
1131 }
1132
1133 let frames = match self.format {
1134 ImageFormat::Gif => {
1135 let decoder = GifDecoder::new(Cursor::new(&self.bytes))?;
1136 let mut frames = SmallVec::new();
1137
1138 for frame in decoder.into_frames() {
1139 let mut frame = frame?;
1140 // Convert from RGBA to BGRA.
1141 for pixel in frame.buffer_mut().chunks_exact_mut(4) {
1142 pixel.swap(0, 2);
1143 }
1144 frames.push(frame);
1145 }
1146
1147 frames
1148 }
1149 ImageFormat::Png => frames_for_image(&self.bytes, image::ImageFormat::Png)?,
1150 ImageFormat::Jpeg => frames_for_image(&self.bytes, image::ImageFormat::Jpeg)?,
1151 ImageFormat::Webp => frames_for_image(&self.bytes, image::ImageFormat::WebP)?,
1152 ImageFormat::Bmp => frames_for_image(&self.bytes, image::ImageFormat::Bmp)?,
1153 ImageFormat::Tiff => frames_for_image(&self.bytes, image::ImageFormat::Tiff)?,
1154 ImageFormat::Svg => {
1155 // TODO: Fix this
1156 let pixmap = cx
1157 .svg_renderer()
1158 .render_pixmap(&self.bytes, SvgSize::ScaleFactor(1.0))?;
1159
1160 let buffer =
1161 image::ImageBuffer::from_raw(pixmap.width(), pixmap.height(), pixmap.take())
1162 .unwrap();
1163
1164 SmallVec::from_elem(Frame::new(buffer), 1)
1165 }
1166 };
1167
1168 Ok(Arc::new(RenderImage::new(frames)))
1169 }
1170
1171 /// Get the format of the clipboard image
1172 pub fn format(&self) -> ImageFormat {
1173 self.format
1174 }
1175
1176 /// Get the raw bytes of the clipboard image
1177 pub fn bytes(&self) -> &[u8] {
1178 self.bytes.as_slice()
1179 }
1180}
1181
1182/// A clipboard item that should be copied to the clipboard
1183#[derive(Clone, Debug, Eq, PartialEq)]
1184pub struct ClipboardString {
1185 pub(crate) text: String,
1186 pub(crate) metadata: Option<String>,
1187}
1188
1189impl ClipboardString {
1190 /// Create a new clipboard string with the given text
1191 pub fn new(text: String) -> Self {
1192 Self {
1193 text,
1194 metadata: None,
1195 }
1196 }
1197
1198 /// Return a new clipboard item with the metadata replaced by the given metadata,
1199 /// after serializing it as JSON.
1200 pub fn with_json_metadata<T: Serialize>(mut self, metadata: T) -> Self {
1201 self.metadata = Some(serde_json::to_string(&metadata).unwrap());
1202 self
1203 }
1204
1205 /// Get the text of the clipboard string
1206 pub fn text(&self) -> &String {
1207 &self.text
1208 }
1209
1210 /// Get the owned text of the clipboard string
1211 pub fn into_text(self) -> String {
1212 self.text
1213 }
1214
1215 /// Get the metadata of the clipboard string, formatted as JSON
1216 pub fn metadata_json<T>(&self) -> Option<T>
1217 where
1218 T: for<'a> Deserialize<'a>,
1219 {
1220 self.metadata
1221 .as_ref()
1222 .and_then(|m| serde_json::from_str(m).ok())
1223 }
1224
1225 #[cfg_attr(target_os = "linux", allow(dead_code))]
1226 pub(crate) fn text_hash(text: &str) -> u64 {
1227 let mut hasher = SeaHasher::new();
1228 text.hash(&mut hasher);
1229 hasher.finish()
1230 }
1231}