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