window.rs

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