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