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