uzor-framework 1.5.46

uzor app engine: one kernel of single-writer engines driven by a typed input bus
Documentation
//! Create a winit window + hub render surface from a [`WindowSpec`].

use std::path::PathBuf;
use std::sync::Arc;

use uzor::RgbaIcon;
use uzor_render_hub::{
    resolve_render_family_from_process_env, PipelineCacheStore, Prewarmed, RenderBackend, RenderHub, SurfaceSize,
    WindowRenderState,
};
use winit::dpi::{LogicalSize, PhysicalPosition};
use winit::event_loop::ActiveEventLoop;
use winit::window::{Icon, Window, WindowButtons};

use super::mapper::WinitMapper;
use super::prewarm::{self, PrewarmConfig};
use super::window::{apply_spawn_style, NativeWindow};
use super::win32;
use crate::types::error::FrameworkError;
use crate::types::ids::WindowId;
use crate::types::window::{CaptionButtons, SizePx, WindowSpec};

/// Resolve this platform's base cache directory (L-D4).
///
/// - Windows: `%LOCALAPPDATA%`
/// - macOS, iOS: `$HOME/Library/Caches`
/// - other: `$XDG_CACHE_HOME` or `$HOME/.cache`
pub fn platform_pipeline_cache_dir() -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        std::env::var_os("LOCALAPPDATA").map(PathBuf::from)
    }
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    {
        std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Caches"))
    }
    #[cfg(all(not(target_os = "windows"), not(target_os = "macos"), not(target_os = "ios")))]
    {
        if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME") {
            Some(PathBuf::from(xdg))
        } else {
            std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))
        }
    }
}

/// Create the OS window and a hub render state for `spec`.
pub fn create_window(
    event_loop: &ActiveEventLoop,
    hub: &RenderHub,
    id: WindowId,
    spec: WindowSpec,
) -> Result<NativeWindow, FrameworkError> {
    create_window_with(event_loop, id, spec, |window, size| Ok((create_surface(hub, window, size)?, None)))
}

/// [`create_window`] whose surface comes from `warm` (a prewarm made before
/// the window), or from a prewarm made now when `cfg` enables it; the
/// factory path when neither applies or binding fails.
pub(crate) fn create_window_warm(
    event_loop: &ActiveEventLoop,
    hub: &RenderHub,
    id: WindowId,
    spec: WindowSpec,
    warm: Option<Prewarmed>,
    cfg: &PrewarmConfig,
) -> Result<NativeWindow, FrameworkError> {
    create_window_with(event_loop, id, spec, |window, size| create_surface_warm(hub, window, size, warm, cfg))
}

fn create_window_with(
    event_loop: &ActiveEventLoop,
    id: WindowId,
    spec: WindowSpec,
    surface: impl FnOnce(&Arc<Window>, SurfaceSize) -> Result<(WindowRenderState, Option<PipelineCacheStore>), FrameworkError>,
) -> Result<NativeWindow, FrameworkError> {
    let mut attrs = Window::default_attributes()
        .with_title(&spec.title)
        .with_inner_size(LogicalSize::new(
            f64::from(spec.inner_size.width),
            f64::from(spec.inner_size.height),
        ))
        .with_decorations(spec.decorations)
        .with_enabled_buttons(match spec.caption_buttons {
            CaptionButtons::All => WindowButtons::all(),
            CaptionButtons::MinClose => WindowButtons::MINIMIZE | WindowButtons::CLOSE,
        })
        .with_resizable(spec.resizable)
        .with_visible(false)
        .with_transparent(spec.transparent);

    // macOS: an undecorated transparent window keeps the system's rounded
    // corners and shadow by hiding the title bar instead of dropping the frame
    // (the app's floating controls replace the traffic lights).
    #[cfg(target_os = "macos")]
    if !spec.decorations && spec.transparent {
        use winit::platform::macos::WindowAttributesExtMacOS;
        attrs = attrs
            .with_decorations(true)
            .with_titlebar_transparent(true)
            .with_title_hidden(true)
            .with_fullsize_content_view(true)
            .with_titlebar_buttons_hidden(true);
    }

    if let Some(min) = spec.min_inner_size {
        attrs = attrs.with_min_inner_size(LogicalSize::new(
            f64::from(min.width),
            f64::from(min.height),
        ));
    }
    if let Some((x, y)) = spec.position {
        attrs = attrs.with_position(PhysicalPosition::new(x, y));
    }

    #[cfg(target_os = "macos")]
    {
        use winit::platform::macos::WindowAttributesExtMacOS;
        attrs = attrs.with_movable_by_window_background(false);
    }

    let window = event_loop
        .create_window(attrs)
        .map_err(|e| FrameworkError::Host(format!("create_window: {e}")))?;
    let window = Arc::new(window);

    let dpr = window.scale_factor();
    let inner = surface_px(&window);
    let size = SurfaceSize {
        width: inner.width.max(1),
        height: inner.height.max(1),
    };

    let (render_state, pipeline_cache) = surface(&window, size)?;

    apply_spawn_style(&window, &spec);
    if !spec.decorations {
        win32::install_borderless_resize(&window);
    }

    // Stay hidden. The host shows a visible spec on the next tick, after
    // the app's Opened handler has set the icon. The taskbar button is
    // born at ShowWindow and reads that icon.
    let defer_show = spec.visible;
    window.request_redraw();

    let key = spec.key.0.clone();
    Ok(NativeWindow {
        id,
        key,
        window,
        render_state: Some(render_state),
        mapper: WinitMapper::new(dpr),
        decorations: spec.decorations,
        maximized: None,
        dnd_hover: None,
        transparent: spec.transparent,
        defer_show,
        created: std::time::Instant::now(),
        presented: false,
        pipeline_cache,
    })
}

/// A render surface for `window`: bound to `warm` when it was made for the
/// hub's active backend, else prewarmed now (when `cfg` enables it), else
/// from the hub's factory as [`create_surface`]. Also the pipeline cache to
/// save after the first frame.
pub(crate) fn create_surface_warm(
    hub: &RenderHub,
    window: &Arc<Window>,
    size: SurfaceSize,
    warm: Option<Prewarmed>,
    cfg: &PrewarmConfig,
) -> Result<(WindowRenderState, Option<PipelineCacheStore>), FrameworkError> {
    let warm = match warm {
        Some(w) if w.backend() == hub.active() => Some(w),
        Some(w) => {
            prewarm::trace("prewarm-stale", &format!("{:?} != active {:?}", w.backend(), hub.active()));
            prewarm::warm(hub, cfg, "spawn")
        }
        None => prewarm::warm(hub, cfg, "spawn"),
    };
    if let Some(w) = warm {
        let raw = raw_handle_for(window).ok_or_else(|| FrameworkError::Host("no raw window handle".into()))?;
        match w.into_render_state(&raw, size) {
            Ok(ok) => return Ok(ok),
            Err(e) => {
                log::warn!("prewarmed device does not fit this window, using the factory: {e}");
                prewarm::trace("prewarm-unbound", &e.to_string());
            }
        }
    }
    Ok((create_surface(hub, window, size)?, None))
}

/// A render surface for `window` from the hub's active backend. Window creation calls
/// it, and so does `resumed` on Android, where the OS destroys the native window
/// while the app is in the background and the surface has to be made again.
pub fn create_surface(hub: &RenderHub, window: &Arc<Window>, size: SurfaceSize) -> Result<WindowRenderState, FrameworkError> {
    let raw = raw_handle_for(window)
        .ok_or_else(|| FrameworkError::Host("no raw window handle".into()))?;
    let active = hub.active();
    let factory = hub
        .factory_for(active)
        .ok_or_else(|| FrameworkError::Host(format!("hub has no factory for {active:?}")))?;
    let mut render_state = factory
        .create_render_state(&raw, active, size)
        .map_err(|e| FrameworkError::Host(format!("create_render_state: {e}")))?;
    render_state.resize_surface(size.width, size.height);
    Ok(render_state)
}

/// The physical size the surface covers. On iOS winit's `inner_size` is the safe
/// area while the view, its layer and `WindowEvent::Resized` cover the whole
/// window: sizing the swapchain from the safe area stretched the first frames and
/// put touches off by the notch until the next resize.
pub fn surface_px(window: &Window) -> winit::dpi::PhysicalSize<u32> {
    #[cfg(target_os = "ios")]
    {
        window.outer_size()
    }
    #[cfg(not(target_os = "ios"))]
    {
        window.inner_size()
    }
}

/// The window's safe area in logical px. winit reports it on iOS only (as the
/// difference between the safe-area `inner_*` and the full `outer_*` rect); the
/// Android wrapper pushes its `WindowInsets` through [`crate::platform`].
pub fn safe_area(window: &Window) -> crate::types::window::Insets {
    #[cfg(target_os = "ios")]
    {
        let dpr = window.scale_factor().max(0.1);
        let (Ok(ip), Ok(op)) = (window.inner_position(), window.outer_position()) else {
            return crate::types::window::Insets::ZERO;
        };
        let (is, os) = (window.inner_size(), window.outer_size());
        let top = f64::from(ip.y - op.y) / dpr;
        let left = f64::from(ip.x - op.x) / dpr;
        let bottom = (f64::from(os.height) - f64::from(is.height)) / dpr - top;
        let right = (f64::from(os.width) - f64::from(is.width)) / dpr - left;
        crate::types::window::Insets::new(top.max(0.0), right.max(0.0), bottom.max(0.0), left.max(0.0))
    }
    #[cfg(not(target_os = "ios"))]
    {
        let _ = window;
        crate::types::window::Insets::ZERO
    }
}

/// Physical surface size + DPR for a Created / Resized echo.
pub fn geometry_echo(window: &Window) -> (SizePx, f64, Option<(i32, i32)>) {
    let inner = surface_px(window);
    let dpr = window.scale_factor();
    let pos = window.outer_position().ok().map(|p| (p.x, p.y));
    (SizePx::new(inner.width, inner.height), dpr, pos)
}

fn raw_handle_for(window: &Arc<Window>) -> Option<uzor::layout::window::RawHandle> {
    use uzor::layout::window::RawHandle;
    use uzor_window_desktop::winit_provider::SendSyncHandlePair;
    use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle};

    let window_handle = window.window_handle().ok()?.as_raw();
    let display_handle = window.display_handle().ok()?.as_raw();
    // SAFETY: same contract as `WinitWindowProvider::raw_window_handle` —
    // the Arc<Window> outlives the surface created from these handles.
    let pair: Box<dyn std::any::Any + Send + Sync> =
        Box::new(SendSyncHandlePair(
            window_handle,
            display_handle,
            Some(window.clone()),
        ));
    Some(RawHandle::RawWindowHandle(pair))
}

/// Explicit backend skips family resolution. Otherwise walk the default
/// chain: `UZOR_RENDER_FAMILY`, then `RenderFamily::default` (URX).
pub fn build_hub(preferred: Option<RenderBackend>) -> RenderHub {
    match preferred {
        Some(b) => RenderHub::fixed(b),
        None => RenderHub::autodetect(resolve_render_family_from_process_env(None)),
    }
}

/// Build a winit icon from an RGBA buffer, if valid.
pub fn icon_from_rgba(icon: &RgbaIcon) -> Option<Icon> {
    Icon::from_rgba(icon.pixels.clone(), icon.width, icon.height).ok()
}