platform.rs

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