gpui/platform/linux/
platform.rs

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