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