platform.rs

  1use std::{
  2    env,
  3    path::{Path, PathBuf},
  4    process::Command,
  5    rc::Rc,
  6    sync::Arc,
  7};
  8#[cfg(any(feature = "wayland", feature = "x11"))]
  9use std::{
 10    ffi::OsString,
 11    fs::File,
 12    io::Read as _,
 13    os::fd::{AsFd, AsRawFd, FromRawFd},
 14    time::Duration,
 15};
 16
 17use anyhow::{Context as _, anyhow};
 18use async_task::Runnable;
 19use calloop::{LoopSignal, channel::Channel};
 20use futures::channel::oneshot;
 21use util::ResultExt as _;
 22#[cfg(any(feature = "wayland", feature = "x11"))]
 23use xkbcommon::xkb::{self, Keycode, Keysym, State};
 24
 25use crate::{
 26    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
 27    ForegroundExecutor, Keymap, LinuxDispatcher, Menu, MenuItem, OwnedMenu, PathPromptOptions,
 28    Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformTextSystem, PlatformWindow,
 29    Point, Result, ScreenCaptureSource, Task, WindowAppearance, WindowParams, px,
 30};
 31
 32#[cfg(any(feature = "wayland", feature = "x11"))]
 33pub(crate) const SCROLL_LINES: f32 = 3.0;
 34
 35// Values match the defaults on GTK.
 36// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320
 37#[cfg(any(feature = "wayland", feature = "x11"))]
 38pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);
 39pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);
 40pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
 41
 42#[cfg(any(feature = "wayland", feature = "x11"))]
 43const FILE_PICKER_PORTAL_MISSING: &str =
 44    "Couldn't open file picker due to missing xdg-desktop-portal implementation.";
 45
 46pub trait LinuxClient {
 47    fn compositor_name(&self) -> &'static str;
 48    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;
 49    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;
 50    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;
 51    #[allow(unused)]
 52    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;
 53    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;
 54    fn is_screen_capture_supported(&self) -> bool;
 55    fn screen_capture_sources(
 56        &self,
 57    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>>;
 58
 59    fn open_window(
 60        &self,
 61        handle: AnyWindowHandle,
 62        options: WindowParams,
 63    ) -> anyhow::Result<Box<dyn PlatformWindow>>;
 64    fn set_cursor_style(&self, style: CursorStyle);
 65    fn open_uri(&self, uri: &str);
 66    fn reveal_path(&self, path: PathBuf);
 67    fn write_to_primary(&self, item: ClipboardItem);
 68    fn write_to_clipboard(&self, item: ClipboardItem);
 69    fn read_from_primary(&self) -> Option<ClipboardItem>;
 70    fn read_from_clipboard(&self) -> Option<ClipboardItem>;
 71    fn active_window(&self) -> Option<AnyWindowHandle>;
 72    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>;
 73    fn run(&self);
 74}
 75
 76#[derive(Default)]
 77pub(crate) struct PlatformHandlers {
 78    pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 79    pub(crate) quit: Option<Box<dyn FnMut()>>,
 80    pub(crate) reopen: Option<Box<dyn FnMut()>>,
 81    pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,
 82    pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,
 83    pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 84    pub(crate) keyboard_layout_change: Option<Box<dyn FnMut()>>,
 85}
 86
 87pub(crate) struct LinuxCommon {
 88    pub(crate) background_executor: BackgroundExecutor,
 89    pub(crate) foreground_executor: ForegroundExecutor,
 90    pub(crate) text_system: Arc<dyn PlatformTextSystem>,
 91    pub(crate) appearance: WindowAppearance,
 92    pub(crate) auto_hide_scrollbars: bool,
 93    pub(crate) callbacks: PlatformHandlers,
 94    pub(crate) signal: LoopSignal,
 95    pub(crate) menus: Vec<OwnedMenu>,
 96}
 97
 98impl LinuxCommon {
 99    pub fn new(signal: LoopSignal) -> (Self, Channel<Runnable>) {
100        let (main_sender, main_receiver) = calloop::channel::channel::<Runnable>();
101
102        #[cfg(any(feature = "wayland", feature = "x11"))]
103        let text_system = Arc::new(crate::CosmicTextSystem::new());
104        #[cfg(not(any(feature = "wayland", feature = "x11")))]
105        let text_system = Arc::new(crate::NoopTextSystem::new());
106
107        let callbacks = PlatformHandlers::default();
108
109        let dispatcher = Arc::new(LinuxDispatcher::new(main_sender.clone()));
110
111        let background_executor = BackgroundExecutor::new(dispatcher.clone());
112
113        let common = LinuxCommon {
114            background_executor,
115            foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
116            text_system,
117            appearance: WindowAppearance::Light,
118            auto_hide_scrollbars: false,
119            callbacks,
120            signal,
121            menus: Vec::new(),
122        };
123
124        (common, main_receiver)
125    }
126}
127
128impl<P: LinuxClient + 'static> Platform for P {
129    fn background_executor(&self) -> BackgroundExecutor {
130        self.with_common(|common| common.background_executor.clone())
131    }
132
133    fn foreground_executor(&self) -> ForegroundExecutor {
134        self.with_common(|common| common.foreground_executor.clone())
135    }
136
137    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
138        self.with_common(|common| common.text_system.clone())
139    }
140
141    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
142        self.keyboard_layout()
143    }
144
145    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
146        self.with_common(|common| common.callbacks.keyboard_layout_change = Some(callback));
147    }
148
149    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
150        on_finish_launching();
151
152        LinuxClient::run(self);
153
154        let quit = self.with_common(|common| common.callbacks.quit.take());
155        if let Some(mut fun) = quit {
156            fun();
157        }
158    }
159
160    fn quit(&self) {
161        self.with_common(|common| common.signal.stop());
162    }
163
164    fn compositor_name(&self) -> &'static str {
165        self.compositor_name()
166    }
167
168    fn restart(&self, binary_path: Option<PathBuf>) {
169        use std::os::unix::process::CommandExt as _;
170
171        // get the process id of the current process
172        let app_pid = std::process::id().to_string();
173        // get the path to the executable
174        let app_path = if let Some(path) = binary_path {
175            path
176        } else {
177            match self.app_path() {
178                Ok(path) => path,
179                Err(err) => {
180                    log::error!("Failed to get app path: {:?}", err);
181                    return;
182                }
183            }
184        };
185
186        log::info!("Restarting process, using app path: {:?}", app_path);
187
188        // Script to wait for the current process to exit and then restart the app.
189        let script = format!(
190            r#"
191            while kill -0 {pid} 2>/dev/null; do
192                sleep 0.1
193            done
194
195            {app_path}
196            "#,
197            pid = app_pid,
198            app_path = app_path.display()
199        );
200
201        // execute the script using /bin/bash
202        let restart_process = Command::new("/bin/bash")
203            .arg("-c")
204            .arg(script)
205            .process_group(0)
206            .spawn();
207
208        match restart_process {
209            Ok(_) => self.quit(),
210            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
211        }
212    }
213
214    fn activate(&self, _ignoring_other_apps: bool) {
215        log::info!("activate is not implemented on Linux, ignoring the call")
216    }
217
218    fn hide(&self) {
219        log::info!("hide is not implemented on Linux, ignoring the call")
220    }
221
222    fn hide_other_apps(&self) {
223        log::info!("hide_other_apps is not implemented on Linux, ignoring the call")
224    }
225
226    fn unhide_other_apps(&self) {
227        log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")
228    }
229
230    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
231        self.primary_display()
232    }
233
234    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
235        self.displays()
236    }
237
238    fn is_screen_capture_supported(&self) -> bool {
239        self.is_screen_capture_supported()
240    }
241
242    fn screen_capture_sources(
243        &self,
244    ) -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptureSource>>>> {
245        self.screen_capture_sources()
246    }
247
248    fn active_window(&self) -> Option<AnyWindowHandle> {
249        self.active_window()
250    }
251
252    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
253        self.window_stack()
254    }
255
256    fn open_window(
257        &self,
258        handle: AnyWindowHandle,
259        options: WindowParams,
260    ) -> anyhow::Result<Box<dyn PlatformWindow>> {
261        self.open_window(handle, options)
262    }
263
264    fn open_url(&self, url: &str) {
265        self.open_uri(url);
266    }
267
268    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
269        self.with_common(|common| common.callbacks.open_urls = Some(callback));
270    }
271
272    fn prompt_for_paths(
273        &self,
274        options: PathPromptOptions,
275    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
276        let (done_tx, done_rx) = oneshot::channel();
277
278        #[cfg(not(any(feature = "wayland", feature = "x11")))]
279        let _ = (done_tx.send(Ok(None)), options);
280
281        #[cfg(any(feature = "wayland", feature = "x11"))]
282        self.foreground_executor()
283            .spawn(async move {
284                let title = if options.directories {
285                    "Open Folder"
286                } else {
287                    "Open File"
288                };
289
290                let request = match ashpd::desktop::file_chooser::OpenFileRequest::default()
291                    .modal(true)
292                    .title(title)
293                    .multiple(options.multiple)
294                    .directory(options.directories)
295                    .send()
296                    .await
297                {
298                    Ok(request) => request,
299                    Err(err) => {
300                        let result = match err {
301                            ashpd::Error::PortalNotFound(_) => anyhow!(FILE_PICKER_PORTAL_MISSING),
302                            err => err.into(),
303                        };
304                        let _ = done_tx.send(Err(result));
305                        return;
306                    }
307                };
308
309                let result = match request.response() {
310                    Ok(response) => Ok(Some(
311                        response
312                            .uris()
313                            .iter()
314                            .filter_map(|uri| uri.to_file_path().ok())
315                            .collect::<Vec<_>>(),
316                    )),
317                    Err(ashpd::Error::Response(_)) => Ok(None),
318                    Err(e) => Err(e.into()),
319                };
320                let _ = done_tx.send(result);
321            })
322            .detach();
323        done_rx
324    }
325
326    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
327        let (done_tx, done_rx) = oneshot::channel();
328
329        #[cfg(not(any(feature = "wayland", feature = "x11")))]
330        let _ = (done_tx.send(Ok(None)), directory);
331
332        #[cfg(any(feature = "wayland", feature = "x11"))]
333        self.foreground_executor()
334            .spawn({
335                let directory = directory.to_owned();
336
337                async move {
338                    let request = match ashpd::desktop::file_chooser::SaveFileRequest::default()
339                        .modal(true)
340                        .title("Save File")
341                        .current_folder(directory)
342                        .expect("pathbuf should not be nul terminated")
343                        .send()
344                        .await
345                    {
346                        Ok(request) => request,
347                        Err(err) => {
348                            let result = match err {
349                                ashpd::Error::PortalNotFound(_) => {
350                                    anyhow!(FILE_PICKER_PORTAL_MISSING)
351                                }
352                                err => err.into(),
353                            };
354                            let _ = done_tx.send(Err(result));
355                            return;
356                        }
357                    };
358
359                    let result = match request.response() {
360                        Ok(response) => Ok(response
361                            .uris()
362                            .first()
363                            .and_then(|uri| uri.to_file_path().ok())),
364                        Err(ashpd::Error::Response(_)) => Ok(None),
365                        Err(e) => Err(e.into()),
366                    };
367                    let _ = done_tx.send(result);
368                }
369            })
370            .detach();
371
372        done_rx
373    }
374
375    fn can_select_mixed_files_and_dirs(&self) -> bool {
376        // org.freedesktop.portal.FileChooser only supports "pick files" and "pick directories".
377        false
378    }
379
380    fn reveal_path(&self, path: &Path) {
381        self.reveal_path(path.to_owned());
382    }
383
384    fn open_with_system(&self, path: &Path) {
385        let path = path.to_owned();
386        self.background_executor()
387            .spawn(async move {
388                let _ = std::process::Command::new("xdg-open")
389                    .arg(path)
390                    .spawn()
391                    .context("invoking xdg-open")
392                    .log_err();
393            })
394            .detach();
395    }
396
397    fn on_quit(&self, callback: Box<dyn FnMut()>) {
398        self.with_common(|common| {
399            common.callbacks.quit = Some(callback);
400        });
401    }
402
403    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
404        self.with_common(|common| {
405            common.callbacks.reopen = Some(callback);
406        });
407    }
408
409    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
410        self.with_common(|common| {
411            common.callbacks.app_menu_action = Some(callback);
412        });
413    }
414
415    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
416        self.with_common(|common| {
417            common.callbacks.will_open_app_menu = Some(callback);
418        });
419    }
420
421    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
422        self.with_common(|common| {
423            common.callbacks.validate_app_menu_command = Some(callback);
424        });
425    }
426
427    fn app_path(&self) -> Result<PathBuf> {
428        // get the path of the executable of the current process
429        let app_path = env::current_exe()?;
430        return Ok(app_path);
431    }
432
433    fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
434        self.with_common(|common| {
435            common.menus = menus.into_iter().map(|menu| menu.owned()).collect();
436        })
437    }
438
439    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
440        self.with_common(|common| Some(common.menus.clone()))
441    }
442
443    fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {
444        // todo(linux)
445    }
446
447    fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
448        Err(anyhow::Error::msg(
449            "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet",
450        ))
451    }
452
453    fn set_cursor_style(&self, style: CursorStyle) {
454        self.set_cursor_style(style)
455    }
456
457    fn should_auto_hide_scrollbars(&self) -> bool {
458        self.with_common(|common| common.auto_hide_scrollbars)
459    }
460
461    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
462        let url = url.to_string();
463        let username = username.to_string();
464        let password = password.to_vec();
465        self.background_executor().spawn(async move {
466            let keyring = oo7::Keyring::new().await?;
467            keyring.unlock().await?;
468            keyring
469                .create_item(
470                    KEYRING_LABEL,
471                    &vec![("url", &url), ("username", &username)],
472                    password,
473                    true,
474                )
475                .await?;
476            Ok(())
477        })
478    }
479
480    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
481        let url = url.to_string();
482        self.background_executor().spawn(async move {
483            let keyring = oo7::Keyring::new().await?;
484            keyring.unlock().await?;
485
486            let items = keyring.search_items(&vec![("url", &url)]).await?;
487
488            for item in items.into_iter() {
489                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
490                    let attributes = item.attributes().await?;
491                    let username = attributes
492                        .get("username")
493                        .context("Cannot find username in stored credentials")?;
494                    item.unlock().await?;
495                    let secret = item.secret().await?;
496
497                    // we lose the zeroizing capabilities at this boundary,
498                    // a current limitation GPUI's credentials api
499                    return Ok(Some((username.to_string(), secret.to_vec())));
500                } else {
501                    continue;
502                }
503            }
504            Ok(None)
505        })
506    }
507
508    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
509        let url = url.to_string();
510        self.background_executor().spawn(async move {
511            let keyring = oo7::Keyring::new().await?;
512            keyring.unlock().await?;
513
514            let items = keyring.search_items(&vec![("url", &url)]).await?;
515
516            for item in items.into_iter() {
517                if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) {
518                    item.delete().await?;
519                    return Ok(());
520                }
521            }
522
523            Ok(())
524        })
525    }
526
527    fn window_appearance(&self) -> WindowAppearance {
528        self.with_common(|common| common.appearance)
529    }
530
531    fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
532        Task::ready(Err(anyhow!("register_url_scheme unimplemented")))
533    }
534
535    fn write_to_primary(&self, item: ClipboardItem) {
536        self.write_to_primary(item)
537    }
538
539    fn write_to_clipboard(&self, item: ClipboardItem) {
540        self.write_to_clipboard(item)
541    }
542
543    fn read_from_primary(&self) -> Option<ClipboardItem> {
544        self.read_from_primary()
545    }
546
547    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
548        self.read_from_clipboard()
549    }
550
551    fn add_recent_document(&self, _path: &Path) {}
552}
553
554#[cfg(any(feature = "wayland", feature = "x11"))]
555pub(super) fn open_uri_internal(
556    executor: BackgroundExecutor,
557    uri: &str,
558    activation_token: Option<String>,
559) {
560    if let Some(uri) = ashpd::url::Url::parse(uri).log_err() {
561        executor
562            .spawn(async move {
563                match ashpd::desktop::open_uri::OpenFileRequest::default()
564                    .activation_token(activation_token.clone().map(ashpd::ActivationToken::from))
565                    .send_uri(&uri)
566                    .await
567                {
568                    Ok(_) => return,
569                    Err(e) => log::error!("Failed to open with dbus: {}", e),
570                }
571
572                for mut command in open::commands(uri.to_string()) {
573                    if let Some(token) = activation_token.as_ref() {
574                        command.env("XDG_ACTIVATION_TOKEN", token);
575                    }
576                    match command.spawn() {
577                        Ok(_) => return,
578                        Err(e) => {
579                            log::error!("Failed to open with {:?}: {}", command.get_program(), e)
580                        }
581                    }
582                }
583            })
584            .detach();
585    }
586}
587
588#[cfg(any(feature = "x11", feature = "wayland"))]
589pub(super) fn reveal_path_internal(
590    executor: BackgroundExecutor,
591    path: PathBuf,
592    activation_token: Option<String>,
593) {
594    executor
595        .spawn(async move {
596            if let Some(dir) = File::open(path.clone()).log_err() {
597                match ashpd::desktop::open_uri::OpenDirectoryRequest::default()
598                    .activation_token(activation_token.map(ashpd::ActivationToken::from))
599                    .send(&dir.as_fd())
600                    .await
601                {
602                    Ok(_) => return,
603                    Err(e) => log::error!("Failed to open with dbus: {}", e),
604                }
605                if path.is_dir() {
606                    open::that_detached(path).log_err();
607                } else {
608                    open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
609                }
610            }
611        })
612        .detach();
613}
614
615#[allow(unused)]
616pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
617    let diff = a - b;
618    diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
619}
620
621#[cfg(any(feature = "wayland", feature = "x11"))]
622pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
623    let mut locales = Vec::default();
624    if let Some(locale) = env::var_os("LC_CTYPE") {
625        locales.push(locale);
626    }
627    locales.push(OsString::from("C"));
628    let mut state: Option<xkb::compose::State> = None;
629    for locale in locales {
630        if let Ok(table) =
631            xkb::compose::Table::new_from_locale(&cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
632        {
633            state = Some(xkb::compose::State::new(
634                &table,
635                xkb::compose::STATE_NO_FLAGS,
636            ));
637            break;
638        }
639    }
640    state
641}
642
643#[cfg(any(feature = "wayland", feature = "x11"))]
644pub(super) unsafe fn read_fd(mut fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
645    let mut file = unsafe { File::from_raw_fd(fd.as_raw_fd()) };
646    let mut buffer = Vec::new();
647    file.read_to_end(&mut buffer)?;
648    Ok(buffer)
649}
650
651#[cfg(any(feature = "wayland", feature = "x11"))]
652pub(super) const DEFAULT_CURSOR_ICON_NAME: &str = "left_ptr";
653
654impl CursorStyle {
655    #[cfg(any(feature = "wayland", feature = "x11"))]
656    pub(super) fn to_icon_names(&self) -> &'static [&'static str] {
657        // Based on cursor names from chromium:
658        // https://github.com/chromium/chromium/blob/d3069cf9c973dc3627fa75f64085c6a86c8f41bf/ui/base/cursor/cursor_factory.cc#L113
659        match self {
660            CursorStyle::Arrow => &[DEFAULT_CURSOR_ICON_NAME],
661            CursorStyle::IBeam => &["text", "xterm"],
662            CursorStyle::Crosshair => &["crosshair", "cross"],
663            CursorStyle::ClosedHand => &["closedhand", "grabbing", "hand2"],
664            CursorStyle::OpenHand => &["openhand", "grab", "hand1"],
665            CursorStyle::PointingHand => &["pointer", "hand", "hand2"],
666            CursorStyle::ResizeLeft => &["w-resize", "left_side"],
667            CursorStyle::ResizeRight => &["e-resize", "right_side"],
668            CursorStyle::ResizeLeftRight => &["ew-resize", "sb_h_double_arrow"],
669            CursorStyle::ResizeUp => &["n-resize", "top_side"],
670            CursorStyle::ResizeDown => &["s-resize", "bottom_side"],
671            CursorStyle::ResizeUpDown => &["sb_v_double_arrow", "ns-resize"],
672            CursorStyle::ResizeUpLeftDownRight => &["size_fdiag", "bd_double_arrow", "nwse-resize"],
673            CursorStyle::ResizeUpRightDownLeft => &["size_bdiag", "nesw-resize", "fd_double_arrow"],
674            CursorStyle::ResizeColumn => &["col-resize", "sb_h_double_arrow"],
675            CursorStyle::ResizeRow => &["row-resize", "sb_v_double_arrow"],
676            CursorStyle::IBeamCursorForVerticalLayout => &["vertical-text"],
677            CursorStyle::OperationNotAllowed => &["not-allowed", "crossed_circle"],
678            CursorStyle::DragLink => &["alias"],
679            CursorStyle::DragCopy => &["copy"],
680            CursorStyle::ContextualMenu => &["context-menu"],
681            CursorStyle::None => {
682                #[cfg(debug_assertions)]
683                panic!("CursorStyle::None should be handled separately in the client");
684                #[cfg(not(debug_assertions))]
685                &[DEFAULT_CURSOR_ICON_NAME]
686            }
687        }
688    }
689}
690
691#[cfg(any(feature = "wayland", feature = "x11"))]
692pub(super) fn log_cursor_icon_warning(message: impl std::fmt::Display) {
693    if let Ok(xcursor_path) = env::var("XCURSOR_PATH") {
694        log::warn!(
695            "{:#}\ncursor icon loading may be failing if XCURSOR_PATH environment variable is invalid. \
696                    XCURSOR_PATH overrides the default icon search. Its current value is '{}'",
697            message,
698            xcursor_path
699        );
700    } else {
701        log::warn!("{:#}", message);
702    }
703}
704
705#[cfg(any(feature = "wayland", feature = "x11"))]
706impl crate::Keystroke {
707    pub(super) fn from_xkb(
708        state: &State,
709        mut modifiers: crate::Modifiers,
710        keycode: Keycode,
711    ) -> Self {
712        let key_utf32 = state.key_get_utf32(keycode);
713        let key_utf8 = state.key_get_utf8(keycode);
714        let key_sym = state.key_get_one_sym(keycode);
715
716        let key = match key_sym {
717            Keysym::Return => "enter".to_owned(),
718            Keysym::Prior => "pageup".to_owned(),
719            Keysym::Next => "pagedown".to_owned(),
720            Keysym::ISO_Left_Tab => "tab".to_owned(),
721            Keysym::KP_Prior => "pageup".to_owned(),
722            Keysym::KP_Next => "pagedown".to_owned(),
723            Keysym::XF86_Back => "back".to_owned(),
724            Keysym::XF86_Forward => "forward".to_owned(),
725            Keysym::XF86_Cut => "cut".to_owned(),
726            Keysym::XF86_Copy => "copy".to_owned(),
727            Keysym::XF86_Paste => "paste".to_owned(),
728            Keysym::XF86_New => "new".to_owned(),
729            Keysym::XF86_Open => "open".to_owned(),
730            Keysym::XF86_Save => "save".to_owned(),
731
732            Keysym::comma => ",".to_owned(),
733            Keysym::period => ".".to_owned(),
734            Keysym::less => "<".to_owned(),
735            Keysym::greater => ">".to_owned(),
736            Keysym::slash => "/".to_owned(),
737            Keysym::question => "?".to_owned(),
738
739            Keysym::semicolon => ";".to_owned(),
740            Keysym::colon => ":".to_owned(),
741            Keysym::apostrophe => "'".to_owned(),
742            Keysym::quotedbl => "\"".to_owned(),
743
744            Keysym::bracketleft => "[".to_owned(),
745            Keysym::braceleft => "{".to_owned(),
746            Keysym::bracketright => "]".to_owned(),
747            Keysym::braceright => "}".to_owned(),
748            Keysym::backslash => "\\".to_owned(),
749            Keysym::bar => "|".to_owned(),
750
751            Keysym::grave => "`".to_owned(),
752            Keysym::asciitilde => "~".to_owned(),
753            Keysym::exclam => "!".to_owned(),
754            Keysym::at => "@".to_owned(),
755            Keysym::numbersign => "#".to_owned(),
756            Keysym::dollar => "$".to_owned(),
757            Keysym::percent => "%".to_owned(),
758            Keysym::asciicircum => "^".to_owned(),
759            Keysym::ampersand => "&".to_owned(),
760            Keysym::asterisk => "*".to_owned(),
761            Keysym::parenleft => "(".to_owned(),
762            Keysym::parenright => ")".to_owned(),
763            Keysym::minus => "-".to_owned(),
764            Keysym::underscore => "_".to_owned(),
765            Keysym::equal => "=".to_owned(),
766            Keysym::plus => "+".to_owned(),
767
768            _ => {
769                let name = xkb::keysym_get_name(key_sym).to_lowercase();
770                if key_sym.is_keypad_key() {
771                    name.replace("kp_", "")
772                } else {
773                    name
774                }
775            }
776        };
777
778        if modifiers.shift {
779            // we only include the shift for upper-case letters by convention,
780            // so don't include for numbers and symbols, but do include for
781            // tab/enter, etc.
782            if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() {
783                modifiers.shift = false;
784            }
785        }
786
787        // Ignore control characters (and DEL) for the purposes of key_char
788        let key_char =
789            (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
790
791        Self {
792            modifiers,
793            key,
794            key_char,
795        }
796    }
797
798    /**
799     * Returns which symbol the dead key represents
800     * <https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux>
801     */
802    pub fn underlying_dead_key(keysym: Keysym) -> Option<String> {
803        match keysym {
804            Keysym::dead_grave => Some("`".to_owned()),
805            Keysym::dead_acute => Some("´".to_owned()),
806            Keysym::dead_circumflex => Some("^".to_owned()),
807            Keysym::dead_tilde => Some("~".to_owned()),
808            Keysym::dead_macron => Some("¯".to_owned()),
809            Keysym::dead_breve => Some("˘".to_owned()),
810            Keysym::dead_abovedot => Some("˙".to_owned()),
811            Keysym::dead_diaeresis => Some("¨".to_owned()),
812            Keysym::dead_abovering => Some("˚".to_owned()),
813            Keysym::dead_doubleacute => Some("˝".to_owned()),
814            Keysym::dead_caron => Some("ˇ".to_owned()),
815            Keysym::dead_cedilla => Some("¸".to_owned()),
816            Keysym::dead_ogonek => Some("˛".to_owned()),
817            Keysym::dead_iota => Some("ͅ".to_owned()),
818            Keysym::dead_voiced_sound => Some("".to_owned()),
819            Keysym::dead_semivoiced_sound => Some("".to_owned()),
820            Keysym::dead_belowdot => Some("̣̣".to_owned()),
821            Keysym::dead_hook => Some("̡".to_owned()),
822            Keysym::dead_horn => Some("̛".to_owned()),
823            Keysym::dead_stroke => Some("̶̶".to_owned()),
824            Keysym::dead_abovecomma => Some("̓̓".to_owned()),
825            Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
826            Keysym::dead_doublegrave => Some("̏".to_owned()),
827            Keysym::dead_belowring => Some("˳".to_owned()),
828            Keysym::dead_belowmacron => Some("̱".to_owned()),
829            Keysym::dead_belowcircumflex => Some("".to_owned()),
830            Keysym::dead_belowtilde => Some("̰".to_owned()),
831            Keysym::dead_belowbreve => Some("̮".to_owned()),
832            Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
833            Keysym::dead_invertedbreve => Some("̯".to_owned()),
834            Keysym::dead_belowcomma => Some("̦".to_owned()),
835            Keysym::dead_currency => None,
836            Keysym::dead_lowline => None,
837            Keysym::dead_aboveverticalline => None,
838            Keysym::dead_belowverticalline => None,
839            Keysym::dead_longsolidusoverlay => None,
840            Keysym::dead_a => None,
841            Keysym::dead_A => None,
842            Keysym::dead_e => None,
843            Keysym::dead_E => None,
844            Keysym::dead_i => None,
845            Keysym::dead_I => None,
846            Keysym::dead_o => None,
847            Keysym::dead_O => None,
848            Keysym::dead_u => None,
849            Keysym::dead_U => None,
850            Keysym::dead_small_schwa => Some("ə".to_owned()),
851            Keysym::dead_capital_schwa => Some("Ə".to_owned()),
852            Keysym::dead_greek => None,
853            _ => None,
854        }
855    }
856}
857
858#[cfg(any(feature = "wayland", feature = "x11"))]
859impl crate::Modifiers {
860    pub(super) fn from_xkb(keymap_state: &State) -> Self {
861        let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
862        let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
863        let control =
864            keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
865        let platform =
866            keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
867        Self {
868            shift,
869            alt,
870            control,
871            platform,
872            function: false,
873        }
874    }
875}
876
877#[cfg(any(feature = "wayland", feature = "x11"))]
878impl crate::Capslock {
879    pub(super) fn from_xkb(keymap_state: &State) -> Self {
880        let on = keymap_state.mod_name_is_active(xkb::MOD_NAME_CAPS, xkb::STATE_MODS_EFFECTIVE);
881        Self { on }
882    }
883}
884
885#[cfg(test)]
886mod tests {
887    use super::*;
888    use crate::{Point, px};
889
890    #[test]
891    fn test_is_within_click_distance() {
892        let zero = Point::new(px(0.0), px(0.0));
893        assert_eq!(
894            is_within_click_distance(zero, Point::new(px(5.0), px(5.0))),
895            true
896        );
897        assert_eq!(
898            is_within_click_distance(zero, Point::new(px(-4.9), px(5.0))),
899            true
900        );
901        assert_eq!(
902            is_within_click_distance(Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0))),
903            true
904        );
905        assert_eq!(
906            is_within_click_distance(zero, Point::new(px(5.0), px(5.1))),
907            false
908        );
909    }
910}