Skip to main content

Platform

Struct Platform 

Source
pub struct Platform { /* private fields */ }
Expand description

The game’s window and its connection to the operating system.

It stays on the thread that created it. On Linux it holds that thread’s OpenGL context, so the thread cannot have another (see GlContext).

Implementations§

Source§

impl Platform

Source

pub fn new(config: &WindowConfig) -> Result<Self, PlatformError>

Opens the window.

On Linux, it first sets the C library’s character locale (LC_CTYPE) from the environment, if it is still “C”, which a Rust program never changes: X’s input methods type in it, and in “C” they compose Latin-1 characters only. The locale is the whole process’s, and changing it races with another thread’s C code that reads it meanwhile, so open the window before starting threads that call such code. A program that has set a locale of its own keeps it.

§Errors

Fails if this system has no backend, if there is no display server to connect to, or if a system library is missing or too old. On macOS it fails on any thread but the main one. On Linux it also fails if the graphics driver cannot make an OpenGL 3.3 core context for the window, or if this thread already has an OpenGL context.

Examples found in repository?
examples/events.rs (line 83)
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}
Source

pub fn pump_events(&mut self, out: &mut Vec<Event>)

Appends the events that arrived since the last call to out. Does not wait for any.

Examples found in repository?
examples/events.rs (line 111)
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}
Source

pub fn poll_gamepads(&mut self, out: &mut Vec<Event>)

Appends what happened to the gamepads since the last call to out: pads plugged in and unplugged, and their buttons and axes. Does not wait for any. Call it once a frame, beside Platform::pump_events.

The first call reports the pads that are already plugged in: each one Event::GamepadConnected, at rest, then what is held on it. A pad unplugged is put back at rest by events of their own before its Event::GamepadDisconnected, so that the events alone always give each pad’s state. Pads are read whether or not the window has the focus.

Linux reads the kernel’s event devices, and needs read access to the gamepads’ nodes in /dev/input, which the desktop’s udev rules normally give the user at the seat. Windows (roadmap task M8.2) and macOS (M8.3) report no pads yet.

Examples found in repository?
examples/events.rs (line 112)
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}
Source

pub fn gamepad_state(&self, id: GamepadId) -> Option<&GamepadState>

What the pad’s buttons and axes are, as the events reported so far leave them, while it is plugged in. None for a pad that was unplugged, or never reported.

Examples found in repository?
examples/events.rs (line 118)
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}
Source

pub fn window_size(&self) -> UVec2

The size of the inside of the window, in physical pixels.

Examples found in repository?
examples/events.rs (line 84)
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}
Source

pub fn scale_factor(&self) -> f32

How many physical pixels one logical pixel covers: 1.0 on a standard display, 2.0 on one of twice the density.

Examples found in repository?
examples/events.rs (line 90)
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}
Source

pub fn set_fullscreen(&mut self, on: bool)

Enters or leaves borderless fullscreen.

Examples found in repository?
examples/events.rs (line 130)
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}
Source

pub fn set_title(&mut self, title: &str)

Changes the text in the title bar.

Examples found in repository?
examples/events.rs (line 138)
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}
Source

pub fn set_cursor_visible(&mut self, visible: bool)

Shows or hides the pointer while it is over the window.

Examples found in repository?
examples/events.rs (line 134)
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}
Source

pub fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>)

Sets what to call while the operating system runs an event loop of its own, and Platform::pump_events therefore does not return: while the user drags or resizes the window on Windows, or resizes it on macOS. It is called every 10 to 16 ms on Windows, and on macOS once for each step of the resize, so that the game can run frames. It replaces any callback set before.

The events of that time come from the next pump, after the loop. On Linux there is no such loop, and the callback is never called.

Examples found in repository?
examples/events.rs (line 103)
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}
Source

pub fn gpu_surface(&self) -> GpuSurface<'_>

What the GPU draws the window with. On Linux it is the window’s OpenGL context, current on this thread. On Windows and macOS, for now, it is a context with no functions, whose swaps fail with PlatformError::Unsupported.

Examples found in repository?
examples/events.rs (line 92)
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}

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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.