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