aboutsummaryrefslogtreecommitdiff
path: root/client/src/window.rs
blob: a7e1859fe9dfe5f4483a8685b82fe5ee0a01f0c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::sync::Arc;

use crate::{client::Client, renderer::Renderer};
use log::warn;
use winit::{
    application::ApplicationHandler,
    event::WindowEvent,
    event_loop::ActiveEventLoop,
    window::{Window, WindowAttributes, WindowId},
};

pub struct WindowState {
    temp_client: Option<Arc<Client>>,
    window: Option<(Window, Renderer<'static>)>,
}

impl WindowState {
    pub fn new(client: Arc<Client>) -> Self {
        Self {
            window: None,
            temp_client: Some(client),
        }
    }
}
impl ApplicationHandler for WindowState {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        let window = event_loop
            .create_window(WindowAttributes::default().with_maximized(true))
            .unwrap();
        let renderer = Renderer::new(
            unsafe { std::mem::transmute(&window) },
            self.temp_client.take().unwrap(),
        )
        .unwrap();
        self.window = Some((window, renderer))
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        event: WindowEvent,
    ) {
        if let Some((_win, ren)) = &mut self.window {
            match event {
                WindowEvent::CloseRequested => {
                    event_loop.exit();
                }
                WindowEvent::Resized(size) => {
                    ren.resize(size);
                }
                WindowEvent::RedrawRequested => {
                    if let Err(e) = ren.redraw() {
                        warn!("{e:?}")
                    }
                }
                _ => (),
            }
        }
    }
}

impl Drop for WindowState {
    fn drop(&mut self) {
        if let Some((win, ren)) = self.window.take() {
            drop(ren);
            drop(win);
        }
    }
}