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