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 .event_mask(
435 xproto::EventMask::EXPOSURE
436 | xproto::EventMask::STRUCTURE_NOTIFY
437 | xproto::EventMask::FOCUS_CHANGE
438 | xproto::EventMask::KEY_PRESS
439 | xproto::EventMask::KEY_RELEASE
440 | xproto::EventMask::PROPERTY_CHANGE
441 | xproto::EventMask::VISIBILITY_CHANGE,
442 );
443
444 let mut bounds = params.bounds.to_device_pixels(scale_factor);
445 if bounds.size.width.0 == 0 || bounds.size.height.0 == 0 {
446 log::warn!(
447 "Window bounds contain a zero value. height={}, width={}. Falling back to defaults.",
448 bounds.size.height.0,
449 bounds.size.width.0
450 );
451 bounds.size.width = 800.into();
452 bounds.size.height = 600.into();
453 }
454
455 check_reply(
456 || {
457 format!(
458 "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: {}",
459 visual.depth,
460 x_window,
461 visual_set.root,
462 bounds.origin.x.0 + 2,
463 bounds.origin.y.0,
464 bounds.size.width.0,
465 bounds.size.height.0
466 )
467 },
468 xcb.create_window(
469 visual.depth,
470 x_window,
471 visual_set.root,
472 (bounds.origin.x.0 + 2) as i16,
473 bounds.origin.y.0 as i16,
474 bounds.size.width.0 as u16,
475 bounds.size.height.0 as u16,
476 0,
477 xproto::WindowClass::INPUT_OUTPUT,
478 visual.id,
479 &win_aux,
480 ),
481 )?;
482
483 // Collect errors during setup, so that window can be destroyed on failure.
484 let setup_result = maybe!({
485 let pid = std::process::id();
486 check_reply(
487 || "X11 ChangeProperty for _NET_WM_PID failed.",
488 xcb.change_property32(
489 xproto::PropMode::REPLACE,
490 x_window,
491 atoms._NET_WM_PID,
492 xproto::AtomEnum::CARDINAL,
493 &[pid],
494 ),
495 )?;
496
497 if let Some(size) = params.window_min_size {
498 let mut size_hints = WmSizeHints::new();
499 let min_size = (size.width.0 as i32, size.height.0 as i32);
500 size_hints.min_size = Some(min_size);
501 check_reply(
502 || {
503 format!(
504 "X11 change of WM_SIZE_HINTS failed. min_size: {:?}",
505 min_size
506 )
507 },
508 size_hints.set_normal_hints(xcb, x_window),
509 )?;
510 }
511
512 let reply = get_reply(|| "X11 GetGeometry failed.", xcb.get_geometry(x_window))?;
513 if reply.x == 0 && reply.y == 0 {
514 bounds.origin.x.0 += 2;
515 // Work around a bug where our rendered content appears
516 // outside the window bounds when opened at the default position
517 // (14px, 49px on X + Gnome + Ubuntu 22).
518 let x = bounds.origin.x.0;
519 let y = bounds.origin.y.0;
520 check_reply(
521 || format!("X11 ConfigureWindow failed. x: {}, y: {}", x, y),
522 xcb.configure_window(x_window, &xproto::ConfigureWindowAux::new().x(x).y(y)),
523 )?;
524 }
525 if let Some(titlebar) = params.titlebar
526 && let Some(title) = titlebar.title
527 {
528 check_reply(
529 || "X11 ChangeProperty8 on window title failed.",
530 xcb.change_property8(
531 xproto::PropMode::REPLACE,
532 x_window,
533 xproto::AtomEnum::WM_NAME,
534 xproto::AtomEnum::STRING,
535 title.as_bytes(),
536 ),
537 )?;
538 }
539
540 if params.kind == WindowKind::PopUp {
541 check_reply(
542 || "X11 ChangeProperty32 setting window type for pop-up failed.",
543 xcb.change_property32(
544 xproto::PropMode::REPLACE,
545 x_window,
546 atoms._NET_WM_WINDOW_TYPE,
547 xproto::AtomEnum::ATOM,
548 &[atoms._NET_WM_WINDOW_TYPE_NOTIFICATION],
549 ),
550 )?;
551 }
552
553 if params.kind == WindowKind::Floating || params.kind == WindowKind::Dialog {
554 if let Some(parent_window) = parent_window.as_ref().map(|w| w.x_window) {
555 // WM_TRANSIENT_FOR hint indicating the main application window. For floating windows, we set
556 // a parent window (WM_TRANSIENT_FOR) such that the window manager knows where to
557 // place the floating window in relation to the main window.
558 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
559 check_reply(
560 || "X11 ChangeProperty32 setting WM_TRANSIENT_FOR for floating window failed.",
561 xcb.change_property32(
562 xproto::PropMode::REPLACE,
563 x_window,
564 atoms.WM_TRANSIENT_FOR,
565 xproto::AtomEnum::WINDOW,
566 &[parent_window],
567 ),
568 )?;
569 }
570 }
571
572 let parent = if params.kind == WindowKind::Dialog
573 && let Some(parent) = parent_window
574 {
575 parent.add_child(x_window);
576
577 Some(parent)
578 } else {
579 None
580 };
581
582 if params.kind == WindowKind::Dialog {
583 // _NET_WM_WINDOW_TYPE_DIALOG indicates that this is a dialog (floating) window
584 // https://specifications.freedesktop.org/wm-spec/1.4/ar01s05.html
585 check_reply(
586 || "X11 ChangeProperty32 setting window type for dialog window failed.",
587 xcb.change_property32(
588 xproto::PropMode::REPLACE,
589 x_window,
590 atoms._NET_WM_WINDOW_TYPE,
591 xproto::AtomEnum::ATOM,
592 &[atoms._NET_WM_WINDOW_TYPE_DIALOG],
593 ),
594 )?;
595
596 // We set the modal state for dialog windows, so that the window manager
597 // can handle it appropriately (e.g., prevent interaction with the parent window
598 // while the dialog is open).
599 check_reply(
600 || "X11 ChangeProperty32 setting modal state for dialog window failed.",
601 xcb.change_property32(
602 xproto::PropMode::REPLACE,
603 x_window,
604 atoms._NET_WM_STATE,
605 xproto::AtomEnum::ATOM,
606 &[atoms._NET_WM_STATE_MODAL],
607 ),
608 )?;
609 }
610
611 check_reply(
612 || "X11 ChangeProperty32 setting protocols failed.",
613 xcb.change_property32(
614 xproto::PropMode::REPLACE,
615 x_window,
616 atoms.WM_PROTOCOLS,
617 xproto::AtomEnum::ATOM,
618 &[atoms.WM_DELETE_WINDOW, atoms._NET_WM_SYNC_REQUEST],
619 ),
620 )?;
621
622 get_reply(
623 || "X11 sync protocol initialize failed.",
624 sync::initialize(xcb, 3, 1),
625 )?;
626 let sync_request_counter = xcb.generate_id()?;
627 check_reply(
628 || "X11 sync CreateCounter failed.",
629 sync::create_counter(xcb, sync_request_counter, sync::Int64 { lo: 0, hi: 0 }),
630 )?;
631
632 check_reply(
633 || "X11 ChangeProperty32 setting sync request counter failed.",
634 xcb.change_property32(
635 xproto::PropMode::REPLACE,
636 x_window,
637 atoms._NET_WM_SYNC_REQUEST_COUNTER,
638 xproto::AtomEnum::CARDINAL,
639 &[sync_request_counter],
640 ),
641 )?;
642
643 check_reply(
644 || "X11 XiSelectEvents failed.",
645 xcb.xinput_xi_select_events(
646 x_window,
647 &[xinput::EventMask {
648 deviceid: XINPUT_ALL_DEVICE_GROUPS,
649 mask: vec![
650 xinput::XIEventMask::MOTION
651 | xinput::XIEventMask::BUTTON_PRESS
652 | xinput::XIEventMask::BUTTON_RELEASE
653 | xinput::XIEventMask::ENTER
654 | xinput::XIEventMask::LEAVE,
655 ],
656 }],
657 ),
658 )?;
659
660 check_reply(
661 || "X11 XiSelectEvents for device changes failed.",
662 xcb.xinput_xi_select_events(
663 x_window,
664 &[xinput::EventMask {
665 deviceid: XINPUT_ALL_DEVICES,
666 mask: vec![
667 xinput::XIEventMask::HIERARCHY | xinput::XIEventMask::DEVICE_CHANGED,
668 ],
669 }],
670 ),
671 )?;
672
673 xcb_flush(xcb);
674
675 let renderer = {
676 let raw_window = RawWindow {
677 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
678 xcb,
679 ) as *mut _,
680 screen_id: x_screen_index,
681 window_id: x_window,
682 visual_id: visual.id,
683 };
684 let config = BladeSurfaceConfig {
685 // Note: this has to be done after the GPU init, or otherwise
686 // the sizes are immediately invalidated.
687 size: query_render_extent(xcb, x_window)?,
688 // We set it to transparent by default, even if we have client-side
689 // decorations, since those seem to work on X11 even without `true` here.
690 // If the window appearance changes, then the renderer will get updated
691 // too
692 transparent: false,
693 };
694 BladeRenderer::new(gpu_context, &raw_window, config)?
695 };
696
697 let display = Rc::new(X11Display::new(xcb, scale_factor, x_screen_index)?);
698
699 Ok(Self {
700 parent,
701 children: FxHashSet::default(),
702 client,
703 executor,
704 display,
705 x_root_window: visual_set.root,
706 bounds: bounds.to_pixels(scale_factor),
707 scale_factor,
708 renderer,
709 atoms: *atoms,
710 input_handler: None,
711 active: false,
712 hovered: false,
713 fullscreen: false,
714 maximized_vertical: false,
715 maximized_horizontal: false,
716 hidden: false,
717 appearance,
718 handle,
719 background_appearance: WindowBackgroundAppearance::Opaque,
720 destroyed: false,
721 client_side_decorations_supported,
722 decorations: WindowDecorations::Server,
723 last_insets: [0, 0, 0, 0],
724 edge_constraints: None,
725 counter_id: sync_request_counter,
726 last_sync_counter: None,
727 })
728 });
729
730 if setup_result.is_err() {
731 check_reply(
732 || "X11 DestroyWindow failed while cleaning it up after setup failure.",
733 xcb.destroy_window(x_window),
734 )?;
735 xcb_flush(xcb);
736 }
737
738 setup_result
739 }
740
741 fn content_size(&self) -> Size<Pixels> {
742 let size = self.renderer.viewport_size();
743 Size {
744 width: size.width.into(),
745 height: size.height.into(),
746 }
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: &BladeContext,
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(size(
1170 DevicePixels(gpu_size.width as i32),
1171 DevicePixels(gpu_size.height as i32),
1172 ));
1173 resize_args = Some((state.content_size(), state.scale_factor));
1174 }
1175 if let Some(value) = state.last_sync_counter.take() {
1176 check_reply(
1177 || "X11 sync SetCounter failed.",
1178 sync::set_counter(&self.xcb, state.counter_id, value),
1179 )?;
1180 }
1181 }
1182
1183 let mut callbacks = self.callbacks.borrow_mut();
1184 if let Some((content_size, scale_factor)) = resize_args
1185 && let Some(ref mut fun) = callbacks.resize
1186 {
1187 fun(content_size, scale_factor)
1188 }
1189
1190 if !is_resize && let Some(ref mut fun) = callbacks.moved {
1191 fun();
1192 }
1193
1194 Ok(())
1195 }
1196
1197 pub fn set_active(&self, focus: bool) {
1198 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
1199 fun(focus);
1200 }
1201 }
1202
1203 pub fn set_hovered(&self, focus: bool) {
1204 if let Some(ref mut fun) = self.callbacks.borrow_mut().hovered_status_change {
1205 fun(focus);
1206 }
1207 }
1208
1209 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1210 let mut state = self.state.borrow_mut();
1211 state.appearance = appearance;
1212 let is_transparent = state.is_transparent();
1213 state.renderer.update_transparency(is_transparent);
1214 state.appearance = appearance;
1215 drop(state);
1216 let mut callbacks = self.callbacks.borrow_mut();
1217 if let Some(ref mut fun) = callbacks.appearance_changed {
1218 (fun)()
1219 }
1220 }
1221}
1222
1223impl PlatformWindow for X11Window {
1224 fn bounds(&self) -> Bounds<Pixels> {
1225 self.0.state.borrow().bounds
1226 }
1227
1228 fn is_maximized(&self) -> bool {
1229 let state = self.0.state.borrow();
1230
1231 // A maximized window that gets minimized will still retain its maximized state.
1232 !state.hidden && state.maximized_vertical && state.maximized_horizontal
1233 }
1234
1235 fn window_bounds(&self) -> WindowBounds {
1236 let state = self.0.state.borrow();
1237 if self.is_maximized() {
1238 WindowBounds::Maximized(state.bounds)
1239 } else {
1240 WindowBounds::Windowed(state.bounds)
1241 }
1242 }
1243
1244 fn inner_window_bounds(&self) -> WindowBounds {
1245 let state = self.0.state.borrow();
1246 if self.is_maximized() {
1247 WindowBounds::Maximized(state.bounds)
1248 } else {
1249 let mut bounds = state.bounds;
1250 let [left, right, top, bottom] = state.last_insets;
1251
1252 let [left, right, top, bottom] = [
1253 Pixels((left as f32) / state.scale_factor),
1254 Pixels((right as f32) / state.scale_factor),
1255 Pixels((top as f32) / state.scale_factor),
1256 Pixels((bottom as f32) / state.scale_factor),
1257 ];
1258
1259 bounds.origin.x += left;
1260 bounds.origin.y += top;
1261 bounds.size.width -= left + right;
1262 bounds.size.height -= top + bottom;
1263
1264 WindowBounds::Windowed(bounds)
1265 }
1266 }
1267
1268 fn content_size(&self) -> Size<Pixels> {
1269 // We divide by the scale factor here because this value is queried to determine how much to draw,
1270 // but it will be multiplied later by the scale to adjust for scaling.
1271 let state = self.0.state.borrow();
1272 state
1273 .content_size()
1274 .map(|size| size.div(state.scale_factor))
1275 }
1276
1277 fn resize(&mut self, size: Size<Pixels>) {
1278 let state = self.0.state.borrow();
1279 let size = size.to_device_pixels(state.scale_factor);
1280 let width = size.width.0 as u32;
1281 let height = size.height.0 as u32;
1282
1283 check_reply(
1284 || {
1285 format!(
1286 "X11 ConfigureWindow failed. width: {}, height: {}",
1287 width, height
1288 )
1289 },
1290 self.0.xcb.configure_window(
1291 self.0.x_window,
1292 &xproto::ConfigureWindowAux::new()
1293 .width(width)
1294 .height(height),
1295 ),
1296 )
1297 .log_err();
1298 xcb_flush(&self.0.xcb);
1299 }
1300
1301 fn scale_factor(&self) -> f32 {
1302 self.0.state.borrow().scale_factor
1303 }
1304
1305 fn appearance(&self) -> WindowAppearance {
1306 self.0.state.borrow().appearance
1307 }
1308
1309 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1310 Some(self.0.state.borrow().display.clone())
1311 }
1312
1313 fn mouse_position(&self) -> Point<Pixels> {
1314 get_reply(
1315 || "X11 QueryPointer failed.",
1316 self.0.xcb.query_pointer(self.0.x_window),
1317 )
1318 .log_err()
1319 .map_or(Point::new(Pixels::ZERO, Pixels::ZERO), |reply| {
1320 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1321 })
1322 }
1323
1324 fn modifiers(&self) -> Modifiers {
1325 self.0
1326 .state
1327 .borrow()
1328 .client
1329 .0
1330 .upgrade()
1331 .map(|ref_cell| ref_cell.borrow().modifiers)
1332 .unwrap_or_default()
1333 }
1334
1335 fn capslock(&self) -> crate::Capslock {
1336 self.0
1337 .state
1338 .borrow()
1339 .client
1340 .0
1341 .upgrade()
1342 .map(|ref_cell| ref_cell.borrow().capslock)
1343 .unwrap_or_default()
1344 }
1345
1346 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1347 self.0.state.borrow_mut().input_handler = Some(input_handler);
1348 }
1349
1350 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1351 self.0.state.borrow_mut().input_handler.take()
1352 }
1353
1354 fn prompt(
1355 &self,
1356 _level: PromptLevel,
1357 _msg: &str,
1358 _detail: Option<&str>,
1359 _answers: &[PromptButton],
1360 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1361 None
1362 }
1363
1364 fn activate(&self) {
1365 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1366 let message = xproto::ClientMessageEvent::new(
1367 32,
1368 self.0.x_window,
1369 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1370 data,
1371 );
1372 self.0
1373 .xcb
1374 .send_event(
1375 false,
1376 self.0.state.borrow().x_root_window,
1377 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1378 message,
1379 )
1380 .log_err();
1381 self.0
1382 .xcb
1383 .set_input_focus(
1384 xproto::InputFocus::POINTER_ROOT,
1385 self.0.x_window,
1386 xproto::Time::CURRENT_TIME,
1387 )
1388 .log_err();
1389 xcb_flush(&self.0.xcb);
1390 }
1391
1392 fn is_active(&self) -> bool {
1393 self.0.state.borrow().active
1394 }
1395
1396 fn is_hovered(&self) -> bool {
1397 self.0.state.borrow().hovered
1398 }
1399
1400 fn set_title(&mut self, title: &str) {
1401 check_reply(
1402 || "X11 ChangeProperty8 on WM_NAME failed.",
1403 self.0.xcb.change_property8(
1404 xproto::PropMode::REPLACE,
1405 self.0.x_window,
1406 xproto::AtomEnum::WM_NAME,
1407 xproto::AtomEnum::STRING,
1408 title.as_bytes(),
1409 ),
1410 )
1411 .log_err();
1412
1413 check_reply(
1414 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1415 self.0.xcb.change_property8(
1416 xproto::PropMode::REPLACE,
1417 self.0.x_window,
1418 self.0.state.borrow().atoms._NET_WM_NAME,
1419 self.0.state.borrow().atoms.UTF8_STRING,
1420 title.as_bytes(),
1421 ),
1422 )
1423 .log_err();
1424 xcb_flush(&self.0.xcb);
1425 }
1426
1427 fn set_app_id(&mut self, app_id: &str) {
1428 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1429 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1430 data.push(b'\0');
1431 data.extend(app_id.bytes()); // class
1432
1433 check_reply(
1434 || "X11 ChangeProperty8 for WM_CLASS failed.",
1435 self.0.xcb.change_property8(
1436 xproto::PropMode::REPLACE,
1437 self.0.x_window,
1438 xproto::AtomEnum::WM_CLASS,
1439 xproto::AtomEnum::STRING,
1440 &data,
1441 ),
1442 )
1443 .log_err();
1444 }
1445
1446 fn map_window(&mut self) -> anyhow::Result<()> {
1447 check_reply(
1448 || "X11 MapWindow failed.",
1449 self.0.xcb.map_window(self.0.x_window),
1450 )?;
1451 Ok(())
1452 }
1453
1454 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1455 let mut state = self.0.state.borrow_mut();
1456 state.background_appearance = background_appearance;
1457 let transparent = state.is_transparent();
1458 state.renderer.update_transparency(transparent);
1459 }
1460
1461 fn minimize(&self) {
1462 let state = self.0.state.borrow();
1463 const WINDOW_ICONIC_STATE: u32 = 3;
1464 let message = ClientMessageEvent::new(
1465 32,
1466 self.0.x_window,
1467 state.atoms.WM_CHANGE_STATE,
1468 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1469 );
1470 check_reply(
1471 || "X11 SendEvent to minimize window failed.",
1472 self.0.xcb.send_event(
1473 false,
1474 state.x_root_window,
1475 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1476 message,
1477 ),
1478 )
1479 .log_err();
1480 }
1481
1482 fn zoom(&self) {
1483 let state = self.0.state.borrow();
1484 self.set_wm_hints(
1485 || "X11 SendEvent to maximize a window failed.",
1486 WmHintPropertyState::Toggle,
1487 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1488 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1489 )
1490 .log_err();
1491 }
1492
1493 fn toggle_fullscreen(&self) {
1494 let state = self.0.state.borrow();
1495 self.set_wm_hints(
1496 || "X11 SendEvent to fullscreen a window failed.",
1497 WmHintPropertyState::Toggle,
1498 state.atoms._NET_WM_STATE_FULLSCREEN,
1499 xproto::AtomEnum::NONE.into(),
1500 )
1501 .log_err();
1502 }
1503
1504 fn is_fullscreen(&self) -> bool {
1505 self.0.state.borrow().fullscreen
1506 }
1507
1508 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1509 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1510 }
1511
1512 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1513 self.0.callbacks.borrow_mut().input = Some(callback);
1514 }
1515
1516 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1517 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1518 }
1519
1520 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1521 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1522 }
1523
1524 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1525 self.0.callbacks.borrow_mut().resize = Some(callback);
1526 }
1527
1528 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1529 self.0.callbacks.borrow_mut().moved = Some(callback);
1530 }
1531
1532 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1533 self.0.callbacks.borrow_mut().should_close = Some(callback);
1534 }
1535
1536 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1537 self.0.callbacks.borrow_mut().close = Some(callback);
1538 }
1539
1540 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1541 }
1542
1543 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1544 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1545 }
1546
1547 fn draw(&self, scene: &Scene) {
1548 let mut inner = self.0.state.borrow_mut();
1549 inner.renderer.draw(scene);
1550 }
1551
1552 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1553 let inner = self.0.state.borrow();
1554 inner.renderer.sprite_atlas().clone()
1555 }
1556
1557 fn show_window_menu(&self, position: Point<Pixels>) {
1558 let state = self.0.state.borrow();
1559
1560 check_reply(
1561 || "X11 UngrabPointer failed.",
1562 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1563 )
1564 .log_err();
1565
1566 let Some(coords) = self.get_root_position(position).log_err() else {
1567 return;
1568 };
1569 let message = ClientMessageEvent::new(
1570 32,
1571 self.0.x_window,
1572 state.atoms._GTK_SHOW_WINDOW_MENU,
1573 [
1574 XINPUT_ALL_DEVICE_GROUPS as u32,
1575 coords.dst_x as u32,
1576 coords.dst_y as u32,
1577 0,
1578 0,
1579 ],
1580 );
1581 check_reply(
1582 || "X11 SendEvent to show window menu failed.",
1583 self.0.xcb.send_event(
1584 false,
1585 state.x_root_window,
1586 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1587 message,
1588 ),
1589 )
1590 .log_err();
1591 }
1592
1593 fn start_window_move(&self) {
1594 const MOVERESIZE_MOVE: u32 = 8;
1595 self.send_moveresize(MOVERESIZE_MOVE).log_err();
1596 }
1597
1598 fn start_window_resize(&self, edge: ResizeEdge) {
1599 self.send_moveresize(edge.to_moveresize()).log_err();
1600 }
1601
1602 fn window_decorations(&self) -> crate::Decorations {
1603 let state = self.0.state.borrow();
1604
1605 // Client window decorations require compositor support
1606 if !state.client_side_decorations_supported {
1607 return Decorations::Server;
1608 }
1609
1610 match state.decorations {
1611 WindowDecorations::Server => Decorations::Server,
1612 WindowDecorations::Client => {
1613 let tiling = if state.fullscreen {
1614 Tiling::tiled()
1615 } else if let Some(edge_constraints) = &state.edge_constraints {
1616 edge_constraints.to_tiling()
1617 } else {
1618 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1619 Tiling {
1620 top: state.maximized_vertical,
1621 bottom: state.maximized_vertical,
1622 left: state.maximized_horizontal,
1623 right: state.maximized_horizontal,
1624 }
1625 };
1626 Decorations::Client { tiling }
1627 }
1628 }
1629 }
1630
1631 fn set_client_inset(&self, inset: Pixels) {
1632 let mut state = self.0.state.borrow_mut();
1633
1634 let dp = (inset.0 * state.scale_factor) as u32;
1635
1636 let insets = if state.fullscreen {
1637 [0, 0, 0, 0]
1638 } else if let Some(edge_constraints) = &state.edge_constraints {
1639 let left = if edge_constraints.left_tiled { 0 } else { dp };
1640 let top = if edge_constraints.top_tiled { 0 } else { dp };
1641 let right = if edge_constraints.right_tiled { 0 } else { dp };
1642 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1643
1644 [left, right, top, bottom]
1645 } else {
1646 let (left, right) = if state.maximized_horizontal {
1647 (0, 0)
1648 } else {
1649 (dp, dp)
1650 };
1651 let (top, bottom) = if state.maximized_vertical {
1652 (0, 0)
1653 } else {
1654 (dp, dp)
1655 };
1656 [left, right, top, bottom]
1657 };
1658
1659 if state.last_insets != insets {
1660 state.last_insets = insets;
1661
1662 check_reply(
1663 || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1664 self.0.xcb.change_property(
1665 xproto::PropMode::REPLACE,
1666 self.0.x_window,
1667 state.atoms._GTK_FRAME_EXTENTS,
1668 xproto::AtomEnum::CARDINAL,
1669 size_of::<u32>() as u8 * 8,
1670 4,
1671 bytemuck::cast_slice::<u32, u8>(&insets),
1672 ),
1673 )
1674 .log_err();
1675 }
1676 }
1677
1678 fn request_decorations(&self, mut decorations: crate::WindowDecorations) {
1679 let mut state = self.0.state.borrow_mut();
1680
1681 if matches!(decorations, crate::WindowDecorations::Client)
1682 && !state.client_side_decorations_supported
1683 {
1684 log::info!(
1685 "x11: no compositor present, falling back to server-side window decorations"
1686 );
1687 decorations = crate::WindowDecorations::Server;
1688 }
1689
1690 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1691 let hints_data: [u32; 5] = match decorations {
1692 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1693 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1694 };
1695
1696 let success = check_reply(
1697 || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1698 self.0.xcb.change_property(
1699 xproto::PropMode::REPLACE,
1700 self.0.x_window,
1701 state.atoms._MOTIF_WM_HINTS,
1702 state.atoms._MOTIF_WM_HINTS,
1703 size_of::<u32>() as u8 * 8,
1704 5,
1705 bytemuck::cast_slice::<u32, u8>(&hints_data),
1706 ),
1707 )
1708 .log_err();
1709
1710 let Some(()) = success else {
1711 return;
1712 };
1713
1714 match decorations {
1715 WindowDecorations::Server => {
1716 state.decorations = WindowDecorations::Server;
1717 let is_transparent = state.is_transparent();
1718 state.renderer.update_transparency(is_transparent);
1719 }
1720 WindowDecorations::Client => {
1721 state.decorations = WindowDecorations::Client;
1722 let is_transparent = state.is_transparent();
1723 state.renderer.update_transparency(is_transparent);
1724 }
1725 }
1726
1727 drop(state);
1728 let mut callbacks = self.0.callbacks.borrow_mut();
1729 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1730 appearance_changed();
1731 }
1732 }
1733
1734 fn update_ime_position(&self, bounds: Bounds<Pixels>) {
1735 let mut state = self.0.state.borrow_mut();
1736 let client = state.client.clone();
1737 drop(state);
1738 client.update_ime_position(bounds);
1739 }
1740
1741 fn gpu_specs(&self) -> Option<GpuSpecs> {
1742 self.0.state.borrow().renderer.gpu_specs().into()
1743 }
1744}