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: Add parent-anchored native popup windows (with wayland xdg_popup implementation only so far) (#60232)

Philipp Schaffrath546a16d64fa5
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index bad1feabb3b..eab072e470b 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -29,9 +29,7 @@ test-support = [
bench = ["test-support", "dep:criterion", "dep:hdrhistogram"]
inspector = ["gpui_macros/inspector"]
leak-detection = ["backtrace"]
-wayland = [
- "bitflags",
-]
+wayland = []
x11 = [
"scap?/x11",
]
@@ -51,7 +49,7 @@ accesskit.workspace = true
anyhow.workspace = true
async-task = "4.7"
backtrace = { workspace = true, optional = true }
-bitflags = { workspace = true, optional = true }
+bitflags.workspace = true
collections.workspace = true
criterion = { workspace = true, optional = true }
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
index 13fcbcee7a7..2a37d0b19b2 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
@@ -6,6 +6,9 @@ mod keystroke;
#[expect(missing_docs)]
pub mod layer_shell;
+/// Types for configuring parent-anchored popup windows such as menus, dropdowns and tooltips.
+pub mod popup;
+
#[cfg(any(test, feature = "bench"))]
mod bench_dispatcher;
@@ -1677,6 +1680,14 @@ pub enum WindowKind {
/// use sparingly!
PopUp,
+ /// A parent-anchored, platform-native popup window for menus, comboboxes, context menus and
+ /// tooltips. Unlike [`WindowKind::PopUp`], it is positioned relative to a parent window.
+ ///
+ /// The popup's size comes from [`WindowOptions::window_bounds`], whose origin is ignored.
+ /// See [`popup::PopupOptions`] for the placement options. Platforms without a native
+ /// implementation reject it with [`popup::PopupNotSupportedError`].
+ AnchoredPopup(popup::PopupOptions),
+
/// A floating window that appears on top of its parent window
Floating,
diff --git a/crates/gpui/src/platform/popup.rs b/crates/gpui/src/platform/popup.rs
new file mode 100644
index 00000000000..a1f8d7ea0d5
--- /dev/null
+++ b/crates/gpui/src/platform/popup.rs
@@ -0,0 +1,134 @@
+use bitflags::bitflags;
+use thiserror::Error;
+
+use crate::{AnyWindowHandle, Bounds, Pixels, Point};
+
+/// Options for a parent-anchored popup window such as a menu, dropdown, context menu or tooltip.
+///
+/// A popup is placed relative to an anchor rectangle on its parent window rather than at an
+/// absolute screen position. The platform resolves the final position, so this works both on
+/// systems where the compositor owns window placement (Wayland) and on platforms with absolute
+/// coordinates.
+///
+/// The popup's size comes from [`WindowOptions::window_bounds`](crate::WindowOptions), whose
+/// origin is ignored. All coordinates are in logical pixels.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PopupOptions {
+ /// The window the popup is anchored to.
+ pub parent: AnyWindowHandle,
+
+ /// The rectangle the popup is positioned relative to, in the parent window's coordinate
+ /// space (the same space element bounds are in). For example, a dropdown menu uses the
+ /// bounds of the button that opened it.
+ pub anchor_rect: Bounds<Pixels>,
+
+ /// Which point of [`Self::anchor_rect`] the popup is anchored to.
+ pub anchor: PopupAnchor,
+
+ /// The direction in which the popup extends away from the anchor point. A dropdown that
+ /// drops below its button anchors to [`PopupAnchor::BottomLeft`] with a gravity of
+ /// [`PopupGravity::BottomRight`] so it grows down and to the right.
+ pub gravity: PopupGravity,
+
+ /// How the platform may adjust the popup if the requested placement would put it off-screen.
+ pub constraint_adjustment: PopupConstraintAdjustment,
+
+ /// An additional offset applied to the popup after anchoring.
+ pub offset: Point<Pixels>,
+
+ /// Whether the popup should take an explicit input grab.
+ ///
+ /// Grabbing popups behave like menus: they take keyboard focus and are dismissed when the
+ /// user clicks outside of them or presses a dismissing key. Use it for menus and comboboxes,
+ /// not for tooltips or other passive popups.
+ ///
+ /// A grab must be requested while the triggering input is still active, in practice the
+ /// press of the mouse button that opens the popup. Open grabbing popups from a mouse-down
+ /// handler rather than a click handler, otherwise the grab is refused.
+ ///
+ /// Automatic dismissal only covers input aimed at other applications. A click elsewhere in
+ /// your own application still reaches it as usual, so closing the popup in that case is up
+ /// to you. Nested grabbing popups must be closed in the reverse order they were opened.
+ pub grab: bool,
+}
+
+/// The point of the anchor rectangle that a popup is anchored to.
+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
+pub enum PopupAnchor {
+ /// Anchor to the center of the anchor rectangle.
+ #[default]
+ Center,
+ /// Anchor to the center of the top edge.
+ Top,
+ /// Anchor to the center of the bottom edge.
+ Bottom,
+ /// Anchor to the center of the left edge.
+ Left,
+ /// Anchor to the center of the right edge.
+ Right,
+ /// Anchor to the top-left corner.
+ TopLeft,
+ /// Anchor to the bottom-left corner.
+ BottomLeft,
+ /// Anchor to the top-right corner.
+ TopRight,
+ /// Anchor to the bottom-right corner.
+ BottomRight,
+}
+
+/// The direction in which a popup extends away from its anchor point.
+///
+/// For instance, a gravity of [`PopupGravity::BottomRight`] places the popup below and to the
+/// right of the anchor point.
+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
+pub enum PopupGravity {
+ /// The popup is centered over the anchor point.
+ #[default]
+ Center,
+ /// The popup extends upwards from the anchor point.
+ Top,
+ /// The popup extends downwards from the anchor point.
+ Bottom,
+ /// The popup extends to the left of the anchor point.
+ Left,
+ /// The popup extends to the right of the anchor point.
+ Right,
+ /// The popup extends up and to the left of the anchor point.
+ TopLeft,
+ /// The popup extends down and to the left of the anchor point.
+ BottomLeft,
+ /// The popup extends up and to the right of the anchor point.
+ TopRight,
+ /// The popup extends down and to the right of the anchor point.
+ BottomRight,
+}
+
+bitflags! {
+ /// How a popup may be adjusted by the platform if the requested placement would put it
+ /// off-screen. If no flags are set, the popup is placed exactly as requested and may be
+ /// clipped.
+ #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
+ pub struct PopupConstraintAdjustment: u32 {
+ /// The popup may be slid horizontally to stay on-screen.
+ const SLIDE_X = 1;
+ /// The popup may be slid vertically to stay on-screen.
+ const SLIDE_Y = 2;
+ /// The popup's anchor and gravity may be flipped horizontally to stay on-screen.
+ const FLIP_X = 4;
+ /// The popup's anchor and gravity may be flipped vertically to stay on-screen.
+ const FLIP_Y = 8;
+ /// The popup may be shrunk horizontally to stay on-screen.
+ const RESIZE_X = 16;
+ /// The popup may be shrunk vertically to stay on-screen.
+ const RESIZE_Y = 32;
+ }
+}
+
+/// Returned when the current platform has no native popup implementation yet.
+///
+/// Native popups are separate from gpui's in-window popovers, which are drawn as elements inside
+/// an existing window. A caller that wants a popup on every platform should treat this error as
+/// a cue to fall back to that in-window rendering.
+#[derive(Debug, Error)]
+#[error("popups are not supported on this platform")]
+pub struct PopupNotSupportedError;
diff --git a/crates/gpui_linux/src/linux/wayland.rs b/crates/gpui_linux/src/linux/wayland.rs
index 3e90688d1bd..cbc962bcffe 100644
--- a/crates/gpui_linux/src/linux/wayland.rs
+++ b/crates/gpui_linux/src/linux/wayland.rs
@@ -2,6 +2,7 @@ mod client;
mod clipboard;
mod cursor;
mod display;
+mod popup;
mod serial;
mod window;
diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rs
index 256875bed1e..9522ebb8f0d 100644
--- a/crates/gpui_linux/src/linux/wayland/client.rs
+++ b/crates/gpui_linux/src/linux/wayland/client.rs
@@ -57,7 +57,9 @@ use wayland_protocols::xdg::activation::v1::client::{xdg_activation_token_v1, xd
use wayland_protocols::xdg::decoration::zv1::client::{
zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1,
};
-use wayland_protocols::xdg::shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base};
+use wayland_protocols::xdg::shell::client::{
+ xdg_popup, xdg_positioner, xdg_surface, xdg_toplevel, xdg_wm_base,
+};
use wayland_protocols::xdg::system_bell::v1::client::xdg_system_bell_v1;
use wayland_protocols::{
wp::cursor_shape::v1::client::{wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1},
@@ -96,7 +98,7 @@ use gpui::{
ForegroundExecutor, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ModifiersChangedEvent,
MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent, MouseUpEvent, NavigationDirection,
Pixels, PlatformDisplay, PlatformInput, PlatformKeyboardLayout, PlatformWindow, Point,
- ScrollDelta, ScrollWheelEvent, SharedString, Size, TouchPhase, WindowButtonLayout,
+ ScrollDelta, ScrollWheelEvent, SharedString, Size, TouchPhase, WindowButtonLayout, WindowKind,
WindowParams, point, profiler, px, size,
};
use gpui_wgpu::{CompositorGpuHint, GpuContext};
@@ -846,7 +848,29 @@ impl LinuxClient for WaylandClient {
) -> anyhow::Result<Box<dyn PlatformWindow>> {
let mut state = self.0.borrow_mut();
- let parent = state.keyboard_focused_window.clone();
+ // Popups name their parent explicitly. Other kinds are parented to the focused window.
+ let (parent, popup_grab) = match &params.kind {
+ WindowKind::AnchoredPopup(options) => {
+ let parent = state
+ .windows
+ .values()
+ .find(|window| window.handle() == options.parent)
+ .cloned()
+ .ok_or_else(|| anyhow::anyhow!("popup parent window not found"))?;
+ // A popup grab must reference a press event or the compositor declines it and
+ // immediately dismisses the popup, so use the most recent press serial, or no
+ // grab before any press.
+ let popup_grab = options.grab.then(|| {
+ let serial = state
+ .serial_tracker
+ .get(SerialKind::MousePress)
+ .max(state.serial_tracker.get(SerialKind::KeyPress));
+ (serial != 0).then(|| (serial, state.wl_seat.clone()))
+ });
+ (Some(parent), popup_grab.flatten())
+ }
+ _ => (state.keyboard_focused_window.clone(), None),
+ };
let target_output = params.display_id.and_then(|display_id| {
let target_protocol_id: u64 = display_id.into();
@@ -859,6 +883,7 @@ impl LinuxClient for WaylandClient {
let appearance = state.common.appearance;
let compositor_gpu = state.compositor_gpu.take();
+
let (window, surface_id) = WaylandWindow::new(
handle,
state.globals.clone(),
@@ -868,8 +893,10 @@ impl LinuxClient for WaylandClient {
params,
appearance,
parent,
+ popup_grab,
target_output,
)?;
+
if window.0.toplevel().is_some() {
state.consume_startup_activation_token(&window.0.surface());
}
@@ -1196,6 +1223,7 @@ delegate_noop!(WaylandClientStatePtr: ignore wl_region::WlRegion);
delegate_noop!(WaylandClientStatePtr: ignore wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1);
delegate_noop!(WaylandClientStatePtr: ignore zxdg_decoration_manager_v1::ZxdgDecorationManagerV1);
delegate_noop!(WaylandClientStatePtr: ignore zwlr_layer_shell_v1::ZwlrLayerShellV1);
+delegate_noop!(WaylandClientStatePtr: ignore xdg_positioner::XdgPositioner);
delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur_manager::OrgKdeKwinBlurManager);
delegate_noop!(WaylandClientStatePtr: ignore zwp_text_input_manager_v3::ZwpTextInputManagerV3);
delegate_noop!(WaylandClientStatePtr: ignore org_kde_kwin_blur::OrgKdeKwinBlur);
@@ -1359,6 +1387,31 @@ impl Dispatch<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1, ObjectId> for WaylandCl
drop(state);
let should_close = window.handle_layersurface_event(event);
+ if should_close {
+ // Close logic will be handled in drop_window()
+ window.close();
+ }
+ }
+}
+
+impl Dispatch<xdg_popup::XdgPopup, ObjectId> for WaylandClientStatePtr {
+ fn event(
+ this: &mut Self,
+ _: &xdg_popup::XdgPopup,
+ event: <xdg_popup::XdgPopup as Proxy>::Event,
+ surface_id: &ObjectId,
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ let client = this.get_client();
+ let mut state = client.borrow_mut();
+ let Some(window) = get_window(&mut state, surface_id) else {
+ return;
+ };
+
+ drop(state);
+ let should_close = window.handle_popup_event(event);
+
if should_close {
// The close logic will be handled in drop_window()
window.close();
@@ -1934,7 +1987,11 @@ impl Dispatch<wl_pointer::WlPointer, ()> for WaylandClientStatePtr {
state: WEnum::Value(button_state),
..
} => {
- state.serial_tracker.update(SerialKind::MousePress, serial);
+ // Record presses only. Requests referencing this serial (popup grabs,
+ // interactive moves) are declined when given a release serial.
+ if button_state == wl_pointer::ButtonState::Pressed {
+ state.serial_tracker.update(SerialKind::MousePress, serial);
+ }
let button = linux_button_to_gpui(button);
let Some(button) = button else { return };
if state.mouse_focused_window.is_none() {
diff --git a/crates/gpui_linux/src/linux/wayland/popup.rs b/crates/gpui_linux/src/linux/wayland/popup.rs
new file mode 100644
index 00000000000..4a15e78211b
--- /dev/null
+++ b/crates/gpui_linux/src/linux/wayland/popup.rs
@@ -0,0 +1,38 @@
+pub use gpui::popup::*;
+
+use wayland_protocols::xdg::shell::client::xdg_positioner;
+
+pub(crate) fn wayland_anchor(anchor: PopupAnchor) -> xdg_positioner::Anchor {
+ match anchor {
+ PopupAnchor::Center => xdg_positioner::Anchor::None,
+ PopupAnchor::Top => xdg_positioner::Anchor::Top,
+ PopupAnchor::Bottom => xdg_positioner::Anchor::Bottom,
+ PopupAnchor::Left => xdg_positioner::Anchor::Left,
+ PopupAnchor::Right => xdg_positioner::Anchor::Right,
+ PopupAnchor::TopLeft => xdg_positioner::Anchor::TopLeft,
+ PopupAnchor::BottomLeft => xdg_positioner::Anchor::BottomLeft,
+ PopupAnchor::TopRight => xdg_positioner::Anchor::TopRight,
+ PopupAnchor::BottomRight => xdg_positioner::Anchor::BottomRight,
+ }
+}
+
+pub(crate) fn wayland_gravity(gravity: PopupGravity) -> xdg_positioner::Gravity {
+ match gravity {
+ PopupGravity::Center => xdg_positioner::Gravity::None,
+ PopupGravity::Top => xdg_positioner::Gravity::Top,
+ PopupGravity::Bottom => xdg_positioner::Gravity::Bottom,
+ PopupGravity::Left => xdg_positioner::Gravity::Left,
+ PopupGravity::Right => xdg_positioner::Gravity::Right,
+ PopupGravity::TopLeft => xdg_positioner::Gravity::TopLeft,
+ PopupGravity::BottomLeft => xdg_positioner::Gravity::BottomLeft,
+ PopupGravity::TopRight => xdg_positioner::Gravity::TopRight,
+ PopupGravity::BottomRight => xdg_positioner::Gravity::BottomRight,
+ }
+}
+
+pub(crate) fn wayland_constraint_adjustment(
+ adjustment: PopupConstraintAdjustment,
+) -> xdg_positioner::ConstraintAdjustment {
+ // The flag values match the protocol bitfield, so the bits map across directly.
+ xdg_positioner::ConstraintAdjustment::from_bits_truncate(adjustment.bits())
+}
diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs
index 731569a025f..675602082bb 100644
--- a/crates/gpui_linux/src/linux/wayland/window.rs
+++ b/crates/gpui_linux/src/linux/wayland/window.rs
@@ -1,12 +1,12 @@
use std::{
- cell::{Ref, RefCell, RefMut},
+ cell::{Cell, Ref, RefCell, RefMut},
ffi::c_void,
ptr::NonNull,
rc::Rc,
sync::Arc,
};
-use collections::{FxHashSet, HashMap};
+use collections::{FxHashMap, HashMap};
use futures::channel::oneshot::Receiver;
use raw_window_handle as rwh;
@@ -14,10 +14,12 @@ use wayland_backend::client::ObjectId;
use wayland_client::WEnum;
use wayland_client::{
Proxy,
- protocol::{wl_output, wl_surface},
+ protocol::{wl_output, wl_seat, wl_surface},
};
use wayland_protocols::wp::viewporter::client::wp_viewport;
use wayland_protocols::xdg::decoration::zv1::client::zxdg_toplevel_decoration_v1;
+use wayland_protocols::xdg::shell::client::xdg_popup;
+use wayland_protocols::xdg::shell::client::xdg_positioner;
use wayland_protocols::xdg::shell::client::xdg_surface;
use wayland_protocols::xdg::shell::client::xdg_toplevel::{self};
use wayland_protocols::{
@@ -34,8 +36,8 @@ use gpui::{
PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, Scene, Size, Tiling,
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowControls,
- WindowDecorations, WindowKind, WindowParams, layer_shell::LayerShellNotSupportedError, px,
- size,
+ WindowDecorations, WindowKind, WindowParams, layer_shell::LayerShellNotSupportedError,
+ popup::PopupOptions, px, size,
};
use gpui_wgpu::{CompositorGpuHint, WgpuRenderer, WgpuSurfaceConfig, wgpu};
@@ -93,7 +95,9 @@ pub struct WaylandWindowState {
surface_state: WaylandSurfaceState,
acknowledged_first_configure: bool,
parent: Option<WaylandWindowStatePtr>,
- children: FxHashSet<ObjectId>,
+ /// Child surfaces mapped to whether they block this window's input (dialogs
+ /// block, popups don't). Children are closed before this window closes.
+ children: FxHashMap<ObjectId, bool>,
pub surface: wl_surface::WlSurface,
app_id: Option<String>,
appearance: WindowAppearance,
@@ -129,6 +133,7 @@ pub struct WaylandWindowState {
pub enum WaylandSurfaceState {
Xdg(WaylandXdgSurfaceState),
LayerShell(WaylandLayerSurfaceState),
+ Popup(WaylandPopupSurfaceState),
}
impl WaylandSurfaceState {
@@ -137,6 +142,7 @@ impl WaylandSurfaceState {
globals: &Globals,
params: &WindowParams,
parent: Option<WaylandWindowStatePtr>,
+ popup_grab: Option<(u32, wl_seat::WlSeat)>,
target_output: Option<wl_output::WlOutput>,
) -> anyhow::Result<Self> {
// For layer_shell windows, create a layer surface instead of an xdg surface
@@ -186,6 +192,54 @@ impl WaylandSurfaceState {
}));
}
+ if let WindowKind::AnchoredPopup(options) = &params.kind {
+ let Some(parent) = parent.as_ref() else {
+ return Err(anyhow::anyhow!("popup parent window not found"));
+ };
+
+ let positioner = build_popup_positioner(
+ globals,
+ options,
+ params.bounds.size,
+ parent.window_geometry(),
+ );
+
+ let xdg_surface = globals
+ .wm_base
+ .get_xdg_surface(&surface, &globals.qh, surface.id());
+
+ // A layer-shell parent takes a null xdg parent and is attached via the layer
+ // surface. Every other surface kind has an xdg_surface to parent to directly.
+ let xdg_popup = if let Some(parent_layer_surface) = parent.layer_surface() {
+ let xdg_popup = xdg_surface.get_popup(None, &positioner, &globals.qh, surface.id());
+ parent_layer_surface.get_popup(&xdg_popup);
+ xdg_popup
+ } else {
+ xdg_surface.get_popup(
+ parent.xdg_surface().as_ref(),
+ &positioner,
+ &globals.qh,
+ surface.id(),
+ )
+ };
+ positioner.destroy();
+
+ if let Some((serial, seat)) = popup_grab {
+ xdg_popup.grab(&seat, serial);
+ }
+
+ // Non-blocking: the parent keeps its input so it can dismiss the popup on
+ // clicks in its own window.
+ parent.add_child(surface.id(), false);
+
+ return Ok(WaylandSurfaceState::Popup(WaylandPopupSurfaceState {
+ xdg_surface,
+ xdg_popup,
+ options: options.clone(),
+ next_reposition_token: Cell::new(0),
+ }));
+ }
+
// All other WindowKinds result in a regular xdg surface
let xdg_surface = globals
.wm_base
@@ -206,7 +260,7 @@ impl WaylandSurfaceState {
});
if let Some(parent) = parent.as_ref() {
- parent.add_child(surface.id());
+ parent.add_child(surface.id(), true);
}
dialog
@@ -246,6 +300,65 @@ pub struct WaylandLayerSurfaceState {
layer_surface: zwlr_layer_surface_v1::ZwlrLayerSurfaceV1,
}
+pub struct WaylandPopupSurfaceState {
+ xdg_surface: xdg_surface::XdgSurface,
+ xdg_popup: xdg_popup::XdgPopup,
+ // Kept so the popup can be re-anchored via `xdg_popup.reposition` when resized.
+ options: PopupOptions,
+ next_reposition_token: Cell<u32>,
+}
+
+fn build_popup_positioner(
+ globals: &Globals,
+ options: &PopupOptions,
+ size: Size<Pixels>,
+ parent_geometry: Bounds<Pixels>,
+) -> xdg_positioner::XdgPositioner {
+ let positioner = globals.wm_base.create_positioner(&globals.qh, ());
+ // A zero or negative size is a protocol error.
+ positioner.set_size(
+ f32::from(size.width).max(1.0) as i32,
+ f32::from(size.height).max(1.0) as i32,
+ );
+
+ // The protocol wants the anchor rect relative to the parent's window geometry, while
+ // `options.anchor_rect` is in gpui window coordinates (surface-local). A rect extending
+ // outside the geometry or with a zero size is a protocol error, so translate, then clamp
+ // to at least one pixel inside the geometry, pulling the origin inward at the edges.
+ let anchor_rect = Bounds {
+ origin: options.anchor_rect.origin - parent_geometry.origin,
+ size: options.anchor_rect.size,
+ };
+ let one = Point::new(px(1.0), px(1.0));
+ let geometry_bottom_right: Point<Pixels> = parent_geometry.size.into();
+ let top_left = anchor_rect
+ .origin
+ .min(&(geometry_bottom_right - one))
+ .max(&Point::default());
+ let bottom_right = anchor_rect
+ .bottom_right()
+ .min(&geometry_bottom_right)
+ .max(&(top_left + one));
+ let anchor_rect = Bounds::from_corners(top_left, bottom_right);
+ positioner.set_anchor_rect(
+ f32::from(anchor_rect.origin.x) as i32,
+ f32::from(anchor_rect.origin.y) as i32,
+ f32::from(anchor_rect.size.width) as i32,
+ f32::from(anchor_rect.size.height) as i32,
+ );
+
+ positioner.set_anchor(super::popup::wayland_anchor(options.anchor));
+ positioner.set_gravity(super::popup::wayland_gravity(options.gravity));
+ positioner.set_constraint_adjustment(super::popup::wayland_constraint_adjustment(
+ options.constraint_adjustment,
+ ));
+ positioner.set_offset(
+ f32::from(options.offset.x) as i32,
+ f32::from(options.offset.y) as i32,
+ );
+ positioner
+}
+
impl WaylandSurfaceState {
fn ack_configure(&self, serial: u32) {
match self {
@@ -255,6 +368,9 @@ impl WaylandSurfaceState {
WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState { layer_surface, .. }) => {
layer_surface.ack_configure(serial);
}
+ WaylandSurfaceState::Popup(WaylandPopupSurfaceState { xdg_surface, .. }) => {
+ xdg_surface.ack_configure(serial);
+ }
}
}
@@ -274,6 +390,28 @@ impl WaylandSurfaceState {
}
}
+ fn xdg_surface(&self) -> Option<&xdg_surface::XdgSurface> {
+ match self {
+ WaylandSurfaceState::Xdg(WaylandXdgSurfaceState { xdg_surface, .. }) => {
+ Some(xdg_surface)
+ }
+ WaylandSurfaceState::Popup(WaylandPopupSurfaceState { xdg_surface, .. }) => {
+ Some(xdg_surface)
+ }
+ WaylandSurfaceState::LayerShell(_) => None,
+ }
+ }
+
+ fn layer_surface(&self) -> Option<&zwlr_layer_surface_v1::ZwlrLayerSurfaceV1> {
+ if let WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState { layer_surface, .. }) =
+ self
+ {
+ Some(layer_surface)
+ } else {
+ None
+ }
+ }
+
fn set_geometry(&self, x: i32, y: i32, width: i32, height: i32) {
match self {
WaylandSurfaceState::Xdg(WaylandXdgSurfaceState { xdg_surface, .. }) => {
@@ -283,6 +421,34 @@ impl WaylandSurfaceState {
// cannot set window position of a layer surface
layer_surface.set_size(width as u32, height as u32);
}
+ WaylandSurfaceState::Popup(WaylandPopupSurfaceState { xdg_surface, .. }) => {
+ xdg_surface.set_window_geometry(x, y, width, height);
+ }
+ }
+ }
+
+ // Re-anchors a mapped popup at a new size via `xdg_popup.reposition`. Repositioning an
+ // unmapped popup (before the first configure) is a protocol error.
+ fn reposition_popup(
+ &self,
+ globals: &Globals,
+ size: Size<Pixels>,
+ parent_geometry: Bounds<Pixels>,
+ ) {
+ if let WaylandSurfaceState::Popup(WaylandPopupSurfaceState {
+ xdg_popup,
+ options,
+ next_reposition_token,
+ ..
+ }) = self
+ && xdg_popup.version() >= xdg_popup::REQ_REPOSITION_SINCE
+ {
+ let token = next_reposition_token.get();
+ next_reposition_token.set(token.wrapping_add(1));
+
+ let positioner = build_popup_positioner(globals, options, size, parent_geometry);
+ xdg_popup.reposition(&positioner, token);
+ positioner.destroy();
}
}
@@ -307,6 +473,15 @@ impl WaylandSurfaceState {
WaylandSurfaceState::LayerShell(WaylandLayerSurfaceState { layer_surface }) => {
layer_surface.destroy();
}
+ WaylandSurfaceState::Popup(WaylandPopupSurfaceState {
+ xdg_surface,
+ xdg_popup,
+ ..
+ }) => {
+ // Role object before its xdg_surface, as with the toplevel above.
+ xdg_popup.destroy();
+ xdg_surface.destroy();
+ }
}
}
}
@@ -374,7 +549,7 @@ impl WaylandWindowState {
surface_state,
acknowledged_first_configure: false,
parent,
- children: FxHashSet::default(),
+ children: FxHashMap::default(),
surface,
app_id: options.app_id,
blur: None,
@@ -523,11 +698,18 @@ impl WaylandWindow {
params: WindowParams,
appearance: WindowAppearance,
parent: Option<WaylandWindowStatePtr>,
+ popup_grab: Option<(u32, wl_seat::WlSeat)>,
target_output: Option<wl_output::WlOutput>,
) -> anyhow::Result<(Self, ObjectId)> {
let surface = globals.compositor.create_surface(&globals.qh, ());
- let surface_state =
- WaylandSurfaceState::new(&surface, &globals, &params, parent.clone(), target_output)?;
+ let surface_state = WaylandSurfaceState::new(
+ &surface,
+ &globals,
+ &params,
+ parent.clone(),
+ popup_grab,
+ target_output,
+ )?;
if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
fractional_scale_manager.get_fractional_scale(&surface, &globals.qh, surface.id());
@@ -575,18 +757,39 @@ impl WaylandWindowStatePtr {
self.state.borrow().surface_state.toplevel().cloned()
}
+ /// The `xdg_surface` backing this window, if it has one. Used to anchor child popups.
+ pub fn xdg_surface(&self) -> Option<xdg_surface::XdgSurface> {
+ self.state.borrow().surface_state.xdg_surface().cloned()
+ }
+
+ /// The layer-shell surface backing this window, if it is one. Used to anchor child popups.
+ pub fn layer_surface(&self) -> Option<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1> {
+ self.state.borrow().surface_state.layer_surface().cloned()
+ }
+
+ /// This window's xdg window geometry in surface-local coordinates. Child popup anchor
+ /// rectangles are relative to it, while gpui coordinates are surface-local.
+ pub fn window_geometry(&self) -> Bounds<Pixels> {
+ let state = self.state.borrow();
+ inset_by_tiling(
+ state.bounds.map_origin(|_| px(0.0)),
+ state.inset(),
+ state.tiling,
+ )
+ }
+
pub fn ptr_eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.state, &other.state)
}
- pub fn add_child(&self, child: ObjectId) {
+ pub fn add_child(&self, child: ObjectId, blocking: bool) {
let mut state = self.state.borrow_mut();
- state.children.insert(child);
+ state.children.insert(child, blocking);
}
pub fn is_blocked(&self) -> bool {
let state = self.state.borrow();
- !state.children.is_empty()
+ state.children.values().any(|&blocking| blocking)
}
pub fn frame(&self) {
@@ -889,6 +1092,35 @@ impl WaylandWindowStatePtr {
}
}
+ // Returns `true` if the popup should be closed.
+ pub fn handle_popup_event(&self, event: xdg_popup::Event) -> bool {
+ match event {
+ // Only the size is needed, the position is the compositor's. The following
+ // xdg_surface.configure applies the change.
+ xdg_popup::Event::Configure { width, height, .. } => {
+ let size = if width <= 0 || height <= 0 {
+ None
+ } else {
+ Some(size(px(width as f32), px(height as f32)))
+ };
+
+ self.state.borrow_mut().in_progress_configure = Some(InProgressConfigure {
+ size,
+ fullscreen: false,
+ maximized: false,
+ resizing: false,
+ tiling: Tiling::default(),
+ });
+
+ false
+ }
+ xdg_popup::Event::PopupDone => true,
+ // Precedes the reposition's Configure, which does the work. The token is not needed.
+ xdg_popup::Event::Repositioned { .. } => false,
+ _ => false,
+ }
+ }
+
#[allow(clippy::mutable_key_type)]
pub fn handle_surface_event(
&self,
@@ -1025,8 +1257,7 @@ impl WaylandWindowStatePtr {
pub fn close(&self) {
let state = self.state.borrow();
let client = state.client.get_client();
- #[allow(clippy::mutable_key_type)]
- let children = state.children.clone();
+ let children = state.children.keys().cloned().collect::<Vec<_>>();
drop(state);
for child in children {
@@ -1192,6 +1423,23 @@ impl PlatformWindow for WaylandWindow {
let state = self.borrow();
let state_ptr = self.0.clone();
+ // A popup's placement is the compositor's, so a resize re-runs the positioner and the
+ // configure reply drives the buffer resize. Before the first configure the popup is
+ // unmapped and cannot reposition, but the initial positioner already carries the size.
+ if matches!(state.surface_state, WaylandSurfaceState::Popup(_)) {
+ if state.acknowledged_first_configure {
+ let parent_geometry = state
+ .parent
+ .as_ref()
+ .map(|parent| parent.window_geometry())
+ .unwrap_or_default();
+ state
+ .surface_state
+ .reposition_popup(&state.globals, size, parent_geometry);
+ }
+ return;
+ }
+
// Keep window geometry consistent with configure handling. On Wayland, window geometry is
// surface-local: resizing should not attempt to translate the window; the compositor
// controls placement. We also account for client-side decoration insets and tiling.
diff --git a/crates/gpui_linux/src/linux/x11/window.rs b/crates/gpui_linux/src/linux/x11/window.rs
index d2edb72408b..a459ed03b5d 100644
--- a/crates/gpui_linux/src/linux/x11/window.rs
+++ b/crates/gpui_linux/src/linux/x11/window.rs
@@ -7,7 +7,7 @@ use gpui::{
Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
Point, PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, ScaledPixels, Scene, Size,
Tiling, WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea,
- WindowDecorations, WindowKind, WindowParams, px,
+ WindowDecorations, WindowKind, WindowParams, popup::PopupNotSupportedError, px,
};
use gpui_wgpu::{CompositorGpuHint, WgpuRenderer, WgpuSurfaceConfig};
@@ -428,6 +428,12 @@ impl X11WindowState {
supports_xinput_gestures: bool,
is_bgr: bool,
) -> anyhow::Result<Self> {
+ // Native popups are not implemented on X11 yet. Rejecting lets callers fall back to
+ // gpui's in-window popovers.
+ if let WindowKind::AnchoredPopup(_) = params.kind {
+ return Err(PopupNotSupportedError.into());
+ }
+
let x_screen_index = params
.display_id
.map_or(x_main_screen_index, |did| u64::from(did) as usize);
diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
index 8266cade4d2..eed9e90bcd3 100644
--- a/crates/gpui_macos/src/platform.rs
+++ b/crates/gpui_macos/src/platform.rs
@@ -31,7 +31,8 @@ use gpui::{
Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform,
PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
- PlatformWindow, Result, SystemMenuType, Task, ThermalState, WindowAppearance, WindowParams,
+ PlatformWindow, Result, SystemMenuType, Task, ThermalState, WindowAppearance, WindowKind,
+ WindowParams, popup::PopupNotSupportedError,
};
use gpui_util::{ResultExt, new_std_command};
use itertools::Itertools;
@@ -640,6 +641,12 @@ impl Platform for MacPlatform {
handle: AnyWindowHandle,
options: WindowParams,
) -> Result<Box<dyn PlatformWindow>> {
+ // Native popups are not implemented on macOS yet. Rejecting lets callers fall back to
+ // gpui's in-window popovers.
+ if let WindowKind::AnchoredPopup(_) = options.kind {
+ return Err(PopupNotSupportedError.into());
+ }
+
let (cursor_visible, foreground_executor, background_executor, renderer_context) = {
let guard = self.0.lock();
(
diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs
index d3d87608253..6221b141610 100644
--- a/crates/gpui_macos/src/window.rs
+++ b/crates/gpui_macos/src/window.rs
@@ -795,7 +795,9 @@ impl MacWindow {
WindowKind::Normal => {
msg_send![WINDOW_CLASS, alloc]
}
- WindowKind::PopUp => {
+ // `AnchoredPopup` is rejected in `MacPlatform::open_window`, grouped here only
+ // for exhaustiveness.
+ WindowKind::PopUp | WindowKind::AnchoredPopup(_) => {
style_mask |= NSWindowStyleMaskNonactivatingPanel;
msg_send![PANEL_CLASS, alloc]
}
@@ -988,7 +990,9 @@ impl MacWindow {
let _: () = msg_send![native_window, setTabbingIdentifier:nil];
}
}
- WindowKind::PopUp => {
+ // `AnchoredPopup` is rejected in `MacPlatform::open_window`, grouped here only
+ // for exhaustiveness.
+ WindowKind::PopUp | WindowKind::AnchoredPopup(_) => {
// Use a tracking area to allow receiving MouseMoved events even when
// the window or application aren't active, which is often the case
// e.g. for notification windows.
diff --git a/crates/gpui_web/src/platform.rs b/crates/gpui_web/src/platform.rs
index fecc39f368d..c39723ea5b2 100644
--- a/crates/gpui_web/src/platform.rs
+++ b/crates/gpui_web/src/platform.rs
@@ -8,7 +8,7 @@ use gpui::{
Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DummyKeyboardMapper,
ForegroundExecutor, Keymap, Menu, MenuItem, PathPromptOptions, Platform, PlatformDisplay,
PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem, PlatformWindow, Task,
- ThermalState, WindowAppearance, WindowParams,
+ ThermalState, WindowAppearance, WindowKind, WindowParams, popup::PopupNotSupportedError,
};
use gpui_wgpu::WgpuContext;
use std::{
@@ -166,6 +166,12 @@ impl Platform for WebPlatform {
handle: AnyWindowHandle,
params: WindowParams,
) -> anyhow::Result<Box<dyn PlatformWindow>> {
+ // Native popups are not implemented on the web yet. Rejecting lets callers fall back to
+ // gpui's in-window popovers.
+ if let WindowKind::AnchoredPopup(_) = params.kind {
+ return Err(PopupNotSupportedError.into());
+ }
+
let context_ref = self.wgpu_context.borrow();
let context = context_ref.as_ref().ok_or_else(|| {
anyhow::anyhow!("WebGPU context not initialized. Was Platform::run() called?")
diff --git a/crates/gpui_windows/src/window.rs b/crates/gpui_windows/src/window.rs
index 547ee7a9dde..76075a66b1c 100644
--- a/crates/gpui_windows/src/window.rs
+++ b/crates/gpui_windows/src/window.rs
@@ -411,6 +411,12 @@ impl WindowsWindow {
params: WindowParams,
creation_info: WindowCreationInfo,
) -> Result<Self> {
+ // Native popups are not implemented on Windows yet. Rejecting lets callers fall back to
+ // gpui's in-window popovers.
+ if let WindowKind::AnchoredPopup(_) = params.kind {
+ return Err(popup::PopupNotSupportedError.into());
+ }
+
let WindowCreationInfo {
icon,
executor,