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