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