1327 lines · 46.3 KB · Rust
RawDownload
use std::{    env,    path::{Path, PathBuf},    rc::Rc,    sync::Arc,};#[cfg(any(feature = "wayland", feature = "x11"))]use std::{    ffi::OsString,    fs::File,    io::Read as _,    os::fd::{AsFd, AsRawFd},    time::Duration,}; use anyhow::{Context as _, anyhow};use calloop::{LoopSignal, channel::Sender};use futures::channel::oneshot;use gpui_util::{ResultExt as _, new_std_command};#[cfg(any(feature = "wayland", feature = "x11"))]use xkbcommon::xkb::{self, Keycode, Keysym, State}; use crate::linux::{LinuxDispatcher, PriorityQueueCalloopReceiver};use gpui::{    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,    ForegroundExecutor, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform,    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,    PlatformWindow, Result, RunnableVariant, Task, ThermalState, WindowAppearance,    WindowButtonLayout, WindowParams,};#[cfg(any(feature = "wayland", feature = "x11"))]use gpui::{Pixels, Point, px}; #[cfg(any(feature = "wayland", feature = "x11"))]pub(crate) const SCROLL_LINES: f32 = 3.0; // Values match the defaults on GTK.// Taken from https://github.com/GNOME/gtk/blob/main/gtk/gtksettings.c#L320#[cfg(any(feature = "wayland", feature = "x11"))]pub(crate) const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(400);#[cfg(any(feature = "wayland", feature = "x11"))]pub(crate) const DOUBLE_CLICK_DISTANCE: Pixels = px(5.0);pub(crate) const KEYRING_LABEL: &str = "zed-github-account"; #[cfg(any(feature = "wayland", feature = "x11"))]const FILE_PICKER_PORTAL_MISSING: &str =    "Couldn't open file picker due to missing xdg-desktop-portal implementation."; pub(crate) trait LinuxClient {    fn compositor_name(&self) -> &'static str;    fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R;    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout>;    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>;    #[allow(unused)]    fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>>;    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>>;     #[cfg(feature = "screen-capture")]    fn is_screen_capture_supported(&self) -> bool {        true    }     #[cfg(feature = "screen-capture")]    fn screen_capture_sources(        &self,    ) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {        let (sources_tx, sources_rx) = oneshot::channel();        sources_tx            .send(Err(anyhow::anyhow!(                "gpui_linux was compiled without the screen-capture feature"            )))            .ok();        sources_rx    }     fn open_window(        &self,        handle: AnyWindowHandle,        options: WindowParams,    ) -> anyhow::Result<Box<dyn PlatformWindow>>;    fn set_cursor_style(&self, style: CursorStyle);    fn hide_cursor_until_mouse_moves(&self) {}    fn is_cursor_visible(&self) -> bool {        true    }    fn open_uri(&self, uri: &str);    fn reveal_path(&self, path: PathBuf);    fn write_to_primary(&self, item: ClipboardItem);    fn write_to_clipboard(&self, item: ClipboardItem);    fn read_from_primary(&self) -> Option<ClipboardItem>;    fn read_from_clipboard(&self) -> Option<ClipboardItem>;    fn active_window(&self) -> Option<AnyWindowHandle>;    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>>;    fn run(&self);     #[cfg(any(feature = "wayland", feature = "x11"))]    fn window_identifier(        &self,    ) -> impl Future<Output = Option<ashpd::WindowIdentifier>> + Send + 'static {        std::future::ready::<Option<ashpd::WindowIdentifier>>(None)    }} #[derive(Default)]pub(crate) struct PlatformHandlers {    pub(crate) open_urls: Option<Box<dyn FnMut(Vec<String>)>>,    pub(crate) quit: Option<Box<dyn FnMut()>>,    pub(crate) reopen: Option<Box<dyn FnMut()>>,    pub(crate) app_menu_action: Option<Box<dyn FnMut(&dyn Action)>>,    pub(crate) will_open_app_menu: Option<Box<dyn FnMut()>>,    pub(crate) validate_app_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,    pub(crate) keyboard_layout_change: Option<Box<dyn FnMut()>>,    pub(crate) system_wake: Option<Box<dyn FnMut()>>,} pub(crate) struct LinuxCommon {    pub(crate) background_executor: BackgroundExecutor,    pub(crate) foreground_executor: ForegroundExecutor,    pub(crate) text_system: Arc<dyn PlatformTextSystem>,    pub(crate) appearance: WindowAppearance,    pub(crate) auto_hide_scrollbars: bool,    pub(crate) button_layout: WindowButtonLayout,    pub(crate) callbacks: PlatformHandlers,    pub(crate) signal: LoopSignal,    pub(crate) menus: Vec<OwnedMenu>,    #[cfg_attr(        not(all(target_os = "linux", any(feature = "wayland", feature = "x11"))),        allow(dead_code)    )]    wake_sender: Sender<()>,    wake_listener_started: bool,} impl LinuxCommon {    pub fn new(        signal: LoopSignal,    ) -> (        Self,        PriorityQueueCalloopReceiver<RunnableVariant>,        calloop::channel::Channel<()>,    ) {        let (main_sender, main_receiver) = PriorityQueueCalloopReceiver::new();        let (wake_sender, wake_receiver) = calloop::channel::channel();         #[cfg(any(feature = "wayland", feature = "x11"))]        let text_system = Arc::new(crate::linux::CosmicTextSystem::new("IBM Plex Sans"));        #[cfg(not(any(feature = "wayland", feature = "x11")))]        let text_system = Arc::new(gpui::NoopTextSystem::new());         let callbacks = PlatformHandlers::default();         let dispatcher = Arc::new(LinuxDispatcher::new(main_sender));         let background_executor = BackgroundExecutor::new(dispatcher.clone());         let common = LinuxCommon {            background_executor,            foreground_executor: ForegroundExecutor::new(dispatcher),            text_system,            appearance: WindowAppearance::Light,            auto_hide_scrollbars: false,            button_layout: WindowButtonLayout::linux_default(),            callbacks,            signal,            menus: Vec::new(),            wake_sender,            wake_listener_started: false,        };         (common, main_receiver, wake_receiver)    }     pub(crate) fn start_wake_listener(&mut self) {        if !self.wake_listener_started {            #[cfg(all(target_os = "linux", any(feature = "wayland", feature = "x11")))]            smol::spawn({                let wake_sender = self.wake_sender.clone();                async move {                    if let Err(error) = listen_for_system_wake(wake_sender).await {                        log::debug!("failed to listen for system wake events: {error:?}");                    }                }            })            .detach();             self.wake_listener_started = true;        }    }     pub(crate) fn handle_system_wake(&mut self) {        if let Some(mut callback) = self.callbacks.system_wake.take() {            callback();            self.callbacks.system_wake = Some(callback);        }    }} #[cfg(all(target_os = "linux", any(feature = "wayland", feature = "x11")))]async fn listen_for_system_wake(wake_sender: Sender<()>) -> anyhow::Result<()> {    use futures::StreamExt as _;     let connection = ashpd::zbus::Connection::system().await?;    let proxy = ashpd::zbus::Proxy::new(        &connection,        "org.freedesktop.login1",        "/org/freedesktop/login1",        "org.freedesktop.login1.Manager",    )    .await?;    let mut sleep_events = proxy.receive_signal("PrepareForSleep").await?;     while let Some(message) = sleep_events.next().await {        let sleeping = message.body().deserialize::<bool>()?;        if !sleeping {            wake_sender.send(()).ok();        }    }     Ok(())} pub(crate) struct LinuxPlatform<P> {    pub(crate) inner: P,} impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {    fn background_executor(&self) -> BackgroundExecutor {        self.inner            .with_common(|common| common.background_executor.clone())    }     fn foreground_executor(&self) -> ForegroundExecutor {        self.inner            .with_common(|common| common.foreground_executor.clone())    }     fn text_system(&self) -> Arc<dyn PlatformTextSystem> {        self.inner.with_common(|common| common.text_system.clone())    }     fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {        self.inner.keyboard_layout()    }     fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {        Rc::new(gpui::DummyKeyboardMapper)    }     fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {        self.inner            .with_common(|common| common.callbacks.keyboard_layout_change = Some(callback));    }     fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}     fn thermal_state(&self) -> ThermalState {        ThermalState::Nominal    }     fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {        on_finish_launching();         LinuxClient::run(&self.inner);         let quit = self            .inner            .with_common(|common| common.callbacks.quit.take());        if let Some(mut fun) = quit {            fun();        }    }     fn quit(&self) {        self.inner.with_common(|common| common.signal.stop());    }     fn compositor_name(&self) -> &'static str {        self.inner.compositor_name()    }     fn restart(&self, binary_path: Option<PathBuf>) {        use std::os::unix::process::CommandExt as _;         // get the process id of the current process        let app_pid = std::process::id().to_string();        // get the path to the executable        let app_path = if let Some(path) = binary_path {            path        } else {            match self.app_path() {                Ok(path) => path,                Err(err) => {                    log::error!("Failed to get app path: {:?}", err);                    return;                }            }        };         log::info!("Restarting process, using app path: {:?}", app_path);         // Script to wait for the current process to exit and then restart the app.        // Pass dynamic values as positional parameters to avoid shell interpolation issues.        let script = r#"            while kill -0 "$0" 2>/dev/null; do                sleep 0.1            done             "$1"            "#;         #[allow(            clippy::disallowed_methods,            reason = "We are restarting ourselves, using std command thus is fine"        )]        let restart_process = new_std_command("/usr/bin/env")            .arg("bash")            .arg("-c")            .arg(script)            .arg(&app_pid)            .arg(&app_path)            .process_group(0)            .spawn();         match restart_process {            Ok(_) => self.quit(),            Err(e) => log::error!("failed to spawn restart script: {:?}", e),        }    }     fn activate(&self, _ignoring_other_apps: bool) {        log::info!("activate is not implemented on Linux, ignoring the call")    }     fn hide(&self) {        log::info!("hide is not implemented on Linux, ignoring the call")    }     fn hide_other_apps(&self) {        log::info!("hide_other_apps is not implemented on Linux, ignoring the call")    }     fn unhide_other_apps(&self) {        log::info!("unhide_other_apps is not implemented on Linux, ignoring the call")    }     fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {        self.inner.primary_display()    }     fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {        self.inner.displays()    }     #[cfg(feature = "screen-capture")]    fn is_screen_capture_supported(&self) -> bool {        self.inner.is_screen_capture_supported()    }     #[cfg(feature = "screen-capture")]    fn screen_capture_sources(        &self,    ) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {        self.inner.screen_capture_sources()    }     fn active_window(&self) -> Option<AnyWindowHandle> {        self.inner.active_window()    }     fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {        self.inner.window_stack()    }     fn open_window(        &self,        handle: AnyWindowHandle,        options: WindowParams,    ) -> anyhow::Result<Box<dyn PlatformWindow>> {        self.inner.open_window(handle, options)    }     fn open_url(&self, url: &str) {        self.inner.open_uri(url);    }     fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {        self.inner            .with_common(|common| common.callbacks.open_urls = Some(callback));    }     fn prompt_for_paths(        &self,        options: PathPromptOptions,    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {        let (done_tx, done_rx) = oneshot::channel();         #[cfg(not(any(feature = "wayland", feature = "x11")))]        let _ = (done_tx.send(Ok(None)), options);         #[cfg(any(feature = "wayland", feature = "x11"))]        let identifier = self.inner.window_identifier();         #[cfg(any(feature = "wayland", feature = "x11"))]        self.foreground_executor()            .spawn(async move {                let title = if options.directories {                    "Open Folder"                } else {                    "Open File"                };                 let request = match ashpd::desktop::file_chooser::OpenFileRequest::default()                    .identifier(identifier.await)                    .modal(true)                    .title(title)                    .accept_label(options.prompt.as_ref().map(gpui::SharedString::as_str))                    .multiple(options.multiple)                    .directory(options.directories)                    .send()                    .await                {                    Ok(request) => request,                    Err(err) => {                        let result = match err {                            ashpd::Error::PortalNotFound(_) => anyhow!(FILE_PICKER_PORTAL_MISSING),                            err => err.into(),                        };                        let _ = done_tx.send(Err(result));                        return;                    }                };                 let result = match request.response() {                    Ok(response) => Ok(Some(                        response                            .uris()                            .iter()                            .filter_map(|uri: &ashpd::Uri| url::Url::parse(uri.as_str()).ok())                            .filter_map(|uri: url::Url| uri.to_file_path().ok())                            .collect::<Vec<_>>(),                    )),                    Err(ashpd::Error::Response(_)) => Ok(None),                    Err(e) => Err(e.into()),                };                let _ = done_tx.send(result);            })            .detach();        done_rx    }     fn prompt_for_new_path(        &self,        directory: &Path,        suggested_name: Option<&str>,    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {        let (done_tx, done_rx) = oneshot::channel();         #[cfg(not(any(feature = "wayland", feature = "x11")))]        let _ = (done_tx.send(Ok(None)), directory, suggested_name);         #[cfg(any(feature = "wayland", feature = "x11"))]        let identifier = self.inner.window_identifier();         #[cfg(any(feature = "wayland", feature = "x11"))]        self.foreground_executor()            .spawn({                let directory = directory.to_owned();                let suggested_name = suggested_name.map(|s| s.to_owned());                 async move {                    let mut request_builder =                        ashpd::desktop::file_chooser::SaveFileRequest::default()                            .identifier(identifier.await)                            .modal(true)                            .title("Save File")                            .current_folder(directory)                            .expect("pathbuf should not be nul terminated");                     if let Some(suggested_name) = suggested_name {                        request_builder = request_builder.current_name(suggested_name.as_str());                    }                     let request = match request_builder.send().await {                        Ok(request) => request,                        Err(err) => {                            let result = match err {                                ashpd::Error::PortalNotFound(_) => {                                    anyhow!(FILE_PICKER_PORTAL_MISSING)                                }                                err => err.into(),                            };                            let _ = done_tx.send(Err(result));                            return;                        }                    };                     let result = match request.response() {                        Ok(response) => Ok(response                            .uris()                            .first()

Lines 1–500 of 1327.