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