platform.rs

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