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