window.rs

  1use crate::{
  2    platform::blade::{BladeRenderer, BladeSurfaceConfig},
  3    size, AnyWindowHandle, Bounds, DevicePixels, ForegroundExecutor, Modifiers, Pixels,
  4    PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
  5    PromptLevel, Scene, Size, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
  6    WindowParams, X11ClientStatePtr,
  7};
  8
  9use blade_graphics as gpu;
 10use raw_window_handle as rwh;
 11use util::ResultExt;
 12use x11rb::{
 13    connection::Connection,
 14    protocol::{
 15        xinput::{self, ConnectionExt as _},
 16        xproto::{
 17            self, ClientMessageEvent, ConnectionExt as _, EventMask, TranslateCoordinatesReply,
 18        },
 19    },
 20    wrapper::ConnectionExt as _,
 21    xcb_ffi::XCBConnection,
 22};
 23
 24use std::{
 25    cell::RefCell,
 26    ffi::c_void,
 27    num::NonZeroU32,
 28    ops::Div,
 29    ptr::NonNull,
 30    rc::Rc,
 31    sync::{self, Arc},
 32};
 33
 34use super::{X11Display, XINPUT_MASTER_DEVICE};
 35
 36x11rb::atom_manager! {
 37    pub XcbAtoms: AtomsCookie {
 38        UTF8_STRING,
 39        WM_PROTOCOLS,
 40        WM_DELETE_WINDOW,
 41        WM_CHANGE_STATE,
 42        _NET_WM_NAME,
 43        _NET_WM_STATE,
 44        _NET_WM_STATE_MAXIMIZED_VERT,
 45        _NET_WM_STATE_MAXIMIZED_HORZ,
 46        _NET_WM_STATE_FULLSCREEN,
 47        _NET_WM_STATE_HIDDEN,
 48        _NET_WM_STATE_FOCUSED,
 49        _NET_WM_MOVERESIZE,
 50        _GTK_SHOW_WINDOW_MENU,
 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 struct X11WindowState {
157    pub destroyed: bool,
158    client: X11ClientStatePtr,
159    executor: ForegroundExecutor,
160    atoms: XcbAtoms,
161    x_root_window: xproto::Window,
162    _raw: RawWindow,
163    bounds: Bounds<i32>,
164    scale_factor: f32,
165    renderer: BladeRenderer,
166    display: Rc<dyn PlatformDisplay>,
167    input_handler: Option<PlatformInputHandler>,
168    appearance: WindowAppearance,
169    pub handle: AnyWindowHandle,
170}
171
172#[derive(Clone)]
173pub(crate) struct X11WindowStatePtr {
174    pub state: Rc<RefCell<X11WindowState>>,
175    pub(crate) callbacks: Rc<RefCell<Callbacks>>,
176    xcb_connection: Rc<XCBConnection>,
177    x_window: xproto::Window,
178}
179
180impl rwh::HasWindowHandle for RawWindow {
181    fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
182        let non_zero = NonZeroU32::new(self.window_id).unwrap();
183        let mut handle = rwh::XcbWindowHandle::new(non_zero);
184        handle.visual_id = NonZeroU32::new(self.visual_id);
185        Ok(unsafe { rwh::WindowHandle::borrow_raw(handle.into()) })
186    }
187}
188impl rwh::HasDisplayHandle for RawWindow {
189    fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
190        let non_zero = NonNull::new(self.connection).unwrap();
191        let handle = rwh::XcbDisplayHandle::new(Some(non_zero), self.screen_id as i32);
192        Ok(unsafe { rwh::DisplayHandle::borrow_raw(handle.into()) })
193    }
194}
195
196impl rwh::HasWindowHandle for X11Window {
197    fn window_handle(&self) -> Result<rwh::WindowHandle, rwh::HandleError> {
198        unimplemented!()
199    }
200}
201impl rwh::HasDisplayHandle for X11Window {
202    fn display_handle(&self) -> Result<rwh::DisplayHandle, rwh::HandleError> {
203        unimplemented!()
204    }
205}
206
207impl X11WindowState {
208    #[allow(clippy::too_many_arguments)]
209    pub fn new(
210        handle: AnyWindowHandle,
211        client: X11ClientStatePtr,
212        executor: ForegroundExecutor,
213        params: WindowParams,
214        xcb_connection: &Rc<XCBConnection>,
215        x_main_screen_index: usize,
216        x_window: xproto::Window,
217        atoms: &XcbAtoms,
218        scale_factor: f32,
219        appearance: WindowAppearance,
220    ) -> anyhow::Result<Self> {
221        let x_screen_index = params
222            .display_id
223            .map_or(x_main_screen_index, |did| did.0 as usize);
224
225        let visual_set = find_visuals(&xcb_connection, x_screen_index);
226        let visual_maybe = match params.window_background {
227            WindowBackgroundAppearance::Opaque => visual_set.opaque,
228            WindowBackgroundAppearance::Transparent | WindowBackgroundAppearance::Blurred => {
229                visual_set.transparent
230            }
231        };
232        let visual = match visual_maybe {
233            Some(visual) => visual,
234            None => {
235                log::warn!(
236                    "Unable to find a matching visual for {:?}",
237                    params.window_background
238                );
239                visual_set.inherit
240            }
241        };
242        log::info!("Using {:?}", visual);
243
244        let colormap = if visual.colormap != 0 {
245            visual.colormap
246        } else {
247            let id = xcb_connection.generate_id().unwrap();
248            log::info!("Creating colormap {}", id);
249            xcb_connection
250                .create_colormap(xproto::ColormapAlloc::NONE, id, visual_set.root, visual.id)
251                .unwrap()
252                .check()?;
253            id
254        };
255
256        let win_aux = xproto::CreateWindowAux::new()
257            .background_pixel(x11rb::NONE)
258            // https://stackoverflow.com/questions/43218127/x11-xlib-xcb-creating-a-window-requires-border-pixel-if-specifying-colormap-wh
259            .border_pixel(visual_set.black_pixel)
260            .colormap(colormap)
261            .event_mask(
262                xproto::EventMask::EXPOSURE
263                    | xproto::EventMask::STRUCTURE_NOTIFY
264                    | xproto::EventMask::FOCUS_CHANGE
265                    | xproto::EventMask::KEY_PRESS
266                    | xproto::EventMask::KEY_RELEASE,
267            );
268
269        xcb_connection
270            .create_window(
271                visual.depth,
272                x_window,
273                visual_set.root,
274                params.bounds.origin.x.0 as i16,
275                params.bounds.origin.y.0 as i16,
276                params.bounds.size.width.0 as u16,
277                params.bounds.size.height.0 as u16,
278                0,
279                xproto::WindowClass::INPUT_OUTPUT,
280                visual.id,
281                &win_aux,
282            )
283            .unwrap()
284            .check()?;
285
286        if let Some(titlebar) = params.titlebar {
287            if let Some(title) = titlebar.title {
288                xcb_connection
289                    .change_property8(
290                        xproto::PropMode::REPLACE,
291                        x_window,
292                        xproto::AtomEnum::WM_NAME,
293                        xproto::AtomEnum::STRING,
294                        title.as_bytes(),
295                    )
296                    .unwrap();
297            }
298        }
299
300        xcb_connection
301            .change_property32(
302                xproto::PropMode::REPLACE,
303                x_window,
304                atoms.WM_PROTOCOLS,
305                xproto::AtomEnum::ATOM,
306                &[atoms.WM_DELETE_WINDOW],
307            )
308            .unwrap();
309
310        xcb_connection
311            .xinput_xi_select_events(
312                x_window,
313                &[xinput::EventMask {
314                    deviceid: XINPUT_MASTER_DEVICE,
315                    mask: vec![
316                        xinput::XIEventMask::MOTION
317                            | xinput::XIEventMask::BUTTON_PRESS
318                            | xinput::XIEventMask::BUTTON_RELEASE
319                            | xinput::XIEventMask::LEAVE,
320                    ],
321                }],
322            )
323            .unwrap();
324
325        xcb_connection.map_window(x_window).unwrap();
326        xcb_connection.flush().unwrap();
327
328        let raw = RawWindow {
329            connection: as_raw_xcb_connection::AsRawXcbConnection::as_raw_xcb_connection(
330                xcb_connection,
331            ) as *mut _,
332            screen_id: x_screen_index,
333            window_id: x_window,
334            visual_id: visual.id,
335        };
336        let gpu = Arc::new(
337            unsafe {
338                gpu::Context::init_windowed(
339                    &raw,
340                    gpu::ContextDesc {
341                        validation: false,
342                        capture: false,
343                        overlay: false,
344                    },
345                )
346            }
347            .map_err(|e| anyhow::anyhow!("{:?}", e))?,
348        );
349
350        let config = BladeSurfaceConfig {
351            // Note: this has to be done after the GPU init, or otherwise
352            // the sizes are immediately invalidated.
353            size: query_render_extent(xcb_connection, x_window),
354            transparent: params.window_background != WindowBackgroundAppearance::Opaque,
355        };
356
357        Ok(Self {
358            client,
359            executor,
360            display: Rc::new(X11Display::new(xcb_connection, x_screen_index).unwrap()),
361            _raw: raw,
362            x_root_window: visual_set.root,
363            bounds: params.bounds.map(|v| v.0),
364            scale_factor,
365            renderer: BladeRenderer::new(gpu, config),
366            atoms: *atoms,
367            input_handler: None,
368            appearance,
369            handle,
370            destroyed: false,
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        // Mark window as destroyed so that we can filter out when X11 events
398        // for it still come in.
399        state.destroyed = true;
400
401        let this_ptr = self.0.clone();
402        let client_ptr = state.client.clone();
403        state
404            .executor
405            .spawn(async move {
406                this_ptr.close();
407                client_ptr.drop_window(this_ptr.x_window);
408            })
409            .detach();
410        drop(state);
411    }
412}
413
414enum WmHintPropertyState {
415    // Remove = 0,
416    // Add = 1,
417    Toggle = 2,
418}
419
420impl X11Window {
421    #[allow(clippy::too_many_arguments)]
422    pub fn new(
423        handle: AnyWindowHandle,
424        client: X11ClientStatePtr,
425        executor: ForegroundExecutor,
426        params: WindowParams,
427        xcb_connection: &Rc<XCBConnection>,
428        x_main_screen_index: usize,
429        x_window: xproto::Window,
430        atoms: &XcbAtoms,
431        scale_factor: f32,
432        appearance: WindowAppearance,
433    ) -> anyhow::Result<Self> {
434        Ok(Self(X11WindowStatePtr {
435            state: Rc::new(RefCell::new(X11WindowState::new(
436                handle,
437                client,
438                executor,
439                params,
440                xcb_connection,
441                x_main_screen_index,
442                x_window,
443                atoms,
444                scale_factor,
445                appearance,
446            )?)),
447            callbacks: Rc::new(RefCell::new(Callbacks::default())),
448            xcb_connection: xcb_connection.clone(),
449            x_window,
450        }))
451    }
452
453    fn set_wm_hints(&self, wm_hint_property_state: WmHintPropertyState, prop1: u32, prop2: u32) {
454        let state = self.0.state.borrow();
455        let message = ClientMessageEvent::new(
456            32,
457            self.0.x_window,
458            state.atoms._NET_WM_STATE,
459            [wm_hint_property_state as u32, prop1, prop2, 1, 0],
460        );
461        self.0
462            .xcb_connection
463            .send_event(
464                false,
465                state.x_root_window,
466                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
467                message,
468            )
469            .unwrap();
470    }
471
472    fn get_wm_hints(&self) -> Vec<u32> {
473        let reply = self
474            .0
475            .xcb_connection
476            .get_property(
477                false,
478                self.0.x_window,
479                self.0.state.borrow().atoms._NET_WM_STATE,
480                xproto::AtomEnum::ATOM,
481                0,
482                u32::MAX,
483            )
484            .unwrap()
485            .reply()
486            .unwrap();
487        // Reply is in u8 but atoms are represented as u32
488        reply
489            .value
490            .chunks_exact(4)
491            .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
492            .collect()
493    }
494
495    fn get_root_position(&self, position: Point<Pixels>) -> TranslateCoordinatesReply {
496        let state = self.0.state.borrow();
497        self.0
498            .xcb_connection
499            .translate_coordinates(
500                self.0.x_window,
501                state.x_root_window,
502                (position.x.0 * state.scale_factor) as i16,
503                (position.y.0 * state.scale_factor) as i16,
504            )
505            .unwrap()
506            .reply()
507            .unwrap()
508    }
509}
510
511impl X11WindowStatePtr {
512    pub fn should_close(&self) -> bool {
513        let mut cb = self.callbacks.borrow_mut();
514        if let Some(mut should_close) = cb.should_close.take() {
515            let result = (should_close)();
516            cb.should_close = Some(should_close);
517            result
518        } else {
519            true
520        }
521    }
522
523    pub fn close(&self) {
524        let mut callbacks = self.callbacks.borrow_mut();
525        if let Some(fun) = callbacks.close.take() {
526            fun()
527        }
528    }
529
530    pub fn refresh(&self) {
531        let mut cb = self.callbacks.borrow_mut();
532        if let Some(ref mut fun) = cb.request_frame {
533            fun();
534        }
535    }
536
537    pub fn handle_input(&self, input: PlatformInput) {
538        if let Some(ref mut fun) = self.callbacks.borrow_mut().input {
539            if !fun(input.clone()).propagate {
540                return;
541            }
542        }
543        if let PlatformInput::KeyDown(event) = input {
544            let mut state = self.state.borrow_mut();
545            if let Some(mut input_handler) = state.input_handler.take() {
546                if let Some(ime_key) = &event.keystroke.ime_key {
547                    drop(state);
548                    input_handler.replace_text_in_range(None, ime_key);
549                    state = self.state.borrow_mut();
550                }
551                state.input_handler = Some(input_handler);
552            }
553        }
554    }
555
556    pub fn handle_ime_commit(&self, text: String) {
557        let mut state = self.state.borrow_mut();
558        if let Some(mut input_handler) = state.input_handler.take() {
559            drop(state);
560            input_handler.replace_text_in_range(None, &text);
561            let mut state = self.state.borrow_mut();
562            state.input_handler = Some(input_handler);
563        }
564    }
565
566    pub fn handle_ime_preedit(&self, text: String) {
567        let mut state = self.state.borrow_mut();
568        if let Some(mut input_handler) = state.input_handler.take() {
569            drop(state);
570            input_handler.replace_and_mark_text_in_range(None, &text, None);
571            let mut state = self.state.borrow_mut();
572            state.input_handler = Some(input_handler);
573        }
574    }
575
576    pub fn handle_ime_unmark(&self) {
577        let mut state = self.state.borrow_mut();
578        if let Some(mut input_handler) = state.input_handler.take() {
579            drop(state);
580            input_handler.unmark_text();
581            let mut state = self.state.borrow_mut();
582            state.input_handler = Some(input_handler);
583        }
584    }
585
586    pub fn handle_ime_delete(&self) {
587        let mut state = self.state.borrow_mut();
588        if let Some(mut input_handler) = state.input_handler.take() {
589            drop(state);
590            if let Some(marked) = input_handler.marked_text_range() {
591                input_handler.replace_text_in_range(Some(marked), "");
592            }
593            let mut state = self.state.borrow_mut();
594            state.input_handler = Some(input_handler);
595        }
596    }
597
598    pub fn get_ime_area(&self) -> Option<Bounds<Pixels>> {
599        let mut state = self.state.borrow_mut();
600        let mut bounds: Option<Bounds<Pixels>> = None;
601        if let Some(mut input_handler) = state.input_handler.take() {
602            drop(state);
603            if let Some(range) = input_handler.selected_text_range() {
604                bounds = input_handler.bounds_for_range(range);
605            }
606            let mut state = self.state.borrow_mut();
607            state.input_handler = Some(input_handler);
608        };
609        bounds
610    }
611
612    pub fn configure(&self, bounds: Bounds<i32>) {
613        let mut resize_args = None;
614        let is_resize;
615        {
616            let mut state = self.state.borrow_mut();
617
618            is_resize = bounds.size.width != state.bounds.size.width
619                || bounds.size.height != state.bounds.size.height;
620
621            // If it's a resize event (only width/height changed), we ignore `bounds.origin`
622            // because it contains wrong values.
623            if is_resize {
624                state.bounds.size = bounds.size;
625            } else {
626                state.bounds = bounds;
627            }
628
629            let gpu_size = query_render_extent(&self.xcb_connection, self.x_window);
630            if state.renderer.viewport_size() != gpu_size {
631                state
632                    .renderer
633                    .update_drawable_size(size(gpu_size.width as f64, gpu_size.height as f64));
634                resize_args = Some((state.content_size(), state.scale_factor));
635            }
636        }
637
638        let mut callbacks = self.callbacks.borrow_mut();
639        if let Some((content_size, scale_factor)) = resize_args {
640            if let Some(ref mut fun) = callbacks.resize {
641                fun(content_size, scale_factor)
642            }
643        }
644        if !is_resize {
645            if let Some(ref mut fun) = callbacks.moved {
646                fun()
647            }
648        }
649    }
650
651    pub fn set_focused(&self, focus: bool) {
652        if let Some(ref mut fun) = self.callbacks.borrow_mut().active_status_change {
653            fun(focus);
654        }
655    }
656
657    pub fn set_appearance(&mut self, appearance: WindowAppearance) {
658        self.state.borrow_mut().appearance = appearance;
659
660        let mut callbacks = self.callbacks.borrow_mut();
661        if let Some(ref mut fun) = callbacks.appearance_changed {
662            (fun)()
663        }
664    }
665}
666
667impl PlatformWindow for X11Window {
668    fn bounds(&self) -> Bounds<DevicePixels> {
669        self.0.state.borrow().bounds.map(|v| v.into())
670    }
671
672    fn is_maximized(&self) -> bool {
673        let state = self.0.state.borrow();
674        let wm_hints = self.get_wm_hints();
675        // A maximized window that gets minimized will still retain its maximized state.
676        !wm_hints.contains(&state.atoms._NET_WM_STATE_HIDDEN)
677            && wm_hints.contains(&state.atoms._NET_WM_STATE_MAXIMIZED_VERT)
678            && wm_hints.contains(&state.atoms._NET_WM_STATE_MAXIMIZED_HORZ)
679    }
680
681    fn window_bounds(&self) -> WindowBounds {
682        let state = self.0.state.borrow();
683        WindowBounds::Windowed(state.bounds.map(|p| DevicePixels(p)))
684    }
685
686    fn content_size(&self) -> Size<Pixels> {
687        // We divide by the scale factor here because this value is queried to determine how much to draw,
688        // but it will be multiplied later by the scale to adjust for scaling.
689        let state = self.0.state.borrow();
690        state
691            .content_size()
692            .map(|size| size.div(state.scale_factor))
693    }
694
695    fn scale_factor(&self) -> f32 {
696        self.0.state.borrow().scale_factor
697    }
698
699    fn appearance(&self) -> WindowAppearance {
700        self.0.state.borrow().appearance
701    }
702
703    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
704        Some(self.0.state.borrow().display.clone())
705    }
706
707    fn mouse_position(&self) -> Point<Pixels> {
708        let reply = self
709            .0
710            .xcb_connection
711            .query_pointer(self.0.x_window)
712            .unwrap()
713            .reply()
714            .unwrap();
715        Point::new((reply.root_x as u32).into(), (reply.root_y as u32).into())
716    }
717
718    fn modifiers(&self) -> Modifiers {
719        self.0
720            .state
721            .borrow()
722            .client
723            .0
724            .upgrade()
725            .map(|ref_cell| ref_cell.borrow().modifiers)
726            .unwrap_or_default()
727    }
728
729    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
730        self.0.state.borrow_mut().input_handler = Some(input_handler);
731    }
732
733    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
734        self.0.state.borrow_mut().input_handler.take()
735    }
736
737    fn prompt(
738        &self,
739        _level: PromptLevel,
740        _msg: &str,
741        _detail: Option<&str>,
742        _answers: &[&str],
743    ) -> Option<futures::channel::oneshot::Receiver<usize>> {
744        None
745    }
746
747    fn activate(&self) {
748        let win_aux = xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE);
749        self.0
750            .xcb_connection
751            .configure_window(self.0.x_window, &win_aux)
752            .log_err();
753    }
754
755    fn is_active(&self) -> bool {
756        let state = self.0.state.borrow();
757        self.get_wm_hints()
758            .contains(&state.atoms._NET_WM_STATE_FOCUSED)
759    }
760
761    fn set_title(&mut self, title: &str) {
762        self.0
763            .xcb_connection
764            .change_property8(
765                xproto::PropMode::REPLACE,
766                self.0.x_window,
767                xproto::AtomEnum::WM_NAME,
768                xproto::AtomEnum::STRING,
769                title.as_bytes(),
770            )
771            .unwrap();
772
773        self.0
774            .xcb_connection
775            .change_property8(
776                xproto::PropMode::REPLACE,
777                self.0.x_window,
778                self.0.state.borrow().atoms._NET_WM_NAME,
779                self.0.state.borrow().atoms.UTF8_STRING,
780                title.as_bytes(),
781            )
782            .unwrap();
783    }
784
785    fn set_app_id(&mut self, app_id: &str) {
786        let mut data = Vec::with_capacity(app_id.len() * 2 + 1);
787        data.extend(app_id.bytes()); // instance https://unix.stackexchange.com/a/494170
788        data.push(b'\0');
789        data.extend(app_id.bytes()); // class
790
791        self.0
792            .xcb_connection
793            .change_property8(
794                xproto::PropMode::REPLACE,
795                self.0.x_window,
796                xproto::AtomEnum::WM_CLASS,
797                xproto::AtomEnum::STRING,
798                &data,
799            )
800            .unwrap();
801    }
802
803    fn set_edited(&mut self, _edited: bool) {
804        log::info!("ignoring macOS specific set_edited");
805    }
806
807    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
808        let mut inner = self.0.state.borrow_mut();
809        let transparent = background_appearance != WindowBackgroundAppearance::Opaque;
810        inner.renderer.update_transparency(transparent);
811    }
812
813    fn show_character_palette(&self) {
814        log::info!("ignoring macOS specific show_character_palette");
815    }
816
817    fn minimize(&self) {
818        let state = self.0.state.borrow();
819        const WINDOW_ICONIC_STATE: u32 = 3;
820        let message = ClientMessageEvent::new(
821            32,
822            self.0.x_window,
823            state.atoms.WM_CHANGE_STATE,
824            [WINDOW_ICONIC_STATE, 0, 0, 0, 0],
825        );
826        self.0
827            .xcb_connection
828            .send_event(
829                false,
830                state.x_root_window,
831                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
832                message,
833            )
834            .unwrap();
835    }
836
837    fn zoom(&self) {
838        let state = self.0.state.borrow();
839        self.set_wm_hints(
840            WmHintPropertyState::Toggle,
841            state.atoms._NET_WM_STATE_MAXIMIZED_VERT,
842            state.atoms._NET_WM_STATE_MAXIMIZED_HORZ,
843        );
844    }
845
846    fn toggle_fullscreen(&self) {
847        let state = self.0.state.borrow();
848        self.set_wm_hints(
849            WmHintPropertyState::Toggle,
850            state.atoms._NET_WM_STATE_FULLSCREEN,
851            xproto::AtomEnum::NONE.into(),
852        );
853    }
854
855    fn is_fullscreen(&self) -> bool {
856        let state = self.0.state.borrow();
857        self.get_wm_hints()
858            .contains(&state.atoms._NET_WM_STATE_FULLSCREEN)
859    }
860
861    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
862        self.0.callbacks.borrow_mut().request_frame = Some(callback);
863    }
864
865    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
866        self.0.callbacks.borrow_mut().input = Some(callback);
867    }
868
869    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
870        self.0.callbacks.borrow_mut().active_status_change = Some(callback);
871    }
872
873    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
874        self.0.callbacks.borrow_mut().resize = Some(callback);
875    }
876
877    fn on_moved(&self, callback: Box<dyn FnMut()>) {
878        self.0.callbacks.borrow_mut().moved = Some(callback);
879    }
880
881    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
882        self.0.callbacks.borrow_mut().should_close = Some(callback);
883    }
884
885    fn on_close(&self, callback: Box<dyn FnOnce()>) {
886        self.0.callbacks.borrow_mut().close = Some(callback);
887    }
888
889    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
890        self.0.callbacks.borrow_mut().appearance_changed = Some(callback);
891    }
892
893    fn draw(&self, scene: &Scene) {
894        let mut inner = self.0.state.borrow_mut();
895        inner.renderer.draw(scene);
896    }
897
898    fn sprite_atlas(&self) -> sync::Arc<dyn PlatformAtlas> {
899        let inner = self.0.state.borrow();
900        inner.renderer.sprite_atlas().clone()
901    }
902
903    fn show_window_menu(&self, position: Point<Pixels>) {
904        let state = self.0.state.borrow();
905        let coords = self.get_root_position(position);
906        let message = ClientMessageEvent::new(
907            32,
908            self.0.x_window,
909            state.atoms._GTK_SHOW_WINDOW_MENU,
910            [
911                XINPUT_MASTER_DEVICE as u32,
912                coords.dst_x as u32,
913                coords.dst_y as u32,
914                0,
915                0,
916            ],
917        );
918        self.0
919            .xcb_connection
920            .send_event(
921                false,
922                state.x_root_window,
923                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
924                message,
925            )
926            .unwrap();
927    }
928
929    fn start_system_move(&self) {
930        let state = self.0.state.borrow();
931        let pointer = self
932            .0
933            .xcb_connection
934            .query_pointer(self.0.x_window)
935            .unwrap()
936            .reply()
937            .unwrap();
938        const MOVERESIZE_MOVE: u32 = 8;
939        let message = ClientMessageEvent::new(
940            32,
941            self.0.x_window,
942            state.atoms._NET_WM_MOVERESIZE,
943            [
944                pointer.root_x as u32,
945                pointer.root_y as u32,
946                MOVERESIZE_MOVE,
947                1, // Left mouse button
948                1,
949            ],
950        );
951        self.0
952            .xcb_connection
953            .send_event(
954                false,
955                state.x_root_window,
956                EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY,
957                message,
958            )
959            .unwrap();
960    }
961
962    fn should_render_window_controls(&self) -> bool {
963        false
964    }
965}