1use std::{
2 env,
3 path::{Path, PathBuf},
4 rc::Rc,
5 sync::Arc,
6};
7#[cfg(any(feature = "wayland", feature = "x11"))]
8use std::{
9 ffi::OsString,
10 fs::File,
11 io::Read as _,
12 os::fd::{AsFd, FromRawFd, IntoRawFd},
13 time::Duration,
14};
15
16use anyhow::{Context as _, anyhow};
17use calloop::LoopSignal;
18use futures::channel::oneshot;
19use util::ResultExt as _;
20use util::command::{new_command, new_std_command};
21#[cfg(any(feature = "wayland", feature = "x11"))]
22use xkbcommon::xkb::{self, Keycode, Keysym, State};
23
24use crate::linux::{LinuxDispatcher, PriorityQueueCalloopReceiver};
25use gpui::{
26 Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
27 ForegroundExecutor, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform,
28 PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
29 PlatformWindow, Result, RunnableVariant, Task, ThermalState, WindowAppearance, WindowParams,
30};
31#[cfg(any(feature = "wayland", feature = "x11"))]
32use gpui::{Pixels, Point, px};
33
34#[cfg(any(feature = "wayland", feature = "x11"))]
35pub(crate) const SCROLL_LINES: f32 = 3.0;
36
37// Values match the defaults on GTK.
38// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
39#[cfg(any(feature = "wayland", feature = "x11"))]
40pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
41#[cfg(any(feature = "wayland", feature = "x11"))]
42pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
43pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
44
45#[cfg(any(feature = "wayland", feature = "x11"))]
46const FILE_PICKER_PORTAL_MISSING: &str =
47 "Couldn't open file picker due to missing xdg-desktop-portal implementation.";
48
49#[cfg(any(feature = "x11", feature = "wayland"))]
50pub trait ResultExt {
51 type Ok;
52
53 fn notify_err(self, msg: &'static str) -> Self::Ok;
54}
55
56#[cfg(any(feature = "x11", feature = "wayland"))]
57impl<T> ResultExt for anyhow::Result<T> {
58 type Ok = T;
59
60 fn notify_err(self, msg: &'static str) -> T {
61 match self {
62 Ok(v) => v,
63 Err(e) => {
64 use ashpd::desktop::notification::{Notification, NotificationProxy, Priority};
65 use futures::executor::block_on;
66
67 let proxy = block_on(NotificationProxy::new()).expect(msg);
68
69 let notification_id = "dev.zed.Oops";
70 block_on(
71 proxy.add_notification(
72 notification_id,
73 Notification::new("Zed failed to launch")
74 .body(Some(
75 format!(
76 "{e:?}. See https://zed.dev/docs/linux for troubleshooting steps."
77 )
78 .as_str(),
79 ))
80 .priority(Priority::High)
81 .icon(ashpd::desktop::Icon::with_names(&[
82 "dialog-question-symbolic",
83 ])),
84 )
85 ).expect(msg);
86
87 panic!("{msg}");
88 }
89 }
90 }
91}
92
93pub(crate) trait LinuxClient {
94 fn compositor_name(&self) -> &'static str;
95 fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
96 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
97 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
98 #[allow(unused)]
99 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
100 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
101
102 fn is_screen_capture_supported(&self) -> bool {
103 false
104 }
105
106 fn screen_capture_sources(
107 &self,
108 ) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {
109 let (sources_tx, sources_rx) = oneshot::channel();
110 sources_tx
111 .send(Err(anyhow::anyhow!(
112 "gpui_linux was compiled without the screen-capture feature"
113 )))
114 .ok();
115 sources_rx
116 }
117
118 fn open_window(
119 &self,
120 handle: AnyWindowHandle,
121 options: WindowParams,
122 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
123 fn set_cursor_style(&self, style: CursorStyle);
124 fn open_uri(&self, uri: &str);
125 fn reveal_path(&self, path: PathBuf);
126 fn write_to_primary(&self, item: ClipboardItem);
127 fn write_to_clipboard(&self, item: ClipboardItem);
128 fn read_from_primary(&self) -> Option<ClipboardItem>;
129 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
130 fn active_window(&self) -> Option<AnyWindowHandle>;
131 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>;
132 fn run(&self);
133
134 #[cfg(any(feature = "wayland", feature = "x11"))]
135 fn window_identifier(
136 &self,
137 ) -> impl Future<Output = Option<ashpd::WindowIdentifier>> + Send + 'static {
138 std::future::ready::<Option<ashpd::WindowIdentifier>>(None)
139 }
140}
141
142#[derive(Default)]
143pub(crate) struct PlatformHandlers {
144 pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
145 pub(crate) quit: Option<Box<dyn FnMut()>>,
146 pub(crate) reopen: Option<Box<dyn FnMut()>>,
147 pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
148 pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
149 pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
150 pub(crate) keyboard_layout_change: Option<Box<dyn FnMut()>>,
151}
152
153pub(crate) struct LinuxCommon {
154 pub(crate) background_executor: BackgroundExecutor,
155 pub(crate) foreground_executor: ForegroundExecutor,
156 pub(crate) text_system: Arc<dyn PlatformTextSystem>,
157 pub(crate) appearance: WindowAppearance,
158 pub(crate) auto_hide_scrollbars: bool,
159 pub(crate) callbacks: PlatformHandlers,
160 pub(crate) signal: LoopSignal,
161 pub(crate) menus: Vec<OwnedMenu>,
162}
163
164impl LinuxCommon {
165 pub fn new(signal: LoopSignal) -> (Self, PriorityQueueCalloopReceiver<RunnableVariant>) {
166 let (main_sender, main_receiver) = PriorityQueueCalloopReceiver::new();
167
168 #[cfg(any(feature = "wayland", feature = "x11"))]
169 let text_system = Arc::new(crate::linux::CosmicTextSystem::new());
170 #[cfg(not(any(feature = "wayland", feature = "x11")))]
171 let text_system = Arc::new(gpui::NoopTextSystem::new());
172
173 let callbacks = PlatformHandlers::default();
174
175 let dispatcher = Arc::new(LinuxDispatcher::new(main_sender));
176
177 let background_executor = BackgroundExecutor::new(dispatcher.clone());
178
179 let common = LinuxCommon {
180 background_executor,
181 foreground_executor: ForegroundExecutor::new(dispatcher),
182 text_system,
183 appearance: WindowAppearance::Light,
184 auto_hide_scrollbars: false,
185 callbacks,
186 signal,
187 menus: Vec::new(),
188 };
189
190 (common, main_receiver)
191 }
192}
193
194pub(crate) struct LinuxPlatform<P> {
195 pub(crate) inner: P,
196}
197
198impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
199 fn background_executor(&self) -> BackgroundExecutor {
200 self.inner
201 .with_common(|common| common.background_executor.clone())
202 }
203
204 fn foreground_executor(&self) -> ForegroundExecutor {
205 self.inner
206 .with_common(|common| common.foreground_executor.clone())
207 }
208
209 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
210 self.inner.with_common(|common| common.text_system.clone())
211 }
212
213 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
214 self.inner.keyboard_layout()
215 }
216
217 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
218 Rc::new(gpui::DummyKeyboardMapper)
219 }
220
221 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
222 self.inner
223 .with_common(|common| common.callbacks.keyboard_layout_change = Some(callback));
224 }
225
226 fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
227
228 fn thermal_state(&self) -> ThermalState {
229 ThermalState::Nominal
230 }
231
232 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
233 on_finish_launching();
234
235 LinuxClient::run(&self.inner);
236
237 let quit = self
238 .inner
239 .with_common(|common| common.callbacks.quit.take());
240 if let Some(mut fun) = quit {
241 fun();
242 }
243 }
244
245 fn quit(&self) {
246 self.inner.with_common(|common| common.signal.stop());
247 }
248
249 fn compositor_name(&self) -> &'static str {
250 self.inner.compositor_name()
251 }
252
253 fn restart(&self, binary_path: Option<PathBuf>) {
254 use std::os::unix::process::CommandExt as _;
255
256 // get the process id of the current process
257 let app_pid = std::process::id().to_string();
258 // get the path to the executable
259 let app_path = if let Some(path) = binary_path {
260 path
261 } else {
262 match self.app_path() {
263 Ok(path) => path,
264 Err(err) => {
265 log::error!("Failed to get app path: {:?}", err);
266 return;
267 }
268 }
269 };
270
271 log::info!("Restarting process, using app path: {:?}", app_path);
272
273 // Script to wait for the current process to exit and then restart the app.
274 let script = format!(
275 r#"
276 while kill -0 {pid} 2>/dev/null; do
277 sleep 0.1
278 done
279
280 {app_path}
281 "#,
282 pid = app_pid,
283 app_path = app_path.display()
284 );
285
286 #[allow(
287 clippy::disallowed_methods,
288 reason = "We are restarting ourselves, using std command thus is fine"
289 )]
290 let restart_process = new_std_command("/usr/bin/env")
291 .arg("bash")
292 .arg("-c")
293 .arg(script)
294 .process_group(0)
295 .spawn();
296
297 match restart_process {
298 Ok(_) => self.quit(),
299 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
300 }
301 }
302
303 fn activate(&self, _ignoring_other_apps: bool) {
304 log::info!("activate is not implemented on Linux, ignoring the call")
305 }
306
307 fn hide(&self) {
308 log::info!("hide is not implemented on Linux, ignoring the call")
309 }
310
311 fn hide_other_apps(&self) {
312 log::info!("hide_other_apps is not implemented on Linux, ignoring the call")
313 }
314
315 fn unhide_other_apps(&self) {
316 log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")
317 }
318
319 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
320 self.inner.primary_display()
321 }
322
323 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
324 self.inner.displays()
325 }
326
327 #[cfg(feature = "screen-capture")]
328 fn is_screen_capture_supported(&self) -> bool {
329 self.inner.is_screen_capture_supported()
330 }
331
332 #[cfg(feature = "screen-capture")]
333 fn screen_capture_sources(
334 &self,
335 ) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {
336 self.inner.screen_capture_sources()
337 }
338
339 fn active_window(&self) -> Option<AnyWindowHandle> {
340 self.inner.active_window()
341 }
342
343 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
344 self.inner.window_stack()
345 }
346
347 fn open_window(
348 &self,
349 handle: AnyWindowHandle,
350 options: WindowParams,
351 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
352 self.inner.open_window(handle, options)
353 }
354
355 fn open_url(&self, url: &str) {
356 self.inner.open_uri(url);
357 }
358
359 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
360 self.inner
361 .with_common(|common| common.callbacks.open_urls = Some(callback));
362 }
363
364 fn prompt_for_paths(
365 &self,
366 options: PathPromptOptions,
367 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
368 let (done_tx, done_rx) = oneshot::channel();
369
370 #[cfg(not(any(feature = "wayland", feature = "x11")))]
371 let _ = (done_tx.send(Ok(None)), options);
372
373 #[cfg(any(feature = "wayland", feature = "x11"))]
374 let identifier = self.inner.window_identifier();
375
376 #[cfg(any(feature = "wayland", feature = "x11"))]
377 self.foreground_executor()
378 .spawn(async move {
379 let title = if options.directories {
380 "Open Folder"
381 } else {
382 "Open File"
383 };
384
385 let request = match ashpd::desktop::file_chooser::OpenFileRequest::default()
386 .identifier(identifier.await)
387 .modal(true)
388 .title(title)
389 .accept_label(options.prompt.as_ref().map(gpui::SharedString::as_str))
390 .multiple(options.multiple)
391 .directory(options.directories)
392 .send()
393 .await
394 {
395 Ok(request) => request,
396 Err(err) => {
397 let result = match err {
398 ashpd::Error::PortalNotFound(_) => anyhow!(FILE_PICKER_PORTAL_MISSING),
399 err => err.into(),
400 };
401 let _ = done_tx.send(Err(result));
402 return;
403 }
404 };
405
406 let result = match request.response() {
407 Ok(response) => Ok(Some(
408 response
409 .uris()
410 .iter()
411 .filter_map(|uri| uri.to_file_path().ok())
412 .collect::<Vec<_>>(),
413 )),
414 Err(ashpd::Error::Response(_)) => Ok(None),
415 Err(e) => Err(e.into()),
416 };
417 let _ = done_tx.send(result);
418 })
419 .detach();
420 done_rx
421 }
422
423 fn prompt_for_new_path(
424 &self,
425 directory: &Path,
426 suggested_name: Option<&str>,
427 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
428 let (done_tx, done_rx) = oneshot::channel();
429
430 #[cfg(not(any(feature = "wayland", feature = "x11")))]
431 let _ = (done_tx.send(Ok(None)), directory, suggested_name);
432
433 #[cfg(any(feature = "wayland", feature = "x11"))]
434 let identifier = self.inner.window_identifier();
435
436 #[cfg(any(feature = "wayland", feature = "x11"))]
437 self.foreground_executor()
438 .spawn({
439 let directory = directory.to_owned();
440 let suggested_name = suggested_name.map(|s| s.to_owned());
441
442 async move {
443 let mut request_builder =
444 ashpd::desktop::file_chooser::SaveFileRequest::default()
445 .identifier(identifier.await)
446 .modal(true)
447 .title("Save File")
448 .current_folder(directory)
449 .expect("pathbuf should not be nul terminated");
450
451 if let Some(suggested_name) = suggested_name {
452 request_builder = request_builder.current_name(suggested_name.as_str());
453 }
454
455 let request = match request_builder.send().await {
456 Ok(request) => request,
457 Err(err) => {
458 let result = match err {
459 ashpd::Error::PortalNotFound(_) => {
460 anyhow!(FILE_PICKER_PORTAL_MISSING)
461 }
462 err => err.into(),
463 };
464 let _ = done_tx.send(Err(result));
465 return;
466 }
467 };
468
469 let result = match request.response() {
470 Ok(response) => Ok(response
471 .uris()
472 .first()
473 .and_then(|uri| uri.to_file_path().ok())),
474 Err(ashpd::Error::Response(_)) => Ok(None),
475 Err(e) => Err(e.into()),
476 };
477 let _ = done_tx.send(result);
478 }
479 })
480 .detach();
481
482 done_rx
483 }
484
485 fn can_select_mixed_files_and_dirs(&self) -> bool {
486 // org.freedesktop.portal.FileChooser only supports "pick files" and "pick directories".
487 false
488 }
489
490 fn reveal_path(&self, path: &Path) {
491 self.inner.reveal_path(path.to_owned());
492 }
493
494 fn open_with_system(&self, path: &Path) {
495 let path = path.to_owned();
496 self.background_executor()
497 .spawn(async move {
498 let _ = new_command("xdg-open")
499 .arg(path)
500 .spawn()
501 .context("invoking xdg-open")
502 .log_err()?
503 .status()
504 .await
505 .log_err()?;
506 Some(())
507 })
508 .detach();
509 }
510
511 fn on_quit(&self, callback: Box<dyn FnMut()>) {
512 self.inner.with_common(|common| {
513 common.callbacks.quit = Some(callback);
514 });
515 }
516
517 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
518 self.inner.with_common(|common| {
519 common.callbacks.reopen = Some(callback);
520 });
521 }
522
523 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
524 self.inner.with_common(|common| {
525 common.callbacks.app_menu_action = Some(callback);
526 });
527 }
528
529 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
530 self.inner.with_common(|common| {
531 common.callbacks.will_open_app_menu = Some(callback);
532 });
533 }
534
535 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
536 self.inner.with_common(|common| {
537 common.callbacks.validate_app_menu_command = Some(callback);
538 });
539 }
540
541 fn app_path(&self) -> Result<PathBuf> {
542 // get the path of the executable of the current process
543 let app_path = env::current_exe()?;
544 Ok(app_path)
545 }
546
547 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
548 self.inner.with_common(|common| {
549 common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
550 })
551 }
552
553 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
554 self.inner.with_common(|common| Some(common.menus.clone()))
555 }
556
557 fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {
558 // todo(linux)
559 }
560
561 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
562 Err(anyhow::Error::msg(
563 "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
564 ))
565 }
566
567 fn set_cursor_style(&self, style: CursorStyle) {
568 self.inner.set_cursor_style(style)
569 }
570
571 fn should_auto_hide_scrollbars(&self) -> bool {
572 self.inner.with_common(|common| common.auto_hide_scrollbars)
573 }
574
575 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
576 let url = url.to_string();
577 let username = username.to_string();
578 let password = password.to_vec();
579 self.background_executor().spawn(async move {
580 let keyring = oo7::Keyring::new().await?;
581 keyring.unlock().await?;
582 keyring
583 .create_item(
584 KEYRING_LABEL,
585 &vec![("url", &url), ("username", &username)],
586 password,
587 true,
588 )
589 .await?;
590 Ok(())
591 })
592 }
593
594 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
595 let url = url.to_string();
596 self.background_executor().spawn(async move {
597 let keyring = oo7::Keyring::new().await?;
598 keyring.unlock().await?;
599
600 let items = keyring.search_items(&vec![("url", &url)]).await?;
601
602 for item in items.into_iter() {
603 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
604 let attributes = item.attributes().await?;
605 let username = attributes
606 .get("username")
607 .context("Cannot find username in stored credentials")?;
608 item.unlock().await?;
609 let secret = item.secret().await?;
610
611 // we lose the zeroizing capabilities at this boundary,
612 // a current limitation GPUI's credentials api
613 return Ok(Some((username.to_string(), secret.to_vec())));
614 } else {
615 continue;
616 }
617 }
618 Ok(None)
619 })
620 }
621
622 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
623 let url = url.to_string();
624 self.background_executor().spawn(async move {
625 let keyring = oo7::Keyring::new().await?;
626 keyring.unlock().await?;
627
628 let items = keyring.search_items(&vec![("url", &url)]).await?;
629
630 for item in items.into_iter() {
631 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
632 item.delete().await?;
633 return Ok(());
634 }
635 }
636
637 Ok(())
638 })
639 }
640
641 fn window_appearance(&self) -> WindowAppearance {
642 self.inner.with_common(|common| common.appearance)
643 }
644
645 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
646 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
647 }
648
649 fn write_to_primary(&self, item: ClipboardItem) {
650 self.inner.write_to_primary(item)
651 }
652
653 fn write_to_clipboard(&self, item: ClipboardItem) {
654 self.inner.write_to_clipboard(item)
655 }
656
657 fn read_from_primary(&self) -> Option<ClipboardItem> {
658 self.inner.read_from_primary()
659 }
660
661 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
662 self.inner.read_from_clipboard()
663 }
664
665 fn add_recent_document(&self, _path: &Path) {}
666}
667
668#[cfg(any(feature = "wayland", feature = "x11"))]
669pub(super) fn open_uri_internal(
670 executor: BackgroundExecutor,
671 uri: &str,
672 activation_token: Option<String>,
673) {
674 if let Some(uri) = ashpd::url::Url::parse(uri).log_err() {
675 executor
676 .spawn(async move {
677 match ashpd::desktop::open_uri::OpenFileRequest::default()
678 .activation_token(activation_token.clone().map(ashpd::ActivationToken::from))
679 .send_uri(&uri)
680 .await
681 .and_then(|e| e.response())
682 {
683 Ok(()) => return,
684 Err(e) => log::error!("Failed to open with dbus: {}", e),
685 }
686
687 for mut command in open::commands(uri.to_string()) {
688 if let Some(token) = activation_token.as_ref() {
689 command.env("XDG_ACTIVATION_TOKEN", token);
690 }
691 let program = format!("{:?}", command.get_program());
692 match smol::process::Command::from(command).spawn() {
693 Ok(mut cmd) => {
694 cmd.status().await.log_err();
695 return;
696 }
697 Err(e) => {
698 log::error!("Failed to open with {}: {}", program, e)
699 }
700 }
701 }
702 })
703 .detach();
704 }
705}
706
707#[cfg(any(feature = "x11", feature = "wayland"))]
708pub(super) fn reveal_path_internal(
709 executor: BackgroundExecutor,
710 path: PathBuf,
711 activation_token: Option<String>,
712) {
713 executor
714 .spawn(async move {
715 if let Some(dir) = File::open(path.clone()).log_err() {
716 match ashpd::desktop::open_uri::OpenDirectoryRequest::default()
717 .activation_token(activation_token.map(ashpd::ActivationToken::from))
718 .send(&dir.as_fd())
719 .await
720 {
721 Ok(_) => return,
722 Err(e) => log::error!("Failed to open with dbus: {}", e),
723 }
724 if path.is_dir() {
725 open::that_detached(path).log_err();
726 } else {
727 open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
728 }
729 }
730 })
731 .detach();
732}
733
734#[cfg(any(feature = "wayland", feature = "x11"))]
735pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
736 let diff = a - b;
737 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
738}
739
740#[cfg(any(feature = "wayland", feature = "x11"))]
741pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
742 let mut locales = Vec::default();
743 if let Some(locale) = env::var_os("LC_CTYPE") {
744 locales.push(locale);
745 }
746 locales.push(OsString::from("C"));
747 let mut state: Option<xkb::compose::State> = None;
748 for locale in locales {
749 if let Ok(table) =
750 xkb::compose::Table::new_from_locale(cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
751 {
752 state = Some(xkb::compose::State::new(
753 &table,
754 xkb::compose::STATE_NO_FLAGS,
755 ));
756 break;
757 }
758 }
759 state
760}
761
762#[cfg(any(feature = "wayland", feature = "x11"))]
763pub(super) unsafe fn read_fd(fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
764 let mut file = unsafe { File::from_raw_fd(fd.into_raw_fd()) };
765 let mut buffer = Vec::new();
766 file.read_to_end(&mut buffer)?;
767 Ok(buffer)
768}
769
770#[cfg(any(feature = "wayland", feature = "x11"))]
771pub(super) const DEFAULT_CURSOR_ICON_NAME: &str = "left_ptr";
772
773#[cfg(any(feature = "wayland", feature = "x11"))]
774pub(super) fn cursor_style_to_icon_names(style: CursorStyle) -> &'static [&'static str] {
775 // Based on cursor names from chromium:
776 // https://github.com/chromium/chromium/blob/d3069cf9c973dc3627fa75f64085c6a86c8f41bf/ui/base/cursor/cursor_factory.cc#L113
777 match style {
778 CursorStyle::Arrow => &[DEFAULT_CURSOR_ICON_NAME],
779 CursorStyle::IBeam => &["text", "xterm"],
780 CursorStyle::Crosshair => &["crosshair", "cross"],
781 CursorStyle::ClosedHand => &["closedhand", "grabbing", "hand2"],
782 CursorStyle::OpenHand => &["openhand", "grab", "hand1"],
783 CursorStyle::PointingHand => &["pointer", "hand", "hand2"],
784 CursorStyle::ResizeLeft => &["w-resize", "left_side"],
785 CursorStyle::ResizeRight => &["e-resize", "right_side"],
786 CursorStyle::ResizeLeftRight => &["ew-resize", "sb_h_double_arrow"],
787 CursorStyle::ResizeUp => &["n-resize", "top_side"],
788 CursorStyle::ResizeDown => &["s-resize", "bottom_side"],
789 CursorStyle::ResizeUpDown => &["sb_v_double_arrow", "ns-resize"],
790 CursorStyle::ResizeUpLeftDownRight => &["size_fdiag", "bd_double_arrow", "nwse-resize"],
791 CursorStyle::ResizeUpRightDownLeft => &["size_bdiag", "nesw-resize", "fd_double_arrow"],
792 CursorStyle::ResizeColumn => &["col-resize", "sb_h_double_arrow"],
793 CursorStyle::ResizeRow => &["row-resize", "sb_v_double_arrow"],
794 CursorStyle::IBeamCursorForVerticalLayout => &["vertical-text"],
795 CursorStyle::OperationNotAllowed => &["not-allowed", "crossed_circle"],
796 CursorStyle::DragLink => &["alias"],
797 CursorStyle::DragCopy => &["copy"],
798 CursorStyle::ContextualMenu => &["context-menu"],
799 CursorStyle::None => {
800 #[cfg(debug_assertions)]
801 panic!("CursorStyle::None should be handled separately in the client");
802 #[cfg(not(debug_assertions))]
803 &[DEFAULT_CURSOR_ICON_NAME]
804 }
805 }
806}
807
808#[cfg(any(feature = "wayland", feature = "x11"))]
809pub(super) fn log_cursor_icon_warning(message: impl std::fmt::Display) {
810 if let Ok(xcursor_path) = env::var("XCURSOR_PATH") {
811 log::warn!(
812 "{:#}\ncursor icon loading may be failing if XCURSOR_PATH environment variable is invalid. \
813 XCURSOR_PATH overrides the default icon search. Its current value is '{}'",
814 message,
815 xcursor_path
816 );
817 } else {
818 log::warn!("{:#}", message);
819 }
820}
821
822#[cfg(any(feature = "wayland", feature = "x11"))]
823fn guess_ascii(keycode: Keycode, shift: bool) -> Option<char> {
824 let c = match (keycode.raw(), shift) {
825 (24, _) => 'q',
826 (25, _) => 'w',
827 (26, _) => 'e',
828 (27, _) => 'r',
829 (28, _) => 't',
830 (29, _) => 'y',
831 (30, _) => 'u',
832 (31, _) => 'i',
833 (32, _) => 'o',
834 (33, _) => 'p',
835 (34, false) => '[',
836 (34, true) => '{',
837 (35, false) => ']',
838 (35, true) => '}',
839 (38, _) => 'a',
840 (39, _) => 's',
841 (40, _) => 'd',
842 (41, _) => 'f',
843 (42, _) => 'g',
844 (43, _) => 'h',
845 (44, _) => 'j',
846 (45, _) => 'k',
847 (46, _) => 'l',
848 (47, false) => ';',
849 (47, true) => ':',
850 (48, false) => '\'',
851 (48, true) => '"',
852 (49, false) => '`',
853 (49, true) => '~',
854 (51, false) => '\\',
855 (51, true) => '|',
856 (52, _) => 'z',
857 (53, _) => 'x',
858 (54, _) => 'c',
859 (55, _) => 'v',
860 (56, _) => 'b',
861 (57, _) => 'n',
862 (58, _) => 'm',
863 (59, false) => ',',
864 (59, true) => '>',
865 (60, false) => '.',
866 (60, true) => '<',
867 (61, false) => '/',
868 (61, true) => '?',
869
870 _ => return None,
871 };
872
873 Some(c)
874}
875
876#[cfg(any(feature = "wayland", feature = "x11"))]
877pub(super) fn keystroke_from_xkb(
878 state: &State,
879 mut modifiers: gpui::Modifiers,
880 keycode: Keycode,
881) -> gpui::Keystroke {
882 let key_utf32 = state.key_get_utf32(keycode);
883 let key_utf8 = state.key_get_utf8(keycode);
884 let key_sym = state.key_get_one_sym(keycode);
885
886 let key = match key_sym {
887 Keysym::Return => "enter".to_owned(),
888 Keysym::Prior => "pageup".to_owned(),
889 Keysym::Next => "pagedown".to_owned(),
890 Keysym::ISO_Left_Tab => "tab".to_owned(),
891 Keysym::KP_Prior => "pageup".to_owned(),
892 Keysym::KP_Next => "pagedown".to_owned(),
893 Keysym::XF86_Back => "back".to_owned(),
894 Keysym::XF86_Forward => "forward".to_owned(),
895 Keysym::XF86_Cut => "cut".to_owned(),
896 Keysym::XF86_Copy => "copy".to_owned(),
897 Keysym::XF86_Paste => "paste".to_owned(),
898 Keysym::XF86_New => "new".to_owned(),
899 Keysym::XF86_Open => "open".to_owned(),
900 Keysym::XF86_Save => "save".to_owned(),
901
902 Keysym::comma => ",".to_owned(),
903 Keysym::period => ".".to_owned(),
904 Keysym::less => "<".to_owned(),
905 Keysym::greater => ">".to_owned(),
906 Keysym::slash => "/".to_owned(),
907 Keysym::question => "?".to_owned(),
908
909 Keysym::semicolon => ";".to_owned(),
910 Keysym::colon => ":".to_owned(),
911 Keysym::apostrophe => "'".to_owned(),
912 Keysym::quotedbl => "\"".to_owned(),
913
914 Keysym::bracketleft => "[".to_owned(),
915 Keysym::braceleft => "{".to_owned(),
916 Keysym::bracketright => "]".to_owned(),
917 Keysym::braceright => "}".to_owned(),
918 Keysym::backslash => "\\".to_owned(),
919 Keysym::bar => "|".to_owned(),
920
921 Keysym::grave => "`".to_owned(),
922 Keysym::asciitilde => "~".to_owned(),
923 Keysym::exclam => "!".to_owned(),
924 Keysym::at => "@".to_owned(),
925 Keysym::numbersign => "#".to_owned(),
926 Keysym::dollar => "$".to_owned(),
927 Keysym::percent => "%".to_owned(),
928 Keysym::asciicircum => "^".to_owned(),
929 Keysym::ampersand => "&".to_owned(),
930 Keysym::asterisk => "*".to_owned(),
931 Keysym::parenleft => "(".to_owned(),
932 Keysym::parenright => ")".to_owned(),
933 Keysym::minus => "-".to_owned(),
934 Keysym::underscore => "_".to_owned(),
935 Keysym::equal => "=".to_owned(),
936 Keysym::plus => "+".to_owned(),
937 Keysym::space => "space".to_owned(),
938 Keysym::BackSpace => "backspace".to_owned(),
939 Keysym::Tab => "tab".to_owned(),
940 Keysym::Delete => "delete".to_owned(),
941 Keysym::Escape => "escape".to_owned(),
942
943 Keysym::Left => "left".to_owned(),
944 Keysym::Right => "right".to_owned(),
945 Keysym::Up => "up".to_owned(),
946 Keysym::Down => "down".to_owned(),
947 Keysym::Home => "home".to_owned(),
948 Keysym::End => "end".to_owned(),
949 Keysym::Insert => "insert".to_owned(),
950
951 _ => {
952 let name = xkb::keysym_get_name(key_sym).to_lowercase();
953 if key_sym.is_keypad_key() {
954 name.replace("kp_", "")
955 } else if let Some(key) = key_utf8.chars().next()
956 && key_utf8.len() == 1
957 && key.is_ascii()
958 {
959 if key.is_ascii_graphic() {
960 key_utf8.to_lowercase()
961 // map ctrl-a to `a`
962 // ctrl-0..9 may emit control codes like ctrl-[, but
963 // we don't want to map them to `[`
964 } else if key_utf32 <= 0x1f
965 && !name.chars().next().is_some_and(|c| c.is_ascii_digit())
966 {
967 ((key_utf32 as u8 + 0x40) as char)
968 .to_ascii_lowercase()
969 .to_string()
970 } else {
971 name
972 }
973 } else if let Some(key_en) = guess_ascii(keycode, modifiers.shift) {
974 String::from(key_en)
975 } else {
976 name
977 }
978 }
979 };
980
981 if modifiers.shift {
982 // we only include the shift for upper-case letters by convention,
983 // so don't include for numbers and symbols, but do include for
984 // tab/enter, etc.
985 if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() {
986 modifiers.shift = false;
987 }
988 }
989
990 // Ignore control characters (and DEL) for the purposes of key_char
991 let key_char =
992 (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
993
994 gpui::Keystroke {
995 modifiers,
996 key,
997 key_char,
998 }
999}
1000
1001/**
1002 * Returns which symbol the dead key represents
1003 * <https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux>
1004 */
1005#[cfg(any(feature = "wayland", feature = "x11"))]
1006pub fn keystroke_underlying_dead_key(keysym: Keysym) -> Option<String> {
1007 match keysym {
1008 Keysym::dead_grave => Some("`".to_owned()),
1009 Keysym::dead_acute => Some("´".to_owned()),
1010 Keysym::dead_circumflex => Some("^".to_owned()),
1011 Keysym::dead_tilde => Some("~".to_owned()),
1012 Keysym::dead_macron => Some("¯".to_owned()),
1013 Keysym::dead_breve => Some("˘".to_owned()),
1014 Keysym::dead_abovedot => Some("˙".to_owned()),
1015 Keysym::dead_diaeresis => Some("¨".to_owned()),
1016 Keysym::dead_abovering => Some("˚".to_owned()),
1017 Keysym::dead_doubleacute => Some("˝".to_owned()),
1018 Keysym::dead_caron => Some("ˇ".to_owned()),
1019 Keysym::dead_cedilla => Some("¸".to_owned()),
1020 Keysym::dead_ogonek => Some("˛".to_owned()),
1021 Keysym::dead_iota => Some("ͅ".to_owned()),
1022 Keysym::dead_voiced_sound => Some("゙".to_owned()),
1023 Keysym::dead_semivoiced_sound => Some("゚".to_owned()),
1024 Keysym::dead_belowdot => Some("̣̣".to_owned()),
1025 Keysym::dead_hook => Some("̡".to_owned()),
1026 Keysym::dead_horn => Some("̛".to_owned()),
1027 Keysym::dead_stroke => Some("̶̶".to_owned()),
1028 Keysym::dead_abovecomma => Some("̓̓".to_owned()),
1029 Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
1030 Keysym::dead_doublegrave => Some("̏".to_owned()),
1031 Keysym::dead_belowring => Some("˳".to_owned()),
1032 Keysym::dead_belowmacron => Some("̱".to_owned()),
1033 Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()),
1034 Keysym::dead_belowtilde => Some("̰".to_owned()),
1035 Keysym::dead_belowbreve => Some("̮".to_owned()),
1036 Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
1037 Keysym::dead_invertedbreve => Some("̯".to_owned()),
1038 Keysym::dead_belowcomma => Some("̦".to_owned()),
1039 Keysym::dead_currency => None,
1040 Keysym::dead_lowline => None,
1041 Keysym::dead_aboveverticalline => None,
1042 Keysym::dead_belowverticalline => None,
1043 Keysym::dead_longsolidusoverlay => None,
1044 Keysym::dead_a => None,
1045 Keysym::dead_A => None,
1046 Keysym::dead_e => None,
1047 Keysym::dead_E => None,
1048 Keysym::dead_i => None,
1049 Keysym::dead_I => None,
1050 Keysym::dead_o => None,
1051 Keysym::dead_O => None,
1052 Keysym::dead_u => None,
1053 Keysym::dead_U => None,
1054 Keysym::dead_small_schwa => Some("ə".to_owned()),
1055 Keysym::dead_capital_schwa => Some("Ə".to_owned()),
1056 Keysym::dead_greek => None,
1057 _ => None,
1058 }
1059}
1060#[cfg(any(feature = "wayland", feature = "x11"))]
1061pub(super) fn modifiers_from_xkb(keymap_state: &State) -> gpui::Modifiers {
1062 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
1063 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
1064 let control = keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
1065 let platform = keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
1066 gpui::Modifiers {
1067 shift,
1068 alt,
1069 control,
1070 platform,
1071 function: false,
1072 }
1073}
1074
1075#[cfg(any(feature = "wayland", feature = "x11"))]
1076pub(super) fn capslock_from_xkb(keymap_state: &State) -> gpui::Capslock {
1077 let on = keymap_state.mod_name_is_active(xkb::MOD_NAME_CAPS, xkb::STATE_MODS_EFFECTIVE);
1078 gpui::Capslock { on }
1079}
1080
1081#[cfg(test)]
1082mod tests {
1083 use super::*;
1084 use gpui::{Point, px};
1085
1086 #[test]
1087 fn test_is_within_click_distance() {
1088 let zero = Point::new(px(0.0), px(0.0));
1089 assert!(is_within_click_distance(zero, Point::new(px(5.0), px(5.0))));
1090 assert!(is_within_click_distance(
1091 zero,
1092 Point::new(px(-4.9), px(5.0))
1093 ));
1094 assert!(is_within_click_distance(
1095 Point::new(px(3.0), px(2.0)),
1096 Point::new(px(-2.0), px(-2.0))
1097 ));
1098 assert!(!is_within_click_distance(
1099 zero,
1100 Point::new(px(5.0), px(5.1))
1101 ),);
1102 }
1103}