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