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