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