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