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        true
  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                let mut xdg_open_failed = false;
 637                for mut command in open::commands(uri.to_string()) {
 638                    if let Some(token) = activation_token.as_ref() {
 639                        command.env("XDG_ACTIVATION_TOKEN", token);
 640                    }
 641                    let program = format!("{:?}", command.get_program());
 642                    match smol::process::Command::from(command).spawn() {
 643                        Ok(mut cmd) => match cmd.status().await {
 644                            Ok(status) if status.success() => return,
 645                            Ok(status) => {
 646                                log::error!("Command {} exited with status: {}", program, status);
 647                                xdg_open_failed = true;
 648                            }
 649                            Err(e) => {
 650                                log::error!("Failed to get status from {}: {}", program, e);
 651                                xdg_open_failed = true;
 652                            }
 653                        },
 654                        Err(e) => {
 655                            log::error!("Failed to open with {}: {}", program, e);
 656                            xdg_open_failed = true;
 657                        }
 658                    }
 659                }
 660
 661                if xdg_open_failed {
 662                    match ashpd::desktop::open_uri::OpenFileRequest::default()
 663                        .activation_token(activation_token.map(ashpd::ActivationToken::from))
 664                        .send_uri(&uri)
 665                        .await
 666                        .and_then(|e| e.response())
 667                    {
 668                        Ok(()) => {}
 669                        Err(ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled)) => {}
 670                        Err(e) => {
 671                            log::error!("Failed to open with dbus: {}", e);
 672                        }
 673                    }
 674                }
 675            })
 676            .detach();
 677    }
 678}
 679
 680#[cfg(any(feature = "x11", feature = "wayland"))]
 681pub(super) fn reveal_path_internal(
 682    executor: BackgroundExecutor,
 683    path: PathBuf,
 684    activation_token: Option<String>,
 685) {
 686    executor
 687        .spawn(async move {
 688            if let Some(dir) = File::open(path.clone()).log_err() {
 689                match ashpd::desktop::open_uri::OpenDirectoryRequest::default()
 690                    .activation_token(activation_token.map(ashpd::ActivationToken::from))
 691                    .send(&dir.as_fd())
 692                    .await
 693                {
 694                    Ok(_) => return,
 695                    Err(e) => log::error!("Failed to open with dbus: {}", e),
 696                }
 697                if path.is_dir() {
 698                    open::that_detached(path).log_err();
 699                } else {
 700                    open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
 701                }
 702            }
 703        })
 704        .detach();
 705}
 706
 707#[cfg(any(feature = "wayland", feature = "x11"))]
 708pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool {
 709    let diff = a - b;
 710    diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE
 711}
 712
 713#[cfg(any(feature = "wayland", feature = "x11"))]
 714pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> {
 715    let mut locales = Vec::default();
 716    if let Some(locale) = env::var_os("LC_CTYPE") {
 717        locales.push(locale);
 718    }
 719    locales.push(OsString::from("C"));
 720    let mut state: Option<xkb::compose::State> = None;
 721    for locale in locales {
 722        if let Ok(table) =
 723            xkb::compose::Table::new_from_locale(cx, &locale, xkb::compose::COMPILE_NO_FLAGS)
 724        {
 725            state = Some(xkb::compose::State::new(
 726                &table,
 727                xkb::compose::STATE_NO_FLAGS,
 728            ));
 729            break;
 730        }
 731    }
 732    state
 733}
 734
 735#[cfg(any(feature = "wayland", feature = "x11"))]
 736pub(super) unsafe fn read_fd(fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
 737    let mut file = unsafe { File::from_raw_fd(fd.into_raw_fd()) };
 738    let mut buffer = Vec::new();
 739    file.read_to_end(&mut buffer)?;
 740    Ok(buffer)
 741}
 742
 743#[cfg(any(feature = "wayland", feature = "x11"))]
 744pub(super) const DEFAULT_CURSOR_ICON_NAME: &str = "left_ptr";
 745
 746#[cfg(any(feature = "wayland", feature = "x11"))]
 747pub(super) fn cursor_style_to_icon_names(style: CursorStyle) -> &'static [&'static str] {
 748    // Based on cursor names from chromium:
 749    // https://github.com/chromium/chromium/blob/d3069cf9c973dc3627fa75f64085c6a86c8f41bf/ui/base/cursor/cursor_factory.cc#L113
 750    match style {
 751        CursorStyle::Arrow => &[DEFAULT_CURSOR_ICON_NAME],
 752        CursorStyle::IBeam => &["text", "xterm"],
 753        CursorStyle::Crosshair => &["crosshair", "cross"],
 754        CursorStyle::ClosedHand => &["closedhand", "grabbing", "hand2"],
 755        CursorStyle::OpenHand => &["openhand", "grab", "hand1"],
 756        CursorStyle::PointingHand => &["pointer", "hand", "hand2"],
 757        CursorStyle::ResizeLeft => &["w-resize", "left_side"],
 758        CursorStyle::ResizeRight => &["e-resize", "right_side"],
 759        CursorStyle::ResizeLeftRight => &["ew-resize", "sb_h_double_arrow"],
 760        CursorStyle::ResizeUp => &["n-resize", "top_side"],
 761        CursorStyle::ResizeDown => &["s-resize", "bottom_side"],
 762        CursorStyle::ResizeUpDown => &["sb_v_double_arrow", "ns-resize"],
 763        CursorStyle::ResizeUpLeftDownRight => &["size_fdiag", "bd_double_arrow", "nwse-resize"],
 764        CursorStyle::ResizeUpRightDownLeft => &["size_bdiag", "nesw-resize", "fd_double_arrow"],
 765        CursorStyle::ResizeColumn => &["col-resize", "sb_h_double_arrow"],
 766        CursorStyle::ResizeRow => &["row-resize", "sb_v_double_arrow"],
 767        CursorStyle::IBeamCursorForVerticalLayout => &["vertical-text"],
 768        CursorStyle::OperationNotAllowed => &["not-allowed", "crossed_circle"],
 769        CursorStyle::DragLink => &["alias"],
 770        CursorStyle::DragCopy => &["copy"],
 771        CursorStyle::ContextualMenu => &["context-menu"],
 772        CursorStyle::None => {
 773            #[cfg(debug_assertions)]
 774            panic!("CursorStyle::None should be handled separately in the client");
 775            #[cfg(not(debug_assertions))]
 776            &[DEFAULT_CURSOR_ICON_NAME]
 777        }
 778    }
 779}
 780
 781#[cfg(any(feature = "wayland", feature = "x11"))]
 782pub(super) fn log_cursor_icon_warning(message: impl std::fmt::Display) {
 783    if let Ok(xcursor_path) = env::var("XCURSOR_PATH") {
 784        log::warn!(
 785            "{:#}\ncursor icon loading may be failing if XCURSOR_PATH environment variable is invalid. \
 786                    XCURSOR_PATH overrides the default icon search. Its current value is '{}'",
 787            message,
 788            xcursor_path
 789        );
 790    } else {
 791        log::warn!("{:#}", message);
 792    }
 793}
 794
 795#[cfg(any(feature = "wayland", feature = "x11"))]
 796fn guess_ascii(keycode: Keycode, shift: bool) -> Option<char> {
 797    let c = match (keycode.raw(), shift) {
 798        (24, _) => 'q',
 799        (25, _) => 'w',
 800        (26, _) => 'e',
 801        (27, _) => 'r',
 802        (28, _) => 't',
 803        (29, _) => 'y',
 804        (30, _) => 'u',
 805        (31, _) => 'i',
 806        (32, _) => 'o',
 807        (33, _) => 'p',
 808        (34, false) => '[',
 809        (34, true) => '{',
 810        (35, false) => ']',
 811        (35, true) => '}',
 812        (38, _) => 'a',
 813        (39, _) => 's',
 814        (40, _) => 'd',
 815        (41, _) => 'f',
 816        (42, _) => 'g',
 817        (43, _) => 'h',
 818        (44, _) => 'j',
 819        (45, _) => 'k',
 820        (46, _) => 'l',
 821        (47, false) => ';',
 822        (47, true) => ':',
 823        (48, false) => '\'',
 824        (48, true) => '"',
 825        (49, false) => '`',
 826        (49, true) => '~',
 827        (51, false) => '\\',
 828        (51, true) => '|',
 829        (52, _) => 'z',
 830        (53, _) => 'x',
 831        (54, _) => 'c',
 832        (55, _) => 'v',
 833        (56, _) => 'b',
 834        (57, _) => 'n',
 835        (58, _) => 'm',
 836        (59, false) => ',',
 837        (59, true) => '>',
 838        (60, false) => '.',
 839        (60, true) => '<',
 840        (61, false) => '/',
 841        (61, true) => '?',
 842
 843        _ => return None,
 844    };
 845
 846    Some(c)
 847}
 848
 849#[cfg(any(feature = "wayland", feature = "x11"))]
 850pub(super) fn keystroke_from_xkb(
 851    state: &State,
 852    mut modifiers: gpui::Modifiers,
 853    keycode: Keycode,
 854) -> gpui::Keystroke {
 855    let key_utf32 = state.key_get_utf32(keycode);
 856    let key_utf8 = state.key_get_utf8(keycode);
 857    let key_sym = state.key_get_one_sym(keycode);
 858
 859    let key = match key_sym {
 860        Keysym::Return => "enter".to_owned(),
 861        Keysym::Prior => "pageup".to_owned(),
 862        Keysym::Next => "pagedown".to_owned(),
 863        Keysym::ISO_Left_Tab => "tab".to_owned(),
 864        Keysym::KP_Prior => "pageup".to_owned(),
 865        Keysym::KP_Next => "pagedown".to_owned(),
 866        Keysym::XF86_Back => "back".to_owned(),
 867        Keysym::XF86_Forward => "forward".to_owned(),
 868        Keysym::XF86_Cut => "cut".to_owned(),
 869        Keysym::XF86_Copy => "copy".to_owned(),
 870        Keysym::XF86_Paste => "paste".to_owned(),
 871        Keysym::XF86_New => "new".to_owned(),
 872        Keysym::XF86_Open => "open".to_owned(),
 873        Keysym::XF86_Save => "save".to_owned(),
 874
 875        Keysym::comma => ",".to_owned(),
 876        Keysym::period => ".".to_owned(),
 877        Keysym::less => "<".to_owned(),
 878        Keysym::greater => ">".to_owned(),
 879        Keysym::slash => "/".to_owned(),
 880        Keysym::question => "?".to_owned(),
 881
 882        Keysym::semicolon => ";".to_owned(),
 883        Keysym::colon => ":".to_owned(),
 884        Keysym::apostrophe => "'".to_owned(),
 885        Keysym::quotedbl => "\"".to_owned(),
 886
 887        Keysym::bracketleft => "[".to_owned(),
 888        Keysym::braceleft => "{".to_owned(),
 889        Keysym::bracketright => "]".to_owned(),
 890        Keysym::braceright => "}".to_owned(),
 891        Keysym::backslash => "\\".to_owned(),
 892        Keysym::bar => "|".to_owned(),
 893
 894        Keysym::grave => "`".to_owned(),
 895        Keysym::asciitilde => "~".to_owned(),
 896        Keysym::exclam => "!".to_owned(),
 897        Keysym::at => "@".to_owned(),
 898        Keysym::numbersign => "#".to_owned(),
 899        Keysym::dollar => "$".to_owned(),
 900        Keysym::percent => "%".to_owned(),
 901        Keysym::asciicircum => "^".to_owned(),
 902        Keysym::ampersand => "&".to_owned(),
 903        Keysym::asterisk => "*".to_owned(),
 904        Keysym::parenleft => "(".to_owned(),
 905        Keysym::parenright => ")".to_owned(),
 906        Keysym::minus => "-".to_owned(),
 907        Keysym::underscore => "_".to_owned(),
 908        Keysym::equal => "=".to_owned(),
 909        Keysym::plus => "+".to_owned(),
 910        Keysym::space => "space".to_owned(),
 911        Keysym::BackSpace => "backspace".to_owned(),
 912        Keysym::Tab => "tab".to_owned(),
 913        Keysym::Delete => "delete".to_owned(),
 914        Keysym::Escape => "escape".to_owned(),
 915
 916        Keysym::Left => "left".to_owned(),
 917        Keysym::Right => "right".to_owned(),
 918        Keysym::Up => "up".to_owned(),
 919        Keysym::Down => "down".to_owned(),
 920        Keysym::Home => "home".to_owned(),
 921        Keysym::End => "end".to_owned(),
 922        Keysym::Insert => "insert".to_owned(),
 923
 924        _ => {
 925            let name = xkb::keysym_get_name(key_sym).to_lowercase();
 926            if key_sym.is_keypad_key() {
 927                name.replace("kp_", "")
 928            } else if let Some(key) = key_utf8.chars().next()
 929                && key_utf8.len() == 1
 930                && key.is_ascii()
 931            {
 932                if key.is_ascii_graphic() {
 933                    key_utf8.to_lowercase()
 934                // map ctrl-a to `a`
 935                // ctrl-0..9 may emit control codes like ctrl-[, but
 936                // we don't want to map them to `[`
 937                } else if key_utf32 <= 0x1f
 938                    && !name.chars().next().is_some_and(|c| c.is_ascii_digit())
 939                {
 940                    ((key_utf32 as u8 + 0x40) as char)
 941                        .to_ascii_lowercase()
 942                        .to_string()
 943                } else {
 944                    name
 945                }
 946            } else if let Some(key_en) = guess_ascii(keycode, modifiers.shift) {
 947                String::from(key_en)
 948            } else {
 949                name
 950            }
 951        }
 952    };
 953
 954    if modifiers.shift {
 955        // we only include the shift for upper-case letters by convention,
 956        // so don't include for numbers and symbols, but do include for
 957        // tab/enter, etc.
 958        if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() {
 959            modifiers.shift = false;
 960        }
 961    }
 962
 963    // Ignore control characters (and DEL) for the purposes of key_char
 964    let key_char =
 965        (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
 966
 967    gpui::Keystroke {
 968        modifiers,
 969        key,
 970        key_char,
 971    }
 972}
 973
 974/**
 975 * Returns which symbol the dead key represents
 976 * <https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux>
 977 */
 978#[cfg(any(feature = "wayland", feature = "x11"))]
 979pub fn keystroke_underlying_dead_key(keysym: Keysym) -> Option<String> {
 980    match keysym {
 981        Keysym::dead_grave => Some("`".to_owned()),
 982        Keysym::dead_acute => Some("´".to_owned()),
 983        Keysym::dead_circumflex => Some("^".to_owned()),
 984        Keysym::dead_tilde => Some("~".to_owned()),
 985        Keysym::dead_macron => Some("¯".to_owned()),
 986        Keysym::dead_breve => Some("˘".to_owned()),
 987        Keysym::dead_abovedot => Some("˙".to_owned()),
 988        Keysym::dead_diaeresis => Some("¨".to_owned()),
 989        Keysym::dead_abovering => Some("˚".to_owned()),
 990        Keysym::dead_doubleacute => Some("˝".to_owned()),
 991        Keysym::dead_caron => Some("ˇ".to_owned()),
 992        Keysym::dead_cedilla => Some("¸".to_owned()),
 993        Keysym::dead_ogonek => Some("˛".to_owned()),
 994        Keysym::dead_iota => Some("ͅ".to_owned()),
 995        Keysym::dead_voiced_sound => Some("".to_owned()),
 996        Keysym::dead_semivoiced_sound => Some("".to_owned()),
 997        Keysym::dead_belowdot => Some("̣̣".to_owned()),
 998        Keysym::dead_hook => Some("̡".to_owned()),
 999        Keysym::dead_horn => Some("̛".to_owned()),
1000        Keysym::dead_stroke => Some("̶̶".to_owned()),
1001        Keysym::dead_abovecomma => Some("̓̓".to_owned()),
1002        Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
1003        Keysym::dead_doublegrave => Some("̏".to_owned()),
1004        Keysym::dead_belowring => Some("˳".to_owned()),
1005        Keysym::dead_belowmacron => Some("̱".to_owned()),
1006        Keysym::dead_belowcircumflex => Some("".to_owned()),
1007        Keysym::dead_belowtilde => Some("̰".to_owned()),
1008        Keysym::dead_belowbreve => Some("̮".to_owned()),
1009        Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
1010        Keysym::dead_invertedbreve => Some("̯".to_owned()),
1011        Keysym::dead_belowcomma => Some("̦".to_owned()),
1012        Keysym::dead_currency => None,
1013        Keysym::dead_lowline => None,
1014        Keysym::dead_aboveverticalline => None,
1015        Keysym::dead_belowverticalline => None,
1016        Keysym::dead_longsolidusoverlay => None,
1017        Keysym::dead_a => None,
1018        Keysym::dead_A => None,
1019        Keysym::dead_e => None,
1020        Keysym::dead_E => None,
1021        Keysym::dead_i => None,
1022        Keysym::dead_I => None,
1023        Keysym::dead_o => None,
1024        Keysym::dead_O => None,
1025        Keysym::dead_u => None,
1026        Keysym::dead_U => None,
1027        Keysym::dead_small_schwa => Some("ə".to_owned()),
1028        Keysym::dead_capital_schwa => Some("Ə".to_owned()),
1029        Keysym::dead_greek => None,
1030        _ => None,
1031    }
1032}
1033#[cfg(any(feature = "wayland", feature = "x11"))]
1034pub(super) fn modifiers_from_xkb(keymap_state: &State) -> gpui::Modifiers {
1035    let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE);
1036    let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE);
1037    let control = keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE);
1038    let platform = keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE);
1039    gpui::Modifiers {
1040        shift,
1041        alt,
1042        control,
1043        platform,
1044        function: false,
1045    }
1046}
1047
1048#[cfg(any(feature = "wayland", feature = "x11"))]
1049pub(super) fn capslock_from_xkb(keymap_state: &State) -> gpui::Capslock {
1050    let on = keymap_state.mod_name_is_active(xkb::MOD_NAME_CAPS, xkb::STATE_MODS_EFFECTIVE);
1051    gpui::Capslock { on }
1052}
1053
1054/// Resolve a Linux `dev_t` to PCI vendor/device IDs via sysfs, returning a
1055/// [`CompositorGpuHint`] that the GPU adapter selection code can use to
1056/// prioritize the compositor's rendering device.
1057#[cfg(any(feature = "wayland", feature = "x11"))]
1058pub(super) fn compositor_gpu_hint_from_dev_t(dev: u64) -> Option<gpui_wgpu::CompositorGpuHint> {
1059    fn dev_major(dev: u64) -> u32 {
1060        ((dev >> 8) & 0xfff) as u32 | (((dev >> 32) & !0xfff) as u32)
1061    }
1062
1063    fn dev_minor(dev: u64) -> u32 {
1064        (dev & 0xff) as u32 | (((dev >> 12) & !0xff) as u32)
1065    }
1066
1067    fn read_sysfs_hex_id(path: &str) -> Option<u32> {
1068        let content = std::fs::read_to_string(path).ok()?;
1069        let trimmed = content.trim().strip_prefix("0x").unwrap_or(content.trim());
1070        u32::from_str_radix(trimmed, 16).ok()
1071    }
1072
1073    let major = dev_major(dev);
1074    let minor = dev_minor(dev);
1075
1076    let vendor_path = format!("/sys/dev/char/{major}:{minor}/device/vendor");
1077    let device_path = format!("/sys/dev/char/{major}:{minor}/device/device");
1078
1079    let vendor_id = read_sysfs_hex_id(&vendor_path)?;
1080    let device_id = read_sysfs_hex_id(&device_path)?;
1081
1082    log::info!(
1083        "Compositor GPU hint: vendor={:#06x}, device={:#06x} (from dev {major}:{minor})",
1084        vendor_id,
1085        device_id,
1086    );
1087
1088    Some(gpui_wgpu::CompositorGpuHint {
1089        vendor_id,
1090        device_id,
1091    })
1092}
1093
1094#[cfg(test)]
1095mod tests {
1096    use super::*;
1097    use gpui::{Point, px};
1098
1099    #[test]
1100    fn test_is_within_click_distance() {
1101        let zero = Point::new(px(0.0), px(0.0));
1102        assert!(is_within_click_distance(zero, Point::new(px(5.0), px(5.0))));
1103        assert!(is_within_click_distance(
1104            zero,
1105            Point::new(px(-4.9), px(5.0))
1106        ));
1107        assert!(is_within_click_distance(
1108            Point::new(px(3.0), px(2.0)),
1109            Point::new(px(-2.0), px(-2.0))
1110        ));
1111        assert!(!is_within_click_distance(
1112            zero,
1113            Point::new(px(5.0), px(5.1))
1114        ),);
1115    }
1116}