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