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