platform.rs

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