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