1// todo(linux): remove
2#![allow(unused)]
3
4use crate::{
5 platform::blade::{BladeRenderer, BladeSurfaceConfig},
6 size, Bounds, DevicePixels, ForegroundExecutor, Modifiers, Pixels, Platform, PlatformAtlas,
7 PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptLevel,
8 Scene, Size, WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowOptions,
9 WindowParams, X11Client, X11ClientState, X11ClientStatePtr,
10};
11use blade_graphics as gpu;
12use parking_lot::Mutex;
13use raw_window_handle as rwh;
14use util::ResultExt;
15use x11rb::{
16 connection::{Connection as _, RequestConnection as _},
17 protocol::{
18 render::{self, ConnectionExt as _},
19 xinput::{self, ConnectionExt as _},
20 xproto::{self, ConnectionExt as _, CreateWindowAux},
21 },
22 resource_manager::Database,
23 wrapper::ConnectionExt as _,
24 xcb_ffi::XCBConnection,
25};
26
27use std::{
28 cell::{Ref, RefCell, RefMut},
29 collections::HashMap,
30 ffi::c_void,
31 iter::Zip,
32 mem,
33 num::NonZeroU32,
34 ops::Div,
35 ptr::NonNull,
36 rc::Rc,
37 sync::{self, Arc},
38};
39
40use super::X11Display;
41
42x11rb::atom_manager! {
43 pub XcbAtoms: AtomsCookie {
44 UTF8_STRING,
45 WM_PROTOCOLS,
46 WM_DELETE_WINDOW,
47 _NET_WM_NAME,
48 _NET_WM_STATE,
49 _NET_WM_STATE_MAXIMIZED_VERT,
50 _NET_WM_STATE_MAXIMIZED_HORZ,
51 }
52}
53
54fn query_render_extent(xcb_connection: &XCBConnection, x_window: xproto::Window) -> gpu::Extent {
55 let reply = xcb_connection
56 .get_geometry(x_window)
57 .unwrap()
58 .reply()
59 .unwrap();
60 gpu::Extent {
61 width: reply.width as u32,
62 height: reply.height as u32,
63 depth: 1,
64 }
65}
66
67#[derive(Debug)]
68struct Visual {
69 id: xproto::Visualid,
70 colormap: u32,
71 depth: u8,
72}
73
74struct VisualSet {
75 inherit: Visual,
76 opaque: Option<Visual>,
77 transparent: Option<Visual>,
78 root: u32,
79 black_pixel: u32,
80}
81
82fn find_visuals(xcb_connection: &XCBConnection, screen_index: usize) -> VisualSet {
83 let screen = &xcb_connection.setup().roots[screen_index];
84 let mut set = VisualSet {
85 inherit: Visual {
86 id: screen.root_visual,
87 colormap: screen.default_colormap,
88 depth: screen.root_depth,
89 },
90 opaque: None,
91 transparent: None,
92 root: screen.root,
93 black_pixel: screen.black_pixel,
94 };
95
96 for depth_info in screen.allowed_depths.iter() {
97 for visual_type in depth_info.visuals.iter() {
98 let visual = Visual {
99 id: visual_type.visual_id,
100 colormap: 0,
101 depth: depth_info.depth,
102 };
103 log::debug!("Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
104 visual_type.visual_id,
105 visual_type.class,
106 depth_info.depth,
107 visual_type.bits_per_rgb_value,
108 visual_type.red_mask, visual_type.green_mask, visual_type.blue_mask,
109 );
110
111 if (
112 visual_type.red_mask,
113 visual_type.green_mask,
114 visual_type.blue_mask,
115 ) != (0xFF0000, 0xFF00, 0xFF)
116 {
117 continue;
118 }
119 let color_mask = visual_type.red_mask | visual_type.green_mask | visual_type.blue_mask;
120 let alpha_mask = color_mask as usize ^ ((1usize << depth_info.depth) - 1);
121
122 if alpha_mask == 0 {
123 if set.opaque.is_none() {
124 set.opaque = Some(visual);
125 }
126 } else {
127 if set.transparent.is_none() {
128 set.transparent = Some(visual);
129 }
130 }
131 }
132 }
133
134 set
135}
136
137struct RawWindow {
138 connection: *mut c_void,
139 screen_id: usize,
140 window_id: u32,
141 visual_id: u32,
142}
143
144#[derive(Default)]
145pub struct Callbacks {
146 request_frame: Option<Box<dyn FnMut()>>,
147 input: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
148 active_status_change: Option<Box<dyn FnMut(bool)>>,
149 resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
150 moved: Option<Box<dyn FnMut()>>,
151 should_close: Option<Box<dyn FnMut() -> bool>>,
152 close: Option<Box<dyn FnOnce()>>,
153 appearance_changed: Option<Box<dyn FnMut()>>,
154}
155
156pub(crate) struct X11WindowState {
157 client: X11ClientStatePtr,
158 executor: ForegroundExecutor,
159 atoms: XcbAtoms,
160 raw: RawWindow,
161 bounds: Bounds<i32>,
162 scale_factor: f32,
163 renderer: BladeRenderer,
164 display: Rc<dyn PlatformDisplay>,
165 input_handler: Option<PlatformInputHandler>,
166}
167
168#[derive(Clone)]
169pub(crate) struct X11WindowStatePtr {
170 pub(crate) state: Rc<RefCell<X11WindowState>>,
171 pub(crate) callbacks: Rc<RefCell<Callbacks>>,
172 xcb_connection: Rc<XCBConnection>,
173 x_window: xproto::Window,
174}
175
176// todo(linux): Remove other RawWindowHandle implementation
177impl rwh::HasWindowHandle for RawWindow {
178 fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
179 let non_zero = NonZeroU32::new(self.window_id).unwrap();
180 let mut handle = rwh::XcbWindowHandle::new(non_zero);
181 handle.visual_id = NonZeroU32::new(self.visual_id);
182 Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
183 }
184}
185impl rwh::HasDisplayHandle for RawWindow {
186 fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
187 let non_zero = NonNull::new(self.connection).unwrap();
188 let handle = rwh::XcbDisplayHandle::new(Some(non_zero), self.screen_id as i32);
189 Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
190 }
191}
192
193impl rwh::HasWindowHandle for X11Window {
194 fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
195 unimplemented!()
196 }
197}
198impl rwh::HasDisplayHandle for X11Window {
199 fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
200 unimplemented!()
201 }
202}
203
204impl X11WindowState {
205 #[allow(clippy::too_many_arguments)]
206 pub fn new(
207 client: X11ClientStatePtr,
208 executor: ForegroundExecutor,
209 params: WindowParams,
210 xcb_connection: &Rc<XCBConnection>,
211 x_main_screen_index: usize,
212 x_window: xproto::Window,
213 atoms: &XcbAtoms,
214 scale_factor: f32,
215 ) -> Self {
216 let x_screen_index = params
217 .display_id
218 .map_or(x_main_screen_index, |did| did.0 as usize);
219
220 let visual_set = find_visuals(&xcb_connection, x_screen_index);
221 let visual_maybe = match params.window_background {
222 WindowBackgroundAppearance::Opaque => visual_set.opaque,
223 WindowBackgroundAppearance::Transparent | WindowBackgroundAppearance::Blurred => {
224 visual_set.transparent
225 }
226 };
227 let visual = match visual_maybe {
228 Some(visual) => visual,
229 None => {
230 log::warn!(
231 "Unable to find a matching visual for {:?}",
232 params.window_background
233 );
234 visual_set.inherit
235 }
236 };
237 log::info!("Using {:?}", visual);
238
239 let colormap = if visual.colormap != 0 {
240 visual.colormap
241 } else {
242 let id = xcb_connection.generate_id().unwrap();
243 log::info!("Creating colormap {}", id);
244 xcb_connection
245 .create_colormap(xproto::ColormapAlloc::NONE, id, visual_set.root, visual.id)
246 .unwrap()
247 .check()
248 .unwrap();
249 id
250 };
251
252 let win_aux = xproto::CreateWindowAux::new()
253 .background_pixel(x11rb::NONE)
254 // https://stackoverflow.com/questions/43218127/x11-xlib-xcb-creating-a-window-requires-border-pixel-if-specifying-colormap-wh
255 .border_pixel(visual_set.black_pixel)
256 .colormap(colormap)
257 .event_mask(
258 xproto::EventMask::EXPOSURE
259 | xproto::EventMask::STRUCTURE_NOTIFY
260 | xproto::EventMask::ENTER_WINDOW
261 | xproto::EventMask::LEAVE_WINDOW
262 | xproto::EventMask::FOCUS_CHANGE
263 | xproto::EventMask::KEY_PRESS
264 | xproto::EventMask::KEY_RELEASE,
265 );
266
267 xcb_connection
268 .create_window(
269 visual.depth,
270 x_window,
271 visual_set.root,
272 params.bounds.origin.x.0 as i16,
273 params.bounds.origin.y.0 as i16,
274 params.bounds.size.width.0 as u16,
275 params.bounds.size.height.0 as u16,
276 0,
277 xproto::WindowClass::INPUT_OUTPUT,
278 visual.id,
279 &win_aux,
280 )
281 .unwrap()
282 .check()
283 .unwrap();
284
285 if let Some(titlebar) = params.titlebar {
286 if let Some(title) = titlebar.title {
287 xcb_connection
288 .change_property8(
289 xproto::PropMode::REPLACE,
290 x_window,
291 xproto::AtomEnum::WM_NAME,
292 xproto::AtomEnum::STRING,
293 title.as_bytes(),
294 )
295 .unwrap();
296 }
297 }
298
299 xcb_connection
300 .change_property32(
301 xproto::PropMode::REPLACE,
302 x_window,
303 atoms.WM_PROTOCOLS,
304 xproto::AtomEnum::ATOM,
305 &[atoms.WM_DELETE_WINDOW],
306 )
307 .unwrap();
308
309 xcb_connection
310 .xinput_xi_select_events(
311 x_window,
312 &[xinput::EventMask {
313 deviceid: 1,
314 mask: vec![
315 xinput::XIEventMask::MOTION
316 | xinput::XIEventMask::BUTTON_PRESS
317 | xinput::XIEventMask::BUTTON_RELEASE
318 | xinput::XIEventMask::LEAVE,
319 ],
320 }],
321 )
322 .unwrap();
323
324 xcb_connection.map_window(x_window).unwrap();
325 xcb_connection.flush().unwrap();
326
327 let raw = RawWindow {
328 connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
329 xcb_connection,
330 ) as *mut _,
331 screen_id: x_screen_index,
332 window_id: x_window,
333 visual_id: visual.id,
334 };
335 let gpu = Arc::new(
336 unsafe {
337 gpu::Context::init_windowed(
338 &raw,
339 gpu::ContextDesc {
340 validation: false,
341 capture: false,
342 overlay: false,
343 },
344 )
345 }
346 .unwrap(),
347 );
348
349 let config = BladeSurfaceConfig {
350 // Note: this has to be done after the GPU init, or otherwise
351 // the sizes are immediately invalidated.
352 size: query_render_extent(xcb_connection, x_window),
353 transparent: params.window_background != WindowBackgroundAppearance::Opaque,
354 };
355
356 Self {
357 client,
358 executor,
359 display: Rc::new(X11Display::new(xcb_connection, x_screen_index).unwrap()),
360 raw,
361 bounds: params.bounds.map(|v| v.0),
362 scale_factor,
363 renderer: BladeRenderer::new(gpu, config),
364 atoms: *atoms,
365 input_handler: None,
366 }
367 }
368
369 fn content_size(&self) -> Size<Pixels> {
370 let size = self.renderer.viewport_size();
371 Size {
372 width: size.width.into(),
373 height: size.height.into(),
374 }
375 }
376}
377
378pub(crate) struct X11Window(pub X11WindowStatePtr);
379
380impl Drop for X11Window {
381 fn drop(&mut self) {
382 let mut state = self.0.state.borrow_mut();
383 state.renderer.destroy();
384
385 self.0.xcb_connection.unmap_window(self.0.x_window).unwrap();
386 self.0
387 .xcb_connection
388 .destroy_window(self.0.x_window)
389 .unwrap();
390 self.0.xcb_connection.flush().unwrap();
391
392 let this_ptr = self.0.clone();
393 let client_ptr = state.client.clone();
394 state
395 .executor
396 .spawn(async move {
397 this_ptr.close();
398 client_ptr.drop_window(this_ptr.x_window);
399 })
400 .detach();
401 drop(state);
402 }
403}
404
405impl X11Window {
406 #[allow(clippy::too_many_arguments)]
407 pub fn new(
408 client: X11ClientStatePtr,
409 executor: ForegroundExecutor,
410 params: WindowParams,
411 xcb_connection: &Rc<XCBConnection>,
412 x_main_screen_index: usize,
413 x_window: xproto::Window,
414 atoms: &XcbAtoms,
415 scale_factor: f32,
416 ) -> Self {
417 Self(X11WindowStatePtr {
418 state: Rc::new(RefCell::new(X11WindowState::new(
419 client,
420 executor,
421 params,
422 xcb_connection,
423 x_main_screen_index,
424 x_window,
425 atoms,
426 scale_factor,
427 ))),
428 callbacks: Rc::new(RefCell::new(Callbacks::default())),
429 xcb_connection: xcb_connection.clone(),
430 x_window,
431 })
432 }
433}
434
435impl X11WindowStatePtr {
436 pub fn should_close(&self) -> bool {
437 let mut cb = self.callbacks.borrow_mut();
438 if let Some(mut should_close) = cb.should_close.take() {
439 let result = (should_close)();
440 cb.should_close = Some(should_close);
441 result
442 } else {
443 true
444 }
445 }
446
447 pub fn close(&self) {
448 let mut callbacks = self.callbacks.borrow_mut();
449 if let Some(fun) = callbacks.close.take() {
450 fun()
451 }
452 }
453
454 pub fn refresh(&self) {
455 let mut cb = self.callbacks.borrow_mut();
456 if let Some(ref mut fun) = cb.request_frame {
457 fun();
458 }
459 }
460
461 pub fn handle_input(&self, input: PlatformInput) {
462 if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
463 if !fun(input.clone()).propagate {
464 return;
465 }
466 }
467 if let PlatformInput::KeyDown(event) = input {
468 let mut state = self.state.borrow_mut();
469 if let Some(mut input_handler) = state.input_handler.take() {
470 if let Some(ime_key) = &event.keystroke.ime_key {
471 drop(state);
472 input_handler.replace_text_in_range(None, ime_key);
473 state = self.state.borrow_mut();
474 }
475 state.input_handler = Some(input_handler);
476 }
477 }
478 }
479
480 pub fn configure(&self, bounds: Bounds<i32>) {
481 let mut resize_args = None;
482 let do_move;
483 {
484 let mut state = self.state.borrow_mut();
485 let old_bounds = mem::replace(&mut state.bounds, bounds);
486 do_move = old_bounds.origin != bounds.origin;
487 // todo(linux): use normal GPUI types here, refactor out the double
488 // viewport check and extra casts ( )
489 let gpu_size = query_render_extent(&self.xcb_connection, self.x_window);
490 if state.renderer.viewport_size() != gpu_size {
491 state
492 .renderer
493 .update_drawable_size(size(gpu_size.width as f64, gpu_size.height as f64));
494 resize_args = Some((state.content_size(), state.scale_factor));
495 }
496 }
497
498 let mut callbacks = self.callbacks.borrow_mut();
499 if let Some((content_size, scale_factor)) = resize_args {
500 if let Some(ref mut fun) = callbacks.resize {
501 fun(content_size, scale_factor)
502 }
503 }
504 if do_move {
505 if let Some(ref mut fun) = callbacks.moved {
506 fun()
507 }
508 }
509 }
510
511 pub fn set_focused(&self, focus: bool) {
512 if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
513 fun(focus);
514 }
515 }
516}
517
518impl PlatformWindow for X11Window {
519 fn bounds(&self) -> Bounds<DevicePixels> {
520 self.0.state.borrow().bounds.map(|v| v.into())
521 }
522
523 // todo(linux)
524 fn is_maximized(&self) -> bool {
525 false
526 }
527
528 // todo(linux)
529 fn window_bounds(&self) -> WindowBounds {
530 let state = self.0.state.borrow();
531 WindowBounds::Windowed(state.bounds.map(|p| DevicePixels(p)))
532 }
533
534 fn content_size(&self) -> Size<Pixels> {
535 // We divide by the scale factor here because this value is queried to determine how much to draw,
536 // but it will be multiplied later by the scale to adjust for scaling.
537 let state = self.0.state.borrow();
538 state
539 .content_size()
540 .map(|size| size.div(state.scale_factor))
541 }
542
543 fn scale_factor(&self) -> f32 {
544 self.0.state.borrow().scale_factor
545 }
546
547 // todo(linux)
548 fn appearance(&self) -> WindowAppearance {
549 WindowAppearance::Light
550 }
551
552 fn display(&self) -> Rc<dyn PlatformDisplay> {
553 self.0.state.borrow().display.clone()
554 }
555
556 fn mouse_position(&self) -> Point<Pixels> {
557 let reply = self
558 .0
559 .xcb_connection
560 .query_pointer(self.0.x_window)
561 .unwrap()
562 .reply()
563 .unwrap();
564 Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
565 }
566
567 // todo(linux)
568 fn modifiers(&self) -> Modifiers {
569 Modifiers::default()
570 }
571
572 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
573 self.0.state.borrow_mut().input_handler = Some(input_handler);
574 }
575
576 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
577 self.0.state.borrow_mut().input_handler.take()
578 }
579
580 fn prompt(
581 &self,
582 _level: PromptLevel,
583 _msg: &str,
584 _detail: Option<&str>,
585 _answers: &[&str],
586 ) -> Option<futures::channel::oneshot::Receiver<usize>> {
587 None
588 }
589
590 fn activate(&self) {
591 let win_aux = xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE);
592 self.0
593 .xcb_connection
594 .configure_window(self.0.x_window, &win_aux)
595 .log_err();
596 }
597
598 // todo(linux)
599 fn is_active(&self) -> bool {
600 false
601 }
602
603 fn set_title(&mut self, title: &str) {
604 self.0
605 .xcb_connection
606 .change_property8(
607 xproto::PropMode::REPLACE,
608 self.0.x_window,
609 xproto::AtomEnum::WM_NAME,
610 xproto::AtomEnum::STRING,
611 title.as_bytes(),
612 )
613 .unwrap();
614
615 self.0
616 .xcb_connection
617 .change_property8(
618 xproto::PropMode::REPLACE,
619 self.0.x_window,
620 self.0.state.borrow().atoms._NET_WM_NAME,
621 self.0.state.borrow().atoms.UTF8_STRING,
622 title.as_bytes(),
623 )
624 .unwrap();
625 }
626
627 fn set_app_id(&mut self, app_id: &str) {
628 let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
629 data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
630 data.push(b'\0');
631 data.extend(app_id.bytes()); // class
632
633 self.0.xcb_connection.change_property8(
634 xproto::PropMode::REPLACE,
635 self.0.x_window,
636 xproto::AtomEnum::WM_CLASS,
637 xproto::AtomEnum::STRING,
638 &data,
639 );
640 }
641
642 // todo(linux)
643 fn set_edited(&mut self, edited: bool) {}
644
645 fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
646 let mut inner = self.0.state.borrow_mut();
647 let transparent = background_appearance != WindowBackgroundAppearance::Opaque;
648 inner.renderer.update_transparency(transparent);
649 }
650
651 // todo(linux), this corresponds to `orderFrontCharacterPalette` on macOS,
652 // but it looks like the equivalent for Linux is GTK specific:
653 //
654 // https://docs.gtk.org/gtk3/signal.Entry.insert-emoji.html
655 //
656 // This API might need to change, or we might need to build an emoji picker into GPUI
657 fn show_character_palette(&self) {
658 unimplemented!()
659 }
660
661 // todo(linux)
662 fn minimize(&self) {
663 unimplemented!()
664 }
665
666 // todo(linux)
667 fn zoom(&self) {
668 unimplemented!()
669 }
670
671 // todo(linux)
672 fn toggle_fullscreen(&self) {
673 unimplemented!()
674 }
675
676 // todo(linux)
677 fn is_fullscreen(&self) -> bool {
678 false
679 }
680
681 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
682 self.0.callbacks.borrow_mut().request_frame = Some(callback);
683 }
684
685 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
686 self.0.callbacks.borrow_mut().input = Some(callback);
687 }
688
689 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
690 self.0.callbacks.borrow_mut().active_status_change = Some(callback);
691 }
692
693 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
694 self.0.callbacks.borrow_mut().resize = Some(callback);
695 }
696
697 fn on_moved(&self, callback: Box<dyn FnMut()>) {
698 self.0.callbacks.borrow_mut().moved = Some(callback);
699 }
700
701 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
702 self.0.callbacks.borrow_mut().should_close = Some(callback);
703 }
704
705 fn on_close(&self, callback: Box<dyn FnOnce()>) {
706 self.0.callbacks.borrow_mut().close = Some(callback);
707 }
708
709 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
710 self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
711 }
712
713 fn draw(&self, scene: &Scene) {
714 let mut inner = self.0.state.borrow_mut();
715 inner.renderer.draw(scene);
716 }
717
718 fn sprite_atlas(&self) -> sync::Arc<dyn PlatformAtlas> {
719 let inner = self.0.state.borrow();
720 inner.renderer.sprite_atlas().clone()
721 }
722}