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
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 dbg!("Window: handle_input called", &input);
960 if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
961 let result = fun(input.clone());
962 dbg!("Window: input callback result", result.propagate);
963 if !result.propagate {
964 return;
965 }
966 }
967 if let PlatformInput::KeyDown(event) = input {
968 dbg!("Window: handling KeyDown event", &event.keystroke);
969 // only allow shift modifier when inserting text
970 if event.keystroke.modifiers.is_subset_of(&Modifiers::shift()) {
971 dbg!("Window: modifiers subset of shift, checking for key_char");
972 let mut state = self.state.borrow_mut();
973 if let Some(mut input_handler) = state.input_handler.take() {
974 if let Some(key_char) = &event.keystroke.key_char {
975 dbg!("Window: inserting key_char directly", key_char);
976 drop(state);
977 input_handler.replace_text_in_range(None, key_char);
978 state = self.state.borrow_mut();
979 }
980 state.input_handler = Some(input_handler);
981 }
982 } else {
983 dbg!("Window: modifiers not subset of shift, ignoring key_char insertion");
984 }
985 }
986 }
987
988 pub fn handle_ime_commit(&self, text: String) {
989 dbg!("Window: handle_ime_commit called", &text);
990 let mut state = self.state.borrow_mut();
991 if let Some(mut input_handler) = state.input_handler.take() {
992 dbg!("Window: got input handler, calling replace_text_in_range");
993 drop(state);
994 input_handler.replace_text_in_range(None, &text);
995 let mut state = self.state.borrow_mut();
996 state.input_handler = Some(input_handler);
997 } else {
998 dbg!("Window: no input handler available for IME commit");
999 }
1000 }
1001
1002 pub fn handle_ime_preedit(&self, text: String) {
1003 dbg!("Window: handle_ime_preedit called", &text);
1004 let mut state = self.state.borrow_mut();
1005 if let Some(mut input_handler) = state.input_handler.take() {
1006 dbg!("Window: got input handler, calling replace_and_mark_text_in_range");
1007 drop(state);
1008 input_handler.replace_and_mark_text_in_range(None, &text, None);
1009 let mut state = self.state.borrow_mut();
1010 state.input_handler = Some(input_handler);
1011 } else {
1012 dbg!("Window: no input handler available for IME preedit");
1013 }
1014 }
1015
1016 pub fn handle_ime_unmark(&self) {
1017 dbg!("Window: handle_ime_unmark called");
1018 let mut state = self.state.borrow_mut();
1019 if let Some(mut input_handler) = state.input_handler.take() {
1020 dbg!("Window: got input handler, calling unmark_text");
1021 drop(state);
1022 input_handler.unmark_text();
1023 let mut state = self.state.borrow_mut();
1024 state.input_handler = Some(input_handler);
1025 } else {
1026 dbg!("Window: no input handler available for IME unmark");
1027 }
1028 }
1029
1030 pub fn handle_ime_delete(&self) {
1031 dbg!("Window: handle_ime_delete called");
1032 let mut state = self.state.borrow_mut();
1033 if let Some(mut input_handler) = state.input_handler.take() {
1034 drop(state);
1035 if let Some(marked) = input_handler.marked_text_range() {
1036 dbg!("Window: found marked text range, deleting", &marked);
1037 input_handler.replace_text_in_range(Some(marked), "");
1038 } else {
1039 dbg!("Window: no marked text range to delete");
1040 }
1041 let mut state = self.state.borrow_mut();
1042 state.input_handler = Some(input_handler);
1043 } else {
1044 dbg!("Window: no input handler available for IME delete");
1045 }
1046 }
1047
1048 pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
1049 dbg!("Window: get_ime_area called");
1050 let mut state = self.state.borrow_mut();
1051 let mut bounds: Option<Bounds<Pixels>> = None;
1052 if let Some(mut input_handler) = state.input_handler.take() {
1053 drop(state);
1054 if let Some(selection) = input_handler.selected_text_range(true) {
1055 bounds = input_handler.bounds_for_range(selection.range);
1056 dbg!("Window: got IME area bounds", bounds);
1057 } else {
1058 dbg!("Window: no selected text range for IME area");
1059 }
1060 let mut state = self.state.borrow_mut();
1061 state.input_handler = Some(input_handler);
1062 } else {
1063 dbg!("Window: no input handler available for IME area");
1064 };
1065 bounds
1066 }
1067
1068 pub fn set_bounds(&self, bounds: Bounds<i32>) -> anyhow::Result<()> {
1069 let mut resize_args = None;
1070 let is_resize;
1071 {
1072 let mut state = self.state.borrow_mut();
1073 let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
1074
1075 is_resize = bounds.size.width != state.bounds.size.width
1076 || bounds.size.height != state.bounds.size.height;
1077
1078 // If it's a resize event (only width/height changed), we ignore `bounds.origin`
1079 // because it contains wrong values.
1080 if is_resize {
1081 state.bounds.size = bounds.size;
1082 } else {
1083 state.bounds = bounds;
1084 }
1085
1086 let gpu_size = query_render_extent(&self.xcb, self.x_window)?;
1087 if true {
1088 state.renderer.update_drawable_size(size(
1089 DevicePixels(gpu_size.width as i32),
1090 DevicePixels(gpu_size.height as i32),
1091 ));
1092 resize_args = Some((state.content_size(), state.scale_factor));
1093 }
1094 if let Some(value) = state.last_sync_counter.take() {
1095 check_reply(
1096 || "X11 sync SetCounter failed.",
1097 sync::set_counter(&self.xcb, state.counter_id, value),
1098 )?;
1099 }
1100 }
1101
1102 let mut callbacks = self.callbacks.borrow_mut();
1103 if let Some((content_size, scale_factor)) = resize_args {
1104 if let Some(ref mut fun) = callbacks.resize {
1105 fun(content_size, scale_factor)
1106 }
1107 }
1108 if !is_resize {
1109 if let Some(ref mut fun) = callbacks.moved {
1110 fun();
1111 }
1112 }
1113
1114 Ok(())
1115 }
1116
1117 pub fn set_active(&self, focus: bool) {
1118 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
1119 fun(focus);
1120 }
1121 }
1122
1123 pub fn set_hovered(&self, focus: bool) {
1124 if let Some(ref mut fun) = self.callbacks.borrow_mut().hovered_status_change {
1125 fun(focus);
1126 }
1127 }
1128
1129 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
1130 let mut state = self.state.borrow_mut();
1131 state.appearance = appearance;
1132 let is_transparent = state.is_transparent();
1133 state.renderer.update_transparency(is_transparent);
1134 state.appearance = appearance;
1135 drop(state);
1136 let mut callbacks = self.callbacks.borrow_mut();
1137 if let Some(ref mut fun) = callbacks.appearance_changed {
1138 (fun)()
1139 }
1140 }
1141}
1142
1143impl PlatformWindow for X11Window {
1144 fn bounds(&self) -> Bounds<Pixels> {
1145 self.0.state.borrow().bounds
1146 }
1147
1148 fn is_maximized(&self) -> bool {
1149 let state = self.0.state.borrow();
1150
1151 // A maximized window that gets minimized will still retain its maximized state.
1152 !state.hidden && state.maximized_vertical && state.maximized_horizontal
1153 }
1154
1155 fn window_bounds(&self) -> WindowBounds {
1156 let state = self.0.state.borrow();
1157 if self.is_maximized() {
1158 WindowBounds::Maximized(state.bounds)
1159 } else {
1160 WindowBounds::Windowed(state.bounds)
1161 }
1162 }
1163
1164 fn inner_window_bounds(&self) -> WindowBounds {
1165 let state = self.0.state.borrow();
1166 if self.is_maximized() {
1167 WindowBounds::Maximized(state.bounds)
1168 } else {
1169 let mut bounds = state.bounds;
1170 let [left, right, top, bottom] = state.last_insets;
1171
1172 let [left, right, top, bottom] = [
1173 Pixels((left as f32) / state.scale_factor),
1174 Pixels((right as f32) / state.scale_factor),
1175 Pixels((top as f32) / state.scale_factor),
1176 Pixels((bottom as f32) / state.scale_factor),
1177 ];
1178
1179 bounds.origin.x += left;
1180 bounds.origin.y += top;
1181 bounds.size.width -= left + right;
1182 bounds.size.height -= top + bottom;
1183
1184 WindowBounds::Windowed(bounds)
1185 }
1186 }
1187
1188 fn content_size(&self) -> Size<Pixels> {
1189 // We divide by the scale factor here because this value is queried to determine how much to draw,
1190 // but it will be multiplied later by the scale to adjust for scaling.
1191 let state = self.0.state.borrow();
1192 state
1193 .content_size()
1194 .map(|size| size.div(state.scale_factor))
1195 }
1196
1197 fn resize(&mut self, size: Size<Pixels>) {
1198 let state = self.0.state.borrow();
1199 let size = size.to_device_pixels(state.scale_factor);
1200 let width = size.width.0 as u32;
1201 let height = size.height.0 as u32;
1202
1203 check_reply(
1204 || {
1205 format!(
1206 "X11 ConfigureWindow failed. width: {}, height: {}",
1207 width, height
1208 )
1209 },
1210 self.0.xcb.configure_window(
1211 self.0.x_window,
1212 &xproto::ConfigureWindowAux::new()
1213 .width(width)
1214 .height(height),
1215 ),
1216 )
1217 .log_err();
1218 xcb_flush(&self.0.xcb);
1219 }
1220
1221 fn scale_factor(&self) -> f32 {
1222 self.0.state.borrow().scale_factor
1223 }
1224
1225 fn appearance(&self) -> WindowAppearance {
1226 self.0.state.borrow().appearance
1227 }
1228
1229 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1230 Some(self.0.state.borrow().display.clone())
1231 }
1232
1233 fn mouse_position(&self) -> Point<Pixels> {
1234 get_reply(
1235 || "X11 QueryPointer failed.",
1236 self.0.xcb.query_pointer(self.0.x_window),
1237 )
1238 .log_err()
1239 .map_or(Point::new(Pixels(0.0), Pixels(0.0)), |reply| {
1240 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1241 })
1242 }
1243
1244 fn modifiers(&self) -> Modifiers {
1245 self.0
1246 .state
1247 .borrow()
1248 .client
1249 .0
1250 .upgrade()
1251 .map(|ref_cell| ref_cell.borrow().modifiers)
1252 .unwrap_or_default()
1253 }
1254
1255 fn capslock(&self) -> crate::Capslock {
1256 self.0
1257 .state
1258 .borrow()
1259 .client
1260 .0
1261 .upgrade()
1262 .map(|ref_cell| ref_cell.borrow().capslock)
1263 .unwrap_or_default()
1264 }
1265
1266 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1267 self.0.state.borrow_mut().input_handler = Some(input_handler);
1268 }
1269
1270 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1271 self.0.state.borrow_mut().input_handler.take()
1272 }
1273
1274 fn prompt(
1275 &self,
1276 _level: PromptLevel,
1277 _msg: &str,
1278 _detail: Option<&str>,
1279 _answers: &[PromptButton],
1280 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1281 None
1282 }
1283
1284 fn activate(&self) {
1285 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1286 let message = xproto::ClientMessageEvent::new(
1287 32,
1288 self.0.x_window,
1289 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1290 data,
1291 );
1292 self.0
1293 .xcb
1294 .send_event(
1295 false,
1296 self.0.state.borrow().x_root_window,
1297 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1298 message,
1299 )
1300 .log_err();
1301 self.0
1302 .xcb
1303 .set_input_focus(
1304 xproto::InputFocus::POINTER_ROOT,
1305 self.0.x_window,
1306 xproto::Time::CURRENT_TIME,
1307 )
1308 .log_err();
1309 xcb_flush(&self.0.xcb);
1310 }
1311
1312 fn is_active(&self) -> bool {
1313 self.0.state.borrow().active
1314 }
1315
1316 fn is_hovered(&self) -> bool {
1317 self.0.state.borrow().hovered
1318 }
1319
1320 fn set_title(&mut self, title: &str) {
1321 check_reply(
1322 || "X11 ChangeProperty8 on WM_NAME failed.",
1323 self.0.xcb.change_property8(
1324 xproto::PropMode::REPLACE,
1325 self.0.x_window,
1326 xproto::AtomEnum::WM_NAME,
1327 xproto::AtomEnum::STRING,
1328 title.as_bytes(),
1329 ),
1330 )
1331 .log_err();
1332
1333 check_reply(
1334 || "X11 ChangeProperty8 on _NET_WM_NAME failed.",
1335 self.0.xcb.change_property8(
1336 xproto::PropMode::REPLACE,
1337 self.0.x_window,
1338 self.0.state.borrow().atoms._NET_WM_NAME,
1339 self.0.state.borrow().atoms.UTF8_STRING,
1340 title.as_bytes(),
1341 ),
1342 )
1343 .log_err();
1344 xcb_flush(&self.0.xcb);
1345 }
1346
1347 fn set_app_id(&mut self, app_id: &str) {
1348 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1349 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1350 data.push(b'\0');
1351 data.extend(app_id.bytes()); // class
1352
1353 check_reply(
1354 || "X11 ChangeProperty8 for WM_CLASS failed.",
1355 self.0.xcb.change_property8(
1356 xproto::PropMode::REPLACE,
1357 self.0.x_window,
1358 xproto::AtomEnum::WM_CLASS,
1359 xproto::AtomEnum::STRING,
1360 &data,
1361 ),
1362 )
1363 .log_err();
1364 }
1365
1366 fn map_window(&mut self) -> anyhow::Result<()> {
1367 check_reply(
1368 || "X11 MapWindow failed.",
1369 self.0.xcb.map_window(self.0.x_window),
1370 )?;
1371 Ok(())
1372 }
1373
1374 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1375 let mut state = self.0.state.borrow_mut();
1376 state.background_appearance = background_appearance;
1377 let transparent = state.is_transparent();
1378 state.renderer.update_transparency(transparent);
1379 }
1380
1381 fn minimize(&self) {
1382 let state = self.0.state.borrow();
1383 const WINDOW_ICONIC_STATE: u32 = 3;
1384 let message = ClientMessageEvent::new(
1385 32,
1386 self.0.x_window,
1387 state.atoms.WM_CHANGE_STATE,
1388 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1389 );
1390 check_reply(
1391 || "X11 SendEvent to minimize window failed.",
1392 self.0.xcb.send_event(
1393 false,
1394 state.x_root_window,
1395 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1396 message,
1397 ),
1398 )
1399 .log_err();
1400 }
1401
1402 fn zoom(&self) {
1403 let state = self.0.state.borrow();
1404 self.set_wm_hints(
1405 || "X11 SendEvent to maximize a window failed.",
1406 WmHintPropertyState::Toggle,
1407 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1408 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1409 )
1410 .log_err();
1411 }
1412
1413 fn toggle_fullscreen(&self) {
1414 let state = self.0.state.borrow();
1415 self.set_wm_hints(
1416 || "X11 SendEvent to fullscreen a window failed.",
1417 WmHintPropertyState::Toggle,
1418 state.atoms._NET_WM_STATE_FULLSCREEN,
1419 xproto::AtomEnum::NONE.into(),
1420 )
1421 .log_err();
1422 }
1423
1424 fn is_fullscreen(&self) -> bool {
1425 self.0.state.borrow().fullscreen
1426 }
1427
1428 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1429 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1430 }
1431
1432 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1433 self.0.callbacks.borrow_mut().input = Some(callback);
1434 }
1435
1436 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1437 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1438 }
1439
1440 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1441 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1442 }
1443
1444 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1445 self.0.callbacks.borrow_mut().resize = Some(callback);
1446 }
1447
1448 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1449 self.0.callbacks.borrow_mut().moved = Some(callback);
1450 }
1451
1452 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1453 self.0.callbacks.borrow_mut().should_close = Some(callback);
1454 }
1455
1456 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1457 self.0.callbacks.borrow_mut().close = Some(callback);
1458 }
1459
1460 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1461 }
1462
1463 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1464 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1465 }
1466
1467 fn draw(&self, scene: &Scene) {
1468 let mut inner = self.0.state.borrow_mut();
1469 inner.renderer.draw(scene);
1470 }
1471
1472 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1473 let inner = self.0.state.borrow();
1474 inner.renderer.sprite_atlas().clone()
1475 }
1476
1477 fn show_window_menu(&self, position: Point<Pixels>) {
1478 let state = self.0.state.borrow();
1479
1480 check_reply(
1481 || "X11 UngrabPointer failed.",
1482 self.0.xcb.ungrab_pointer(x11rb::CURRENT_TIME),
1483 )
1484 .log_err();
1485
1486 let Some(coords) = self.get_root_position(position).log_err() else {
1487 return;
1488 };
1489 let message = ClientMessageEvent::new(
1490 32,
1491 self.0.x_window,
1492 state.atoms._GTK_SHOW_WINDOW_MENU,
1493 [
1494 XINPUT_ALL_DEVICE_GROUPS as u32,
1495 coords.dst_x as u32,
1496 coords.dst_y as u32,
1497 0,
1498 0,
1499 ],
1500 );
1501 check_reply(
1502 || "X11 SendEvent to show window menu failed.",
1503 self.0.xcb.send_event(
1504 false,
1505 state.x_root_window,
1506 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1507 message,
1508 ),
1509 )
1510 .log_err();
1511 }
1512
1513 fn start_window_move(&self) {
1514 const MOVERESIZE_MOVE: u32 = 8;
1515 self.send_moveresize(MOVERESIZE_MOVE).log_err();
1516 }
1517
1518 fn start_window_resize(&self, edge: ResizeEdge) {
1519 self.send_moveresize(edge.to_moveresize()).log_err();
1520 }
1521
1522 fn window_decorations(&self) -> crate::Decorations {
1523 let state = self.0.state.borrow();
1524
1525 // Client window decorations require compositor support
1526 if !state.client_side_decorations_supported {
1527 return Decorations::Server;
1528 }
1529
1530 match state.decorations {
1531 WindowDecorations::Server => Decorations::Server,
1532 WindowDecorations::Client => {
1533 let tiling = if state.fullscreen {
1534 Tiling::tiled()
1535 } else if let Some(edge_constraints) = &state.edge_constraints {
1536 edge_constraints.to_tiling()
1537 } else {
1538 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1539 Tiling {
1540 top: state.maximized_vertical,
1541 bottom: state.maximized_vertical,
1542 left: state.maximized_horizontal,
1543 right: state.maximized_horizontal,
1544 }
1545 };
1546 Decorations::Client { tiling }
1547 }
1548 }
1549 }
1550
1551 fn set_client_inset(&self, inset: Pixels) {
1552 let mut state = self.0.state.borrow_mut();
1553
1554 let dp = (inset.0 * state.scale_factor) as u32;
1555
1556 let insets = if state.fullscreen {
1557 [0, 0, 0, 0]
1558 } else if let Some(edge_constraints) = &state.edge_constraints {
1559 let left = if edge_constraints.left_tiled { 0 } else { dp };
1560 let top = if edge_constraints.top_tiled { 0 } else { dp };
1561 let right = if edge_constraints.right_tiled { 0 } else { dp };
1562 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1563
1564 [left, right, top, bottom]
1565 } else {
1566 let (left, right) = if state.maximized_horizontal {
1567 (0, 0)
1568 } else {
1569 (dp, dp)
1570 };
1571 let (top, bottom) = if state.maximized_vertical {
1572 (0, 0)
1573 } else {
1574 (dp, dp)
1575 };
1576 [left, right, top, bottom]
1577 };
1578
1579 if state.last_insets != insets {
1580 state.last_insets = insets;
1581
1582 check_reply(
1583 || "X11 ChangeProperty for _GTK_FRAME_EXTENTS failed.",
1584 self.0.xcb.change_property(
1585 xproto::PropMode::REPLACE,
1586 self.0.x_window,
1587 state.atoms._GTK_FRAME_EXTENTS,
1588 xproto::AtomEnum::CARDINAL,
1589 size_of::<u32>() as u8 * 8,
1590 4,
1591 bytemuck::cast_slice::<u32, u8>(&insets),
1592 ),
1593 )
1594 .log_err();
1595 }
1596 }
1597
1598 fn request_decorations(&self, mut decorations: crate::WindowDecorations) {
1599 let mut state = self.0.state.borrow_mut();
1600
1601 if matches!(decorations, crate::WindowDecorations::Client)
1602 && !state.client_side_decorations_supported
1603 {
1604 log::info!(
1605 "x11: no compositor present, falling back to server-side window decorations"
1606 );
1607 decorations = crate::WindowDecorations::Server;
1608 }
1609
1610 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1611 let hints_data: [u32; 5] = match decorations {
1612 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1613 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1614 };
1615
1616 let success = check_reply(
1617 || "X11 ChangeProperty for _MOTIF_WM_HINTS failed.",
1618 self.0.xcb.change_property(
1619 xproto::PropMode::REPLACE,
1620 self.0.x_window,
1621 state.atoms._MOTIF_WM_HINTS,
1622 state.atoms._MOTIF_WM_HINTS,
1623 size_of::<u32>() as u8 * 8,
1624 5,
1625 bytemuck::cast_slice::<u32, u8>(&hints_data),
1626 ),
1627 )
1628 .log_err();
1629
1630 let Some(()) = success else {
1631 return;
1632 };
1633
1634 match decorations {
1635 WindowDecorations::Server => {
1636 state.decorations = WindowDecorations::Server;
1637 let is_transparent = state.is_transparent();
1638 state.renderer.update_transparency(is_transparent);
1639 }
1640 WindowDecorations::Client => {
1641 state.decorations = WindowDecorations::Client;
1642 let is_transparent = state.is_transparent();
1643 state.renderer.update_transparency(is_transparent);
1644 }
1645 }
1646
1647 drop(state);
1648 let mut callbacks = self.0.callbacks.borrow_mut();
1649 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1650 appearance_changed();
1651 }
1652 }
1653
1654 fn update_ime_position(&self, bounds: Bounds<ScaledPixels>) {
1655 let mut state = self.0.state.borrow_mut();
1656 let client = state.client.clone();
1657 drop(state);
1658 client.update_ime_position(bounds);
1659 }
1660
1661 fn gpu_specs(&self) -> Option<GpuSpecs> {
1662 self.0.state.borrow().renderer.gpu_specs().into()
1663 }
1664}