sdl3-main 0.6.2

Tools for using SDL's main and callback APIs
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#![no_std]
#![deny(unsafe_op_in_unsafe_fn)]
#![doc = include_str!("../README.md.inc")]
#![cfg_attr(all(feature = "nightly", doc), feature(doc_cfg))] // https://github.com/rust-lang/rust/issues/43781
#![cfg_attr(feature = "nightly", feature(try_trait_v2))] // https://github.com/rust-lang/rust/issues/84277

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

use core::{
    ffi::{c_int, c_void},
    ptr,
};
use sdl3_sys::{
    init::SDL_AppResult,
    log::{SDL_LogCategory, SDL_LogCritical},
};

#[cfg(all(feature = "log-errors", feature = "nightly"))]
use {
    core::fmt::Display,
    sdl3_sys::{error::SDL_SetError, log::SDL_LogError},
};

#[cfg(feature = "nightly")]
use core::{convert::Infallible, ops::FromResidual};

#[cfg(doc)]
use state::SyncPtr;

/// Use this attribute macro if you want to provide your own main, but run it through SDL.
///
/// Supported signatures: (all of these can be safe or unsafe)
/// ```custom,{.rust}
/// fn()
/// fn() -> c_int
/// fn() -> bool
/// fn(argc: c_int, argv: *mut *mut c_char)
/// fn(argc: c_int, argv: *mut *mut c_char) -> c_int
/// fn(argc: c_int, argv: *mut *mut c_char) -> bool
/// fn() -> impl Termination
/// ```
///
/// Example:
/// ```rust
/// #[sdl3_main::main]
/// fn my_main() {
///     println!("main called through SDL!");
/// }
/// ```
pub use sdl3_main_macros::main;

/// This attribute macro can be applied to an `impl` block for a type to assign the associated
/// functions or methods named `app_init`, `app_iterate`, `app_event` and `app_quit` to the
/// respective sdl main callbacks, as if the corresponding attribute macros were used.
/// All four must be defined in a single impl block, but `app_quit` is optional and will be
/// defined as an empty function if omitted.
///
/// This is functionally the same as marking those functions with the respective attribute
/// macros, but works with methods and uses the type the block is implemented for as the
/// app state type.
///
/// See the documentation for [`app_init`], [`app_iterate`], [`app_event`] and [`app_quit`]
/// for information about supported function signatures. `app_impl` also supports methods,
/// taking `self` as the app state.
///
/// Example:
/// ```rust
/// use sdl3_main::{app_impl, AppResult};
/// use sdl3_sys::events::SDL_Event;
/// use std::sync::Mutex;
///
/// struct MyAppState {
///     // ...
/// }
///
/// #[app_impl]
/// impl MyAppState {
///     fn app_init() -> Option<Box<Mutex<MyAppState>>> {
///         todo!()
///     }
///
///     fn app_iterate(&mut self) -> AppResult {
///         todo!()
///     }
///
///     fn app_event(&mut self, event: &SDL_Event) -> AppResult {
///         todo!()
///     }
/// }
/// ```
pub use sdl3_main_macros::app_impl;

/// The function tagged with `app_init` is called by SDL at the start of the program on the main thread.
///
/// See the SDL documentation for this function:
/// [`SDL_AppInit`](https://docs.rs/sdl3-sys/latest/sdl3_sys/main/fn.SDL_AppInit.html)
///
/// The function tagged with this attribute determines the type of the app state, if any.
/// You can use a raw signature that doesn't handle the app state for you (safe or unsafe):
/// ```custom,{.rust}
/// fn(appstate: *mut *mut c_void, argc: c_int, argv: *mut *mut c_char) -> SDL_AppResult
/// fn(appstate: *mut *mut c_void, argc: c_int, argv: *mut *mut c_char) -> sdl3_main::AppResult
/// fn(argc: c_int, argv: *mut *mut c_char) -> SDL_AppResult
/// fn(argc: c_int, argv: *mut *mut c_char) -> sdl3_main::AppResult
/// fn(appstate: *mut *mut c_void) -> SDL_AppResult
/// fn(appstate: *mut *mut c_void) -> sdl3_main::AppResult
/// fn() -> SDL_AppResult
/// fn() -> sdl3_main::AppResult
/// ```
///
/// Or you can use one of these signatures with an app state type `S` (safe or unsafe):
/// ```custom,{.rust}
/// fn() -> Option<S>
/// fn() -> sdl3_main::AppResultWithState<S>
/// ```
///
/// The app state type must implement `Send` and `Sync`. You can define your own app state type
/// by implementing the `sdl3_main::AppState` trait, or use one of these predefined types:
/// ```custom,{.rust}
/// ()
/// sdl3_main::state::SyncPtr<_>
/// Box<_>
/// Arc<_>
/// ```
///
/// App states can be borrowed as many different types, depending on the app state. Everything
/// can be borrowed as `()` or `*mut c_void`.
///
/// | AppState | Can be borrowed as |
/// | -------- | ------------------ |
/// | [`SyncPtr<T>`] | <ul><li>`SyncPtr<T>`</li><li>`NonNull<T>` (may panic)</li><li>`Option<NonNull<T>>`</li></ul> |
/// | `Box<T>` | <ul><li>`&T`</li><li>`NonNull<T>`</li></ul> |
/// | `Box<Mutex<T>>` | <ul><li>`&T`</li><li>`&mut T`</li></ul> |
/// | `Box<RwLock<T>>` | <ul><li>`&T`</li><li>`&mut T`</li></ul> |
/// | `Arc<T>` | <ul><li>`Arc<T>`</li><li>`&Arc<T>`</li><li>`&T`</li><li>`NonNull<T>`</li></ul> |
/// | `Arc<Mutex<T>>` | <ul><li>`&T`</li><li>`&mut T`</li></ul> |
/// | `Arc<RwLock<T>>` | <ul><li>`&T`</li><li>`&mut T`</li></ul> |
pub use sdl3_main_macros::app_init;

/// The function tagged with `app_iterate` is called continuously by SDL on the main thread while the app is running.
///
/// It will only be called if `app_init` returned continue status, and keep getting called
/// for as long as `app_iterate` and `app_event` return continue status.
///
/// See the SDL documentation for this function:
/// [`SDL_AppIterate`](https://docs.rs/sdl3-sys/latest/sdl3_sys/main/fn.SDL_AppIterate.html)
///
/// Supported signatures (safe or unsafe), where `B` is a borrowed app state as defined in [`app_init`]:
/// ```custom,{.rust}
/// fn() -> impl sdl3_main::IntoAppResult
/// fn(B) -> impl sdl3_main::IntoAppResult
/// ```
pub use sdl3_main_macros::app_iterate;

/// The function tagged with `app_event` is called by SDL when an event is delivered. This may get called on the main thread
/// or on another thread.
///
/// See the SDL documentation for this function:
/// [`SDL_AppEvent`](https://docs.rs/sdl3-sys/latest/sdl3_sys/main/fn.SDL_AppEvent.html)
///
/// Supported signatures (safe or unsafe), where `B` is a borrowed app state as defined in [`app_init`],
/// and `E` is any supported event type:
/// ```custom,{.rust}
/// fn() -> impl sdl3_main::IntoAppResult
/// fn(E) -> impl sdl3_main::IntoAppResult
/// fn(B, E) -> impl sdl3_main::IntoAppResult
/// ```
///
/// Predefined supported event types:
/// ```custom,{.rust}
/// SDL_Event
/// &SDL_Event
/// &mut SDL_Event
/// *const SDL_Event
/// *mut SDL_Event
/// ```
/// You can add support for your own event types by implementing the `PassEventVal`, `PassEventRef` and/or `PassEventMut` traits.
pub use sdl3_main_macros::app_event;

/// The function tagged with `app_quit` is called by SDL on the main thread when the app quits.
///
/// This will get called regardless of the return status of `app_init`, so if that fails the
/// app state may not be available. If you're using an app state type you should take it as
/// an `Option` to avoid a panic in that case.
///
/// See the SDL documentation for this function:
/// [`SDL_AppQuit`](https://docs.rs/sdl3-sys/latest/sdl3_sys/main/fn.SDL_AppQuit.html)
///
/// Supported signatures (safe or unsafe), where `B` is a borrowed app state, and `S` is the app state
/// itself as defined in [`app_init`]:
/// ```custom,{.rust}
/// fn()
/// fn(Option<B>)
/// fn(Option<B>, SDL_AppResult)
/// fn(Option<B>, sdl3_main::AppResult)
/// fn(Option<S>)
/// fn(Option<S>, SDL_AppResult)
/// fn(Option<S>, sdl3_main::AppResult)
/// fn(B)
/// fn(B, SDL_AppResult)
/// fn(B, sdl3_main::AppResult)
/// fn(S)
/// fn(S, SDL_AppResult)
/// fn(S, sdl3_main::AppResult)
/// ```
pub use sdl3_main_macros::app_quit;

macro_rules! defer {
    ($($tt:tt)*) => {
        let _defer = $crate::Defer(Some(move || {{ $($tt)* };}));
    };
}

struct Defer<F: FnOnce()>(Option<F>);

impl<F: FnOnce()> Drop for Defer<F> {
    fn drop(&mut self) {
        if let Some(f) = self.0.take() {
            f();
        }
    }
}

pub mod app;
mod main_thread;
pub mod state;

pub use main_thread::{
    run_async_on_main_thread, run_sync_on_main_thread, MainThreadData, MainThreadToken,
};
use state::{AppState, BorrowMut, BorrowRef, BorrowVal, ConsumeMut, ConsumeRef, ConsumeVal};

#[doc(hidden)]
pub mod __internal {
    pub use ::sdl3_sys;

    #[cfg(feature = "alloc")]
    use alloc::boxed::Box;
    use core::{
        ffi::{c_char, c_int},
        ptr,
    };
    use sdl3_sys::main::SDL_RunApp;
    #[cfg(feature = "std")]
    use std::{
        any::Any,
        cell::UnsafeCell,
        mem::MaybeUninit,
        panic::{catch_unwind, resume_unwind, UnwindSafe},
    };

    #[cfg(feature = "std")]
    pub struct Shuttle<T>(UnsafeCell<MaybeUninit<Result<T, Box<dyn Any + Send>>>>);

    #[cfg(feature = "std")]
    unsafe impl<T> Sync for Shuttle<T> {}

    #[cfg(feature = "std")]
    impl<T> Shuttle<T> {
        #[allow(clippy::new_without_default)]
        pub const fn new() -> Self {
            Self(UnsafeCell::new(MaybeUninit::uninit()))
        }

        /// # Safety
        /// - This is not thread safe!
        /// - Calling this after a previous capture without a corresponding resume will
        ///   leak/forget the previous capture
        pub unsafe fn capture(&self, f: impl FnOnce() -> T + UnwindSafe) {
            match catch_unwind(f) {
                Ok(value) => {
                    unsafe { self.0.get().write(MaybeUninit::new(Ok(value))) };
                }
                Err(unwind) => {
                    unsafe { self.0.get().write(MaybeUninit::new(Err(unwind))) };
                }
            }
        }

        /// # Safety
        /// - This is not thread safe!
        /// - It's UB to call this without having called `capture`
        /// - It's UB to call this more than once after each call to `capture`
        pub unsafe fn resume(&self) -> T {
            match unsafe { (*self.0.get()).assume_init_read() } {
                Ok(value) => value,
                Err(unwind) => resume_unwind(unwind),
            }
        }
    }

    #[cfg(feature = "std")]
    impl Shuttle<()> {
        /// # Safety
        /// - This is not thread safe!
        /// - It's UB to call this more than once before each call to `resume`
        pub unsafe fn capture_and_continue<T>(
            &self,
            unwind_val: T,
            f: impl FnOnce() -> T + UnwindSafe,
        ) -> T {
            match catch_unwind(f) {
                Ok(value) => {
                    unsafe { self.0.get().write(MaybeUninit::new(Ok(()))) };
                    value
                }
                Err(unwind) => {
                    unsafe { self.0.get().write(MaybeUninit::new(Err(unwind))) };
                    unwind_val
                }
            }
        }
    }

    #[cfg(feature = "std")]
    #[inline(always)] // this is only called once
    pub unsafe fn run_app(
        main_fn: unsafe extern "C" fn(c_int, *mut *mut c_char) -> c_int,
    ) -> c_int {
        #[cfg(windows)]
        {
            // On Windows, SDL_RunApp gets arguments from the win api if passed NULL
            unsafe { SDL_RunApp(0, ptr::null_mut(), Some(main_fn), ptr::null_mut()) }
        }
        #[cfg(not(windows))]
        {
            use std::env;
            use std::vec::Vec;

            // copy arguments so we can null-terminate them
            let args = env::args_os();

            let mut cargs = Vec::with_capacity(args.len());
            for arg in args {
                let mut carg;
                #[cfg(unix)]
                {
                    use std::{borrow::ToOwned, os::unix::ffi::OsStringExt};
                    carg = arg.to_owned().into_vec();
                }
                #[cfg(not(unix))]
                {
                    // yolo
                    carg = arg.to_string_lossy().into_owned().into_bytes();
                }
                carg.reserve_exact(1);
                carg.push(0);
                cargs.push(carg.into_boxed_slice());
            }

            let mut ptrargs = Vec::with_capacity(cargs.len() + 1);
            for carg in cargs.iter_mut() {
                ptrargs.push(carg.as_mut_ptr() as *mut c_char);
            }
            ptrargs.push(ptr::null_mut());

            unsafe {
                SDL_RunApp(
                    cargs.len().try_into().expect("too many arguments"),
                    ptrargs.as_mut_ptr(),
                    Some(main_fn),
                    ptr::null_mut(),
                )
            }
        }
    }
}

/// This trait is used for converting a type into an [`SDL_AppResult`] or [`AppResult`].
///
/// `()` implements this trait and turns into [`SDL_AppResult::CONTINUE`]
pub trait IntoAppResult: Sized {
    fn into_sdl_app_result(self) -> SDL_AppResult;

    #[inline(always)]
    fn into_app_result(self) -> AppResult {
        self.into_sdl_app_result().into()
    }
}

impl IntoAppResult for () {
    #[inline(always)]
    fn into_sdl_app_result(self) -> SDL_AppResult {
        SDL_AppResult::CONTINUE
    }

    #[inline(always)]
    fn into_app_result(self) -> AppResult {
        AppResult::Continue
    }
}

impl IntoAppResult for SDL_AppResult {
    #[inline(always)]
    fn into_sdl_app_result(self) -> SDL_AppResult {
        self
    }

    #[inline(always)]
    fn into_app_result(self) -> AppResult {
        self.into()
    }
}

impl IntoAppResult for AppResult {
    #[inline(always)]
    fn into_sdl_app_result(self) -> SDL_AppResult {
        self.into()
    }

    #[inline(always)]
    fn into_app_result(self) -> AppResult {
        self
    }
}

/// This is the Rust enum equivalent to [`SDL_AppResult`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AppResult {
    /// Continue running
    Continue,

    /// Quit with success status
    Success,

    /// Quit with failure status
    Failure,
}

impl From<AppResult> for SDL_AppResult {
    #[inline(always)]
    fn from(value: AppResult) -> Self {
        match value {
            AppResult::Continue => Self::CONTINUE,
            AppResult::Success => Self::SUCCESS,
            AppResult::Failure => Self::FAILURE,
        }
    }
}

impl From<SDL_AppResult> for AppResult {
    #[inline]
    fn from(value: SDL_AppResult) -> Self {
        match value {
            SDL_AppResult::CONTINUE => Self::Continue,
            SDL_AppResult::SUCCESS => Self::Success,
            SDL_AppResult::FAILURE => Self::Failure,
            SDL_AppResult(value) => {
                #[cold]
                #[inline(never)]
                fn unknown_app_result_value(result: c_int) -> AppResult {
                    unsafe {
                        SDL_LogCritical(
                            SDL_LogCategory::APPLICATION.into(),
                            c"Unrecognized app result value: %d".as_ptr(),
                            result,
                        )
                    };
                    AppResult::Failure
                }
                unknown_app_result_value(value)
            }
        }
    }
}

#[cfg(all(feature = "nightly", feature = "log-errors"))]
impl<E: Display> FromResidual<Result<Infallible, E>> for AppResult {
    fn from_residual(residual: Result<Infallible, E>) -> Self {
        let Err(err) = residual;
        let err = ::alloc::format!("{err}\0");
        unsafe {
            SDL_LogError(0, c"%s".as_ptr(), err.as_ptr());
            SDL_SetError(c"%s".as_ptr(), err.as_ptr());
        };
        AppResult::Failure
    }
}

#[cfg(all(feature = "nightly", not(feature = "log-errors")))]
impl<E> FromResidual<Result<Infallible, E>> for AppResult {
    #[inline(always)]
    fn from_residual(_residual: Result<Infallible, E>) -> Self {
        AppResult::Failure
    }
}

#[cfg(feature = "nightly")]
impl FromResidual<Option<Infallible>> for AppResult {
    #[inline(always)]
    fn from_residual(_residual: Option<Infallible>) -> Self {
        AppResult::Failure
    }
}

/// An [`AppResult`] with an app state, for returning from the function tagged with [`app_init`].
#[derive(Debug)]
pub enum AppResultWithState<S: AppState> {
    /// Continue running
    Continue(S),

    /// Quit with success status
    Success(Option<S>),

    /// Quit with failure status
    Failure(Option<S>),
}

#[cfg(all(feature = "nightly", feature = "log-errors"))]
impl<S: AppState, E: Display> FromResidual<Result<Infallible, E>> for AppResultWithState<S> {
    fn from_residual(residual: Result<Infallible, E>) -> Self {
        let Err(err) = residual;
        let err = ::alloc::format!("{err}\0");
        unsafe {
            SDL_LogError(0, c"%s".as_ptr(), err.as_ptr());
            SDL_SetError(c"%s".as_ptr(), err.as_ptr());
        };
        AppResultWithState::Failure(None)
    }
}

#[cfg(all(feature = "nightly", not(feature = "log-errors")))]
impl<S: AppState, E> FromResidual<Result<Infallible, E>> for AppResultWithState<S> {
    #[inline(always)]
    fn from_residual(_residual: Result<Infallible, E>) -> Self {
        AppResultWithState::Failure(None)
    }
}

#[cfg(feature = "nightly")]
impl<S: AppState> FromResidual<Option<Infallible>> for AppResultWithState<S> {
    #[inline(always)]
    fn from_residual(_residual: Option<Infallible>) -> Self {
        AppResultWithState::Failure(None)
    }
}

impl<S: AppState> AppResultWithState<S> {
    pub fn into_raw(self) -> (SDL_AppResult, *mut c_void) {
        match self {
            Self::Continue(s) => (SDL_AppResult::CONTINUE, s.into_raw()),
            Self::Success(s) => (
                SDL_AppResult::SUCCESS,
                s.map(|s| s.into_raw()).unwrap_or(ptr::null_mut()),
            ),
            Self::Failure(s) => (
                SDL_AppResult::FAILURE,
                s.map(|s| s.into_raw()).unwrap_or(ptr::null_mut()),
            ),
        }
    }
}