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