Press Escape to quit

Description

Before we start rendering larger scenes, we'll switch to a fullscreen window. But before we go fullscreen, we need an easy way to exit the program.

This change shuts down the application if the Escape key is pressed.

Keyboard input events are tied to the active window. In our event loop we're checking that the key was pressed down and which keycode was sent.

We'll be expanding the list of keys we check shortly, so we're ignoring clippy's suggestion to switch the match statement to a single if.

Commands

git clone git@github.com:atsheehan/iridium
cd iridium
git checkout de4f0138d6572f11e0db50af4b81f99f9a852ae1
cargo run --release

Code Changes

Modified src/main.rsGitHub

@@ -4,8 +4,9 @@
44 use math::Vec3;
55 use render::Renderer;
66 use winit::{
7- event::{Event, WindowEvent},
7+ event::{ElementState, Event, KeyEvent, WindowEvent},
88 event_loop::EventLoop,
9+ keyboard::{KeyCode, PhysicalKey},
910 };
1011
1112 fn main() {
@@ -21,6 +22,27 @@
2122 window_target.exit();
2223 }
2324 Event::WindowEvent {
25+ event:
26+ WindowEvent::KeyboardInput {
27+ event:
28+ KeyEvent {
29+ state,
30+ physical_key,
31+ ..
32+ },
33+ ..
34+ },
35+ window_id,
36+ } if window_id == renderer.window_id() => {
37+ #[allow(clippy::single_match)]
38+ match (state, physical_key) {
39+ (ElementState::Pressed, PhysicalKey::Code(KeyCode::Escape)) => {
40+ window_target.exit();
41+ }
42+ _ => {}
43+ };
44+ }
45+ Event::WindowEvent {
2446 event: WindowEvent::RedrawRequested,
2547 window_id,
2648 } if window_id == renderer.window_id() => {
@@ -4,8 +4,9 @@
4 use math::Vec3;
5 use render::Renderer;
6 use winit::{
7- event::{Event, WindowEvent},
8 event_loop::EventLoop,
 
9 };
10
11 fn main() {
@@ -21,6 +22,27 @@
21 window_target.exit();
22 }
23 Event::WindowEvent {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24 event: WindowEvent::RedrawRequested,
25 window_id,
26 } if window_id == renderer.window_id() => {
@@ -4,8 +4,9 @@
4 use math::Vec3;
5 use render::Renderer;
6 use winit::{
7+ event::{ElementState, Event, KeyEvent, WindowEvent},
8 event_loop::EventLoop,
9+ keyboard::{KeyCode, PhysicalKey},
10 };
11
12 fn main() {
@@ -21,6 +22,27 @@
22 window_target.exit();
23 }
24 Event::WindowEvent {
25+ event:
26+ WindowEvent::KeyboardInput {
27+ event:
28+ KeyEvent {
29+ state,
30+ physical_key,
31+ ..
32+ },
33+ ..
34+ },
35+ window_id,
36+ } if window_id == renderer.window_id() => {
37+ #[allow(clippy::single_match)]
38+ match (state, physical_key) {
39+ (ElementState::Pressed, PhysicalKey::Code(KeyCode::Escape)) => {
40+ window_target.exit();
41+ }
42+ _ => {}
43+ };
44+ }
45+ Event::WindowEvent {
46 event: WindowEvent::RedrawRequested,
47 window_id,
48 } if window_id == renderer.window_id() => {