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