iris-core 1.1.5

Iris engine core: cross-platform windowing, async runtime, memory pool, IO and networking
Documentation
//! 跨平台窗口管理
//!
//! 桌面端基于 winit 0.30+,Wasm 端基于浏览器 canvas(待实现)。

#![allow(missing_docs)]

/// 窗口创建配置。
#[derive(Debug, Clone)]
pub struct WindowConfig {
    /// 窗口标题。
    pub title: String,
    /// 窗口初始宽度(逻辑像素)。
    pub width: u32,
    /// 窗口初始高度(逻辑像素)。
    pub height: u32,
    /// 是否允许调整窗口大小。
    pub resizable: bool,
    /// 是否最大化显示。
    pub maximized: bool,
}

impl Default for WindowConfig {
    fn default() -> Self {
        Self {
            title: "Iris App".to_string(),
            width: 1280,
            height: 720,
            resizable: true,
            maximized: false,
        }
    }
}

impl WindowConfig {
    /// 快速创建指定标题和尺寸的窗口配置。
    pub fn new(title: impl Into<String>, width: u32, height: u32) -> Self {
        Self {
            title: title.into(),
            width,
            height,
            ..Default::default()
        }
    }
}

/// 在桌面端创建 winit 窗口。
#[cfg(not(target_arch = "wasm32"))]
pub fn create_window(
    event_loop: &winit::event_loop::ActiveEventLoop,
    config: WindowConfig,
) -> Result<winit::window::Window, Box<dyn std::error::Error>> {
    use winit::dpi::LogicalSize;

    let attributes = winit::window::Window::default_attributes()
        .with_title(config.title)
        .with_inner_size(LogicalSize::new(config.width, config.height))
        .with_resizable(config.resizable)
        .with_maximized(config.maximized);

    let window = event_loop.create_window(attributes)?;
    Ok(window)
}

/// Wasm 窗口创建:通过 wasm-bindgen 获取 canvas 并返回窗口 ID。
/// 返回 canvas 元素 ID 字符串,由上层 iris-gpu 初始化 WebGPU 上下文。
#[cfg(target_arch = "wasm32")]
pub fn create_window(
    _event_loop: &(),
    config: WindowConfig,
) -> Result<String, Box<dyn std::error::Error>> {
    use wasm_bindgen::JsCast;

    let window = web_sys::window().ok_or("No browser window found")?;
    let document = window.document().ok_or("No document found")?;

    // 创建 canvas 元素
    let canvas = document.create_element("canvas")
        .map_err(|_| "Failed to create canvas element")?;
    let canvas = canvas.dyn_into::<web_sys::HtmlCanvasElement>()
        .map_err(|_| "Failed to cast to HtmlCanvasElement")?;

    canvas.set_width(config.width);
    canvas.set_height(config.height);
    // 设置 canvas 样式,失败时静默忽略(不影响核心功能)
    let _ = canvas.set_attribute("style", "display:block;width:100%;height:100%");

    // 插入到 body
    let body = document.body().ok_or("No body element")?;
    body.append_child(&canvas)
        .map_err(|_| "Failed to append canvas")?;

    // 设置标题
    document.set_title(&config.title);

    let canvas_id = canvas.id();
    Ok(canvas_id)
}