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