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