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