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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
|
use crate::*;
use winit::application::ApplicationHandler;
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::{MouseButton as WinitMouseButton, MouseScrollDelta, StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::keyboard::PhysicalKey;
use winit::window::WindowId;
use winit::error::EventLoopError;
use std::collections::HashMap;
use std::time::{Duration, Instant};
pub struct Phosphor {
event_loop: EventLoop<()>,
builders: Vec<WindowBuilder>,
}
impl Phosphor {
pub fn new() -> Result<Self, ()> {
if let Ok(event_loop) = EventLoop::new() {
Ok( Self {
event_loop,
builders: Vec::new(),
} )
} else {
Err(())
}
}
pub fn create_window(&mut self, window: WindowBuilder) {
self.builders.push(window);
}
pub fn run(self) -> Result<(), EventLoopError> {
let mut application = PhosphorApplication {
builders: self.builders,
windows: HashMap::new(),
frame_start: Instant::now(),
};
self.event_loop.run_app(&mut application)
}
}
struct PhosphorApplication {
builders: Vec<WindowBuilder>,
windows: HashMap<WindowId, PhosphorWindow>,
frame_start: Instant,
}
impl PhosphorApplication {
pub fn handle_builders_and_destructors(&mut self, event_loop: &ActiveEventLoop) {
// Find marked windows, handle final requests and destroy.
let mut marked_ids = Vec::new();
for (id, window) in &mut self.windows {
if window.marked_for_destruction {
window.handle_requests(&mut self.builders);
marked_ids.push(id.clone());
}
}
for id in marked_ids {
self.windows.remove(&id);
}
// Build any newly-requested windows.
while !self.builders.is_empty() {
for builder in std::mem::take(&mut self.builders) {
let mut window = PhosphorWindow::from_builder(builder, event_loop);
window.program.handle_event(Event::Initialise, &mut window.requests.as_writer());
window.handle_requests(&mut self.builders);
self.windows.insert(window.winit.id(), window);
}
}
// If all windows have been destroyed, close the event loop.
if self.windows.is_empty() {
event_loop.exit();
}
}
pub fn handle_window_event(&mut self, event: WindowEvent, id: WindowId) {
let window = match self.windows.get_mut(&id) {
Some(w) => w,
None => return,
};
macro_rules! handle { ($event:expr) => {
window.program.handle_event($event, &mut window.requests.as_writer())
}; }
match event {
WindowEvent::Resized( PhysicalSize { width, height } ) => {
window.update_buffer_size(Dimensions::new(width, height));
}
WindowEvent::CloseRequested => {
handle!(Event::CloseRequest);
}
WindowEvent::Destroyed => {
handle!(Event::Close);
}
WindowEvent::DroppedFile(path) => {
handle!(Event::FileDrop(path));
}
WindowEvent::Focused(focused) => {
handle!(Event::FocusChange(focused));
}
WindowEvent::KeyboardInput { event, .. } => {
if let Some(smol_str) = event.text {
if event.state.is_pressed() {
for c in smol_str.chars() {
handle!(Event::CharacterInput(c));
}
}
}
if let PhysicalKey::Code(code) = event.physical_key {
handle!(Event::KeyboardInput {
key: code,
action: event.state.into(),
});
}
}
WindowEvent::ModifiersChanged(modifiers) => {
handle!(Event::ModifierChange(modifiers.state()));
}
WindowEvent::CursorMoved { position, .. } => {
let pointer = Position::new(
position.x as i32 / window.scale() as i32,
position.y as i32 / window.scale() as i32,
);
if window.pointer != Some(pointer) {
window.pointer = Some(pointer);
handle!(Event::CursorMove(pointer));
}
}
WindowEvent::CursorEntered { .. } => {
handle!(Event::CursorEnter);
}
WindowEvent::CursorLeft { .. } => {
handle!(Event::CursorExit);
}
WindowEvent::MouseWheel { delta, .. } => match delta {
MouseScrollDelta::LineDelta(x, y) => {
if x != 0.0 { handle!(Event::ScrollLines { axis: Axis::Horizontal, distance: -x }); }
if y != 0.0 { handle!(Event::ScrollLines { axis: Axis::Vertical, distance: -y }); }
}
MouseScrollDelta::PixelDelta(PhysicalPosition {x, y}) => {
if x != 0.0 { handle!(Event::ScrollPixels { axis: Axis::Horizontal, distance: -x as f32 }); }
if y != 0.0 { handle!(Event::ScrollPixels { axis: Axis::Vertical, distance: -y as f32 }); }
}
}
WindowEvent::MouseInput { state, button, .. } => {
let action = state.into();
match button {
WinitMouseButton::Left => handle!(Event::MouseButton { button: MouseButton::Left, action }),
WinitMouseButton::Middle => handle!(Event::MouseButton { button: MouseButton::Middle, action }),
WinitMouseButton::Right => handle!(Event::MouseButton { button: MouseButton::Right, action }),
_ => (),
}
}
WindowEvent::RedrawRequested => {
window.redraw();
},
_ => (),
}
}
}
impl ApplicationHandler for PhosphorApplication {
fn resumed(&mut self, _event_loop: &ActiveEventLoop) {}
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
if let StartCause::Init = cause {
// Ensure a minimum duration between frames.
const MINIMUM_WAIT: Duration = Duration::from_millis(1);
std::thread::sleep(MINIMUM_WAIT.saturating_sub(self.frame_start.elapsed()));
self.frame_start = Instant::now();
event_loop.set_control_flow(ControlFlow::Poll);
self.handle_builders_and_destructors(event_loop);
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
for (_, window) in &mut self.windows {
window.program.process(&mut window.requests.as_writer());
window.handle_requests(&mut self.builders);
}
self.handle_builders_and_destructors(event_loop);
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
self.handle_window_event(event, id);
if let Some(window) = self.windows.get_mut(&id) {
window.handle_requests(&mut self.builders);
}
self.handle_builders_and_destructors(event_loop);
}
}
|