1use anyhow::{Context as _, anyhow};
2use x11rb::connection::RequestConnection;
3
4use crate::platform::wgpu::{WgpuContext, WgpuRenderer, WgpuSurfaceConfig};
5use crate::{
6 AnyWindowHandle, Bounds, Decorations, DevicePixels, ForegroundExecutor, GpuSpecs, Modifiers,
7 Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
8 Point, PromptButton, PromptLevel, RequestFrameOptions, ResizeEdge, ScaledPixels, Scene, Size,
9 Tiling, WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea,
10 WindowDecorations, WindowKind, WindowParams, X11ClientStatePtr, px,
11};
12
13use collections::FxHashSet;
14use raw_window_handle as rwh;
15use util::{ResultExt, maybe};
16use x11rb::{
17 connection::Connection,
18 cookie::{Cookie, VoidCookie},
19 errors::ConnectionError,
20 properties::WmSizeHints,
21 protocol::{
22 sync,
23 xinput::{self, ConnectionExt as _},
24 xproto::{self, ClientMessageEvent, ConnectionExt, TranslateCoordinatesReply},
25 },
26 wrapper::ConnectionExt as _,
27 xcb_ffi::XCBConnection,
28};
29
30use std::{
31 cell::RefCell, ffi::c_void, fmt::Display, num::NonZeroU32, ptr::NonNull, rc::Rc, sync::Arc,
32};
33
34use super::{X11Display, XINPUT_ALL_DEVICE_GROUPS, XINPUT_ALL_DEVICES};
35
36x11rb::atom_manager! {
37 pub XcbAtoms: AtomsCookie {
38 XA_ATOM,
39 XdndAware,
40 XdndStatus,
41 XdndEnter,
42 XdndLeave,
43 XdndPosition,
44 XdndSelection,
45 XdndDrop,
46 XdndFinished,
47 XdndTypeList,
48 XdndActionCopy,
49 TextUriList: b"text/uri-list",
50 UTF8_STRING,
51 TEXT,
52 STRING,
53 TEXT_PLAIN_UTF8: b"text/plain;charset=utf-8",
54 TEXT_PLAIN: b"text/plain",
55 XDND_DATA,
56 WM_PROTOCOLS,
57 WM_DELETE_WINDOW,
58 WM_CHANGE_STATE,
59 WM_TRANSIENT_FOR,
60 _NET_WM_PID,
61 _NET_WM_NAME,
62 _NET_WM_STATE,
63 _NET_WM_STATE_MAXIMIZED_VERT,
64 _NET_WM_STATE_MAXIMIZED_HORZ,
65 _NET_WM_STATE_FULLSCREEN,
66 _NET_WM_STATE_HIDDEN,
67 _NET_WM_STATE_FOCUSED,
68 _NET_ACTIVE_WINDOW,
69 _NET_WM_SYNC_REQUEST,
70 _NET_WM_SYNC_REQUEST_COUNTER,
71 _NET_WM_BYPASS_COMPOSITOR,
72 _NET_WM_MOVERESIZE,
73 _NET_WM_WINDOW_TYPE,
74 _NET_WM_WINDOW_TYPE_NOTIFICATION,
75 _NET_WM_WINDOW_TYPE_DIALOG,
76 _NET_WM_STATE_MODAL,
77 _NET_WM_SYNC,
78 _NET_SUPPORTED,
79 _MOTIF_WM_HINTS,
80 _GTK_SHOW_WINDOW_MENU,
81 _GTK_FRAME_EXTENTS,
82 _GTK_EDGE_CONSTRAINTS,
83 _NET_CLIENT_LIST_STACKING,
84 }
85}
86
87fn query_render_extent(
88 xcb: &Rc<XCBConnection>,
89 x_window: xproto::Window,
90) -> anyhow::Result<Size<DevicePixels>> {
91 let reply = get_reply(|| "X11 GetGeometry failed.", xcb.get_geometry(x_window))?;
92 Ok(Size {
93 width: DevicePixels(reply.width as i32),
94 height: DevicePixels(reply.height as i32),
95 })
96}
97
98impl ResizeEdge {
99 fn to_moveresize(self) -> u32 {
100 match self {
101 ResizeEdge::TopLeft => 0,
102 ResizeEdge::Top => 1,
103 ResizeEdge::TopRight => 2,
104 ResizeEdge::Right => 3,
105 ResizeEdge::BottomRight => 4,
106 ResizeEdge::Bottom => 5,
107 ResizeEdge::BottomLeft => 6,
108 ResizeEdge::Left => 7,
109 }
110 }
111}
112
113#[derive(Debug)]
114struct EdgeConstraints {
115 top_tiled: bool,
116 #[allow(dead_code)]
117 top_resizable: bool,
118
119 right_tiled: bool,
120 #[allow(dead_code)]
121 right_resizable: bool,
122
123 bottom_tiled: bool,
124 #[allow(dead_code)]
125 bottom_resizable: bool,
126
127 left_tiled: bool,
128 #[allow(dead_code)]
129 left_resizable: bool,
130}
131
132impl EdgeConstraints {
133 fn from_atom(atom: u32) -> Self {
134 EdgeConstraints {
135 top_tiled: (atom & (1 << 0)) != 0,
136 top_resizable: (atom & (1 << 1)) != 0,
137 right_tiled: (atom & (1 << 2)) != 0,
138 right_resizable: (atom & (1 << 3)) != 0,
139 bottom_tiled: (atom & (1 << 4)) != 0,
140 bottom_resizable: (atom & (1 << 5)) != 0,
141 left_tiled: (atom & (1 << 6)) != 0,
142 left_resizable: (atom & (1 << 7)) != 0,
143 }
144 }
145
146 fn to_tiling(&self) -> Tiling {
147 Tiling {
148 top: self.top_tiled,
149 right: self.right_tiled,
150 bottom: self.bottom_tiled,
151 left: self.left_tiled,
152 }
153 }
154}
155
156#[derive(Copy, Clone, Debug)]
157struct Visual {
158 id: xproto::Visualid,
159 colormap: u32,
160 depth: u8,
161}
162
163struct VisualSet {
164 inherit: Visual,
165 opaque: Option<Visual>,
166 transparent: Option<Visual>,
167 root: u32,
168 black_pixel: u32,
169}
170
171fn find_visuals(xcb: &XCBConnection, screen_index: usize) -> VisualSet {
172 let screen = &xcb.setup().roots[screen_index];
173 let mut set = VisualSet {
174 inherit: Visual {
175 id: screen.root_visual,
176 colormap: screen.default_colormap,
177 depth: screen.root_depth,
178 },
179 opaque: None,
180 transparent: None,
181 root: screen.root,
182 black_pixel: screen.black_pixel,
183 };
184
185 for depth_info in screen.allowed_depths.iter() {
186 for visual_type in depth_info.visuals.iter() {
187 let visual = Visual {
188 id: visual_type.visual_id,
189 colormap: 0,
190 depth: depth_info.depth,
191 };
192 log::debug!(
193 "Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
194 visual_type.visual_id,
195 visual_type.class,
196 depth_info.depth,
197 visual_type.bits_per_rgb_value,
198 visual_type.red_mask,
199 visual_type.green_mask,
200 visual_type.blue_mask,
201 );
202
203 if (
204 visual_type.red_mask,
205 visual_type.green_mask,
206 visual_type.blue_mask,
207 ) != (0xFF0000, 0xFF00, 0xFF)
208 {
209 continue;
210 }
211 let color_mask = visual_type.red_mask | visual_type.green_mask | visual_type.blue_mask;
212 let alpha_mask = color_mask as usize ^ ((1usize << depth_info.depth) - 1);
213
214 if alpha_mask == 0 {
215 if set.opaque.is_none() {
216 set.opaque = Some(visual);
217 }
218 } else {
219 if set.transparent.is_none() {
220 set.transparent = Some(visual);
221 }
222 }
223 }
224 }
225
226 set
227}
228
229struct RawWindow {
230 connection: *mut c_void,
231 screen_id: usize,
232 window_id: u32,
233 visual_id: u32,
234}
235
236// Safety: The raw pointers in RawWindow point to X11 connection
237// which is valid for the window's lifetime. These are used only for
238// passing to wgpu which needs Send+Sync for surface creation.
239unsafe impl Send for RawWindow {}
240unsafe impl Sync for RawWindow {}
241
242#[derive(Default)]
243pub struct Callbacks {
244 request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
245 input: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
246 active_status_change: Option<Box<dyn FnMut(bool)>>,
247 hovered_status_change: Option<Box<dyn FnMut(bool)>>,
248 resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
249 moved: Option<Box<dyn FnMut()>>,
250 should_close: Option<Box<dyn FnMut() -> bool>>,
251 close: Option<Box<dyn FnOnce()>>,
252 appearance_changed: Option<Box<dyn FnMut()>>,
253}
254
255pub struct X11WindowState {
256 pub destroyed: bool,
257 parent: Option<X11WindowStatePtr>,
258 children: FxHashSet<xproto::Window>,
259 client: X11ClientStatePtr,
260 executor: ForegroundExecutor,
261 atoms: XcbAtoms,
262 x_root_window: xproto::Window,
263 pub(crate) counter_id: sync::Counter,
264 pub(crate) last_sync_counter: Option<sync::Int64>,
265 bounds: Bounds<Pixels>,
266 scale_factor: f32,
267 renderer: WgpuRenderer,
268 display: Rc<dyn PlatformDisplay>,
269 input_handler: Option<PlatformInputHandler>,
270 appearance: WindowAppearance,
271 background_appearance: WindowBackgroundAppearance,
272 maximized_vertical: bool,
273 maximized_horizontal: bool,
274 hidden: bool,
275 active: bool,
276 hovered: bool,
277 fullscreen: bool,
278 client_side_decorations_supported: bool,
279 decorations: WindowDecorations,
280 edge_constraints: Option<EdgeConstraints>,
281 pub handle: AnyWindowHandle,
282 last_insets: [u32; 4],
283}
284
285impl X11WindowState {
286 fn is_transparent(&self) -> bool {
287 self.background_appearance != WindowBackgroundAppearance::Opaque
288 }
289}
290
291#[derive(Clone)]
292pub(crate) struct X11WindowStatePtr {
293 pub state: Rc<RefCell<X11WindowState>>,
294 pub(crate) callbacks: Rc<RefCell<Callbacks>>,
295 xcb: Rc<XCBConnection>,
296 pub(crate) x_window: xproto::Window,
297}
298
299impl rwh::HasWindowHandle for RawWindow {
300 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
301 let Some(non_zero) = NonZeroU32::new(self.window_id) else {
302 log::error!("RawWindow.window_id zero when getting window handle.");
303 return Err(rwh::HandleError::Unavailable);
304 };
305 let mut handle = rwh::XcbWindowHandle::new(non_zero);
306 handle.visual_id = NonZeroU32::new(self.visual_id);
307 Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
308 }
309}
310impl rwh::HasDisplayHandle for RawWindow {
311 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
312 let Some(non_zero) = NonNull::new(self.connection) else {
313 log::error!("Null RawWindow.connection when getting display handle.");
314 return Err(rwh::HandleError::Unavailable);
315 };
316 let handle = rwh::XcbDisplayHandle::new(Some(non_zero), self.screen_id as i32);
317 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
318 }
319}
320
321impl rwh::HasWindowHandle for X11Window {
322 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
323 unimplemented!()
324 }
325}
326impl rwh::HasDisplayHandle for X11Window {
327 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
328 unimplemented!()
329 }
330}
331
332pub(crate) fn xcb_flush(xcb: &XCBConnection) {
333 xcb.flush()
334 .map_err(handle_connection_error)
335 .context("X11 flush failed")
336 .log_err();
337}
338
339pub(crate) fn check_reply<E, F, C>(
340 failure_context: F,
341 result: Result<VoidCookie<'_, C>, ConnectionError>,
342) -> anyhow::Result<()>
343where
344 E: Display + Send + Sync + 'static,
345 F: FnOnce() -> E,
346 C: RequestConnection,
347{
348 result
349 .map_err(handle_connection_error)
350 .and_then(|response| response.check().map_err(|reply_error| anyhow!(reply_error)))
351 .with_context(failure_context)
352}
353
354pub(crate) fn get_reply<E, F, C, O>(
355 failure_context: F,
356 result: Result<Cookie<'_, C, O>, ConnectionError>,
357) -> anyhow::Result<O>
358where
359 E: Display + Send + Sync + 'static,
360 F: FnOnce() -> E,
361 C: RequestConnection,
362 O: x11rb::x11_utils::TryParse,
363{
364 result
365 .map_err(handle_connection_error)
366 .and_then(|response| response.reply().map_err(|reply_error| anyhow!(reply_error)))
367 .with_context(failure_context)
368}
369
370/// Convert X11 connection errors to `anyhow::Error` and panic for unrecoverable errors.
371pub(crate) fn handle_connection_error(err: ConnectionError) -> anyhow::Error {
372 match err {
373 ConnectionError::UnknownError => anyhow!("X11 connection: Unknown error"),
374 ConnectionError::UnsupportedExtension => anyhow!("X11 connection: Unsupported extension"),
375 ConnectionError::MaximumRequestLengthExceeded => {
376 anyhow!("X11 connection: Maximum request length exceeded")
377 }
378 ConnectionError::FdPassingFailed => {
379 panic!("X11 connection: File descriptor passing failed")
380 }
381 ConnectionError::ParseError(parse_error) => {
382 anyhow!(parse_error).context("Parse error in X11 response")
383 }
384 ConnectionError::InsufficientMemory => panic!("X11 connection: Insufficient memory"),
385 ConnectionError::IoError(err) => anyhow!(err).context("X11 connection: IOError"),
386 _ => anyhow!(err),
387 }
388}
389
390impl X11WindowState {
391 pub fn new(
392 handle: AnyWindowHandle,
393 client: X11ClientStatePtr,
394 executor: ForegroundExecutor,
395 gpu_context: &mut Option<WgpuContext>,
396 params: WindowParams,
397 xcb: &Rc<XCBConnection>,
398 client_side_decorations_supported: bool,
399 x_main_screen_index: usize,
400 x_window: xproto::Window,
401 atoms: &XcbAtoms,
402 scale_factor: f32,
403 appearance: WindowAppearance,
404 parent_window: Option<X11WindowStatePtr>,
405 ) -> anyhow::Result<Self> {
406 let x_screen_index = params
407 .display_id
408 .map_or(x_main_screen_index, |did| did.0 as usize);
409
410 let visual_set = find_visuals(xcb, x_screen_index);
411
412 let visual = match visual_set.transparent {
413 Some(visual) => visual,
414 None => {
415 log::warn!("Unable to find a transparent visual",);
416 visual_set.inherit
417 }
418 };
419 log::info!("Using {:?}", visual);
420
421 let colormap = if visual.colormap != 0 {
422 visual.colormap
423 } else {
424 let id = xcb.generate_id()?;
425 log::info!("Creating colormap {}", id);
426 check_reply(
427 || format!("X11 CreateColormap failed. id: {}", id),
428 xcb.create_colormap(xproto::ColormapAlloc::NONE, id, visual_set.root, visual.id),
429 )?;
430 id
431 };
432
433 let win_aux = xproto::CreateWindowAux::new()
434 // https://stackoverflow.com/questions/43218127/x11-xlib-xcb-creating-a-window-requires-border-pixel-if-specifying-colormap-wh
435 .border_pixel(visual_set.black_pixel)
436 .colormap(colormap)
437 .override_redirect((params.kind == WindowKind::PopUp) as u32)
438 .event_mask(
439 xproto::EventMask::EXPOSURE
440 | xproto::EventMask::STRUCTURE_NOTIFY
441 | xproto::EventMask::FOCUS_CHANGE
442 | xproto::EventMask::KEY_PRESS
443 | xproto::EventMask::KEY_RELEASE
444 | xproto::EventMask::PROPERTY_CHANGE
445 | xproto::EventMask::VISIBILITY_CHANGE,
446 );
447
448 let mut bounds = params.bounds.to_device_pixels(scale_factor);
449 if bounds.size.width.0 == 0 || bounds.size.height.0 == 0 {
450 log::warn!(
451 "Window bounds contain a zero value. height={}, width={}. Falling back to defaults.",
452 bounds.size.height.0,
453 bounds.size.width.0
454 );
455 bounds.size.width = 800.into();
456 bounds.size.height = 600.into();
457 }
458
459 check_reply(
460 || {
461 format!(
462 "X11 CreateWindow failed. depth: {}, x_window: {}, visual_set.root: {}, bounds.origin.x.0: {}, bounds.origin.y.0: {}, bounds.size.width.0: {}, bounds.size.height.0: {}",
463 visual.depth,
464 x_window,
465 visual_set.root,
466 bounds.origin.x.0 + 2,
467 bounds.origin.y.0,
468 bounds.size.width.0,
469 bounds.size.height.0
470 )
471 },
472 xcb.create_window(
473 visual.depth,
474 x_window,
475 visual_set.root,
476 (bounds.origin.x.0 + 2) as i16,
477 bounds.origin.y.0 as i16,
478 bounds.size.width.0 as u16,
479 bounds.size.height.0 as u16,
480 0,
481 xproto::WindowClass::INPUT_OUTPUT,
482 visual.id,
483 &win_aux,
484 ),
485 )?;
486
487 // Collect errors during setup, so that window can be destroyed on failure.
488 let setup_result = maybe!({
489 let pid = std::process::id();
490 check_reply(
491 || "X11 ChangeProperty for _NET_WM_PID failed.",
492 xcb.change_property32(
493 xproto::PropMode::REPLACE,
494 x_window,
495 atoms._NET_WM_PID,
496 xproto::AtomEnum::CARDINAL,
497 &[pid],
498 ),
499 )?;
500
501 if let Some(size) = params.window_min_size {
502 let mut size_hints = WmSizeHints::new();
503 let min_size = (size.width.0 as i32, size.height.0 as i32);
504 size_hints.min_size = Some(min_size);
505 check_reply(
506 || {
507 format!(
508 "X11 change of WM_SIZE_HINTS failed. min_size: {:?}",
509 min_size
510 )
511 },
512 size_hints.set_normal_hints(xcb, x_window),
513 )?;
514 }
515
516 let reply = get_reply(|| "X11 GetGeometry failed.", xcb.get_geometry(x_window))?;
517 if reply.x == 0 && reply.y == 0 {
518 bounds.origin.x.0 += 2;
519 // Work around a bug where our rendered content appears
520 // outside the window bounds when opened at the default position
521 // (14px, 49px on X + Gnome + Ubuntu 22).
522 let x = bounds.origin.x.0;
523 let y = bounds.origin.y.0;
524 check_reply(
525 || format!("X11 ConfigureWindow failed. x: {}, y: {}", x, y),
526 xcb.configure_window(x_window, &xproto::ConfigureWindowAux::new().x(x).y(y)),
527 )?;
528 }
529 if let Some(titlebar) = params.titlebar
530 && let Some(title) = titlebar.title
531 {
532 check_reply(
533 || "X11 ChangeProperty8 on window title failed.",
534 xcb.change_property8(
535 xproto::PropMode::REPLACE,
536 x_window,
537 xproto::AtomEnum::WM_NAME,
538 xproto::AtomEnum::STRING,
539 title.as_bytes(),
540 ),
541 )?;
542 }
543
544 if params.kind == WindowKind::PopUp {
545 check_reply(
546 || "X11 ChangeProperty32 setting window type for pop-up failed.",
547 xcb.change_property32(
548 xproto::PropMode::REPLACE,
549 x_window,
550 atoms._NET_WM_WINDOW_TYPE,
551 xproto::AtomEnum::ATOM,
552 &[atoms._NET_WM_WINDOW_TYPE_NOTIFICATION],
553 ),
554 )?;
555 }
556
557 if params.kind == WindowKind::Floating || params.kind == WindowKind::Dialog {
558 if let Some(parent_window) = parent_window.as_ref().map(|w| w.x_window) {
559 // WM_TRANSIENT_FOR hint indicating the main application window. For floating windows, we set
560 // a parent window (WM_TRANSIENT_FOR) such that the window manager knows where to
561 // place the floating window in relation to the main window.
562 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
563 check_reply(
564 || "X11 ChangeProperty32 setting WM_TRANSIENT_FOR for floating window failed.",
565 xcb.change_property32(
566 xproto::PropMode::REPLACE,
567 x_window,
568 atoms.WM_TRANSIENT_FOR,
569 xproto::AtomEnum::WINDOW,
570 &[parent_window],
571 ),
572 )?;
573 }
574 }
575
576 let parent = if params.kind == WindowKind::Dialog
577 && let Some(parent) = parent_window
578 {
579 parent.add_child(x_window);
580
581 Some(parent)
582 } else {
583 None
584 };
585
586 if params.kind == WindowKind::Dialog {
587 // _NET_WM_WINDOW_TYPE_DIALOG indicates that this is a dialog (floating) window
588 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
589 check_reply(
590 || "X11 ChangeProperty32 setting window type for dialog window failed.",
591 xcb.change_property32(
592 xproto::PropMode::REPLACE,
593 x_window,
594 atoms._NET_WM_WINDOW_TYPE,
595 xproto::AtomEnum::ATOM,
596 &[atoms._NET_WM_WINDOW_TYPE_DIALOG],
597 ),
598 )?;
599
600 // We set the modal state for dialog windows, so that the window manager
601 // can handle it appropriately (e.g., prevent interaction with the parent window
602 // while the dialog is open).
603 check_reply(
604 || "X11 ChangeProperty32 setting modal state for dialog window failed.",
605 xcb.change_property32(
606 xproto::PropMode::REPLACE,
607 x_window,
608 atoms._NET_WM_STATE,
609 xproto::AtomEnum::ATOM,
610 &[atoms._NET_WM_STATE_MODAL],
611 ),
612 )?;
613 }
614
615 check_reply(
616 || "X11 ChangeProperty32 setting protocols failed.",
617 xcb.change_property32(
618 xproto::PropMode::REPLACE,
619 x_window,
620 atoms.WM_PROTOCOLS,
621 xproto::AtomEnum::ATOM,
622 &[atoms.WM_DELETE_WINDOW, atoms._NET_WM_SYNC_REQUEST],
623 ),
624 )?;
625
626 get_reply(
627 || "X11 sync protocol initialize failed.",
628 sync::initialize(xcb, 3, 1),
629 )?;
630 let sync_request_counter = xcb.generate_id()?;
631 check_reply(
632 || "X11 sync CreateCounter failed.",
633 sync::create_counter(xcb, sync_request_counter, sync::Int64 { lo: 0, hi: 0 }),
634 )?;
635
636 check_reply(
637 || "X11 ChangeProperty32 setting sync request counter failed.",
638 xcb.change_property32(
639 xproto::PropMode::REPLACE,
640 x_window,
641 atoms._NET_WM_SYNC_REQUEST_COUNTER,
642 xproto::AtomEnum::CARDINAL,
643 &[sync_request_counter],
644 ),
645 )?;
646
647 check_reply(
648 || "X11 XiSelectEvents failed.",
649 xcb.xinput_xi_select_events(
650 x_window,
651 &[xinput::EventMask {
652 deviceid: XINPUT_ALL_DEVICE_GROUPS,
653 mask: vec![
654 xinput::XIEventMask::MOTION
655 | xinput::XIEventMask::BUTTON_PRESS
656 | xinput::XIEventMask::BUTTON_RELEASE
657 | xinput::XIEventMask::ENTER
658 | xinput::XIEventMask::LEAVE,
659 ],
660 }],
661 ),
662 )?;
663
664 check_reply(
665 || "X11 XiSelectEvents for device changes failed.",
666 xcb.xinput_xi_select_events(
667 x_window,
668 &[xinput::EventMask {
669 deviceid: XINPUT_ALL_DEVICES,
670 mask: vec![
671 xinput::XIEventMask::HIERARCHY | xinput::XIEventMask::DEVICE_CHANGED,
672 ],
673 }],
674 ),
675 )?;
676
677 xcb_flush(xcb);
678
679 let renderer = {
680 let raw_window = RawWindow {
681 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
682 xcb,
683 ) as *mut _,
684 screen_id: x_screen_index,
685 window_id: x_window,
686 visual_id: visual.id,
687 };
688 let config = WgpuSurfaceConfig {
689 // Note: this has to be done after the GPU init, or otherwise
690 // the sizes are immediately invalidated.
691 size: query_render_extent(xcb, x_window)?,
692 // We set it to transparent by default, even if we have client-side
693 // decorations, since those seem to work on X11 even without `true` here.
694 // If the window appearance changes, then the renderer will get updated
695 // too
696 transparent: false,
697 };
698 WgpuRenderer::new(gpu_context, &raw_window, config)?
699 };
700
701 let display = Rc::new(X11Display::new(xcb, scale_factor, x_screen_index)?);
702
703 Ok(Self {
704 parent,
705 children: FxHashSet::default(),
706 client,
707 executor,
708 display,
709 x_root_window: visual_set.root,
710 bounds: bounds.to_pixels(scale_factor),
711 scale_factor,
712 renderer,
713 atoms: *atoms,
714 input_handler: None,
715 active: false,
716 hovered: false,
717 fullscreen: false,
718 maximized_vertical: false,
719 maximized_horizontal: false,
720 hidden: false,
721 appearance,
722 handle,
723 background_appearance: WindowBackgroundAppearance::Opaque,
724 destroyed: false,
725 client_side_decorations_supported,
726 decorations: WindowDecorations::Server,
727 last_insets: [0, 0, 0, 0],
728 edge_constraints: None,
729 counter_id: sync_request_counter,
730 last_sync_counter: None,
731 })
732 });
733
734 if setup_result.is_err() {
735 check_reply(
736 || "X11 DestroyWindow failed while cleaning it up after setup failure.",
737 xcb.destroy_window(x_window),
738 )?;
739 xcb_flush(xcb);
740 }
741
742 setup_result
743 }
744
745 fn content_size(&self) -> Size<Pixels> {
746 self.bounds.size
747 }
748}
749
750pub(crate) struct X11Window(pub X11WindowStatePtr);
751
752impl Drop for X11Window {
753 fn drop(&mut self) {
754 let mut state = self.0.state.borrow_mut();
755
756 if let Some(parent) = state.parent.as_ref() {
757 parent.state.borrow_mut().children.remove(&self.0.x_window);
758 }
759
760 state.renderer.destroy();
761
762 let destroy_x_window = maybe!({
763 check_reply(
764 || "X11 DestroyWindow failure.",
765 self.0.xcb.destroy_window(self.0.x_window),
766 )?;
767 xcb_flush(&self.0.xcb);
768
769 anyhow::Ok(())
770 })
771 .log_err();
772
773 if destroy_x_window.is_some() {
774 state.destroyed = true;
775
776 let this_ptr = self.0.clone();
777 let client_ptr = state.client.clone();
778 state
779 .executor
780 .spawn(async move {
781 this_ptr.close();
782 client_ptr.drop_window(this_ptr.x_window);
783 })
784 .detach();
785 }
786
787 drop(state);
788 }
789}
790
791enum WmHintPropertyState {
792 // Remove = 0,
793 // Add = 1,
794 Toggle = 2,
795}
796
797impl X11Window {
798 pub fn new(
799 handle: AnyWindowHandle,
800 client: X11ClientStatePtr,
801 executor: ForegroundExecutor,
802 gpu_context: &mut Option<WgpuContext>,
803 params: WindowParams,
804 xcb: &Rc<XCBConnection>,
805 client_side_decorations_supported: bool,
806 x_main_screen_index: usize,
807 x_window: xproto::Window,
808 atoms: &XcbAtoms,
809 scale_factor: f32,
810 appearance: WindowAppearance,
811 parent_window: Option<X11WindowStatePtr>,
812 ) -> anyhow::Result<Self> {
813 let ptr = X11WindowStatePtr {
814 state: Rc::new(RefCell::new(X11WindowState::new(
815 handle,
816 client,
817 executor,
818 gpu_context,
819 params,
820 xcb,
821 client_side_decorations_supported,
822 x_main_screen_index,
823 x_window,
824 atoms,
825 scale_factor,
826 appearance,
827 parent_window,
828 )?)),
829 callbacks: Rc::new(RefCell::new(Callbacks::default())),
830 xcb: xcb.clone(),
831 x_window,
832 };
833
834 let state = ptr.state.borrow_mut();
835 ptr.set_wm_properties(state)?;
836
837 Ok(Self(ptr))
838 }
839
840 fn set_wm_hints<C: Display + Send + Sync + 'static, F: FnOnce() -> C>(
841 &self,
842 failure_context: F,
843 wm_hint_property_state: WmHintPropertyState,
844 prop1: u32,
845 prop2: u32,
846 ) -> anyhow::Result<()> {
847 let state = self.0.state.borrow();
848 let message = ClientMessageEvent::new(
849 32,
850 self.0.x_window,
851 state.atoms._NET_WM_STATE,
852 [wm_hint_property_state as u32, prop1, prop2, 1, 0],
853 );
854 check_reply(
855 failure_context,
856 self.0.xcb.send_event(
857 false,
858 state.x_root_window,
859 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
860 message,
861 ),
862 )?;
863 xcb_flush(&self.0.xcb);
864 Ok(())
865 }
866
867 fn get_root_position(
868 &self,
869 position: Point<Pixels>,
870 ) -> anyhow::Result<TranslateCoordinatesReply> {
871 let state = self.0.state.borrow();
872 get_reply(
873 || "X11 TranslateCoordinates failed.",
874 self.0.xcb.translate_coordinates(
875 self.0.x_window,
876 state.x_root_window,
877 (position.x.0 * state.scale_factor) as i16,
878 (position.y.0 * state.scale_factor) as i16,
879 ),
880 )
881 }
882
883 fn send_moveresize(&self, flag: u32) -> anyhow::Result<()> {
884 let state = self.0.state.borrow();
885
886 check_reply(
887 || "X11 UngrabPointer before move/resize of window failed.",
888 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
889 )?;
890
891 let pointer = get_reply(
892 || "X11 QueryPointer before move/resize of window failed.",
893 self.0.xcb.query_pointer(self.0.x_window),
894 )?;
895 let message = ClientMessageEvent::new(
896 32,
897 self.0.x_window,
898 state.atoms._NET_WM_MOVERESIZE,
899 [
900 pointer.root_x as u32,
901 pointer.root_y as u32,
902 flag,
903 0, // Left mouse button
904 0,
905 ],
906 );
907 check_reply(
908 || "X11 SendEvent to move/resize window failed.",
909 self.0.xcb.send_event(
910 false,
911 state.x_root_window,
912 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
913 message,
914 ),
915 )?;
916
917 xcb_flush(&self.0.xcb);
918 Ok(())
919 }
920}
921
922impl X11WindowStatePtr {
923 pub fn should_close(&self) -> bool {
924 let mut cb = self.callbacks.borrow_mut();
925 if let Some(mut should_close) = cb.should_close.take() {
926 let result = (should_close)();
927 cb.should_close = Some(should_close);
928 result
929 } else {
930 true
931 }
932 }
933
934 pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> {
935 let mut state = self.state.borrow_mut();
936 if event.atom == state.atoms._NET_WM_STATE {
937 self.set_wm_properties(state)?;
938 } else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS {
939 self.set_edge_constraints(state)?;
940 }
941 Ok(())
942 }
943
944 fn set_edge_constraints(
945 &self,
946 mut state: std::cell::RefMut<X11WindowState>,
947 ) -> anyhow::Result<()> {
948 let reply = get_reply(
949 || "X11 GetProperty for _GTK_EDGE_CONSTRAINTS failed.",
950 self.xcb.get_property(
951 false,
952 self.x_window,
953 state.atoms._GTK_EDGE_CONSTRAINTS,
954 xproto::AtomEnum::CARDINAL,
955 0,
956 4,
957 ),
958 )?;
959
960 if reply.value_len != 0 {
961 if let Ok(bytes) = reply.value[0..4].try_into() {
962 let atom = u32::from_ne_bytes(bytes);
963 let edge_constraints = EdgeConstraints::from_atom(atom);
964 state.edge_constraints.replace(edge_constraints);
965 } else {
966 log::error!("Failed to parse GTK_EDGE_CONSTRAINTS");
967 }
968 }
969
970 Ok(())
971 }
972
973 fn set_wm_properties(
974 &self,
975 mut state: std::cell::RefMut<X11WindowState>,
976 ) -> anyhow::Result<()> {
977 let reply = get_reply(
978 || "X11 GetProperty for _NET_WM_STATE failed.",
979 self.xcb.get_property(
980 false,
981 self.x_window,
982 state.atoms._NET_WM_STATE,
983 xproto::AtomEnum::ATOM,
984 0,
985 u32::MAX,
986 ),
987 )?;
988
989 let atoms = reply
990 .value
991 .chunks_exact(4)
992 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
993
994 state.active = false;
995 state.fullscreen = false;
996 state.maximized_vertical = false;
997 state.maximized_horizontal = false;
998 state.hidden = false;
999
1000 for atom in atoms {
1001 if atom == state.atoms._NET_WM_STATE_FOCUSED {
1002 state.active = true;
1003 } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
1004 state.fullscreen = true;
1005 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
1006 state.maximized_vertical = true;
1007 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
1008 state.maximized_horizontal = true;
1009 } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
1010 state.hidden = true;
1011 }
1012 }
1013
1014 Ok(())
1015 }
1016
1017 pub fn add_child(&self, child: xproto::Window) {
1018 let mut state = self.state.borrow_mut();
1019 state.children.insert(child);
1020 }
1021
1022 pub fn is_blocked(&self) -> bool {
1023 let state = self.state.borrow();
1024 !state.children.is_empty()
1025 }
1026
1027 pub fn close(&self) {
1028 let state = self.state.borrow();
1029 let client = state.client.clone();
1030 #[allow(clippy::mutable_key_type)]
1031 let children = state.children.clone();
1032 drop(state);
1033
1034 if let Some(client) = client.get_client() {
1035 for child in children {
1036 if let Some(child_window) = client.get_window(child) {
1037 child_window.close();
1038 }
1039 }
1040 }
1041
1042 let mut callbacks = self.callbacks.borrow_mut();
1043 if let Some(fun) = callbacks.close.take() {
1044 fun()
1045 }
1046 }
1047
1048 pub fn refresh(&self, request_frame_options: RequestFrameOptions) {
1049 let mut cb = self.callbacks.borrow_mut();
1050 if let Some(ref mut fun) = cb.request_frame {
1051 fun(request_frame_options);
1052 }
1053 }
1054
1055 pub fn handle_input(&self, input: PlatformInput) {
1056 if self.is_blocked() {
1057 return;
1058 }
1059 if let Some(ref mut fun) = self.callbacks.borrow_mut().input
1060 && !fun(input.clone()).propagate
1061 {
1062 return;
1063 }
1064 if let PlatformInput::KeyDown(event) = input {
1065 // only allow shift modifier when inserting text
1066 if event.keystroke.modifiers.is_subset_of(&Modifiers::shift()) {
1067 let mut state = self.state.borrow_mut();
1068 if let Some(mut input_handler) = state.input_handler.take() {
1069 if let Some(key_char) = &event.keystroke.key_char {
1070 drop(state);
1071 input_handler.replace_text_in_range(None, key_char);
1072 state = self.state.borrow_mut();
1073 }
1074 state.input_handler = Some(input_handler);
1075 }
1076 }
1077 }
1078 }
1079
1080 pub fn handle_ime_commit(&self, text: String) {
1081 if self.is_blocked() {
1082 return;
1083 }
1084 let mut state = self.state.borrow_mut();
1085 if let Some(mut input_handler) = state.input_handler.take() {
1086 drop(state);
1087 input_handler.replace_text_in_range(None, &text);
1088 let mut state = self.state.borrow_mut();
1089 state.input_handler = Some(input_handler);
1090 }
1091 }
1092
1093 pub fn handle_ime_preedit(&self, text: String) {
1094 if self.is_blocked() {
1095 return;
1096 }
1097 let mut state = self.state.borrow_mut();
1098 if let Some(mut input_handler) = state.input_handler.take() {
1099 drop(state);
1100 input_handler.replace_and_mark_text_in_range(None, &text, None);
1101 let mut state = self.state.borrow_mut();
1102 state.input_handler = Some(input_handler);
1103 }
1104 }
1105
1106 pub fn handle_ime_unmark(&self) {
1107 if self.is_blocked() {
1108 return;
1109 }
1110 let mut state = self.state.borrow_mut();
1111 if let Some(mut input_handler) = state.input_handler.take() {
1112 drop(state);
1113 input_handler.unmark_text();
1114 let mut state = self.state.borrow_mut();
1115 state.input_handler = Some(input_handler);
1116 }
1117 }
1118
1119 pub fn handle_ime_delete(&self) {
1120 if self.is_blocked() {
1121 return;
1122 }
1123 let mut state = self.state.borrow_mut();
1124 if let Some(mut input_handler) = state.input_handler.take() {
1125 drop(state);
1126 if let Some(marked) = input_handler.marked_text_range() {
1127 input_handler.replace_text_in_range(Some(marked), "");
1128 }
1129 let mut state = self.state.borrow_mut();
1130 state.input_handler = Some(input_handler);
1131 }
1132 }
1133
1134 pub fn get_ime_area(&self) -> Option<Bounds<ScaledPixels>> {
1135 let mut state = self.state.borrow_mut();
1136 let scale_factor = state.scale_factor;
1137 let mut bounds: Option<Bounds<Pixels>> = None;
1138 if let Some(mut input_handler) = state.input_handler.take() {
1139 drop(state);
1140 if let Some(selection) = input_handler.selected_text_range(true) {
1141 bounds = input_handler.bounds_for_range(selection.range);
1142 }
1143 let mut state = self.state.borrow_mut();
1144 state.input_handler = Some(input_handler);
1145 };
1146 bounds.map(|b| b.scale(scale_factor))
1147 }
1148
1149 pub fn set_bounds(&self, bounds: Bounds<i32>) -> anyhow::Result<()> {
1150 let mut resize_args = None;
1151 let is_resize;
1152 {
1153 let mut state = self.state.borrow_mut();
1154 let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
1155
1156 is_resize = bounds.size.width != state.bounds.size.width
1157 || bounds.size.height != state.bounds.size.height;
1158
1159 // If it's a resize event (only width/height changed), we ignore `bounds.origin`
1160 // because it contains wrong values.
1161 if is_resize {
1162 state.bounds.size = bounds.size;
1163 } else {
1164 state.bounds = bounds;
1165 }
1166
1167 let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
1168 if true {
1169 state.renderer.update_drawable_size(gpu_size);
1170 resize_args = Some((state.content_size(), state.scale_factor));
1171 }
1172 if let Some(value) = state.last_sync_counter.take() {
1173 check_reply(
1174 || "X11 sync SetCounter failed.",
1175 sync::set_counter(&self.xcb, state.counter_id, value),
1176 )?;
1177 }
1178 }
1179
1180 let mut callbacks = self.callbacks.borrow_mut();
1181 if let Some((content_size, scale_factor)) = resize_args
1182 && let Some(ref mut fun) = callbacks.resize
1183 {
1184 fun(content_size, scale_factor)
1185 }
1186
1187 if !is_resize && let Some(ref mut fun) = callbacks.moved {
1188 fun();
1189 }
1190
1191 Ok(())
1192 }
1193
1194 pub fn set_active(&self, focus: bool) {
1195 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
1196 fun(focus);
1197 }
1198 }
1199
1200 pub fn set_hovered(&self, focus: bool) {
1201 if let Some(ref mut fun) = self.callbacks.borrow_mut().hovered_status_change {
1202 fun(focus);
1203 }
1204 }
1205
1206 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1207 let mut state = self.state.borrow_mut();
1208 state.appearance = appearance;
1209 let is_transparent = state.is_transparent();
1210 state.renderer.update_transparency(is_transparent);
1211 state.appearance = appearance;
1212 drop(state);
1213 let mut callbacks = self.callbacks.borrow_mut();
1214 if let Some(ref mut fun) = callbacks.appearance_changed {
1215 (fun)()
1216 }
1217 }
1218}
1219
1220impl PlatformWindow for X11Window {
1221 fn bounds(&self) -> Bounds<Pixels> {
1222 self.0.state.borrow().bounds
1223 }
1224
1225 fn is_maximized(&self) -> bool {
1226 let state = self.0.state.borrow();
1227
1228 // A maximized window that gets minimized will still retain its maximized state.
1229 !state.hidden && state.maximized_vertical && state.maximized_horizontal
1230 }
1231
1232 fn window_bounds(&self) -> WindowBounds {
1233 let state = self.0.state.borrow();
1234 if self.is_maximized() {
1235 WindowBounds::Maximized(state.bounds)
1236 } else {
1237 WindowBounds::Windowed(state.bounds)
1238 }
1239 }
1240
1241 fn inner_window_bounds(&self) -> WindowBounds {
1242 let state = self.0.state.borrow();
1243 if self.is_maximized() {
1244 WindowBounds::Maximized(state.bounds)
1245 } else {
1246 let mut bounds = state.bounds;
1247 let [left, right, top, bottom] = state.last_insets;
1248
1249 let [left, right, top, bottom] = [
1250 Pixels((left as f32) / state.scale_factor),
1251 Pixels((right as f32) / state.scale_factor),
1252 Pixels((top as f32) / state.scale_factor),
1253 Pixels((bottom as f32) / state.scale_factor),
1254 ];
1255
1256 bounds.origin.x += left;
1257 bounds.origin.y += top;
1258 bounds.size.width -= left + right;
1259 bounds.size.height -= top + bottom;
1260
1261 WindowBounds::Windowed(bounds)
1262 }
1263 }
1264
1265 fn content_size(&self) -> Size<Pixels> {
1266 // After the wgpu migration, X11WindowState::content_size() returns logical pixels
1267 // (bounds.size is already divided by scale_factor in set_bounds), so no further
1268 // division is needed here. This matches the Wayland implementation.
1269 self.0.state.borrow().content_size()
1270 }
1271
1272 fn resize(&mut self, size: Size<Pixels>) {
1273 let state = self.0.state.borrow();
1274 let size = size.to_device_pixels(state.scale_factor);
1275 let width = size.width.0 as u32;
1276 let height = size.height.0 as u32;
1277
1278 check_reply(
1279 || {
1280 format!(
1281 "X11 ConfigureWindow failed. width: {}, height: {}",
1282 width, height
1283 )
1284 },
1285 self.0.xcb.configure_window(
1286 self.0.x_window,
1287 &xproto::ConfigureWindowAux::new()
1288 .width(width)
1289 .height(height),
1290 ),
1291 )
1292 .log_err();
1293 xcb_flush(&self.0.xcb);
1294 }
1295
1296 fn scale_factor(&self) -> f32 {
1297 self.0.state.borrow().scale_factor
1298 }
1299
1300 fn appearance(&self) -> WindowAppearance {
1301 self.0.state.borrow().appearance
1302 }
1303
1304 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1305 Some(self.0.state.borrow().display.clone())
1306 }
1307
1308 fn mouse_position(&self) -> Point<Pixels> {
1309 get_reply(
1310 || "X11 QueryPointer failed.",
1311 self.0.xcb.query_pointer(self.0.x_window),
1312 )
1313 .log_err()
1314 .map_or(Point::new(Pixels::ZERO, Pixels::ZERO), |reply| {
1315 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1316 })
1317 }
1318
1319 fn modifiers(&self) -> Modifiers {
1320 self.0
1321 .state
1322 .borrow()
1323 .client
1324 .0
1325 .upgrade()
1326 .map(|ref_cell| ref_cell.borrow().modifiers)
1327 .unwrap_or_default()
1328 }
1329
1330 fn capslock(&self) -> crate::Capslock {
1331 self.0
1332 .state
1333 .borrow()
1334 .client
1335 .0
1336 .upgrade()
1337 .map(|ref_cell| ref_cell.borrow().capslock)
1338 .unwrap_or_default()
1339 }
1340
1341 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1342 self.0.state.borrow_mut().input_handler = Some(input_handler);
1343 }
1344
1345 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1346 self.0.state.borrow_mut().input_handler.take()
1347 }
1348
1349 fn prompt(
1350 &self,
1351 _level: PromptLevel,
1352 _msg: &str,
1353 _detail: Option<&str>,
1354 _answers: &[PromptButton],
1355 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1356 None
1357 }
1358
1359 fn activate(&self) {
1360 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1361 let message = xproto::ClientMessageEvent::new(
1362 32,
1363 self.0.x_window,
1364 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1365 data,
1366 );
1367 self.0
1368 .xcb
1369 .send_event(
1370 false,
1371 self.0.state.borrow().x_root_window,
1372 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1373 message,
1374 )
1375 .log_err();
1376 self.0
1377 .xcb
1378 .set_input_focus(
1379 xproto::InputFocus::POINTER_ROOT,
1380 self.0.x_window,
1381 xproto::Time::CURRENT_TIME,
1382 )
1383 .log_err();
1384 xcb_flush(&self.0.xcb);
1385 }
1386
1387 fn is_active(&self) -> bool {
1388 self.0.state.borrow().active
1389 }
1390
1391 fn is_hovered(&self) -> bool {
1392 self.0.state.borrow().hovered
1393 }
1394
1395 fn set_title(&mut self, title: &str) {
1396 check_reply(
1397 || "X11 ChangeProperty8 on WM_NAME failed.",
1398 self.0.xcb.change_property8(
1399 xproto::PropMode::REPLACE,
1400 self.0.x_window,
1401 xproto::AtomEnum::WM_NAME,
1402 xproto::AtomEnum::STRING,
1403 title.as_bytes(),
1404 ),
1405 )
1406 .log_err();
1407
1408 check_reply(
1409 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1410 self.0.xcb.change_property8(
1411 xproto::PropMode::REPLACE,
1412 self.0.x_window,
1413 self.0.state.borrow().atoms._NET_WM_NAME,
1414 self.0.state.borrow().atoms.UTF8_STRING,
1415 title.as_bytes(),
1416 ),
1417 )
1418 .log_err();
1419 xcb_flush(&self.0.xcb);
1420 }
1421
1422 fn set_app_id(&mut self, app_id: &str) {
1423 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1424 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1425 data.push(b'\0');
1426 data.extend(app_id.bytes()); // class
1427
1428 check_reply(
1429 || "X11 ChangeProperty8 for WM_CLASS failed.",
1430 self.0.xcb.change_property8(
1431 xproto::PropMode::REPLACE,
1432 self.0.x_window,
1433 xproto::AtomEnum::WM_CLASS,
1434 xproto::AtomEnum::STRING,
1435 &data,
1436 ),
1437 )
1438 .log_err();
1439 }
1440
1441 fn map_window(&mut self) -> anyhow::Result<()> {
1442 check_reply(
1443 || "X11 MapWindow failed.",
1444 self.0.xcb.map_window(self.0.x_window),
1445 )?;
1446 Ok(())
1447 }
1448
1449 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1450 let mut state = self.0.state.borrow_mut();
1451 state.background_appearance = background_appearance;
1452 let transparent = state.is_transparent();
1453 state.renderer.update_transparency(transparent);
1454 }
1455
1456 fn background_appearance(&self) -> WindowBackgroundAppearance {
1457 self.0.state.borrow().background_appearance
1458 }
1459
1460 fn is_subpixel_rendering_supported(&self) -> bool {
1461 self.0
1462 .state
1463 .borrow()
1464 .client
1465 .0
1466 .upgrade()
1467 .map(|ref_cell| {
1468 let state = ref_cell.borrow();
1469 state
1470 .gpu_context
1471 .as_ref()
1472 .is_some_and(|ctx| ctx.supports_dual_source_blending())
1473 })
1474 .unwrap_or_default()
1475 }
1476
1477 fn minimize(&self) {
1478 let state = self.0.state.borrow();
1479 const WINDOW_ICONIC_STATE: u32 = 3;
1480 let message = ClientMessageEvent::new(
1481 32,
1482 self.0.x_window,
1483 state.atoms.WM_CHANGE_STATE,
1484 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1485 );
1486 check_reply(
1487 || "X11 SendEvent to minimize window failed.",
1488 self.0.xcb.send_event(
1489 false,
1490 state.x_root_window,
1491 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1492 message,
1493 ),
1494 )
1495 .log_err();
1496 }
1497
1498 fn zoom(&self) {
1499 let state = self.0.state.borrow();
1500 self.set_wm_hints(
1501 || "X11 SendEvent to maximize a window failed.",
1502 WmHintPropertyState::Toggle,
1503 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1504 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1505 )
1506 .log_err();
1507 }
1508
1509 fn toggle_fullscreen(&self) {
1510 let state = self.0.state.borrow();
1511 self.set_wm_hints(
1512 || "X11 SendEvent to fullscreen a window failed.",
1513 WmHintPropertyState::Toggle,
1514 state.atoms._NET_WM_STATE_FULLSCREEN,
1515 xproto::AtomEnum::NONE.into(),
1516 )
1517 .log_err();
1518 }
1519
1520 fn is_fullscreen(&self) -> bool {
1521 self.0.state.borrow().fullscreen
1522 }
1523
1524 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1525 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1526 }
1527
1528 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1529 self.0.callbacks.borrow_mut().input = Some(callback);
1530 }
1531
1532 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1533 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1534 }
1535
1536 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1537 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1538 }
1539
1540 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1541 self.0.callbacks.borrow_mut().resize = Some(callback);
1542 }
1543
1544 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1545 self.0.callbacks.borrow_mut().moved = Some(callback);
1546 }
1547
1548 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1549 self.0.callbacks.borrow_mut().should_close = Some(callback);
1550 }
1551
1552 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1553 self.0.callbacks.borrow_mut().close = Some(callback);
1554 }
1555
1556 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1557 }
1558
1559 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1560 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1561 }
1562
1563 fn draw(&self, scene: &Scene) {
1564 let mut inner = self.0.state.borrow_mut();
1565 inner.renderer.draw(scene);
1566 }
1567
1568 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1569 let inner = self.0.state.borrow();
1570 inner.renderer.sprite_atlas().clone()
1571 }
1572
1573 fn show_window_menu(&self, position: Point<Pixels>) {
1574 let state = self.0.state.borrow();
1575
1576 check_reply(
1577 || "X11 UngrabPointer failed.",
1578 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1579 )
1580 .log_err();
1581
1582 let Some(coords) = self.get_root_position(position).log_err() else {
1583 return;
1584 };
1585 let message = ClientMessageEvent::new(
1586 32,
1587 self.0.x_window,
1588 state.atoms._GTK_SHOW_WINDOW_MENU,
1589 [
1590 XINPUT_ALL_DEVICE_GROUPS as u32,
1591 coords.dst_x as u32,
1592 coords.dst_y as u32,
1593 0,
1594 0,
1595 ],
1596 );
1597 check_reply(
1598 || "X11 SendEvent to show window menu failed.",
1599 self.0.xcb.send_event(
1600 false,
1601 state.x_root_window,
1602 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1603 message,
1604 ),
1605 )
1606 .log_err();
1607 }
1608
1609 fn start_window_move(&self) {
1610 const MOVERESIZE_MOVE: u32 = 8;
1611 self.send_moveresize(MOVERESIZE_MOVE).log_err();
1612 }
1613
1614 fn start_window_resize(&self, edge: ResizeEdge) {
1615 self.send_moveresize(edge.to_moveresize()).log_err();
1616 }
1617
1618 fn window_decorations(&self) -> crate::Decorations {
1619 let state = self.0.state.borrow();
1620
1621 // Client window decorations require compositor support
1622 if !state.client_side_decorations_supported {
1623 return Decorations::Server;
1624 }
1625
1626 match state.decorations {
1627 WindowDecorations::Server => Decorations::Server,
1628 WindowDecorations::Client => {
1629 let tiling = if state.fullscreen {
1630 Tiling::tiled()
1631 } else if let Some(edge_constraints) = &state.edge_constraints {
1632 edge_constraints.to_tiling()
1633 } else {
1634 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1635 Tiling {
1636 top: state.maximized_vertical,
1637 bottom: state.maximized_vertical,
1638 left: state.maximized_horizontal,
1639 right: state.maximized_horizontal,
1640 }
1641 };
1642 Decorations::Client { tiling }
1643 }
1644 }
1645 }
1646
1647 fn set_client_inset(&self, inset: Pixels) {
1648 let mut state = self.0.state.borrow_mut();
1649
1650 let dp = (inset.0 * state.scale_factor) as u32;
1651
1652 let insets = if state.fullscreen {
1653 [0, 0, 0, 0]
1654 } else if let Some(edge_constraints) = &state.edge_constraints {
1655 let left = if edge_constraints.left_tiled { 0 } else { dp };
1656 let top = if edge_constraints.top_tiled { 0 } else { dp };
1657 let right = if edge_constraints.right_tiled { 0 } else { dp };
1658 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1659
1660 [left, right, top, bottom]
1661 } else {
1662 let (left, right) = if state.maximized_horizontal {
1663 (0, 0)
1664 } else {
1665 (dp, dp)
1666 };
1667 let (top, bottom) = if state.maximized_vertical {
1668 (0, 0)
1669 } else {
1670 (dp, dp)
1671 };
1672 [left, right, top, bottom]
1673 };
1674
1675 if state.last_insets != insets {
1676 state.last_insets = insets;
1677
1678 check_reply(
1679 || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1680 self.0.xcb.change_property(
1681 xproto::PropMode::REPLACE,
1682 self.0.x_window,
1683 state.atoms._GTK_FRAME_EXTENTS,
1684 xproto::AtomEnum::CARDINAL,
1685 size_of::<u32>() as u8 * 8,
1686 4,
1687 bytemuck::cast_slice::<u32, u8>(&insets),
1688 ),
1689 )
1690 .log_err();
1691 }
1692 }
1693
1694 fn request_decorations(&self, mut decorations: crate::WindowDecorations) {
1695 let mut state = self.0.state.borrow_mut();
1696
1697 if matches!(decorations, crate::WindowDecorations::Client)
1698 && !state.client_side_decorations_supported
1699 {
1700 log::info!(
1701 "x11: no compositor present, falling back to server-side window decorations"
1702 );
1703 decorations = crate::WindowDecorations::Server;
1704 }
1705
1706 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1707 let hints_data: [u32; 5] = match decorations {
1708 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1709 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1710 };
1711
1712 let success = check_reply(
1713 || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1714 self.0.xcb.change_property(
1715 xproto::PropMode::REPLACE,
1716 self.0.x_window,
1717 state.atoms._MOTIF_WM_HINTS,
1718 state.atoms._MOTIF_WM_HINTS,
1719 size_of::<u32>() as u8 * 8,
1720 5,
1721 bytemuck::cast_slice::<u32, u8>(&hints_data),
1722 ),
1723 )
1724 .log_err();
1725
1726 let Some(()) = success else {
1727 return;
1728 };
1729
1730 match decorations {
1731 WindowDecorations::Server => {
1732 state.decorations = WindowDecorations::Server;
1733 let is_transparent = state.is_transparent();
1734 state.renderer.update_transparency(is_transparent);
1735 }
1736 WindowDecorations::Client => {
1737 state.decorations = WindowDecorations::Client;
1738 let is_transparent = state.is_transparent();
1739 state.renderer.update_transparency(is_transparent);
1740 }
1741 }
1742
1743 drop(state);
1744 let mut callbacks = self.0.callbacks.borrow_mut();
1745 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1746 appearance_changed();
1747 }
1748 }
1749
1750 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1751 let mut state = self.0.state.borrow_mut();
1752 let client = state.client.clone();
1753 drop(state);
1754 client.update_ime_position(bounds);
1755 }
1756
1757 fn gpu_specs(&self) -> Option<GpuSpecs> {
1758 self.0.state.borrow().renderer.gpu_specs().into()
1759 }
1760}