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