use std::{
any::Any,
cell::RefCell,
num::NonZeroU32,
rc::{Rc, Weak},
};
use anyhow::{Context as _, anyhow};
use collections::{FxHashMap, FxHashSet};
use gpui::{
Bounds, ComposedScene, CompositionSurfaceId, DevicePixels, PlatformCompositionSurface,
PlatformCompositionSurfaceContent, PlatformSurfaceAttachment, PlatformWindow, Point, Scene,
Size,
};
use gpui_util::ResultExt as _;
use gpui_wgpu::{WgpuRenderer, WgpuSurfaceConfig, wgpu};
use raw_window_handle as rwh;
use x11rb::{
connection::{Connection as _, RequestConnection as _},
protocol::{
shape::{self, ConnectionExt as _},
xinput::{self, ConnectionExt as _},
xproto::{self, ConnectionExt as _},
},
xcb_ffi::XCBConnection,
};
use crate::linux::{
X11Window, X11WindowStatePtr, XINPUT_ALL_DEVICE_GROUPS, check_reply, get_reply, xcb_flush,
};
pub(crate) struct Composition(Rc<RefCell<X11Composition>>);
impl Composition {
pub(crate) fn new(
xcb: &Rc<XCBConnection>,
x_window: xproto::Window,
depth: u8,
visual_id: u32,
) -> Self {
Self(Rc::new(RefCell::new(X11Composition {
xcb: xcb.clone(),
x_window,
depth,
visual_id,
base_surface: None,
native_surfaces: Vec::new(),
order: Vec::new(),
occluders: FxHashMap::default(),
overlay: Overlay::Unknown,
input_windows: Vec::new(),
})))
}
pub(crate) fn destroy(&self) {
self.0.borrow_mut().destroy();
}
}
struct X11Composition {
xcb: Rc<XCBConnection>,
x_window: xproto::Window,
depth: u8,
visual_id: u32,
base_surface: Option<CompositionSurfaceId>,
native_surfaces: Vec<Weak<RefCell<X11NativeSurfaceState>>>,
order: Vec<PlatformCompositionSurface>,
occluders: FxHashMap<CompositionSurfaceId, Vec<Bounds<DevicePixels>>>,
overlay: Overlay,
input_windows: Vec<xproto::Window>,
}
struct X11NativeSurfaceState {
xcb: Rc<XCBConnection>,
x_window: xproto::Window,
parent_window: xproto::Window,
bounds: Bounds<DevicePixels>,
parent_origin: Point<DevicePixels>,
visible: bool,
mapped: bool,
occluders: Vec<Bounds<DevicePixels>>,
applied_shape: Option<(Bounds<DevicePixels>, Vec<Bounds<DevicePixels>>)>,
destroyed: bool,
}
impl X11NativeSurfaceState {
fn apply(&mut self) -> anyhow::Result<()> {
if self.destroyed {
return Ok(());
}
let origin = self.bounds.origin - self.parent_origin;
check_reply(
|| "X11 ConfigureWindow for a native surface failed.",
self.xcb.configure_window(
self.x_window,
&xproto::ConfigureWindowAux::new()
.x(origin.x.0)
.y(origin.y.0)
.width(self.bounds.size.width.0.max(1) as u32)
.height(self.bounds.size.height.0.max(1) as u32),
),
)?;
self.apply_shape()?;
let should_map = self.visible && !self.bounds.is_empty();
if should_map != self.mapped {
if should_map {
check_reply(
|| "X11 MapWindow for a native surface failed.",
self.xcb.map_window(self.x_window),
)?;
} else {
check_reply(
|| "X11 UnmapWindow for a native surface failed.",
self.xcb.unmap_window(self.x_window),
)?;
}
self.mapped = should_map;
}
xcb_flush(&self.xcb);
Ok(())
}
fn apply_shape(&mut self) -> anyhow::Result<()> {
let local_bounds = Bounds::new(Point::default(), self.bounds.size);
let cutouts = self
.occluders
.iter()
.map(|occluder| {
let occluder = Bounds::new(occluder.origin - self.bounds.origin, occluder.size);
occluder.intersect(&local_bounds)
})
.filter(|occluder| !occluder.is_empty())
.collect::<Vec<_>>();
let shape = (self.bounds, cutouts);
if self.applied_shape.as_ref() == Some(&shape) {
return Ok(());
}
let (_, cutouts) = &shape;
if cutouts.is_empty() {
check_reply(
|| "X11 ShapeMask reset for a native surface failed.",
self.xcb.shape_mask(
shape::SO::SET,
shape::SK::BOUNDING,
self.x_window,
0,
0,
x11rb::NONE,
),
)?;
} else {
check_reply(
|| "X11 ShapeRectangles for a native surface failed.",
self.xcb.shape_rectangles(
shape::SO::SET,
shape::SK::BOUNDING,
xproto::ClipOrdering::UNSORTED,
self.x_window,
0,
0,
&[x11_rectangle(local_bounds)],
),
)?;
check_reply(
|| "X11 ShapeRectangles cutout for a native surface failed.",
self.xcb.shape_rectangles(
shape::SO::SUBTRACT,
shape::SK::BOUNDING,
xproto::ClipOrdering::UNSORTED,
self.x_window,
0,
0,
&cutouts
.iter()
.copied()
.map(x11_rectangle)
.collect::<Vec<_>>(),
),
)?;
}
self.applied_shape = Some(shape);
Ok(())
}
fn destroy(&mut self) {
INPUT_WINDOWS.with(|windows| windows.borrow_mut().remove(&self.x_window));
if std::mem::replace(&mut self.destroyed, true) {
return;
}
check_reply(
|| "X11 DestroyWindow for a native surface failed.",
self.xcb.destroy_window(self.x_window),
)
.log_err();
xcb_flush(&self.xcb);
}
}
fn x11_rectangle(bounds: Bounds<DevicePixels>) -> xproto::Rectangle {
xproto::Rectangle {
x: bounds.origin.x.0.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
y: bounds.origin.y.0.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
width: bounds.size.width.0.clamp(0, u16::MAX as i32) as u16,
height: bounds.size.height.0.clamp(0, u16::MAX as i32) as u16,
}
}
fn scene_occluders(scene: &Scene, opaque_only: bool) -> Vec<Bounds<DevicePixels>> {
super::occluders::scene_occluders(scene, opaque_only)
}
struct X11NativeSurface {
state: Rc<RefCell<X11NativeSurfaceState>>,
visual_id: u32,
}
impl PlatformSurfaceAttachment for X11NativeSurface {
fn set_bounds(&self, bounds: Bounds<DevicePixels>) -> anyhow::Result<()> {
let mut state = self.state.borrow_mut();
state.bounds = bounds;
state.apply()
}
fn bounds(&self) -> Bounds<DevicePixels> {
self.state.borrow().bounds
}
fn set_parent_origin(&self, origin: Point<DevicePixels>) -> anyhow::Result<()> {
let mut state = self.state.borrow_mut();
state.parent_origin = origin;
state.apply()
}
fn set_visible(&self, visible: bool) -> anyhow::Result<()> {
let mut state = self.state.borrow_mut();
state.visible = visible;
state.apply()
}
fn platform_handle(&self) -> anyhow::Result<Box<dyn Any>> {
let window = NonZeroU32::new(self.state.borrow().x_window)
.context("native surface has no X11 window")?;
let mut handle = rwh::XcbWindowHandle::new(window);
handle.visual_id = NonZeroU32::new(self.visual_id);
Ok(Box::new(rwh::RawWindowHandle::Xcb(handle)))
}
}
impl Drop for X11NativeSurface {
fn drop(&mut self) {
self.state.borrow_mut().destroy();
}
}
impl X11Composition {
fn create_native_surface(&mut self) -> anyhow::Result<Rc<RefCell<X11NativeSurfaceState>>> {
let window = self.xcb.generate_id()?;
check_reply(
|| "X11 CreateWindow for a native surface failed.",
self.xcb.create_window(
self.depth,
window,
self.x_window,
0,
0,
1,
1,
0,
xproto::WindowClass::INPUT_OUTPUT,
self.visual_id,
&xproto::CreateWindowAux::new(),
),
)?;
let selected = check_reply(
|| "X11 XiSelectEvents for a native surface failed.",
self.xcb.xinput_xi_select_events(
window,
&[xinput::EventMask {
deviceid: XINPUT_ALL_DEVICE_GROUPS,
mask: vec![
xinput::XIEventMask::MOTION
| xinput::XIEventMask::ENTER
| xinput::XIEventMask::LEAVE
| xinput::XIEventMask::BUTTON_PRESS
| xinput::XIEventMask::BUTTON_RELEASE,
],
}],
),
);
if let Err(error) = selected {
check_reply(
|| "X11 DestroyWindow for a native surface failed.",
self.xcb.destroy_window(window),
)
.log_err();
return Err(error);
}
xcb_flush(&self.xcb);
let state = Rc::new(RefCell::new(X11NativeSurfaceState {
xcb: self.xcb.clone(),
x_window: window,
parent_window: self.x_window,
bounds: Bounds::default(),
parent_origin: Point::default(),
visible: true,
mapped: false,
occluders: Vec::new(),
applied_shape: None,
destroyed: false,
}));
self.native_surfaces.push(Rc::downgrade(&state));
Ok(state)
}
fn native_surface(
&mut self,
attachment: &dyn PlatformSurfaceAttachment,
) -> anyhow::Result<Rc<RefCell<X11NativeSurfaceState>>> {
let handle = attachment
.platform_handle()?
.downcast::<rwh::RawWindowHandle>()
.map_err(|_| anyhow!("native surface is not backed by an X11 window"))?;
let rwh::RawWindowHandle::Xcb(handle) = *handle else {
anyhow::bail!("native surface is not backed by an X11 window");
};
self.native_surfaces
.retain(|surface| surface.strong_count() > 0);
self.native_surfaces
.iter()
.filter_map(Weak::upgrade)
.find(|surface| surface.borrow().x_window == handle.window.get())
.context("native surface belongs to another window")
}
fn apply_order(&mut self) -> anyhow::Result<()> {
let base = self
.base_surface
.context("composition has no GPUI base surface")?;
let order = self.order.clone();
let mut native_states = FxHashMap::default();
for surface in &order {
if let PlatformCompositionSurfaceContent::Native(attachment)
| PlatformCompositionSurfaceContent::ExternalGpu(attachment) = &surface.content
{
native_states.insert(surface.id, self.native_surface(attachment.as_ref())?);
}
}
let mut origins = FxHashMap::default();
for surface in &order {
origins.insert(surface.id, surface.window_origin);
}
origins.insert(base, Point::default());
for (index, surface) in order.iter().enumerate() {
let Some(state) = native_states.get(&surface.id) else {
continue;
};
let (parent_window, parent_origin) = surface
.parent
.and_then(|parent| {
native_states.get(&parent).map(|parent_state| {
(
parent_state.borrow().x_window,
origins.get(&parent).copied().unwrap_or_default(),
)
})
})
.unwrap_or((self.x_window, Point::default()));
let occluders = order[index + 1..]
.iter()
.filter(|above| above.id != base)
.filter_map(|above| self.occluders.get(&above.id))
.flatten()
.copied()
.collect::<Vec<_>>();
let mut state = state.borrow_mut();
if state.parent_window != parent_window {
check_reply(
|| "X11 ReparentWindow for a native surface failed.",
self.xcb
.reparent_window(state.x_window, parent_window, 0, 0),
)?;
state.parent_window = parent_window;
state.mapped = false;
}
state.parent_origin = parent_origin;
if let Some(bounds) = surface.window_bounds {
state.bounds = bounds;
}
state.occluders = occluders;
check_reply(
|| "X11 ConfigureWindow stacking for a native surface failed.",
self.xcb.configure_window(
state.x_window,
&xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE),
),
)?;
state.apply()?;
}
Ok(())
}
fn destroy(&mut self) {
INPUT_WINDOWS.with(|windows| {
let mut windows = windows.borrow_mut();
for id in self.input_windows.drain(..) {
windows.remove(&id);
}
});
for surface in self
.native_surfaces
.drain(..)
.filter_map(|surface| surface.upgrade())
{
surface.borrow_mut().destroy();
}
self.order.clear();
self.occluders.clear();
self.base_surface = None;
if let Overlay::Supported {
colormap,
window,
spare_renderer,
..
} = std::mem::replace(&mut self.overlay, Overlay::Unknown)
{
for mut renderer in window
.map(|window| window.destroy(&self.xcb))
.into_iter()
.chain(spare_renderer)
{
renderer.destroy();
}
check_reply(
|| "X11 FreeColormap for the overlay window failed.",
self.xcb.free_colormap(colormap),
)
.log_err();
xcb_flush(&self.xcb);
}
}
fn surfaces_above_native(&self) -> FxHashSet<CompositionSurfaceId> {
let Some(first_native) = self.order.iter().position(|surface| {
matches!(
surface.content,
PlatformCompositionSurfaceContent::Native(_)
| PlatformCompositionSurfaceContent::ExternalGpu(_)
)
}) else {
return FxHashSet::default();
};
self.order[first_native + 1..]
.iter()
.filter(|surface| matches!(surface.content, PlatformCompositionSurfaceContent::Gpui))
.map(|surface| surface.id)
.collect()
}
fn overlay_supported(&mut self) -> bool {
if matches!(self.overlay, Overlay::Unknown) {
self.overlay = match self.detect_overlay_support() {
Ok(Some((root, colormap))) => Overlay::Supported {
root,
colormap,
window: None,
spare_renderer: None,
},
Ok(None) => Overlay::Unsupported,
Err(error) => {
log::warn!("X11 composition overlay window unavailable: {error:#}");
Overlay::Unsupported
}
};
}
matches!(self.overlay, Overlay::Supported { .. })
}
fn detect_overlay_support(&self) -> anyhow::Result<Option<(xproto::Window, xproto::Colormap)>> {
if self.depth != 32 {
return Ok(None);
}
let root = get_reply(
|| "X11 GetGeometry for the composition window failed.",
self.xcb.get_geometry(self.x_window),
)?
.root;
let screen = self
.xcb
.setup()
.roots
.iter()
.position(|screen| screen.root == root)
.context("composition window is on an unknown screen")?;
let composited = self
.xcb
.extension_information("XWAYLAND")
.context("X11 QueryExtension for XWAYLAND failed")?
.is_some()
|| {
let atom = get_reply(
|| "X11 InternAtom for the compositing manager selection failed.",
self.xcb
.intern_atom(false, format!("_NET_WM_CM_S{screen}").as_bytes()),
)?
.atom;
get_reply(
|| "X11 GetSelectionOwner for the compositing manager failed.",
self.xcb.get_selection_owner(atom),
)?
.owner
!= x11rb::NONE
};
if !composited {
return Ok(None);
}
let colormap = self.xcb.generate_id()?;
check_reply(
|| "X11 CreateColormap for the overlay window failed.",
self.xcb
.create_colormap(xproto::ColormapAlloc::NONE, colormap, root, self.visual_id),
)?;
Ok(Some((root, colormap)))
}
fn draw_overlay(
&mut self,
window: &X11Window,
scene: &Scene,
input: Vec<Bounds<DevicePixels>>,
) -> anyhow::Result<()> {
let Overlay::Supported {
root,
colormap,
window: overlay,
spare_renderer,
} = &mut self.overlay
else {
return Ok(());
};
if scene.is_empty() && input.is_empty() {
if let Some(overlay) = overlay.take() {
*spare_renderer = Some(overlay.destroy(&self.xcb));
xcb_flush(&self.xcb);
}
return Ok(());
}
let state = window.0.state.borrow();
let Some(window_renderer) = state.renderer.as_ref() else {
return Ok(());
};
if window_renderer.device_lost() {
return Ok(());
}
let size = window_renderer.viewport_size();
if overlay
.as_ref()
.is_some_and(|overlay| overlay.renderer.device_lost())
&& let Some(lost) = overlay.take()
{
lost.destroy(&self.xcb).destroy();
}
if spare_renderer
.as_ref()
.is_some_and(|renderer| renderer.device_lost())
&& let Some(mut lost) = spare_renderer.take()
{
lost.destroy();
}
let overlay = match overlay {
Some(overlay) => overlay,
None => {
let created = OverlayWindow::new(
&self.xcb,
window_renderer,
spare_renderer.take(),
self.x_window,
*root,
*colormap,
self.depth,
self.visual_id,
size,
)?;
INPUT_WINDOWS.with(|windows| {
windows.borrow_mut().insert(
created.x_window,
InputWindow {
window: window.0.clone(),
native: None,
},
)
});
overlay.insert(created)
}
};
drop(state);
let origin = get_reply(
|| "X11 TranslateCoordinates for the overlay window failed.",
self.xcb.translate_coordinates(self.x_window, *root, 0, 0),
)?;
overlay.set_geometry(
&self.xcb,
Point::new(
DevicePixels(origin.dst_x.into()),
DevicePixels(origin.dst_y.into()),
),
size,
)?;
overlay.set_input(&self.xcb, input)?;
overlay.map(&self.xcb)?;
overlay.raise_above(&self.xcb, self.x_window);
overlay.renderer.draw(scene);
xcb_flush(&self.xcb);
Ok(())
}
fn hide_overlay(&mut self) {
if let Overlay::Supported {
window,
spare_renderer,
..
} = &mut self.overlay
&& let Some(overlay) = window.take()
{
*spare_renderer = Some(overlay.destroy(&self.xcb));
xcb_flush(&self.xcb);
}
}
}
thread_local! {
static INPUT_WINDOWS: RefCell<FxHashMap<xproto::Window, InputWindow>> =
RefCell::default();
}
struct InputWindow {
window: X11WindowStatePtr,
native: Option<Weak<dyn PlatformSurfaceAttachment>>,
}
pub(crate) fn input_window(x_window: xproto::Window) -> Option<X11WindowStatePtr> {
INPUT_WINDOWS.with(|windows| {
windows
.borrow()
.get(&x_window)
.filter(|input| input.native.is_none())
.map(|input| input.window.clone())
})
}
pub(crate) fn pointer_window(x_window: xproto::Window) -> Option<X11WindowStatePtr> {
INPUT_WINDOWS.with(|windows| {
let windows = windows.borrow();
let input = windows.get(&x_window)?;
if let Some(native) = &input.native {
native.upgrade()?;
}
Some(input.window.clone())
})
}
pub(crate) fn pointer_window_id(x_window: xproto::Window) -> xproto::Window {
pointer_window(x_window).map_or(x_window, |window| window.x_window)
}
pub(crate) fn pointer_position(
x_window: xproto::Window,
position: Point<gpui::Pixels>,
scale: f32,
) -> Point<gpui::Pixels> {
let native = INPUT_WINDOWS.with(|windows| {
windows
.borrow()
.get(&x_window)
.and_then(|input| input.native.clone())
});
native
.and_then(|native| native.upgrade())
.map_or(position, |native| {
position + native.bounds().to_pixels(scale).origin
})
}
enum Overlay {
Unknown,
Unsupported,
Supported {
root: xproto::Window,
colormap: xproto::Colormap,
window: Option<OverlayWindow>,
spare_renderer: Option<WgpuRenderer>,
},
}
struct OverlayWindow {
x_window: xproto::Window,
renderer: WgpuRenderer,
origin: Point<DevicePixels>,
size: Size<DevicePixels>,
input: Option<Vec<Bounds<DevicePixels>>>,
mapped: bool,
}
impl OverlayWindow {
fn new(
xcb: &Rc<XCBConnection>,
window_renderer: &WgpuRenderer,
spare_renderer: Option<WgpuRenderer>,
parent: xproto::Window,
root: xproto::Window,
colormap: xproto::Colormap,
depth: u8,
visual_id: u32,
size: Size<DevicePixels>,
) -> anyhow::Result<Self> {
let x_window = xcb.generate_id()?;
check_reply(
|| "X11 CreateWindow for the overlay window failed.",
xcb.create_window(
depth,
x_window,
root,
0,
0,
size.width.0.max(1) as u16,
size.height.0.max(1) as u16,
0,
xproto::WindowClass::INPUT_OUTPUT,
visual_id,
&xproto::CreateWindowAux::new()
.background_pixel(0)
.border_pixel(0)
.colormap(colormap)
.override_redirect(1),
),
)?;
let mut overlay = Self {
x_window,
renderer: match Self::create_renderer(
xcb,
window_renderer,
spare_renderer,
x_window,
visual_id,
size,
) {
Ok(renderer) => renderer,
Err(error) => {
check_reply(
|| "X11 DestroyWindow for the overlay window failed.",
xcb.destroy_window(x_window),
)
.log_err();
return Err(error);
}
},
origin: Point::default(),
size,
input: None,
mapped: false,
};
overlay.set_popup_hints(xcb, parent)?;
overlay.set_input(xcb, Vec::new())?;
check_reply(
|| "X11 XiSelectEvents for the overlay window failed.",
xcb.xinput_xi_select_events(
x_window,
&[xinput::EventMask {
deviceid: XINPUT_ALL_DEVICE_GROUPS,
mask: vec![
xinput::XIEventMask::MOTION
| xinput::XIEventMask::BUTTON_PRESS
| xinput::XIEventMask::BUTTON_RELEASE
| xinput::XIEventMask::ENTER
| xinput::XIEventMask::LEAVE,
],
}],
),
)?;
Ok(overlay)
}
fn set_popup_hints(&self, xcb: &XCBConnection, parent: xproto::Window) -> anyhow::Result<()> {
use x11rb::wrapper::ConnectionExt as _;
let atom = |name: &str| -> anyhow::Result<xproto::Atom> {
Ok(get_reply(
|| format!("X11 InternAtom {name} for the overlay window failed."),
xcb.intern_atom(false, name.as_bytes()),
)?
.atom)
};
check_reply(
|| "X11 ChangeProperty _NET_WM_WINDOW_TYPE for the overlay window failed.",
xcb.change_property32(
xproto::PropMode::REPLACE,
self.x_window,
atom("_NET_WM_WINDOW_TYPE")?,
xproto::AtomEnum::ATOM,
&[atom("_NET_WM_WINDOW_TYPE_DROPDOWN_MENU")?],
),
)?;
const INPUT_HINT: u32 = 1;
check_reply(
|| "X11 ChangeProperty WM_HINTS for the overlay window failed.",
xcb.change_property32(
xproto::PropMode::REPLACE,
self.x_window,
xproto::AtomEnum::WM_HINTS,
xproto::AtomEnum::WM_HINTS,
&[INPUT_HINT, 0, 0, 0, 0, 0, 0, 0, 0],
),
)?;
check_reply(
|| "X11 ChangeProperty WM_TRANSIENT_FOR for the overlay window failed.",
xcb.change_property32(
xproto::PropMode::REPLACE,
self.x_window,
xproto::AtomEnum::WM_TRANSIENT_FOR,
xproto::AtomEnum::WINDOW,
&[parent],
),
)
}
fn create_renderer(
xcb: &Rc<XCBConnection>,
window_renderer: &WgpuRenderer,
spare_renderer: Option<WgpuRenderer>,
x_window: xproto::Window,
visual_id: u32,
size: Size<DevicePixels>,
) -> anyhow::Result<WgpuRenderer> {
let raw_window = OverlayRawWindow {
connection: xcb.clone(),
x_window,
visual_id,
};
let config = WgpuSurfaceConfig {
size,
transparent: true,
preferred_present_mode: Some(wgpu::PresentMode::Mailbox),
};
match spare_renderer {
Some(mut renderer) => {
renderer.replace_surface_sharing_context(&raw_window, config)?;
Ok(renderer)
}
None => window_renderer.new_sharing_atlas(&raw_window, config),
}
}
fn set_geometry(
&mut self,
xcb: &XCBConnection,
origin: Point<DevicePixels>,
size: Size<DevicePixels>,
) -> anyhow::Result<()> {
if (origin, size) == (self.origin, self.size) && self.mapped {
return Ok(());
}
check_reply(
|| "X11 ConfigureWindow for the overlay window failed.",
xcb.configure_window(
self.x_window,
&xproto::ConfigureWindowAux::new()
.x(origin.x.0)
.y(origin.y.0)
.width(size.width.0.max(1) as u32)
.height(size.height.0.max(1) as u32),
),
)?;
if size != self.size {
self.renderer.update_drawable_size(size);
}
self.origin = origin;
self.size = size;
Ok(())
}
fn set_input(
&mut self,
xcb: &XCBConnection,
input: Vec<Bounds<DevicePixels>>,
) -> anyhow::Result<()> {
if self.input.as_ref() == Some(&input) {
return Ok(());
}
check_reply(
|| "X11 ShapeRectangles input for the overlay window failed.",
xcb.shape_rectangles(
shape::SO::SET,
shape::SK::INPUT,
xproto::ClipOrdering::UNSORTED,
self.x_window,
0,
0,
&input.iter().copied().map(x11_rectangle).collect::<Vec<_>>(),
),
)?;
self.input = Some(input);
Ok(())
}
fn map(&mut self, xcb: &XCBConnection) -> anyhow::Result<()> {
if self.mapped {
return Ok(());
}
check_reply(
|| "X11 MapWindow for the overlay window failed.",
xcb.map_window(self.x_window),
)?;
xcb_flush(xcb);
self.mapped = true;
Ok(())
}
fn raise_above(&self, xcb: &XCBConnection, parent: xproto::Window) {
check_reply(
|| "X11 ConfigureWindow stacking for the overlay window failed.",
xcb.configure_window(
self.x_window,
&xproto::ConfigureWindowAux::new()
.sibling(parent)
.stack_mode(xproto::StackMode::ABOVE),
),
)
.log_err();
}
fn destroy(mut self, xcb: &XCBConnection) -> WgpuRenderer {
INPUT_WINDOWS.with(|windows| windows.borrow_mut().remove(&self.x_window));
self.renderer.unconfigure_surface();
check_reply(
|| "X11 DestroyWindow for the overlay window failed.",
xcb.destroy_window(self.x_window),
)
.log_err();
self.renderer
}
}
struct OverlayRawWindow {
connection: Rc<XCBConnection>,
x_window: xproto::Window,
visual_id: u32,
}
impl rwh::HasWindowHandle for OverlayRawWindow {
fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
let _ = &self.connection;
let window = NonZeroU32::new(self.x_window).ok_or(rwh::HandleError::Unavailable)?;
let mut handle = rwh::XcbWindowHandle::new(window);
handle.visual_id = NonZeroU32::new(self.visual_id);
Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
}
}
pub(crate) fn draw_composed(window: &X11Window, scene: ComposedScene<'_>) {
let composition = window.0.state.borrow().fast_composition.0.clone();
let mut composition = composition.borrow_mut();
let Some(base_surface) = composition.base_surface else {
drop(composition);
window.draw(scene.scene());
return;
};
let track_occluders = composition
.native_surfaces
.iter()
.any(|surface| surface.strong_count() > 0);
let overlay_surfaces = if track_occluders && composition.overlay_supported() {
composition.surfaces_above_native()
} else {
FxHashSet::default()
};
let mut window_scene = Scene::default();
let mut overlay_scene = Scene::default();
let mut overlay_input = Vec::new();
let mut occluders = FxHashMap::default();
for layer in scene.layers() {
let in_overlay = overlay_surfaces.contains(&layer.surface);
if in_overlay {
overlay_input.extend(
scene
.layer_hitboxes(layer)
.iter()
.map(|hitbox| hitbox.bounds.to_device_pixels(window.scale_factor())),
);
}
let cuts_out = track_occluders && layer.surface != base_surface;
let mut layer_scene = Scene::default();
for range in &layer.ranges {
let replayed = window_scene
.replay_balanced(range.clone(), scene.scene())
.and_then(|()| {
if in_overlay {
overlay_scene.replay_balanced(range.clone(), scene.scene())
} else {
Ok(())
}
})
.and_then(|()| {
if cuts_out {
layer_scene.replay_balanced(range.clone(), scene.scene())
} else {
Ok(())
}
});
if let Err(error) = replayed {
log::error!("replaying X11 composition scene: {error:#}");
return;
}
}
if cuts_out {
layer_scene.finish();
occluders.insert(layer.surface, scene_occluders(&layer_scene, in_overlay));
}
}
window_scene.finish();
overlay_scene.finish();
if occluders != composition.occluders {
composition.occluders = occluders;
composition.apply_order().log_err();
}
if overlay_surfaces.is_empty() {
composition.hide_overlay();
} else if let Err(error) = composition.draw_overlay(window, &overlay_scene, overlay_input) {
log::error!("drawing the X11 composition overlay window: {error:#}");
}
drop(composition);
window.draw(&window_scene);
}
pub(crate) fn enable_window_composition(window: &X11Window) -> anyhow::Result<()> {
let shape = window
.0
.xcb
.extension_information(shape::X11_EXTENSION_NAME)
.context("X11 QueryExtension for SHAPE failed")?;
anyhow::ensure!(
shape.is_some(),
"the X11 server does not support the SHAPE extension"
);
Ok(())
}
pub(crate) fn create_native_surface(
window: &X11Window,
) -> anyhow::Result<Rc<dyn PlatformSurfaceAttachment>> {
enable_window_composition(window)?;
let composition = window.0.state.borrow().fast_composition.0.clone();
let mut composition = composition.borrow_mut();
let state = composition.create_native_surface()?;
Ok(Rc::new(X11NativeSurface {
state,
visual_id: composition.visual_id,
}))
}
pub(crate) fn set_composition_order(
window: &X11Window,
surfaces: &[PlatformCompositionSurface],
) -> anyhow::Result<()> {
let base_surface = surfaces
.iter()
.find_map(|surface| match surface.content {
PlatformCompositionSurfaceContent::Gpui => Some(surface.id),
PlatformCompositionSurfaceContent::Native(_)
| PlatformCompositionSurfaceContent::ExternalGpu(_) => None,
})
.context("composition has no GPUI base surface")?;
let composition = window.0.state.borrow().fast_composition.0.clone();
let mut composition = composition.borrow_mut();
composition.base_surface = Some(base_surface);
composition.order = surfaces.to_vec();
composition
.occluders
.retain(|id, _| surfaces.iter().any(|surface| surface.id == *id));
composition.apply_order()?;
if !surfaces.iter().any(|surface| {
matches!(
surface.content,
PlatformCompositionSurfaceContent::Native(_)
| PlatformCompositionSurfaceContent::ExternalGpu(_)
)
}) {
composition.hide_overlay();
}
let inputs = surfaces
.iter()
.filter(|surface| match &surface.content {
PlatformCompositionSurfaceContent::Native(attachment)
| PlatformCompositionSurfaceContent::ExternalGpu(attachment) => {
attachment.input_forwarding()
}
PlatformCompositionSurfaceContent::Gpui => false,
})
.map(|surface| {
let attachment = match &surface.content {
PlatformCompositionSurfaceContent::Native(attachment)
| PlatformCompositionSurfaceContent::ExternalGpu(attachment) => attachment,
PlatformCompositionSurfaceContent::Gpui => {
anyhow::bail!("GPUI surface cannot forward native input")
}
};
let handle = attachment
.platform_handle()?
.downcast::<rwh::RawWindowHandle>()
.map_err(|_| anyhow!("native X11 input surface has no window handle"))?;
let id = match *handle {
rwh::RawWindowHandle::Xcb(handle) => handle.window.get(),
rwh::RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,
_ => anyhow::bail!("native input surface requires an X11 window"),
};
anyhow::ensure!(id != 0, "native X11 input window is null");
Ok((
id,
InputWindow {
window: window.0.clone(),
native: Some(Rc::downgrade(attachment)),
},
))
})
.collect::<anyhow::Result<Vec<_>>>()?;
INPUT_WINDOWS.with(|windows| {
let mut windows = windows.borrow_mut();
for id in composition.input_windows.drain(..) {
windows.remove(&id);
}
for (id, input) in inputs {
windows.insert(id, input);
composition.input_windows.push(id);
}
});
Ok(())
}