bite-gp-linux 1.24.400

gpui_linux — part of the bite-gpui rearchitecture of zed's gpui
Documentation
//! Windows for the headless platform client.
//!
//! A headless window has no compositor surface and no GPU: layout, text
//! shaping, and entity plumbing run normally, `draw` discards the scene, and
//! the sprite atlas hands out tiles without uploading pixels (the same
//! `HeadlessAtlas` GPUI's `TestWindow` uses). This lets command-line tools
//! drive real `Window`-based code paths without a display server.

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use uuid::Uuid;

use gpui_engine::{HeadlessAtlas, PlatformAtlas, Scene, SceneRenderer};
use gpui_platform::{
    Bounds, Capslock, DispatchEventResult, DisplayId, GpuSpecs, Modifiers, Pixels, PlatformDisplay,
    PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton, PromptLevel,
    RendererTarget, RequestFrameOptions, Size, WindowAppearance, WindowBackgroundAppearance,
    WindowBounds, WindowControlArea, WindowParams, WindowVisibility, px,
};

#[derive(Debug)]
pub(crate) struct HeadlessDisplay {
    bounds: Bounds<Pixels>,
}

impl HeadlessDisplay {
    pub(crate) fn new() -> Self {
        Self {
            bounds: Bounds::from_corners(Point::default(), Point::new(px(1920.), px(1080.))),
        }
    }
}

impl PlatformDisplay for HeadlessDisplay {
    fn id(&self) -> DisplayId {
        DisplayId::new(0)
    }

    fn uuid(&self) -> anyhow::Result<Uuid> {
        // Stable identity: there is exactly one headless display.
        Ok(Uuid::nil())
    }

    fn bounds(&self) -> Bounds<Pixels> {
        self.bounds
    }
}

struct HeadlessWindowState {
    bounds: Bounds<Pixels>,
    display: Rc<dyn PlatformDisplay>,
    /// Held while this window exists, so the platform can tell that headless windows are open.
    _lease: Rc<()>,
    input_handler: Option<PlatformInputHandler>,
    title: Option<String>,
    is_fullscreen: bool,
    /// The window's renderer. The discard renderer unless the window installed one through
    /// `WindowParams::renderer_factory` — the same option a real window honours, so a headless
    /// guest can render into an offscreen target instead of throwing its scene away.
    renderer: Box<dyn SceneRenderer>,
}

pub(crate) struct HeadlessWindow(Rc<RefCell<HeadlessWindowState>>);

impl raw_window_handle::HasWindowHandle for HeadlessWindow {
    fn window_handle(
        &self,
    ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
        // Headless windows are not backed by a native window.
        Err(raw_window_handle::HandleError::NotSupported)
    }
}

impl raw_window_handle::HasDisplayHandle for HeadlessWindow {
    fn display_handle(
        &self,
    ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
        Err(raw_window_handle::HandleError::NotSupported)
    }
}

impl HeadlessWindow {
    pub(crate) fn new(
        params: WindowParams,
        display: Rc<dyn PlatformDisplay>,
        lease: Rc<()>,
    ) -> anyhow::Result<Self> {
        // A headless window has no native surface, so a factory that needs raw handles cannot
        // build here — an offscreen renderer is the one that can, and it gets the size it will
        // draw at. Without a factory the window keeps the discard renderer it has always had.
        let renderer: Box<dyn SceneRenderer> = match params.renderer_factory.as_ref() {
            Some(factory) => factory.0.create(RendererTarget {
                window_handle: None,
                display_handle: None,
                size: params.bounds.size,
                scale_factor: 1.0,
                transparent: false,
                backend: None,
            })?,
            None => Box::new(HeadlessRenderer::default()),
        };

        Ok(Self(Rc::new(RefCell::new(HeadlessWindowState {
            bounds: params.bounds,
            display,
            _lease: lease,
            input_handler: None,
            title: None,
            is_fullscreen: false,
            renderer,
        }))))
    }
}

impl PlatformWindow for HeadlessWindow {
    fn bounds(&self) -> Bounds<Pixels> {
        self.0.borrow().bounds
    }

    fn is_maximized(&self) -> bool {
        false
    }

    fn window_bounds(&self) -> WindowBounds {
        WindowBounds::Windowed(self.bounds())
    }

    fn content_size(&self) -> Size<Pixels> {
        self.bounds().size
    }

    fn resize(&mut self, size: Size<Pixels>) {
        self.0.borrow_mut().bounds.size = size;
    }

    fn scale_factor(&self) -> f32 {
        1.0
    }

    fn appearance(&self) -> WindowAppearance {
        WindowAppearance::Dark
    }

    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
        Some(self.0.borrow().display.clone())
    }

    fn mouse_position(&self) -> Point<Pixels> {
        Point::default()
    }

    fn modifiers(&self) -> Modifiers {
        Modifiers::default()
    }

    fn capslock(&self) -> Capslock {
        Capslock::default()
    }

    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
        self.0.borrow_mut().input_handler = Some(input_handler);
    }

    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
        self.0.borrow_mut().input_handler.take()
    }

    fn prompt(
        &self,
        _level: PromptLevel,
        _msg: &str,
        _detail: Option<&str>,
        _answers: &[PromptButton],
    ) -> Option<futures::channel::oneshot::Receiver<usize>> {
        // Fall back to GPUI's rendered prompts.
        None
    }

    fn activate(&self) {}

    fn is_active(&self) -> bool {
        false
    }

    fn visibility(&self) -> WindowVisibility {
        // There is no display server: `draw` discards every scene.
        WindowVisibility::Hidden
    }

    fn is_hovered(&self) -> bool {
        false
    }

    fn background_appearance(&self) -> WindowBackgroundAppearance {
        WindowBackgroundAppearance::Opaque
    }

    fn set_title(&mut self, title: &str) {
        self.0.borrow_mut().title = Some(title.to_owned());
    }

    fn get_title(&self) -> String {
        self.0.borrow().title.clone().unwrap_or_default()
    }

    fn set_background_appearance(&self, _background: WindowBackgroundAppearance) {}

    fn minimize(&self) {}

    fn zoom(&self) {}

    fn toggle_fullscreen(&self) {
        let mut state = self.0.borrow_mut();
        state.is_fullscreen = !state.is_fullscreen;
    }

    fn is_fullscreen(&self) -> bool {
        self.0.borrow().is_fullscreen
    }

    // No compositor drives a frame loop, so frame and status callbacks are
    // dropped: anything that awaits a frame will never resolve headlessly.
    fn on_request_frame(&self, _callback: Box<dyn FnMut(RequestFrameOptions)>) {}

    fn on_input(&self, _callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {}

    fn on_active_status_change(&self, _callback: Box<dyn FnMut(bool)>) {}

    fn on_visibility_change(&self, _callback: Box<dyn FnMut(WindowVisibility)>) {}

    fn on_hover_status_change(&self, _callback: Box<dyn FnMut(bool)>) {}

    fn on_resize(&self, _callback: Box<dyn FnMut(Size<Pixels>, f32)>) {}

    fn on_moved(&self, _callback: Box<dyn FnMut()>) {}

    fn on_should_close(&self, _callback: Box<dyn FnMut() -> bool>) {}

    fn on_close(&self, _callback: Box<dyn FnOnce()>) {}

    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
    }

    fn on_appearance_changed(&self, _callback: Box<dyn FnMut()>) {}

    fn with_renderer(&mut self, f: &mut dyn FnMut(&mut dyn SceneRenderer)) {
        let mut state = self.0.borrow_mut();
        f(state.renderer.as_mut());
    }

    fn present(&mut self, f: &mut dyn FnMut(&mut dyn SceneRenderer) -> bool) {
        let mut state = self.0.borrow_mut();
        // There is no compositor to size the target, so the window tells the renderer what it
        // is about to draw into. A discard renderer ignores it.
        let size = state.bounds.size.to_device_pixels(1.0);
        state.renderer.set_viewport_size(size);
        f(state.renderer.as_mut());
    }

    fn is_subpixel_rendering_supported(&self) -> bool {
        false
    }

    fn update_ime_position(&self, _bounds: Bounds<Pixels>) {}

    fn gpu_specs(&self) -> Option<GpuSpecs> {
        None
    }
}

/// A renderer for headless windows: it discards frames and hands out atlas
/// tiles without uploading pixels.
struct HeadlessRenderer {
    atlas: Arc<HeadlessAtlas>,
}

impl Default for HeadlessRenderer {
    fn default() -> Self {
        Self {
            atlas: Arc::new(HeadlessAtlas::default()),
        }
    }
}

impl SceneRenderer for HeadlessRenderer {
    fn draw(&mut self, _scene: &Scene) -> bool {
        true
    }

    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
        self.atlas.clone()
    }
}