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