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