Skip to main content

events/
events.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Opens a window and prints every event it and the gamepads report.
16//!
17//! ```text
18//! cargo run -p nadir-platform --example events -- [options]
19//! ```
20//!
21//! Options:
22//!
23//! - `--seconds N`: close after N seconds.
24//! - `--fullscreen`: start fullscreen.
25//! - `--fixed`: do not let the user resize the window.
26//! - `--no-vsync`: ask for a swap interval of 0.
27//!
28//! Keys, named by their place on a US keyboard:
29//!
30//! - `F`: enter or leave fullscreen.
31//! - `C`: hide or show the pointer.
32//! - `T`: change the title.
33//! - `Escape`: quit. So does closing the window.
34//!
35//! While the system holds the event loop (on Windows, while the window is
36//! dragged or resized), it counts modal frames, and says how many ran once
37//! the loop is back.
38//!
39//! Gamepads are polled with the window's events: plugging one in or out, its
40//! buttons and its axes are printed too, and a pad's name when it connects.
41
42use std::cell::Cell;
43use std::error::Error;
44use std::io::{self, Write};
45use std::process::ExitCode;
46use std::rc::Rc;
47use std::thread;
48use std::time::{Duration, Instant};
49
50use nadir_core::cli::Args;
51use nadir_core::{Key, UVec2};
52use nadir_platform::{Event, GpuSurface, Platform, WindowConfig};
53
54/// How long to wait between looks at the event queue.
55const POLL_INTERVAL: Duration = Duration::from_millis(5);
56
57fn main() -> ExitCode {
58    match run(Args::from_env(), &mut io::stdout()) {
59        Ok(()) => ExitCode::SUCCESS,
60        Err(error) => {
61            // If standard error is closed too, there is nobody left to tell.
62            let _ = writeln!(io::stderr(), "events: {error}");
63            ExitCode::FAILURE
64        }
65    }
66}
67
68fn run(mut args: Args, out: &mut dyn Write) -> Result<(), Box<dyn Error>> {
69    let seconds: Option<f64> = args.parsed("--seconds")?;
70    let config = WindowConfig {
71        title: "Nadir events".to_string(),
72        size: UVec2::new(640, 360),
73        min_size: UVec2::new(320, 180),
74        resizable: !args.flag("--fixed"),
75        fullscreen: args.flag("--fullscreen"),
76        vsync: !args.flag("--no-vsync"),
77    };
78    if let Some(extra) = args.finish()?.first() {
79        return Err(format!("unexpected argument `{extra}`").into());
80    }
81    let deadline = seconds.map(Duration::try_from_secs_f64).transpose()?;
82
83    let mut platform = Platform::new(&config)?;
84    let size = platform.window_size();
85    writeln!(
86        out,
87        "window: {}x{} physical pixels, scale factor {}",
88        size.x,
89        size.y,
90        platform.scale_factor()
91    )?;
92    match platform.gpu_surface() {
93        GpuSurface::Gl(gl) => {
94            let drawable = gl.drawable_size();
95            writeln!(out, "gpu: OpenGL, drawable {}x{}", drawable.x, drawable.y)?;
96        }
97        _ => writeln!(out, "gpu: not OpenGL")?,
98    }
99    writeln!(out, "keys: F fullscreen, C pointer, T title, Escape quit")?;
100
101    let modal_frames = Rc::new(Cell::new(0u64));
102    let counter = Rc::clone(&modal_frames);
103    platform.set_modal_frame_callback(Box::new(move |_frame| counter.set(counter.get() + 1)));
104
105    let start = Instant::now();
106    let mut events = Vec::new();
107    let mut fullscreen = config.fullscreen;
108    let mut pointer_visible = true;
109    let mut titles = 0;
110    loop {
111        platform.pump_events(&mut events);
112        platform.poll_gamepads(&mut events);
113        for &event in &events {
114            writeln!(out, "{:9.3}  {event:?}", start.elapsed().as_secs_f64())?;
115            match event {
116                Event::CloseRequested => return Ok(()),
117                Event::GamepadConnected(id) => {
118                    if let Some(state) = platform.gamepad_state(id) {
119                        writeln!(out, "           gamepad {}: {:?}", id.raw(), state.name())?;
120                    }
121                }
122                Event::Key {
123                    key,
124                    pressed: true,
125                    repeat: false,
126                } => match key {
127                    Key::Escape => return Ok(()),
128                    Key::F => {
129                        fullscreen = !fullscreen;
130                        platform.set_fullscreen(fullscreen);
131                    }
132                    Key::C => {
133                        pointer_visible = !pointer_visible;
134                        platform.set_cursor_visible(pointer_visible);
135                    }
136                    Key::T => {
137                        titles += 1;
138                        platform.set_title(&format!("Nadir events — title {titles}"));
139                    }
140                    _ => {}
141                },
142                _ => {}
143            }
144        }
145        let held = modal_frames.replace(0);
146        if held > 0 {
147            writeln!(
148                out,
149                "{:9.3}  {held} modal frames ran while the system held the loop",
150                start.elapsed().as_secs_f64()
151            )?;
152        }
153        // Show the events now, also when the output is a pipe.
154        out.flush()?;
155        events.clear();
156        if deadline.is_some_and(|deadline| start.elapsed() >= deadline) {
157            writeln!(out, "closing after {:.1} s", start.elapsed().as_secs_f64())?;
158            return Ok(());
159        }
160        thread::sleep(POLL_INTERVAL);
161    }
162}