WindowManager

Struct WindowManager 

Source
pub struct WindowManager { /* private fields */ }
Expand description

Manages multiple renderable windows with automatic event handling.

The WindowManager eliminates the boilerplate of manually managing a HashMap<WindowId, RenderableWindow> and handling common events like resizing.

§Example

use astrelis_render::{WindowManager, GraphicsContext, RenderTarget, Color};
use astrelis_winit::app::{App, AppCtx};
use astrelis_winit::{WindowId, FrameTime};
use astrelis_winit::window::WindowBackend;
use astrelis_winit::event::EventBatch;

struct MyApp {
    window_manager: WindowManager,
}

impl App for MyApp {
    fn update(&mut self, _ctx: &mut AppCtx, _time: &FrameTime) {}
    fn render(&mut self, _ctx: &mut AppCtx, window_id: WindowId, events: &mut EventBatch) {
        self.window_manager.render_window(window_id, events, |window, _events| {
            // Resize already handled automatically!
            let mut frame = window.begin_drawing();
            frame.clear_and_render(RenderTarget::Surface, Color::BLACK, |_pass| {
                // Your rendering here
            });
            frame.finish();
        });
    }
}

Implementations§

Source§

impl WindowManager

Source

pub fn new(graphics: Arc<GraphicsContext>) -> Self

Creates a new WindowManager with the given graphics context.

§Example
use astrelis_render::{WindowManager, GraphicsContext};
use std::sync::Arc;

let graphics = GraphicsContext::new_owned_sync_or_panic();
let window_manager = WindowManager::new(graphics);
Examples found in repository?
examples/window_manager_demo.rs (line 38)
33fn main() {
34    logging::init();
35
36    run_app(|ctx| {
37        let graphics_ctx = GraphicsContext::new_owned_sync_or_panic();
38        let mut window_manager = WindowManager::new(graphics_ctx);
39        let mut window_colors = HashMap::new();
40
41        // Create 3 windows with different colors
42        let colors = [
43            Color::rgb(0.8, 0.2, 0.2), // Red
44            Color::rgb(0.2, 0.8, 0.2), // Green
45            Color::rgb(0.2, 0.2, 0.8), // Blue
46        ];
47
48        for (i, color) in colors.iter().enumerate() {
49            let window_id = window_manager.create_window_with_descriptor(
50                ctx,
51                WindowDescriptor {
52                    title: format!("Window {} - WindowManager Demo", i + 1),
53                    size: Some(WinitPhysicalSize::new(400.0, 300.0)),
54                    ..Default::default()
55                },
56                WindowContextDescriptor {
57                    format: Some(wgpu::TextureFormat::Bgra8UnormSrgb),
58                    ..Default::default()
59                },
60            ).expect("Failed to create window");
61
62            window_colors.insert(window_id, *color);
63        }
64
65        Box::new(WindowManagerApp {
66            window_manager,
67            window_colors,
68        })
69    });
70}
Source

pub fn create_window( &mut self, ctx: &mut AppCtx<'_>, descriptor: WindowDescriptor, ) -> Result<WindowId, GraphicsError>

Creates a new window and adds it to the manager.

Returns the WindowId of the created window.

§Example
use astrelis_render::WindowManager;
use astrelis_winit::window::{WindowDescriptor, WindowBackend};

let window_id = window_manager.create_window(
    ctx,
    WindowDescriptor {
        title: "My Window".to_string(),
        ..Default::default()
    },
);
Source

pub fn create_window_with_descriptor( &mut self, ctx: &mut AppCtx<'_>, descriptor: WindowDescriptor, window_descriptor: WindowContextDescriptor, ) -> Result<WindowId, GraphicsError>

Creates a new window with a custom rendering context descriptor.

§Example
use astrelis_render::{WindowManager, WindowContextDescriptor, wgpu};
use astrelis_winit::window::{WindowDescriptor, WindowBackend};

let window_id = window_manager.create_window_with_descriptor(
    ctx,
    WindowDescriptor::default(),
    WindowContextDescriptor {
        present_mode: Some(wgpu::PresentMode::Mailbox),
        ..Default::default()
    },
);
Examples found in repository?
examples/window_manager_demo.rs (lines 49-60)
33fn main() {
34    logging::init();
35
36    run_app(|ctx| {
37        let graphics_ctx = GraphicsContext::new_owned_sync_or_panic();
38        let mut window_manager = WindowManager::new(graphics_ctx);
39        let mut window_colors = HashMap::new();
40
41        // Create 3 windows with different colors
42        let colors = [
43            Color::rgb(0.8, 0.2, 0.2), // Red
44            Color::rgb(0.2, 0.8, 0.2), // Green
45            Color::rgb(0.2, 0.2, 0.8), // Blue
46        ];
47
48        for (i, color) in colors.iter().enumerate() {
49            let window_id = window_manager.create_window_with_descriptor(
50                ctx,
51                WindowDescriptor {
52                    title: format!("Window {} - WindowManager Demo", i + 1),
53                    size: Some(WinitPhysicalSize::new(400.0, 300.0)),
54                    ..Default::default()
55                },
56                WindowContextDescriptor {
57                    format: Some(wgpu::TextureFormat::Bgra8UnormSrgb),
58                    ..Default::default()
59                },
60            ).expect("Failed to create window");
61
62            window_colors.insert(window_id, *color);
63        }
64
65        Box::new(WindowManagerApp {
66            window_manager,
67            window_colors,
68        })
69    });
70}
Source

pub fn get_window(&self, id: WindowId) -> Option<&RenderableWindow>

Gets a reference to a window by its ID.

Returns None if the window doesn’t exist.

Source

pub fn get_window_mut(&mut self, id: WindowId) -> Option<&mut RenderableWindow>

Gets a mutable reference to a window by its ID.

Returns None if the window doesn’t exist.

Source

pub fn remove_window(&mut self, id: WindowId) -> Option<RenderableWindow>

Removes a window from the manager.

Returns the removed window if it existed.

Source

pub fn window_count(&self) -> usize

Returns the number of windows being managed.

Source

pub fn window_ids(&self) -> impl Iterator<Item = WindowId> + '_

Returns an iterator over all window IDs.

Source

pub fn render_window<F>( &mut self, id: WindowId, events: &mut EventBatch, render_fn: F, )
where F: FnMut(&mut RenderableWindow, &mut EventBatch),

Renders a window with automatic event handling.

This method:

  1. Automatically handles common events (resize, etc.)
  2. Calls your render closure with the window and remaining events
  3. Returns immediately if the window doesn’t exist
§Example
use astrelis_render::{WindowManager, RenderTarget, Color};
use astrelis_winit::window::WindowBackend;

window_manager.render_window(window_id, events, |window, events| {
    // Handle custom events if needed
    events.dispatch(|_event| {
        // Your event handling
        astrelis_winit::event::HandleStatus::ignored()
    });

    // Render
    let mut frame = window.begin_drawing();
    frame.clear_and_render(RenderTarget::Surface, Color::BLACK, |_pass| {
        // Your rendering
    });
    frame.finish();
});
Examples found in repository?
examples/window_manager_demo.rs (lines 89-101)
78    fn render(&mut self, _ctx: &mut AppCtx, window_id: WindowId, events: &mut EventBatch) {
79        // Get the color for this window
80        let Some(&color) = self.window_colors.get(&window_id) else {
81            return;
82        };
83
84        // WindowManager automatically handles:
85        // 1. Window lookup (no manual HashMap.get_mut)
86        // 2. Resize events (automatic)
87        // 3. Event dispatching
88        self.window_manager
89            .render_window(window_id, events, |window, _events| {
90                // No need to manually handle resize events!
91                // WindowManager already did that for us
92
93                // Just render!
94                let mut frame = window.begin_drawing();
95
96                frame.clear_and_render(RenderTarget::Surface, color, |_pass| {
97                    // Additional rendering would go here
98                });
99
100                frame.finish();
101            });
102    }
Source

pub fn render_window_result<F, E>( &mut self, id: WindowId, events: &mut EventBatch, render_fn: F, ) -> Result<(), E>
where F: FnMut(&mut RenderableWindow, &mut EventBatch) -> Result<(), E>,

Renders a window with automatic event handling, passing a closure that returns a result.

This is useful when rendering might fail and you want to propagate errors.

§Example
use astrelis_render::{WindowManager, RenderTarget, Color};
use astrelis_winit::window::WindowBackend;

window_manager.render_window_result(window_id, events, |window, _events| {
    let mut frame = window.begin_drawing();
    frame.clear_and_render(RenderTarget::Surface, Color::BLACK, |_pass| {
        // Rendering that might fail
    });
    frame.finish();
    Ok(())
})
Source

pub fn graphics(&self) -> &Arc<GraphicsContext>

Gets the shared graphics context.

Source

pub fn iter(&self) -> impl Iterator<Item = (WindowId, &RenderableWindow)>

Iterates over all windows with their IDs.

Source

pub fn iter_mut( &mut self, ) -> impl Iterator<Item = (WindowId, &mut RenderableWindow)>

Iterates mutably over all windows with their IDs.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,