1use std::{
2 env,
3 panic::AssertUnwindSafe,
4 path::{Path, PathBuf},
5 process::Command,
6 rc::Rc,
7 sync::Arc,
8};
9#[cfg(any(feature = "wayland", feature = "x11"))]
10use std::{
11 ffi::OsString,
12 fs::File,
13 io::Read as _,
14 os::fd::{AsFd, AsRawFd, FromRawFd},
15 time::Duration,
16};
17
18use anyhow::{anyhow, Context as _};
19use async_task::Runnable;
20use calloop::{channel::Channel, LoopSignal};
21use futures::{channel::oneshot, future::FutureExt};
22use util::ResultExt as _;
23#[cfg(any(feature = "wayland", feature = "x11"))]
24use xkbcommon::xkb::{self, Keycode, Keysym, State};
25
26use crate::{
27 px, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
28 ForegroundExecutor, Keymap, LinuxDispatcher, Menu, MenuItem, OwnedMenu, PathPromptOptions,
29 Pixels, Platform, PlatformDisplay, PlatformTextSystem, PlatformWindow, Point, Result,
30 ScreenCaptureSource, Task, WindowAppearance, WindowParams,
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) -> String;
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
55 fn open_window(
56 &self,
57 handle: AnyWindowHandle,
58 options: WindowParams,
59 ) -> anyhow::Result<Box<dyn PlatformWindow>>;
60 fn set_cursor_style(&self, style: CursorStyle);
61 fn open_uri(&self, uri: &str);
62 fn reveal_path(&self, path: PathBuf);
63 fn write_to_primary(&self, item: ClipboardItem);
64 fn write_to_clipboard(&self, item: ClipboardItem);
65 fn read_from_primary(&self) -> Option<ClipboardItem>;
66 fn read_from_clipboard(&self) -> Option<ClipboardItem>;
67 fn active_window(&self) -> Option<AnyWindowHandle>;
68 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>;
69 fn run(&self);
70}
71
72#[derive(Default)]
73pub(crate) struct PlatformHandlers {
74 pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
75 pub(crate) quit: Option<Box<dyn FnMut()>>,
76 pub(crate) reopen: Option<Box<dyn FnMut()>>,
77 pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
78 pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
79 pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
80 pub(crate) keyboard_layout_change: Option<Box<dyn FnMut()>>,
81}
82
83pub(crate) struct LinuxCommon {
84 pub(crate) background_executor: BackgroundExecutor,
85 pub(crate) foreground_executor: ForegroundExecutor,
86 pub(crate) text_system: Arc<dyn PlatformTextSystem>,
87 pub(crate) appearance: WindowAppearance,
88 pub(crate) auto_hide_scrollbars: bool,
89 pub(crate) callbacks: PlatformHandlers,
90 pub(crate) signal: LoopSignal,
91 pub(crate) menus: Vec<OwnedMenu>,
92}
93
94impl LinuxCommon {
95 pub fn new(signal: LoopSignal) -> (Self, Channel<Runnable>) {
96 let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
97
98 #[cfg(any(feature = "wayland", feature = "x11"))]
99 let text_system = Arc::new(crate::CosmicTextSystem::new());
100 #[cfg(not(any(feature = "wayland", feature = "x11")))]
101 let text_system = Arc::new(crate::NoopTextSystem::new());
102
103 let callbacks = PlatformHandlers::default();
104
105 let dispatcher = Arc::new(LinuxDispatcher::new(main_sender.clone()));
106
107 let background_executor = BackgroundExecutor::new(dispatcher.clone());
108
109 let common = LinuxCommon {
110 background_executor,
111 foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
112 text_system,
113 appearance: WindowAppearance::Light,
114 auto_hide_scrollbars: false,
115 callbacks,
116 signal,
117 menus: Vec::new(),
118 };
119
120 (common, main_receiver)
121 }
122}
123
124impl<P: LinuxClient + 'static> Platform for P {
125 fn background_executor(&self) -> BackgroundExecutor {
126 self.with_common(|common| common.background_executor.clone())
127 }
128
129 fn foreground_executor(&self) -> ForegroundExecutor {
130 self.with_common(|common| common.foreground_executor.clone())
131 }
132
133 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
134 self.with_common(|common| common.text_system.clone())
135 }
136
137 fn keyboard_layout(&self) -> String {
138 self.keyboard_layout()
139 }
140
141 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
142 self.with_common(|common| common.callbacks.keyboard_layout_change = Some(callback));
143 }
144
145 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
146 on_finish_launching();
147
148 LinuxClient::run(self);
149
150 let quit = self.with_common(|common| common.callbacks.quit.take());
151 if let Some(mut fun) = quit {
152 fun();
153 }
154 }
155
156 fn quit(&self) {
157 self.with_common(|common| common.signal.stop());
158 }
159
160 fn compositor_name(&self) -> &'static str {
161 self.compositor_name()
162 }
163
164 fn restart(&self, binary_path: Option<PathBuf>) {
165 use std::os::unix::process::CommandExt as _;
166
167 // get the process id of the current process
168 let app_pid = std::process::id().to_string();
169 // get the path to the executable
170 let app_path = if let Some(path) = binary_path {
171 path
172 } else {
173 match self.app_path() {
174 Ok(path) => path,
175 Err(err) => {
176 log::error!("Failed to get app path: {:?}", err);
177 return;
178 }
179 }
180 };
181
182 log::info!("Restarting process, using app path: {:?}", app_path);
183
184 // Script to wait for the current process to exit and then restart the app.
185 // We also wait for possibly open TCP sockets by the process to be closed,
186 // since on Linux it's not guaranteed that a process' resources have been
187 // cleaned up when `kill -0` returns.
188 let script = format!(
189 r#"
190 while kill -0 {pid} 2>/dev/null; do
191 sleep 0.1
192 done
193
194 while lsof -nP -iTCP -a -p {pid} 2>/dev/null; do
195 sleep 0.1
196 done
197
198 {app_path}
199 "#,
200 pid = app_pid,
201 app_path = app_path.display()
202 );
203
204 // execute the script using /bin/bash
205 let restart_process = Command::new("/bin/bash")
206 .arg("-c")
207 .arg(script)
208 .process_group(0)
209 .spawn();
210
211 match restart_process {
212 Ok(_) => self.quit(),
213 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
214 }
215 }
216
217 fn activate(&self, _ignoring_other_apps: bool) {
218 log::info!("activate is not implemented on Linux, ignoring the call")
219 }
220
221 fn hide(&self) {
222 log::info!("hide is not implemented on Linux, ignoring the call")
223 }
224
225 fn hide_other_apps(&self) {
226 log::info!("hide_other_apps is not implemented on Linux, ignoring the call")
227 }
228
229 fn unhide_other_apps(&self) {
230 log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")
231 }
232
233 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
234 self.primary_display()
235 }
236
237 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
238 self.displays()
239 }
240
241 fn screen_capture_sources(
242 &self,
243 ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
244 let (mut tx, rx) = oneshot::channel();
245 tx.send(Err(anyhow!("screen capture not implemented"))).ok();
246 rx
247 }
248
249 fn active_window(&self) -> Option<AnyWindowHandle> {
250 self.active_window()
251 }
252
253 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
254 self.window_stack()
255 }
256
257 fn open_window(
258 &self,
259 handle: AnyWindowHandle,
260 options: WindowParams,
261 ) -> anyhow::Result<Box<dyn PlatformWindow>> {
262 self.open_window(handle, options)
263 }
264
265 fn open_url(&self, url: &str) {
266 self.open_uri(url);
267 }
268
269 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
270 self.with_common(|common| common.callbacks.open_urls = Some(callback));
271 }
272
273 fn prompt_for_paths(
274 &self,
275 options: PathPromptOptions,
276 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
277 let (done_tx, done_rx) = oneshot::channel();
278
279 #[cfg(not(any(feature = "wayland", feature = "x11")))]
280 let _ = (done_tx.send(Ok(None)), options);
281
282 #[cfg(any(feature = "wayland", feature = "x11"))]
283 self.foreground_executor()
284 .spawn(async move {
285 let title = if options.directories {
286 "Open Folder"
287 } else {
288 "Open File"
289 };
290
291 let request = match ashpd::desktop::file_chooser::OpenFileRequest::default()
292 .modal(true)
293 .title(title)
294 .multiple(options.multiple)
295 .directory(options.directories)
296 .send()
297 .await
298 {
299 Ok(request) => request,
300 Err(err) => {
301 let result = match err {
302 ashpd::Error::PortalNotFound(_) => anyhow!(FILE_PICKER_PORTAL_MISSING),
303 err => err.into(),
304 };
305 let _ = done_tx.send(Err(result));
306 return;
307 }
308 };
309
310 let result = match request.response() {
311 Ok(response) => Ok(Some(
312 response
313 .uris()
314 .iter()
315 .filter_map(|uri| uri.to_file_path().ok())
316 .collect::<Vec<_>>(),
317 )),
318 Err(ashpd::Error::Response(_)) => Ok(None),
319 Err(e) => Err(e.into()),
320 };
321 let _ = done_tx.send(result);
322 })
323 .detach();
324 done_rx
325 }
326
327 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<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)), directory);
332
333 #[cfg(any(feature = "wayland", feature = "x11"))]
334 self.foreground_executor()
335 .spawn({
336 let directory = directory.to_owned();
337
338 async move {
339 let request = match ashpd::desktop::file_chooser::SaveFileRequest::default()
340 .modal(true)
341 .title("Save File")
342 .current_folder(directory)
343 .expect("pathbuf should not be nul terminated")
344 .send()
345 .await
346 {
347 Ok(request) => request,
348 Err(err) => {
349 let result = match err {
350 ashpd::Error::PortalNotFound(_) => {
351 anyhow!(FILE_PICKER_PORTAL_MISSING)
352 }
353 err => err.into(),
354 };
355 let _ = done_tx.send(Err(result));
356 return;
357 }
358 };
359
360 let result = match request.response() {
361 Ok(response) => Ok(response
362 .uris()
363 .first()
364 .and_then(|uri| uri.to_file_path().ok())),
365 Err(ashpd::Error::Response(_)) => Ok(None),
366 Err(e) => Err(e.into()),
367 };
368 let _ = done_tx.send(result);
369 }
370 })
371 .detach();
372
373 done_rx
374 }
375
376 fn reveal_path(&self, path: &Path) {
377 self.reveal_path(path.to_owned());
378 }
379
380 fn open_with_system(&self, path: &Path) {
381 let path = path.to_owned();
382 self.background_executor()
383 .spawn(async move {
384 let _ = std::process::Command::new("xdg-open")
385 .arg(path)
386 .spawn()
387 .context("invoking xdg-open")
388 .log_err();
389 })
390 .detach();
391 }
392
393 fn on_quit(&self, callback: Box<dyn FnMut()>) {
394 self.with_common(|common| {
395 common.callbacks.quit = Some(callback);
396 });
397 }
398
399 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
400 self.with_common(|common| {
401 common.callbacks.reopen = Some(callback);
402 });
403 }
404
405 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
406 self.with_common(|common| {
407 common.callbacks.app_menu_action = Some(callback);
408 });
409 }
410
411 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
412 self.with_common(|common| {
413 common.callbacks.will_open_app_menu = Some(callback);
414 });
415 }
416
417 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
418 self.with_common(|common| {
419 common.callbacks.validate_app_menu_command = Some(callback);
420 });
421 }
422
423 fn app_path(&self) -> Result<PathBuf> {
424 // get the path of the executable of the current process
425 let exe_path = env::current_exe()?;
426 Ok(exe_path)
427 }
428
429 fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
430 self.with_common(|common| {
431 common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
432 })
433 }
434
435 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
436 self.with_common(|common| Some(common.menus.clone()))
437 }
438
439 fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {}
440
441 fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
442 Err(anyhow::Error::msg(
443 "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
444 ))
445 }
446
447 fn set_cursor_style(&self, style: CursorStyle) {
448 self.set_cursor_style(style)
449 }
450
451 fn should_auto_hide_scrollbars(&self) -> bool {
452 self.with_common(|common| common.auto_hide_scrollbars)
453 }
454
455 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
456 let url = url.to_string();
457 let username = username.to_string();
458 let password = password.to_vec();
459 self.background_executor().spawn(async move {
460 let keyring = oo7::Keyring::new().await?;
461 keyring.unlock().await?;
462 keyring
463 .create_item(
464 KEYRING_LABEL,
465 &vec![("url", &url), ("username", &username)],
466 password,
467 true,
468 )
469 .await?;
470 Ok(())
471 })
472 }
473
474 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
475 let url = url.to_string();
476 self.background_executor().spawn(async move {
477 let keyring = oo7::Keyring::new().await?;
478 keyring.unlock().await?;
479
480 let items = keyring.search_items(&vec![("url", &url)]).await?;
481
482 for item in items.into_iter() {
483 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
484 let attributes = item.attributes().await?;
485 let username = attributes
486 .get("username")
487 .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
488 // oo7 panics if the retrieved secret can't be decrypted due to
489 // unexpected padding.
490 let secret = AssertUnwindSafe(item.secret())
491 .catch_unwind()
492 .await
493 .map_err(|_| anyhow!("oo7 panicked while trying to read credentials"))??;
494
495 // we lose the zeroizing capabilities at this boundary,
496 // a current limitation GPUI's credentials api
497 return Ok(Some((username.to_string(), secret.to_vec())));
498 } else {
499 continue;
500 }
501 }
502 Ok(None)
503 })
504 }
505
506 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
507 let url = url.to_string();
508 self.background_executor().spawn(async move {
509 let keyring = oo7::Keyring::new().await?;
510 keyring.unlock().await?;
511
512 let items = keyring.search_items(&vec![("url", &url)]).await?;
513
514 for item in items.into_iter() {
515 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
516 item.delete().await?;
517 return Ok(());
518 }
519 }
520
521 Ok(())
522 })
523 }
524
525 fn window_appearance(&self) -> WindowAppearance {
526 self.with_common(|common| common.appearance)
527 }
528
529 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
530 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
531 }
532
533 fn write_to_primary(&self, item: ClipboardItem) {
534 self.write_to_primary(item)
535 }
536
537 fn write_to_clipboard(&self, item: ClipboardItem) {
538 self.write_to_clipboard(item)
539 }
540
541 fn read_from_primary(&self) -> Option<ClipboardItem> {
542 self.read_from_primary()
543 }
544
545 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
546 self.read_from_clipboard()
547 }
548
549 fn add_recent_document(&self, _path: &Path) {}
550}
551
552#[cfg(any(feature = "wayland", feature = "x11"))]
553pub(super) fn open_uri_internal(
554 executor: BackgroundExecutor,
555 uri: &str,
556 activation_token: Option<String>,
557) {
558 if let Some(uri) = ashpd::url::Url::parse(uri).log_err() {
559 executor
560 .spawn(async move {
561 match ashpd::desktop::open_uri::OpenFileRequest::default()
562 .activation_token(activation_token.clone().map(ashpd::ActivationToken::from))
563 .send_uri(&uri)
564 .await
565 {
566 Ok(_) => return,
567 Err(e) => log::error!("Failed to open with dbus: {}", e),
568 }
569
570 for mut command in open::commands(uri.to_string()) {
571 if let Some(token) = activation_token.as_ref() {
572 command.env("XDG_ACTIVATION_TOKEN", token);
573 }
574 match command.spawn() {
575 Ok(_) => return,
576 Err(e) => {
577 log::error!("Failed to open with {:?}: {}", command.get_program(), e)
578 }
579 }
580 }
581 })
582 .detach();
583 }
584}
585
586#[cfg(any(feature = "x11", feature = "wayland"))]
587pub(super) fn reveal_path_internal(
588 executor: BackgroundExecutor,
589 path: PathBuf,
590 activation_token: Option<String>,
591) {
592 executor
593 .spawn(async move {
594 if let Some(dir) = File::open(path.clone()).log_err() {
595 match ashpd::desktop::open_uri::OpenDirectoryRequest::default()
596 .activation_token(activation_token.map(ashpd::ActivationToken::from))
597 .send(&dir.as_fd())
598 .await
599 {
600 Ok(_) => return,
601 Err(e) => log::error!("Failed to open with dbus: {}", e),
602 }
603 if path.is_dir() {
604 open::that_detached(path).log_err();
605 } else {
606 open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
607 }
608 }
609 })
610 .detach();
611}
612
613#[allow(unused)]
614pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
615 let diff = a - b;
616 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
617}
618
619#[cfg(any(feature = "wayland", feature = "x11"))]
620pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
621 let mut locales = Vec::default();
622 if let Some(locale) = env::var_os("LC_CTYPE") {
623 locales.push(locale);
624 }
625 locales.push(OsString::from("C"));
626 let mut state: Option<xkb::compose::State> = None;
627 for locale in locales {
628 if let Ok(table) =
629 xkb::compose::Table::new_from_locale(&cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
630 {
631 state = Some(xkb::compose::State::new(
632 &table,
633 xkb::compose::STATE_NO_FLAGS,
634 ));
635 break;
636 }
637 }
638 state
639}
640
641#[cfg(any(feature = "wayland", feature = "x11"))]
642pub(super) unsafe fn read_fd(mut fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
643 let mut file = File::from_raw_fd(fd.as_raw_fd());
644 let mut buffer = Vec::new();
645 file.read_to_end(&mut buffer)?;
646 Ok(buffer)
647}
648
649impl CursorStyle {
650 #[allow(unused)]
651 pub(super) fn to_icon_name(&self) -> String {
652 // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
653 // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
654 // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
655 match self {
656 CursorStyle::Arrow => "left_ptr",
657 CursorStyle::IBeam => "text",
658 CursorStyle::Crosshair => "crosshair",
659 CursorStyle::ClosedHand => "grabbing",
660 CursorStyle::OpenHand => "grab",
661 CursorStyle::PointingHand => "pointer",
662 CursorStyle::ResizeLeft => "w-resize",
663 CursorStyle::ResizeRight => "e-resize",
664 CursorStyle::ResizeLeftRight => "ew-resize",
665 CursorStyle::ResizeUp => "n-resize",
666 CursorStyle::ResizeDown => "s-resize",
667 CursorStyle::ResizeUpDown => "ns-resize",
668 CursorStyle::ResizeUpLeftDownRight => "nwse-resize",
669 CursorStyle::ResizeUpRightDownLeft => "nesw-resize",
670 CursorStyle::ResizeColumn => "col-resize",
671 CursorStyle::ResizeRow => "row-resize",
672 CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
673 CursorStyle::OperationNotAllowed => "not-allowed",
674 CursorStyle::DragLink => "alias",
675 CursorStyle::DragCopy => "copy",
676 CursorStyle::ContextualMenu => "context-menu",
677 }
678 .to_string()
679 }
680}
681
682#[cfg(any(feature = "wayland", feature = "x11"))]
683impl crate::Keystroke {
684 pub(super) fn from_xkb(
685 state: &State,
686 mut modifiers: crate::Modifiers,
687 keycode: Keycode,
688 ) -> Self {
689 let key_utf32 = state.key_get_utf32(keycode);
690 let key_utf8 = state.key_get_utf8(keycode);
691 let key_sym = state.key_get_one_sym(keycode);
692
693 let key = match key_sym {
694 Keysym::Return => "enter".to_owned(),
695 Keysym::Prior => "pageup".to_owned(),
696 Keysym::Next => "pagedown".to_owned(),
697 Keysym::ISO_Left_Tab => "tab".to_owned(),
698 Keysym::KP_Prior => "pageup".to_owned(),
699 Keysym::KP_Next => "pagedown".to_owned(),
700 Keysym::XF86_Back => "back".to_owned(),
701 Keysym::XF86_Forward => "forward".to_owned(),
702
703 Keysym::comma => ",".to_owned(),
704 Keysym::period => ".".to_owned(),
705 Keysym::less => "<".to_owned(),
706 Keysym::greater => ">".to_owned(),
707 Keysym::slash => "/".to_owned(),
708 Keysym::question => "?".to_owned(),
709
710 Keysym::semicolon => ";".to_owned(),
711 Keysym::colon => ":".to_owned(),
712 Keysym::apostrophe => "'".to_owned(),
713 Keysym::quotedbl => "\"".to_owned(),
714
715 Keysym::bracketleft => "[".to_owned(),
716 Keysym::braceleft => "{".to_owned(),
717 Keysym::bracketright => "]".to_owned(),
718 Keysym::braceright => "}".to_owned(),
719 Keysym::backslash => "\\".to_owned(),
720 Keysym::bar => "|".to_owned(),
721
722 Keysym::grave => "`".to_owned(),
723 Keysym::asciitilde => "~".to_owned(),
724 Keysym::exclam => "!".to_owned(),
725 Keysym::at => "@".to_owned(),
726 Keysym::numbersign => "#".to_owned(),
727 Keysym::dollar => "$".to_owned(),
728 Keysym::percent => "%".to_owned(),
729 Keysym::asciicircum => "^".to_owned(),
730 Keysym::ampersand => "&".to_owned(),
731 Keysym::asterisk => "*".to_owned(),
732 Keysym::parenleft => "(".to_owned(),
733 Keysym::parenright => ")".to_owned(),
734 Keysym::minus => "-".to_owned(),
735 Keysym::underscore => "_".to_owned(),
736 Keysym::equal => "=".to_owned(),
737 Keysym::plus => "+".to_owned(),
738
739 _ => {
740 let name = xkb::keysym_get_name(key_sym).to_lowercase();
741 if key_sym.is_keypad_key() {
742 name.replace("kp_", "")
743 } else {
744 name
745 }
746 }
747 };
748
749 if modifiers.shift {
750 // we only include the shift for upper-case letters by convention,
751 // so don't include for numbers and symbols, but do include for
752 // tab/enter, etc.
753 if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() {
754 modifiers.shift = false;
755 }
756 }
757
758 // Ignore control characters (and DEL) for the purposes of key_char
759 let key_char =
760 (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
761
762 Self {
763 modifiers,
764 key,
765 key_char,
766 }
767 }
768
769 /**
770 * Returns which symbol the dead key represents
771 * https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux
772 */
773 pub fn underlying_dead_key(keysym: Keysym) -> Option<String> {
774 match keysym {
775 Keysym::dead_grave => Some("`".to_owned()),
776 Keysym::dead_acute => Some("´".to_owned()),
777 Keysym::dead_circumflex => Some("^".to_owned()),
778 Keysym::dead_tilde => Some("~".to_owned()),
779 Keysym::dead_macron => Some("¯".to_owned()),
780 Keysym::dead_breve => Some("˘".to_owned()),
781 Keysym::dead_abovedot => Some("˙".to_owned()),
782 Keysym::dead_diaeresis => Some("¨".to_owned()),
783 Keysym::dead_abovering => Some("˚".to_owned()),
784 Keysym::dead_doubleacute => Some("˝".to_owned()),
785 Keysym::dead_caron => Some("ˇ".to_owned()),
786 Keysym::dead_cedilla => Some("¸".to_owned()),
787 Keysym::dead_ogonek => Some("˛".to_owned()),
788 Keysym::dead_iota => Some("ͅ".to_owned()),
789 Keysym::dead_voiced_sound => Some("゙".to_owned()),
790 Keysym::dead_semivoiced_sound => Some("゚".to_owned()),
791 Keysym::dead_belowdot => Some("̣̣".to_owned()),
792 Keysym::dead_hook => Some("̡".to_owned()),
793 Keysym::dead_horn => Some("̛".to_owned()),
794 Keysym::dead_stroke => Some("̶̶".to_owned()),
795 Keysym::dead_abovecomma => Some("̓̓".to_owned()),
796 Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
797 Keysym::dead_doublegrave => Some("̏".to_owned()),
798 Keysym::dead_belowring => Some("˳".to_owned()),
799 Keysym::dead_belowmacron => Some("̱".to_owned()),
800 Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()),
801 Keysym::dead_belowtilde => Some("̰".to_owned()),
802 Keysym::dead_belowbreve => Some("̮".to_owned()),
803 Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
804 Keysym::dead_invertedbreve => Some("̯".to_owned()),
805 Keysym::dead_belowcomma => Some("̦".to_owned()),
806 Keysym::dead_currency => None,
807 Keysym::dead_lowline => None,
808 Keysym::dead_aboveverticalline => None,
809 Keysym::dead_belowverticalline => None,
810 Keysym::dead_longsolidusoverlay => None,
811 Keysym::dead_a => None,
812 Keysym::dead_A => None,
813 Keysym::dead_e => None,
814 Keysym::dead_E => None,
815 Keysym::dead_i => None,
816 Keysym::dead_I => None,
817 Keysym::dead_o => None,
818 Keysym::dead_O => None,
819 Keysym::dead_u => None,
820 Keysym::dead_U => None,
821 Keysym::dead_small_schwa => Some("ə".to_owned()),
822 Keysym::dead_capital_schwa => Some("Ə".to_owned()),
823 Keysym::dead_greek => None,
824 _ => None,
825 }
826 }
827}
828
829#[cfg(any(feature = "wayland", feature = "x11"))]
830impl crate::Modifiers {
831 pub(super) fn from_xkb(keymap_state: &State) -> Self {
832 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
833 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
834 let control =
835 keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
836 let platform =
837 keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
838 Self {
839 shift,
840 alt,
841 control,
842 platform,
843 function: false,
844 }
845 }
846}
847
848#[cfg(test)]
849mod tests {
850 use super::*;
851 use crate::{px, Point};
852
853 #[test]
854 fn test_is_within_click_distance() {
855 let zero = Point::new(px(0.0), px(0.0));
856 assert_eq!(
857 is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
858 true
859 );
860 assert_eq!(
861 is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
862 true
863 );
864 assert_eq!(
865 is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
866 true
867 );
868 assert_eq!(
869 is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
870 false
871 );
872 }
873}