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