Something went wrong. Try again.
fork of gpui
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361use 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>, app_name: Option<String>, system_notifications: crate::linux::system_notifications::SystemNotificationState, #[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(), app_name: None, system_notifications: crate::linux::system_notifications::SystemNotificationState::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() .and_then(|uri: &ashpd::Uri| url::Url::parse(uri.as_str()).ok()) .and_then(|uri: url::Url| uri.to_file_path().ok())), Err(ashpd::Error::Response(_)) => Ok(None), Err(e) => Err(e.into()), }; let _ = done_tx.send(result); } }) .detach();
done_rx }
fn can_select_mixed_files_and_dirs(&self) -> bool { // org.freedesktop.portal.FileChooser only supports "pick files" and "pick directories". false }
fn reveal_path(&self, path: &Path) { self.inner.reveal_path(path.to_owned()); }
fn open_with_system(&self, path: &Path) { let path = path.to_owned(); self.background_executor() .spawn(async move { #[allow( clippy::disallowed_methods, reason = "running on a background thread, so blocking is fine" )] new_std_command("xdg-open") .arg(path) .status() .context("invoking xdg-open") .log_err(); }) .detach(); }
fn on_quit(&self, callback: Box<dyn FnMut()>) { self.inner.with_common(|common| { common.callbacks.quit = Some(callback); }); }
fn on_reopen(&self, callback: Box<dyn FnMut()>) { self.inner.with_common(|common| { common.callbacks.reopen = Some(callback); }); }
fn on_system_wake(&self, callback: Box<dyn FnMut()>) { self.inner.with_common(|common| { common.callbacks.system_wake = Some(callback); common.start_wake_listener(); }); }
fn set_app_identity(&self, _identifier: &str, name: &str) { self.inner .with_common(|common| common.app_name = Some(name.to_string())); }
fn show_system_notification(&self, notification: gpui::SystemNotification) { self.inner.with_common(|common| { common .system_notifications .show(common.app_name.as_deref(), notification) }); }
fn dismiss_system_notification(&self, tag: &str) { self.inner .with_common(|common| common.system_notifications.dismiss(tag)); }
fn on_system_notification_response( &self, callback: Box<dyn FnMut(gpui::SystemNotificationResponse)>, ) { self.inner.with_common(|common| { let executor = common.foreground_executor.clone(); common.system_notifications.on_response(&executor, callback) }); }
fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) { self.inner.with_common(|common| { common.callbacks.app_menu_action = Some(callback); }); }
fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) { self.inner.with_common(|common| { common.callbacks.will_open_app_menu = Some(callback); }); }
fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) { self.inner.with_common(|common| { common.callbacks.validate_app_menu_command = Some(callback); }); }
fn app_path(&self) -> Result<PathBuf> { // get the path of the executable of the current process let app_path = env::current_exe()?; Ok(app_path) }
fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) { self.inner.with_common(|common| { common.menus = menus.into_iter().map(|menu| menu.owned()).collect(); }) }
fn get_menus(&self) -> Option<Vec<OwnedMenu>> { self.inner.with_common(|common| Some(common.menus.clone())) }
fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) { // todo(linux) }
fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> { Err(anyhow::Error::msg( "Platform<LinuxPlatform>::path_for_auxiliary_executable is not implemented yet", )) }
fn set_cursor_style(&self, style: CursorStyle) { self.inner.set_cursor_style(style) }
fn hide_cursor_until_mouse_moves(&self) { self.inner.hide_cursor_until_mouse_moves() }
fn is_cursor_visible(&self) -> bool { self.inner.is_cursor_visible() }
fn should_auto_hide_scrollbars(&self) -> bool { self.inner.with_common(|common| common.auto_hide_scrollbars) }
fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> { let url = url.to_string(); let username = username.to_string(); let password = password.to_vec(); self.background_executor().spawn(async move { let keyring = oo7::Keyring::new().await?; keyring.unlock().await?; keyring .create_item( KEYRING_LABEL, &vec![("url", &url), ("username", &username)], password, true, ) .await?; Ok(()) }) }
fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> { let url = url.to_string(); self.background_executor().spawn(async move { let keyring = oo7::Keyring::new().await?; keyring.unlock().await?;
let items = keyring.search_items(&vec![("url", &url)]).await?;
for item in items.into_iter() { if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) { let attributes = item.attributes().await?; let username = attributes .get("username") .context("Cannot find username in stored credentials")?; item.unlock().await?; let secret = item.secret().await?;
// we lose the zeroizing capabilities at this boundary, // a current limitation GPUI's credentials api return Ok(Some((username.to_string(), secret.to_vec()))); } else { continue; } } Ok(None) }) }
fn delete_credentials(&self, url: &str) -> Task<Result<()>> { let url = url.to_string(); self.background_executor().spawn(async move { let keyring = oo7::Keyring::new().await?; keyring.unlock().await?;
let items = keyring.search_items(&vec![("url", &url)]).await?;
for item in items.into_iter() { if item.label().await.is_ok_and(|label| label == KEYRING_LABEL) { item.delete().await?; return Ok(()); } }
Ok(()) }) }
fn window_appearance(&self) -> WindowAppearance { self.inner.with_common(|common| common.appearance) }
fn button_layout(&self) -> Option<WindowButtonLayout> { Some(self.inner.with_common(|common| common.button_layout)) }
fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> { Task::ready(Err(anyhow!("register_url_scheme unimplemented"))) }
fn write_to_primary(&self, item: ClipboardItem) { self.inner.write_to_primary(item) }
fn write_to_clipboard(&self, item: ClipboardItem) { self.inner.write_to_clipboard(item) }
fn read_from_primary(&self) -> Option<ClipboardItem> { self.inner.read_from_primary() }
fn read_from_clipboard(&self) -> Option<ClipboardItem> { self.inner.read_from_clipboard() }
fn add_recent_document(&self, _path: &Path) {}}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn open_uri_internal( executor: BackgroundExecutor, uri: &str, activation_token: Option<String>,) { if let Some(uri) = ashpd::Uri::parse(uri).log_err() { executor .spawn(async move { let mut xdg_open_failed = false; for mut command in open::commands(uri.to_string()) { if let Some(token) = activation_token.as_ref() { command.env("XDG_ACTIVATION_TOKEN", token); } let program = format!("{:?}", command.get_program()); match smol::process::Command::from(command).spawn() { Ok(mut cmd) => match cmd.status().await { Ok(status) if status.success() => return, Ok(status) => { log::error!("Command {} exited with status: {}", program, status); xdg_open_failed = true; } Err(e) => { log::error!("Failed to get status from {}: {}", program, e); xdg_open_failed = true; } }, Err(e) => { log::error!("Failed to open with {}: {}", program, e); xdg_open_failed = true; } } }
if xdg_open_failed { match ashpd::desktop::open_uri::OpenFileRequest::default() .activation_token(activation_token.map(ashpd::ActivationToken::from)) .send_uri(&uri) .await .and_then(|e| e.response()) { Ok(()) => {} Err(ashpd::Error::Response(ashpd::desktop::ResponseError::Cancelled)) => {} Err(e) => { log::error!("Failed to open with dbus: {}", e); } } } }) .detach(); }}
#[cfg(any(feature = "x11", feature = "wayland"))]pub(super) fn reveal_path_internal( executor: BackgroundExecutor, path: PathBuf, activation_token: Option<String>,) { executor .spawn(async move { if let Some(dir) = File::open(path.clone()).log_err() { match ashpd::desktop::open_uri::OpenDirectoryRequest::default() .activation_token(activation_token.map(ashpd::ActivationToken::from)) .send(&dir.as_fd()) .await { Ok(_) => return, Err(e) => log::error!("Failed to open with dbus: {}", e), } if path.is_dir() { open::that_detached(path).log_err(); } else { open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err(); } } }) .detach();}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn is_within_click_distance(a: Point<Pixels>, b: Point<Pixels>) -> bool { let diff = a - b; diff.x.abs() <= DOUBLE_CLICK_DISTANCE && diff.y.abs() <= DOUBLE_CLICK_DISTANCE}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::State> { let mut locales = Vec::default(); if let Some(locale) = env::var_os("LC_CTYPE") { locales.push(locale); } locales.push(OsString::from("C")); let mut state: Option<xkb::compose::State> = None; for locale in locales { if let Ok(table) = xkb::compose::Table::new_from_locale(cx, &locale, xkb::compose::COMPILE_NO_FLAGS) { state = Some(xkb::compose::State::new( &table, xkb::compose::STATE_NO_FLAGS, )); break; } } state}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) const PIPE_READ_TIMEOUT: Duration = Duration::from_secs(4);
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn read_fd_with_timeout( mut fd: filedescriptor::FileDescriptor, timeout: Duration,) -> Result<Vec<u8>> { fd.set_non_blocking(true)?; let mut buffer = Vec::new(); let mut chunk = [0u8; 8192]; loop { let mut poll_fds = [filedescriptor::pollfd { fd: fd.as_raw_fd(), events: filedescriptor::POLLIN, revents: 0, }]; let ready = match filedescriptor::poll(&mut poll_fds, Some(timeout)) { Ok(ready) => ready, Err(filedescriptor::Error::Poll(err)) if err.kind() == std::io::ErrorKind::Interrupted => { continue; } Err(err) => return Err(err.into()), }; if ready == 0 { anyhow::bail!("timed out waiting for data on pipe after {timeout:?}"); } match fd.read(&mut chunk) { Ok(0) => return Ok(buffer), Ok(len) => buffer.extend_from_slice(&chunk[..len]), Err(err) if err.kind() == std::io::ErrorKind::WouldBlock || err.kind() == std::io::ErrorKind::Interrupted => {} Err(err) => return Err(err.into()), } }}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) const DEFAULT_CURSOR_ICON_NAME: &str = "left_ptr";
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn cursor_style_to_icon_names(style: CursorStyle) -> &'static [&'static str] { // Based on cursor names from chromium: // https://github.com/chromium/chromium/blob/d3069cf9c973dc3627fa75f64085c6a86c8f41bf/ui/base/cursor/cursor_factory.cc#L113 match style { CursorStyle::Arrow => &[DEFAULT_CURSOR_ICON_NAME], CursorStyle::IBeam => &["text", "xterm"], CursorStyle::Crosshair => &["crosshair", "cross"], CursorStyle::ClosedHand => &["closedhand", "grabbing", "hand2"], CursorStyle::OpenHand => &["openhand", "grab", "hand1"], CursorStyle::PointingHand => &["pointer", "hand", "hand2"], CursorStyle::ResizeLeft => &["w-resize", "left_side"], CursorStyle::ResizeRight => &["e-resize", "right_side"], CursorStyle::ResizeLeftRight => &["ew-resize", "sb_h_double_arrow"], CursorStyle::ResizeUp => &["n-resize", "top_side"], CursorStyle::ResizeDown => &["s-resize", "bottom_side"], CursorStyle::ResizeUpDown => &["sb_v_double_arrow", "ns-resize"], CursorStyle::ResizeUpLeftDownRight => &["size_fdiag", "bd_double_arrow", "nwse-resize"], CursorStyle::ResizeUpRightDownLeft => &["size_bdiag", "nesw-resize", "fd_double_arrow"], CursorStyle::ResizeColumn => &["col-resize", "sb_h_double_arrow"], CursorStyle::ResizeRow => &["row-resize", "sb_v_double_arrow"], CursorStyle::IBeamCursorForVerticalLayout => &["vertical-text"], CursorStyle::OperationNotAllowed => &["not-allowed", "crossed_circle"], CursorStyle::DragLink => &["alias"], CursorStyle::DragCopy => &["copy"], CursorStyle::ContextualMenu => &["context-menu"], }}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn log_cursor_icon_warning(message: impl std::fmt::Display) { if let Ok(xcursor_path) = env::var("XCURSOR_PATH") { log::warn!( "{:#}\ncursor icon loading may be failing if XCURSOR_PATH environment variable is invalid. \ XCURSOR_PATH overrides the default icon search. Its current value is '{}'", message, xcursor_path ); } else { log::warn!("{:#}", message); }}
#[cfg(any(feature = "wayland", feature = "x11"))]fn guess_ascii(keycode: Keycode, shift: bool) -> Option<char> { let c = match (keycode.raw(), shift) { (24, _) => 'q', (25, _) => 'w', (26, _) => 'e', (27, _) => 'r', (28, _) => 't', (29, _) => 'y', (30, _) => 'u', (31, _) => 'i', (32, _) => 'o', (33, _) => 'p', (34, false) => '[', (34, true) => '{', (35, false) => ']', (35, true) => '}', (38, _) => 'a', (39, _) => 's', (40, _) => 'd', (41, _) => 'f', (42, _) => 'g', (43, _) => 'h', (44, _) => 'j', (45, _) => 'k', (46, _) => 'l', (47, false) => ';', (47, true) => ':', (48, false) => '\'', (48, true) => '"', (49, false) => '`', (49, true) => '~', (51, false) => '\\', (51, true) => '|', (52, _) => 'z', (53, _) => 'x', (54, _) => 'c', (55, _) => 'v', (56, _) => 'b', (57, _) => 'n', (58, _) => 'm', (59, false) => ',', (59, true) => '>', (60, false) => '.', (60, true) => '<', (61, false) => '/', (61, true) => '?',
_ => return None, };
Some(c)}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn keystroke_from_xkb( state: &State, mut modifiers: gpui::Modifiers, keycode: Keycode,) -> gpui::Keystroke { let key_utf32 = state.key_get_utf32(keycode); let key_utf8 = state.key_get_utf8(keycode); let key_sym = state.key_get_one_sym(keycode);
let key = match key_sym { Keysym::Return => "enter".to_owned(), Keysym::Prior => "pageup".to_owned(), Keysym::Next => "pagedown".to_owned(), Keysym::ISO_Left_Tab => "tab".to_owned(), Keysym::KP_Prior => "pageup".to_owned(), Keysym::KP_Next => "pagedown".to_owned(), Keysym::XF86_Back => "back".to_owned(), Keysym::XF86_Forward => "forward".to_owned(), Keysym::XF86_Cut => "cut".to_owned(), Keysym::XF86_Copy => "copy".to_owned(), Keysym::XF86_Paste => "paste".to_owned(), Keysym::XF86_New => "new".to_owned(), Keysym::XF86_Open => "open".to_owned(), Keysym::XF86_Save => "save".to_owned(),
Keysym::comma => ",".to_owned(), Keysym::period => ".".to_owned(), Keysym::less => "<".to_owned(), Keysym::greater => ">".to_owned(), Keysym::slash => "/".to_owned(), Keysym::question => "?".to_owned(),
Keysym::semicolon => ";".to_owned(), Keysym::colon => ":".to_owned(), Keysym::apostrophe => "'".to_owned(), Keysym::quotedbl => "\"".to_owned(),
Keysym::bracketleft => "[".to_owned(), Keysym::braceleft => "{".to_owned(), Keysym::bracketright => "]".to_owned(), Keysym::braceright => "}".to_owned(), Keysym::backslash => "\\".to_owned(), Keysym::bar => "|".to_owned(),
Keysym::grave => "`".to_owned(), Keysym::asciitilde => "~".to_owned(), Keysym::exclam => "!".to_owned(), Keysym::at => "@".to_owned(), Keysym::numbersign => "#".to_owned(), Keysym::dollar => "$".to_owned(), Keysym::percent => "%".to_owned(), Keysym::asciicircum => "^".to_owned(), Keysym::ampersand => "&".to_owned(), Keysym::asterisk => "*".to_owned(), Keysym::parenleft => "(".to_owned(), Keysym::parenright => ")".to_owned(), Keysym::minus => "-".to_owned(), Keysym::underscore => "_".to_owned(), Keysym::equal => "=".to_owned(), Keysym::plus => "+".to_owned(), Keysym::space => "space".to_owned(), Keysym::BackSpace => "backspace".to_owned(), Keysym::Tab => "tab".to_owned(), Keysym::Delete => "delete".to_owned(), Keysym::Escape => "escape".to_owned(),
Keysym::Left => "left".to_owned(), Keysym::Right => "right".to_owned(), Keysym::Up => "up".to_owned(), Keysym::Down => "down".to_owned(), Keysym::Home => "home".to_owned(), Keysym::End => "end".to_owned(), Keysym::Insert => "insert".to_owned(),
_ => { let name = xkb::keysym_get_name(key_sym).to_lowercase(); if key_sym.is_keypad_key() { name.replace("kp_", "") } else if let Some(key) = key_utf8.chars().next() && key_utf8.len() == 1 && key.is_ascii() { if key.is_ascii_graphic() { key_utf8.to_lowercase() // map ctrl-a to `a` // ctrl-0..9 may emit control codes like ctrl-[, but // we don't want to map them to `[` } else if key_utf32 <= 0x1f && !name.chars().next().is_some_and(|c| c.is_ascii_digit()) { ((key_utf32 as u8 + 0x40) as char) .to_ascii_lowercase() .to_string() } else { name } } else if let Some(key_en) = guess_ascii(keycode, modifiers.shift) { String::from(key_en) } else { name } } };
if modifiers.shift { // we only include the shift for upper-case letters by convention, // so don't include for numbers and symbols, but do include for // tab/enter, etc. if key.chars().count() == 1 && key.to_lowercase() == key.to_uppercase() { modifiers.shift = false; } }
// Ignore control characters (and DEL) for the purposes of key_char let key_char = (key_utf32 >= 32 && key_utf32 != 127 && !key_utf8.is_empty()).then_some(key_utf8);
gpui::Keystroke { modifiers, key, key_char, }}
/** * Returns which symbol the dead key represents * <https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux> */#[cfg(any(feature = "wayland", feature = "x11"))]pub fn keystroke_underlying_dead_key(keysym: Keysym) -> Option<String> { match keysym { Keysym::dead_grave => Some("`".to_owned()), Keysym::dead_acute => Some("´".to_owned()), Keysym::dead_circumflex => Some("^".to_owned()), Keysym::dead_tilde => Some("~".to_owned()), Keysym::dead_macron => Some("¯".to_owned()), Keysym::dead_breve => Some("˘".to_owned()), Keysym::dead_abovedot => Some("˙".to_owned()), Keysym::dead_diaeresis => Some("¨".to_owned()), Keysym::dead_abovering => Some("˚".to_owned()), Keysym::dead_doubleacute => Some("˝".to_owned()), Keysym::dead_caron => Some("ˇ".to_owned()), Keysym::dead_cedilla => Some("¸".to_owned()), Keysym::dead_ogonek => Some("˛".to_owned()), Keysym::dead_iota => Some("ͅ".to_owned()), Keysym::dead_voiced_sound => Some("゙".to_owned()), Keysym::dead_semivoiced_sound => Some("゚".to_owned()), Keysym::dead_belowdot => Some("̣̣".to_owned()), Keysym::dead_hook => Some("̡".to_owned()), Keysym::dead_horn => Some("̛".to_owned()), Keysym::dead_stroke => Some("̶̶".to_owned()), Keysym::dead_abovecomma => Some("̓̓".to_owned()), Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()), Keysym::dead_doublegrave => Some("̏".to_owned()), Keysym::dead_belowring => Some("˳".to_owned()), Keysym::dead_belowmacron => Some("̱".to_owned()), Keysym::dead_belowcircumflex => Some("ꞈ".to_owned()), Keysym::dead_belowtilde => Some("̰".to_owned()), Keysym::dead_belowbreve => Some("̮".to_owned()), Keysym::dead_belowdiaeresis => Some("̤".to_owned()), Keysym::dead_invertedbreve => Some("̯".to_owned()), Keysym::dead_belowcomma => Some("̦".to_owned()), Keysym::dead_currency => None, Keysym::dead_lowline => None, Keysym::dead_aboveverticalline => None, Keysym::dead_belowverticalline => None, Keysym::dead_longsolidusoverlay => None, Keysym::dead_a => None, Keysym::dead_A => None, Keysym::dead_e => None, Keysym::dead_E => None, Keysym::dead_i => None, Keysym::dead_I => None, Keysym::dead_o => None, Keysym::dead_O => None, Keysym::dead_u => None, Keysym::dead_U => None, Keysym::dead_small_schwa => Some("ə".to_owned()), Keysym::dead_capital_schwa => Some("Ə".to_owned()), Keysym::dead_greek => None, _ => None, }}#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn modifiers_from_xkb(keymap_state: &State) -> gpui::Modifiers { let shift = keymap_state.mod_name_is_active(xkb::MOD_NAME_SHIFT, xkb::STATE_MODS_EFFECTIVE); let alt = keymap_state.mod_name_is_active(xkb::MOD_NAME_ALT, xkb::STATE_MODS_EFFECTIVE); let control = keymap_state.mod_name_is_active(xkb::MOD_NAME_CTRL, xkb::STATE_MODS_EFFECTIVE); let platform = keymap_state.mod_name_is_active(xkb::MOD_NAME_LOGO, xkb::STATE_MODS_EFFECTIVE); gpui::Modifiers { shift, alt, control, platform, function: false, }}
#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn capslock_from_xkb(keymap_state: &State) -> gpui::Capslock { let on = keymap_state.mod_name_is_active(xkb::MOD_NAME_CAPS, xkb::STATE_MODS_EFFECTIVE); gpui::Capslock { on }}
/// Resolve a Linux `dev_t` to PCI vendor/device IDs via sysfs, returning a/// [`CompositorGpuHint`] that the GPU adapter selection code can use to/// prioritize the compositor's rendering device.#[cfg(any(feature = "wayland", feature = "x11"))]pub(super) fn compositor_gpu_hint_from_dev_t(dev: u64) -> Option<gpui_wgpu::CompositorGpuHint> { fn dev_major(dev: u64) -> u32 { ((dev >> 8) & 0xfff) as u32 | (((dev >> 32) & !0xfff) as u32) }
fn dev_minor(dev: u64) -> u32 { (dev & 0xff) as u32 | (((dev >> 12) & !0xff) as u32) }
fn read_sysfs_hex_id(path: &str) -> Option<u32> { let content = std::fs::read_to_string(path).ok()?; let trimmed = content.trim().strip_prefix("0x").unwrap_or(content.trim()); u32::from_str_radix(trimmed, 16).ok() }
let major = dev_major(dev); let minor = dev_minor(dev);
let vendor_path = format!("/sys/dev/char/{major}:{minor}/device/vendor"); let device_path = format!("/sys/dev/char/{major}:{minor}/device/device");
let vendor_id = read_sysfs_hex_id(&vendor_path)?; let device_id = read_sysfs_hex_id(&device_path)?;
log::info!( "Compositor GPU hint: vendor={:#06x}, device={:#06x} (from dev {major}:{minor})", vendor_id, device_id, );
Some(gpui_wgpu::CompositorGpuHint { vendor_id, device_id, })}
#[cfg(test)]mod tests { use super::*; use gpui::{Point, px};
#[test] fn test_is_within_click_distance() { let zero = Point::new(px(0.0), px(0.0)); assert!(is_within_click_distance(zero, Point::new(px(5.0), px(5.0)))); assert!(is_within_click_distance( zero, Point::new(px(-4.9), px(5.0)) )); assert!(is_within_click_distance( Point::new(px(3.0), px(2.0)), Point::new(px(-2.0), px(-2.0)) )); assert!(!is_within_click_distance( zero, Point::new(px(5.0), px(5.1)) ),); }
#[cfg(any(feature = "wayland", feature = "x11"))] mod read_fd_with_timeout { use super::super::{PIPE_READ_TIMEOUT, read_fd_with_timeout}; use std::io::Write as _; use std::time::{Duration, Instant};
#[test] fn reads_data_written_before_close() { let mut pipe = filedescriptor::Pipe::new().unwrap(); pipe.write.write_all(b"hello clipboard").unwrap(); drop(pipe.write);
let bytes = read_fd_with_timeout(pipe.read, PIPE_READ_TIMEOUT).unwrap(); assert_eq!(bytes, b"hello clipboard"); }
#[test] fn returns_empty_when_writer_closes_without_writing() { let pipe = filedescriptor::Pipe::new().unwrap(); drop(pipe.write);
let bytes = read_fd_with_timeout(pipe.read, PIPE_READ_TIMEOUT).unwrap(); assert!(bytes.is_empty()); }
#[test] fn times_out_when_writer_never_writes() { let pipe = filedescriptor::Pipe::new().unwrap(); let _open_writer = pipe.write;
let timeout = Duration::from_millis(50); let started = Instant::now(); let result = read_fd_with_timeout(pipe.read, timeout); let elapsed = started.elapsed();
let err = result.unwrap_err(); assert!( err.to_string().contains("timed out"), "unexpected error: {err}" ); assert!(elapsed >= timeout, "returned before the timeout elapsed"); }
#[test] fn times_out_when_writer_stalls_after_partial_write() { let mut pipe = filedescriptor::Pipe::new().unwrap(); pipe.write.write_all(b"partial").unwrap(); let _open_writer = pipe.write;
let err = read_fd_with_timeout(pipe.read, Duration::from_millis(50)).unwrap_err(); assert!( err.to_string().contains("timed out"), "unexpected error: {err}" ); }
#[test] fn slow_writer_resets_deadline_between_chunks() { let pipe = filedescriptor::Pipe::new().unwrap(); let chunks = 12; let gap = Duration::from_millis(40); let timeout = Duration::from_millis(400);
let writer = std::thread::spawn({ let mut write = pipe.write; move || { for _ in 0..chunks { std::thread::sleep(gap); write.write_all(&[b'x'; 1000]).unwrap(); } } }); // The total transfer (~480ms) exceeds the timeout; this only // passes because the timeout is re-armed per chunk. let bytes = read_fd_with_timeout(pipe.read, timeout).unwrap(); writer.join().unwrap(); assert_eq!(bytes, vec![b'x'; 1000 * chunks]); }
#[test] fn reads_payload_larger_than_pipe_capacity() { let pipe = filedescriptor::Pipe::new().unwrap(); // Exceeds the 64 KiB pipe capacity, forcing the writer to block. let payload = vec![b'z'; 1024 * 1024];
let writer = std::thread::spawn({ let mut write = pipe.write; let payload = payload.clone(); move || write.write_all(&payload).unwrap() }); let bytes = read_fd_with_timeout(pipe.read, PIPE_READ_TIMEOUT).unwrap(); writer.join().unwrap(); assert_eq!(bytes, payload); } }}