Skip to main content

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, RenderWindow> and handling common events like resizing.

§Example

use astrelis_render::{WindowManager, GraphicsContext, Color};
use astrelis_winit::app::{App, AppCtx};
use astrelis_winit::{WindowId, FrameTime};
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 Some(frame) = window.begin_frame() else { return };
            {
                let mut pass = frame.render_pass()
                    .clear_color(Color::BLACK)
                    .build();
                // Your rendering here
            }
        });
    }
}

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

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

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 RenderWindow>

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<RenderWindow>

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 RenderWindow, &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, Color};

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 Some(frame) = window.begin_frame() else { return };
    {
        let mut pass = frame.render_pass()
            .clear_color(Color::BLACK)
            .build();
        // Your rendering
    }
});
Examples found in repository?
examples/window_manager_demo.rs (lines 97-115)
86    fn render(&mut self, _ctx: &mut AppCtx, window_id: WindowId, events: &mut EventBatch) {
87        // Get the color for this window
88        let Some(&color) = self.window_colors.get(&window_id) else {
89            return;
90        };
91
92        // WindowManager automatically handles:
93        // 1. Window lookup (no manual HashMap.get_mut)
94        // 2. Resize events (automatic)
95        // 3. Event dispatching
96        self.window_manager
97            .render_window(window_id, events, |window, _events| {
98                // No need to manually handle resize events!
99                // WindowManager already did that for us
100
101                // Just render!
102                let Some(frame) = window.begin_frame() else {
103                    return; // Surface not available
104                };
105
106                {
107                    let _pass = frame
108                        .render_pass()
109                        .clear_color(color)
110                        .label("window_manager_pass")
111                        .build();
112                    // Additional rendering would go here
113                }
114                // Frame auto-submits on drop
115            });
116    }
Source

pub fn render_window_result<F, E>( &mut self, id: WindowId, events: &mut EventBatch, render_fn: F, ) -> Result<(), E>
where F: FnMut(&mut RenderWindow, &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, Color};

window_manager.render_window_result(window_id, events, |window, _events| {
    let Some(frame) = window.begin_frame() else { return Ok(()) };
    {
        let mut pass = frame.render_pass()
            .clear_color(Color::BLACK)
            .build();
        // Rendering that might fail
    }
    Ok(())
})
Source

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

Gets the shared graphics context.

Source

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

Iterates over all windows with their IDs.

Source

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

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,