1#![allow(unused)]
2
3use std::any::{type_name, Any};
4use std::cell::{self, RefCell};
5use std::env;
6use std::fs::File;
7use std::io::Read;
8use std::ops::{Deref, DerefMut};
9use std::os::fd::{AsRawFd, FromRawFd};
10use std::panic::Location;
11use std::{
12 path::{Path, PathBuf},
13 process::Command,
14 rc::Rc,
15 sync::Arc,
16 time::Duration,
17};
18
19use anyhow::anyhow;
20use ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
21use async_task::Runnable;
22use calloop::channel::Channel;
23use calloop::{EventLoop, LoopHandle, LoopSignal};
24use copypasta::ClipboardProvider;
25use filedescriptor::FileDescriptor;
26use flume::{Receiver, Sender};
27use futures::channel::oneshot;
28use parking_lot::Mutex;
29use time::UtcOffset;
30use wayland_client::Connection;
31use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
32use xkbcommon::xkb::{self, Keycode, Keysym, State};
33
34use crate::platform::linux::wayland::WaylandClient;
35use crate::{
36 px, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CosmicTextSystem, CursorStyle,
37 DisplayId, ForegroundExecutor, Keymap, Keystroke, LinuxDispatcher, Menu, Modifiers,
38 PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformInput, PlatformInputHandler,
39 PlatformTextSystem, PlatformWindow, Point, PromptLevel, Result, SemanticVersion, Size, Task,
40 WindowAppearance, WindowOptions, WindowParams,
41};
42
43use super::x11::X11Client;
44
45pub(crate) const SCROLL_LINES: f64 = 3.0;
46
47// Values match the defaults on GTK.
48// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
49pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
50pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
51pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
52
53pub trait LinuxClient {
54 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
55 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
56 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
57 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
58 fn open_window(
59 &self,
60 handle: AnyWindowHandle,
61 options: WindowParams,
62 ) -> Box<dyn PlatformWindow>;
63 fn set_cursor_style(&self, style: CursorStyle);
64 fn open_uri(&self, uri: &str);
65 fn write_to_primary(&self, item: ClipboardItem);
66 fn write_to_clipboard(&self, item: ClipboardItem);
67 fn read_from_primary(&self) -> Option<ClipboardItem>;
68 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
69 fn run(&self);
70}
71
72#[derive(Default)]
73pub(crate) struct PlatformHandlers {
74 pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
75 pub(crate) become_active: Option<Box<dyn FnMut()>>,
76 pub(crate) resign_active: Option<Box<dyn FnMut()>>,
77 pub(crate) quit: Option<Box<dyn FnMut()>>,
78 pub(crate) reopen: Option<Box<dyn FnMut()>>,
79 pub(crate) event: Option<Box<dyn FnMut(PlatformInput) -> bool>>,
80 pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
81 pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
82 pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
83}
84
85pub(crate) struct LinuxCommon {
86 pub(crate) background_executor: BackgroundExecutor,
87 pub(crate) foreground_executor: ForegroundExecutor,
88 pub(crate) text_system: Arc<CosmicTextSystem>,
89 pub(crate) callbacks: PlatformHandlers,
90 pub(crate) signal: LoopSignal,
91}
92
93impl LinuxCommon {
94 pub fn new(signal: LoopSignal) -> (Self, Channel<Runnable>) {
95 let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
96 let text_system = Arc::new(CosmicTextSystem::new());
97 let callbacks = PlatformHandlers::default();
98
99 let dispatcher = Arc::new(LinuxDispatcher::new(main_sender));
100
101 let common = LinuxCommon {
102 background_executor: BackgroundExecutor::new(dispatcher.clone()),
103 foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
104 text_system,
105 callbacks,
106 signal,
107 };
108
109 (common, main_receiver)
110 }
111}
112
113impl<P: LinuxClient + 'static> Platform for P {
114 fn background_executor(&self) -> BackgroundExecutor {
115 self.with_common(|common| common.background_executor.clone())
116 }
117
118 fn foreground_executor(&self) -> ForegroundExecutor {
119 self.with_common(|common| common.foreground_executor.clone())
120 }
121
122 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
123 self.with_common(|common| common.text_system.clone())
124 }
125
126 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
127 on_finish_launching();
128
129 LinuxClient::run(self);
130
131 self.with_common(|common| {
132 if let Some(mut fun) = common.callbacks.quit.take() {
133 fun();
134 }
135 });
136 }
137
138 fn quit(&self) {
139 self.with_common(|common| common.signal.stop());
140 }
141
142 fn restart(&self) {
143 use std::os::unix::process::CommandExt as _;
144
145 // get the process id of the current process
146 let app_pid = std::process::id().to_string();
147 // get the path to the executable
148 let app_path = match self.app_path() {
149 Ok(path) => path,
150 Err(err) => {
151 log::error!("Failed to get app path: {:?}", err);
152 return;
153 }
154 };
155
156 // script to wait for the current process to exit and then restart the app
157 let script = format!(
158 r#"
159 while kill -O {pid} 2>/dev/null; do
160 sleep 0.1
161 done
162 {app_path}
163 "#,
164 pid = app_pid,
165 app_path = app_path.display()
166 );
167
168 // execute the script using /bin/bash
169 let restart_process = Command::new("/bin/bash")
170 .arg("-c")
171 .arg(script)
172 .process_group(0)
173 .spawn();
174
175 match restart_process {
176 Ok(_) => self.quit(),
177 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
178 }
179 }
180
181 // todo(linux)
182 fn activate(&self, ignoring_other_apps: bool) {}
183
184 // todo(linux)
185 fn hide(&self) {}
186
187 fn hide_other_apps(&self) {
188 log::warn!("hide_other_apps is not implemented on Linux, ignoring the call")
189 }
190
191 // todo(linux)
192 fn unhide_other_apps(&self) {}
193
194 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
195 self.primary_display()
196 }
197
198 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
199 self.displays()
200 }
201
202 // todo(linux)
203 fn active_window(&self) -> Option<AnyWindowHandle> {
204 None
205 }
206
207 fn open_window(
208 &self,
209 handle: AnyWindowHandle,
210 options: WindowParams,
211 ) -> Box<dyn PlatformWindow> {
212 self.open_window(handle, options)
213 }
214
215 fn open_url(&self, url: &str) {
216 self.open_uri(url);
217 }
218
219 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
220 self.with_common(|common| common.callbacks.open_urls = Some(callback));
221 }
222
223 fn prompt_for_paths(
224 &self,
225 options: PathPromptOptions,
226 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
227 let (done_tx, done_rx) = oneshot::channel();
228 self.foreground_executor()
229 .spawn(async move {
230 let title = if options.multiple {
231 if !options.files {
232 "Open folders"
233 } else {
234 "Open files"
235 }
236 } else {
237 if !options.files {
238 "Open folder"
239 } else {
240 "Open file"
241 }
242 };
243
244 let result = OpenFileRequest::default()
245 .modal(true)
246 .title(title)
247 .accept_label("Select")
248 .multiple(options.multiple)
249 .directory(options.directories)
250 .send()
251 .await
252 .ok()
253 .and_then(|request| request.response().ok())
254 .and_then(|response| {
255 response
256 .uris()
257 .iter()
258 .map(|uri| uri.to_file_path().ok())
259 .collect()
260 });
261
262 done_tx.send(result);
263 })
264 .detach();
265 done_rx
266 }
267
268 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
269 let (done_tx, done_rx) = oneshot::channel();
270 let directory = directory.to_owned();
271 self.foreground_executor()
272 .spawn(async move {
273 let result = SaveFileRequest::default()
274 .modal(true)
275 .title("Select new path")
276 .accept_label("Accept")
277 .send()
278 .await
279 .ok()
280 .and_then(|request| request.response().ok())
281 .and_then(|response| {
282 response
283 .uris()
284 .first()
285 .and_then(|uri| uri.to_file_path().ok())
286 });
287
288 done_tx.send(result);
289 })
290 .detach();
291
292 done_rx
293 }
294
295 fn reveal_path(&self, path: &Path) {
296 if path.is_dir() {
297 open::that(path);
298 return;
299 }
300 // If `path` is a file, the system may try to open it in a text editor
301 let dir = path.parent().unwrap_or(Path::new(""));
302 open::that(dir);
303 }
304
305 fn on_quit(&self, callback: Box<dyn FnMut()>) {
306 self.with_common(|common| {
307 common.callbacks.quit = Some(callback);
308 });
309 }
310
311 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
312 self.with_common(|common| {
313 common.callbacks.reopen = Some(callback);
314 });
315 }
316
317 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
318 self.with_common(|common| {
319 common.callbacks.app_menu_action = Some(callback);
320 });
321 }
322
323 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
324 self.with_common(|common| {
325 common.callbacks.will_open_app_menu = Some(callback);
326 });
327 }
328
329 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
330 self.with_common(|common| {
331 common.callbacks.validate_app_menu_command = Some(callback);
332 });
333 }
334
335 fn os_name(&self) -> &'static str {
336 "Linux"
337 }
338
339 fn os_version(&self) -> Result<SemanticVersion> {
340 Ok(SemanticVersion::new(1, 0, 0))
341 }
342
343 fn app_version(&self) -> Result<SemanticVersion> {
344 Ok(SemanticVersion::new(1, 0, 0))
345 }
346
347 fn app_path(&self) -> Result<PathBuf> {
348 // get the path of the executable of the current process
349 let exe_path = std::env::current_exe()?;
350 Ok(exe_path)
351 }
352
353 // todo(linux)
354 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
355
356 fn local_timezone(&self) -> UtcOffset {
357 UtcOffset::UTC
358 }
359
360 //todo(linux)
361 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
362 Err(anyhow::Error::msg(
363 "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
364 ))
365 }
366
367 fn set_cursor_style(&self, style: CursorStyle) {
368 self.set_cursor_style(style)
369 }
370
371 // todo(linux)
372 fn should_auto_hide_scrollbars(&self) -> bool {
373 false
374 }
375
376 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
377 let url = url.to_string();
378 let username = username.to_string();
379 let password = password.to_vec();
380 self.background_executor().spawn(async move {
381 let keyring = oo7::Keyring::new().await?;
382 keyring.unlock().await?;
383 keyring
384 .create_item(
385 KEYRING_LABEL,
386 &vec![("url", &url), ("username", &username)],
387 password,
388 true,
389 )
390 .await?;
391 Ok(())
392 })
393 }
394
395 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
396 let url = url.to_string();
397 self.background_executor().spawn(async move {
398 let keyring = oo7::Keyring::new().await?;
399 keyring.unlock().await?;
400
401 let items = keyring.search_items(&vec![("url", &url)]).await?;
402
403 for item in items.into_iter() {
404 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
405 let attributes = item.attributes().await?;
406 let username = attributes
407 .get("username")
408 .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
409 let secret = item.secret().await?;
410
411 // we lose the zeroizing capabilities at this boundary,
412 // a current limitation GPUI's credentials api
413 return Ok(Some((username.to_string(), secret.to_vec())));
414 } else {
415 continue;
416 }
417 }
418 Ok(None)
419 })
420 }
421
422 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
423 let url = url.to_string();
424 self.background_executor().spawn(async move {
425 let keyring = oo7::Keyring::new().await?;
426 keyring.unlock().await?;
427
428 let items = keyring.search_items(&vec![("url", &url)]).await?;
429
430 for item in items.into_iter() {
431 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
432 item.delete().await?;
433 return Ok(());
434 }
435 }
436
437 Ok(())
438 })
439 }
440
441 fn window_appearance(&self) -> crate::WindowAppearance {
442 crate::WindowAppearance::Light
443 }
444
445 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
446 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
447 }
448
449 fn write_to_primary(&self, item: ClipboardItem) {
450 self.write_to_primary(item)
451 }
452
453 fn write_to_clipboard(&self, item: ClipboardItem) {
454 self.write_to_clipboard(item)
455 }
456
457 fn read_from_primary(&self) -> Option<ClipboardItem> {
458 self.read_from_primary()
459 }
460
461 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
462 self.read_from_clipboard()
463 }
464}
465
466pub(super) fn open_uri_internal(uri: &str, activation_token: Option<&str>) {
467 let mut last_err = None;
468 for mut command in open::commands(uri) {
469 if let Some(token) = activation_token {
470 command.env("XDG_ACTIVATION_TOKEN", token);
471 }
472 match command.status() {
473 Ok(_) => return,
474 Err(err) => last_err = Some(err),
475 }
476 }
477 log::error!("failed to open uri: {uri:?}, last error: {last_err:?}");
478}
479
480pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
481 let diff = a - b;
482 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
483}
484
485pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<String> {
486 let mut file = File::from_raw_fd(fd.as_raw_fd());
487
488 let mut buffer = String::new();
489 file.read_to_string(&mut buffer)?;
490
491 // Normalize the text to unix line endings, otherwise
492 // copying from eg: firefox inserts a lot of blank
493 // lines, and that is super annoying.
494 let result = buffer.replace("\r\n", "\n");
495 Ok(result)
496}
497
498impl CursorStyle {
499 pub(super) fn to_shape(&self) -> Shape {
500 match self {
501 CursorStyle::Arrow => Shape::Default,
502 CursorStyle::IBeam => Shape::Text,
503 CursorStyle::Crosshair => Shape::Crosshair,
504 CursorStyle::ClosedHand => Shape::Grabbing,
505 CursorStyle::OpenHand => Shape::Grab,
506 CursorStyle::PointingHand => Shape::Pointer,
507 CursorStyle::ResizeLeft => Shape::WResize,
508 CursorStyle::ResizeRight => Shape::EResize,
509 CursorStyle::ResizeLeftRight => Shape::EwResize,
510 CursorStyle::ResizeUp => Shape::NResize,
511 CursorStyle::ResizeDown => Shape::SResize,
512 CursorStyle::ResizeUpDown => Shape::NsResize,
513 CursorStyle::DisappearingItem => Shape::Grabbing, // todo(linux) - couldn't find equivalent icon in linux
514 CursorStyle::IBeamCursorForVerticalLayout => Shape::VerticalText,
515 CursorStyle::OperationNotAllowed => Shape::NotAllowed,
516 CursorStyle::DragLink => Shape::Alias,
517 CursorStyle::DragCopy => Shape::Copy,
518 CursorStyle::ContextualMenu => Shape::ContextMenu,
519 }
520 }
521
522 pub(super) fn to_icon_name(&self) -> String {
523 // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
524 // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
525 // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
526 match self {
527 CursorStyle::Arrow => "arrow",
528 CursorStyle::IBeam => "text",
529 CursorStyle::Crosshair => "crosshair",
530 CursorStyle::ClosedHand => "grabbing",
531 CursorStyle::OpenHand => "grab",
532 CursorStyle::PointingHand => "pointer",
533 CursorStyle::ResizeLeft => "w-resize",
534 CursorStyle::ResizeRight => "e-resize",
535 CursorStyle::ResizeLeftRight => "ew-resize",
536 CursorStyle::ResizeUp => "n-resize",
537 CursorStyle::ResizeDown => "s-resize",
538 CursorStyle::ResizeUpDown => "ns-resize",
539 CursorStyle::DisappearingItem => "grabbing", // todo(linux) - couldn't find equivalent icon in linux
540 CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
541 CursorStyle::OperationNotAllowed => "not-allowed",
542 CursorStyle::DragLink => "alias",
543 CursorStyle::DragCopy => "copy",
544 CursorStyle::ContextualMenu => "context-menu",
545 }
546 .to_string()
547 }
548}
549
550impl Keystroke {
551 pub(super) fn from_xkb(state: &State, modifiers: Modifiers, keycode: Keycode) -> Self {
552 let mut modifiers = modifiers;
553
554 let key_utf32 = state.key_get_utf32(keycode);
555 let key_utf8 = state.key_get_utf8(keycode);
556 let key_sym = state.key_get_one_sym(keycode);
557
558 // The logic here tries to replicate the logic in `../mac/events.rs`
559 // "Consumed" modifiers are modifiers that have been used to translate a key, for example
560 // pressing "shift" and "1" on US layout produces the key `!` but "consumes" the shift.
561 // Notes:
562 // - macOS gets the key character directly ("."), xkb gives us the key name ("period")
563 // - macOS logic removes consumed shift modifier for symbols: "{", not "shift-{"
564 // - macOS logic keeps consumed shift modifiers for letters: "shift-a", not "a" or "A"
565
566 let mut handle_consumed_modifiers = true;
567 let key = match key_sym {
568 Keysym::Return => "enter".to_owned(),
569 Keysym::Prior => "pageup".to_owned(),
570 Keysym::Next => "pagedown".to_owned(),
571
572 Keysym::comma => ",".to_owned(),
573 Keysym::period => ".".to_owned(),
574 Keysym::less => "<".to_owned(),
575 Keysym::greater => ">".to_owned(),
576 Keysym::slash => "/".to_owned(),
577 Keysym::question => "?".to_owned(),
578
579 Keysym::semicolon => ";".to_owned(),
580 Keysym::colon => ":".to_owned(),
581 Keysym::apostrophe => "'".to_owned(),
582 Keysym::quotedbl => "\"".to_owned(),
583
584 Keysym::bracketleft => "[".to_owned(),
585 Keysym::braceleft => "{".to_owned(),
586 Keysym::bracketright => "]".to_owned(),
587 Keysym::braceright => "}".to_owned(),
588 Keysym::backslash => "\\".to_owned(),
589 Keysym::bar => "|".to_owned(),
590
591 Keysym::grave => "`".to_owned(),
592 Keysym::asciitilde => "~".to_owned(),
593 Keysym::exclam => "!".to_owned(),
594 Keysym::at => "@".to_owned(),
595 Keysym::numbersign => "#".to_owned(),
596 Keysym::dollar => "$".to_owned(),
597 Keysym::percent => "%".to_owned(),
598 Keysym::asciicircum => "^".to_owned(),
599 Keysym::ampersand => "&".to_owned(),
600 Keysym::asterisk => "*".to_owned(),
601 Keysym::parenleft => "(".to_owned(),
602 Keysym::parenright => ")".to_owned(),
603 Keysym::minus => "-".to_owned(),
604 Keysym::underscore => "_".to_owned(),
605 Keysym::equal => "=".to_owned(),
606 Keysym::plus => "+".to_owned(),
607
608 Keysym::ISO_Left_Tab => {
609 handle_consumed_modifiers = false;
610 "tab".to_owned()
611 }
612
613 _ => {
614 handle_consumed_modifiers = false;
615 xkb::keysym_get_name(key_sym).to_lowercase()
616 }
617 };
618
619 // Ignore control characters (and DEL) for the purposes of ime_key,
620 // but if key_utf32 is 0 then assume it isn't one
621 let ime_key = ((key_utf32 == 0 || (key_utf32 >= 32 && key_utf32 != 127))
622 && !key_utf8.is_empty())
623 .then_some(key_utf8);
624
625 if handle_consumed_modifiers {
626 let mod_shift_index = state.get_keymap().mod_get_index(xkb::MOD_NAME_SHIFT);
627 let is_shift_consumed = state.mod_index_is_consumed(keycode, mod_shift_index);
628
629 if modifiers.shift && is_shift_consumed {
630 modifiers.shift = false;
631 }
632 }
633
634 Keystroke {
635 modifiers,
636 key,
637 ime_key,
638 }
639 }
640}
641
642impl Modifiers {
643 pub(super) fn from_xkb(keymap_state: &State) -> Self {
644 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
645 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
646 let control =
647 keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
648 let platform =
649 keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
650 Modifiers {
651 shift,
652 alt,
653 control,
654 platform,
655 function: false,
656 }
657 }
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663 use crate::{px, Point};
664
665 #[test]
666 fn test_is_within_click_distance() {
667 let zero = Point::new(px(0.0), px(0.0));
668 assert_eq!(
669 is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
670 true
671 );
672 assert_eq!(
673 is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
674 true
675 );
676 assert_eq!(
677 is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
678 true
679 );
680 assert_eq!(
681 is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
682 false
683 );
684 }
685}