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 if let Some(title) = titlebar.title {
520 check_reply(
521 || "X11 ChangeProperty8 on window title failed.",
522 xcb.change_property8(
523 xproto::PropMode::REPLACE,
524 x_window,
525 xproto::AtomEnum::WM_NAME,
526 xproto::AtomEnum::STRING,
527 title.as_bytes(),
528 ),
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
682/// A handle to an X11 window which destroys it on Drop.
683pub struct X11WindowHandle {
684 id: xproto::Window,
685 xcb: Rc<XCBConnection>,
686}
687
688impl Drop for X11WindowHandle {
689 fn drop(&mut self) {
690 maybe!({
691 check_reply(
692 || "X11 DestroyWindow failed while dropping X11WindowHandle.",
693 self.xcb.destroy_window(self.id),
694 )?;
695 xcb_flush(&self.xcb);
696 anyhow::Ok(())
697 })
698 .log_err();
699 }
700}
701
702pub(crate) struct X11Window(pub X11WindowStatePtr);
703
704impl Drop for X11Window {
705 fn drop(&mut self) {
706 let mut state = self.0.state.borrow_mut();
707 state.renderer.destroy();
708
709 let destroy_x_window = maybe!({
710 check_reply(
711 || "X11 DestroyWindow failure.",
712 self.0.xcb.destroy_window(self.0.x_window),
713 )?;
714 xcb_flush(&self.0.xcb);
715
716 anyhow::Ok(())
717 })
718 .log_err();
719
720 if destroy_x_window.is_some() {
721 // Mark window as destroyed so that we can filter out when X11 events
722 // for it still come in.
723 state.destroyed = true;
724
725 let this_ptr = self.0.clone();
726 let client_ptr = state.client.clone();
727 state
728 .executor
729 .spawn(async move {
730 this_ptr.close();
731 client_ptr.drop_window(this_ptr.x_window);
732 })
733 .detach();
734 }
735
736 drop(state);
737 }
738}
739
740enum WmHintPropertyState {
741 // Remove = 0,
742 // Add = 1,
743 Toggle = 2,
744}
745
746impl X11Window {
747 pub fn new(
748 handle: AnyWindowHandle,
749 client: X11ClientStatePtr,
750 executor: ForegroundExecutor,
751 gpu_context: &BladeContext,
752 params: WindowParams,
753 xcb: &Rc<XCBConnection>,
754 client_side_decorations_supported: bool,
755 x_main_screen_index: usize,
756 x_window: xproto::Window,
757 atoms: &XcbAtoms,
758 scale_factor: f32,
759 appearance: WindowAppearance,
760 ) -> anyhow::Result<Self> {
761 let ptr = X11WindowStatePtr {
762 state: Rc::new(RefCell::new(X11WindowState::new(
763 handle,
764 client,
765 executor,
766 gpu_context,
767 params,
768 xcb,
769 client_side_decorations_supported,
770 x_main_screen_index,
771 x_window,
772 atoms,
773 scale_factor,
774 appearance,
775 )?)),
776 callbacks: Rc::new(RefCell::new(Callbacks::default())),
777 xcb: xcb.clone(),
778 x_window,
779 };
780
781 let state = ptr.state.borrow_mut();
782 ptr.set_wm_properties(state)?;
783
784 Ok(Self(ptr))
785 }
786
787 fn set_wm_hints<C: Display + Send + Sync + 'static, F: FnOnce() -> C>(
788 &self,
789 failure_context: F,
790 wm_hint_property_state: WmHintPropertyState,
791 prop1: u32,
792 prop2: u32,
793 ) -> anyhow::Result<()> {
794 let state = self.0.state.borrow();
795 let message = ClientMessageEvent::new(
796 32,
797 self.0.x_window,
798 state.atoms._NET_WM_STATE,
799 [wm_hint_property_state as u32, prop1, prop2, 1, 0],
800 );
801 check_reply(
802 failure_context,
803 self.0.xcb.send_event(
804 false,
805 state.x_root_window,
806 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
807 message,
808 ),
809 )?;
810 xcb_flush(&self.0.xcb);
811 Ok(())
812 }
813
814 fn get_root_position(
815 &self,
816 position: Point<Pixels>,
817 ) -> anyhow::Result<TranslateCoordinatesReply> {
818 let state = self.0.state.borrow();
819 get_reply(
820 || "X11 TranslateCoordinates failed.",
821 self.0.xcb.translate_coordinates(
822 self.0.x_window,
823 state.x_root_window,
824 (position.x.0 * state.scale_factor) as i16,
825 (position.y.0 * state.scale_factor) as i16,
826 ),
827 )
828 }
829
830 fn send_moveresize(&self, flag: u32) -> anyhow::Result<()> {
831 let state = self.0.state.borrow();
832
833 check_reply(
834 || "X11 UngrabPointer before move/resize of window failed.",
835 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
836 )?;
837
838 let pointer = get_reply(
839 || "X11 QueryPointer before move/resize of window failed.",
840 self.0.xcb.query_pointer(self.0.x_window),
841 )?;
842 let message = ClientMessageEvent::new(
843 32,
844 self.0.x_window,
845 state.atoms._NET_WM_MOVERESIZE,
846 [
847 pointer.root_x as u32,
848 pointer.root_y as u32,
849 flag,
850 0, // Left mouse button
851 0,
852 ],
853 );
854 check_reply(
855 || "X11 SendEvent to move/resize window failed.",
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
864 xcb_flush(&self.0.xcb);
865 Ok(())
866 }
867}
868
869impl X11WindowStatePtr {
870 pub fn should_close(&self) -> bool {
871 let mut cb = self.callbacks.borrow_mut();
872 if let Some(mut should_close) = cb.should_close.take() {
873 let result = (should_close)();
874 cb.should_close = Some(should_close);
875 result
876 } else {
877 true
878 }
879 }
880
881 pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> {
882 let mut state = self.state.borrow_mut();
883 if event.atom == state.atoms._NET_WM_STATE {
884 self.set_wm_properties(state)?;
885 } else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS {
886 self.set_edge_constraints(state)?;
887 }
888 Ok(())
889 }
890
891 fn set_edge_constraints(
892 &self,
893 mut state: std::cell::RefMut<X11WindowState>,
894 ) -> anyhow::Result<()> {
895 let reply = get_reply(
896 || "X11 GetProperty for _GTK_EDGE_CONSTRAINTS failed.",
897 self.xcb.get_property(
898 false,
899 self.x_window,
900 state.atoms._GTK_EDGE_CONSTRAINTS,
901 xproto::AtomEnum::CARDINAL,
902 0,
903 4,
904 ),
905 )?;
906
907 if reply.value_len != 0 {
908 if let Ok(bytes) = reply.value[0..4].try_into() {
909 let atom = u32::from_ne_bytes(bytes);
910 let edge_constraints = EdgeConstraints::from_atom(atom);
911 state.edge_constraints.replace(edge_constraints);
912 } else {
913 log::error!("Failed to parse GTK_EDGE_CONSTRAINTS");
914 }
915 }
916
917 Ok(())
918 }
919
920 fn set_wm_properties(
921 &self,
922 mut state: std::cell::RefMut<X11WindowState>,
923 ) -> anyhow::Result<()> {
924 let reply = get_reply(
925 || "X11 GetProperty for _NET_WM_STATE failed.",
926 self.xcb.get_property(
927 false,
928 self.x_window,
929 state.atoms._NET_WM_STATE,
930 xproto::AtomEnum::ATOM,
931 0,
932 u32::MAX,
933 ),
934 )?;
935
936 let atoms = reply
937 .value
938 .chunks_exact(4)
939 .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
940
941 state.active = false;
942 state.fullscreen = false;
943 state.maximized_vertical = false;
944 state.maximized_horizontal = false;
945 state.hidden = false;
946
947 for atom in atoms {
948 if atom == state.atoms._NET_WM_STATE_FOCUSED {
949 state.active = true;
950 } else if atom == state.atoms._NET_WM_STATE_FULLSCREEN {
951 state.fullscreen = true;
952 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_VERT {
953 state.maximized_vertical = true;
954 } else if atom == state.atoms._NET_WM_STATE_MAXIMIZED_HORZ {
955 state.maximized_horizontal = true;
956 } else if atom == state.atoms._NET_WM_STATE_HIDDEN {
957 state.hidden = true;
958 }
959 }
960
961 Ok(())
962 }
963
964 pub fn close(&self) {
965 let mut callbacks = self.callbacks.borrow_mut();
966 if let Some(fun) = callbacks.close.take() {
967 fun()
968 }
969 }
970
971 pub fn refresh(&self, request_frame_options: RequestFrameOptions) {
972 let mut cb = self.callbacks.borrow_mut();
973 if let Some(ref mut fun) = cb.request_frame {
974 fun(request_frame_options);
975 }
976 }
977
978 pub fn handle_input(&self, input: PlatformInput) {
979 if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
980 if !fun(input.clone()).propagate {
981 return;
982 }
983 }
984 if let PlatformInput::KeyDown(event) = input {
985 let mut state = self.state.borrow_mut();
986 if let Some(mut input_handler) = state.input_handler.take() {
987 if let Some(key_char) = &event.keystroke.key_char {
988 drop(state);
989 input_handler.replace_text_in_range(None, key_char);
990 state = self.state.borrow_mut();
991 }
992 state.input_handler = Some(input_handler);
993 }
994 }
995 }
996
997 pub fn handle_ime_commit(&self, text: String) {
998 let mut state = self.state.borrow_mut();
999 if let Some(mut input_handler) = state.input_handler.take() {
1000 drop(state);
1001 input_handler.replace_text_in_range(None, &text);
1002 let mut state = self.state.borrow_mut();
1003 state.input_handler = Some(input_handler);
1004 }
1005 }
1006
1007 pub fn handle_ime_preedit(&self, text: String) {
1008 let mut state = self.state.borrow_mut();
1009 if let Some(mut input_handler) = state.input_handler.take() {
1010 drop(state);
1011 input_handler.replace_and_mark_text_in_range(None, &text, None);
1012 let mut state = self.state.borrow_mut();
1013 state.input_handler = Some(input_handler);
1014 }
1015 }
1016
1017 pub fn handle_ime_unmark(&self) {
1018 let mut state = self.state.borrow_mut();
1019 if let Some(mut input_handler) = state.input_handler.take() {
1020 drop(state);
1021 input_handler.unmark_text();
1022 let mut state = self.state.borrow_mut();
1023 state.input_handler = Some(input_handler);
1024 }
1025 }
1026
1027 pub fn handle_ime_delete(&self) {
1028 let mut state = self.state.borrow_mut();
1029 if let Some(mut input_handler) = state.input_handler.take() {
1030 drop(state);
1031 if let Some(marked) = input_handler.marked_text_range() {
1032 input_handler.replace_text_in_range(Some(marked), "");
1033 }
1034 let mut state = self.state.borrow_mut();
1035 state.input_handler = Some(input_handler);
1036 }
1037 }
1038
1039 pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
1040 let mut state = self.state.borrow_mut();
1041 let mut bounds: Option<Bounds<Pixels>> = None;
1042 if let Some(mut input_handler) = state.input_handler.take() {
1043 drop(state);
1044 if let Some(selection) = input_handler.selected_text_range(true) {
1045 bounds = input_handler.bounds_for_range(selection.range);
1046 }
1047 let mut state = self.state.borrow_mut();
1048 state.input_handler = Some(input_handler);
1049 };
1050 bounds
1051 }
1052
1053 pub fn set_bounds(&self, bounds: Bounds<i32>) -> anyhow::Result<()> {
1054 let mut resize_args = None;
1055 let is_resize;
1056 {
1057 let mut state = self.state.borrow_mut();
1058 let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
1059
1060 is_resize = bounds.size.width != state.bounds.size.width
1061 || bounds.size.height != state.bounds.size.height;
1062
1063 // If it's a resize event (only width/height changed), we ignore `bounds.origin`
1064 // because it contains wrong values.
1065 if is_resize {
1066 state.bounds.size = bounds.size;
1067 } else {
1068 state.bounds = bounds;
1069 }
1070
1071 let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
1072 if true {
1073 state.renderer.update_drawable_size(size(
1074 DevicePixels(gpu_size.width as i32),
1075 DevicePixels(gpu_size.height as i32),
1076 ));
1077 resize_args = Some((state.content_size(), state.scale_factor));
1078 }
1079 if let Some(value) = state.last_sync_counter.take() {
1080 check_reply(
1081 || "X11 sync SetCounter failed.",
1082 sync::set_counter(&self.xcb, state.counter_id, value),
1083 )?;
1084 }
1085 }
1086
1087 let mut callbacks = self.callbacks.borrow_mut();
1088 if let Some((content_size, scale_factor)) = resize_args {
1089 if let Some(ref mut fun) = callbacks.resize {
1090 fun(content_size, scale_factor)
1091 }
1092 }
1093 if !is_resize {
1094 if let Some(ref mut fun) = callbacks.moved {
1095 fun();
1096 }
1097 }
1098
1099 Ok(())
1100 }
1101
1102 pub fn set_active(&self, focus: bool) {
1103 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
1104 fun(focus);
1105 }
1106 }
1107
1108 pub fn set_hovered(&self, focus: bool) {
1109 if let Some(ref mut fun) = self.callbacks.borrow_mut().hovered_status_change {
1110 fun(focus);
1111 }
1112 }
1113
1114 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1115 let mut state = self.state.borrow_mut();
1116 state.appearance = appearance;
1117 let is_transparent = state.is_transparent();
1118 state.renderer.update_transparency(is_transparent);
1119 state.appearance = appearance;
1120 drop(state);
1121 let mut callbacks = self.callbacks.borrow_mut();
1122 if let Some(ref mut fun) = callbacks.appearance_changed {
1123 (fun)()
1124 }
1125 }
1126}
1127
1128impl PlatformWindow for X11Window {
1129 fn bounds(&self) -> Bounds<Pixels> {
1130 self.0.state.borrow().bounds
1131 }
1132
1133 fn is_maximized(&self) -> bool {
1134 let state = self.0.state.borrow();
1135
1136 // A maximized window that gets minimized will still retain its maximized state.
1137 !state.hidden && state.maximized_vertical && state.maximized_horizontal
1138 }
1139
1140 fn window_bounds(&self) -> WindowBounds {
1141 let state = self.0.state.borrow();
1142 if self.is_maximized() {
1143 WindowBounds::Maximized(state.bounds)
1144 } else {
1145 WindowBounds::Windowed(state.bounds)
1146 }
1147 }
1148
1149 fn inner_window_bounds(&self) -> WindowBounds {
1150 let state = self.0.state.borrow();
1151 if self.is_maximized() {
1152 WindowBounds::Maximized(state.bounds)
1153 } else {
1154 let mut bounds = state.bounds;
1155 let [left, right, top, bottom] = state.last_insets;
1156
1157 let [left, right, top, bottom] = [
1158 Pixels((left as f32) / state.scale_factor),
1159 Pixels((right as f32) / state.scale_factor),
1160 Pixels((top as f32) / state.scale_factor),
1161 Pixels((bottom as f32) / state.scale_factor),
1162 ];
1163
1164 bounds.origin.x += left;
1165 bounds.origin.y += top;
1166 bounds.size.width -= left + right;
1167 bounds.size.height -= top + bottom;
1168
1169 WindowBounds::Windowed(bounds)
1170 }
1171 }
1172
1173 fn content_size(&self) -> Size<Pixels> {
1174 // We divide by the scale factor here because this value is queried to determine how much to draw,
1175 // but it will be multiplied later by the scale to adjust for scaling.
1176 let state = self.0.state.borrow();
1177 state
1178 .content_size()
1179 .map(|size| size.div(state.scale_factor))
1180 }
1181
1182 fn resize(&mut self, size: Size<Pixels>) {
1183 let state = self.0.state.borrow();
1184 let size = size.to_device_pixels(state.scale_factor);
1185 let width = size.width.0 as u32;
1186 let height = size.height.0 as u32;
1187
1188 check_reply(
1189 || {
1190 format!(
1191 "X11 ConfigureWindow failed. width: {}, height: {}",
1192 width, height
1193 )
1194 },
1195 self.0.xcb.configure_window(
1196 self.0.x_window,
1197 &xproto::ConfigureWindowAux::new()
1198 .width(width)
1199 .height(height),
1200 ),
1201 )
1202 .log_err();
1203 xcb_flush(&self.0.xcb);
1204 }
1205
1206 fn scale_factor(&self) -> f32 {
1207 self.0.state.borrow().scale_factor
1208 }
1209
1210 fn appearance(&self) -> WindowAppearance {
1211 self.0.state.borrow().appearance
1212 }
1213
1214 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1215 Some(self.0.state.borrow().display.clone())
1216 }
1217
1218 fn mouse_position(&self) -> Point<Pixels> {
1219 get_reply(
1220 || "X11 QueryPointer failed.",
1221 self.0.xcb.query_pointer(self.0.x_window),
1222 )
1223 .log_err()
1224 .map_or(Point::new(Pixels(0.0), Pixels(0.0)), |reply| {
1225 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1226 })
1227 }
1228
1229 fn modifiers(&self) -> Modifiers {
1230 self.0
1231 .state
1232 .borrow()
1233 .client
1234 .0
1235 .upgrade()
1236 .map(|ref_cell| ref_cell.borrow().modifiers)
1237 .unwrap_or_default()
1238 }
1239
1240 fn capslock(&self) -> crate::Capslock {
1241 self.0
1242 .state
1243 .borrow()
1244 .client
1245 .0
1246 .upgrade()
1247 .map(|ref_cell| ref_cell.borrow().capslock)
1248 .unwrap_or_default()
1249 }
1250
1251 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1252 self.0.state.borrow_mut().input_handler = Some(input_handler);
1253 }
1254
1255 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1256 self.0.state.borrow_mut().input_handler.take()
1257 }
1258
1259 fn prompt(
1260 &self,
1261 _level: PromptLevel,
1262 _msg: &str,
1263 _detail: Option<&str>,
1264 _answers: &[PromptButton],
1265 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1266 None
1267 }
1268
1269 fn activate(&self) {
1270 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1271 let message = xproto::ClientMessageEvent::new(
1272 32,
1273 self.0.x_window,
1274 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1275 data,
1276 );
1277 self.0
1278 .xcb
1279 .send_event(
1280 false,
1281 self.0.state.borrow().x_root_window,
1282 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1283 message,
1284 )
1285 .log_err();
1286 self.0
1287 .xcb
1288 .set_input_focus(
1289 xproto::InputFocus::POINTER_ROOT,
1290 self.0.x_window,
1291 xproto::Time::CURRENT_TIME,
1292 )
1293 .log_err();
1294 xcb_flush(&self.0.xcb);
1295 }
1296
1297 fn is_active(&self) -> bool {
1298 self.0.state.borrow().active
1299 }
1300
1301 fn is_hovered(&self) -> bool {
1302 self.0.state.borrow().hovered
1303 }
1304
1305 fn set_title(&mut self, title: &str) {
1306 check_reply(
1307 || "X11 ChangeProperty8 on WM_NAME failed.",
1308 self.0.xcb.change_property8(
1309 xproto::PropMode::REPLACE,
1310 self.0.x_window,
1311 xproto::AtomEnum::WM_NAME,
1312 xproto::AtomEnum::STRING,
1313 title.as_bytes(),
1314 ),
1315 )
1316 .log_err();
1317
1318 check_reply(
1319 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1320 self.0.xcb.change_property8(
1321 xproto::PropMode::REPLACE,
1322 self.0.x_window,
1323 self.0.state.borrow().atoms._NET_WM_NAME,
1324 self.0.state.borrow().atoms.UTF8_STRING,
1325 title.as_bytes(),
1326 ),
1327 )
1328 .log_err();
1329 xcb_flush(&self.0.xcb);
1330 }
1331
1332 fn set_app_id(&mut self, app_id: &str) {
1333 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1334 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1335 data.push(b'\0');
1336 data.extend(app_id.bytes()); // class
1337
1338 check_reply(
1339 || "X11 ChangeProperty8 for WM_CLASS failed.",
1340 self.0.xcb.change_property8(
1341 xproto::PropMode::REPLACE,
1342 self.0.x_window,
1343 xproto::AtomEnum::WM_CLASS,
1344 xproto::AtomEnum::STRING,
1345 &data,
1346 ),
1347 )
1348 .log_err();
1349 }
1350
1351 fn map_window(&mut self) -> anyhow::Result<()> {
1352 check_reply(
1353 || "X11 MapWindow failed.",
1354 self.0.xcb.map_window(self.0.x_window),
1355 )?;
1356 Ok(())
1357 }
1358
1359 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1360 let mut state = self.0.state.borrow_mut();
1361 state.background_appearance = background_appearance;
1362 let transparent = state.is_transparent();
1363 state.renderer.update_transparency(transparent);
1364 }
1365
1366 fn minimize(&self) {
1367 let state = self.0.state.borrow();
1368 const WINDOW_ICONIC_STATE: u32 = 3;
1369 let message = ClientMessageEvent::new(
1370 32,
1371 self.0.x_window,
1372 state.atoms.WM_CHANGE_STATE,
1373 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1374 );
1375 check_reply(
1376 || "X11 SendEvent to minimize window failed.",
1377 self.0.xcb.send_event(
1378 false,
1379 state.x_root_window,
1380 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1381 message,
1382 ),
1383 )
1384 .log_err();
1385 }
1386
1387 fn zoom(&self) {
1388 let state = self.0.state.borrow();
1389 self.set_wm_hints(
1390 || "X11 SendEvent to maximize a window failed.",
1391 WmHintPropertyState::Toggle,
1392 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1393 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1394 )
1395 .log_err();
1396 }
1397
1398 fn toggle_fullscreen(&self) {
1399 let state = self.0.state.borrow();
1400 self.set_wm_hints(
1401 || "X11 SendEvent to fullscreen a window failed.",
1402 WmHintPropertyState::Toggle,
1403 state.atoms._NET_WM_STATE_FULLSCREEN,
1404 xproto::AtomEnum::NONE.into(),
1405 )
1406 .log_err();
1407 }
1408
1409 fn is_fullscreen(&self) -> bool {
1410 self.0.state.borrow().fullscreen
1411 }
1412
1413 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1414 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1415 }
1416
1417 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1418 self.0.callbacks.borrow_mut().input = Some(callback);
1419 }
1420
1421 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1422 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1423 }
1424
1425 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1426 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1427 }
1428
1429 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1430 self.0.callbacks.borrow_mut().resize = Some(callback);
1431 }
1432
1433 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1434 self.0.callbacks.borrow_mut().moved = Some(callback);
1435 }
1436
1437 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1438 self.0.callbacks.borrow_mut().should_close = Some(callback);
1439 }
1440
1441 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1442 self.0.callbacks.borrow_mut().close = Some(callback);
1443 }
1444
1445 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1446 }
1447
1448 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1449 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1450 }
1451
1452 fn draw(&self, scene: &Scene) {
1453 let mut inner = self.0.state.borrow_mut();
1454 inner.renderer.draw(scene);
1455 }
1456
1457 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1458 let inner = self.0.state.borrow();
1459 inner.renderer.sprite_atlas().clone()
1460 }
1461
1462 fn show_window_menu(&self, position: Point<Pixels>) {
1463 let state = self.0.state.borrow();
1464
1465 check_reply(
1466 || "X11 UngrabPointer failed.",
1467 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1468 )
1469 .log_err();
1470
1471 let Some(coords) = self.get_root_position(position).log_err() else {
1472 return;
1473 };
1474 let message = ClientMessageEvent::new(
1475 32,
1476 self.0.x_window,
1477 state.atoms._GTK_SHOW_WINDOW_MENU,
1478 [
1479 XINPUT_ALL_DEVICE_GROUPS as u32,
1480 coords.dst_x as u32,
1481 coords.dst_y as u32,
1482 0,
1483 0,
1484 ],
1485 );
1486 check_reply(
1487 || "X11 SendEvent to show window menu failed.",
1488 self.0.xcb.send_event(
1489 false,
1490 state.x_root_window,
1491 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1492 message,
1493 ),
1494 )
1495 .log_err();
1496 }
1497
1498 fn start_window_move(&self) {
1499 const MOVERESIZE_MOVE: u32 = 8;
1500 self.send_moveresize(MOVERESIZE_MOVE).log_err();
1501 }
1502
1503 fn start_window_resize(&self, edge: ResizeEdge) {
1504 self.send_moveresize(edge.to_moveresize()).log_err();
1505 }
1506
1507 fn window_decorations(&self) -> crate::Decorations {
1508 let state = self.0.state.borrow();
1509
1510 // Client window decorations require compositor support
1511 if !state.client_side_decorations_supported {
1512 return Decorations::Server;
1513 }
1514
1515 match state.decorations {
1516 WindowDecorations::Server => Decorations::Server,
1517 WindowDecorations::Client => {
1518 let tiling = if state.fullscreen {
1519 Tiling::tiled()
1520 } else if let Some(edge_constraints) = &state.edge_constraints {
1521 edge_constraints.to_tiling()
1522 } else {
1523 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1524 Tiling {
1525 top: state.maximized_vertical,
1526 bottom: state.maximized_vertical,
1527 left: state.maximized_horizontal,
1528 right: state.maximized_horizontal,
1529 }
1530 };
1531 Decorations::Client { tiling }
1532 }
1533 }
1534 }
1535
1536 fn set_client_inset(&self, inset: Pixels) {
1537 let mut state = self.0.state.borrow_mut();
1538
1539 let dp = (inset.0 * state.scale_factor) as u32;
1540
1541 let insets = if state.fullscreen {
1542 [0, 0, 0, 0]
1543 } else if let Some(edge_constraints) = &state.edge_constraints {
1544 let left = if edge_constraints.left_tiled { 0 } else { dp };
1545 let top = if edge_constraints.top_tiled { 0 } else { dp };
1546 let right = if edge_constraints.right_tiled { 0 } else { dp };
1547 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1548
1549 [left, right, top, bottom]
1550 } else {
1551 let (left, right) = if state.maximized_horizontal {
1552 (0, 0)
1553 } else {
1554 (dp, dp)
1555 };
1556 let (top, bottom) = if state.maximized_vertical {
1557 (0, 0)
1558 } else {
1559 (dp, dp)
1560 };
1561 [left, right, top, bottom]
1562 };
1563
1564 if state.last_insets != insets {
1565 state.last_insets = insets;
1566
1567 check_reply(
1568 || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1569 self.0.xcb.change_property(
1570 xproto::PropMode::REPLACE,
1571 self.0.x_window,
1572 state.atoms._GTK_FRAME_EXTENTS,
1573 xproto::AtomEnum::CARDINAL,
1574 size_of::<u32>() as u8 * 8,
1575 4,
1576 bytemuck::cast_slice::<u32, u8>(&insets),
1577 ),
1578 )
1579 .log_err();
1580 }
1581 }
1582
1583 fn request_decorations(&self, mut decorations: crate::WindowDecorations) {
1584 let mut state = self.0.state.borrow_mut();
1585
1586 if matches!(decorations, crate::WindowDecorations::Client)
1587 && !state.client_side_decorations_supported
1588 {
1589 log::info!(
1590 "x11: no compositor present, falling back to server-side window decorations"
1591 );
1592 decorations = crate::WindowDecorations::Server;
1593 }
1594
1595 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1596 let hints_data: [u32; 5] = match decorations {
1597 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1598 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1599 };
1600
1601 let success = check_reply(
1602 || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1603 self.0.xcb.change_property(
1604 xproto::PropMode::REPLACE,
1605 self.0.x_window,
1606 state.atoms._MOTIF_WM_HINTS,
1607 state.atoms._MOTIF_WM_HINTS,
1608 size_of::<u32>() as u8 * 8,
1609 5,
1610 bytemuck::cast_slice::<u32, u8>(&hints_data),
1611 ),
1612 )
1613 .log_err();
1614
1615 let Some(()) = success else {
1616 return;
1617 };
1618
1619 match decorations {
1620 WindowDecorations::Server => {
1621 state.decorations = WindowDecorations::Server;
1622 let is_transparent = state.is_transparent();
1623 state.renderer.update_transparency(is_transparent);
1624 }
1625 WindowDecorations::Client => {
1626 state.decorations = WindowDecorations::Client;
1627 let is_transparent = state.is_transparent();
1628 state.renderer.update_transparency(is_transparent);
1629 }
1630 }
1631
1632 drop(state);
1633 let mut callbacks = self.0.callbacks.borrow_mut();
1634 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1635 appearance_changed();
1636 }
1637 }
1638
1639 fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
1640 let mut state = self.0.state.borrow_mut();
1641 let client = state.client.clone();
1642 drop(state);
1643 client.update_ime_position(bounds);
1644 }
1645
1646 fn gpu_specs(&self) -> Option<GpuSpecs> {
1647 self.0.state.borrow().renderer.gpu_specs().into()
1648 }
1649}