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 let hovered_window = self
796 .xcb_connection
797 .query_pointer(state.x_root_window)
798 .unwrap()
799 .reply()
800 .unwrap()
801 .child;
802 self.set_hovered(hovered_window == self.x_window);
803 }
804
805 pub fn close(&self) {
806 let mut callbacks = self.callbacks.borrow_mut();
807 if let Some(fun) = callbacks.close.take() {
808 fun()
809 }
810 }
811
812 pub fn refresh(&self) {
813 let mut cb = self.callbacks.borrow_mut();
814 if let Some(ref mut fun) = cb.request_frame {
815 fun();
816 }
817 }
818
819 pub fn handle_input(&self, input: PlatformInput) {
820 if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
821 if !fun(input.clone()).propagate {
822 return;
823 }
824 }
825 if let PlatformInput::KeyDown(event) = input {
826 let mut state = self.state.borrow_mut();
827 if let Some(mut input_handler) = state.input_handler.take() {
828 if let Some(ime_key) = &event.keystroke.ime_key {
829 drop(state);
830 input_handler.replace_text_in_range(None, ime_key);
831 state = self.state.borrow_mut();
832 }
833 state.input_handler = Some(input_handler);
834 }
835 }
836 }
837
838 pub fn handle_ime_commit(&self, text: String) {
839 let mut state = self.state.borrow_mut();
840 if let Some(mut input_handler) = state.input_handler.take() {
841 drop(state);
842 input_handler.replace_text_in_range(None, &text);
843 let mut state = self.state.borrow_mut();
844 state.input_handler = Some(input_handler);
845 }
846 }
847
848 pub fn handle_ime_preedit(&self, text: String) {
849 let mut state = self.state.borrow_mut();
850 if let Some(mut input_handler) = state.input_handler.take() {
851 drop(state);
852 input_handler.replace_and_mark_text_in_range(None, &text, None);
853 let mut state = self.state.borrow_mut();
854 state.input_handler = Some(input_handler);
855 }
856 }
857
858 pub fn handle_ime_unmark(&self) {
859 let mut state = self.state.borrow_mut();
860 if let Some(mut input_handler) = state.input_handler.take() {
861 drop(state);
862 input_handler.unmark_text();
863 let mut state = self.state.borrow_mut();
864 state.input_handler = Some(input_handler);
865 }
866 }
867
868 pub fn handle_ime_delete(&self) {
869 let mut state = self.state.borrow_mut();
870 if let Some(mut input_handler) = state.input_handler.take() {
871 drop(state);
872 if let Some(marked) = input_handler.marked_text_range() {
873 input_handler.replace_text_in_range(Some(marked), "");
874 }
875 let mut state = self.state.borrow_mut();
876 state.input_handler = Some(input_handler);
877 }
878 }
879
880 pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
881 let mut state = self.state.borrow_mut();
882 let mut bounds: Option<Bounds<Pixels>> = None;
883 if let Some(mut input_handler) = state.input_handler.take() {
884 drop(state);
885 if let Some(range) = input_handler.selected_text_range() {
886 bounds = input_handler.bounds_for_range(range);
887 }
888 let mut state = self.state.borrow_mut();
889 state.input_handler = Some(input_handler);
890 };
891 bounds
892 }
893
894 pub fn configure(&self, bounds: Bounds<i32>) {
895 let mut resize_args = None;
896 let is_resize;
897 {
898 let mut state = self.state.borrow_mut();
899 let bounds = bounds.map(|f| px(f as f32 / state.scale_factor));
900
901 is_resize = bounds.size.width != state.bounds.size.width
902 || bounds.size.height != state.bounds.size.height;
903
904 // If it's a resize event (only width/height changed), we ignore `bounds.origin`
905 // because it contains wrong values.
906 if is_resize {
907 state.bounds.size = bounds.size;
908 } else {
909 state.bounds = bounds;
910 }
911
912 let gpu_size = query_render_extent(&self.xcb_connection, self.x_window);
913 if true {
914 state.renderer.update_drawable_size(size(
915 DevicePixels(gpu_size.width as i32),
916 DevicePixels(gpu_size.height as i32),
917 ));
918 resize_args = Some((state.content_size(), state.scale_factor));
919 }
920 if let Some(value) = state.last_sync_counter.take() {
921 sync::set_counter(&self.xcb_connection, state.counter_id, value).unwrap();
922 }
923 }
924
925 let mut callbacks = self.callbacks.borrow_mut();
926 if let Some((content_size, scale_factor)) = resize_args {
927 if let Some(ref mut fun) = callbacks.resize {
928 fun(content_size, scale_factor)
929 }
930 }
931 if !is_resize {
932 if let Some(ref mut fun) = callbacks.moved {
933 fun()
934 }
935 }
936 }
937
938 pub fn set_active(&self, focus: bool) {
939 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
940 fun(focus);
941 }
942 }
943
944 pub fn set_hovered(&self, focus: bool) {
945 if let Some(ref mut fun) = self.callbacks.borrow_mut().hovered_status_change {
946 fun(focus);
947 }
948 }
949
950 pub fn set_appearance(&mut self, appearance: WindowAppearance) {
951 let mut state = self.state.borrow_mut();
952 state.appearance = appearance;
953 let is_transparent = state.is_transparent();
954 state.renderer.update_transparency(is_transparent);
955 state.appearance = appearance;
956 drop(state);
957 let mut callbacks = self.callbacks.borrow_mut();
958 if let Some(ref mut fun) = callbacks.appearance_changed {
959 (fun)()
960 }
961 }
962}
963
964impl PlatformWindow for X11Window {
965 fn bounds(&self) -> Bounds<Pixels> {
966 self.0.state.borrow().bounds
967 }
968
969 fn is_maximized(&self) -> bool {
970 let state = self.0.state.borrow();
971
972 // A maximized window that gets minimized will still retain its maximized state.
973 !state.hidden && state.maximized_vertical && state.maximized_horizontal
974 }
975
976 fn window_bounds(&self) -> WindowBounds {
977 let state = self.0.state.borrow();
978 if self.is_maximized() {
979 WindowBounds::Maximized(state.bounds)
980 } else {
981 WindowBounds::Windowed(state.bounds)
982 }
983 }
984
985 fn content_size(&self) -> Size<Pixels> {
986 // We divide by the scale factor here because this value is queried to determine how much to draw,
987 // but it will be multiplied later by the scale to adjust for scaling.
988 let state = self.0.state.borrow();
989 state
990 .content_size()
991 .map(|size| size.div(state.scale_factor))
992 }
993
994 fn scale_factor(&self) -> f32 {
995 self.0.state.borrow().scale_factor
996 }
997
998 fn appearance(&self) -> WindowAppearance {
999 self.0.state.borrow().appearance
1000 }
1001
1002 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1003 Some(self.0.state.borrow().display.clone())
1004 }
1005
1006 fn mouse_position(&self) -> Point<Pixels> {
1007 let reply = self
1008 .0
1009 .xcb_connection
1010 .query_pointer(self.0.x_window)
1011 .unwrap()
1012 .reply()
1013 .unwrap();
1014 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
1015 }
1016
1017 fn modifiers(&self) -> Modifiers {
1018 self.0
1019 .state
1020 .borrow()
1021 .client
1022 .0
1023 .upgrade()
1024 .map(|ref_cell| ref_cell.borrow().modifiers)
1025 .unwrap_or_default()
1026 }
1027
1028 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1029 self.0.state.borrow_mut().input_handler = Some(input_handler);
1030 }
1031
1032 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1033 self.0.state.borrow_mut().input_handler.take()
1034 }
1035
1036 fn prompt(
1037 &self,
1038 _level: PromptLevel,
1039 _msg: &str,
1040 _detail: Option<&str>,
1041 _answers: &[&str],
1042 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
1043 None
1044 }
1045
1046 fn activate(&self) {
1047 let data = [1, xproto::Time::CURRENT_TIME.into(), 0, 0, 0];
1048 let message = xproto::ClientMessageEvent::new(
1049 32,
1050 self.0.x_window,
1051 self.0.state.borrow().atoms._NET_ACTIVE_WINDOW,
1052 data,
1053 );
1054 self.0
1055 .xcb_connection
1056 .send_event(
1057 false,
1058 self.0.state.borrow().x_root_window,
1059 xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY,
1060 message,
1061 )
1062 .log_err();
1063 self.0
1064 .xcb_connection
1065 .set_input_focus(
1066 xproto::InputFocus::POINTER_ROOT,
1067 self.0.x_window,
1068 xproto::Time::CURRENT_TIME,
1069 )
1070 .log_err();
1071 self.0.xcb_connection.flush().unwrap();
1072 }
1073
1074 fn is_active(&self) -> bool {
1075 self.0.state.borrow().active
1076 }
1077
1078 fn is_hovered(&self) -> bool {
1079 self.0.state.borrow().hovered
1080 }
1081
1082 fn set_title(&mut self, title: &str) {
1083 self.0
1084 .xcb_connection
1085 .change_property8(
1086 xproto::PropMode::REPLACE,
1087 self.0.x_window,
1088 xproto::AtomEnum::WM_NAME,
1089 xproto::AtomEnum::STRING,
1090 title.as_bytes(),
1091 )
1092 .unwrap();
1093
1094 self.0
1095 .xcb_connection
1096 .change_property8(
1097 xproto::PropMode::REPLACE,
1098 self.0.x_window,
1099 self.0.state.borrow().atoms._NET_WM_NAME,
1100 self.0.state.borrow().atoms.UTF8_STRING,
1101 title.as_bytes(),
1102 )
1103 .unwrap();
1104 self.0.xcb_connection.flush().unwrap();
1105 }
1106
1107 fn set_app_id(&mut self, app_id: &str) {
1108 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
1109 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
1110 data.push(b'\0');
1111 data.extend(app_id.bytes()); // class
1112
1113 self.0
1114 .xcb_connection
1115 .change_property8(
1116 xproto::PropMode::REPLACE,
1117 self.0.x_window,
1118 xproto::AtomEnum::WM_CLASS,
1119 xproto::AtomEnum::STRING,
1120 &data,
1121 )
1122 .unwrap()
1123 .check()
1124 .unwrap();
1125 }
1126
1127 fn set_edited(&mut self, _edited: bool) {
1128 log::info!("ignoring macOS specific set_edited");
1129 }
1130
1131 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1132 let mut state = self.0.state.borrow_mut();
1133 state.background_appearance = background_appearance;
1134 let transparent = state.is_transparent();
1135 state.renderer.update_transparency(transparent);
1136 }
1137
1138 fn show_character_palette(&self) {
1139 log::info!("ignoring macOS specific show_character_palette");
1140 }
1141
1142 fn minimize(&self) {
1143 let state = self.0.state.borrow();
1144 const WINDOW_ICONIC_STATE: u32 = 3;
1145 let message = ClientMessageEvent::new(
1146 32,
1147 self.0.x_window,
1148 state.atoms.WM_CHANGE_STATE,
1149 [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
1150 );
1151 self.0
1152 .xcb_connection
1153 .send_event(
1154 false,
1155 state.x_root_window,
1156 EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
1157 message,
1158 )
1159 .unwrap()
1160 .check()
1161 .unwrap();
1162 }
1163
1164 fn zoom(&self) {
1165 let state = self.0.state.borrow();
1166 self.set_wm_hints(
1167 WmHintPropertyState::Toggle,
1168 state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
1169 state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
1170 );
1171 }
1172
1173 fn toggle_fullscreen(&self) {
1174 let state = self.0.state.borrow();
1175 self.set_wm_hints(
1176 WmHintPropertyState::Toggle,
1177 state.atoms._NET_WM_STATE_FULLSCREEN,
1178 xproto::AtomEnum::NONE.into(),
1179 );
1180 }
1181
1182 fn is_fullscreen(&self) -> bool {
1183 self.0.state.borrow().fullscreen
1184 }
1185
1186 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1187 self.0.callbacks.borrow_mut().request_frame = Some(callback);
1188 }
1189
1190 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1191 self.0.callbacks.borrow_mut().input = Some(callback);
1192 }
1193
1194 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1195 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
1196 }
1197
1198 fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1199 self.0.callbacks.borrow_mut().hovered_status_change = Some(callback);
1200 }
1201
1202 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1203 self.0.callbacks.borrow_mut().resize = Some(callback);
1204 }
1205
1206 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1207 self.0.callbacks.borrow_mut().moved = Some(callback);
1208 }
1209
1210 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1211 self.0.callbacks.borrow_mut().should_close = Some(callback);
1212 }
1213
1214 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1215 self.0.callbacks.borrow_mut().close = Some(callback);
1216 }
1217
1218 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1219 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
1220 }
1221
1222 fn draw(&self, scene: &Scene) {
1223 let mut inner = self.0.state.borrow_mut();
1224 inner.renderer.draw(scene);
1225 }
1226
1227 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1228 let inner = self.0.state.borrow();
1229 inner.renderer.sprite_atlas().clone()
1230 }
1231
1232 fn show_window_menu(&self, position: Point<Pixels>) {
1233 let state = self.0.state.borrow();
1234
1235 self.0
1236 .xcb_connection
1237 .ungrab_pointer(x11rb::CURRENT_TIME)
1238 .unwrap()
1239 .check()
1240 .unwrap();
1241
1242 let coords = self.get_root_position(position);
1243 let message = ClientMessageEvent::new(
1244 32,
1245 self.0.x_window,
1246 state.atoms._GTK_SHOW_WINDOW_MENU,
1247 [
1248 XINPUT_MASTER_DEVICE as u32,
1249 coords.dst_x as u32,
1250 coords.dst_y as u32,
1251 0,
1252 0,
1253 ],
1254 );
1255 self.0
1256 .xcb_connection
1257 .send_event(
1258 false,
1259 state.x_root_window,
1260 EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
1261 message,
1262 )
1263 .unwrap()
1264 .check()
1265 .unwrap();
1266 }
1267
1268 fn start_window_move(&self) {
1269 const MOVERESIZE_MOVE: u32 = 8;
1270 self.send_moveresize(MOVERESIZE_MOVE);
1271 }
1272
1273 fn start_window_resize(&self, edge: ResizeEdge) {
1274 self.send_moveresize(edge.to_moveresize());
1275 }
1276
1277 fn window_decorations(&self) -> crate::Decorations {
1278 let state = self.0.state.borrow();
1279
1280 // Client window decorations require compositor support
1281 if !state.client_side_decorations_supported {
1282 return Decorations::Server;
1283 }
1284
1285 match state.decorations {
1286 WindowDecorations::Server => Decorations::Server,
1287 WindowDecorations::Client => {
1288 let tiling = if state.fullscreen {
1289 Tiling::tiled()
1290 } else if let Some(edge_constraints) = &state.edge_constraints {
1291 edge_constraints.to_tiling()
1292 } else {
1293 // https://source.chromium.org/chromium/chromium/src/+/main:ui/ozone/platform/x11/x11_window.cc;l=2519;drc=1f14cc876cc5bf899d13284a12c451498219bb2d
1294 Tiling {
1295 top: state.maximized_vertical,
1296 bottom: state.maximized_vertical,
1297 left: state.maximized_horizontal,
1298 right: state.maximized_horizontal,
1299 }
1300 };
1301 Decorations::Client { tiling }
1302 }
1303 }
1304 }
1305
1306 fn set_client_inset(&self, inset: Pixels) {
1307 let mut state = self.0.state.borrow_mut();
1308
1309 let dp = (inset.0 * state.scale_factor) as u32;
1310
1311 let insets = if state.fullscreen {
1312 [0, 0, 0, 0]
1313 } else if let Some(edge_constraints) = &state.edge_constraints {
1314 let left = if edge_constraints.left_tiled { 0 } else { dp };
1315 let top = if edge_constraints.top_tiled { 0 } else { dp };
1316 let right = if edge_constraints.right_tiled { 0 } else { dp };
1317 let bottom = if edge_constraints.bottom_tiled { 0 } else { dp };
1318
1319 [left, right, top, bottom]
1320 } else {
1321 let (left, right) = if state.maximized_horizontal {
1322 (0, 0)
1323 } else {
1324 (dp, dp)
1325 };
1326 let (top, bottom) = if state.maximized_vertical {
1327 (0, 0)
1328 } else {
1329 (dp, dp)
1330 };
1331 [left, right, top, bottom]
1332 };
1333
1334 if state.last_insets != insets {
1335 state.last_insets = insets;
1336
1337 self.0
1338 .xcb_connection
1339 .change_property(
1340 xproto::PropMode::REPLACE,
1341 self.0.x_window,
1342 state.atoms._GTK_FRAME_EXTENTS,
1343 xproto::AtomEnum::CARDINAL,
1344 size_of::<u32>() as u8 * 8,
1345 4,
1346 bytemuck::cast_slice::<u32, u8>(&insets),
1347 )
1348 .unwrap()
1349 .check()
1350 .unwrap();
1351 }
1352 }
1353
1354 fn request_decorations(&self, mut decorations: crate::WindowDecorations) {
1355 let mut state = self.0.state.borrow_mut();
1356
1357 if matches!(decorations, crate::WindowDecorations::Client)
1358 && !state.client_side_decorations_supported
1359 {
1360 log::info!(
1361 "x11: no compositor present, falling back to server-side window decorations"
1362 );
1363 decorations = crate::WindowDecorations::Server;
1364 }
1365
1366 // https://github.com/rust-windowing/winit/blob/master/src/platform_impl/linux/x11/util/hint.rs#L53-L87
1367 let hints_data: [u32; 5] = match decorations {
1368 WindowDecorations::Server => [1 << 1, 0, 1, 0, 0],
1369 WindowDecorations::Client => [1 << 1, 0, 0, 0, 0],
1370 };
1371
1372 self.0
1373 .xcb_connection
1374 .change_property(
1375 xproto::PropMode::REPLACE,
1376 self.0.x_window,
1377 state.atoms._MOTIF_WM_HINTS,
1378 state.atoms._MOTIF_WM_HINTS,
1379 std::mem::size_of::<u32>() as u8 * 8,
1380 5,
1381 bytemuck::cast_slice::<u32, u8>(&hints_data),
1382 )
1383 .unwrap()
1384 .check()
1385 .unwrap();
1386
1387 match decorations {
1388 WindowDecorations::Server => {
1389 state.decorations = WindowDecorations::Server;
1390 let is_transparent = state.is_transparent();
1391 state.renderer.update_transparency(is_transparent);
1392 }
1393 WindowDecorations::Client => {
1394 state.decorations = WindowDecorations::Client;
1395 let is_transparent = state.is_transparent();
1396 state.renderer.update_transparency(is_transparent);
1397 }
1398 }
1399
1400 drop(state);
1401 let mut callbacks = self.0.callbacks.borrow_mut();
1402 if let Some(appearance_changed) = callbacks.appearance_changed.as_mut() {
1403 appearance_changed();
1404 }
1405 }
1406
1407 fn gpu_specs(&self) -> Option<GPUSpecs> {
1408 self.0.state.borrow().renderer.gpu_specs().into()
1409 }
1410}