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