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