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