Skip to content

Commit 1f2ecbc

Browse files
hansladamgreig
andcommitted
Move SDL objects to TLS, allowing multiple windows to co-exist.
Fixes embedded-graphics#47. Co-Authored-By: Adam Greig <[email protected]>
1 parent 7245086 commit 1f2ecbc

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed

Diff for: src/window/sdl_window.rs

+31-13
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,24 @@ use sdl2::{
1414

1515
use crate::{OutputImage, OutputSettings, SimulatorDisplay};
1616

17+
struct SdlContext {
18+
video_subsystem: sdl2::VideoSubsystem,
19+
event_pump: EventPump,
20+
}
21+
22+
thread_local! {
23+
static SDL_CONTEXT: std::cell::RefCell<SdlContext> = {
24+
let sdl_context = sdl2::init().unwrap();
25+
let video_subsystem = sdl_context.video().unwrap();
26+
let event_pump = sdl_context.event_pump().unwrap();
27+
28+
std::cell::RefCell::new(SdlContext {
29+
video_subsystem,
30+
event_pump,
31+
})
32+
};
33+
}
34+
1735
/// A derivation of [`sdl2::event::Event`] mapped to embedded-graphics coordinates
1836
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1937
pub enum SimulatorEvent {
@@ -67,7 +85,6 @@ pub enum SimulatorEvent {
6785

6886
pub struct SdlWindow {
6987
canvas: Canvas<sdl2::video::Window>,
70-
event_pump: EventPump,
7188
window_texture: SdlWindowTexture,
7289
size: Size,
7390
}
@@ -81,19 +98,18 @@ impl SdlWindow {
8198
where
8299
C: PixelColor + Into<Rgb888>,
83100
{
84-
let sdl_context = sdl2::init().unwrap();
85-
let video_subsystem = sdl_context.video().unwrap();
86-
87101
let size = output_settings.framebuffer_size(display);
88102

89-
let window = video_subsystem
90-
.window(title, size.width, size.height)
91-
.position_centered()
92-
.build()
93-
.unwrap();
103+
let window = SDL_CONTEXT.with(|ctx| {
104+
ctx.borrow_mut()
105+
.video_subsystem
106+
.window(title, size.width, size.height)
107+
.position_centered()
108+
.build()
109+
.unwrap()
110+
});
94111

95112
let canvas = window.into_canvas().build().unwrap();
96-
let event_pump = sdl_context.event_pump().unwrap();
97113

98114
let window_texture = SdlWindowTextureBuilder {
99115
texture_creator: canvas.texture_creator(),
@@ -107,7 +123,6 @@ impl SdlWindow {
107123

108124
Self {
109125
canvas,
110-
event_pump,
111126
window_texture,
112127
size,
113128
}
@@ -138,8 +153,11 @@ impl SdlWindow {
138153
output_settings: &OutputSettings,
139154
) -> impl Iterator<Item = SimulatorEvent> + '_ {
140155
let output_settings = output_settings.clone();
141-
self.event_pump
142-
.poll_iter()
156+
let events: Vec<Event> =
157+
SDL_CONTEXT.with(|ctx| ctx.borrow_mut().event_pump.poll_iter().collect());
158+
events
159+
.into_iter()
160+
.filter(|e| e.get_window_id() == Some(self.canvas.window().id()))
143161
.filter_map(move |event| match event {
144162
Event::Quit { .. }
145163
| Event::KeyDown {

0 commit comments

Comments
 (0)