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