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