Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Cross-platform headless windowing API and linux impl (#64969)

Cameron Mcloughlinf37989fbdf84
diff --git a/Cargo.lock b/Cargo.lock
index cd7027eb0f2..492307a40fb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2707,7 +2707,7 @@ dependencies = [
[[package]]
name = "calloop"
version = "0.14.3"
-source = "git+https://github.com/zed-industries/calloop#eb6b4fd17b9af5ecc226546bdd04185391b3e265"
+source = "git+https://github.com/zed-industries/calloop?rev=3759371fee14c40066d64777e2a36b6ffcc22590#3759371fee14c40066d64777e2a36b6ffcc22590"
dependencies = [
"bitflags 2.13.1",
"polling",
@@ -7635,7 +7635,6 @@ dependencies = [
"anyhow",
"as-raw-xcb-connection",
"ashpd",
- "bitflags 2.13.1",
"bytemuck",
"calloop",
"calloop-wayland-source",
diff --git a/Cargo.toml b/Cargo.toml
index 9388515ba58..4d9a614a10d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1019,7 +1019,7 @@ tree-sitter-language = { git = "https://github.com/tree-sitter/tree-sitter", rev
async-process = { git = "https://github.com/zed-industries/async-process.git", rev = "0b6d6713570af61806e1e5cb40e0f757cb93fd9d" }
async-task = { git = "https://github.com/smol-rs/async-task.git", rev = "b4486cd71e4e94fbda54ce6302444de14f4d190e" }
windows-capture = { git = "https://github.com/zed-industries/windows-capture.git", rev = "f0d6c1b6691db75461b732f6d5ff56eed002eeb9" }
-calloop = { git = "https://github.com/zed-industries/calloop" }
+calloop = { git = "https://github.com/zed-industries/calloop", rev = "3759371fee14c40066d64777e2a36b6ffcc22590" }
livekit = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "0a1c519cfce9b365229026b55de9b9dbdb6fed3c" }
libwebrtc = { git = "https://github.com/zed-industries/livekit-rust-sdks", rev = "0a1c519cfce9b365229026b55de9b9dbdb6fed3c" }
notify = { git = "https://github.com/zed-industries/notify", rev = "d842f16b2716bd60f09caf3ae3a894237ab38f54" }
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index 222777fa396..1957084c876 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -139,7 +139,13 @@ libc.workspace = true
[target.'cfg(target_os = "windows")'.dependencies]
-windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_Power", "Win32_System_WindowsProgramming"] }
+windows = { workspace = true, features = [
+ "Win32_Foundation",
+ "Win32_System_Power",
+ "Win32_System_RemoteDesktop",
+ "Win32_System_Threading",
+ "Win32_System_WindowsProgramming",
+] }
[dev-dependencies]
@@ -271,3 +277,7 @@ path = "examples/a11y.rs"
[[example]]
name = "view_example"
path = "examples/view_example/view_example_main.rs"
+
+[[example]]
+name = "toggle_headless"
+path = "examples/toggle_headless.rs"
diff --git a/crates/gpui/examples/README.md b/crates/gpui/examples/README.md
index f4a017cda01..395bf5e967c 100644
--- a/crates/gpui/examples/README.md
+++ b/crates/gpui/examples/README.md
@@ -143,6 +143,13 @@ These examples are useful when working on GPUI itself, but they may not be the
best starting point for new applications:
- `active_state_bug` is a focused active-state reproduction.
+- `toggle_headless` starts without a display and preserves its app and todo
+ entities while attaching to or detaching from Wayland or X11. Run it on Linux
+ with `cargo run -p gpui --example toggle_headless`; its stdin commands are
+ `ls`, `create [message]`, `open`, `close`, and `quit`. `open` attaches to the
+ display server in the process environment and opens the window; while headless,
+ `open DISPLAY=:1` (or `WAYLAND_DISPLAY=… XDG_RUNTIME_DIR=…`) targets another one.
+ `close` closes the window and returns to headless mode.
- `layer_shell` demonstrates Linux layer-shell windows.
- `list_example` demonstrates bottom-aligned list state and scrollbar behavior.
- `ownership_post` supports the ownership and data-flow documentation.
diff --git a/crates/gpui/examples/toggle_headless.rs b/crates/gpui/examples/toggle_headless.rs
new file mode 100644
index 00000000000..136e31f7e01
--- /dev/null
+++ b/crates/gpui/examples/toggle_headless.rs
@@ -0,0 +1,309 @@
+#![cfg_attr(target_family = "wasm", no_main)]
+
+#[cfg(not(target_family = "wasm"))]
+use std::{
+ io::{self, BufRead as _},
+ sync::mpsc,
+ time::Duration,
+};
+
+#[cfg(not(target_family = "wasm"))]
+use gpui::{
+ AnyWindowHandle, App, AppContext as _, AsyncApp, Context, Entity, GraphicalEnvironment,
+ QuitMode, Render, Subscription, TitlebarOptions, Window, WindowOptions, WindowingRequest, div,
+ prelude::*,
+};
+
+#[cfg(not(target_family = "wasm"))]
+struct Todo {
+ message: String,
+}
+
+#[cfg(not(target_family = "wasm"))]
+struct Todos {
+ items: Vec<Entity<Todo>>,
+ window: Option<AnyWindowHandle>,
+}
+
+#[cfg(not(target_family = "wasm"))]
+struct TodoWindow {
+ todos: Entity<Todos>,
+ _todos_subscription: Subscription,
+}
+
+#[cfg(not(target_family = "wasm"))]
+impl Render for TodoWindow {
+ fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
+ let rows = self
+ .todos
+ .read(cx)
+ .items
+ .iter()
+ .enumerate()
+ .map(|(index, todo)| div().child(describe_todo(index, todo, cx)))
+ .collect::<Vec<_>>();
+
+ div()
+ .size_full()
+ .bg(gpui::rgb(0xffffff))
+ .text_color(gpui::rgb(0x202020))
+ .flex()
+ .flex_col()
+ .gap_2()
+ .p_4()
+ .child("Switchable display todos")
+ .child("Use the terminal: create [message], ls, close, open, quit")
+ .when(rows.is_empty(), |view| {
+ view.child("No todos yet. Type `create` in the terminal.")
+ })
+ .children(rows)
+ }
+}
+
+/// English, Chinese, Japanese and Korean for a word, then an emoji for it.
+#[cfg(not(target_family = "wasm"))]
+const SAMPLE_TODOS: [&str; 5] = [
+ "milk / 牛奶 / 牛乳 / 우유 🥛",
+ "apple / 苹果 / りんご / 사과 🍎",
+ "cat / 猫 / ねこ / 고양이 🐱",
+ "book / 书 / 本 / 책 📚",
+ "rain / 雨 / あめ / 비 🌧️",
+];
+
+#[cfg(not(target_family = "wasm"))]
+fn describe_todo(index: usize, todo: &Entity<Todo>, cx: &App) -> String {
+ let todo_reference: &Todo = todo.read(cx);
+ format!(
+ "{index} - {} - {:?} @{:p}",
+ todo_reference.message,
+ todo.entity_id(),
+ todo_reference
+ )
+}
+
+#[cfg(not(target_family = "wasm"))]
+fn print_todos(todos: &Entity<Todos>, cx: &App) {
+ if todos.read(cx).items.is_empty() {
+ println!("no todos");
+ }
+ for (index, todo) in todos.read(cx).items.iter().enumerate() {
+ println!("{}", describe_todo(index, todo, cx));
+ }
+}
+
+#[cfg(not(target_family = "wasm"))]
+fn open_window(todos: &Entity<Todos>, cx: &mut App) -> anyhow::Result<()> {
+ if todos.read(cx).window.is_some() {
+ return Ok(());
+ }
+
+ let options = WindowOptions {
+ titlebar: Some(TitlebarOptions {
+ title: Some("Switchable display todos".into()),
+ ..Default::default()
+ }),
+ ..Default::default()
+ };
+ let handle = cx.open_window(options, |_, cx| {
+ cx.new(|cx| TodoWindow {
+ todos: todos.clone(),
+ _todos_subscription: cx.observe(todos, |_, _, cx| cx.notify()),
+ })
+ })?;
+ // On macOS, making the window key does not activate the app over the terminal.
+ cx.activate(true);
+ handle.update(cx, |_, window, _| window.activate_window())?;
+ todos.update(cx, |todos, _| todos.window = Some(handle.into()));
+ Ok(())
+}
+
+/// Builds the environment for `open`: the given `NAME=value` pairs, or this process's
+/// environment when none are given.
+#[cfg(target_os = "linux")]
+fn display_environment(arguments: &str) -> anyhow::Result<GraphicalEnvironment> {
+ if arguments.trim().is_empty() {
+ return Ok(GraphicalEnvironment::detect());
+ }
+ let mut environment = GraphicalEnvironment::default();
+ for assignment in arguments.split_whitespace() {
+ let (name, value) = assignment
+ .split_once('=')
+ .ok_or_else(|| anyhow::anyhow!("expected NAME=value, got {assignment:?}"))?;
+ match name {
+ "WAYLAND_DISPLAY" => environment.wayland_display = Some(value.into()),
+ "DISPLAY" => environment.x11_display = Some(value.into()),
+ "XDG_RUNTIME_DIR" => environment.xdg_runtime_dir = Some(value.into()),
+ "XDG_ACTIVATION_TOKEN" => environment.activation_token = Some(value.into()),
+ _ => anyhow::bail!("unknown display variable {name}"),
+ }
+ }
+ Ok(environment)
+}
+
+/// Builds the environment for `open`: `SESSION=id`, or this process's session when not given.
+#[cfg(target_os = "windows")]
+fn display_environment(arguments: &str) -> anyhow::Result<GraphicalEnvironment> {
+ let mut environment = GraphicalEnvironment::detect();
+ for assignment in arguments.split_whitespace() {
+ let session = assignment
+ .strip_prefix("SESSION=")
+ .ok_or_else(|| anyhow::anyhow!("expected SESSION=id, got {assignment:?}"))?;
+ environment.session_id = Some(session.parse()?);
+ }
+ Ok(environment)
+}
+
+/// Builds the environment for `open`, which carries nothing on this platform.
+#[cfg(not(any(target_os = "linux", target_os = "windows", target_family = "wasm")))]
+fn display_environment(_arguments: &str) -> anyhow::Result<GraphicalEnvironment> {
+ Ok(GraphicalEnvironment::detect())
+}
+
+#[cfg(not(target_family = "wasm"))]
+fn handle_command(
+ command: &str,
+ todos: &Entity<Todos>,
+ cx: &mut App,
+) -> anyhow::Result<Option<WindowingRequest>> {
+ let (name, arguments) = command.split_once(' ').unwrap_or((command, ""));
+ match name {
+ "ls" => print_todos(todos, cx),
+ "create" => {
+ // A sample with CJK text and an emoji, so that drawing todos exercises color glyph
+ // rasterization, which uses the GPU devices a switch to windowed mode creates.
+ let count = todos.read(cx).items.len();
+ let sample = SAMPLE_TODOS[count % SAMPLE_TODOS.len()];
+ let message = if arguments.trim().is_empty() {
+ sample.to_owned()
+ } else {
+ format!("{arguments} · {sample}")
+ };
+ let todo = cx.new(|_| Todo { message });
+ todos.update(cx, |todos, cx| {
+ todos.items.push(todo);
+ println!("todo added, total {}", todos.items.len());
+ cx.notify();
+ });
+ }
+ "open" => {
+ return Ok(Some(WindowingRequest::Windowed(display_environment(
+ arguments,
+ )?)));
+ }
+ "close" => {
+ let window = todos.update(cx, |todos, _| todos.window.take());
+ if let Some(window) = window {
+ window.update(cx, |_, window, _| window.remove_window())?;
+ }
+ return Ok(Some(WindowingRequest::Headless));
+ }
+ "quit" => cx.quit(),
+ "" => {}
+ _ => println!("{USAGE}"),
+ }
+ Ok(None)
+}
+
+#[cfg(target_os = "linux")]
+const USAGE: &str = "commands: ls | create [message] | open [DISPLAY=… WAYLAND_DISPLAY=… XDG_RUNTIME_DIR=… XDG_ACTIVATION_TOKEN=…] | close | quit";
+
+#[cfg(target_os = "windows")]
+const USAGE: &str = "commands: ls | create [message] | open [SESSION=…] | close | quit";
+
+#[cfg(not(any(target_os = "linux", target_os = "windows", target_family = "wasm")))]
+const USAGE: &str = "commands: ls | create [message] | open | close | quit";
+
+#[cfg(not(target_family = "wasm"))]
+async fn run_command(
+ command: String,
+ todos: &Entity<Todos>,
+ cx: &mut AsyncApp,
+) -> anyhow::Result<()> {
+ match cx.update(|cx| handle_command(&command, todos, cx))? {
+ None => return Ok(()),
+ Some(request @ WindowingRequest::Headless) => {
+ if cx.update(|cx| cx.graphical_environment()).is_some() {
+ cx.update(|cx| cx.request_windowing(request)).await?;
+ }
+ }
+ Some(request @ WindowingRequest::Windowed(_)) => {
+ // Switching fails while windowed, so `open` then just opens the window.
+ if cx.update(|cx| cx.graphical_environment()).is_none() {
+ cx.update(|cx| cx.request_windowing(request)).await?;
+ }
+ cx.update(|cx| open_window(todos, cx))?;
+ }
+ }
+ let mode = cx.update(|cx| match cx.graphical_environment() {
+ None => "headless".to_owned(),
+ Some(_) => match cx.compositor_name() {
+ "" => "windowed".to_owned(),
+ compositor => compositor.to_owned(),
+ },
+ });
+ println!("mode: {mode}");
+ Ok(())
+}
+
+#[cfg(not(target_family = "wasm"))]
+fn main() {
+ #[cfg(target_os = "linux")]
+ let application = gpui_platform::linux(gpui::WindowingModes::all());
+ #[cfg(not(target_os = "linux"))]
+ let application = gpui_platform::application();
+ application
+ .with_windowing(WindowingRequest::Headless)
+ .with_quit_mode(QuitMode::Explicit)
+ .run(|cx| {
+ let todos = cx.new(|_| Todos {
+ items: Vec::new(),
+ window: None,
+ });
+ let window_closed_subscription = cx.on_window_closed({
+ let todos = todos.clone();
+ move |cx, window_id| {
+ todos.update(cx, |todos, _| {
+ if todos
+ .window
+ .as_ref()
+ .is_some_and(|window| window.window_id() == window_id)
+ {
+ todos.window = None;
+ }
+ });
+ }
+ });
+ let (command_sender, command_receiver) = mpsc::channel();
+ std::thread::spawn(move || {
+ for line in io::stdin().lock().lines() {
+ match line {
+ Ok(line) => {
+ if command_sender.send(line).is_err() {
+ break;
+ }
+ }
+ Err(error) => {
+ eprintln!("stdin error: {error}");
+ break;
+ }
+ }
+ }
+ });
+
+ println!("{USAGE}");
+ cx.spawn(async move |cx| {
+ let _window_closed_subscription = window_closed_subscription;
+ loop {
+ cx.background_executor()
+ .timer(Duration::from_millis(25))
+ .await;
+ while let Ok(command) = command_receiver.try_recv() {
+ if let Err(error) = run_command(command, &todos, cx).await {
+ println!("error: {error:#}");
+ }
+ }
+ }
+ })
+ .detach();
+ });
+}
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index 9ef3d6d33e4..a921de1aa03 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -44,17 +44,17 @@ pub use visual_test_context::*;
use crate::InspectorElementRegistry;
use crate::asset_cache::CachedLoad;
use crate::{
- Action, ActionBuildError, ActionRegistry, ActivityGuard, Any, AnyView, AnyWindowHandle,
- AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds, ClipboardItem,
- ClipboardReadError, CursorStyle, DispatchPhase, DisplayId, EventEmitter, ExternalDragPayload,
- FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext, Keymap, Keystroke,
- LayoutId, Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions, Pixels, Platform,
- PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority,
- PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
+ Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
+ AnyWindowHandle, AppContext, Arena, ArenaBox, Asset, AssetSource, BackgroundExecutor, Bounds,
+ ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase, DisplayId, EventEmitter,
+ ExternalDragPayload, FocusHandle, FocusMap, ForegroundExecutor, Global, KeyBinding, KeyContext,
+ Keymap, Keystroke, LayoutId, Menu, MenuItem, MissingGlyph, OwnedMenu, PathPromptOptions,
+ Pixels, Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point,
+ Priority, PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
Subscription, SvgRenderer, SystemNotification, SystemNotificationResponse, Task,
TextRenderingMode, TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout,
- WindowHandle, WindowId, WindowInvalidator,
+ WindowHandle, WindowId, WindowInvalidator, WindowingRequest,
colors::{Colors, GlobalColors},
hash, init_app_menus,
};
@@ -229,6 +229,17 @@ impl Application {
self
}
+ /// Sets the windowing mode the app starts in. See [`App::request_windowing`].
+ ///
+ /// Defaults to windowed. On Linux, the default environment is the process's own, and the app
+ /// starts headless if that names no allowed display server. On macOS, headless means the app
+ /// starts without a Dock icon or menu bar ([`ActivationPolicy::Accessory`]). Has no effect on
+ /// other platforms.
+ pub fn with_windowing(self, request: WindowingRequest) -> Self {
+ self.0.borrow().platform.set_initial_windowing(request);
+ self
+ }
+
/// Start the application. The provided callback will be called once the
/// app is fully launched.
///
@@ -1150,6 +1161,41 @@ impl App {
self.platform.quit();
}
+ /// Switches the platform between headless and windowed modes.
+ ///
+ /// On Linux, headless means no display server: windows opened afterwards lay out and handle
+ /// input but draw nothing. Windowed, the platform connects to the display server the
+ /// environment names. On macOS, the modes set the [`ActivationPolicy`]: headless is
+ /// `Accessory` (no Dock icon or menu bar) and windowed is `Regular`. Switching to windowed
+ /// doesn't activate the app: call [`App::activate`] for that.
+ ///
+ /// The returned task resolves once the switch has been applied. It fails if the platform is
+ /// already in the requested mode (switching to another display server means going headless
+ /// first), if the platform doesn't allow the mode or can't switch at all, if any window is
+ /// open (a window belongs to the display server that opened it), or if the display server
+ /// can't be reached.
+ pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
+ if !self.windows.is_empty() {
+ return Task::ready(Err(anyhow::anyhow!(
+ "cannot switch windowing modes while windows are open"
+ )));
+ }
+ self.platform.request_windowing(request)
+ }
+
+ /// The environment of the display server the platform is connected to, or `None` while
+ /// headless. Its activation token is always unset, since the connection has used it.
+ ///
+ /// Programs an app launches inherit this process's environment, which may name another
+ /// graphical session, or none if the app started headless. Pass them this one with
+ /// [`GraphicalEnvironment::apply_to`](crate::GraphicalEnvironment::apply_to).
+ ///
+ /// On macOS, the environment carries nothing, and this is `None` while the activation
+ /// policy is `Accessory`. Always `None` on platforms that can't switch windowing modes.
+ pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
+ self.platform.graphical_environment()
+ }
+
/// Returns the current policy for hiding the cursor in response to
/// keyboard input.
pub fn cursor_hide_mode(&self) -> CursorHideMode {
@@ -1790,6 +1836,18 @@ impl App {
self.quit_mode = mode;
}
+ /// Sets whether the application participates in the system's foreground UI.
+ ///
+ /// Only has an effect on macOS, where [`Self::request_windowing`] normally sets it. Use this
+ /// for an accessory app that shows windows, such as a menu bar utility. It overrides the
+ /// policy until the next [`Self::request_windowing`], and the app counts as headless while
+ /// `Accessory`. After switching to [`ActivationPolicy::Regular`], activate the app yourself
+ /// with [`Self::activate`]; otherwise its menu bar may not appear until the app is
+ /// reactivated.
+ pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
+ self.platform.set_activation_policy(policy);
+ }
+
/// Returns the SVG renderer used by the application.
pub fn svg_renderer(&self) -> SvgRenderer {
self.svg_renderer.clone()
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 8a103008253..e47fd002885 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -119,6 +119,21 @@ impl WindowVisibility {
}
}
+/// Controls whether the application participates in the system's foreground UI.
+///
+/// Only has an effect on macOS; other platforms ignore this setting. There,
+/// [`App::request_windowing`] sets it: `Accessory` while headless and `Regular` while windowed.
+/// Set it directly with [`App::set_activation_policy`] for the one case that doesn't cover: an
+/// accessory app that shows windows, such as a menu bar utility.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub enum ActivationPolicy {
+ /// Participate in foreground application UI, such as the Dock and menu bar on macOS.
+ #[default]
+ Regular,
+ /// Run without foreground application UI while retaining the ability to open windows.
+ Accessory,
+}
+
#[cfg(any(test, feature = "test-support", feature = "bench-support"))]
pub(crate) use test::*;
@@ -159,26 +174,152 @@ pub fn guess_compositor() -> &'static str {
if std::env::var_os("ZED_HEADLESS").is_some() {
return "Headless";
}
+ GraphicalEnvironment::detect().guess_compositor()
+}
- #[cfg(feature = "wayland")]
- let wayland_display = std::env::var_os("WAYLAND_DISPLAY");
- #[cfg(not(feature = "wayland"))]
- let wayland_display: Option<std::ffi::OsString> = None;
+/// The graphical session to connect to: the variables that locate its display server, as some
+/// process sees them.
+///
+/// A long-running process can outlive the graphical session it was started in, so a platform
+/// that attaches to a display server later can be given a fresher environment than its own.
+/// While connected, programs the platform launches (for example to open a URL) get these
+/// variables instead of the ones this process started with. Apply
+/// [`App::graphical_environment`] to the programs an app launches, for the same reason.
+#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+#[derive(Clone, Debug, Default)]
+pub struct GraphicalEnvironment {
+ /// `WAYLAND_DISPLAY`: a socket name relative to `xdg_runtime_dir`, or an absolute path.
+ pub wayland_display: Option<OsString>,
+ /// `DISPLAY`: the X11 display name.
+ pub x11_display: Option<OsString>,
+ /// `XDG_RUNTIME_DIR`: the directory containing Wayland sockets.
+ pub xdg_runtime_dir: Option<OsString>,
+ /// `XDG_ACTIVATION_TOKEN`: lets the first window take focus on Wayland.
+ ///
+ /// A platform takes this process's token from its environment when it's created, and uses
+ /// it if it starts windowed. Pass one here to switch to windowed mode later, for example
+ /// the token of the process that asked for a window.
+ pub activation_token: Option<String>,
+}
- #[cfg(feature = "x11")]
- let x11_display = std::env::var_os("DISPLAY");
- #[cfg(not(feature = "x11"))]
- let x11_display: Option<std::ffi::OsString> = None;
+/// The graphical session to connect to: the Windows session whose desktop windows appear on.
+///
+/// A process can only show windows in its own session, so switching to windowed mode fails if
+/// this names another one, for example when a process started over SSH is asked to show a
+/// window on the desktop.
+#[cfg(target_os = "windows")]
+#[derive(Clone, Debug, Default)]
+pub struct GraphicalEnvironment {
+ /// The session ID, as `ProcessIdToSessionId` reports it. `None` means this process's own
+ /// session.
+ pub session_id: Option<u32>,
+}
+
+#[cfg(target_os = "windows")]
+impl GraphicalEnvironment {
+ /// Returns the environment of this process's session.
+ pub fn detect() -> Self {
+ let mut session_id = 0;
+ // SAFETY: `session_id` is a valid pointer for the call's duration.
+ let result = unsafe {
+ windows::Win32::System::RemoteDesktop::ProcessIdToSessionId(
+ windows::Win32::System::Threading::GetCurrentProcessId(),
+ &mut session_id,
+ )
+ };
+ Self {
+ session_id: result.is_ok().then_some(session_id),
+ }
+ }
+
+ /// Does nothing on this platform: programs inherit the session of the process that
+ /// starts them.
+ pub fn apply_to(&self, _command: &mut std::process::Command) {}
+}
- let use_wayland = wayland_display.is_some_and(|display| !display.is_empty());
- let use_x11 = x11_display.is_some_and(|display| !display.is_empty());
+/// The graphical session to connect to. Carries nothing yet on this platform.
+#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
+#[derive(Clone, Debug, Default)]
+pub struct GraphicalEnvironment;
- if use_wayland {
- "Wayland"
- } else if use_x11 {
- "X11"
- } else {
- "Headless"
+#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "windows")))]
+impl GraphicalEnvironment {
+ /// Returns the environment of this process's graphical session.
+ pub fn detect() -> Self {
+ Self
+ }
+
+ /// Does nothing on this platform.
+ pub fn apply_to(&self, _command: &mut std::process::Command) {}
+}
+
+/// A display mode for [`App::request_windowing`] to switch to.
+#[derive(Clone, Debug)]
+pub enum WindowingRequest {
+ /// No display server. Windows lay out and handle input but draw nothing.
+ Headless,
+ /// Connected to the display server that the environment names.
+ Windowed(GraphicalEnvironment),
+}
+
+#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+impl GraphicalEnvironment {
+ /// Reads the display variables from this process's environment.
+ ///
+ /// This only reads environment variables: whether they name a reachable display server is
+ /// checked when a platform connects. Leaves `activation_token` unset: see its documentation.
+ pub fn detect() -> Self {
+ Self {
+ wayland_display: std::env::var_os("WAYLAND_DISPLAY"),
+ x11_display: std::env::var_os("DISPLAY"),
+ xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"),
+ activation_token: None,
+ }
+ }
+
+ /// Sets this environment's display variables on `command`, and removes the ones it doesn't
+ /// set, so the program connects to this graphical session rather than the one this process
+ /// started in. Leaves `XDG_ACTIVATION_TOKEN` alone.
+ pub fn apply_to(&self, command: &mut std::process::Command) {
+ for (name, value) in [
+ ("WAYLAND_DISPLAY", &self.wayland_display),
+ ("DISPLAY", &self.x11_display),
+ ("XDG_RUNTIME_DIR", &self.xdg_runtime_dir),
+ ] {
+ match value {
+ Some(value) => command.env(name, value),
+ None => command.env_remove(name),
+ };
+ }
+ }
+
+ /// Returns the compositor this environment selects: Wayland, then X11, then headless.
+ ///
+ /// Does not attempt to connect to the compositor.
+ pub fn guess_compositor(&self) -> &'static str {
+ let is_set =
+ |value: &Option<OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
+ if cfg!(feature = "wayland") && is_set(&self.wayland_display) {
+ "Wayland"
+ } else if cfg!(feature = "x11") && is_set(&self.x11_display) {
+ "X11"
+ } else {
+ "Headless"
+ }
+ }
+}
+
+#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+bitflags::bitflags! {
+ /// The windowing modes a platform may start in or switch to.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub struct WindowingModes: u8 {
+ /// Connected to a Wayland compositor.
+ const WAYLAND = 1 << 0;
+ /// Connected to an X server.
+ const X11 = 1 << 1;
+ /// No display server. Windows lay out and handle input but draw nothing.
+ const HEADLESS = 1 << 2;
}
}
@@ -190,8 +331,20 @@ pub trait Platform: 'static {
fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);
fn quit(&self);
+ /// Switches a capable platform between headless and windowed modes. See
+ /// [`App::request_windowing`].
+ /// Sets the windowing mode the platform starts in. Called before `run`. See
+ /// [`Application::with_windowing`].
+ fn set_initial_windowing(&self, _request: WindowingRequest) {}
+ fn request_windowing(&self, _request: WindowingRequest) -> Task<anyhow::Result<()>> {
+ Task::ready(Err(anyhow::anyhow!(
+ "this platform cannot switch between headless and windowed modes"
+ )))
+ }
fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>);
fn activate(&self, ignoring_other_apps: bool);
+ /// Sets the initial or current activation policy. Has no effect outside macOS.
+ fn set_activation_policy(&self, _policy: ActivationPolicy) {}
fn hide(&self);
fn hide_other_apps(&self);
fn unhide_other_apps(&self);
@@ -357,6 +510,11 @@ pub trait Platform: 'static {
fn compositor_name(&self) -> &'static str {
""
}
+ /// The environment of the display server a platform that can switch windowing modes is
+ /// connected to. See [`App::graphical_environment`].
+ fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
+ None
+ }
fn app_path(&self) -> Result<PathBuf>;
fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf>;
diff --git a/crates/gpui_linux/Cargo.toml b/crates/gpui_linux/Cargo.toml
index 812d8d3b995..47ab8389e4d 100644
--- a/crates/gpui_linux/Cargo.toml
+++ b/crates/gpui_linux/Cargo.toml
@@ -16,7 +16,6 @@ doctest = false
default = ["wayland", "x11"]
test-support = ["gpui/test-support"]
wayland = [
- "bitflags",
"gpui_wgpu",
"ashpd/wayland",
@@ -81,7 +80,6 @@ raw-window-handle.workspace = true
# Used in both windowing options
ashpd = { workspace = true, optional = true }
-bitflags = { workspace = true, optional = true }
filedescriptor = { version = "0.8.2", optional = true }
open = { version = "5.2.0", optional = true }
xkbcommon = { version = "0.8.0", default-features = false, optional = true }
@@ -132,4 +130,4 @@ xim = { git = "https://github.com/zed-industries/xim-rs.git", rev = "16f35a2c881
gpui = { workspace = true, features = ["test-support"] }
[package.metadata.cargo-shear]
-ignored = ["bitflags", "scap"]
+ignored = ["scap"]
diff --git a/crates/gpui_linux/src/gpui_linux.rs b/crates/gpui_linux/src/gpui_linux.rs
index 62d972dc4e0..a5390e77f87 100644
--- a/crates/gpui_linux/src/gpui_linux.rs
+++ b/crates/gpui_linux/src/gpui_linux.rs
@@ -1,4 +1,4 @@
#![cfg(any(target_os = "linux", target_os = "freebsd"))]
mod linux;
-pub use linux::current_platform;
+pub use linux::{current_platform, linux_platform};
diff --git a/crates/gpui_linux/src/linux.rs b/crates/gpui_linux/src/linux.rs
index 33393f7e9ee..e4da54b52b4 100644
--- a/crates/gpui_linux/src/linux.rs
+++ b/crates/gpui_linux/src/linux.rs
@@ -1,4 +1,5 @@
mod dispatcher;
+mod display_connection;
mod headless;
mod keyboard;
mod platform;
@@ -14,6 +15,7 @@ mod x11;
mod xdg_desktop_portal;
pub use dispatcher::*;
+pub(crate) use display_connection::{Backend, DisplayConnection, select_backend};
pub(crate) use headless::*;
pub(crate) use keyboard::*;
pub(crate) use platform::*;
@@ -26,35 +28,25 @@ pub(crate) use x11::*;
use std::rc::Rc;
+use gpui::WindowingModes;
+
/// Returns the default platform implementation for the current OS.
+///
+/// A windowed platform connects to the display server the process environment names, or starts
+/// headless when it names none, and can switch between those modes later. A headless platform
+/// stays headless.
pub fn current_platform(headless: bool) -> Rc<dyn gpui::Platform> {
- #[cfg(feature = "x11")]
- use anyhow::Context as _;
-
- if headless {
- return Rc::new(LinuxPlatform {
- inner: HeadlessClient::new(),
- });
+ if headless || std::env::var_os("ZED_HEADLESS").is_some() {
+ linux_platform(WindowingModes::HEADLESS)
+ } else {
+ linux_platform(WindowingModes::all())
}
+}
- match gpui::guess_compositor() {
- #[cfg(feature = "wayland")]
- "Wayland" => Rc::new(LinuxPlatform {
- inner: WaylandClient::new(),
- }),
-
- #[cfg(feature = "x11")]
- "X11" => Rc::new(LinuxPlatform {
- inner: X11Client::new()
- .context("Failed to initialize X11 client.")
- .unwrap(),
- }),
-
- "Headless" => Rc::new(LinuxPlatform {
- inner: HeadlessClient::new(),
- }),
- _ => unreachable!(
- r#"At least one of the "wayland" or "x11" features must be enabled on gpui_linux or gpui_platform."#
- ),
- }
+/// Returns a platform that may switch among `allowed_modes`.
+///
+/// It starts windowed in the process's own environment, or headless if that names no allowed
+/// display server. Set another initial mode with [`gpui::Application::with_windowing`].
+pub fn linux_platform(allowed_modes: WindowingModes) -> Rc<dyn gpui::Platform> {
+ Rc::new(LinuxPlatform::new(allowed_modes))
}
diff --git a/crates/gpui_linux/src/linux/display_connection.rs b/crates/gpui_linux/src/linux/display_connection.rs
new file mode 100644
index 00000000000..d7849d0c4a1
--- /dev/null
+++ b/crates/gpui_linux/src/linux/display_connection.rs
@@ -0,0 +1,222 @@
+use std::{path::PathBuf, rc::Rc};
+
+use gpui::{
+ AnyWindowHandle, ClipboardItem, CursorStyle, GraphicalEnvironment, PlatformDisplay,
+ PlatformKeyboardLayout, PlatformWindow, WindowParams, WindowingModes,
+};
+
+#[cfg(feature = "wayland")]
+use super::WaylandConnection;
+#[cfg(feature = "x11")]
+use super::X11Connection;
+use super::{HeadlessConnection, LinuxKeyboardLayout};
+
+/// Returns the display server `environment` selects among the windowed modes in `modes`:
+/// Wayland, then X11.
+#[cfg_attr(
+ not(any(feature = "wayland", feature = "x11")),
+ allow(
+ unused_variables,
+ reason = "no windowed modes without a display backend"
+ )
+)]
+pub(crate) fn select_backend(
+ modes: WindowingModes,
+ environment: &GraphicalEnvironment,
+) -> Option<Backend> {
+ let is_set =
+ |value: &Option<std::ffi::OsString>| value.as_ref().is_some_and(|value| !value.is_empty());
+ #[cfg(feature = "wayland")]
+ if modes.contains(WindowingModes::WAYLAND) && is_set(&environment.wayland_display) {
+ return Some(Backend::Wayland);
+ }
+ #[cfg(feature = "x11")]
+ if modes.contains(WindowingModes::X11) && is_set(&environment.x11_display) {
+ return Some(Backend::X11);
+ }
+ None
+}
+
+/// A display server that [`DisplayConnection`] can connect to.
+#[derive(Clone, Copy)]
+pub(crate) enum Backend {
+ #[cfg(feature = "wayland")]
+ Wayland,
+ #[cfg(feature = "x11")]
+ X11,
+}
+
+/// The display server a `LinuxPlatform` is connected to.
+///
+/// Every connection follows the same lifecycle, so that switching display modes acquires and
+/// releases the same things at the same points:
+///
+/// - **Attach** (`attach` on the Wayland or X11 connection): connect, create the connection's
+/// state, then register its event sources on the platform's loop. If a step fails, dropping
+/// the partial connection undoes the earlier ones.
+/// - **Detach** (drop): the platform refuses to switch while a window is open. A closed window
+/// has already released everything bound to the connection, including its GPU objects, so
+/// nothing waits. The platform takes the connection out of its `RefCell` before dropping it,
+/// because dropping can call back into the platform. Dropping removes the event sources, stops
+/// the desktop portal listener, hands the clipboard to a clipboard manager (X11, on a
+/// background thread) and closes the connection.
+///
+/// Nothing tied to a display server outlives its connection. What does, in `LinuxCommon`, is
+/// session-independent: the executors, the text system, callbacks and the power listener.
+pub(crate) enum DisplayConnection {
+ Headless(HeadlessConnection),
+ #[cfg(feature = "wayland")]
+ Wayland(WaylandConnection),
+ #[cfg(feature = "x11")]
+ X11(X11Connection),
+}
+
+/// Evaluates `$connected` with `$connection` bound to the Wayland or X11 connection, or
+/// `$headless` while headless, optionally binding the headless state.
+macro_rules! dispatch {
+ ($self:expr, $connection:ident => $connected:expr, headless => $headless:expr) => {
+ dispatch!($self, $connection => $connected, headless(_) => $headless)
+ };
+ ($self:expr, $connection:ident => $connected:expr, headless($state:pat) => $headless:expr) => {
+ match $self {
+ DisplayConnection::Headless($state) => $headless,
+ #[cfg(feature = "wayland")]
+ DisplayConnection::Wayland($connection) => $connected,
+ #[cfg(feature = "x11")]
+ DisplayConnection::X11($connection) => $connected,
+ }
+ };
+}
+
+#[cfg_attr(
+ not(any(feature = "wayland", feature = "x11")),
+ allow(
+ unused_variables,
+ reason = "only headless mode exists without a display backend"
+ )
+)]
+impl DisplayConnection {
+ pub(crate) fn is_headless(&self) -> bool {
+ matches!(self, DisplayConnection::Headless(_))
+ }
+
+ pub(crate) fn compositor_name(&self) -> &'static str {
+ dispatch!(self, connection => connection.compositor_name(), headless => "headless")
+ }
+
+ /// Whether a window is open.
+ pub(crate) fn has_windows(&self) -> bool {
+ dispatch!(self, connection => connection.has_windows(), headless(connection) => connection.has_windows())
+ }
+
+ /// The environment this connection was made in, or `None` while headless.
+ pub(crate) fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
+ dispatch!(self, connection => Some(connection.graphical_environment()), headless => None)
+ }
+
+ pub(crate) fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
+ dispatch!(
+ self,
+ connection => connection.keyboard_layout(),
+ headless => Box::new(LinuxKeyboardLayout::new("unknown".into()))
+ )
+ }
+
+ pub(crate) fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
+ dispatch!(self, connection => connection.displays(), headless(connection) => connection.displays())
+ }
+
+ pub(crate) fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
+ dispatch!(
+ self,
+ connection => connection.primary_display(),
+ headless(connection) => connection.primary_display()
+ )
+ }
+
+ pub(crate) fn open_window(
+ &self,
+ handle: AnyWindowHandle,
+ params: WindowParams,
+ ) -> anyhow::Result<Box<dyn PlatformWindow>> {
+ dispatch!(
+ self,
+ connection => connection.open_window(handle, params),
+ headless(connection) => connection.open_window(handle, params)
+ )
+ }
+
+ pub(crate) fn active_window(&self) -> Option<AnyWindowHandle> {
+ dispatch!(self, connection => connection.active_window(), headless => None)
+ }
+
+ pub(crate) fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
+ dispatch!(self, connection => connection.window_stack(), headless => None)
+ }
+
+ pub(crate) fn set_cursor_style(&self, style: CursorStyle) {
+ dispatch!(self, connection => connection.set_cursor_style(style), headless => ())
+ }
+
+ pub(crate) fn hide_cursor_until_mouse_moves(&self) {
+ dispatch!(self, connection => connection.hide_cursor_until_mouse_moves(), headless => ())
+ }
+
+ pub(crate) fn is_cursor_visible(&self) -> bool {
+ dispatch!(self, connection => connection.is_cursor_visible(), headless => true)
+ }
+
+ pub(crate) fn open_uri(&self, uri: &str) {
+ dispatch!(self, connection => connection.open_uri(uri), headless => ())
+ }
+
+ pub(crate) fn reveal_path(&self, path: PathBuf) {
+ dispatch!(self, connection => connection.reveal_path(path), headless => ())
+ }
+
+ pub(crate) fn write_to_primary(&self, item: ClipboardItem) {
+ dispatch!(self, connection => connection.write_to_primary(item), headless => ())
+ }
+
+ pub(crate) fn write_to_clipboard(&self, item: ClipboardItem) {
+ dispatch!(self, connection => connection.write_to_clipboard(item), headless => ())
+ }
+
+ pub(crate) fn read_from_primary(&self) -> Option<ClipboardItem> {
+ dispatch!(self, connection => connection.read_from_primary(), headless => None)
+ }
+
+ pub(crate) fn read_from_clipboard(&self) -> Option<ClipboardItem> {
+ dispatch!(self, connection => connection.read_from_clipboard(), headless => None)
+ }
+
+ #[cfg(any(feature = "wayland", feature = "x11"))]
+ pub(crate) fn window_identifier(
+ &self,
+ ) -> futures::future::BoxFuture<'static, Option<ashpd::WindowIdentifier>> {
+ dispatch!(
+ self,
+ connection => Box::pin(connection.window_identifier()),
+ headless => Box::pin(std::future::ready(None))
+ )
+ }
+
+ #[cfg(feature = "screen-capture")]
+ pub(crate) fn is_screen_capture_supported(&self) -> bool {
+ dispatch!(self, connection => connection.is_screen_capture_supported(), headless => false)
+ }
+
+ #[cfg(feature = "screen-capture")]
+ pub(crate) fn screen_capture_sources(
+ &self,
+ ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
+ {
+ dispatch!(self, connection => connection.screen_capture_sources(), headless => {
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ sender
+ .send(Err(anyhow::anyhow!("Headless mode does not support screen capture.")))
+ .ok();
+ receiver
+ })
+ }
+}
diff --git a/crates/gpui_linux/src/linux/headless.rs b/crates/gpui_linux/src/linux/headless.rs
index 6667a3b5a1f..49f624a9eda 100644
--- a/crates/gpui_linux/src/linux/headless.rs
+++ b/crates/gpui_linux/src/linux/headless.rs
@@ -1,4 +1,50 @@
-mod client;
mod window;
-pub(crate) use client::*;
+use std::rc::Rc;
+
+use gpui::{AnyWindowHandle, PlatformDisplay, PlatformWindow, WindowParams};
+
+pub(crate) use window::{HeadlessDisplay, HeadlessWindow};
+
+/// The state of a `LinuxPlatform` with no display server.
+///
+/// It reports one fake display and opens [`HeadlessWindow`]s, which lay out and handle input but
+/// draw nothing.
+pub(crate) struct HeadlessConnection {
+ display: Rc<dyn PlatformDisplay>,
+ /// Cloned into every open window, so its count tells whether windows are open.
+ window_lease: Rc<()>,
+}
+
+impl HeadlessConnection {
+ pub(crate) fn new() -> Self {
+ Self {
+ display: Rc::new(HeadlessDisplay::new()),
+ window_lease: Rc::new(()),
+ }
+ }
+
+ pub(crate) fn has_windows(&self) -> bool {
+ Rc::strong_count(&self.window_lease) > 1
+ }
+
+ pub(crate) fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
+ vec![self.display.clone()]
+ }
+
+ pub(crate) fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
+ Some(self.display.clone())
+ }
+
+ pub(crate) fn open_window(
+ &self,
+ _handle: AnyWindowHandle,
+ params: WindowParams,
+ ) -> anyhow::Result<Box<dyn PlatformWindow>> {
+ Ok(Box::new(HeadlessWindow::new(
+ params,
+ self.display.clone(),
+ self.window_lease.clone(),
+ )))
+ }
+}
diff --git a/crates/gpui_linux/src/linux/headless/client.rs b/crates/gpui_linux/src/linux/headless/client.rs
deleted file mode 100644
index 0e94a06007d..00000000000
--- a/crates/gpui_linux/src/linux/headless/client.rs
+++ /dev/null
@@ -1,143 +0,0 @@
-use std::cell::RefCell;
-use std::rc::Rc;
-
-use calloop::{EventLoop, LoopHandle};
-use gpui_util::ResultExt;
-
-use crate::linux::headless::window::{HeadlessDisplay, HeadlessWindow};
-use crate::linux::{LinuxClient, LinuxCommon, LinuxKeyboardLayout};
-use gpui::{
- AnyWindowHandle, CursorStyle, DisplayId, PlatformDisplay, PlatformKeyboardLayout,
- PlatformWindow, WindowParams,
-};
-
-pub struct HeadlessClientState {
- pub(crate) _loop_handle: LoopHandle<'static, HeadlessClient>,
- pub(crate) event_loop: Option<calloop::EventLoop<'static, HeadlessClient>>,
- pub(crate) common: LinuxCommon,
- pub(crate) display: Rc<dyn PlatformDisplay>,
-}
-
-#[derive(Clone)]
-pub(crate) struct HeadlessClient(Rc<RefCell<HeadlessClientState>>);
-
-impl HeadlessClient {
- pub(crate) fn new() -> Self {
- let event_loop = EventLoop::try_new().unwrap();
-
- let (common, main_receiver, power_receiver) = LinuxCommon::new(event_loop.get_signal());
-
- let handle = event_loop.handle();
-
- handle
- .insert_source(main_receiver, |event, _, _: &mut HeadlessClient| {
- if let calloop::channel::Event::Msg(runnable) = event {
- runnable.run();
- }
- })
- .ok();
-
- handle
- .insert_source(power_receiver, |event, _, client: &mut HeadlessClient| {
- if let calloop::channel::Event::Msg(event) = event {
- client.with_common(|common| common.handle_system_power_event(event));
- }
- })
- .ok();
-
- HeadlessClient(Rc::new(RefCell::new(HeadlessClientState {
- event_loop: Some(event_loop),
- _loop_handle: handle,
- common,
- display: Rc::new(HeadlessDisplay::new()),
- })))
- }
-}
-
-impl LinuxClient for HeadlessClient {
- fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
- f(&mut self.0.borrow_mut().common)
- }
-
- fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
- Box::new(LinuxKeyboardLayout::new("unknown".into()))
- }
-
- fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
- vec![self.0.borrow().display.clone()]
- }
-
- fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
- Some(self.0.borrow().display.clone())
- }
-
- fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
- let display = self.0.borrow().display.clone();
- (display.id() == id).then_some(display)
- }
-
- #[cfg(feature = "screen-capture")]
- fn screen_capture_sources(
- &self,
- ) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
- {
- let (tx, rx) = futures::channel::oneshot::channel();
- tx.send(Err(anyhow::anyhow!(
- "Headless mode does not support screen capture."
- )))
- .ok();
- rx
- }
-
- fn active_window(&self) -> Option<AnyWindowHandle> {
- None
- }
-
- fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
- None
- }
-
- fn open_window(
- &self,
- _handle: AnyWindowHandle,
- params: WindowParams,
- ) -> anyhow::Result<Box<dyn PlatformWindow>> {
- Ok(Box::new(HeadlessWindow::new(
- params,
- self.0.borrow().display.clone(),
- )))
- }
-
- fn compositor_name(&self) -> &'static str {
- "headless"
- }
-
- fn set_cursor_style(&self, _style: CursorStyle) {}
-
- fn open_uri(&self, _uri: &str) {}
-
- fn reveal_path(&self, _path: std::path::PathBuf) {}
-
- fn write_to_primary(&self, _item: gpui::ClipboardItem) {}
-
- fn write_to_clipboard(&self, _item: gpui::ClipboardItem) {}
-
- fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
- None
- }
-
- fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
- None
- }
-
- fn run(&self) {
- let mut event_loop = self
- .0
- .borrow_mut()
- .event_loop
- .take()
- .expect("App is already running");
-
- event_loop.run(None, &mut self.clone(), |_| {}).log_err();
- }
-}
diff --git a/crates/gpui_linux/src/linux/headless/window.rs b/crates/gpui_linux/src/linux/headless/window.rs
index 35096d922b5..be158270038 100644
--- a/crates/gpui_linux/src/linux/headless/window.rs
+++ b/crates/gpui_linux/src/linux/headless/window.rs
@@ -51,6 +51,8 @@ impl PlatformDisplay for HeadlessDisplay {
struct HeadlessWindowState {
bounds: Bounds<Pixels>,
display: Rc<dyn PlatformDisplay>,
+ /// Held while this window exists, so the platform can tell that headless windows are open.
+ _lease: Rc<()>,
input_handler: Option<PlatformInputHandler>,
title: Option<String>,
is_fullscreen: bool,
@@ -76,10 +78,15 @@ impl raw_window_handle::HasDisplayHandle for HeadlessWindow {
}
impl HeadlessWindow {
- pub(crate) fn new(params: WindowParams, display: Rc<dyn PlatformDisplay>) -> Self {
+ pub(crate) fn new(
+ params: WindowParams,
+ display: Rc<dyn PlatformDisplay>,
+ lease: Rc<()>,
+ ) -> Self {
Self(Rc::new(RefCell::new(HeadlessWindowState {
bounds: params.bounds,
display,
+ _lease: lease,
input_handler: None,
title: None,
is_fullscreen: false,
diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs
index 7bf77a1bc35..44aa6589744 100644
--- a/crates/gpui_linux/src/linux/platform.rs
+++ b/crates/gpui_linux/src/linux/platform.rs
@@ -1,4 +1,5 @@
use std::{
+ cell::RefCell,
env,
path::{Path, PathBuf},
rc::Rc,
@@ -24,19 +25,22 @@ use ashpd::{
},
enumflags2::BitFlags,
};
-use calloop::{LoopSignal, channel::Sender};
+use calloop::{EventLoop, LoopHandle, 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 crate::linux::{
+ Backend, DisplayConnection, HeadlessConnection, LinuxDispatcher, PriorityQueueCalloopReceiver,
+ select_backend,
+};
use gpui::{
Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
- DisplayId, ForegroundExecutor, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions, Platform,
- PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
+ ForegroundExecutor, GraphicalEnvironment, Keymap, Menu, MenuItem, OwnedMenu, PathPromptOptions,
+ Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
PlatformWindow, Result, RunnableVariant, Task, ThermalState, WindowAppearance,
- WindowButtonLayout, WindowParams,
+ WindowButtonLayout, WindowParams, WindowingModes, WindowingRequest,
};
#[cfg(any(feature = "wayland", feature = "x11"))]
use gpui::{Pixels, Point, px};
@@ -56,61 +60,6 @@ pub(crate) const KEYRING_LABEL: &str = "zed-github-account";
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>)>>,
@@ -154,6 +103,11 @@ pub(crate) struct LinuxCommon {
)]
power_sender: Sender<SystemPowerEvent>,
power_listener_started: bool,
+ /// Runs after each foreground runnable registered by [`LinuxCommon::register_sources`].
+ ///
+ /// X11 uses this to handle events that a runnable's requests read into xcb's queue, where
+ /// they would not wake the event loop.
+ pub(crate) after_runnable: Option<Rc<dyn Fn()>>,
}
impl LinuxCommon {
@@ -193,6 +147,7 @@ impl LinuxCommon {
),
power_sender,
power_listener_started: false,
+ after_runnable: None,
};
(common, main_receiver, power_receiver)
@@ -215,13 +170,72 @@ impl LinuxCommon {
}
}
- pub(crate) fn handle_system_power_event(&mut self, event: SystemPowerEvent) {
- let callback = match event {
- SystemPowerEvent::Sleep => &mut self.callbacks.system_sleep,
- SystemPowerEvent::Wake => &mut self.callbacks.system_wake,
- };
- if let Some(callback) = callback.as_mut() {
+ /// Registers the foreground executor and power listener on a loop shared with display clients.
+ ///
+ /// Foreground runnables run as idle callbacks, after the loop has dispatched all pending events.
+ pub(crate) fn register_sources(
+ common: &Rc<RefCell<Self>>,
+ loop_handle: &calloop::LoopHandle<'static, ()>,
+ main_receiver: PriorityQueueCalloopReceiver<RunnableVariant>,
+ power_receiver: calloop::channel::Channel<SystemPowerEvent>,
+ ) -> anyhow::Result<()> {
+ loop_handle
+ .insert_source(main_receiver, {
+ let loop_handle = loop_handle.clone();
+ let common = common.clone();
+ move |event, _, _| {
+ if let calloop::channel::Event::Msg(runnable) = event {
+ let common = common.clone();
+ loop_handle.insert_idle(move |_| {
+ let location = runnable.metadata().location;
+ let spawned = runnable.metadata().spawned;
+ gpui::profiler::update_running_task(spawned, location);
+ runnable.run();
+ gpui::profiler::save_task_timing();
+
+ let after_runnable = common.borrow().after_runnable.clone();
+ if let Some(after_runnable) = after_runnable {
+ after_runnable();
+ }
+ });
+ }
+ }
+ })
+ .map_err(|error| anyhow!("failed to register foreground executor: {error}"))?;
+ loop_handle
+ .insert_source(power_receiver, {
+ let common = common.clone();
+ move |event, _, _| {
+ if let calloop::channel::Event::Msg(event) = event {
+ LinuxCommon::handle_system_power_event(&common, event);
+ }
+ }
+ })
+ .map_err(|error| anyhow!("failed to register power listener: {error}"))?;
+ Ok(())
+ }
+
+ /// Runs the app's sleep or wake callback, without `common` borrowed, since the callback
+ /// can call back into the platform.
+ fn handle_system_power_event(common: &RefCell<Self>, event: SystemPowerEvent) {
+ fn slot(
+ callbacks: &mut PlatformHandlers,
+ event: SystemPowerEvent,
+ ) -> &mut Option<Box<dyn FnMut()>> {
+ match event {
+ SystemPowerEvent::Sleep => &mut callbacks.system_sleep,
+ SystemPowerEvent::Wake => &mut callbacks.system_wake,
+ }
+ }
+ let callback = slot(&mut common.borrow_mut().callbacks, event).take();
+ if let Some(mut callback) = callback {
callback();
+ let mut common = common.borrow_mut();
+ let slot = slot(&mut common.callbacks, event);
+ // The callback may have replaced itself.
+ if slot.is_none() {
+ *slot = Some(callback);
+ }
}
}
}
@@ -254,27 +268,289 @@ async fn listen_for_system_power_events(
Ok(())
}
-pub(crate) struct LinuxPlatform<P> {
- pub(crate) inner: P,
+/// GPUI's platform for Linux and FreeBSD.
+///
+/// One event loop serves the whole process. The foreground executor and power listener are
+/// registered on it once, and the current [`DisplayConnection`] adds and removes its own sources
+/// as the app switches between the display modes it allows.
+pub(crate) struct LinuxPlatform {
+ common: Rc<RefCell<LinuxCommon>>,
+ /// The event loop, until `run` takes it.
+ event_loop: RefCell<Option<EventLoop<'static, ()>>>,
+ loop_handle: LoopHandle<'static, ()>,
+ connection: RefCell<DisplayConnection>,
+ allowed_modes: WindowingModes,
+ /// The mode to start in, applied when `run` starts. Windowed in the process's own
+ /// environment when unset.
+ initial_windowing: RefCell<Option<WindowingRequest>>,
+ /// Taken by the connection made when `run` starts.
+ startup_environment: RefCell<Option<StartupEnvironment>>,
+ /// A requested switch waiting for the event loop to apply it.
+ pending_mode: RefCell<Option<WindowingRequest>>,
+ transition_waiter: RefCell<Option<oneshot::Sender<anyhow::Result<()>>>>,
+}
+
+/// What a Wayland connection made at startup may use from this process's environment.
+///
+/// Both are taken from the environment when the platform is created, before it starts any
+/// threads, and are only meaningful for the connection made then.
+#[derive(Default)]
+struct StartupEnvironment {
+ #[cfg(feature = "wayland")]
+ activation_token: Option<String>,
+ /// The socket `WAYLAND_SOCKET` names: a connection to the compositor that the process which
+ /// started us already opened.
+ #[cfg(feature = "wayland")]
+ wayland_socket: Option<std::os::unix::net::UnixStream>,
}
-impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
+impl LinuxPlatform {
+ /// Creates the platform, headless until `run` connects it in its initial mode.
+ pub(crate) fn new(allowed_modes: WindowingModes) -> Self {
+ let startup = StartupEnvironment {
+ #[cfg(feature = "wayland")]
+ activation_token: crate::linux::take_startup_activation_token_from_environment(),
+ #[cfg(feature = "wayland")]
+ wayland_socket: crate::linux::take_wayland_socket_from_environment(),
+ };
+ let event_loop = EventLoop::try_new().expect("failed to create Linux event loop");
+ let (common, main_receiver, power_receiver) = LinuxCommon::new(event_loop.get_signal());
+ let common = Rc::new(RefCell::new(common));
+ let loop_handle = event_loop.handle();
+ LinuxCommon::register_sources(&common, &loop_handle, main_receiver, power_receiver)
+ .expect("failed to register Linux event sources");
+ Self {
+ common,
+ event_loop: RefCell::new(Some(event_loop)),
+ loop_handle,
+ connection: RefCell::new(DisplayConnection::Headless(HeadlessConnection::new())),
+ allowed_modes,
+ initial_windowing: RefCell::new(None),
+ startup_environment: RefCell::new(Some(startup)),
+ pending_mode: RefCell::new(None),
+ transition_waiter: RefCell::new(None),
+ }
+ }
+
+ /// Connects in the initial mode, before the app finishes launching.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the allowed modes don't allow the initial mode, or if its display server can't
+ /// be reached, since the app can't start. A windowed initial mode whose environment names no
+ /// allowed display server starts headless when that's allowed.
+ fn connect_initially(&self) {
+ let request = self
+ .initial_windowing
+ .borrow_mut()
+ .take()
+ .unwrap_or_else(|| WindowingRequest::Windowed(GraphicalEnvironment::detect()));
+ // Dropped unused when starting headless, closing any inherited `WAYLAND_SOCKET`.
+ let startup = self
+ .startup_environment
+ .borrow_mut()
+ .take()
+ .unwrap_or_default();
+ let backend = match &request {
+ WindowingRequest::Headless => None,
+ WindowingRequest::Windowed(environment) => {
+ select_backend(self.allowed_modes, environment)
+ .map(|backend| (backend, environment))
+ }
+ };
+ match backend {
+ Some((backend, environment)) => {
+ let connection = self
+ .connect(backend, environment, startup)
+ .unwrap_or_else(|error| panic!("{error:#}"));
+ self.replace_connection(connection);
+ }
+ None => assert!(
+ self.allowed_modes.contains(WindowingModes::HEADLESS),
+ "{:?} does not allow starting headless, and no allowed display server was given",
+ self.allowed_modes
+ ),
+ }
+ }
+
+ fn with_common<R>(&self, function: impl FnOnce(&mut LinuxCommon) -> R) -> R {
+ function(&mut self.common.borrow_mut())
+ }
+
+ /// Connects to the display server `backend` in `environment`.
+ ///
+ /// `startup` is only given for the connection made when the platform is created.
+ #[cfg_attr(
+ not(feature = "wayland"),
+ allow(
+ unused_variables,
+ reason = "only Wayland uses the startup environment, and without a display backend \
+ `Backend` has no variants"
+ )
+ )]
+ fn connect(
+ &self,
+ backend: Backend,
+ environment: &GraphicalEnvironment,
+ startup: StartupEnvironment,
+ ) -> anyhow::Result<DisplayConnection> {
+ let loop_handle = self.loop_handle.clone();
+ let common = self.common.clone();
+ match backend {
+ #[cfg(feature = "wayland")]
+ Backend::Wayland => {
+ let activation_token = environment
+ .activation_token
+ .clone()
+ .or(startup.activation_token);
+ Ok(DisplayConnection::Wayland(
+ crate::linux::WaylandConnection::attach(
+ loop_handle,
+ common,
+ environment,
+ startup.wayland_socket,
+ activation_token,
+ )?,
+ ))
+ }
+ #[cfg(feature = "x11")]
+ Backend::X11 => Ok(DisplayConnection::X11(crate::linux::X11Connection::attach(
+ loop_handle,
+ common,
+ environment,
+ )?)),
+ }
+ }
+
+ /// Installs `connection`, then drops the previous one outside the borrow, since dropping a
+ /// connection can call back into the platform.
+ fn replace_connection(&self, connection: DisplayConnection) {
+ let previous = std::mem::replace(&mut *self.connection.borrow_mut(), connection);
+ drop(previous);
+ // The app caches the keyboard layout, which belongs to the connection.
+ let callback = self
+ .common
+ .borrow_mut()
+ .callbacks
+ .keyboard_layout_change
+ .take();
+ if let Some(mut callback) = callback {
+ callback();
+ let mut common = self.common.borrow_mut();
+ // The callback may have replaced itself.
+ if common.callbacks.keyboard_layout_change.is_none() {
+ common.callbacks.keyboard_layout_change = Some(callback);
+ }
+ }
+ }
+
+ /// Applies a pending switch.
+ ///
+ /// Runs between event-loop iterations, so no event source is mid-dispatch when the
+ /// connection's sources are added or removed.
+ fn apply_pending_mode(&self) {
+ let Some(mode) = self.pending_mode.borrow().clone() else {
+ return;
+ };
+ // `request_mode` rejects open windows, but one can be opened before this runs.
+ let result = if self.connection.borrow().has_windows() {
+ Err(anyhow!("a window was opened while switching display modes"))
+ } else {
+ match mode {
+ WindowingRequest::Headless => {
+ self.replace_connection(DisplayConnection::Headless(HeadlessConnection::new()));
+ Ok(())
+ }
+ WindowingRequest::Windowed(environment) => {
+ select_backend(self.allowed_modes, &environment)
+ .context("the environment names no allowed Wayland or X11 display server")
+ .and_then(|backend| {
+ self.connect(backend, &environment, StartupEnvironment::default())
+ })
+ .map(|connection| self.replace_connection(connection))
+ }
+ }
+ };
+ self.pending_mode.borrow_mut().take();
+ if let Some(waiter) = self.transition_waiter.borrow_mut().take() {
+ waiter.send(result).ok();
+ }
+ }
+
+ /// Validates a requested switch, then leaves it for the event loop to apply.
+ fn request_mode(&self, mode: WindowingRequest) -> Task<anyhow::Result<()>> {
+ if self.pending_mode.borrow().is_some() {
+ return Task::ready(Err(anyhow!(
+ "a display mode transition is already in progress"
+ )));
+ }
+ let is_headless = self.connection.borrow().is_headless();
+ match &mode {
+ WindowingRequest::Headless
+ if !self.allowed_modes.contains(WindowingModes::HEADLESS) =>
+ {
+ return Task::ready(Err(anyhow!(
+ "{:?} does not allow headless mode",
+ self.allowed_modes
+ )));
+ }
+ WindowingRequest::Headless if is_headless => {
+ return Task::ready(Err(anyhow!("already headless")));
+ }
+ WindowingRequest::Headless => {}
+ WindowingRequest::Windowed(_) if !is_headless => {
+ return Task::ready(Err(anyhow!(
+ "already windowed ({}); switch to headless mode first",
+ self.connection.borrow().compositor_name()
+ )));
+ }
+ WindowingRequest::Windowed(environment) => {
+ if select_backend(self.allowed_modes, environment).is_none() {
+ return Task::ready(Err(anyhow!(
+ "the environment names no display server that {:?} allows",
+ self.allowed_modes
+ )));
+ }
+ }
+ }
+ let (sender, receiver) = oneshot::channel();
+ self.transition_waiter.borrow_mut().replace(sender);
+ *self.pending_mode.borrow_mut() = Some(mode);
+ // The wakeup persists until the loop next polls, so a request made before `run` starts is
+ // applied after its first iteration.
+ self.common.borrow().signal.wakeup();
+ self.common.borrow().foreground_executor.spawn(async move {
+ receiver
+ .await
+ .map_err(|_| anyhow!("display mode transition was canceled"))
+ .and_then(|result| result)
+ })
+ }
+}
+
+impl Drop for LinuxPlatform {
+ fn drop(&mut self) {
+ self.replace_connection(DisplayConnection::Headless(HeadlessConnection::new()));
+ #[cfg(feature = "x11")]
+ crate::linux::wait_for_clipboard_handovers();
+ }
+}
+
+impl Platform for LinuxPlatform {
fn background_executor(&self) -> BackgroundExecutor {
- self.inner
- .with_common(|common| common.background_executor.clone())
+ self.with_common(|common| common.background_executor.clone())
}
fn foreground_executor(&self) -> ForegroundExecutor {
- self.inner
- .with_common(|common| common.foreground_executor.clone())
+ self.with_common(|common| common.foreground_executor.clone())
}
fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
- self.inner.with_common(|common| common.text_system.clone())
+ self.with_common(|common| common.text_system.clone())
}
fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
- self.inner.keyboard_layout()
+ self.connection.borrow().keyboard_layout()
}
fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
@@ -282,8 +558,7 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
- self.inner
- .with_common(|common| common.callbacks.keyboard_layout_change = Some(callback));
+ self.with_common(|common| common.callbacks.keyboard_layout_change = Some(callback));
}
fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
@@ -320,24 +595,44 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
+ self.connect_initially();
on_finish_launching();
- LinuxClient::run(&self.inner);
+ let mut event_loop = self
+ .event_loop
+ .borrow_mut()
+ .take()
+ .expect("App is already running");
+ event_loop
+ .run(None, &mut (), |_| self.apply_pending_mode())
+ .log_err();
- let quit = self
- .inner
- .with_common(|common| common.callbacks.quit.take());
+ let quit = self.with_common(|common| common.callbacks.quit.take());
if let Some(mut fun) = quit {
fun();
}
+ #[cfg(feature = "x11")]
+ crate::linux::wait_for_clipboard_handovers();
}
fn quit(&self) {
- self.inner.with_common(|common| common.signal.stop());
+ self.with_common(|common| common.signal.stop());
+ }
+
+ fn set_initial_windowing(&self, request: WindowingRequest) {
+ *self.initial_windowing.borrow_mut() = Some(request);
+ }
+
+ fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
+ self.request_mode(request)
}
fn compositor_name(&self) -> &'static str {
- self.inner.compositor_name()
+ self.connection.borrow().compositor_name()
+ }
+
+ fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
+ self.connection.borrow().graphical_environment()
}
fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<std::ffi::OsString>) {
@@ -409,31 +704,31 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
- self.inner.primary_display()
+ self.connection.borrow().primary_display()
}
fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
- self.inner.displays()
+ self.connection.borrow().displays()
}
#[cfg(feature = "screen-capture")]
fn is_screen_capture_supported(&self) -> bool {
- self.inner.is_screen_capture_supported()
+ self.connection.borrow().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()
+ self.connection.borrow().screen_capture_sources()
}
fn active_window(&self) -> Option<AnyWindowHandle> {
- self.inner.active_window()
+ self.connection.borrow().active_window()
}
fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
- self.inner.window_stack()
+ self.connection.borrow().window_stack()
}
fn open_window(
@@ -441,16 +736,15 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
handle: AnyWindowHandle,
options: WindowParams,
) -> anyhow::Result<Box<dyn PlatformWindow>> {
- self.inner.open_window(handle, options)
+ self.connection.borrow().open_window(handle, options)
}
fn open_url(&self, url: &str) {
- self.inner.open_uri(url);
+ self.connection.borrow().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));
+ self.with_common(|common| common.callbacks.open_urls = Some(callback));
}
fn prompt_for_paths(
@@ -463,7 +757,7 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
let _ = (done_tx.send(Ok(None)), options);
#[cfg(any(feature = "wayland", feature = "x11"))]
- let identifier = self.inner.window_identifier();
+ let identifier = self.connection.borrow().window_identifier();
#[cfg(any(feature = "wayland", feature = "x11"))]
self.foreground_executor()
@@ -524,7 +818,7 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
let _ = (done_tx.send(Ok(None)), directory, suggested_name);
#[cfg(any(feature = "wayland", feature = "x11"))]
- let identifier = self.inner.window_identifier();
+ let identifier = self.connection.borrow().window_identifier();
#[cfg(any(feature = "wayland", feature = "x11"))]
self.foreground_executor()
@@ -582,59 +876,60 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn reveal_path(&self, path: &Path) {
- self.inner.reveal_path(path.to_owned());
+ self.connection.borrow().reveal_path(path.to_owned());
}
fn open_with_system(&self, path: &Path) {
let path = path.to_owned();
+ let environment = self.connection.borrow().graphical_environment();
self.background_executor()
.spawn(async move {
+ let mut command = new_std_command("xdg-open");
+ command.arg(path);
+ if let Some(environment) = environment {
+ environment.apply_to(&mut command);
+ }
#[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();
+ command.status().context("invoking xdg-open").log_err();
})
.detach();
}
fn on_quit(&self, callback: Box<dyn FnMut() -> bool>) {
- self.inner.with_common(|common| {
+ self.with_common(|common| {
common.callbacks.quit = Some(callback);
});
}
fn on_reopen(&self, callback: Box<dyn FnMut()>) {
- self.inner.with_common(|common| {
+ self.with_common(|common| {
common.callbacks.reopen = Some(callback);
});
}
fn on_system_sleep(&self, callback: Box<dyn FnMut()>) {
- self.inner.with_common(|common| {
+ self.with_common(|common| {
common.callbacks.system_sleep = Some(callback);
common.start_power_listener();
});
}
fn on_system_wake(&self, callback: Box<dyn FnMut()>) {
- self.inner.with_common(|common| {
+ self.with_common(|common| {
common.callbacks.system_wake = Some(callback);
common.start_power_listener();
});
}
fn set_app_identity(&self, _identifier: &str, name: &str) {
- self.inner
- .with_common(|common| common.app_name = Some(name.to_string()));
+ self.with_common(|common| common.app_name = Some(name.to_string()));
}
fn show_system_notification(&self, notification: gpui::SystemNotification) {
- self.inner.with_common(|common| {
+ self.with_common(|common| {
common
.system_notifications
.show(common.app_name.as_deref(), notification)
@@ -642,34 +937,33 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn dismiss_system_notification(&self, tag: &str) {
- self.inner
- .with_common(|common| common.system_notifications.dismiss(tag));
+ self.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| {
+ self.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| {
+ self.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| {
+ self.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| {
+ self.with_common(|common| {
common.callbacks.validate_app_menu_command = Some(callback);
});
}
@@ -681,13 +975,13 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {
- self.inner.with_common(|common| {
+ self.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()))
+ self.with_common(|common| Some(common.menus.clone()))
}
fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {
@@ -701,19 +995,19 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn set_cursor_style(&self, style: CursorStyle) {
- self.inner.set_cursor_style(style)
+ self.connection.borrow().set_cursor_style(style)
}
fn hide_cursor_until_mouse_moves(&self) {
- self.inner.hide_cursor_until_mouse_moves()
+ self.connection.borrow().hide_cursor_until_mouse_moves()
}
fn is_cursor_visible(&self) -> bool {
- self.inner.is_cursor_visible()
+ self.connection.borrow().is_cursor_visible()
}
fn should_auto_hide_scrollbars(&self) -> bool {
- self.inner.with_common(|common| common.auto_hide_scrollbars)
+ self.with_common(|common| common.auto_hide_scrollbars)
}
fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
@@ -783,11 +1077,11 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn window_appearance(&self) -> WindowAppearance {
- self.inner.with_common(|common| common.appearance)
+ self.with_common(|common| common.appearance)
}
fn button_layout(&self) -> Option<WindowButtonLayout> {
- Some(self.inner.with_common(|common| common.button_layout))
+ Some(self.with_common(|common| common.button_layout))
}
fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {
@@ -795,59 +1089,67 @@ impl<P: LinuxClient + 'static> Platform for LinuxPlatform<P> {
}
fn write_to_primary(&self, item: ClipboardItem) {
- self.inner.write_to_primary(item)
+ self.connection.borrow().write_to_primary(item)
}
fn write_to_clipboard(&self, item: ClipboardItem) {
- self.inner.write_to_clipboard(item)
+ self.connection.borrow().write_to_clipboard(item)
}
fn read_from_primary(&self) -> Option<ClipboardItem> {
- self.inner.read_from_primary()
+ self.connection.borrow().read_from_primary()
}
fn read_from_clipboard(&self) -> Option<ClipboardItem> {
- self.inner.read_from_clipboard()
+ self.connection.borrow().read_from_clipboard()
}
fn add_recent_document(&self, _path: &Path) {}
}
+/// Opens `target` with the first of the desktop's launchers that succeeds. Returns whether one
+/// did.
+#[cfg(any(feature = "wayland", feature = "x11"))]
+async fn run_open_commands(
+ target: &std::ffi::OsStr,
+ activation_token: Option<&str>,
+ environment: &GraphicalEnvironment,
+) -> bool {
+ for mut command in open::commands(target) {
+ environment.apply_to(&mut command);
+ if let Some(token) = activation_token {
+ command.env("XDG_ACTIVATION_TOKEN", token);
+ }
+ let program = format!("{:?}", command.get_program());
+ match smol::process::Command::from(command).spawn() {
+ Ok(mut child) => match child.status().await {
+ Ok(status) if status.success() => return true,
+ Ok(status) => log::error!("Command {} exited with status: {}", program, status),
+ Err(error) => log::error!("Failed to get status from {}: {}", program, error),
+ },
+ Err(error) => log::error!("Failed to open with {}: {}", program, error),
+ }
+ }
+ false
+}
+
#[cfg(any(feature = "wayland", feature = "x11"))]
pub(super) fn open_uri_internal(
executor: BackgroundExecutor,
uri: &str,
activation_token: Option<String>,
+ environment: GraphicalEnvironment,
) {
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 {
+ let opened = run_open_commands(
+ uri.as_str().as_ref(),
+ activation_token.as_deref(),
+ &environment,
+ )
+ .await;
+ if !opened {
match ashpd::desktop::open_uri::OpenFileRequest::default()
.activation_token(activation_token.map(ashpd::ActivationToken::from))
.send_uri(&uri)
@@ -871,23 +1173,30 @@ pub(super) fn reveal_path_internal(
executor: BackgroundExecutor,
path: PathBuf,
activation_token: Option<String>,
+ environment: GraphicalEnvironment,
) {
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))
+ .activation_token(activation_token.clone().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();
+ let directory = if path.is_dir() {
+ path.as_path()
} else {
- open::that_detached(path.parent().unwrap_or(Path::new(""))).log_err();
- }
+ path.parent().unwrap_or(Path::new(""))
+ };
+ run_open_commands(
+ directory.as_os_str(),
+ activation_token.as_deref(),
+ &environment,
+ )
+ .await;
}
})
.detach();
@@ -1602,3 +1911,195 @@ mod tests {
}
}
}
+
+#[cfg(test)]
+mod display_mode_tests {
+ use std::{cell::Cell, process::Command};
+
+ #[cfg(feature = "wayland")]
+ use gpui::{AppContext as _, Context, IntoElement, Render, Window, WindowOptions};
+ use gpui::{Application, AsyncApp, QuitMode};
+
+ use super::*;
+
+ /// Set in the child process that runs a scenario, naming the scenario to run.
+ const SCENARIO_ENV: &str = "GPUI_LINUX_DISPLAY_MODE_SCENARIO";
+ const MISSING_WAYLAND_DISPLAY: &str = "/gpui-test/wayland-display-does-not-exist";
+
+ #[cfg(feature = "wayland")]
+ #[test]
+ fn failed_wayland_attach_preserves_headless_app_and_allows_retry() {
+ run_scenario(
+ "failed_wayland_attach_preserves_headless_app_and_allows_retry",
+ WindowingModes::all(),
+ |cx| {
+ Box::pin(async move {
+ let entity = cx.new(|_| 1usize);
+ let (release_task, wait_for_release) = oneshot::channel();
+ let queued_task_ran = Rc::new(Cell::new(false));
+ let queued_task = cx.spawn({
+ let queued_task_ran = queued_task_ran.clone();
+ async move |_| {
+ wait_for_release
+ .await
+ .expect("queued task release sender remains alive");
+ queued_task_ran.set(true);
+ }
+ });
+
+ let first_attach = cx.update(|cx| {
+ cx.request_windowing(WindowingRequest::Windowed(
+ GraphicalEnvironment::detect(),
+ ))
+ });
+ assert_error_contains(
+ first_attach.await,
+ "failed to connect to Wayland compositor",
+ );
+ entity.update(cx, |value, _| *value += 1);
+ release_task
+ .send(())
+ .expect("queued task remains attached to the executor");
+ queued_task.await;
+ assert!(queued_task_ran.get());
+
+ let second_attach = cx.update(|cx| {
+ cx.request_windowing(WindowingRequest::Windowed(
+ GraphicalEnvironment::detect(),
+ ))
+ });
+ assert_error_contains(
+ second_attach.await,
+ "failed to connect to Wayland compositor",
+ );
+ entity.update(cx, |value, _| *value += 1);
+ assert_eq!(entity.read_with(cx, |value, _| *value), 3);
+ })
+ },
+ );
+ }
+
+ #[cfg(feature = "wayland")]
+ #[test]
+ fn headless_windows_block_switching_to_a_display_server() {
+ run_scenario(
+ "headless_windows_block_switching_to_a_display_server",
+ WindowingModes::all(),
+ |cx| {
+ Box::pin(async move {
+ let window = cx
+ .update(|cx| {
+ cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Blank))
+ })
+ .expect("headless mode opens headless windows");
+ let attach = cx.update(|cx| {
+ cx.request_windowing(WindowingRequest::Windowed(
+ GraphicalEnvironment::detect(),
+ ))
+ });
+ assert_error_contains(attach.await, "while windows are open");
+
+ cx.update(|cx| window.update(cx, |_, window, _| window.remove_window()))
+ .expect("close the headless window");
+ let attach = cx.update(|cx| {
+ cx.request_windowing(WindowingRequest::Windowed(
+ GraphicalEnvironment::detect(),
+ ))
+ });
+ assert_error_contains(attach.await, "failed to connect to Wayland compositor");
+ })
+ },
+ );
+ }
+
+ #[test]
+ fn display_modes_limit_switching() {
+ run_scenario(
+ "display_modes_limit_switching",
+ WindowingModes::HEADLESS,
+ |cx| {
+ Box::pin(async move {
+ let attach = cx.update(|cx| {
+ cx.request_windowing(WindowingRequest::Windowed(
+ GraphicalEnvironment::detect(),
+ ))
+ });
+ assert_error_contains(attach.await, "names no display server that");
+ assert_eq!(cx.update(|cx| cx.compositor_name()), "headless");
+ assert!(cx.update(|cx| cx.graphical_environment()).is_none());
+
+ let detach = cx.update(|cx| cx.request_windowing(WindowingRequest::Headless));
+ assert_error_contains(detach.await, "already headless");
+ })
+ },
+ );
+ }
+
+ #[cfg(feature = "wayland")]
+ struct Blank;
+
+ #[cfg(feature = "wayland")]
+ impl Render for Blank {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ gpui::Empty
+ }
+ }
+
+ type Scenario = fn(&mut AsyncApp) -> futures::future::LocalBoxFuture<'_, ()>;
+
+ /// Runs `scenario` on a headless platform in a child process, where `WAYLAND_DISPLAY` names a
+ /// socket that doesn't exist.
+ fn run_scenario(name: &str, modes: WindowingModes, scenario: Scenario) {
+ if std::env::var(SCENARIO_ENV).as_deref() == Ok(name) {
+ let platform = Rc::new(LinuxPlatform::new(modes));
+ platform.set_initial_windowing(WindowingRequest::Headless);
+ let completed = Rc::new(Cell::new(false));
+ Application::with_platform(platform)
+ .with_quit_mode(QuitMode::Explicit)
+ .run({
+ let completed = completed.clone();
+ move |cx| {
+ cx.spawn(async move |cx| {
+ scenario(cx).await;
+ completed.set(true);
+ cx.update(|cx| cx.quit());
+ })
+ .detach();
+ }
+ });
+ assert!(completed.get(), "scenario did not complete");
+ return;
+ }
+
+ // Test names don't include the crate's name.
+ let module = module_path!()
+ .split_once("::")
+ .map_or(module_path!(), |(_, module)| module);
+ let test_name = format!("{module}::{name}");
+ #[allow(
+ clippy::disallowed_methods,
+ reason = "the test thread has nothing else to do while the child runs"
+ )]
+ let output = Command::new(std::env::current_exe().expect("current test executable"))
+ .args(["--exact", &test_name, "--nocapture"])
+ .env(SCENARIO_ENV, name)
+ .env("WAYLAND_DISPLAY", MISSING_WAYLAND_DISPLAY)
+ .env_remove("DISPLAY")
+ .output()
+ .expect("run the scenario in a child process");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ output.status.success() && stdout.contains("1 passed"),
+ "scenario failed\nstdout:\n{stdout}\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stderr),
+ );
+ }
+
+ fn assert_error_contains(result: anyhow::Result<()>, expected: &str) {
+ let error = result.expect_err("the transition fails");
+ assert!(
+ format!("{error:#}").contains(expected),
+ "expected an error containing {expected:?}, got: {error:#}"
+ );
+ }
+}
diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rs
index a28343fcf83..bc73fc3bce0 100644
--- a/crates/gpui_linux/src/linux/wayland/client.rs
+++ b/crates/gpui_linux/src/linux/wayland/client.rs
@@ -1,15 +1,19 @@
use std::{
cell::{RefCell, RefMut},
hash::Hash,
- os::fd::{AsRawFd, BorrowedFd},
+ os::{
+ fd::{AsRawFd, BorrowedFd, FromRawFd as _, RawFd},
+ unix::net::UnixStream,
+ },
path::PathBuf,
rc::{Rc, Weak},
time::{Duration, Instant},
};
+use anyhow::Context as _;
use ashpd::WindowIdentifier;
use calloop::{
- EventLoop, LoopHandle,
+ LoopHandle, RegistrationToken,
ping::Ping,
timer::{TimeoutAction, Timer},
};
@@ -81,11 +85,10 @@ use super::{
};
use crate::linux::{
- DOUBLE_CLICK_INTERVAL, LinuxClient, LinuxCommon, LinuxKeyboardLayout, PIPE_READ_TIMEOUT,
- SCROLL_LINES, capslock_from_xkb, cursor_style_to_icon_names, get_xkb_compose_state,
- is_within_click_distance, keystroke_from_xkb, keystroke_underlying_dead_key,
- modifiers_from_xkb, new_xkb_context, open_uri_internal, read_fd_with_timeout,
- reveal_path_internal,
+ DOUBLE_CLICK_INTERVAL, LinuxCommon, LinuxKeyboardLayout, PIPE_READ_TIMEOUT, SCROLL_LINES,
+ capslock_from_xkb, cursor_style_to_icon_names, get_xkb_compose_state, is_within_click_distance,
+ keystroke_from_xkb, keystroke_underlying_dead_key, modifiers_from_xkb, new_xkb_context,
+ open_uri_internal, read_fd_with_timeout, reveal_path_internal,
wayland::{
clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},
cursor::Cursor,
@@ -96,12 +99,13 @@ use crate::linux::{
xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
};
use gpui::{
- AnyWindowHandle, Bounds, Capslock, CursorStyle, DevicePixels, DisplayId, ExternalDragPayload,
- FileDragPaths, FileDropEvent, ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke,
- Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent,
- MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay, PlatformFrameSignal, PlatformInput,
- PlatformKeyboardLayout, PlatformWindow, Point, ScrollDelta, ScrollWheelEvent, SharedString,
- Size, TouchPhase, WindowButtonLayout, WindowKind, WindowParams, point, profiler, px, size,
+ AnyWindowHandle, Bounds, Capslock, CursorStyle, DevicePixels, ExternalDragPayload,
+ FileDragPaths, FileDropEvent, ForegroundExecutor, GraphicalEnvironment, KeyDownEvent,
+ KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
+ MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformDisplay,
+ PlatformFrameSignal, PlatformInput, PlatformKeyboardLayout, PlatformWindow, Point, ScrollDelta,
+ ScrollWheelEvent, SharedString, Size, TouchPhase, WindowButtonLayout, WindowKind, WindowParams,
+ point, px, size,
};
use gpui_wgpu::{CompositorGpuHint, GpuContext};
use wayland_protocols::wp::linux_dmabuf::zv1::client::{
@@ -192,16 +196,44 @@ fn set_ime_cursor_rectangle_after_done(
/// failed-present frames, so matching the output's actual refresh rate wouldn't be observable.
const FRAME_RETRY_INTERVAL: Duration = Duration::from_micros(16_667);
-fn take_startup_activation_token_from_environment() -> Option<String> {
- let startup_activation_token = std::env::var(XDG_ACTIVATION_TOKEN_ENV_VAR)
+pub(crate) fn take_startup_activation_token_from_environment() -> Option<String> {
+ let token = std::env::var(XDG_ACTIVATION_TOKEN_ENV_VAR)
.ok()
.filter(|token| !token.is_empty());
- // The token must be removed from the environment so it isn't inherited by child
- // processes we spawn, per the xdg-activation spec: https://wayland.app/protocols/xdg-activation-v1
- // SAFETY: This runs during Wayland platform initialization before GPUI starts
- // concurrent environment access or spawning child processes.
+ // Per the xdg-activation spec, so that programs we launch don't inherit the token.
+ // SAFETY: `LinuxPlatform::new` calls this before it starts any threads.
unsafe { std::env::remove_var(XDG_ACTIVATION_TOKEN_ENV_VAR) };
- startup_activation_token
+ token
+}
+
+/// Takes the Wayland connection that `WAYLAND_SOCKET` hands to this process, as libwayland does.
+pub(crate) fn take_wayland_socket_from_environment() -> Option<UnixStream> {
+ const WAYLAND_SOCKET_ENV_VAR: &str = "WAYLAND_SOCKET";
+ let value = std::env::var_os(WAYLAND_SOCKET_ENV_VAR)?;
+ // Removed so that programs we launch don't inherit it, as libwayland does.
+ // SAFETY: `LinuxPlatform::new` calls this before it starts any threads.
+ unsafe { std::env::remove_var(WAYLAND_SOCKET_ENV_VAR) };
+ let Some(fd) = value
+ .to_str()
+ .and_then(|value| value.parse::<RawFd>().ok())
+ .filter(|fd| *fd >= 0)
+ else {
+ log::error!("ignoring WAYLAND_SOCKET={value:?}, which is not a file descriptor");
+ return None;
+ };
+ // SAFETY: the process that started us passes this descriptor for us to own. It is inherited
+ // across exec, so mark it close-on-exec to keep it from programs we launch.
+ unsafe {
+ let flags = libc::fcntl(fd, libc::F_GETFD);
+ if flags == -1 || libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) == -1 {
+ log::error!(
+ "ignoring WAYLAND_SOCKET={fd}: {}",
+ std::io::Error::last_os_error()
+ );
+ return None;
+ }
+ Some(UnixStream::from_raw_fd(fd))
+ }
}
#[derive(Clone)]
@@ -237,9 +269,9 @@ impl Globals {
qh: QueueHandle<WaylandClientStatePtr>,
seat: wl_seat::WlSeat,
frame_ping: Ping,
- ) -> Self {
+ ) -> anyhow::Result<Self> {
let dialog_v = XdgWmDialogV1::interface().version;
- Globals {
+ Ok(Globals {
activation: globals.bind(&qh, 1..=1, ()).ok(),
compositor: globals
.bind(
@@ -248,7 +280,7 @@ impl Globals {
..=wl_surface::EVT_PREFERRED_BUFFER_SCALE_SINCE,
(),
)
- .unwrap(),
+ .context("Wayland compositor does not provide a compatible wl_compositor")?,
cursor_shape_manager: globals.bind(&qh, 1..=1, ()).ok(),
data_device_manager: globals
.bind(
@@ -258,11 +290,15 @@ impl Globals {
)
.ok(),
primary_selection_manager: globals.bind(&qh, 1..=1, ()).ok(),
- shm: globals.bind(&qh, 1..=1, ()).unwrap(),
+ shm: globals
+ .bind(&qh, 1..=1, ())
+ .context("Wayland compositor does not provide wl_shm")?,
seat,
// Accept any xdg_wm_base version up to 6, which added the `suspended`
// toplevel state; older compositors bind at their own version.
- wm_base: globals.bind(&qh, 1..=6, ()).unwrap(),
+ wm_base: globals
+ .bind(&qh, 1..=6, ())
+ .context("Wayland compositor does not provide xdg_wm_base")?,
viewporter: globals.bind(&qh, 1..=1, ()).ok(),
fractional_scale_manager: globals.bind(&qh, 1..=1, ()).ok(),
decoration_manager: globals.bind(&qh, 1..=1, ()).ok(),
@@ -275,7 +311,7 @@ impl Globals {
executor,
qh,
frame_ping,
- }
+ })
}
}
@@ -356,7 +392,7 @@ pub(crate) struct WaylandClientState {
button_pressed: Option<MouseButton>,
mouse_focused_window: Option<WaylandWindowStatePtr>,
keyboard_focused_window: Option<WaylandWindowStatePtr>,
- loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
+ loop_handle: LoopHandle<'static, ()>,
cursor_style: Option<CursorStyle>,
cursor_hidden_window: Option<WaylandWindowStatePtr>,
clipboard: Clipboard,
@@ -365,8 +401,11 @@ pub(crate) struct WaylandClientState {
cursor: Cursor,
pending_activation: Option<PendingActivation>,
startup_activation_token: Option<String>,
- event_loop: Option<EventLoop<'static, WaylandClientStatePtr>>,
- pub common: LinuxCommon,
+ /// The environment this connection was made in, without its activation token.
+ graphical_environment: GraphicalEnvironment,
+ /// Long-lived sources this client registered on the loop, removed when it drops.
+ registrations: Vec<RegistrationToken>,
+ pub common: Rc<RefCell<LinuxCommon>>,
ime_enabled: Option<bool>,
}
@@ -532,6 +571,11 @@ impl WaylandClientStatePtr {
.expect("The pointer should always be valid when dispatching in wayland")
}
+ /// Returns the client, or `None` if it was dropped, for example by a switch to headless mode.
+ pub fn try_get_client(&self) -> Option<Rc<RefCell<WaylandClientState>>> {
+ self.0.upgrade()
+ }
+
pub fn dispatch_scheduled_frames(&self) {
let Some(client) = self.0.upgrade() else {
return;
@@ -556,10 +600,13 @@ impl WaylandClientStatePtr {
let client = self.get_client();
let state = client.borrow();
let surface_id = surface_id.clone();
+ let this = self.clone();
if let Err(err) = state.loop_handle.insert_source(
Timer::from_duration(FRAME_RETRY_INTERVAL),
- move |deadline, _, this| {
- let client = this.get_client();
+ move |deadline, _, _| {
+ let Some(client) = this.0.upgrade() else {
+ return TimeoutAction::Drop;
+ };
let window = get_window(&mut client.borrow_mut(), &surface_id);
if let Some(window) = window {
window.retry_timer_fired(deadline);
@@ -694,12 +741,21 @@ impl WaylandClientStatePtr {
changed
};
- if changed && let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take()
- {
+ let callback = changed
+ .then(|| {
+ state
+ .common
+ .borrow_mut()
+ .callbacks
+ .keyboard_layout_change
+ .take()
+ })
+ .flatten();
+ if let Some(mut callback) = callback {
drop(state);
callback();
state = client.borrow_mut();
- state.common.callbacks.keyboard_layout_change = Some(callback);
+ state.common.borrow_mut().callbacks.keyboard_layout_change = Some(callback);
}
}
@@ -779,11 +835,24 @@ impl WaylandClientState {
}
}
-#[derive(Clone)]
-pub struct WaylandClient(Rc<RefCell<WaylandClientState>>);
+/// A connection to the Wayland compositor.
+///
+/// Not `Clone`: dropping it tears down the connection and its event-loop sources.
+pub struct WaylandConnection(Rc<RefCell<WaylandClientState>>);
-impl Drop for WaylandClient {
+impl Drop for WaylandConnection {
fn drop(&mut self) {
+ let (loop_handle, registrations) = {
+ let mut state = self.0.borrow_mut();
+ (
+ state.loop_handle.clone(),
+ std::mem::take(&mut state.registrations),
+ )
+ };
+ for token in registrations {
+ loop_handle.remove(token);
+ }
+
let mut state = self.0.borrow_mut();
state.windows.clear();
@@ -804,41 +873,87 @@ impl Drop for WaylandClient {
const WL_DATA_DEVICE_MANAGER_VERSION: u32 = 3;
-fn wl_seat_version(version: u32) -> u32 {
+/// Returns the path of the socket that `WAYLAND_DISPLAY` names, as libwayland resolves it.
+fn wayland_socket_path(environment: &GraphicalEnvironment) -> anyhow::Result<PathBuf> {
+ let display = environment
+ .wayland_display
+ .as_ref()
+ .filter(|display| !display.is_empty())
+ .context("WAYLAND_DISPLAY is not set")?;
+ let display = PathBuf::from(display);
+ let socket_path = if display.is_absolute() {
+ display
+ } else {
+ let runtime_directory = environment
+ .xdg_runtime_dir
+ .as_ref()
+ .filter(|directory| !directory.is_empty())
+ .context("XDG_RUNTIME_DIR is not set")?;
+ PathBuf::from(runtime_directory).join(display)
+ };
+ Ok(socket_path)
+}
+
+fn wl_seat_version(version: u32) -> anyhow::Result<u32> {
// We rely on the wl_pointer.frame event
const WL_SEAT_MIN_VERSION: u32 = 5;
const WL_SEAT_MAX_VERSION: u32 = 9;
if version < WL_SEAT_MIN_VERSION {
- panic!(
+ anyhow::bail!(
"wl_seat below required version: {} < {}",
- version, WL_SEAT_MIN_VERSION
+ version,
+ WL_SEAT_MIN_VERSION
);
}
- version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION)
+ Ok(version.clamp(WL_SEAT_MIN_VERSION, WL_SEAT_MAX_VERSION))
}
-fn wl_output_version(version: u32) -> u32 {
+fn wl_output_version(version: u32) -> anyhow::Result<u32> {
const WL_OUTPUT_MIN_VERSION: u32 = 2;
const WL_OUTPUT_MAX_VERSION: u32 = 4;
if version < WL_OUTPUT_MIN_VERSION {
- panic!(
+ anyhow::bail!(
"wl_output below required version: {} < {}",
- version, WL_OUTPUT_MIN_VERSION
+ version,
+ WL_OUTPUT_MIN_VERSION
);
}
- version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION)
-}
-
-impl WaylandClient {
- pub(crate) fn new() -> Self {
- let startup_activation_token = take_startup_activation_token_from_environment();
- let conn = Connection::connect_to_env().unwrap();
-
- let (globals, event_queue) = registry_queue_init::<WaylandClientStatePtr>(&conn).unwrap();
+ Ok(version.clamp(WL_OUTPUT_MIN_VERSION, WL_OUTPUT_MAX_VERSION))
+}
+
+impl WaylandConnection {
+ /// Connects to the Wayland compositor `environment` names, or through `inherited_socket` when
+ /// given, and registers its event sources on `handle`.
+ ///
+ /// Dropping the connection removes its sources, leaving the loop and `common` usable without
+ /// Wayland.
+ pub(crate) fn attach(
+ handle: LoopHandle<'static, ()>,
+ common: Rc<RefCell<LinuxCommon>>,
+ environment: &GraphicalEnvironment,
+ inherited_socket: Option<UnixStream>,
+ activation_token: Option<String>,
+ ) -> anyhow::Result<Self> {
+ let stream = match inherited_socket {
+ Some(stream) => stream,
+ None => {
+ let socket_path = wayland_socket_path(environment)?;
+ UnixStream::connect(&socket_path).with_context(|| {
+ format!(
+ "failed to connect to Wayland compositor at {}",
+ socket_path.display()
+ )
+ })?
+ }
+ };
+ let conn =
+ Connection::from_socket(stream).context("failed to connect to Wayland compositor")?;
+ let (globals, event_queue) = registry_queue_init::<WaylandClientStatePtr>(&conn)
+ .context("failed to initialize Wayland registry")?;
let qh = event_queue.handle();
let mut seat: Option<wl_seat::WlSeat> = None;
@@ -846,13 +961,13 @@ impl WaylandClient {
let mut in_progress_outputs = HashMap::default();
#[allow(clippy::mutable_key_type)]
let mut wl_outputs: HashMap<ObjectId, wl_output::WlOutput> = HashMap::default();
- globals.contents().with_list(|list| {
+ globals.contents().with_list(|list| -> anyhow::Result<()> {
for global in list {
match &global.interface[..] {
"wl_seat" => {
seat = Some(globals.registry().bind::<wl_seat::WlSeat, _, _>(
global.name,
- wl_seat_version(global.version),
+ wl_seat_version(global.version)?,
&qh,
(),
));
@@ -860,7 +975,7 @@ impl WaylandClient {
"wl_output" => {
let output = globals.registry().bind::<wl_output::WlOutput, _, _>(
global.name,
- wl_output_version(global.version),
+ wl_output_version(global.version)?,
&qh,
(),
);
@@ -870,64 +985,25 @@ impl WaylandClient {
_ => {}
}
}
- });
-
- let event_loop = EventLoop::<WaylandClientStatePtr>::try_new().unwrap();
-
- let (common, main_receiver, power_receiver) = LinuxCommon::new(event_loop.get_signal());
-
- let handle = event_loop.handle();
- handle
- .insert_source(main_receiver, {
- let handle = handle.clone();
- move |event, _, _: &mut WaylandClientStatePtr| {
- if let calloop::channel::Event::Msg(runnable) = event {
- handle.insert_idle(|_| {
- let location = runnable.metadata().location;
- let spawned = runnable.metadata().spawned;
- profiler::update_running_task(spawned, location);
- runnable.run();
- profiler::save_task_timing();
- });
- }
- }
- })
- .unwrap();
-
- handle
- .insert_source(
- power_receiver,
- |event, _, client: &mut WaylandClientStatePtr| {
- if let calloop::channel::Event::Msg(event) = event {
- client
- .get_client()
- .borrow_mut()
- .common
- .handle_system_power_event(event);
- }
- },
- )
- .unwrap();
+ Ok(())
+ })?;
let compositor_gpu = detect_compositor_gpu();
let gpu_context = Rc::new(RefCell::new(None));
let (frame_ping, frame_ping_source) =
- calloop::ping::make_ping().expect("Failed to create the frame ping");
- handle
- .insert_source(frame_ping_source, |_, _, client| {
- client.dispatch_scheduled_frames();
- })
- .unwrap();
-
- let seat = seat.unwrap();
+ calloop::ping::make_ping().context("failed to create Wayland frame ping")?;
+ let seat = seat.context("Wayland compositor does not provide wl_seat")?;
+ let foreground_executor = common.borrow().foreground_executor.clone();
+ let background_executor = common.borrow().background_executor.clone();
let globals = Globals::new(
globals,
- common.foreground_executor.clone(),
+ foreground_executor,
qh.clone(),
seat.clone(),
frame_ping,
- );
+ )
+ .context("failed to bind required Wayland globals")?;
let data_device = globals
.data_device_manager
@@ -941,49 +1017,6 @@ impl WaylandClient {
let cursor = Cursor::new(&conn, &globals, 24);
- handle
- .insert_source(XDPEventSource::new(&common.background_executor), {
- move |event, _, client| match event {
- XDPEvent::WindowAppearance(appearance) => {
- if let Some(client) = client.0.upgrade() {
- let mut client = client.borrow_mut();
-
- client.common.appearance = appearance;
-
- for window in client.windows.values_mut() {
- window.set_appearance(appearance);
- }
- }
- }
- XDPEvent::ButtonLayout(layout_str) => {
- if let Some(client) = client.0.upgrade() {
- let layout = WindowButtonLayout::parse(&layout_str)
- .log_err()
- .unwrap_or_else(WindowButtonLayout::linux_default);
- let mut client = client.borrow_mut();
- client.common.button_layout = layout;
-
- for window in client.windows.values_mut() {
- window.set_button_layout();
- }
- }
- }
- XDPEvent::CursorTheme(theme) => {
- if let Some(client) = client.0.upgrade() {
- let mut client = client.borrow_mut();
- client.cursor.set_theme(theme);
- }
- }
- XDPEvent::CursorSize(size) => {
- if let Some(client) = client.0.upgrade() {
- let mut client = client.borrow_mut();
- client.cursor.set_size(size);
- }
- }
- }
- })
- .unwrap();
-
let state = Rc::new(RefCell::new(WaylandClientState {
serial_tracker: SerialTracker::new(),
globals,
@@ -1056,25 +1089,108 @@ impl WaylandClient {
primary_data_offer: None,
cursor,
pending_activation: None,
- startup_activation_token,
- event_loop: Some(event_loop),
+ startup_activation_token: activation_token,
+ graphical_environment: GraphicalEnvironment {
+ activation_token: None,
+ ..environment.clone()
+ },
+ registrations: Vec::new(),
ime_enabled: None,
}));
- WaylandSource::new(conn, event_queue)
- .insert(handle)
- .unwrap();
+ // From here on, `Drop` removes whatever was registered if a later step fails.
+ let client = Self(state);
+ let pointer = WaylandClientStatePtr(Rc::downgrade(&client.0));
- Self(state)
+ client.register_source(
+ handle.insert_source(frame_ping_source, {
+ let client = pointer.clone();
+ move |_, _, _| client.dispatch_scheduled_frames()
+ }),
+ "failed to register Wayland frame source",
+ )?;
+
+ client.register_source(
+ handle.insert_source(XDPEventSource::new(&background_executor), {
+ let client = pointer.clone();
+ move |event, _, _| match event {
+ XDPEvent::WindowAppearance(appearance) => {
+ if let Some(client) = client.0.upgrade() {
+ let mut client = client.borrow_mut();
+
+ client.common.borrow_mut().appearance = appearance;
+
+ for window in client.windows.values_mut() {
+ window.set_appearance(appearance);
+ }
+ }
+ }
+ XDPEvent::ButtonLayout(layout_str) => {
+ if let Some(client) = client.0.upgrade() {
+ let layout = WindowButtonLayout::parse(&layout_str)
+ .log_err()
+ .unwrap_or_else(WindowButtonLayout::linux_default);
+ let mut client = client.borrow_mut();
+ client.common.borrow_mut().button_layout = layout;
+
+ for window in client.windows.values_mut() {
+ window.set_button_layout();
+ }
+ }
+ }
+ XDPEvent::CursorTheme(theme) => {
+ if let Some(client) = client.0.upgrade() {
+ let mut client = client.borrow_mut();
+ client.cursor.set_theme(theme);
+ }
+ }
+ XDPEvent::CursorSize(size) => {
+ if let Some(client) = client.0.upgrade() {
+ let mut client = client.borrow_mut();
+ client.cursor.set_size(size);
+ }
+ }
+ }
+ }),
+ "failed to register desktop portal source",
+ )?;
+
+ client.register_source(
+ handle.insert_source(WaylandSource::new(conn, event_queue), {
+ let mut client = pointer;
+ move |_, queue, _| queue.dispatch_pending(&mut client)
+ }),
+ "failed to register Wayland connection source",
+ )?;
+
+ Ok(client)
+ }
+
+ fn register_source<E: std::fmt::Display>(
+ &self,
+ result: Result<RegistrationToken, E>,
+ description: &str,
+ ) -> anyhow::Result<()> {
+ let token = result.map_err(|error| anyhow::anyhow!("{description}: {error}"))?;
+ self.0.borrow_mut().registrations.push(token);
+ Ok(())
+ }
+
+ pub(crate) fn has_windows(&self) -> bool {
+ !self.0.borrow().windows.is_empty()
+ }
+
+ pub(crate) fn graphical_environment(&self) -> GraphicalEnvironment {
+ self.0.borrow().graphical_environment.clone()
}
}
-impl LinuxClient for WaylandClient {
- fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
+impl WaylandConnection {
+ pub(crate) fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
Box::new(self.0.borrow().keyboard_layout.clone())
}
- fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
+ pub(crate) fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
self.0
.borrow()
.outputs
@@ -1089,28 +1205,17 @@ impl LinuxClient for WaylandClient {
.collect()
}
- fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
- self.0
- .borrow()
- .outputs
- .iter()
- .find_map(|(object_id, output)| {
- (object_id.protocol_id() as u64 == u64::from(id)).then(|| {
- Rc::new(WaylandDisplay {
- id: object_id.clone(),
- name: output.name.clone(),
- bounds: output.bounds.to_pixels(output.scale as f32),
- }) as Rc<dyn PlatformDisplay>
- })
- })
+ pub(crate) fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
+ None
}
- fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
- None
+ #[cfg(feature = "screen-capture")]
+ pub(crate) fn is_screen_capture_supported(&self) -> bool {
+ true
}
#[cfg(feature = "screen-capture")]
- fn screen_capture_sources(
+ pub(crate) fn screen_capture_sources(
&self,
) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
{
@@ -1127,7 +1232,7 @@ impl LinuxClient for WaylandClient {
sources_rx
}
- fn open_window(
+ pub(crate) fn open_window(
&self,
handle: AnyWindowHandle,
params: WindowParams,
@@ -1168,7 +1273,7 @@ impl LinuxClient for WaylandClient {
.map(|(_, output)| output.clone())
});
- let appearance = state.common.appearance;
+ let appearance = state.common.borrow().appearance;
let compositor_gpu = state.compositor_gpu.take();
let (window, surface_id) = WaylandWindow::new(
@@ -1192,7 +1297,7 @@ impl LinuxClient for WaylandClient {
Ok(Box::new(window))
}
- fn set_cursor_style(&self, style: CursorStyle) {
+ pub(crate) fn set_cursor_style(&self, style: CursorStyle) {
let mut state = self.0.borrow_mut();
let need_update = state.cursor_style != Some(style)
@@ -1232,15 +1337,15 @@ impl LinuxClient for WaylandClient {
}
}
- fn hide_cursor_until_mouse_moves(&self) {
+ pub(crate) fn hide_cursor_until_mouse_moves(&self) {
self.0.borrow_mut().hide_cursor_until_mouse_moves();
}
- fn is_cursor_visible(&self) -> bool {
+ pub(crate) fn is_cursor_visible(&self) -> bool {
self.0.borrow().cursor_hidden_window.is_none()
}
- fn open_uri(&self, uri: &str) {
+ pub(crate) fn open_uri(&self, uri: &str) {
let mut state = self.0.borrow_mut();
if let (Some(activation), Some(window)) = (
state.globals.activation.clone(),
@@ -1253,12 +1358,12 @@ impl LinuxClient for WaylandClient {
token.set_surface(&window.surface());
token.commit();
} else {
- let executor = state.common.background_executor.clone();
- open_uri_internal(executor, uri, None);
+ let executor = state.common.borrow().background_executor.clone();
+ open_uri_internal(executor, uri, None, state.graphical_environment.clone());
}
}
- fn reveal_path(&self, path: PathBuf) {
+ pub(crate) fn reveal_path(&self, path: PathBuf) {
let mut state = self.0.borrow_mut();
if let (Some(activation), Some(window)) = (
state.globals.activation.clone(),
@@ -1271,33 +1376,12 @@ impl LinuxClient for WaylandClient {
token.set_surface(&window.surface());
token.commit();
} else {
- let executor = state.common.background_executor.clone();
- reveal_path_internal(executor, path, None);
+ let executor = state.common.borrow().background_executor.clone();
+ reveal_path_internal(executor, path, None, state.graphical_environment.clone());
}
}
- fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
- f(&mut self.0.borrow_mut().common)
- }
-
- fn run(&self) {
- let mut event_loop = self
- .0
- .borrow_mut()
- .event_loop
- .take()
- .expect("App is already running");
-
- event_loop
- .run(
- None,
- &mut WaylandClientStatePtr(Rc::downgrade(&self.0)),
- |_| {},
- )
- .log_err();
- }
-
- fn write_to_primary(&self, item: gpui::ClipboardItem) {
+ pub(crate) fn write_to_primary(&self, item: gpui::ClipboardItem) {
let mut state = self.0.borrow_mut();
let (Some(primary_selection_manager), Some(primary_selection)) = (
state.globals.primary_selection_manager.clone(),
@@ -1322,7 +1406,7 @@ impl LinuxClient for WaylandClient {
}
}
- fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
+ pub(crate) fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
let mut state = self.0.borrow_mut();
let (Some(data_device_manager), Some(data_device)) = (
state.globals.data_device_manager.clone(),
@@ -1348,15 +1432,15 @@ impl LinuxClient for WaylandClient {
}
}
- fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
+ pub(crate) fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
self.0.borrow_mut().clipboard.read_primary()
}
- fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
+ pub(crate) fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
self.0.borrow_mut().clipboard.read()
}
- fn active_window(&self) -> Option<AnyWindowHandle> {
+ pub(crate) fn active_window(&self) -> Option<AnyWindowHandle> {
self.0
.borrow_mut()
.keyboard_focused_window
@@ -1364,15 +1448,17 @@ impl LinuxClient for WaylandClient {
.map(|window| window.handle())
}
- fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
+ pub(crate) fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
None
}
- fn compositor_name(&self) -> &'static str {
+ pub(crate) fn compositor_name(&self) -> &'static str {
"Wayland"
}
- fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
+ pub(crate) fn window_identifier(
+ &self,
+ ) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
async fn inner(surface: Option<wl_surface::WlSurface>) -> Option<WindowIdentifier> {
if let Some(surface) = surface {
ashpd::WindowIdentifier::from_wayland(&surface).await
@@ -1470,6 +1556,10 @@ impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStat
version,
} => match &interface[..] {
"wl_seat" => {
+ let Ok(version) = wl_seat_version(version) else {
+ log::error!("ignoring wl_seat below the required version");
+ return;
+ };
if let Some(wl_pointer) = state.wl_pointer.take() {
wl_pointer.release();
}
@@ -1477,20 +1567,14 @@ impl Dispatch<wl_registry::WlRegistry, GlobalListContents> for WaylandClientStat
wl_keyboard.release();
}
state.wl_seat.release();
- state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(
- name,
- wl_seat_version(version),
- qh,
- (),
- );
+ state.wl_seat = registry.bind::<wl_seat::WlSeat, _, _>(name, version, qh, ());
}
"wl_output" => {
- let output = registry.bind::<wl_output::WlOutput, _, _>(
- name,
- wl_output_version(version),
- qh,
- (),
- );
+ let Ok(version) = wl_output_version(version) else {
+ log::error!("ignoring wl_output below the required version");
+ return;
+ };
+ let output = registry.bind::<wl_output::WlOutput, _, _>(name, version, qh, ());
state
.in_progress_outputs
@@ -1780,11 +1864,14 @@ impl Dispatch<xdg_activation_token_v1::XdgActivationTokenV1, ()> for WaylandClie
let mut state = client.borrow_mut();
if let xdg_activation_token_v1::Event::Done { token } = event {
- let executor = state.common.background_executor.clone();
+ let executor = state.common.borrow().background_executor.clone();
+ let environment = state.graphical_environment.clone();
match state.pending_activation.take() {
- Some(PendingActivation::Uri(uri)) => open_uri_internal(executor, &uri, Some(token)),
+ Some(PendingActivation::Uri(uri)) => {
+ open_uri_internal(executor, &uri, Some(token), environment)
+ }
Some(PendingActivation::Path(path)) => {
- reveal_path_internal(executor, path, Some(token))
+ reveal_path_internal(executor, path, Some(token), environment)
}
Some(PendingActivation::Window(window)) => {
let Some(window) = get_window(&mut state, &window) else {
@@ -2058,8 +2145,11 @@ impl Dispatch<wl_keyboard::WlKeyboard, ()> for WaylandClientStatePtr {
is_held: true,
prefer_character_input: false,
});
- move |event_timestamp, _metadata, this| {
- let client = this.get_client();
+ let this = this.clone();
+ move |event_timestamp, _metadata, _| {
+ let Some(client) = this.0.upgrade() else {
+ return TimeoutAction::Drop;
+ };
let state = client.borrow();
let is_repeating = id == state.repeat.current_id
&& state.repeat.current_keycode.is_some()
@@ -2734,7 +2824,7 @@ impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
let fd = pipe.read;
drop(pipe.write);
- let read_task = state.common.background_executor.spawn(async {
+ let read_task = state.common.borrow().background_executor.spawn(async {
let buffer = read_fd_with_timeout(fd, PIPE_READ_TIMEOUT)?;
let text = String::from_utf8(buffer)?;
anyhow::Ok(text)
@@ -2743,7 +2833,9 @@ impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
let this = this.clone();
state
.common
+ .borrow()
.foreground_executor
+ .clone()
.spawn(async move {
let file_list = match read_task.await {
Ok(list) => list,
@@ -2771,7 +2863,10 @@ impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {
data_offer.destroy();
return;
}
- let client = this.get_client();
+ let Some(client) = this.0.upgrade() else {
+ data_offer.destroy();
+ return;
+ };
let mut state = client.borrow_mut();
let input = state.drag.complete_uri_read(
uri_read_generation,
@@ -3015,6 +3110,14 @@ mod tests {
use super::*;
+ #[test]
+ fn rejects_required_globals_below_supported_versions() {
+ assert!(wl_seat_version(4).is_err());
+ assert!(wl_output_version(1).is_err());
+ assert_eq!(wl_seat_version(5).expect("minimum seat version"), 5);
+ assert_eq!(wl_output_version(2).expect("minimum output version"), 2);
+ }
+
#[test]
fn frame_callback_timestamp_preserves_queue_delay() {
let received_at = Instant::now();
diff --git a/crates/gpui_linux/src/linux/wayland/clipboard.rs b/crates/gpui_linux/src/linux/wayland/clipboard.rs
index 57ecd9345bf..86dc7da97b9 100644
--- a/crates/gpui_linux/src/linux/wayland/clipboard.rs
+++ b/crates/gpui_linux/src/linux/wayland/clipboard.rs
@@ -10,10 +10,7 @@ use strum::IntoEnumIterator;
use wayland_client::{Connection, protocol::wl_data_offer::WlDataOffer};
use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1;
-use crate::linux::{
- WaylandClientStatePtr,
- platform::{PIPE_READ_TIMEOUT, read_fd_with_timeout},
-};
+use crate::linux::platform::{PIPE_READ_TIMEOUT, read_fd_with_timeout};
use gpui::{ClipboardEntry, ClipboardItem, Image, ImageFormat, hash};
/// Text mime types that we'll offer to other programs.
@@ -26,7 +23,7 @@ pub(crate) const ALLOWED_TEXT_MIME_TYPES: [&str; 2] = ["text/plain;charset=utf-8
pub(crate) struct Clipboard {
connection: Connection,
- loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
+ loop_handle: LoopHandle<'static, ()>,
self_mime: String,
// Internal clipboard
@@ -139,10 +136,7 @@ impl<T: ReceiveData> DataOffer<T> {
}
impl Clipboard {
- pub fn new(
- connection: Connection,
- loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
- ) -> Self {
+ pub fn new(connection: Connection, loop_handle: LoopHandle<'static, ()>) -> Self {
Self {
connection,
loop_handle,
diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs
index 7362c1f75e2..be447f84444 100644
--- a/crates/gpui_linux/src/linux/wayland/window.rs
+++ b/crates/gpui_linux/src/linux/wayland/window.rs
@@ -112,7 +112,9 @@ pub struct WaylandWindowState {
outputs: HashMap<ObjectId, Output>,
display: Option<(ObjectId, Output)>,
globals: Globals,
- renderer: WgpuRenderer,
+ /// Taken when the window is dropped. Its GPU objects use the Wayland connection, so they
+ /// mustn't outlive the window, which a display mode switch relies on.
+ renderer: Option<WgpuRenderer>,
bounds: Bounds<Pixels>,
scale: f32,
input_handler: Option<PlatformInputHandler>,
@@ -612,7 +614,7 @@ impl WaylandWindowState {
globals,
outputs: HashMap::default(),
display: None,
- renderer,
+ renderer: Some(renderer),
bounds: options.bounds,
scale: 1.0,
input_handler: None,
@@ -652,7 +654,9 @@ impl WaylandWindowState {
.as_ref()
.and_then(|(_, output)| output.subpixel)
.is_some_and(|s| s == Subpixel::HorizontalBgr);
- self.renderer.set_subpixel_layout(is_bgr);
+ if let Some(renderer) = &mut self.renderer {
+ renderer.set_subpixel_layout(is_bgr);
+ }
}
pub fn primary_output_scale(&mut self) -> i32 {
@@ -770,7 +774,7 @@ impl Drop for WaylandWindow {
let client = state.client.clone();
- state.renderer.destroy();
+ state.renderer.take();
// Destroy blur first, this has no dependencies.
if let Some(blur) = &state.blur {
@@ -796,13 +800,13 @@ impl Drop for WaylandWindow {
// The wl_surface itself should always be destroyed last.
state.surface.destroy();
+ client.drop_window(&surface_id);
let state_ptr = self.0.clone();
state
.globals
.executor
.spawn(async move {
state_ptr.close();
- client.drop_window(&surface_id)
})
.detach();
drop(state);
@@ -1497,7 +1501,9 @@ impl WaylandWindowStatePtr {
state.scale = scale;
}
let device_bounds = state.bounds.to_device_pixels(state.scale);
- state.renderer.update_drawable_size(device_bounds.size);
+ if let Some(renderer) = &mut state.renderer {
+ renderer.update_drawable_size(device_bounds.size);
+ }
(state.bounds.size, state.scale)
};
@@ -1526,17 +1532,21 @@ impl WaylandWindowStatePtr {
pub fn close(&self) {
let state = self.state.borrow();
- let client = state.client.get_client();
+ // Closing is deferred to a task, which can run after the client is dropped by a switch to
+ // headless mode. The client's window map, and so any child window, is gone with it.
+ let client = state.client.try_get_client();
let children = state.children.keys().cloned().collect::<Vec<_>>();
drop(state);
- for child in children {
- let mut client_state = client.borrow_mut();
- let window = get_window(&mut client_state, &child);
- drop(client_state);
+ if let Some(client) = client {
+ for child in children {
+ let mut client_state = client.borrow_mut();
+ let window = get_window(&mut client_state, &child);
+ drop(client_state);
- if let Some(child) = window {
- child.close();
+ if let Some(child) = window {
+ child.close();
+ }
}
}
let mut callbacks = self.callbacks.borrow_mut();
@@ -1950,8 +1960,12 @@ impl PlatformWindow for WaylandWindow {
fn draw(&self, scene: &Scene) {
let mut state = self.borrow_mut();
+ let state = &mut *state;
+ let Some(renderer) = &mut state.renderer else {
+ return;
+ };
- if state.renderer.device_lost() {
+ if renderer.device_lost() {
let raw_window = RawWindow {
window: state.surface.id().as_ptr().cast::<std::ffi::c_void>(),
display: state
@@ -1962,7 +1976,7 @@ impl PlatformWindow for WaylandWindow {
.display_ptr()
.cast::<std::ffi::c_void>(),
};
- match state.renderer.recover(&raw_window) {
+ match renderer.recover(&raw_window) {
Ok(()) => {}
Err(err) => {
log::warn!("GPU recovery failed, will retry on next frame: {err}");
@@ -1979,7 +1993,7 @@ impl PlatformWindow for WaylandWindow {
let callback = state.surface.frame(&state.globals.qh, state.surface.id());
state.pending_frame_callback = Some(callback);
}
- if state.renderer.draw(scene) {
+ if renderer.draw(scene) {
state.presentation = PresentationState::Presented;
self.0.frame_loop.set(FrameLoop::AwaitingCallback);
} else {
@@ -1987,7 +2001,7 @@ impl PlatformWindow for WaylandWindow {
self.0.frame_loop.set(FrameLoop::PresentationFailed);
}
- if state.renderer.needs_redraw() {
+ if renderer.needs_redraw() {
state.redraw_requested = true;
}
}
@@ -1997,8 +2011,12 @@ impl PlatformWindow for WaylandWindow {
}
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
- let state = self.borrow();
- state.renderer.sprite_atlas().clone()
+ self.borrow()
+ .renderer
+ .as_ref()
+ .expect("the renderer is only taken when the window is dropped")
+ .sprite_atlas()
+ .clone()
}
fn show_window_menu(&self, position: Point<Pixels>) {
@@ -2148,7 +2166,7 @@ impl PlatformWindow for WaylandWindow {
}
fn gpu_specs(&self) -> Option<GpuSpecs> {
- self.borrow().renderer.gpu_specs()
+ self.borrow().renderer.as_ref()?.gpu_specs()
}
fn play_system_bell(&self) {
@@ -2221,7 +2239,9 @@ impl accesskit::DeactivationHandler for TrivialDeactivationHandler {
fn update_window(mut state: RefMut<WaylandWindowState>) {
let opaque = !state.is_transparent();
- state.renderer.update_transparency(!opaque);
+ if let Some(renderer) = &mut state.renderer {
+ renderer.update_transparency(!opaque);
+ }
let opaque_area = state.window_bounds.map(|v| f32::from(v) as i32);
opaque_area.inset(f32::from(state.inset()) as i32);
diff --git a/crates/gpui_linux/src/linux/x11.rs b/crates/gpui_linux/src/linux/x11.rs
index 5c7a0c2ac89..f9b97273309 100644
--- a/crates/gpui_linux/src/linux/x11.rs
+++ b/crates/gpui_linux/src/linux/x11.rs
@@ -6,6 +6,7 @@ mod window;
mod xim_handler;
pub(crate) use client::*;
+pub(crate) use clipboard::wait_for_clipboard_handovers;
pub(crate) use display::*;
pub(crate) use event::*;
pub(crate) use window::*;
diff --git a/crates/gpui_linux/src/linux/x11/client.rs b/crates/gpui_linux/src/linux/x11/client.rs
index f83172f95f1..601eb938df4 100644
--- a/crates/gpui_linux/src/linux/x11/client.rs
+++ b/crates/gpui_linux/src/linux/x11/client.rs
@@ -1,12 +1,12 @@
use anyhow::{Context as _, anyhow};
use ashpd::WindowIdentifier;
use calloop::{
- EventLoop, LoopHandle, RegistrationToken,
+ LoopHandle, RegistrationToken,
generic::{FdWrapper, Generic},
};
use collections::HashMap;
use core::str;
-use gpui::{Capslock, profiler};
+use gpui::{Capslock, GraphicalEnvironment};
use gpui_util::ResultExt as _;
use http_client::Url;
use log::Level;
@@ -49,10 +49,9 @@ use super::{
};
use crate::linux::{
- DEFAULT_CURSOR_ICON_NAME, LinuxClient, capslock_from_xkb, cursor_style_to_icon_names,
- get_xkb_compose_state, is_within_click_distance, keystroke_from_xkb,
- keystroke_underlying_dead_key, log_cursor_icon_warning, modifiers_from_xkb, new_xkb_context,
- open_uri_internal,
+ DEFAULT_CURSOR_ICON_NAME, capslock_from_xkb, cursor_style_to_icon_names, get_xkb_compose_state,
+ is_within_click_distance, keystroke_from_xkb, keystroke_underlying_dead_key,
+ log_cursor_icon_warning, modifiers_from_xkb, new_xkb_context, open_uri_internal,
platform::{DOUBLE_CLICK_INTERVAL, SCROLL_LINES},
reveal_path_internal,
xdg_desktop_portal::{Event as XDPEvent, XDPEventSource},
@@ -60,10 +59,10 @@ use crate::linux::{
use crate::linux::{LinuxCommon, LinuxKeyboardLayout, X11Window, modifiers_from_xinput_info};
use gpui::{
- AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, DisplayId, FileDropEvent,
- FrameRequestSource, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, Pixels,
- PlatformDisplay, PlatformFrameSignal, PlatformInput, PlatformKeyboardLayout, PlatformWindow,
- Point, RequestFrameOptions, ScrollDelta, Size, TouchPhase, WindowButtonLayout, WindowParams,
+ AnyWindowHandle, Bounds, ClipboardItem, CursorStyle, FileDropEvent, FrameRequestSource,
+ Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, Pixels, PlatformDisplay,
+ PlatformFrameSignal, PlatformInput, PlatformKeyboardLayout, PlatformWindow, Point,
+ RequestFrameOptions, ScrollDelta, Size, TouchPhase, WindowButtonLayout, WindowParams,
WindowVisibility, point, px,
};
use gpui_wgpu::{CompositorGpuHint, GpuContext};
@@ -181,8 +180,14 @@ struct ScrollAxisState {
}
pub struct X11ClientState {
- pub(crate) loop_handle: LoopHandle<'static, X11Client>,
- pub(crate) event_loop: Option<calloop::EventLoop<'static, X11Client>>,
+ /// A weak pointer to this state, for event-loop callbacks registered by its methods.
+ this: X11ClientStatePtr,
+ pub(crate) loop_handle: LoopHandle<'static, ()>,
+ /// Long-lived sources this client registered on the loop, removed when its
+ /// [`X11Connection`] drops.
+ registrations: Vec<RegistrationToken>,
+ /// The environment this connection was made in, without its activation token.
+ graphical_environment: GraphicalEnvironment,
pub(crate) last_click: Instant,
pub(crate) last_mouse_button: Option<MouseButton>,
@@ -230,7 +235,7 @@ pub struct X11ClientState {
pub(crate) supports_xinput_gestures: bool,
- pub(crate) common: LinuxCommon,
+ pub(crate) common: Rc<RefCell<LinuxCommon>>,
pub(crate) clipboard: Clipboard,
pub(crate) clipboard_item: Option<ClipboardItem>,
pub(crate) xdnd_state: Xdnd,
@@ -314,57 +319,68 @@ impl X11ClientStatePtr {
}
}
-#[derive(Clone)]
-pub(crate) struct X11Client(pub(crate) Rc<RefCell<X11ClientState>>);
+/// A connection to an X server.
+///
+/// Not `Clone`: dropping it removes the connection's event-loop sources and forgets its windows.
+/// The X connection itself closes once the last [`X11Client`] handle is gone.
+pub(crate) struct X11Connection(X11Client);
-impl X11Client {
- pub(crate) fn new() -> anyhow::Result<Self> {
- let event_loop = EventLoop::try_new()?;
-
- let (common, main_receiver, power_receiver) = LinuxCommon::new(event_loop.get_signal());
-
- let handle = event_loop.handle();
-
- handle
- .insert_source(main_receiver, {
- let handle = handle.clone();
- move |event, _, _: &mut X11Client| {
- if let calloop::channel::Event::Msg(runnable) = event {
- // Insert the runnables as idle callbacks, so we make sure that user-input and X11
- // events have higher priority and runnables are only worked off after the event
- // callbacks.
- handle.insert_idle(|client| {
- let location = runnable.metadata().location;
- let spawned = runnable.metadata().spawned;
- profiler::update_running_task(spawned, location);
- runnable.run();
- profiler::save_task_timing();
-
- let xcb_connection = client.0.borrow().xcb_connection.clone();
- client.process_x11_events(&xcb_connection).log_err();
- });
- }
- }
- })
- .map_err(|err| {
- anyhow!("Failed to initialize event loop handling of foreground tasks: {err:?}")
- })?;
-
- handle
- .insert_source(power_receiver, |event, _, client: &mut X11Client| {
- if let calloop::channel::Event::Msg(event) = event {
- client
- .0
- .borrow_mut()
- .common
- .handle_system_power_event(event);
- }
+impl std::ops::Deref for X11Connection {
+ type Target = X11Client;
+
+ fn deref(&self) -> &X11Client {
+ &self.0
+ }
+}
+
+impl Drop for X11Connection {
+ fn drop(&mut self) {
+ let mut state = self.0.0.borrow_mut();
+ state.common.borrow_mut().after_runnable = None;
+ for token in std::mem::take(&mut state.registrations) {
+ state.loop_handle.remove(token);
+ }
+ let refresh_tokens = state
+ .windows
+ .values_mut()
+ .filter_map(|window| match window.refresh_state.take() {
+ Some(RefreshState::PeriodicRefresh {
+ event_loop_token, ..
+ }) => Some(event_loop_token),
+ _ => None,
})
- .map_err(|err| {
- anyhow!("Failed to initialize event loop handling of sleep/wake events: {err:?}")
- })?;
+ .collect::<Vec<_>>();
+ for token in refresh_tokens {
+ state.loop_handle.remove(token);
+ }
+ let windows = std::mem::take(&mut state.windows);
+ drop(state);
+ drop(windows);
+ }
+}
- let (xcb_connection, x_root_index) = XCBConnection::connect(None)?;
+impl X11Connection {
+ /// Connects to the X server `environment` names and registers its event sources on
+ /// `handle`.
+ ///
+ /// Dropping the connection removes those sources, leaving the loop and `common` usable
+ /// without X11.
+ pub(crate) fn attach(
+ handle: LoopHandle<'static, ()>,
+ common: Rc<RefCell<LinuxCommon>>,
+ environment: &GraphicalEnvironment,
+ ) -> anyhow::Result<Self> {
+ let display = environment
+ .x11_display
+ .as_ref()
+ .filter(|display| !display.is_empty())
+ .context("DISPLAY is not set")?
+ .to_str()
+ .context("DISPLAY is not valid UTF-8")?;
+ let display_name =
+ std::ffi::CString::new(display).context("X display name contains a NUL byte")?;
+ let (xcb_connection, x_root_index) = XCBConnection::connect(Some(&display_name))
+ .with_context(|| format!("failed to connect to X server {display:?}"))?;
xcb_connection.prefetch_extension_information(xkb::X11_EXTENSION_NAME)?;
xcb_connection.prefetch_extension_information(randr::X11_EXTENSION_NAME)?;
xcb_connection.prefetch_extension_information(render::X11_EXTENSION_NAME)?;
@@ -378,7 +394,7 @@ impl X11Client {
|| "XInput XiQueryVersion failed",
xcb_connection.xinput_xi_query_version(2, 4),
)?;
- assert!(
+ anyhow::ensure!(
xinput_version.major_version >= 2,
"XInput version >= 2 required."
);
@@ -415,7 +431,7 @@ impl X11Client {
xcb_connection
.xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION),
)?;
- assert!(xkb.supported);
+ anyhow::ensure!(xkb.supported, "X server does not support XKB");
let events = xkb::EventType::STATE_NOTIFY
| xkb::EventType::MAP_NOTIFY
@@ -467,7 +483,7 @@ impl X11Client {
.reply()
.context("Failed to initialize cursor theme handler")?;
- let clipboard = Clipboard::new().context("Failed to initialize clipboard")?;
+ let clipboard = Clipboard::new(display).context("Failed to initialize clipboard")?;
let screen = &xcb_connection.setup().roots[x_root_index];
let compositor_gpu = detect_compositor_gpu(&xcb_connection, screen);
@@ -481,10 +497,88 @@ impl X11Client {
None
};
+ let background_executor = common.borrow().background_executor.clone();
+ let connection = X11Connection(X11Client(Rc::new_cyclic(|this| {
+ RefCell::new(X11ClientState {
+ this: X11ClientStatePtr(this.clone()),
+ registrations: Vec::new(),
+ graphical_environment: GraphicalEnvironment {
+ activation_token: None,
+ ..environment.clone()
+ },
+ modifiers: Modifiers::default(),
+ capslock: Capslock::default(),
+ last_modifiers_changed_event: Modifiers::default(),
+ last_capslock_changed_event: Capslock::default(),
+ loop_handle: handle.clone(),
+ common,
+ last_click: Instant::now(),
+ last_mouse_button: None,
+ last_location: Point::new(px(0.0), px(0.0)),
+ current_count: 0,
+ pinch_scale: 1.0,
+ gpu_context: Rc::new(RefCell::new(None)),
+ compositor_gpu,
+ scale_factor,
+
+ xkb_context,
+ xcb_connection,
+ xkb_device_id,
+ client_side_decorations_supported,
+ x_root_index,
+ resource_database,
+ atoms,
+ windows: HashMap::default(),
+ mouse_focused_window: None,
+ keyboard_focused_window: None,
+ xkb: xkb_state,
+ keyboard_layout,
+ ximc,
+ xim_handler,
+
+ compose_state,
+ pre_edit_text: None,
+ pre_key_char_down: None,
+ composing: false,
+
+ cursor_handle,
+ cursor_styles: HashMap::default(),
+ cursor_cache: HashMap::default(),
+ cursor_hidden_window: None,
+ invisible_cursor_cache: None,
+
+ pointer_device_states,
+
+ supports_xinput_gestures,
+
+ clipboard,
+ clipboard_item: None,
+ xdnd_state: Xdnd::default(),
+ })
+ })));
+ // From here on, `Drop` removes whatever was registered if a later step fails.
+ connection.register_sources(&handle, background_executor)?;
+ let xcb_connection = connection.0.0.borrow().xcb_connection.clone();
+ xcb_flush(&xcb_connection);
+ Ok(connection)
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct X11Client(pub(crate) Rc<RefCell<X11ClientState>>);
+
+impl X11Client {
+ fn register_sources(
+ &self,
+ handle: &LoopHandle<'static, ()>,
+ background_executor: gpui::BackgroundExecutor,
+ ) -> anyhow::Result<()> {
+ let this = self.0.borrow().this.clone();
+ let xcb_connection = self.0.borrow().xcb_connection.clone();
+
// Safety: Safe if xcb::Connection always returns a valid fd
let fd = unsafe { FdWrapper::new(Rc::clone(&xcb_connection)) };
-
- handle
+ let token = handle
.insert_source(
Generic::new_with_error::<EventHandlerError>(
fd,
@@ -492,93 +586,67 @@ impl X11Client {
calloop::Mode::Level,
),
{
+ let this = this.clone();
let xcb_connection = xcb_connection.clone();
- move |_readiness, _, client| {
- client.process_x11_events(&xcb_connection)?;
+ move |_readiness, _, _| {
+ if let Some(client) = this.get_client() {
+ client.process_x11_events(&xcb_connection)?;
+ }
Ok(calloop::PostAction::Continue)
}
},
)
.map_err(|err| anyhow!("Failed to initialize X11 event source: {err:?}"))?;
-
- handle
- .insert_source(XDPEventSource::new(&common.background_executor), {
- move |event, _, client| match event {
- XDPEvent::WindowAppearance(appearance) => {
- client.with_common(|common| common.appearance = appearance);
- for window in client.0.borrow_mut().windows.values_mut() {
- window.window.set_appearance(appearance);
+ self.0.borrow_mut().registrations.push(token);
+
+ let token = handle
+ .insert_source(XDPEventSource::new(&background_executor), {
+ let this = this.clone();
+ move |event, _, _| {
+ let Some(client) = this.get_client() else {
+ return;
+ };
+ match event {
+ XDPEvent::WindowAppearance(appearance) => {
+ client.with_common(|common| common.appearance = appearance);
+ for window in client.0.borrow_mut().windows.values_mut() {
+ window.window.set_appearance(appearance);
+ }
}
- }
- XDPEvent::ButtonLayout(layout_str) => {
- let layout = WindowButtonLayout::parse(&layout_str)
- .log_err()
- .unwrap_or_else(WindowButtonLayout::linux_default);
- client.with_common(|common| common.button_layout = layout);
- for window in client.0.borrow_mut().windows.values_mut() {
- window.window.set_button_layout();
+ XDPEvent::ButtonLayout(layout_str) => {
+ let layout = WindowButtonLayout::parse(&layout_str)
+ .log_err()
+ .unwrap_or_else(WindowButtonLayout::linux_default);
+ client.with_common(|common| common.button_layout = layout);
+ for window in client.0.borrow_mut().windows.values_mut() {
+ window.window.set_button_layout();
+ }
+ }
+ XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
+ // noop, X11 manages this for us.
}
- }
- XDPEvent::CursorTheme(_) | XDPEvent::CursorSize(_) => {
- // noop, X11 manages this for us.
}
}
})
.map_err(|err| anyhow!("Failed to initialize XDP event source: {err:?}"))?;
+ self.0.borrow_mut().registrations.push(token);
- xcb_flush(&xcb_connection);
-
- Ok(X11Client(Rc::new(RefCell::new(X11ClientState {
- modifiers: Modifiers::default(),
- capslock: Capslock::default(),
- last_modifiers_changed_event: Modifiers::default(),
- last_capslock_changed_event: Capslock::default(),
- event_loop: Some(event_loop),
- loop_handle: handle,
- common,
- last_click: Instant::now(),
- last_mouse_button: None,
- last_location: Point::new(px(0.0), px(0.0)),
- current_count: 0,
- pinch_scale: 1.0,
- gpu_context: Rc::new(RefCell::new(None)),
- compositor_gpu,
- scale_factor,
-
- xkb_context,
- xcb_connection,
- xkb_device_id,
- client_side_decorations_supported,
- x_root_index,
- resource_database,
- atoms,
- windows: HashMap::default(),
- mouse_focused_window: None,
- keyboard_focused_window: None,
- xkb: xkb_state,
- keyboard_layout,
- ximc,
- xim_handler,
-
- compose_state,
- pre_edit_text: None,
- pre_key_char_down: None,
- composing: false,
-
- cursor_handle,
- cursor_styles: HashMap::default(),
- cursor_cache: HashMap::default(),
- cursor_hidden_window: None,
- invisible_cursor_cache: None,
-
- pointer_device_states,
+ // Runnables' requests can read events into xcb's queue, where they don't wake the loop.
+ let common = self.0.borrow().common.clone();
+ common.borrow_mut().after_runnable = Some(Rc::new(move || {
+ if let Some(client) = this.get_client() {
+ client.process_x11_events(&xcb_connection).log_err();
+ }
+ }));
+ Ok(())
+ }
- supports_xinput_gestures,
+ pub(crate) fn has_windows(&self) -> bool {
+ !self.0.borrow().windows.is_empty()
+ }
- clipboard,
- clipboard_item: None,
- xdnd_state: Xdnd::default(),
- }))))
+ pub(crate) fn graphical_environment(&self) -> GraphicalEnvironment {
+ self.0.borrow().graphical_environment.clone()
}
pub fn process_x11_events(
@@ -808,7 +876,6 @@ impl X11Client {
state
.windows
.get(&win)
- .filter(|window_reference| !window_reference.window.state.borrow().destroyed)
.map(|window_reference| window_reference.window.clone())
}
@@ -1544,31 +1611,38 @@ impl X11Client {
let layout_name = keymap.layout_get_name(layout_idx);
if layout_name != state.keyboard_layout.name() {
state.keyboard_layout = LinuxKeyboardLayout::new(layout_name.to_string().into());
- if let Some(mut callback) = state.common.callbacks.keyboard_layout_change.take() {
+ let callback = state
+ .common
+ .borrow_mut()
+ .callbacks
+ .keyboard_layout_change
+ .take();
+ if let Some(mut callback) = callback {
drop(state);
callback();
state = self.0.borrow_mut();
- state.common.callbacks.keyboard_layout_change = Some(callback);
+ state.common.borrow_mut().callbacks.keyboard_layout_change = Some(callback);
}
}
}
}
-impl LinuxClient for X11Client {
- fn compositor_name(&self) -> &'static str {
+impl X11Client {
+ pub(crate) fn compositor_name(&self) -> &'static str {
"X11"
}
- fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
- f(&mut self.0.borrow_mut().common)
+ pub(crate) fn with_common<R>(&self, f: impl FnOnce(&mut LinuxCommon) -> R) -> R {
+ let common = self.0.borrow().common.clone();
+ f(&mut common.borrow_mut())
}
- fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
+ pub(crate) fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
let state = self.0.borrow();
Box::new(state.keyboard_layout.clone())
}
- fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
+ pub(crate) fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
let state = self.0.borrow();
let setup = state.xcb_connection.setup();
setup
@@ -1583,7 +1657,7 @@ impl LinuxClient for X11Client {
.collect()
}
- fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
+ pub(crate) fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
let state = self.0.borrow();
X11Display::new(
&state.xcb_connection,
@@ -1594,33 +1668,21 @@ impl LinuxClient for X11Client {
.map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)
}
- fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
- let state = self.0.borrow();
-
- Some(Rc::new(
- X11Display::new(
- &state.xcb_connection,
- state.scale_factor,
- u64::from(id) as usize,
- )
- .ok()?,
- ))
- }
-
#[cfg(feature = "screen-capture")]
- fn is_screen_capture_supported(&self) -> bool {
+ pub(crate) fn is_screen_capture_supported(&self) -> bool {
true
}
#[cfg(feature = "screen-capture")]
- fn screen_capture_sources(
+ pub(crate) fn screen_capture_sources(
&self,
) -> futures::channel::oneshot::Receiver<anyhow::Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>>
{
- gpui::scap_screen_capture::scap_screen_sources(&self.0.borrow().common.foreground_executor)
+ let foreground_executor = self.0.borrow().common.borrow().foreground_executor.clone();
+ gpui::scap_screen_capture::scap_screen_sources(&foreground_executor)
}
- fn open_window(
+ pub(crate) fn open_window(
&self,
handle: AnyWindowHandle,
params: WindowParams,
@@ -1640,7 +1702,7 @@ impl LinuxClient for X11Client {
let x_root_index = state.x_root_index;
let atoms = state.atoms;
let scale_factor = state.scale_factor;
- let appearance = state.common.appearance;
+ let appearance = state.common.borrow().appearance;
let compositor_gpu = state.compositor_gpu.take();
let supports_xinput_gestures = state.supports_xinput_gestures;
let is_bgr = state
@@ -1650,7 +1712,7 @@ impl LinuxClient for X11Client {
let window = X11Window::new(
handle,
X11ClientStatePtr(Rc::downgrade(&self.0)),
- state.common.foreground_executor.clone(),
+ state.common.borrow().foreground_executor.clone(),
state.gpu_context.clone(),
compositor_gpu,
params,
@@ -1689,7 +1751,7 @@ impl LinuxClient for X11Client {
Ok(Box::new(window))
}
- fn set_cursor_style(&self, style: CursorStyle) {
+ pub(crate) fn set_cursor_style(&self, style: CursorStyle) {
let mut state = self.0.borrow_mut();
let Some(focused_window) = state.mouse_focused_window else {
return;
@@ -1735,33 +1797,33 @@ impl LinuxClient for X11Client {
state.xcb_connection.flush().log_err();
}
- fn hide_cursor_until_mouse_moves(&self) {
+ pub(crate) fn hide_cursor_until_mouse_moves(&self) {
self.0.borrow_mut().hide_cursor_until_mouse_moves();
}
- fn is_cursor_visible(&self) -> bool {
+ pub(crate) fn is_cursor_visible(&self) -> bool {
self.0.borrow().cursor_hidden_window.is_none()
}
- fn open_uri(&self, uri: &str) {
- #[cfg(any(feature = "wayland", feature = "x11"))]
+ pub(crate) fn open_uri(&self, uri: &str) {
open_uri_internal(
self.with_common(|c| c.background_executor.clone()),
uri,
None,
+ self.graphical_environment(),
);
}
- fn reveal_path(&self, path: PathBuf) {
- #[cfg(any(feature = "x11", feature = "wayland"))]
+ pub(crate) fn reveal_path(&self, path: PathBuf) {
reveal_path_internal(
self.with_common(|c| c.background_executor.clone()),
path,
None,
+ self.graphical_environment(),
);
}
- fn write_to_primary(&self, item: gpui::ClipboardItem) {
+ pub(crate) fn write_to_primary(&self, item: gpui::ClipboardItem) {
let state = self.0.borrow_mut();
state
.clipboard
@@ -1774,7 +1836,7 @@ impl LinuxClient for X11Client {
.log_with_level(log::Level::Debug);
}
- fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
+ pub(crate) fn write_to_clipboard(&self, item: gpui::ClipboardItem) {
let mut state = self.0.borrow_mut();
state
.clipboard
@@ -1788,7 +1850,7 @@ impl LinuxClient for X11Client {
state.clipboard_item.replace(item);
}
- fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
+ pub(crate) fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
let state = self.0.borrow_mut();
state
.clipboard
@@ -1797,7 +1859,7 @@ impl LinuxClient for X11Client {
.log_with_level(log::Level::Debug)
}
- fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
+ pub(crate) fn read_from_clipboard(&self) -> Option<gpui::ClipboardItem> {
let state = self.0.borrow_mut();
// if the last copy was from this app, return our cached item
// which has metadata attached.
@@ -1814,22 +1876,7 @@ impl LinuxClient for X11Client {
.log_with_level(log::Level::Debug)
}
- fn run(&self) {
- let Some(mut event_loop) = self
- .0
- .borrow_mut()
- .event_loop
- .take()
- .context("X11Client::run called but it's already running")
- .log_err()
- else {
- return;
- };
-
- event_loop.run(None, &mut self.clone(), |_| {}).log_err();
- }
-
- fn active_window(&self) -> Option<AnyWindowHandle> {
+ pub(crate) fn active_window(&self) -> Option<AnyWindowHandle> {
let state = self.0.borrow();
state.keyboard_focused_window.and_then(|focused_window| {
state
@@ -1839,7 +1886,7 @@ impl LinuxClient for X11Client {
})
}
- fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
+ pub(crate) fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
let state = self.0.borrow();
let root = state.xcb_connection.setup().roots[state.x_root_index].root;
@@ -1873,15 +1920,15 @@ impl LinuxClient for X11Client {
.rev()
.filter_map(|&win| state.windows.get(&win))
{
- if !window_ref.window.state.borrow().destroyed {
- handles.push(window_ref.handle());
- }
+ handles.push(window_ref.handle());
}
Some(handles)
}
- fn window_identifier(&self) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
+ pub(crate) fn window_identifier(
+ &self,
+ ) -> impl Future<Output = Option<WindowIdentifier>> + Send + 'static {
let state = self.0.borrow();
state
.keyboard_focused_window
@@ -2005,7 +2052,11 @@ impl X11ClientState {
) -> RegistrationToken {
self.loop_handle
.insert_source(calloop::timer::Timer::immediate(), {
- move |mut instant, (), client| {
+ let this = self.this.clone();
+ move |mut instant, (), _| {
+ let Some(client) = this.get_client() else {
+ return calloop::timer::TimeoutAction::Drop;
+ };
let xcb_connection = {
let mut state = client.0.borrow_mut();
let xcb_connection = state.xcb_connection.clone();
diff --git a/crates/gpui_linux/src/linux/x11/clipboard.rs b/crates/gpui_linux/src/linux/x11/clipboard.rs
index 706e7b09658..9835786efe8 100644
--- a/crates/gpui_linux/src/linux/x11/clipboard.rs
+++ b/crates/gpui_linux/src/linux/x11/clipboard.rs
@@ -124,6 +124,8 @@ struct XContext {
}
struct Inner {
+ /// The X display every clipboard connection uses.
+ display: String,
/// The context for the thread which serves clipboard read
/// requests coming to us.
server: XContext,
@@ -140,10 +142,10 @@ struct Inner {
}
impl XContext {
- fn new() -> Result<Self> {
+ fn new(display: &str) -> Result<Self> {
// create a new connection to an X11 server
- let (conn, screen_num): (RustConnection, _) =
- RustConnection::connect(None).map_err(|_| {
+ let (conn, screen_num): (RustConnection, _) = RustConnection::connect(Some(display))
+ .map_err(|_| {
Error::unknown("X11 server connection timed out because it was unreachable")
})?;
let screen = conn
@@ -208,14 +210,15 @@ enum ReadSelNotifyResult {
}
impl Inner {
- fn new() -> Result<Self> {
- let server = XContext::new()?;
+ fn new(display: &str) -> Result<Self> {
+ let server = XContext::new(display)?;
let atoms = Atoms::new(&server.conn)
.map_err(into_unknown)?
.reply()
.map_err(into_unknown)?;
Ok(Self {
+ display: display.to_owned(),
server,
atoms,
clipboard: Selection::default(),
@@ -297,7 +300,7 @@ impl Inner {
}
return Err(Error::ContentNotAvailable);
}
- let reader = XContext::new()?;
+ let reader = XContext::new(&self.display)?;
let highest_precedence_format =
match self.read_single(&reader, selection, self.atoms.TARGETS) {
@@ -950,7 +953,8 @@ pub(crate) struct Clipboard {
}
impl Clipboard {
- pub(crate) fn new() -> Result<Self> {
+ /// Returns the process's clipboard, connecting it to `display` if it doesn't exist yet.
+ pub(crate) fn new(display: &str) -> Result<Self> {
let mut global_cb = CLIPBOARD.lock();
if let Some(global_cb) = &*global_cb {
return Ok(Self {
@@ -958,7 +962,7 @@ impl Clipboard {
});
}
// At this point we know that the clipboard does not exist.
- let ctx = Arc::new(Inner::new()?);
+ let ctx = Arc::new(Inner::new(display)?);
let join_handle = std::thread::Builder::new()
.name("Clipboard".to_owned())
.spawn({
@@ -1085,53 +1089,82 @@ impl Drop for Clipboard {
if Arc::strong_count(&self.inner) == MIN_OWNERS {
// If the are the only owners of the clipboard are ourselves and
// the global object, then we should destroy the global object,
- // and send the data to the clipboard manager
-
- if let Err(e) = self.inner.ask_clipboard_manager_to_request_our_data() {
- log::error!(
- "Could not hand the clipboard data over to the clipboard manager: {}",
- e
- );
- }
- let global_cb = global_cb.take();
- if let Err(e) = self
- .inner
- .server
- .conn
- .destroy_window(self.inner.server.win_id)
- {
- log::error!("Failed to destroy the clipboard window. Error: {}", e);
- return;
- }
- if let Err(e) = self.inner.server.conn.flush() {
- log::error!("Failed to flush the clipboard window. Error: {}", e);
+ // and send the data to the clipboard manager.
+ //
+ // The handover waits for the clipboard manager, so it runs on its own thread rather
+ // than blocking this one, which can be the UI thread switching display modes. A
+ // clipboard created meanwhile is independent of this one.
+ let Some(global_cb) = global_cb.take() else {
return;
- }
- if let Some(global_cb) = global_cb
- && let Err(e) = global_cb.server_handle.join()
+ };
+ let inner = Arc::clone(&self.inner);
+ match std::thread::Builder::new()
+ .name("Clipboard handover".to_owned())
+ .spawn(move || shut_down(inner, global_cb))
{
- // Let's try extracting the error message
- let message;
- if let Some(msg) = e.downcast_ref::<&'static str>() {
- message = Some((*msg).to_string());
- } else if let Some(msg) = e.downcast_ref::<String>() {
- message = Some(msg.clone());
- } else {
- message = None;
- }
- if let Some(message) = message {
+ Ok(handover) => HANDOVERS.lock().push(handover),
+ Err(error) => {
log::error!(
- "The clipboard server thread panicked. Panic message: '{}'",
- message,
- );
- } else {
- log::error!("The clipboard server thread panicked.");
+ "Failed to hand the clipboard over to the clipboard manager: {error}"
+ )
}
}
}
}
}
+/// Threads handing a dropped clipboard's data to the clipboard manager.
+static HANDOVERS: Mutex<Vec<JoinHandle<()>>> = parking_lot::const_mutex(Vec::new());
+
+/// Waits for dropped clipboards to finish handing their data to the clipboard manager.
+///
+/// Called before the process exits, which would otherwise lose data still being handed over.
+pub(crate) fn wait_for_clipboard_handovers() {
+ let handovers = std::mem::take(&mut *HANDOVERS.lock());
+ for handover in handovers {
+ if handover.join().is_err() {
+ log::error!("The clipboard handover thread panicked.");
+ }
+ }
+}
+
+/// Hands the clipboard's data to the clipboard manager, then stops serving it.
+fn shut_down(inner: Arc<Inner>, global_cb: GlobalClipboard) {
+ if let Err(e) = inner.ask_clipboard_manager_to_request_our_data() {
+ log::error!(
+ "Could not hand the clipboard data over to the clipboard manager: {}",
+ e
+ );
+ }
+ if let Err(e) = inner.server.conn.destroy_window(inner.server.win_id) {
+ log::error!("Failed to destroy the clipboard window. Error: {}", e);
+ return;
+ }
+ if let Err(e) = inner.server.conn.flush() {
+ log::error!("Failed to flush the clipboard window. Error: {}", e);
+ return;
+ }
+ if let Err(e) = global_cb.server_handle.join() {
+ // Let's try extracting the error message
+ let message;
+ if let Some(msg) = e.downcast_ref::<&'static str>() {
+ message = Some((*msg).to_string());
+ } else if let Some(msg) = e.downcast_ref::<String>() {
+ message = Some(msg.clone());
+ } else {
+ message = None;
+ }
+ if let Some(message) = message {
+ log::error!(
+ "The clipboard server thread panicked. Panic message: '{}'",
+ message,
+ );
+ } else {
+ log::error!("The clipboard server thread panicked.");
+ }
+ }
+}
+
fn into_unknown<E: std::fmt::Display>(error: E) -> Error {
Error::Unknown {
description: error.to_string(),
diff --git a/crates/gpui_linux/src/linux/x11/window.rs b/crates/gpui_linux/src/linux/x11/window.rs
index efeb606b202..83a5fdf4806 100644
--- a/crates/gpui_linux/src/linux/x11/window.rs
+++ b/crates/gpui_linux/src/linux/x11/window.rs
@@ -257,7 +257,6 @@ pub struct Callbacks {
}
pub struct X11WindowState {
- pub destroyed: bool,
parent: Option<X11WindowStatePtr>,
children: FxHashSet<xproto::Window>,
client: X11ClientStatePtr,
@@ -270,7 +269,9 @@ pub struct X11WindowState {
pub(crate) last_sync_counter: Option<sync::Int64>,
bounds: Bounds<Pixels>,
scale_factor: f32,
- renderer: WgpuRenderer,
+ /// Taken when the window is dropped. Its GPU objects use the X connection, so they mustn't
+ /// outlive the window, which a display mode switch relies on.
+ renderer: Option<WgpuRenderer>,
display: Rc<dyn PlatformDisplay>,
input_handler: Option<PlatformInputHandler>,
appearance: WindowAppearance,
@@ -297,6 +298,13 @@ impl X11WindowState {
fn is_transparent(&self) -> bool {
self.background_appearance != WindowBackgroundAppearance::Opaque
}
+
+ fn update_transparency(&mut self) {
+ let is_transparent = self.is_transparent();
+ if let Some(renderer) = &mut self.renderer {
+ renderer.update_transparency(is_transparent);
+ }
+ }
}
#[derive(Clone)]
@@ -828,7 +836,7 @@ impl X11WindowState {
visual_id: visual.id,
bounds: bounds.to_pixels(scale_factor),
scale_factor,
- renderer,
+ renderer: Some(renderer),
atoms: *atoms,
input_handler: None,
active: false,
@@ -843,7 +851,6 @@ impl X11WindowState {
appearance,
handle,
background_appearance: WindowBackgroundAppearance::Opaque,
- destroyed: false,
client_side_decorations_supported,
decorations: WindowDecorations::Server,
last_insets: [0, 0, 0, 0],
@@ -880,9 +887,11 @@ impl Drop for X11Window {
parent.state.borrow_mut().children.remove(&self.0.x_window);
}
- state.renderer.destroy();
+ // The renderer's GPU objects use the X connection, and a display mode switch closes the
+ // connection once no window is left in the client's window map, so both go now.
+ state.renderer.take();
- let destroy_x_window = maybe!({
+ maybe!({
check_reply(
|| "X11 DestroyWindow failure.",
self.0.xcb.destroy_window(self.0.x_window),
@@ -892,22 +901,13 @@ impl Drop for X11Window {
anyhow::Ok(())
})
.log_err();
-
- if destroy_x_window.is_some() {
- state.destroyed = true;
-
- let this_ptr = self.0.clone();
- let client_ptr = state.client.clone();
- state
- .executor
- .spawn(async move {
- this_ptr.close();
- client_ptr.drop_window(this_ptr.x_window);
- })
- .detach();
- }
-
+ let client = state.client.clone();
+ let executor = state.executor.clone();
drop(state);
+
+ client.drop_window(self.0.x_window);
+ let this_ptr = self.0.clone();
+ executor.spawn(async move { this_ptr.close() }).detach();
}
}
@@ -1307,7 +1307,9 @@ impl X11WindowStatePtr {
}
let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
- state.renderer.update_drawable_size(gpu_size);
+ if let Some(renderer) = &mut state.renderer {
+ renderer.update_drawable_size(gpu_size);
+ }
let result = (is_resize, state.content_size(), state.scale_factor);
if let Some(value) = state.last_sync_counter.take() {
check_reply(
@@ -1363,8 +1365,7 @@ impl X11WindowStatePtr {
pub fn set_appearance(&mut self, appearance: WindowAppearance) {
let mut state = self.state.borrow_mut();
state.appearance = appearance;
- let is_transparent = state.is_transparent();
- state.renderer.update_transparency(is_transparent);
+ state.update_transparency();
state.appearance = appearance;
drop(state);
let callback = self.callbacks.borrow_mut().appearance_changed.take();
@@ -1624,8 +1625,7 @@ impl PlatformWindow for X11Window {
fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
let mut state = self.0.state.borrow_mut();
state.background_appearance = background_appearance;
- let transparent = state.is_transparent();
- state.renderer.update_transparency(transparent);
+ state.update_transparency();
}
fn background_appearance(&self) -> WindowBackgroundAppearance {
@@ -1746,8 +1746,12 @@ impl PlatformWindow for X11Window {
fn draw(&self, scene: &Scene) {
let mut inner = self.0.state.borrow_mut();
+ let inner = &mut *inner;
+ let Some(renderer) = &mut inner.renderer else {
+ return;
+ };
- if inner.renderer.device_lost() {
+ if renderer.device_lost() {
let raw_window = RawWindow {
connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
&*self.0.xcb,
@@ -1756,7 +1760,7 @@ impl PlatformWindow for X11Window {
window_id: self.0.x_window,
visual_id: inner.visual_id,
};
- match inner.renderer.recover(&raw_window) {
+ match renderer.recover(&raw_window) {
Ok(()) => {}
Err(err) => {
log::warn!("GPU recovery failed, will retry on next frame: {err}");
@@ -1767,16 +1771,22 @@ impl PlatformWindow for X11Window {
return;
}
- inner.renderer.draw(scene);
+ renderer.draw(scene);
- if inner.renderer.needs_redraw() {
+ if renderer.needs_redraw() {
inner.force_render_after_recovery = true;
}
}
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
- let inner = self.0.state.borrow();
- inner.renderer.sprite_atlas().clone()
+ self.0
+ .state
+ .borrow()
+ .renderer
+ .as_ref()
+ .expect("the renderer is only taken when the window is dropped")
+ .sprite_atlas()
+ .clone()
}
fn show_window_menu(&self, position: Point<Pixels>) {
@@ -1940,13 +1950,11 @@ impl PlatformWindow for X11Window {
match decorations {
WindowDecorations::Server => {
state.decorations = WindowDecorations::Server;
- let is_transparent = state.is_transparent();
- state.renderer.update_transparency(is_transparent);
+ state.update_transparency();
}
WindowDecorations::Client => {
state.decorations = WindowDecorations::Client;
- let is_transparent = state.is_transparent();
- state.renderer.update_transparency(is_transparent);
+ state.update_transparency();
}
}
@@ -1965,7 +1973,7 @@ impl PlatformWindow for X11Window {
}
fn gpu_specs(&self) -> Option<GpuSpecs> {
- self.0.state.borrow().renderer.gpu_specs()
+ self.0.state.borrow().renderer.as_ref()?.gpu_specs()
}
fn play_system_bell(&self) {
diff --git a/crates/gpui_linux/src/linux/xdg_desktop_portal.rs b/crates/gpui_linux/src/linux/xdg_desktop_portal.rs
index 9b5d72476b6..9b068365e28 100644
--- a/crates/gpui_linux/src/linux/xdg_desktop_portal.rs
+++ b/crates/gpui_linux/src/linux/xdg_desktop_portal.rs
@@ -3,11 +3,12 @@
//! This module uses the [ashpd] crate
use ashpd::desktop::settings::{ColorScheme, Settings};
-use calloop::channel::Channel;
+use calloop::channel::{Channel, Sender};
use calloop::{EventSource, Poll, PostAction, Readiness, Token, TokenFactory};
+use futures::future::BoxFuture;
use smol::stream::StreamExt;
-use gpui::{BackgroundExecutor, WindowAppearance};
+use gpui::{BackgroundExecutor, Task, WindowAppearance};
pub enum Event {
WindowAppearance(WindowAppearance),
@@ -18,117 +19,117 @@ pub enum Event {
ButtonLayout(String),
}
+/// Forwards desktop settings from the portal to the event loop.
+///
+/// Owns the task that listens to the portal, so removing the source from the loop cancels it and
+/// releases its D-Bus subscriptions.
pub struct XDPEventSource {
channel: Channel<Event>,
+ _listener: Task<()>,
}
impl XDPEventSource {
pub fn new(executor: &BackgroundExecutor) -> Self {
let (sender, channel) = calloop::channel::channel();
+ let listener = executor.spawn(async move {
+ if let Err(error) = listen(sender).await {
+ log::debug!("stopped listening to desktop portal settings: {error:#}");
+ }
+ });
+ Self {
+ channel,
+ _listener: listener,
+ }
+ }
+}
+
+async fn listen(sender: Sender<Event>) -> anyhow::Result<()> {
+ let settings = Settings::new().await?;
+
+ if let Ok(initial_appearance) = settings.color_scheme().await {
+ sender.send(Event::WindowAppearance(
+ window_appearance_from_color_scheme(initial_appearance),
+ ))?;
+ }
+ if let Ok(initial_theme) = settings
+ .read::<String>("org.gnome.desktop.interface", "cursor-theme")
+ .await
+ {
+ sender.send(Event::CursorTheme(initial_theme))?;
+ }
+
+ // If u32 is used here, it throws invalid type error
+ if let Ok(initial_size) = settings
+ .read::<i32>("org.gnome.desktop.interface", "cursor-size")
+ .await
+ {
+ sender.send(Event::CursorSize(initial_size as u32))?;
+ }
+
+ if let Ok(initial_layout) = settings
+ .read::<String>("org.gnome.desktop.wm.preferences", "button-layout")
+ .await
+ {
+ sender.send(Event::ButtonLayout(initial_layout))?;
+ }
+
+ // Each listener runs until its stream or the channel closes. They're joined rather than
+ // spawned, so that cancelling this future cancels them all.
+ let mut listeners: Vec<BoxFuture<'_, anyhow::Result<()>>> = Vec::new();
+
+ if let Ok(mut cursor_theme_changed) = settings
+ .receive_setting_changed_with_args("org.gnome.desktop.interface", "cursor-theme")
+ .await
+ {
+ let sender = sender.clone();
+ listeners.push(Box::pin(async move {
+ while let Some(theme) = cursor_theme_changed.next().await {
+ sender.send(Event::CursorTheme(theme?))?;
+ }
+ anyhow::Ok(())
+ }));
+ }
+
+ if let Ok(mut cursor_size_changed) = settings
+ .receive_setting_changed_with_args::<i32>("org.gnome.desktop.interface", "cursor-size")
+ .await
+ {
+ let sender = sender.clone();
+ listeners.push(Box::pin(async move {
+ while let Some(size) = cursor_size_changed.next().await {
+ sender.send(Event::CursorSize(size? as u32))?;
+ }
+ anyhow::Ok(())
+ }));
+ }
+
+ if let Ok(mut button_layout_changed) = settings
+ .receive_setting_changed_with_args("org.gnome.desktop.wm.preferences", "button-layout")
+ .await
+ {
+ let sender = sender.clone();
+ listeners.push(Box::pin(async move {
+ while let Some(layout) = button_layout_changed.next().await {
+ sender.send(Event::ButtonLayout(layout?))?;
+ }
+ anyhow::Ok(())
+ }));
+ }
- let background = executor.clone();
-
- executor
- .spawn(async move {
- let settings = Settings::new().await?;
-
- if let Ok(initial_appearance) = settings.color_scheme().await {
- sender.send(Event::WindowAppearance(
- window_appearance_from_color_scheme(initial_appearance),
- ))?;
- }
- if let Ok(initial_theme) = settings
- .read::<String>("org.gnome.desktop.interface", "cursor-theme")
- .await
- {
- sender.send(Event::CursorTheme(initial_theme))?;
- }
-
- // If u32 is used here, it throws invalid type error
- if let Ok(initial_size) = settings
- .read::<i32>("org.gnome.desktop.interface", "cursor-size")
- .await
- {
- sender.send(Event::CursorSize(initial_size as u32))?;
- }
-
- if let Ok(initial_layout) = settings
- .read::<String>("org.gnome.desktop.wm.preferences", "button-layout")
- .await
- {
- sender.send(Event::ButtonLayout(initial_layout))?;
- }
-
- if let Ok(mut cursor_theme_changed) = settings
- .receive_setting_changed_with_args(
- "org.gnome.desktop.interface",
- "cursor-theme",
- )
- .await
- {
- let sender = sender.clone();
- background
- .spawn(async move {
- while let Some(theme) = cursor_theme_changed.next().await {
- let theme = theme?;
- sender.send(Event::CursorTheme(theme))?;
- }
- anyhow::Ok(())
- })
- .detach();
- }
-
- if let Ok(mut cursor_size_changed) = settings
- .receive_setting_changed_with_args::<i32>(
- "org.gnome.desktop.interface",
- "cursor-size",
- )
- .await
- {
- let sender = sender.clone();
- background
- .spawn(async move {
- while let Some(size) = cursor_size_changed.next().await {
- let size = size?;
- sender.send(Event::CursorSize(size as u32))?;
- }
- anyhow::Ok(())
- })
- .detach();
- }
-
- if let Ok(mut button_layout_changed) = settings
- .receive_setting_changed_with_args(
- "org.gnome.desktop.wm.preferences",
- "button-layout",
- )
- .await
- {
- let sender = sender.clone();
- background
- .spawn(async move {
- while let Some(layout) = button_layout_changed.next().await {
- let layout = layout?;
- sender.send(Event::ButtonLayout(layout))?;
- }
- anyhow::Ok(())
- })
- .detach();
- }
-
- let mut appearance_changed = settings.receive_color_scheme_changed().await?;
- while let Some(scheme) = appearance_changed.next().await {
- sender.send(Event::WindowAppearance(
- window_appearance_from_color_scheme(scheme),
- ))?;
- }
-
- anyhow::Ok(())
- })
- .detach();
-
- Self { channel }
+ let mut appearance_changed = settings.receive_color_scheme_changed().await?;
+ listeners.push(Box::pin(async move {
+ while let Some(scheme) = appearance_changed.next().await {
+ sender.send(Event::WindowAppearance(
+ window_appearance_from_color_scheme(scheme),
+ ))?;
+ }
+ anyhow::Ok(())
+ }));
+
+ for result in futures::future::join_all(listeners).await {
+ result?;
}
+ Ok(())
}
impl EventSource for XDPEventSource {
diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
index 92fcf9568df..c5ed2b13076 100644
--- a/crates/gpui_macos/src/platform.rs
+++ b/crates/gpui_macos/src/platform.rs
@@ -8,9 +8,12 @@ use block2::RcBlock;
use cocoa::{
appkit::{
NSAppearanceNameVibrantDark, NSAppearanceNameVibrantLight, NSApplication,
- NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular, NSControl as _,
- NSEventModifierFlags, NSMenu, NSMenuItem, NSVisualEffectState, NSVisualEffectView,
- NSWindow,
+ NSApplicationActivationPolicy,
+ NSApplicationActivationPolicy::{
+ NSApplicationActivationPolicyAccessory, NSApplicationActivationPolicyRegular,
+ },
+ NSControl as _, NSEventModifierFlags, NSMenu, NSMenuItem, NSVisualEffectState,
+ NSVisualEffectView, NSWindow,
},
base::{BOOL, NO, YES, id, nil, selector},
foundation::{
@@ -29,11 +32,12 @@ use ctor::ctor;
use dispatch2::DispatchQueue;
use futures::channel::oneshot;
use gpui::{
- Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle,
- ForegroundExecutor, KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions,
- Platform, PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
- PlatformWindow, Result, SystemMenuType, Task, ThermalState, WindowAppearance, WindowKind,
- WindowParams, popup::PopupNotSupportedError,
+ Action, ActivationPolicy, ActivityGuard, AnyWindowHandle, BackgroundExecutor, ClipboardItem,
+ CursorStyle, ForegroundExecutor, GraphicalEnvironment, KeyContext, Keymap, Menu, MenuItem,
+ OsMenu, OwnedMenu, PathPromptOptions, Platform, PlatformDisplay, PlatformKeyboardLayout,
+ PlatformKeyboardMapper, PlatformTextSystem, PlatformWindow, Result, SystemMenuType, Task,
+ ThermalState, WindowAppearance, WindowKind, WindowParams, WindowingRequest,
+ popup::PopupNotSupportedError,
};
use gpui_util::{ResultExt, new_std_command};
use itertools::Itertools;
@@ -182,6 +186,8 @@ pub(crate) struct MacPlatformState {
text_system: Arc<dyn PlatformTextSystem>,
renderer_context: renderer::Context,
headless: bool,
+ activation_policy: ActivationPolicy,
+ application_created: bool,
general_pasteboard: Pasteboard,
find_pasteboard: Pasteboard,
reopen: Option<Box<dyn FnMut()>>,
@@ -205,6 +211,22 @@ pub(crate) struct MacPlatformState {
system_notifications: crate::system_notifications::SystemNotificationState,
}
+/// The activation policy that stands for a windowing mode: an app is headless while it has no
+/// Dock icon or menu bar.
+fn activation_policy_for(request: &WindowingRequest) -> ActivationPolicy {
+ match request {
+ WindowingRequest::Headless => ActivationPolicy::Accessory,
+ WindowingRequest::Windowed(_) => ActivationPolicy::Regular,
+ }
+}
+
+fn native_activation_policy(policy: ActivationPolicy) -> NSApplicationActivationPolicy {
+ match policy {
+ ActivationPolicy::Regular => NSApplicationActivationPolicyRegular,
+ ActivationPolicy::Accessory => NSApplicationActivationPolicyAccessory,
+ }
+}
+
impl MacPlatform {
pub fn new(headless: bool) -> Self {
let marker = MainThreadMarker::new().expect("Mac platform not created on main thread");
@@ -228,6 +250,8 @@ impl MacPlatform {
let state = Mutex::new(MacPlatformState {
headless,
+ activation_policy: ActivationPolicy::Regular,
+ application_created: false,
text_system,
background_executor: BackgroundExecutor::new(dispatcher.clone()),
foreground_executor: ForegroundExecutor::new(dispatcher),
@@ -538,6 +562,18 @@ impl Platform for MacPlatform {
unsafe {
let app: id = msg_send![APP_CLASS, sharedApplication];
+ // An accessory app must not register in the Dock during launch, so its
+ // policy has to precede the run loop. `Regular` is applied in
+ // `did_finish_launching` instead: setting it this early leaves the menu
+ // bar of an unbundled app launched from a terminal unclickable.
+ let policy = {
+ let mut state = self.0.lock();
+ state.application_created = true;
+ state.activation_policy
+ };
+ if policy == ActivationPolicy::Accessory {
+ app.setActivationPolicy_(native_activation_policy(policy));
+ }
let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
app.setDelegate_(app_delegate);
@@ -552,6 +588,7 @@ impl Platform for MacPlatform {
(*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
(*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
}
+ self.0.lock().application_created = false;
}
fn quit(&self) {
@@ -629,6 +666,48 @@ impl Platform for MacPlatform {
}
}
+ fn set_activation_policy(&self, policy: ActivationPolicy) {
+ let mut state = self.0.lock();
+ state.activation_policy = policy;
+ let should_apply = state.application_created && !state.headless;
+ drop(state);
+ if should_apply {
+ unsafe {
+ let app: id = msg_send![APP_CLASS, sharedApplication];
+ app.setActivationPolicy_(native_activation_policy(policy));
+ }
+ }
+ }
+
+ fn set_initial_windowing(&self, request: WindowingRequest) {
+ self.set_activation_policy(activation_policy_for(&request));
+ }
+
+ fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> {
+ let state = self.0.lock();
+ if state.headless {
+ return Task::ready(Err(anyhow!(
+ "a platform created headless has no application to switch windowing modes"
+ )));
+ }
+ let policy = activation_policy_for(&request);
+ if state.activation_policy == policy {
+ return Task::ready(Err(match request {
+ WindowingRequest::Headless => anyhow!("already headless"),
+ WindowingRequest::Windowed(_) => anyhow!("already windowed"),
+ }));
+ }
+ drop(state);
+ self.set_activation_policy(policy);
+ Task::ready(Ok(()))
+ }
+
+ fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
+ let state = self.0.lock();
+ (!state.headless && state.activation_policy == ActivationPolicy::Regular)
+ .then(GraphicalEnvironment::detect)
+ }
+
fn hide(&self) {
unsafe {
let app = NSApplication::sharedApplication(nil);
@@ -1317,7 +1396,8 @@ extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
unsafe {
let app: id = msg_send![APP_CLASS, sharedApplication];
- app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
+ let policy = get_mac_platform(this).0.lock().activation_policy;
+ app.setActivationPolicy_(native_activation_policy(policy));
let notification_center: *mut Object =
msg_send![class!(NSNotificationCenter), defaultCenter];
diff --git a/crates/gpui_platform/src/gpui_platform.rs b/crates/gpui_platform/src/gpui_platform.rs
index 350a41f1749..cb48a79d442 100644
--- a/crates/gpui_platform/src/gpui_platform.rs
+++ b/crates/gpui_platform/src/gpui_platform.rs
@@ -24,6 +24,16 @@ pub fn headless() -> gpui::Application {
gpui::Application::with_platform(current_platform(true))
}
+/// Returns a Linux app that may switch among `allowed_modes`.
+///
+/// It starts windowed in the process's own environment, or headless if that names no allowed
+/// display server. Set another initial mode with [`gpui::Application::with_windowing`], and
+/// switch later with [`gpui::App::request_windowing`].
+#[cfg(any(target_os = "linux", target_os = "freebsd"))]
+pub fn linux(allowed_modes: gpui::WindowingModes) -> gpui::Application {
+ gpui::Application::with_platform(gpui_linux::linux_platform(allowed_modes))
+}
+
#[cfg(target_family = "wasm")]
pub use gpui_web::WebBackendPreference;
diff --git a/crates/gpui_windows/Cargo.toml b/crates/gpui_windows/Cargo.toml
index e82b308a71b..a0aaa5dde31 100644
--- a/crates/gpui_windows/Cargo.toml
+++ b/crates/gpui_windows/Cargo.toml
@@ -38,7 +38,7 @@ raw-window-handle.workspace = true
scheduler.workspace = true
smallvec.workspace = true
uuid.workspace = true
-windows.workspace = true
+windows = { workspace = true, features = ["Win32_System_StationsAndDesktops"] }
windows-core.workspace = true
windows-numerics = "0.3"
windows-registry.workspace = true
diff --git a/crates/gpui_windows/src/direct_write.rs b/crates/gpui_windows/src/direct_write.rs
index dfe98a76be1..304dc38663b 100644
--- a/crates/gpui_windows/src/direct_write.rs
+++ b/crates/gpui_windows/src/direct_write.rs
@@ -70,7 +70,9 @@ struct GPUState {
}
struct DirectWriteState {
- gpu_state: GPUState,
+ /// Used to rasterize color glyphs. `None` while the platform is headless: shaping and
+ /// layout don't need a GPU, and nothing is drawn.
+ gpu_state: Option<GPUState>,
system_font_collection: IDWriteFontCollection1,
custom_font_collection: IDWriteFontCollection1,
fonts: Vec<FontInfo>,
@@ -163,7 +165,8 @@ impl GPUState {
}
impl DirectWriteTextSystem {
- pub(crate) fn new(directx_devices: &DirectXDevices) -> Result<Self> {
+ /// Creates the text system, able to rasterize color glyphs once it has `directx_devices`.
+ pub(crate) fn new(directx_devices: Option<&DirectXDevices>) -> Result<Self> {
let factory: IDWriteFactory5 = unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? };
// The `IDWriteInMemoryFontFileLoader` here is supported starting from
// Windows 10 Creators Update, which consequently requires the entire
@@ -176,7 +179,7 @@ impl DirectWriteTextSystem {
let locale = HSTRING::from_wide(&locale);
let text_renderer = TextRendererWrapper::new(locale.clone());
- let gpu_state = GPUState::new(directx_devices)?;
+ let gpu_state = directx_devices.map(GPUState::new).transpose()?;
let system_subpixel_rendering = get_system_subpixel_rendering();
let system_ui_font_name = get_system_ui_font_name();
@@ -218,9 +221,16 @@ impl DirectWriteTextSystem {
})
}
+ /// Uses `directx_devices` to rasterize color glyphs, replacing any previous devices, for
+ /// example after the device was lost.
pub(crate) fn handle_gpu_lost(&self, directx_devices: &DirectXDevices) -> Result<()> {
self.state.write().handle_gpu_lost(directx_devices)
}
+
+ /// Releases the GPU state, when the platform switches to headless mode.
+ pub(crate) fn release_gpu(&self) {
+ self.state.write().gpu_state = None;
+ }
}
impl PlatformTextSystem for DirectWriteTextSystem {
@@ -885,6 +895,10 @@ impl DirectWriteState {
// (`Map`/`Unmap`/`Draw`/`CopyResource`), which `DirectXRenderer` and `DirectXAtlas` also
// touch. An immediate `ID3D11DeviceContext` is not thread-safe, so this must only run on
// the main UI thread (which it always is; text rasterization never leaves that thread).
+ let gpu_state = self
+ .gpu_state
+ .as_ref()
+ .context("rasterizing color glyphs needs a GPU, which headless mode has none of")?;
let bitmap_size = glyph_bounds.size;
let subpixel_shift = params
.subpixel_variant
@@ -981,7 +995,7 @@ impl DirectWriteState {
};
let bounds = bounds(point(color_bounds.left, color_bounds.top), color_size);
glyph_layers.push(GlyphLayerTexture::new(
- &self.gpu_state,
+ gpu_state,
run_color,
bounds,
&alpha_data,
@@ -997,8 +1011,6 @@ impl DirectWriteState {
}
}
- let gpu_state = &self.gpu_state;
-
let render_target_texture = {
let mut texture = None;
let desc = D3D11_TEXTURE2D_DESC {
@@ -1284,7 +1296,7 @@ impl DirectWriteState {
try_to_recover_from_device_lost(|| {
GPUState::new(directx_devices).context("Recreating GPU state for DirectWrite")
})
- .map(|gpu_state| self.gpu_state = gpu_state)
+ .map(|gpu_state| self.gpu_state = Some(gpu_state))
}
}
@@ -2005,7 +2017,7 @@ mod tests {
#[test]
fn color_emoji_rasterization_is_stable_across_batches() -> Result<()> {
let devices = DirectXDevices::new()?;
- let text_system = DirectWriteTextSystem::new(&devices)?;
+ let text_system = DirectWriteTextSystem::new(Some(&devices))?;
let font = Font {
family: "Segoe UI Emoji".into(),
diff --git a/crates/gpui_windows/src/platform.rs b/crates/gpui_windows/src/platform.rs
index 8dcb041e28b..995017faedb 100644
--- a/crates/gpui_windows/src/platform.rs
+++ b/crates/gpui_windows/src/platform.rs
@@ -53,7 +53,12 @@ impl TrackedWindow {
pub struct WindowsPlatform {
inner: Rc<WindowsPlatformInner>,
raw_window_handles: Arc<RwLock<SmallVec<[TrackedWindow; 4]>>>,
+ /// The windowing mode to start in, applied when `run` starts. Windowed when unset.
+ initial_windowing: RefCell<Option<WindowingRequest>>,
+ /// Set to stop the current `VSyncProvider` thread, which runs while windowed.
+ vsync_stop: RefCell<Option<Arc<AtomicBool>>>,
// The below members will never change throughout the entire lifecycle of the app.
+ /// Created with `headless()`: never windowed, and without a real text system.
headless: bool,
icon: HICON,
background_executor: BackgroundExecutor,
@@ -176,20 +181,18 @@ impl WindowsPlatform {
unsafe {
OleInitialize(None).context("unable to initialize Windows OLE")?;
}
- let (directx_devices, text_system, direct_write_text_system) = if !headless {
- let devices = DirectXDevices::new().context("Creating DirectX devices")?;
+ // A platform that can become windowed needs the real text system from the start: the app
+ // keeps the one it's created with. It gets DirectX devices when it becomes windowed.
+ let (text_system, direct_write_text_system) = if !headless {
let dw_text_system = Arc::new(
- DirectWriteTextSystem::new(&devices)
- .context("Error creating DirectWriteTextSystem")?,
+ DirectWriteTextSystem::new(None).context("Error creating DirectWriteTextSystem")?,
);
(
- Some(devices),
dw_text_system.clone() as Arc<dyn PlatformTextSystem>,
Some(dw_text_system),
)
} else {
(
- None,
Arc::new(gpui::NoopTextSystem::new()) as Arc<dyn PlatformTextSystem>,
None,
)
@@ -210,7 +213,7 @@ impl WindowsPlatform {
validation_number,
main_sender: Some(main_sender),
main_receiver: Some(main_receiver),
- directx_devices,
+ directx_devices: None,
dispatcher: None,
};
let result = unsafe {
@@ -262,6 +265,8 @@ impl WindowsPlatform {
inner,
handle,
raw_window_handles,
+ initial_windowing: RefCell::new(None),
+ vsync_stop: RefCell::new(None),
headless,
icon,
background_executor,
@@ -374,6 +379,57 @@ impl WindowsPlatform {
.map(|hwnd| hwnd.as_raw())
}
+ fn is_windowed(&self) -> bool {
+ self.inner.state.directx_devices.borrow().is_some()
+ }
+
+ /// Connects in the initial windowing mode, before the app finishes launching.
+ ///
+ /// # Panics
+ ///
+ /// Panics if DirectX can't be initialized, since the app can't start. Starts headless if this
+ /// process can't show windows, for example when started over SSH.
+ fn connect_initially(&self) {
+ let request = self
+ .initial_windowing
+ .borrow_mut()
+ .take()
+ .unwrap_or_else(|| WindowingRequest::Windowed(GraphicalEnvironment::detect()));
+ let WindowingRequest::Windowed(environment) = request else {
+ return;
+ };
+ if let Err(error) = check_can_show_windows(&environment) {
+ log::info!("starting headless: {error:#}");
+ return;
+ }
+ self.attach_gpu()
+ .unwrap_or_else(|error| panic!("failed to initialize DirectX: {error:#}"));
+ }
+
+ /// Creates the DirectX devices that windows draw with, and starts vsync.
+ fn attach_gpu(&self) -> Result<()> {
+ let devices = DirectXDevices::new().context("Creating DirectX devices")?;
+ if let Some(text_system) = &self.direct_write_text_system {
+ text_system.handle_gpu_lost(&devices)?;
+ }
+ *self.inner.state.directx_devices.borrow_mut() = Some(devices);
+ self.begin_vsync_thread();
+ Ok(())
+ }
+
+ /// Stops vsync and releases the DirectX devices. No window may be open.
+ fn detach_gpu(&self) {
+ if let Some(stop) = self.vsync_stop.borrow_mut().take() {
+ // Not joined: the thread can be sending this thread a message. It exits after its
+ // next vsync, and drops its reference to the devices then.
+ stop.store(true, Ordering::Release);
+ }
+ if let Some(text_system) = &self.direct_write_text_system {
+ text_system.release_gpu();
+ }
+ self.inner.state.directx_devices.borrow_mut().take();
+ }
+
fn begin_vsync_thread(&self) {
let Some(directx_devices) = self.inner.state.directx_devices.borrow().clone() else {
return;
@@ -381,6 +437,8 @@ impl WindowsPlatform {
let Some(direct_write_text_system) = &self.direct_write_text_system else {
return;
};
+ let stop = Arc::new(AtomicBool::new(false));
+ *self.vsync_stop.borrow_mut() = Some(stop.clone());
let mut directx_device = directx_devices;
let platform_window: SafeHwnd = self.handle.into();
let validation_number = self.inner.validation_number;
@@ -395,6 +453,9 @@ impl WindowsPlatform {
loop {
let signal_source = vsync_provider.wait_for_vsync();
let signal_at = PlatformFrameSignal::capture(scheduler::Instant::now);
+ if stop.load(Ordering::Acquire) {
+ break;
+ }
if check_device_lost(&directx_device.device)
|| invalidate_devices.fetch_and(false, Ordering::Acquire)
{
@@ -530,10 +591,10 @@ impl Platform for WindowsPlatform {
}
fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
- on_finish_launching();
if !self.headless {
- self.begin_vsync_thread();
+ self.connect_initially();
}
+ on_finish_launching();
let mut msg = MSG::default();
unsafe {
@@ -559,6 +620,34 @@ impl Platform for WindowsPlatform {
.detach();
}
+ fn set_initial_windowing(&self, request: WindowingRequest) {
+ *self.initial_windowing.borrow_mut() = Some(request);
+ }
+
+ fn request_windowing(&self, request: WindowingRequest) -> Task<Result<()>> {
+ if self.headless {
+ return Task::ready(Err(anyhow!(
+ "a platform created headless can't switch windowing modes"
+ )));
+ }
+ let windowed = self.is_windowed();
+ Task::ready(match request {
+ WindowingRequest::Headless if !windowed => Err(anyhow!("already headless")),
+ WindowingRequest::Headless => {
+ self.detach_gpu();
+ Ok(())
+ }
+ WindowingRequest::Windowed(_) if windowed => Err(anyhow!("already windowed")),
+ WindowingRequest::Windowed(environment) => {
+ check_can_show_windows(&environment).and_then(|()| self.attach_gpu())
+ }
+ })
+ }
+
+ fn graphical_environment(&self) -> Option<GraphicalEnvironment> {
+ self.is_windowed().then(GraphicalEnvironment::detect)
+ }
+
fn restart(&self, binary_path: Option<PathBuf>, arguments: Vec<OsString>) {
let pid = std::process::id();
let Some(app_path) = binary_path.or(self.app_path().log_err()) else {
@@ -665,6 +754,9 @@ impl Platform for WindowsPlatform {
handle: AnyWindowHandle,
options: WindowParams,
) -> Result<Box<dyn PlatformWindow>> {
+ if !self.is_windowed() {
+ return Err(anyhow!("cannot open windows while headless"));
+ }
let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;
let handle = window.get_raw_handle();
self.raw_window_handles.write().push(TrackedWindow {
@@ -1261,8 +1353,11 @@ impl WindowsPlatformInner {
fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {
let directx_devices = lparam.0 as *const DirectXDevices;
let directx_devices = unsafe { &*directx_devices };
- self.state.directx_devices.borrow_mut().take();
- *self.state.directx_devices.borrow_mut() = Some(directx_devices.clone());
+ let mut current = self.state.directx_devices.borrow_mut();
+ // The platform may have switched to headless while the device was being recovered.
+ if current.is_some() {
+ *current = Some(directx_devices.clone());
+ }
Some(0)
}
@@ -1270,6 +1365,9 @@ impl WindowsPlatformInner {
impl Drop for WindowsPlatform {
fn drop(&mut self) {
+ if let Some(stop) = self.vsync_stop.borrow_mut().take() {
+ stop.store(true, Ordering::Release);
+ }
unsafe {
if let Some(notification) = self.suspend_resume_notification.borrow_mut().take() {
// SAFETY: notification was returned by RegisterSuspendResumeNotification.
@@ -1527,6 +1625,49 @@ fn check_device_lost(device: &ID3D11Device) -> bool {
}
}
+/// Checks that this process can show windows in the session `environment` names.
+fn check_can_show_windows(environment: &GraphicalEnvironment) -> Result<()> {
+ let current = GraphicalEnvironment::detect().session_id;
+ if let (Some(requested), Some(current)) = (environment.session_id, current)
+ && requested != current
+ {
+ return Err(anyhow!(
+ "windows can only be shown in this process's session ({current}), not session \
+ {requested}"
+ ));
+ }
+ if !is_window_station_visible() {
+ return Err(anyhow!(
+ "this process's window station is not interactive, so it can't show windows"
+ ));
+ }
+ Ok(())
+}
+
+/// Whether this process's window station has a visible desktop. A service's, or an SSH login's,
+/// doesn't.
+fn is_window_station_visible() -> bool {
+ use windows::Win32::System::StationsAndDesktops::{
+ GetProcessWindowStation, GetUserObjectInformationW, UOI_FLAGS, USEROBJECTFLAGS,
+ };
+
+ let Ok(station) = (unsafe { GetProcessWindowStation() }) else {
+ return false;
+ };
+ let mut flags = USEROBJECTFLAGS::default();
+ // SAFETY: `flags` is valid for writes of the size passed.
+ let result = unsafe {
+ GetUserObjectInformationW(
+ HANDLE(station.0),
+ UOI_FLAGS,
+ Some(&mut flags as *mut USEROBJECTFLAGS as *mut std::ffi::c_void),
+ std::mem::size_of::<USEROBJECTFLAGS>() as u32,
+ None,
+ )
+ };
+ result.is_ok() && flags.dwFlags & WSF_VISIBLE as u32 != 0
+}
+
fn handle_gpu_device_lost(
directx_devices: &mut DirectXDevices,
platform_window: HWND,