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