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::{AssertUnwindSafe, 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, future::FutureExt};
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 // oo7 panics if the retrieved secret can't be decrypted due to
485 // unexpected padding.
486 let secret = AssertUnwindSafe(item.secret())
487 .catch_unwind()
488 .await
489 .map_err(|_| anyhow!("oo7 panicked while trying to read credentials"))??;
490
491 // we lose the zeroizing capabilities at this boundary,
492 // a current limitation GPUI's credentials api
493 return Ok(Some((username.to_string(), secret.to_vec())));
494 } else {
495 continue;
496 }
497 }
498 Ok(None)
499 })
500 }
501
502 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
503 let url = url.to_string();
504 self.background_executor().spawn(async move {
505 let keyring = oo7::Keyring::new().await?;
506 keyring.unlock().await?;
507
508 let items = keyring.search_items(&vec![("url", &url)]).await?;
509
510 for item in items.into_iter() {
511 if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
512 item.delete().await?;
513 return Ok(());
514 }
515 }
516
517 Ok(())
518 })
519 }
520
521 fn window_appearance(&self) -> WindowAppearance {
522 self.with_common(|common| common.appearance)
523 }
524
525 fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
526 Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
527 }
528
529 fn write_to_primary(&self, item: ClipboardItem) {
530 self.write_to_primary(item)
531 }
532
533 fn write_to_clipboard(&self, item: ClipboardItem) {
534 self.write_to_clipboard(item)
535 }
536
537 fn read_from_primary(&self) -> Option<ClipboardItem> {
538 self.read_from_primary()
539 }
540
541 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
542 self.read_from_clipboard()
543 }
544
545 fn add_recent_document(&self, _path: &Path) {}
546}
547
548#[cfg(any(feature = "wayland", feature = "x11"))]
549pub(super) fn open_uri_internal(
550 executor: BackgroundExecutor,
551 uri: &str,
552 activation_token: Option<String>,
553) {
554 if let Some(uri) = ashpd::url::Url::parse(uri).log_err() {
555 executor
556 .spawn(async move {
557 match ashpd::desktop::open_uri::OpenFileRequest::default()
558 .activation_token(activation_token.clone().map(ashpd::ActivationToken::from))
559 .send_uri(&uri)
560 .await
561 {
562 Ok(_) => return,
563 Err(e) => log::error!("Failed to open with dbus: {}", e),
564 }
565
566 for mut command in open::commands(uri.to_string()) {
567 if let Some(token) = activation_token.as_ref() {
568 command.env("XDG_ACTIVATION_TOKEN", token);
569 }
570 match command.spawn() {
571 Ok(_) => return,
572 Err(e) => {
573 log::error!("Failed to open with {:?}: {}", command.get_program(), e)
574 }
575 }
576 }
577 })
578 .detach();
579 }
580}
581
582#[cfg(any(feature = "x11", feature = "wayland"))]
583pub(super) fn reveal_path_internal(
584 executor: BackgroundExecutor,
585 path: PathBuf,
586 activation_token: Option<String>,
587) {
588 executor
589 .spawn(async move {
590 if let Some(dir) = File::open(path.clone()).log_err() {
591 match ashpd::desktop::open_uri::OpenDirectoryRequest::default()
592 .activation_token(activation_token.map(ashpd::ActivationToken::from))
593 .send(&dir.as_fd())
594 .await
595 {
596 Ok(_) => return,
597 Err(e) => log::error!("Failed to open with dbus: {}", e),
598 }
599 if path.is_dir() {
600 open::that_detached(path).log_err();
601 } else {
602 open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
603 }
604 }
605 })
606 .detach();
607}
608
609pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
610 let diff = a - b;
611 diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
612}
613
614#[cfg(any(feature = "wayland", feature = "x11"))]
615pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
616 let mut locales = Vec::default();
617 if let Some(locale) = std::env::var_os("LC_CTYPE") {
618 locales.push(locale);
619 }
620 locales.push(OsString::from("C"));
621 let mut state: Option<xkb::compose::State> = None;
622 for locale in locales {
623 if let Ok(table) =
624 xkb::compose::Table::new_from_locale(&cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
625 {
626 state = Some(xkb::compose::State::new(
627 &table,
628 xkb::compose::STATE_NO_FLAGS,
629 ));
630 break;
631 }
632 }
633 state
634}
635
636#[cfg(any(feature = "wayland", feature = "x11"))]
637pub(super) unsafe fn read_fd(mut fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
638 let mut file = File::from_raw_fd(fd.as_raw_fd());
639 let mut buffer = Vec::new();
640 file.read_to_end(&mut buffer)?;
641 Ok(buffer)
642}
643
644impl CursorStyle {
645 pub(super) fn to_icon_name(&self) -> String {
646 // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
647 // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
648 // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
649 match self {
650 CursorStyle::Arrow => "arrow",
651 CursorStyle::IBeam => "text",
652 CursorStyle::Crosshair => "crosshair",
653 CursorStyle::ClosedHand => "grabbing",
654 CursorStyle::OpenHand => "grab",
655 CursorStyle::PointingHand => "pointer",
656 CursorStyle::ResizeLeft => "w-resize",
657 CursorStyle::ResizeRight => "e-resize",
658 CursorStyle::ResizeLeftRight => "ew-resize",
659 CursorStyle::ResizeUp => "n-resize",
660 CursorStyle::ResizeDown => "s-resize",
661 CursorStyle::ResizeUpDown => "ns-resize",
662 CursorStyle::ResizeUpLeftDownRight => "nwse-resize",
663 CursorStyle::ResizeUpRightDownLeft => "nesw-resize",
664 CursorStyle::ResizeColumn => "col-resize",
665 CursorStyle::ResizeRow => "row-resize",
666 CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
667 CursorStyle::OperationNotAllowed => "not-allowed",
668 CursorStyle::DragLink => "alias",
669 CursorStyle::DragCopy => "copy",
670 CursorStyle::ContextualMenu => "context-menu",
671 }
672 .to_string()
673 }
674}
675
676#[cfg(any(feature = "wayland", feature = "x11"))]
677impl Keystroke {
678 pub(super) fn from_xkb(state: &State, modifiers: Modifiers, keycode: Keycode) -> Self {
679 let mut modifiers = modifiers;
680
681 let key_utf32 = state.key_get_utf32(keycode);
682 let key_utf8 = state.key_get_utf8(keycode);
683 let key_sym = state.key_get_one_sym(keycode);
684
685 let key = match key_sym {
686 Keysym::Return => "enter".to_owned(),
687 Keysym::Prior => "pageup".to_owned(),
688 Keysym::Next => "pagedown".to_owned(),
689 Keysym::ISO_Left_Tab => "tab".to_owned(),
690 Keysym::KP_Prior => "pageup".to_owned(),
691 Keysym::KP_Next => "pagedown".to_owned(),
692 Keysym::XF86_Back => "back".to_owned(),
693 Keysym::XF86_Forward => "forward".to_owned(),
694
695 Keysym::comma => ",".to_owned(),
696 Keysym::period => ".".to_owned(),
697 Keysym::less => "<".to_owned(),
698 Keysym::greater => ">".to_owned(),
699 Keysym::slash => "/".to_owned(),
700 Keysym::question => "?".to_owned(),
701
702 Keysym::semicolon => ";".to_owned(),
703 Keysym::colon => ":".to_owned(),
704 Keysym::apostrophe => "'".to_owned(),
705 Keysym::quotedbl => "\"".to_owned(),
706
707 Keysym::bracketleft => "[".to_owned(),
708 Keysym::braceleft => "{".to_owned(),
709 Keysym::bracketright => "]".to_owned(),
710 Keysym::braceright => "}".to_owned(),
711 Keysym::backslash => "\\".to_owned(),
712 Keysym::bar => "|".to_owned(),
713
714 Keysym::grave => "`".to_owned(),
715 Keysym::asciitilde => "~".to_owned(),
716 Keysym::exclam => "!".to_owned(),
717 Keysym::at => "@".to_owned(),
718 Keysym::numbersign => "#".to_owned(),
719 Keysym::dollar => "$".to_owned(),
720 Keysym::percent => "%".to_owned(),
721 Keysym::asciicircum => "^".to_owned(),
722 Keysym::ampersand => "&".to_owned(),
723 Keysym::asterisk => "*".to_owned(),
724 Keysym::parenleft => "(".to_owned(),
725 Keysym::parenright => ")".to_owned(),
726 Keysym::minus => "-".to_owned(),
727 Keysym::underscore => "_".to_owned(),
728 Keysym::equal => "=".to_owned(),
729 Keysym::plus => "+".to_owned(),
730
731 _ => {
732 let name = xkb::keysym_get_name(key_sym).to_lowercase();
733 if key_sym.is_keypad_key() {
734 name.replace("kp_", "")
735 } else {
736 name
737 }
738 }
739 };
740
741 if modifiers.shift {
742 // we only include the shift for upper-case letters by convention,
743 // so don't include for numbers and symbols, but do include for
744 // tab/enter, etc.
745 if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() {
746 modifiers.shift = false;
747 }
748 }
749
750 // Ignore control characters (and DEL) for the purposes of key_char
751 let key_char =
752 (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
753
754 Keystroke {
755 modifiers,
756 key,
757 key_char,
758 }
759 }
760
761 /**
762 * Returns which symbol the dead key represents
763 * https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux
764 */
765 pub fn underlying_dead_key(keysym: Keysym) -> Option<String> {
766 match keysym {
767 Keysym::dead_grave => Some("`".to_owned()),
768 Keysym::dead_acute => Some("´".to_owned()),
769 Keysym::dead_circumflex => Some("^".to_owned()),
770 Keysym::dead_tilde => Some("~".to_owned()),
771 Keysym::dead_perispomeni => Some("͂".to_owned()),
772 Keysym::dead_macron => Some("¯".to_owned()),
773 Keysym::dead_breve => Some("˘".to_owned()),
774 Keysym::dead_abovedot => Some("˙".to_owned()),
775 Keysym::dead_diaeresis => Some("¨".to_owned()),
776 Keysym::dead_abovering => Some("˚".to_owned()),
777 Keysym::dead_doubleacute => Some("˝".to_owned()),
778 Keysym::dead_caron => Some("ˇ".to_owned()),
779 Keysym::dead_cedilla => Some("¸".to_owned()),
780 Keysym::dead_ogonek => Some("˛".to_owned()),
781 Keysym::dead_iota => Some("ͅ".to_owned()),
782 Keysym::dead_voiced_sound => Some("゙".to_owned()),
783 Keysym::dead_semivoiced_sound => Some("゚".to_owned()),
784 Keysym::dead_belowdot => Some("̣̣".to_owned()),
785 Keysym::dead_hook => Some("̡".to_owned()),
786 Keysym::dead_horn => Some("̛".to_owned()),
787 Keysym::dead_stroke => Some("̶̶".to_owned()),
788 Keysym::dead_abovecomma => Some("̓̓".to_owned()),
789 Keysym::dead_psili => Some("᾿".to_owned()),
790 Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
791 Keysym::dead_dasia => Some("῾".to_owned()),
792 Keysym::dead_doublegrave => Some("̏".to_owned()),
793 Keysym::dead_belowring => Some("˳".to_owned()),
794 Keysym::dead_belowmacron => Some("̱".to_owned()),
795 Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()),
796 Keysym::dead_belowtilde => Some("̰".to_owned()),
797 Keysym::dead_belowbreve => Some("̮".to_owned()),
798 Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
799 Keysym::dead_invertedbreve => Some("̯".to_owned()),
800 Keysym::dead_belowcomma => Some("̦".to_owned()),
801 Keysym::dead_currency => None,
802 Keysym::dead_lowline => None,
803 Keysym::dead_aboveverticalline => None,
804 Keysym::dead_belowverticalline => None,
805 Keysym::dead_longsolidusoverlay => None,
806 Keysym::dead_a => None,
807 Keysym::dead_A => None,
808 Keysym::dead_e => None,
809 Keysym::dead_E => None,
810 Keysym::dead_i => None,
811 Keysym::dead_I => None,
812 Keysym::dead_o => None,
813 Keysym::dead_O => None,
814 Keysym::dead_u => None,
815 Keysym::dead_U => None,
816 Keysym::dead_small_schwa => Some("ə".to_owned()),
817 Keysym::dead_capital_schwa => Some("Ə".to_owned()),
818 Keysym::dead_greek => None,
819 _ => None,
820 }
821 }
822}
823
824#[cfg(any(feature = "wayland", feature = "x11"))]
825impl Modifiers {
826 pub(super) fn from_xkb(keymap_state: &State) -> Self {
827 let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
828 let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
829 let control =
830 keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
831 let platform =
832 keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
833 Modifiers {
834 shift,
835 alt,
836 control,
837 platform,
838 function: false,
839 }
840 }
841}
842
843#[cfg(test)]
844mod tests {
845 use super::*;
846 use crate::{px, Point};
847
848 #[test]
849 fn test_is_within_click_distance() {
850 let zero = Point::new(px(0.0), px(0.0));
851 assert_eq!(
852 is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
853 true
854 );
855 assert_eq!(
856 is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
857 true
858 );
859 assert_eq!(
860 is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
861 true
862 );
863 assert_eq!(
864 is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
865 false
866 );
867 }
868}