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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use std::error;
use std::ffi::{CStr, CString, NulError};
use std::fmt;
use std::rc::Rc;
use libc::c_char;
use std::mem::transmute;
use crate::sys;
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum Error {
NoMemError = sys::SDL_errorcode::SDL_ENOMEM as i32,
ReadError = sys::SDL_errorcode::SDL_EFREAD as i32,
WriteError = sys::SDL_errorcode::SDL_EFWRITE as i32,
SeekError = sys::SDL_errorcode::SDL_EFSEEK as i32,
UnsupportedError = sys::SDL_errorcode::SDL_UNSUPPORTED as i32
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match *self {
NoMemError => write!(f, "Out of memory"),
ReadError => write!(f, "Error reading from datastream"),
WriteError => write!(f, "Error writing to datastream"),
SeekError => write!(f, "Error seeking in datastream"),
UnsupportedError => write!(f, "Unknown SDL error")
}
}
}
impl error::Error for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
NoMemError => "out of memory",
ReadError => "error reading from datastream",
WriteError => "error writing to datastream",
SeekError => "error seeking in datastream",
UnsupportedError => "unknown SDL error"
}
}
}
use std::sync::atomic::{AtomicBool};
static IS_SDL_CONTEXT_ALIVE: AtomicBool = AtomicBool::new(false);
#[derive(Clone)]
pub struct Sdl {
sdldrop: Rc<SdlDrop>
}
impl Sdl {
#[inline]
fn new() -> Result<Sdl, String> {
unsafe {
use std::sync::atomic::Ordering;
let was_alive = IS_SDL_CONTEXT_ALIVE.swap(true, Ordering::Relaxed);
if was_alive {
Err("Cannot initialize `Sdl` more than once at a time.".to_owned())
} else if sys::SDL_Init(0) == 0 {
Ok(Sdl {
sdldrop: Rc::new(SdlDrop)
})
} else {
IS_SDL_CONTEXT_ALIVE.swap(false, Ordering::Relaxed);
Err(get_error())
}
}
}
#[inline]
pub fn audio(&self) -> Result<AudioSubsystem, String> { AudioSubsystem::new(self) }
#[inline]
pub fn event(&self) -> Result<EventSubsystem, String> { EventSubsystem::new(self) }
#[inline]
pub fn joystick(&self) -> Result<JoystickSubsystem, String> { JoystickSubsystem::new(self) }
#[inline]
pub fn haptic(&self) -> Result<HapticSubsystem, String> { HapticSubsystem::new(self) }
#[inline]
pub fn game_controller(&self) -> Result<GameControllerSubsystem, String> { GameControllerSubsystem::new(self) }
#[inline]
pub fn timer(&self) -> Result<TimerSubsystem, String> { TimerSubsystem::new(self) }
#[inline]
pub fn video(&self) -> Result<VideoSubsystem, String> { VideoSubsystem::new(self) }
#[inline]
pub fn event_pump(&self) -> Result<EventPump, String> {
EventPump::new(self)
}
#[inline]
#[doc(hidden)]
pub fn sdldrop(&self) -> Rc<SdlDrop> {
self.sdldrop.clone()
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct SdlDrop;
impl Drop for SdlDrop {
#[inline]
fn drop(&mut self) {
use std::sync::atomic::Ordering;
let was_alive = IS_SDL_CONTEXT_ALIVE.swap(false, Ordering::Relaxed);
assert!(was_alive);
unsafe { sys::SDL_Quit(); }
}
}
macro_rules! subsystem {
($name:ident, $flag:expr) => (
impl $name {
#[inline]
fn new(sdl: &Sdl) -> Result<$name, String> {
let result = unsafe { sys::SDL_InitSubSystem($flag) };
if result == 0 {
Ok($name {
_subsystem_drop: Rc::new(SubsystemDrop {
_sdldrop: sdl.sdldrop.clone(),
flag: $flag
})
})
} else {
Err(get_error())
}
}
}
);
($name:ident, $flag:expr, nosync) => (
#[derive(Debug, Clone)]
pub struct $name {
_subsystem_drop: Rc<SubsystemDrop>
}
impl $name {
#[inline]
pub fn sdl(&self) -> Sdl {
Sdl { sdldrop: self._subsystem_drop._sdldrop.clone() }
}
}
subsystem!($name, $flag);
);
($name:ident, $flag:expr, sync) => (
pub struct $name {
_subsystem_drop: Rc<SubsystemDrop>
}
unsafe impl Sync for $name {}
impl std::clone::Clone for $name {
#[inline]
fn clone(&self) -> $name {
$name {
_subsystem_drop: self._subsystem_drop.clone()
}
}
}
impl $name {
#[inline]
pub fn sdl(&self) -> Sdl {
Sdl { sdldrop: self._subsystem_drop._sdldrop.clone() }
}
}
subsystem!($name, $flag);
)
}
#[derive(Debug, Clone)]
struct SubsystemDrop {
_sdldrop: Rc<SdlDrop>,
flag: u32
}
impl Drop for SubsystemDrop {
#[inline]
fn drop(&mut self) {
unsafe { sys::SDL_QuitSubSystem(self.flag); }
}
}
subsystem!(AudioSubsystem, sys::SDL_INIT_AUDIO, nosync);
subsystem!(GameControllerSubsystem, sys::SDL_INIT_GAMECONTROLLER, nosync);
subsystem!(HapticSubsystem, sys::SDL_INIT_HAPTIC, nosync);
subsystem!(JoystickSubsystem, sys::SDL_INIT_JOYSTICK, nosync);
subsystem!(VideoSubsystem, sys::SDL_INIT_VIDEO, nosync);
subsystem!(TimerSubsystem, sys::SDL_INIT_TIMER, sync);
subsystem!(EventSubsystem, sys::SDL_INIT_EVENTS, sync);
static mut IS_EVENT_PUMP_ALIVE: bool = false;
pub struct EventPump {
_sdldrop: Rc<SdlDrop>
}
impl EventPump {
#[inline]
fn new(sdl: &Sdl) -> Result<EventPump, String> {
unsafe {
if IS_EVENT_PUMP_ALIVE {
Err("an `EventPump` instance is already alive - there can only be one `EventPump` in use at a time.".to_owned())
} else {
let result = sys::SDL_InitSubSystem(sys::SDL_INIT_EVENTS);
if result == 0 {
IS_EVENT_PUMP_ALIVE = true;
Ok(EventPump {
_sdldrop: sdl.sdldrop.clone()
})
} else {
Err(get_error())
}
}
}
}
}
impl Drop for EventPump {
#[inline]
fn drop(&mut self) {
unsafe {
assert!(IS_EVENT_PUMP_ALIVE);
sys::SDL_QuitSubSystem(sys::SDL_INIT_EVENTS);
IS_EVENT_PUMP_ALIVE = false;
}
}
}
#[inline]
pub fn get_platform() -> &'static str {
unsafe {
CStr::from_ptr(sys::SDL_GetPlatform()).to_str().unwrap()
}
}
#[inline]
pub fn init() -> Result<Sdl, String> { Sdl::new() }
pub fn get_error() -> String {
unsafe {
let err = sys::SDL_GetError();
CStr::from_ptr(err as *const _).to_str().unwrap().to_owned()
}
}
pub fn set_error(err: &str) -> Result<(), NulError> {
let c_string = CString::new(err)?;
unsafe {
sys::SDL_SetError(c_string.as_ptr() as *const c_char);
}
Ok(())
}
pub fn set_error_from_code(err: Error) {
unsafe { sys::SDL_Error(transmute(err)); }
}
pub fn clear_error() {
unsafe { sys::SDL_ClearError(); }
}