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        Ok(SemanticVersion::new(1, 0, 0))
352    }
353
354    fn app_path(&self) -> Result<PathBuf> {
355        // get the path of the executable of the current process
356        let exe_path = std::env::current_exe()?;
357        Ok(exe_path)
358    }
359
360    // todo(linux)
361    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {}
362
363    fn local_timezone(&self) -> UtcOffset {
364        UtcOffset::UTC
365    }
366
367    //todo(linux)
368    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
369        Err(anyhow::Error::msg(
370            "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
371        ))
372    }
373
374    fn set_cursor_style(&self, style: CursorStyle) {
375        self.set_cursor_style(style)
376    }
377
378    // todo(linux)
379    fn should_auto_hide_scrollbars(&self) -> bool {
380        false
381    }
382
383    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
384        let url = url.to_string();
385        let username = username.to_string();
386        let password = password.to_vec();
387        self.background_executor().spawn(async move {
388            let keyring = oo7::Keyring::new().await?;
389            keyring.unlock().await?;
390            keyring
391                .create_item(
392                    KEYRING_LABEL,
393                    &vec![("url", &url), ("username", &username)],
394                    password,
395                    true,
396                )
397                .await?;
398            Ok(())
399        })
400    }
401
402    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
403        let url = url.to_string();
404        self.background_executor().spawn(async move {
405            let keyring = oo7::Keyring::new().await?;
406            keyring.unlock().await?;
407
408            let items = keyring.search_items(&vec![("url", &url)]).await?;
409
410            for item in items.into_iter() {
411                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
412                    let attributes = item.attributes().await?;
413                    let username = attributes
414                        .get("username")
415                        .ok_or_else(|| anyhow!("Cannot find username in stored credentials"))?;
416                    let secret = item.secret().await?;
417
418                    // we lose the zeroizing capabilities at this boundary,
419                    // a current limitation GPUI's credentials api
420                    return Ok(Some((username.to_string(), secret.to_vec())));
421                } else {
422                    continue;
423                }
424            }
425            Ok(None)
426        })
427    }
428
429    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
430        let url = url.to_string();
431        self.background_executor().spawn(async move {
432            let keyring = oo7::Keyring::new().await?;
433            keyring.unlock().await?;
434
435            let items = keyring.search_items(&vec![("url", &url)]).await?;
436
437            for item in items.into_iter() {
438                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
439                    item.delete().await?;
440                    return Ok(());
441                }
442            }
443
444            Ok(())
445        })
446    }
447
448    fn window_appearance(&self) -> crate::WindowAppearance {
449        crate::WindowAppearance::Light
450    }
451
452    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
453        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
454    }
455
456    fn write_to_primary(&self, item: ClipboardItem) {
457        self.write_to_primary(item)
458    }
459
460    fn write_to_clipboard(&self, item: ClipboardItem) {
461        self.write_to_clipboard(item)
462    }
463
464    fn read_from_primary(&self) -> Option<ClipboardItem> {
465        self.read_from_primary()
466    }
467
468    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
469        self.read_from_clipboard()
470    }
471}
472
473pub(super) fn open_uri_internal(uri: &str, activation_token: Option<&str>) {
474    let mut last_err = None;
475    for mut command in open::commands(uri) {
476        if let Some(token) = activation_token {
477            command.env("XDG_ACTIVATION_TOKEN", token);
478        }
479        match command.status() {
480            Ok(_) => return,
481            Err(err) => last_err = Some(err),
482        }
483    }
484    log::error!("failed to open uri: {uri:?}, last error: {last_err:?}");
485}
486
487pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
488    let diff = a - b;
489    diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
490}
491
492pub(super) unsafe fn read_fd(mut fd: FileDescriptor) -> Result<String> {
493    let mut file = File::from_raw_fd(fd.as_raw_fd());
494
495    let mut buffer = String::new();
496    file.read_to_string(&mut buffer)?;
497
498    // Normalize the text to unix line endings, otherwise
499    // copying from eg: firefox inserts a lot of blank
500    // lines, and that is super annoying.
501    let result = buffer.replace("\r\n", "\n");
502    Ok(result)
503}
504
505impl CursorStyle {
506    pub(super) fn to_shape(&self) -> Shape {
507        match self {
508            CursorStyle::Arrow => Shape::Default,
509            CursorStyle::IBeam => Shape::Text,
510            CursorStyle::Crosshair => Shape::Crosshair,
511            CursorStyle::ClosedHand => Shape::Grabbing,
512            CursorStyle::OpenHand => Shape::Grab,
513            CursorStyle::PointingHand => Shape::Pointer,
514            CursorStyle::ResizeLeft => Shape::WResize,
515            CursorStyle::ResizeRight => Shape::EResize,
516            CursorStyle::ResizeLeftRight => Shape::EwResize,
517            CursorStyle::ResizeUp => Shape::NResize,
518            CursorStyle::ResizeDown => Shape::SResize,
519            CursorStyle::ResizeUpDown => Shape::NsResize,
520            CursorStyle::ResizeColumn => Shape::ColResize,
521            CursorStyle::ResizeRow => Shape::RowResize,
522            CursorStyle::DisappearingItem => Shape::Grabbing, // todo(linux) - couldn't find equivalent icon in linux
523            CursorStyle::IBeamCursorForVerticalLayout => Shape::VerticalText,
524            CursorStyle::OperationNotAllowed => Shape::NotAllowed,
525            CursorStyle::DragLink => Shape::Alias,
526            CursorStyle::DragCopy => Shape::Copy,
527            CursorStyle::ContextualMenu => Shape::ContextMenu,
528        }
529    }
530
531    pub(super) fn to_icon_name(&self) -> String {
532        // Based on cursor names from https://gitlab.gnome.org/GNOME/adwaita-icon-theme (GNOME)
533        // and https://github.com/KDE/breeze (KDE). Both of them seem to be also derived from
534        // Web CSS cursor names: https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#values
535        match self {
536            CursorStyle::Arrow => "arrow",
537            CursorStyle::IBeam => "text",
538            CursorStyle::Crosshair => "crosshair",
539            CursorStyle::ClosedHand => "grabbing",
540            CursorStyle::OpenHand => "grab",
541            CursorStyle::PointingHand => "pointer",
542            CursorStyle::ResizeLeft => "w-resize",
543            CursorStyle::ResizeRight => "e-resize",
544            CursorStyle::ResizeLeftRight => "ew-resize",
545            CursorStyle::ResizeUp => "n-resize",
546            CursorStyle::ResizeDown => "s-resize",
547            CursorStyle::ResizeUpDown => "ns-resize",
548            CursorStyle::ResizeColumn => "col-resize",
549            CursorStyle::ResizeRow => "row-resize",
550            CursorStyle::DisappearingItem => "grabbing", // todo(linux) - couldn't find equivalent icon in linux
551            CursorStyle::IBeamCursorForVerticalLayout => "vertical-text",
552            CursorStyle::OperationNotAllowed => "not-allowed",
553            CursorStyle::DragLink => "alias",
554            CursorStyle::DragCopy => "copy",
555            CursorStyle::ContextualMenu => "context-menu",
556        }
557        .to_string()
558    }
559}
560
561impl Keystroke {
562    pub(super) fn from_xkb(state: &State, modifiers: Modifiers, keycode: Keycode) -> Self {
563        let mut modifiers = modifiers;
564
565        let key_utf32 = state.key_get_utf32(keycode);
566        let key_utf8 = state.key_get_utf8(keycode);
567        let key_sym = state.key_get_one_sym(keycode);
568
569        // The logic here tries to replicate the logic in `../mac/events.rs`
570        // "Consumed" modifiers are modifiers that have been used to translate a key, for example
571        // pressing "shift" and "1" on US layout produces the key `!` but "consumes" the shift.
572        // Notes:
573        //  - macOS gets the key character directly ("."), xkb gives us the key name ("period")
574        //  - macOS logic removes consumed shift modifier for symbols: "{", not "shift-{"
575        //  - macOS logic keeps consumed shift modifiers for letters: "shift-a", not "a" or "A"
576
577        let mut handle_consumed_modifiers = true;
578        let key = match key_sym {
579            Keysym::Return => "enter".to_owned(),
580            Keysym::Prior => "pageup".to_owned(),
581            Keysym::Next => "pagedown".to_owned(),
582
583            Keysym::comma => ",".to_owned(),
584            Keysym::period => ".".to_owned(),
585            Keysym::less => "<".to_owned(),
586            Keysym::greater => ">".to_owned(),
587            Keysym::slash => "/".to_owned(),
588            Keysym::question => "?".to_owned(),
589
590            Keysym::semicolon => ";".to_owned(),
591            Keysym::colon => ":".to_owned(),
592            Keysym::apostrophe => "'".to_owned(),
593            Keysym::quotedbl => "\"".to_owned(),
594
595            Keysym::bracketleft => "[".to_owned(),
596            Keysym::braceleft => "{".to_owned(),
597            Keysym::bracketright => "]".to_owned(),
598            Keysym::braceright => "}".to_owned(),
599            Keysym::backslash => "\\".to_owned(),
600            Keysym::bar => "|".to_owned(),
601
602            Keysym::grave => "`".to_owned(),
603            Keysym::asciitilde => "~".to_owned(),
604            Keysym::exclam => "!".to_owned(),
605            Keysym::at => "@".to_owned(),
606            Keysym::numbersign => "#".to_owned(),
607            Keysym::dollar => "$".to_owned(),
608            Keysym::percent => "%".to_owned(),
609            Keysym::asciicircum => "^".to_owned(),
610            Keysym::ampersand => "&".to_owned(),
611            Keysym::asterisk => "*".to_owned(),
612            Keysym::parenleft => "(".to_owned(),
613            Keysym::parenright => ")".to_owned(),
614            Keysym::minus => "-".to_owned(),
615            Keysym::underscore => "_".to_owned(),
616            Keysym::equal => "=".to_owned(),
617            Keysym::plus => "+".to_owned(),
618
619            Keysym::ISO_Left_Tab => {
620                handle_consumed_modifiers = false;
621                "tab".to_owned()
622            }
623
624            _ => {
625                handle_consumed_modifiers = false;
626                xkb::keysym_get_name(key_sym).to_lowercase()
627            }
628        };
629
630        // Ignore control characters (and DEL) for the purposes of ime_key
631        let ime_key =
632            (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
633
634        if handle_consumed_modifiers {
635            let mod_shift_index = state.get_keymap().mod_get_index(xkb::MOD_NAME_SHIFT);
636            let is_shift_consumed = state.mod_index_is_consumed(keycode, mod_shift_index);
637
638            if modifiers.shift && is_shift_consumed {
639                modifiers.shift = false;
640            }
641        }
642
643        Keystroke {
644            modifiers,
645            key,
646            ime_key,
647        }
648    }
649}
650
651impl Modifiers {
652    pub(super) fn from_xkb(keymap_state: &State) -> Self {
653        let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
654        let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
655        let control =
656            keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
657        let platform =
658            keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
659        Modifiers {
660            shift,
661            alt,
662            control,
663            platform,
664            function: false,
665        }
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672    use crate::{px, Point};
673
674    #[test]
675    fn test_is_within_click_distance() {
676        let zero = Point::new(px(0.0), px(0.0));
677        assert_eq!(
678            is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
679            true
680        );
681        assert_eq!(
682            is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
683            true
684        );
685        assert_eq!(
686            is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
687            true
688        );
689        assert_eq!(
690            is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
691            false
692        );
693    }
694}