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