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: &ashpd::Uri| url::Url::parse(uri.as_str()).ok())
368 .filter_map(|uri: url::Url| uri.to_file_path().ok())
369 .collect::<Vec<_>>(),
370 )),
371 Err(ashpd::Error::Response(_)) => Ok(None),
372 Err(e) => Err(e.into()),
373 };
374 let _ = done_tx.send(result);
375 })
376 .detach();
377 done_rx
378 }
379
380 fn prompt_for_new_path(
381 &self,
382 directory: &Path,
383 suggested_name: Option<&str>,
384 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
385 let (done_tx, done_rx) = oneshot::channel();
386
387 #[cfg(not(any(feature = "wayland", feature = "x11")))]
388 let _ = (done_tx.send(Ok(None)), directory, suggested_name);
389
390 #[cfg(any(feature = "wayland", feature = "x11"))]
391 let identifier = self.inner.window_identifier();
392
393 #[cfg(any(feature = "wayland", feature = "x11"))]
394 self.foreground_executor()
395 .spawn({
396 let directory = directory.to_owned();
397 let suggested_name = suggested_name.map(|s| s.to_owned());
398
399 async move {
400 let mut request_builder =
401 ashpd::desktop::file_chooser::SaveFileRequest::default()
402 .identifier(identifier.await)
403 .modal(true)
404 .title("Save File")
405 .current_folder(directory)
406 .expect("pathbuf should not be nul terminated");
407
408 if let Some(suggested_name) = suggested_name {
409 request_builder = request_builder.current_name(suggested_name.as_str());
410 }
411
412 let request = match request_builder.send().await {
413 Ok(request) => request,
414 Err(err) => {
415 let result = match err {
416 ashpd::Error::PortalNotFound(_) => {
417 anyhow!(FILE_PICKER_PORTAL_MISSING)
418 }
419 err => err.into(),
420 };
421 let _ = done_tx.send(Err(result));
422 return;
423 }
424 };
425
426 let result = match request.response() {
427 Ok(response) => Ok(response
428 .uris()
429 .first()
430 .and_then(|uri: &ashpd::Uri| url::Url::parse(uri.as_str()).ok())
431 .and_then(|uri: url::Url| uri.to_file_path().ok())),
432 Err(ashpd::Error::Response(_)) => Ok(None),
433 Err(e) => Err(e.into()),
434 };
435 let _ = done_tx.send(result);
436 }
437 })
438 .detach();
439
440 done_rx
441 }
442
443 fn can_select_mixed_files_and_dirs(&self) -> bool {
444 // org.freedesktop.portal.FileChooser only supports "pick files" and "pick directories".
445 false
446 }
447
448 fn reveal_path(&self, path: &Path) {
449 self.inner.reveal_path(path.to_owned());
450 }
451
452 fn open_with_system(&self, path: &Path) {
453 let path = path.to_owned();
454 self.background_executor()
455 .spawn(async move {
456 let _ = new_command("xdg-open")
457 .arg(path)
458 .spawn()
459 .context("invoking xdg-open")
460 .log_err()?
461 .status()
462 .await
463 .log_err()?;
464 Some(())
465 })
466 .detach();
467 }
468
469 fn on_quit(&self, callback: Box<dyn FnMut()>) {
470 self.inner.with_common(|common| {
471 common.callbacks.quit = Some(callback);
472 });
473 }
474
475 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
476 self.inner.with_common(|common| {
477 common.callbacks.reopen = Some(callback);
478 });
479 }
480
481 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
482 self.inner.with_common(|common| {
483 common.callbacks.app_menu_action = Some(callback);
484 });
485 }
486
487 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
488 self.inner.with_common(|common| {
489 common.callbacks.will_open_app_menu = Some(callback);
490 });
491 }
492
493 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
494 self.inner.with_common(|common| {
495 common.callbacks.validate_app_menu_command = Some(callback);
496 });
497 }
498
499 fn app_path(&self) -> Result<PathBuf> {
500 // get the path of the executable of the current process
501 let app_path = env::current_exe()?;
502 Ok(app_path)
503 }
504
505 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
506 self.inner.with_common(|common| {
507 common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
508 })
509 }
510
511 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
512 self.inner.with_common(|common| Some(common.menus.clone()))
513 }
514
515 fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {
516 // todo(linux)
517 }
518
519 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
520 Err(anyhow::Error::msg(
521 "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
522 ))
523 }
524
525 fn set_cursor_style(&self, style: CursorStyle) {
526 self.inner.set_cursor_style(style)
527 }
528
529 fn should_auto_hide_scrollbars(&self) -> bool {
530 self.inner.with_common(|common| common.auto_hide_scrollbars)
531 }
532
533 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
534 let url = url.to_string();
535 let username = username.to_string();
536 let password = password.to_vec();
537 self.background_executor().spawn(async move {
538 let keyring = oo7::Keyring::new().await?;
539 keyring.unlock().await?;
540 keyring
541 .create_item(
542 KEYRING_LABEL,
543 &vec![("url", &url), ("username", &username)],
544 password,
545 true,
546 )
547 .await?;
548 Ok(())
549 })
550 }
551
552 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
553 let url = url.to_string();
554 self.background_executor().spawn(async move {
555 let keyring = oo7::Keyring::new().await?;
556 keyring.unlock().await?;
557
558 let items = keyring.search_items(&vec![("url", &url)]).await?;
559
560 for item in items.into_iter() {
561 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
562 let attributes = item.attributes().await?;
563 let username = attributes
564 .get("username")
565 .context("Cannot find username in stored credentials")?;
566 item.unlock().await?;
567 let secret = item.secret().await?;
568
569 // we lose the zeroizing capabilities at this boundary,
570 // a current limitation GPUI's credentials api
571 return Ok(Some((username.to_string(), secret.to_vec())));
572 } else {
573 continue;
574 }
575 }
576 Ok(None)
577 })
578 }
579
580 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
581 let url = url.to_string();
582 self.background_executor().spawn(async move {
583 let keyring = oo7::Keyring::new().await?;
584 keyring.unlock().await?;
585
586 let items = keyring.search_items(&vec![("url", &url)]).await?;
587
588 for item in items.into_iter() {
589 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
590 item.delete().await?;
591 return Ok(());
592 }
593 }
594
595 Ok(())
596 })
597 }
598
599 fn window_appearance(&self) -> WindowAppearance {
600 self.inner.with_common(|common| common.appearance)
601 }
602
603 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
604 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
605 }
606
607 fn write_to_primary(&self, item: ClipboardItem) {
608 self.inner.write_to_primary(item)
609 }
610
611 fn write_to_clipboard(&self, item: ClipboardItem) {
612 self.inner.write_to_clipboard(item)
613 }
614
615 fn read_from_primary(&self) -> Option<ClipboardItem> {
616 self.inner.read_from_primary()
617 }
618
619 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
620 self.inner.read_from_clipboard()
621 }
622
623 fn add_recent_document(&self, _path: &Path) {}
624}
625
626#[cfg(any(feature = "wayland", feature = "x11"))]
627pub(super) fn open_uri_internal(
628 executor: BackgroundExecutor,
629 uri: &str,
630 activation_token: Option<String>,
631) {
632 if let Some(uri) = ashpd::Uri::parse(uri).log_err() {
633 executor
634 .spawn(async move {
635 match ashpd::desktop::open_uri::OpenFileRequest::default()
636 .activation_token(activation_token.clone().map(ashpd::ActivationToken::from))
637 .send_uri(&uri)
638 .await
639 .and_then(|e| e.response())
640 {
641 Ok(()) => return,
642 Err(e) => log::error!("Failed to open with dbus: {}", e),
643 }
644
645 for mut command in open::commands(uri.to_string()) {
646 if let Some(token) = activation_token.as_ref() {
647 command.env("XDG_ACTIVATION_TOKEN", token);
648 }
649 let program = format!("{:?}", command.get_program());
650 match smol::process::Command::from(command).spawn() {
651 Ok(mut cmd) => {
652 cmd.status().await.log_err();
653 return;
654 }
655 Err(e) => {
656 log::error!("Failed to open with {}: {}", program, e)
657 }
658 }
659 }
660 })
661 .detach();
662 }
663}
664
665#[cfg(any(feature = "x11", feature = "wayland"))]
666pub(super) fn reveal_path_internal(
667 executor: BackgroundExecutor,
668 path: PathBuf,
669 activation_token: Option<String>,
670) {
671 executor
672 .spawn(async move {
673 if let Some(dir) = File::open(path.clone()).log_err() {
674 match ashpd::desktop::open_uri::OpenDirectoryRequest::default()
675 .activation_token(activation_token.map(ashpd::ActivationToken::from))
676 .send(&dir.as_fd())
677 .await
678 {
679 Ok(_) => return,
680 Err(e) => log::error!("Failed to open with dbus: {}", e),
681 }
682 if path.is_dir() {
683 open::that_detached(path).log_err();
684 } else {
685 open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
686 }
687 }
688 })
689 .detach();
690}
691
692#[cfg(any(feature = "wayland", feature = "x11"))]
693pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
694 let diff = a - b;
695 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
696}
697
698#[cfg(any(feature = "wayland", feature = "x11"))]
699pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
700 let mut locales = Vec::default();
701 if let Some(locale) = env::var_os("LC_CTYPE") {
702 locales.push(locale);
703 }
704 locales.push(OsString::from("C"));
705 let mut state: Option<xkb::compose::State> = None;
706 for locale in locales {
707 if let Ok(table) =
708 xkb::compose::Table::new_from_locale(cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
709 {
710 state = Some(xkb::compose::State::new(
711 &table,
712 xkb::compose::STATE_NO_FLAGS,
713 ));
714 break;
715 }
716 }
717 state
718}
719
720#[cfg(any(feature = "wayland", feature = "x11"))]
721pub(super) unsafe fn read_fd(fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
722 let mut file = unsafe { File::from_raw_fd(fd.into_raw_fd()) };
723 let mut buffer = Vec::new();
724 file.read_to_end(&mut buffer)?;
725 Ok(buffer)
726}
727
728#[cfg(any(feature = "wayland", feature = "x11"))]
729pub(super) const DEFAULT_CURSOR_ICON_NAME: &str = "left_ptr";
730
731#[cfg(any(feature = "wayland", feature = "x11"))]
732pub(super) fn cursor_style_to_icon_names(style: CursorStyle) -> &'static [&'static str] {
733 // Based on cursor names from chromium:
734 // https://github.com/chromium/chromium/blob/d3069cf9c973dc3627fa75f64085c6a86c8f41bf/ui/base/cursor/cursor_factory.cc#L113
735 match style {
736 CursorStyle::Arrow => &[DEFAULT_CURSOR_ICON_NAME],
737 CursorStyle::IBeam => &["text", "xterm"],
738 CursorStyle::Crosshair => &["crosshair", "cross"],
739 CursorStyle::ClosedHand => &["closedhand", "grabbing", "hand2"],
740 CursorStyle::OpenHand => &["openhand", "grab", "hand1"],
741 CursorStyle::PointingHand => &["pointer", "hand", "hand2"],
742 CursorStyle::ResizeLeft => &["w-resize", "left_side"],
743 CursorStyle::ResizeRight => &["e-resize", "right_side"],
744 CursorStyle::ResizeLeftRight => &["ew-resize", "sb_h_double_arrow"],
745 CursorStyle::ResizeUp => &["n-resize", "top_side"],
746 CursorStyle::ResizeDown => &["s-resize", "bottom_side"],
747 CursorStyle::ResizeUpDown => &["sb_v_double_arrow", "ns-resize"],
748 CursorStyle::ResizeUpLeftDownRight => &["size_fdiag", "bd_double_arrow", "nwse-resize"],
749 CursorStyle::ResizeUpRightDownLeft => &["size_bdiag", "nesw-resize", "fd_double_arrow"],
750 CursorStyle::ResizeColumn => &["col-resize", "sb_h_double_arrow"],
751 CursorStyle::ResizeRow => &["row-resize", "sb_v_double_arrow"],
752 CursorStyle::IBeamCursorForVerticalLayout => &["vertical-text"],
753 CursorStyle::OperationNotAllowed => &["not-allowed", "crossed_circle"],
754 CursorStyle::DragLink => &["alias"],
755 CursorStyle::DragCopy => &["copy"],
756 CursorStyle::ContextualMenu => &["context-menu"],
757 CursorStyle::None => {
758 #[cfg(debug_assertions)]
759 panic!("CursorStyle::None should be handled separately in the client");
760 #[cfg(not(debug_assertions))]
761 &[DEFAULT_CURSOR_ICON_NAME]
762 }
763 }
764}
765
766#[cfg(any(feature = "wayland", feature = "x11"))]
767pub(super) fn log_cursor_icon_warning(message: impl std::fmt::Display) {
768 if let Ok(xcursor_path) = env::var("XCURSOR_PATH") {
769 log::warn!(
770 "{:#}\ncursor icon loading may be failing if XCURSOR_PATH environment variable is invalid. \
771 XCURSOR_PATH overrides the default icon search. Its current value is '{}'",
772 message,
773 xcursor_path
774 );
775 } else {
776 log::warn!("{:#}", message);
777 }
778}
779
780#[cfg(any(feature = "wayland", feature = "x11"))]
781fn guess_ascii(keycode: Keycode, shift: bool) -> Option<char> {
782 let c = match (keycode.raw(), shift) {
783 (24, _) => 'q',
784 (25, _) => 'w',
785 (26, _) => 'e',
786 (27, _) => 'r',
787 (28, _) => 't',
788 (29, _) => 'y',
789 (30, _) => 'u',
790 (31, _) => 'i',
791 (32, _) => 'o',
792 (33, _) => 'p',
793 (34, false) => '[',
794 (34, true) => '{',
795 (35, false) => ']',
796 (35, true) => '}',
797 (38, _) => 'a',
798 (39, _) => 's',
799 (40, _) => 'd',
800 (41, _) => 'f',
801 (42, _) => 'g',
802 (43, _) => 'h',
803 (44, _) => 'j',
804 (45, _) => 'k',
805 (46, _) => 'l',
806 (47, false) => ';',
807 (47, true) => ':',
808 (48, false) => '\'',
809 (48, true) => '"',
810 (49, false) => '`',
811 (49, true) => '~',
812 (51, false) => '\\',
813 (51, true) => '|',
814 (52, _) => 'z',
815 (53, _) => 'x',
816 (54, _) => 'c',
817 (55, _) => 'v',
818 (56, _) => 'b',
819 (57, _) => 'n',
820 (58, _) => 'm',
821 (59, false) => ',',
822 (59, true) => '>',
823 (60, false) => '.',
824 (60, true) => '<',
825 (61, false) => '/',
826 (61, true) => '?',
827
828 _ => return None,
829 };
830
831 Some(c)
832}
833
834#[cfg(any(feature = "wayland", feature = "x11"))]
835pub(super) fn keystroke_from_xkb(
836 state: &State,
837 mut modifiers: gpui::Modifiers,
838 keycode: Keycode,
839) -> gpui::Keystroke {
840 let key_utf32 = state.key_get_utf32(keycode);
841 let key_utf8 = state.key_get_utf8(keycode);
842 let key_sym = state.key_get_one_sym(keycode);
843
844 let key = match key_sym {
845 Keysym::Return => "enter".to_owned(),
846 Keysym::Prior => "pageup".to_owned(),
847 Keysym::Next => "pagedown".to_owned(),
848 Keysym::ISO_Left_Tab => "tab".to_owned(),
849 Keysym::KP_Prior => "pageup".to_owned(),
850 Keysym::KP_Next => "pagedown".to_owned(),
851 Keysym::XF86_Back => "back".to_owned(),
852 Keysym::XF86_Forward => "forward".to_owned(),
853 Keysym::XF86_Cut => "cut".to_owned(),
854 Keysym::XF86_Copy => "copy".to_owned(),
855 Keysym::XF86_Paste => "paste".to_owned(),
856 Keysym::XF86_New => "new".to_owned(),
857 Keysym::XF86_Open => "open".to_owned(),
858 Keysym::XF86_Save => "save".to_owned(),
859
860 Keysym::comma => ",".to_owned(),
861 Keysym::period => ".".to_owned(),
862 Keysym::less => "<".to_owned(),
863 Keysym::greater => ">".to_owned(),
864 Keysym::slash => "/".to_owned(),
865 Keysym::question => "?".to_owned(),
866
867 Keysym::semicolon => ";".to_owned(),
868 Keysym::colon => ":".to_owned(),
869 Keysym::apostrophe => "'".to_owned(),
870 Keysym::quotedbl => "\"".to_owned(),
871
872 Keysym::bracketleft => "[".to_owned(),
873 Keysym::braceleft => "{".to_owned(),
874 Keysym::bracketright => "]".to_owned(),
875 Keysym::braceright => "}".to_owned(),
876 Keysym::backslash => "\\".to_owned(),
877 Keysym::bar => "|".to_owned(),
878
879 Keysym::grave => "`".to_owned(),
880 Keysym::asciitilde => "~".to_owned(),
881 Keysym::exclam => "!".to_owned(),
882 Keysym::at => "@".to_owned(),
883 Keysym::numbersign => "#".to_owned(),
884 Keysym::dollar => "$".to_owned(),
885 Keysym::percent => "%".to_owned(),
886 Keysym::asciicircum => "^".to_owned(),
887 Keysym::ampersand => "&".to_owned(),
888 Keysym::asterisk => "*".to_owned(),
889 Keysym::parenleft => "(".to_owned(),
890 Keysym::parenright => ")".to_owned(),
891 Keysym::minus => "-".to_owned(),
892 Keysym::underscore => "_".to_owned(),
893 Keysym::equal => "=".to_owned(),
894 Keysym::plus => "+".to_owned(),
895 Keysym::space => "space".to_owned(),
896 Keysym::BackSpace => "backspace".to_owned(),
897 Keysym::Tab => "tab".to_owned(),
898 Keysym::Delete => "delete".to_owned(),
899 Keysym::Escape => "escape".to_owned(),
900
901 Keysym::Left => "left".to_owned(),
902 Keysym::Right => "right".to_owned(),
903 Keysym::Up => "up".to_owned(),
904 Keysym::Down => "down".to_owned(),
905 Keysym::Home => "home".to_owned(),
906 Keysym::End => "end".to_owned(),
907 Keysym::Insert => "insert".to_owned(),
908
909 _ => {
910 let name = xkb::keysym_get_name(key_sym).to_lowercase();
911 if key_sym.is_keypad_key() {
912 name.replace("kp_", "")
913 } else if let Some(key) = key_utf8.chars().next()
914 && key_utf8.len() == 1
915 && key.is_ascii()
916 {
917 if key.is_ascii_graphic() {
918 key_utf8.to_lowercase()
919 // map ctrl-a to `a`
920 // ctrl-0..9 may emit control codes like ctrl-[, but
921 // we don't want to map them to `[`
922 } else if key_utf32 <= 0x1f
923 && !name.chars().next().is_some_and(|c| c.is_ascii_digit())
924 {
925 ((key_utf32 as u8 + 0x40) as char)
926 .to_ascii_lowercase()
927 .to_string()
928 } else {
929 name
930 }
931 } else if let Some(key_en) = guess_ascii(keycode, modifiers.shift) {
932 String::from(key_en)
933 } else {
934 name
935 }
936 }
937 };
938
939 if modifiers.shift {
940 // we only include the shift for upper-case letters by convention,
941 // so don't include for numbers and symbols, but do include for
942 // tab/enter, etc.
943 if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() {
944 modifiers.shift = false;
945 }
946 }
947
948 // Ignore control characters (and DEL) for the purposes of key_char
949 let key_char =
950 (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
951
952 gpui::Keystroke {
953 modifiers,
954 key,
955 key_char,
956 }
957}
958
959/**
960 * Returns which symbol the dead key represents
961 * <https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux>
962 */
963#[cfg(any(feature = "wayland", feature = "x11"))]
964pub fn keystroke_underlying_dead_key(keysym: Keysym) -> Option<String> {
965 match keysym {
966 Keysym::dead_grave => Some("`".to_owned()),
967 Keysym::dead_acute => Some("´".to_owned()),
968 Keysym::dead_circumflex => Some("^".to_owned()),
969 Keysym::dead_tilde => Some("~".to_owned()),
970 Keysym::dead_macron => Some("¯".to_owned()),
971 Keysym::dead_breve => Some("˘".to_owned()),
972 Keysym::dead_abovedot => Some("˙".to_owned()),
973 Keysym::dead_diaeresis => Some("¨".to_owned()),
974 Keysym::dead_abovering => Some("˚".to_owned()),
975 Keysym::dead_doubleacute => Some("˝".to_owned()),
976 Keysym::dead_caron => Some("ˇ".to_owned()),
977 Keysym::dead_cedilla => Some("¸".to_owned()),
978 Keysym::dead_ogonek => Some("˛".to_owned()),
979 Keysym::dead_iota => Some("ͅ".to_owned()),
980 Keysym::dead_voiced_sound => Some("゙".to_owned()),
981 Keysym::dead_semivoiced_sound => Some("゚".to_owned()),
982 Keysym::dead_belowdot => Some("̣̣".to_owned()),
983 Keysym::dead_hook => Some("̡".to_owned()),
984 Keysym::dead_horn => Some("̛".to_owned()),
985 Keysym::dead_stroke => Some("̶̶".to_owned()),
986 Keysym::dead_abovecomma => Some("̓̓".to_owned()),
987 Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
988 Keysym::dead_doublegrave => Some("̏".to_owned()),
989 Keysym::dead_belowring => Some("˳".to_owned()),
990 Keysym::dead_belowmacron => Some("̱".to_owned()),
991 Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()),
992 Keysym::dead_belowtilde => Some("̰".to_owned()),
993 Keysym::dead_belowbreve => Some("̮".to_owned()),
994 Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
995 Keysym::dead_invertedbreve => Some("̯".to_owned()),
996 Keysym::dead_belowcomma => Some("̦".to_owned()),
997 Keysym::dead_currency => None,
998 Keysym::dead_lowline => None,
999 Keysym::dead_aboveverticalline => None,
1000 Keysym::dead_belowverticalline => None,
1001 Keysym::dead_longsolidusoverlay => None,
1002 Keysym::dead_a => None,
1003 Keysym::dead_A => None,
1004 Keysym::dead_e => None,
1005 Keysym::dead_E => None,
1006 Keysym::dead_i => None,
1007 Keysym::dead_I => None,
1008 Keysym::dead_o => None,
1009 Keysym::dead_O => None,
1010 Keysym::dead_u => None,
1011 Keysym::dead_U => None,
1012 Keysym::dead_small_schwa => Some("ə".to_owned()),
1013 Keysym::dead_capital_schwa => Some("Ə".to_owned()),
1014 Keysym::dead_greek => None,
1015 _ => None,
1016 }
1017}
1018#[cfg(any(feature = "wayland", feature = "x11"))]
1019pub(super) fn modifiers_from_xkb(keymap_state: &State) -> gpui::Modifiers {
1020 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
1021 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
1022 let control = keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
1023 let platform = keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
1024 gpui::Modifiers {
1025 shift,
1026 alt,
1027 control,
1028 platform,
1029 function: false,
1030 }
1031}
1032
1033#[cfg(any(feature = "wayland", feature = "x11"))]
1034pub(super) fn capslock_from_xkb(keymap_state: &State) -> gpui::Capslock {
1035 let on = keymap_state.mod_name_is_active(xkb::MOD_NAME_CAPS, xkb::STATE_MODS_EFFECTIVE);
1036 gpui::Capslock { on }
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041 use super::*;
1042 use gpui::{Point, px};
1043
1044 #[test]
1045 fn test_is_within_click_distance() {
1046 let zero = Point::new(px(0.0), px(0.0));
1047 assert!(is_within_click_distance(zero, Point::new(px(5.0), px(5.0))));
1048 assert!(is_within_click_distance(
1049 zero,
1050 Point::new(px(-4.9), px(5.0))
1051 ));
1052 assert!(is_within_click_distance(
1053 Point::new(px(3.0), px(2.0)),
1054 Point::new(px(-2.0), px(-2.0))
1055 ));
1056 assert!(!is_within_click_distance(
1057 zero,
1058 Point::new(px(5.0), px(5.1))
1059 ),);
1060 }
1061}