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