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