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 ashpd::desktop::file_chooser::{OpenFileRequest, SaveFileRequest};
 23use ashpd::desktop::open_uri::{OpenDirectoryRequest, OpenFileRequest as OpenUriRequest};
 24use ashpd::{url, ActivationToken};
 25use async_task::Runnable;
 26use calloop::channel::Channel;
 27use calloop::{EventLoop, LoopHandle, LoopSignal};
 28use filedescriptor::FileDescriptor;
 29use flume::{Receiver, Sender};
 30use futures::channel::oneshot;
 31use parking_lot::Mutex;
 32use util::ResultExt;
 33use wayland_client::Connection;
 34use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::Shape;
 35use xkbcommon::xkb::{self, Keycode, Keysym, State};
 36
 37use crate::platform::linux::wayland::WaylandClient;
 38use crate::{
 39    px, Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CosmicTextSystem, CursorStyle,
 40    DisplayId, ForegroundExecutor, Keymap, Keystroke, LinuxDispatcher, Menu, MenuItem, Modifiers,
 41    OwnedMenu, PathPromptOptions, Pixels, Platform, PlatformDisplay, PlatformInputHandler,
 42    PlatformTextSystem, PlatformWindow, Point, PromptLevel, Result, SemanticVersion, SharedString,
 43    Size, Task, WindowAppearance, WindowOptions, WindowParams,
 44};
 45
 46use super::x11::X11Client;
 47
 48pub(crate) const SCROLL_LINES: f64 = 3.0;
 49
 50// Values match the defaults on GTK.
 51// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
 52pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
 53pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
 54pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
 55
 56const FILE_PICKER_PORTAL_MISSING: &str =
 57    "Couldn't open file picker due to missing xdg-desktop-portal implementation.";
 58
 59pub trait LinuxClient {
 60    fn compositor_name(&self) -> &'static str;
 61    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
 62    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 63    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 64    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
 65
 66    fn open_window(
 67        &self,
 68        handle: AnyWindowHandle,
 69        options: WindowParams,
 70    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
 71    fn set_cursor_style(&self, style: CursorStyle);
 72    fn open_uri(&self, uri: &str);
 73    fn reveal_path(&self, path: PathBuf);
 74    fn write_to_primary(&self, item: ClipboardItem);
 75    fn write_to_clipboard(&self, item: ClipboardItem);
 76    fn read_from_primary(&self) -> Option<ClipboardItem>;
 77    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 78    fn active_window(&self) -> Option<AnyWindowHandle>;
 79    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>;
 80    fn run(&self);
 81}
 82
 83#[derive(Default)]
 84pub(crate) struct PlatformHandlers {
 85    pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 86    pub(crate) quit: Option<Box<dyn FnMut()>>,
 87    pub(crate) reopen: Option<Box<dyn FnMut()>>,
 88    pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 89    pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
 90    pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 91}
 92
 93pub(crate) struct LinuxCommon {
 94    pub(crate) background_executor: BackgroundExecutor,
 95    pub(crate) foreground_executor: ForegroundExecutor,
 96    pub(crate) text_system: Arc<CosmicTextSystem>,
 97    pub(crate) appearance: WindowAppearance,
 98    pub(crate) auto_hide_scrollbars: bool,
 99    pub(crate) callbacks: PlatformHandlers,
100    pub(crate) signal: LoopSignal,
101    pub(crate) menus: Vec<OwnedMenu>,
102}
103
104impl LinuxCommon {
105    pub fn new(signal: LoopSignal) -> (Self, Channel<Runnable>) {
106        let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
107        let text_system = Arc::new(CosmicTextSystem::new());
108        let callbacks = PlatformHandlers::default();
109
110        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender.clone()));
111
112        let background_executor = BackgroundExecutor::new(dispatcher.clone());
113
114        let common = LinuxCommon {
115            background_executor,
116            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
117            text_system,
118            appearance: WindowAppearance::Light,
119            auto_hide_scrollbars: false,
120            callbacks,
121            signal,
122            menus: Vec::new(),
123        };
124
125        (common, main_receiver)
126    }
127}
128
129impl<P: LinuxClient + 'static> Platform for P {
130    fn background_executor(&self) -> BackgroundExecutor {
131        self.with_common(|common| common.background_executor.clone())
132    }
133
134    fn foreground_executor(&self) -> ForegroundExecutor {
135        self.with_common(|common| common.foreground_executor.clone())
136    }
137
138    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
139        self.with_common(|common| common.text_system.clone())
140    }
141
142    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
143        on_finish_launching();
144
145        LinuxClient::run(self);
146
147        let quit = self.with_common(|common| common.callbacks.quit.take());
148        if let Some(mut fun) = quit {
149            fun();
150        }
151    }
152
153    fn quit(&self) {
154        self.with_common(|common| common.signal.stop());
155    }
156
157    fn compositor_name(&self) -> &'static str {
158        self.compositor_name()
159    }
160
161    fn restart(&self, binary_path: Option<PathBuf>) {
162        use std::os::unix::process::CommandExt as _;
163
164        // get the process id of the current process
165        let app_pid = std::process::id().to_string();
166        // get the path to the executable
167        let app_path = if let Some(path) = binary_path {
168            path
169        } else {
170            match self.app_path() {
171                Ok(path) => path,
172                Err(err) => {
173                    log::error!("Failed to get app path: {:?}", err);
174                    return;
175                }
176            }
177        };
178
179        log::info!("Restarting process, using app path: {:?}", app_path);
180
181        // Script to wait for the current process to exit and then restart the app.
182        // We also wait for possibly open TCP sockets by the process to be closed,
183        // since on Linux it's not guaranteed that a process' resources have been
184        // cleaned up when `kill -0` returns.
185        let script = format!(
186            r#"
187            while kill -0 {pid} 2>/dev/null; do
188                sleep 0.1
189            done
190
191            while lsof -nP -iTCP -a -p {pid} 2>/dev/null; do
192                sleep 0.1
193            done
194
195            {app_path}
196            "#,
197            pid = app_pid,
198            app_path = app_path.display()
199        );
200
201        // execute the script using /bin/bash
202        let restart_process = Command::new("/bin/bash")
203            .arg("-c")
204            .arg(script)
205            .process_group(0)
206            .spawn();
207
208        match restart_process {
209            Ok(_) => self.quit(),
210            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
211        }
212    }
213
214    fn activate(&self, ignoring_other_apps: bool) {
215        log::info!("activate is not implemented on Linux, ignoring the call")
216    }
217
218    fn hide(&self) {
219        log::info!("hide is not implemented on Linux, ignoring the call")
220    }
221
222    fn hide_other_apps(&self) {
223        log::info!("hide_other_apps is not implemented on Linux, ignoring the call")
224    }
225
226    fn unhide_other_apps(&self) {
227        log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")
228    }
229
230    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
231        self.primary_display()
232    }
233
234    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
235        self.displays()
236    }
237
238    fn active_window(&self) -> Option<AnyWindowHandle> {
239        self.active_window()
240    }
241
242    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
243        self.window_stack()
244    }
245
246    fn open_window(
247        &self,
248        handle: AnyWindowHandle,
249        options: WindowParams,
250    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
251        self.open_window(handle, options)
252    }
253
254    fn open_url(&self, url: &str) {
255        self.open_uri(url);
256    }
257
258    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
259        self.with_common(|common| common.callbacks.open_urls = Some(callback));
260    }
261
262    fn prompt_for_paths(
263        &self,
264        options: PathPromptOptions,
265    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
266        let (done_tx, done_rx) = oneshot::channel();
267        self.foreground_executor()
268            .spawn(async move {
269                let title = if options.directories {
270                    "Open Folder"
271                } else {
272                    "Open File"
273                };
274
275                let request = match OpenFileRequest::default()
276                    .modal(true)
277                    .title(title)
278                    .multiple(options.multiple)
279                    .directory(options.directories)
280                    .send()
281                    .await
282                {
283                    Ok(request) => request,
284                    Err(err) => {
285                        let result = match err {
286                            ashpd::Error::PortalNotFound(_) => anyhow!(FILE_PICKER_PORTAL_MISSING),
287                            err => err.into(),
288                        };
289                        done_tx.send(Err(result));
290                        return;
291                    }
292                };
293
294                let result = match request.response() {
295                    Ok(response) => Ok(Some(
296                        response
297                            .uris()
298                            .iter()
299                            .filter_map(|uri| uri.to_file_path().ok())
300                            .collect::<Vec<_>>(),
301                    )),
302                    Err(ashpd::Error::Response(_)) => Ok(None),
303                    Err(e) => Err(e.into()),
304                };
305                done_tx.send(result);
306            })
307            .detach();
308        done_rx
309    }
310
311    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
312        let (done_tx, done_rx) = oneshot::channel();
313        let directory = directory.to_owned();
314        self.foreground_executor()
315            .spawn(async move {
316                let request = match SaveFileRequest::default()
317                    .modal(true)
318                    .title("Save File")
319                    .current_folder(directory)
320                    .expect("pathbuf should not be nul terminated")
321                    .send()
322                    .await
323                {
324                    Ok(request) => request,
325                    Err(err) => {
326                        let result = match err {
327                            ashpd::Error::PortalNotFound(_) => anyhow!(FILE_PICKER_PORTAL_MISSING),
328                            err => err.into(),
329                        };
330                        done_tx.send(Err(result));
331                        return;
332                    }
333                };
334
335                let result = match request.response() {
336                    Ok(response) => Ok(response
337                        .uris()
338                        .first()
339                        .and_then(|uri| uri.to_file_path().ok())),
340                    Err(ashpd::Error::Response(_)) => Ok(None),
341                    Err(e) => Err(e.into()),
342                };
343                done_tx.send(result);
344            })
345            .detach();
346
347        done_rx
348    }
349
350    fn reveal_path(&self, path: &Path) {
351        self.reveal_path(path.to_owned());
352    }
353
354    fn on_quit(&self, callback: Box<dyn FnMut()>) {
355        self.with_common(|common| {
356            common.callbacks.quit = Some(callback);
357        });
358    }
359
360    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
361        self.with_common(|common| {
362            common.callbacks.reopen = Some(callback);
363        });
364    }
365
366    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
367        self.with_common(|common| {
368            common.callbacks.app_menu_action = Some(callback);
369        });
370    }
371
372    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
373        self.with_common(|common| {
374            common.callbacks.will_open_app_menu = Some(callback);
375        });
376    }
377
378    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
379        self.with_common(|common| {
380            common.callbacks.validate_app_menu_command = Some(callback);
381        });
382    }
383
384    fn app_path(&self) -> Result<PathBuf> {
385        // get the path of the executable of the current process
386        let exe_path = std::env::current_exe()?;
387        Ok(exe_path)
388    }
389
390    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
391        self.with_common(|common| {
392            common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
393        })
394    }
395
396    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
397        self.with_common(|common| Some(common.menus.clone()))
398    }
399
400    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {}
401
402    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
403        Err(anyhow::Error::msg(
404            "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
405        ))
406    }
407
408    fn set_cursor_style(&self, style: CursorStyle) {
409        self.set_cursor_style(style)
410    }
411
412    fn should_auto_hide_scrollbars(&self) -> bool {
413        self.with_common(|common| common.auto_hide_scrollbars)
414    }
415
416    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
417        let url = url.to_string();
418        let username = username.to_string();
419        let password = password.to_vec();
420        self.background_executor().spawn(async move {
421            let keyring = oo7::Keyring::new().await?;
422            keyring.unlock().await?;
423            keyring
424                .create_item(
425                    KEYRING_LABEL,
426                    &vec![("url", &url), ("username", &username)],
427                    password,
428                    true,
429                )
430                .await?;
431            Ok(())
432        })
433    }
434
435    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
436        let url = url.to_string();
437        self.background_executor().spawn(async move {
438            let keyring = oo7::Keyring::new().await?;
439            keyring.unlock().await?;
440
441            let items = keyring.search_items(&vec![("url", &url)]).await?;
442
443            for item in items.into_iter() {
444                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
445                    let attributes = item.attributes().await?;
446                    let username = attributes
447                        .get("username")
448                        .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
449                    let secret = item.secret().await?;
450
451                    // we lose the zeroizing capabilities at this boundary,
452                    // a current limitation GPUI's credentials api
453                    return Ok(Some((username.to_string(), secret.to_vec())));
454                } else {
455                    continue;
456                }
457            }
458            Ok(None)
459        })
460    }
461
462    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
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                    item.delete().await?;
473                    return Ok(());
474                }
475            }
476
477            Ok(())
478        })
479    }
480
481    fn window_appearance(&self) -> WindowAppearance {
482        self.with_common(|common| common.appearance)
483    }
484
485    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
486        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
487    }
488
489    fn write_to_primary(&self, item: ClipboardItem) {
490        self.write_to_primary(item)
491    }
492
493    fn write_to_clipboard(&self, item: ClipboardItem) {
494        self.write_to_clipboard(item)
495    }
496
497    fn read_from_primary(&self) -> Option<ClipboardItem> {
498        self.read_from_primary()
499    }
500
501    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
502        self.read_from_clipboard()
503    }
504
505    fn add_recent_document(&self, _path: &Path) {}
506}
507
508pub(super) fn open_uri_internal(
509    executor: BackgroundExecutor,
510    uri: &str,
511    activation_token: Option<String>,
512) {
513    if let Some(uri) = url::Url::parse(uri).log_err() {
514        executor
515            .spawn(async move {
516                match OpenUriRequest::default()
517                    .activation_token(activation_token.clone().map(ActivationToken::from))
518                    .send_uri(&uri)
519                    .await
520                {
521                    Ok(_) => return,
522                    Err(e) => log::error!("Failed to open with dbus: {}", e),
523                }
524
525                for mut command in open::commands(uri.to_string()) {
526                    if let Some(token) = activation_token.as_ref() {
527                        command.env("XDG_ACTIVATION_TOKEN", token);
528                    }
529                    match command.spawn() {
530                        Ok(_) => return,
531                        Err(e) => {
532                            log::error!("Failed to open with {:?}: {}", command.get_program(), e)
533                        }
534                    }
535                }
536            })
537            .detach();
538    }
539}
540
541pub(super) fn reveal_path_internal(
542    executor: BackgroundExecutor,
543    path: PathBuf,
544    activation_token: Option<String>,
545) {
546    executor
547        .spawn(async move {
548            if let Some(dir) = File::open(path.clone()).log_err() {
549                match OpenDirectoryRequest::default()
550                    .activation_token(activation_token.map(ActivationToken::from))
551                    .send(&dir.as_fd())
552                    .await
553                {
554                    Ok(_) => return,
555                    Err(e) => log::error!("Failed to open with dbus: {}", e),
556                }
557                if path.is_dir() {
558                    open::that_detached(path).log_err();
559                } else {
560                    open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
561                }
562            }
563        })
564        .detach();
565}
566
567pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
568    let diff = a - b;
569    diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
570}
571
572pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
573    let mut locales = Vec::default();
574    if let Some(locale) = std::env::var_os("LC_CTYPE") {
575        locales.push(locale);
576    }
577    locales.push(OsString::from("C"));
578    let mut state: Option<xkb::compose::State> = None;
579    for locale in locales {
580        if let Ok(table) =
581            xkb::compose::Table::new_from_locale(&cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
582        {
583            state = Some(xkb::compose::State::new(
584                &table,
585                xkb::compose::STATE_NO_FLAGS,
586            ));
587            break;
588        }
589    }
590    state
591}
592
593pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<String> {
594    let mut file = File::from_raw_fd(fd.as_raw_fd());
595
596    let mut buffer = String::new();
597    file.read_to_string(&mut buffer)?;
598
599    // Normalize the text to unix line endings, otherwise
600    // copying from eg: firefox inserts a lot of blank
601    // lines, and that is super annoying.
602    let result = buffer.replace("\r\n", "\n");
603    Ok(result)
604}
605
606impl CursorStyle {
607    pub(super) fn to_shape(&self) -> Shape {
608        match self {
609            CursorStyle::Arrow => Shape::Default,
610            CursorStyle::IBeam => Shape::Text,
611            CursorStyle::Crosshair => Shape::Crosshair,
612            CursorStyle::ClosedHand => Shape::Grabbing,
613            CursorStyle::OpenHand => Shape::Grab,
614            CursorStyle::PointingHand => Shape::Pointer,
615            CursorStyle::ResizeLeft => Shape::WResize,
616            CursorStyle::ResizeRight => Shape::EResize,
617            CursorStyle::ResizeLeftRight => Shape::EwResize,
618            CursorStyle::ResizeUp => Shape::NResize,
619            CursorStyle::ResizeDown => Shape::SResize,
620            CursorStyle::ResizeUpDown => Shape::NsResize,
621            CursorStyle::ResizeUpLeftDownRight => Shape::NwseResize,
622            CursorStyle::ResizeUpRightDownLeft => Shape::NeswResize,
623            CursorStyle::ResizeColumn => Shape::ColResize,
624            CursorStyle::ResizeRow => Shape::RowResize,
625            CursorStyle::IBeamCursorForVerticalLayout => Shape::VerticalText,
626            CursorStyle::OperationNotAllowed => Shape::NotAllowed,
627            CursorStyle::DragLink => Shape::Alias,
628            CursorStyle::DragCopy => Shape::Copy,
629            CursorStyle::ContextualMenu => Shape::ContextMenu,
630        }
631    }
632
633    pub(super) fn to_icon_name(&self) -> String {
634        // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
635        // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
636        // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
637        match self {
638            CursorStyle::Arrow => "arrow",
639            CursorStyle::IBeam => "text",
640            CursorStyle::Crosshair => "crosshair",
641            CursorStyle::ClosedHand => "grabbing",
642            CursorStyle::OpenHand => "grab",
643            CursorStyle::PointingHand => "pointer",
644            CursorStyle::ResizeLeft => "w-resize",
645            CursorStyle::ResizeRight => "e-resize",
646            CursorStyle::ResizeLeftRight => "ew-resize",
647            CursorStyle::ResizeUp => "n-resize",
648            CursorStyle::ResizeDown => "s-resize",
649            CursorStyle::ResizeUpDown => "ns-resize",
650            CursorStyle::ResizeUpLeftDownRight => "nwse-resize",
651            CursorStyle::ResizeUpRightDownLeft => "nesw-resize",
652            CursorStyle::ResizeColumn => "col-resize",
653            CursorStyle::ResizeRow => "row-resize",
654            CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
655            CursorStyle::OperationNotAllowed => "not-allowed",
656            CursorStyle::DragLink => "alias",
657            CursorStyle::DragCopy => "copy",
658            CursorStyle::ContextualMenu => "context-menu",
659        }
660        .to_string()
661    }
662}
663
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
809impl Modifiers {
810    pub(super) fn from_xkb(keymap_state: &State) -> Self {
811        let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
812        let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
813        let control =
814            keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
815        let platform =
816            keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
817        Modifiers {
818            shift,
819            alt,
820            control,
821            platform,
822            function: false,
823        }
824    }
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830    use crate::{px, Point};
831
832    #[test]
833    fn test_is_within_click_distance() {
834        let zero = Point::new(px(0.0), px(0.0));
835        assert_eq!(
836            is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
837            true
838        );
839        assert_eq!(
840            is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
841            true
842        );
843        assert_eq!(
844            is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
845            true
846        );
847        assert_eq!(
848            is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
849            false
850        );
851    }
852}