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