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