platform.rs

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