sdl3 0.18.4

Bindings to SDL3, a cross-platform library to abstract the platform-specific details for building applications.
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
use crate::sys;
// use crate::sys::joystick::joystick::SDL_PowerState;

use crate::clear_error;
use crate::common::{validate_int, IntegerOrSdlError};
use crate::get_error;
use crate::guid::Guid;
use crate::Error;
use crate::JoystickSubsystem;
use libc::{c_char, c_void};
use std::ffi::{CStr, CString};
use std::fmt;
use sys::power::{SDL_PowerState, SDL_POWERSTATE_UNKNOWN};
use sys::stdinc::SDL_free;

pub type JoystickId = sys::joystick::SDL_JoystickID;

impl JoystickSubsystem {
    /// Get joystick instance IDs and names.
    #[doc(alias = "SDL_GetJoysticks")]
    pub fn joysticks(&self) -> Result<Vec<JoystickId>, Error> {
        let mut num_joysticks: i32 = 0;
        unsafe {
            let joystick_ids = sys::joystick::SDL_GetJoysticks(&mut num_joysticks);
            if joystick_ids.is_null() {
                Err(get_error())
            } else {
                let mut instances = Vec::new();
                for i in 0..num_joysticks {
                    let id = *joystick_ids.offset(i as isize);
                    instances.push(id);
                }
                SDL_free(joystick_ids as *mut c_void);
                Ok(instances)
            }
        }
    }

    /// Attempt to open the joystick at index `joystick_index` and return it.
    #[doc(alias = "SDL_OpenJoystick")]
    pub fn open(&self, joystick_id: JoystickId) -> Result<Joystick, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        let joystick = unsafe { sys::joystick::SDL_OpenJoystick(joystick_id) };

        if joystick.is_null() {
            Err(SdlError(get_error()))
        } else {
            Ok(Joystick {
                subsystem: self.clone(),
                raw: joystick,
            })
        }
    }

    /// If state is `true` joystick events are processed, otherwise
    /// they're ignored.
    #[doc(alias = "SDL_SetJoystickEventsEnabled")]
    pub fn set_joystick_events_enabled(&self, state: bool) {
        unsafe { sys::joystick::SDL_SetJoystickEventsEnabled(state) };
    }

    /// Return `true` if joystick events are processed.
    #[doc(alias = "SDL_JoystickEventsEnabled")]
    pub fn event_state(&self) -> bool {
        unsafe { sys::joystick::SDL_JoystickEventsEnabled() }
    }

    /// Force joystick update when not using the event loop
    #[inline]
    #[doc(alias = "SDL_UpdateJoysticks")]
    pub fn update(&self) {
        unsafe { sys::joystick::SDL_UpdateJoysticks() };
    }

    /// Check if a joystick is virtual
    #[doc(alias = "SDL_IsJoystickVirtual")]
    pub fn is_virtual(&self, joystick_id: JoystickId) -> bool {
        unsafe { sys::joystick::SDL_IsJoystickVirtual(joystick_id) }
    }

    /// Attach a virtual joystick
    pub fn attach_virtual_joystick(
        &self,
        desc: VirtualJoystickDescription,
    ) -> Result<VirtualJoystickConnection, IntegerOrSdlError> {
        let mut raw_desc = sys::joystick::SDL_VirtualJoystickDesc::new();

        raw_desc.name = desc.name.as_ptr();
        raw_desc.r#type = desc.joystick_type.to_ll().0 as u16;
        raw_desc.naxes = desc.num_axes;
        raw_desc.nbuttons = desc.num_buttons;
        raw_desc.nhats = desc.num_hats;
        raw_desc.axis_mask = desc.axis_mask;
        raw_desc.button_mask = desc.button_mask;

        let joystick_id = unsafe { sys::joystick::SDL_AttachVirtualJoystick(&raw_desc) };

        if joystick_id.0 == 0 {
            Err(IntegerOrSdlError::SdlError(get_error()))
        } else {
            let joystick = self.open(joystick_id)?;

            Ok(VirtualJoystickConnection { inner: joystick })
        }
    }
}

// power level and percentage together
pub struct PowerInfo {
    pub state: PowerLevel,
    pub percentage: i32,
}

impl fmt::Debug for PowerInfo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "PowerInfo {{ state: {:?}, percentage: {} }}",
            self.state, self.percentage
        )
    }
}

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[repr(i32)]
pub enum PowerLevel {
    Unknown = SDL_PowerState::UNKNOWN.0,
    Error = SDL_PowerState::ERROR.0,
    OnBattery = SDL_PowerState::ON_BATTERY.0,
    NoBattery = SDL_PowerState::NO_BATTERY.0,
    Charging = SDL_PowerState::CHARGING.0,
    Charged = SDL_PowerState::CHARGED.0,
}

impl PowerLevel {
    pub fn from_ll(raw: SDL_PowerState) -> PowerLevel {
        match raw {
            SDL_PowerState::UNKNOWN => PowerLevel::Unknown,
            SDL_PowerState::ERROR => PowerLevel::Error,
            SDL_PowerState::ON_BATTERY => PowerLevel::OnBattery,
            SDL_PowerState::NO_BATTERY => PowerLevel::NoBattery,
            SDL_PowerState::CHARGING => PowerLevel::Charging,
            SDL_PowerState::CHARGED => PowerLevel::Charged,
            _ => panic!("Unexpected power level"),
        }
    }

    pub fn to_ll(self) -> SDL_PowerState {
        match self {
            PowerLevel::Unknown => SDL_PowerState::UNKNOWN,
            PowerLevel::Error => SDL_PowerState::ERROR,
            PowerLevel::OnBattery => SDL_PowerState::ON_BATTERY,
            PowerLevel::NoBattery => SDL_PowerState::NO_BATTERY,
            PowerLevel::Charging => SDL_PowerState::CHARGING,
            PowerLevel::Charged => SDL_PowerState::CHARGED,
        }
    }
}

/// Wrapper around the `SDL_Joystick` object
pub struct Joystick {
    subsystem: JoystickSubsystem,
    raw: *mut sys::joystick::SDL_Joystick,
}

impl Joystick {
    #[inline]
    pub const fn subsystem(&self) -> &JoystickSubsystem {
        &self.subsystem
    }

    /// Return the name of the joystick or an empty string if no name
    /// is found.
    #[doc(alias = "SDL_GetJoystickName")]
    pub fn name(&self) -> String {
        let name = unsafe { sys::joystick::SDL_GetJoystickName(self.raw) };

        c_str_to_string(name)
    }

    /// Return true if the joystick has been opened and currently
    /// connected.
    #[doc(alias = "SDL_JoystickConnected")]
    pub fn connected(&self) -> bool {
        unsafe { sys::joystick::SDL_JoystickConnected(self.raw) }
    }

    #[doc(alias = "SDL_GetJoystickID")]
    pub fn id(&self) -> u32 {
        let result = unsafe { sys::joystick::SDL_GetJoystickID(self.raw) };

        if result == 0 {
            // Should only fail if the joystick is NULL.
            panic!("{}", get_error())
        } else {
            u32::from(result)
        }
    }

    /// Retrieve the joystick's GUID
    #[doc(alias = "SDL_GetJoystickGUID")]
    pub fn guid(&self) -> Guid {
        let raw = unsafe { sys::joystick::SDL_GetJoystickGUID(self.raw) };

        let guid = Guid { raw };

        if guid.is_zero() {
            // Should only fail if the joystick is NULL.
            panic!("{}", get_error())
        } else {
            guid
        }
    }

    /// Retrieve the battery level of this joystick
    /// This method doesn't match the name of the SDL API since we have PowerLevel + percentage in
    /// a PowerInfo struct.
    #[doc(alias = "SDL_GetJoystickPowerLevel")]
    pub fn power_info(&self) -> Result<PowerInfo, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        clear_error();

        let mut power_pct: core::ffi::c_int = 0;
        let result = unsafe { sys::joystick::SDL_GetJoystickPowerInfo(self.raw, &mut power_pct) };

        let state = PowerLevel::from_ll(result);

        if result != SDL_POWERSTATE_UNKNOWN {
            Ok(PowerInfo {
                state,
                percentage: power_pct,
            })
        } else {
            let err = get_error();

            if err.is_empty() {
                Ok(PowerInfo {
                    state,
                    percentage: power_pct,
                })
            } else {
                Err(SdlError(err))
            }
        }
    }

    /// Retrieve the number of axes for this joystick
    #[doc(alias = "SDL_GetNumJoystickAxes")]
    pub fn num_axes(&self) -> u32 {
        let result = unsafe { sys::joystick::SDL_GetNumJoystickAxes(self.raw) };

        if result < 0 {
            // Should only fail if the joystick is NULL.
            panic!("{}", get_error())
        } else {
            result as u32
        }
    }

    /// Gets the position of the given `axis`.
    ///
    /// The function will fail if the joystick doesn't have the provided axis.
    #[doc(alias = "SDL_GetJoystickAxis")]
    pub fn axis(&self, axis: u32) -> Result<i16, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        // This interface is a bit messed up: 0 is a valid position
        // but can also mean that an error occured. As far as I can
        // tell the only way to know if an error happened is to see if
        // get_error() returns a non-empty string.
        clear_error();

        let axis = validate_int(axis, "axis")?;
        let pos = unsafe { sys::joystick::SDL_GetJoystickAxis(self.raw, axis) };

        if pos != 0 {
            Ok(pos)
        } else {
            let err = get_error();

            if err.is_empty() {
                Ok(pos)
            } else {
                Err(SdlError(err))
            }
        }
    }

    /// Retrieve the number of buttons for this joystick
    #[doc(alias = "SDL_GetNumJoystickButtons")]
    pub fn num_buttons(&self) -> u32 {
        let result = unsafe { sys::joystick::SDL_GetNumJoystickButtons(self.raw) };

        if result < 0 {
            // Should only fail if the joystick is NULL.
            panic!("{}", get_error())
        } else {
            result as u32
        }
    }

    /// Return `Ok(true)` if `button` is pressed.
    ///
    /// The function will fail if the joystick doesn't have the provided button.
    #[doc(alias = "SDL_GetJoystickButton")]
    pub fn button(&self, button: u32) -> Result<bool, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        // Same deal as axis, 0 can mean both unpressed or
        // error...
        clear_error();

        let button = validate_int(button, "button")?;
        let pressed = unsafe { sys::joystick::SDL_GetJoystickButton(self.raw, button) };

        match pressed {
            true => Ok(true),
            false => {
                let err = get_error();

                if err.is_empty() {
                    // Button is not pressed
                    Ok(false)
                } else {
                    Err(SdlError(err))
                }
            }
        }
    }

    /// Retrieve the number of balls for this joystick
    #[doc(alias = "SDL_GetNumJoystickHats")]
    pub fn num_hats(&self) -> u32 {
        let result = unsafe { sys::joystick::SDL_GetNumJoystickHats(self.raw) };

        if result < 0 {
            // Should only fail if the joystick is NULL.
            panic!("{}", get_error())
        } else {
            result as u32
        }
    }

    /// Return the position of `hat` for this joystick
    #[doc(alias = "SDL_GetJoystickHat")]
    pub fn hat(&self, hat: u32) -> Result<HatState, IntegerOrSdlError> {
        use crate::common::IntegerOrSdlError::*;
        // Guess what? This function as well uses 0 to report an error
        // but 0 is also a valid value (HatState::Centered). So we
        // have to use the same hack as `axis`...
        clear_error();

        let hat = validate_int(hat, "hat")?;
        let result = unsafe { sys::joystick::SDL_GetJoystickHat(self.raw, hat) };

        let state = HatState::from_raw(result as u8);

        if result != 0 {
            Ok(state)
        } else {
            let err = get_error();

            if err.is_empty() {
                Ok(state)
            } else {
                Err(SdlError(err))
            }
        }
    }

    /// Set the rumble motors to their specified intensities, if supported.
    /// Automatically resets back to zero after `duration_ms` milliseconds have passed.
    ///
    /// # Notes
    ///
    /// The value range for the intensities is 0 to 0xFFFF.
    ///
    /// Do *not* use `std::u32::MAX` or similar for `duration_ms` if you want
    /// the rumble effect to keep playing for a long time, as this results in
    /// the effect ending immediately after starting due to an overflow.
    /// Use some smaller, "huge enough" number instead.
    ///
    /// Returns false if the gamepad doesn't support rumble.
    #[doc(alias = "SDL_RumbleJoystick")]
    pub fn set_rumble(
        &mut self,
        low_frequency_rumble: u16,
        high_frequency_rumble: u16,
        duration_ms: u32,
    ) -> bool {
        unsafe {
            sys::joystick::SDL_RumbleJoystick(
                self.raw,
                low_frequency_rumble,
                high_frequency_rumble,
                duration_ms,
            )
        }
    }

    /// Start a rumble effect in the joystick's triggers.
    #[doc(alias = "SDL_RumbleJoystickTriggers")]
    pub fn set_rumble_triggers(
        &mut self,
        left_rumble: u16,
        right_rumble: u16,
        duration_ms: u32,
    ) -> Result<(), IntegerOrSdlError> {
        let result = unsafe {
            sys::joystick::SDL_RumbleJoystickTriggers(
                self.raw,
                left_rumble,
                right_rumble,
                duration_ms,
            )
        };

        if !result {
            Err(IntegerOrSdlError::SdlError(get_error()))
        } else {
            Ok(())
        }
    }

    /// Query whether a joystick has an LED.
    #[doc(alias = "SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN")]
    pub unsafe fn has_led(&self) -> bool {
        let props = unsafe { sys::joystick::SDL_GetJoystickProperties(self.raw) };
        sys::properties::SDL_GetBooleanProperty(
            props,
            sys::joystick::SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN,
            false,
        )
    }

    /// Query whether a joystick has rumble support.
    #[doc(alias = "SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN")]
    pub unsafe fn has_rumble(&self) -> bool {
        let props = unsafe { sys::joystick::SDL_GetJoystickProperties(self.raw) };
        sys::properties::SDL_GetBooleanProperty(
            props,
            sys::joystick::SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN,
            false,
        )
    }

    /// Query whether a joystick has rumble support on triggers.
    #[doc(alias = "SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN")]
    pub unsafe fn has_rumble_triggers(&self) -> bool {
        let props = unsafe { sys::joystick::SDL_GetJoystickProperties(self.raw) };
        sys::properties::SDL_GetBooleanProperty(
            props,
            sys::joystick::SDL_PROP_JOYSTICK_CAP_TRIGGER_RUMBLE_BOOLEAN,
            false,
        )
    }

    /// Update a joystick's LED color.
    #[doc(alias = "SDL_SetJoystickLED")]
    pub fn set_led(&mut self, red: u8, green: u8, blue: u8) -> Result<(), IntegerOrSdlError> {
        let result = unsafe { sys::joystick::SDL_SetJoystickLED(self.raw, red, green, blue) };

        if !result {
            Err(IntegerOrSdlError::SdlError(get_error()))
        } else {
            Ok(())
        }
    }

    /// Send a joystick specific effect packet.
    #[doc(alias = "SDL_SendJoystickEffect")]
    pub fn send_effect(&mut self, data: &[u8]) -> Result<(), IntegerOrSdlError> {
        let result = unsafe {
            sys::joystick::SDL_SendJoystickEffect(
                self.raw,
                data.as_ptr() as *const libc::c_void,
                data.len() as i32,
            )
        };

        if !result {
            Err(IntegerOrSdlError::SdlError(get_error()))
        } else {
            Ok(())
        }
    }

    /// Check if a joystick is virtual
    #[doc(alias = "SDL_IsJoystickVirtual")]
    pub fn is_virtual(&self) -> bool {
        let id = sys::joystick::SDL_JoystickID(self.id());
        unsafe { sys::joystick::SDL_IsJoystickVirtual(id) }
    }

    /// Set a virtual axis state
    #[doc(alias = "SDL_SetJoystickVirtualAxis")]
    pub fn set_virtual_axis(&self, axis: u32, state: i16) -> Result<(), IntegerOrSdlError> {
        let axis = validate_int(axis, "axis")?;

        if unsafe { sys::joystick::SDL_SetJoystickVirtualAxis(self.raw, axis, state) } {
            Ok(())
        } else {
            Err(IntegerOrSdlError::SdlError(get_error()))
        }
    }

    /// Set a virtual button state
    #[doc(alias = "SDL_SetJoystickVirtualButton")]
    pub fn set_virtual_button(&self, button: u32, state: bool) -> Result<(), IntegerOrSdlError> {
        let button = validate_int(button, "button")?;

        if unsafe { sys::joystick::SDL_SetJoystickVirtualButton(self.raw, button, state) } {
            Ok(())
        } else {
            Err(IntegerOrSdlError::SdlError(get_error()))
        }
    }

    /// Set a virtual hat state
    #[doc(alias = "SDL_SetJoystickVirtualHat")]
    pub fn set_virtual_hat(&self, hat: u32, state: HatState) -> Result<(), IntegerOrSdlError> {
        let hat = validate_int(hat, "hat")?;

        if unsafe { sys::joystick::SDL_SetJoystickVirtualHat(self.raw, hat, state.to_raw()) } {
            Ok(())
        } else {
            Err(IntegerOrSdlError::SdlError(get_error()))
        }
    }
}

impl Drop for Joystick {
    #[doc(alias = "SDL_CloseJoystick")]
    fn drop(&mut self) {
        if self.connected() {
            unsafe { sys::joystick::SDL_CloseJoystick(self.raw) }
        }
    }
}

/// This is represented in SDL2 as a bitfield but obviously not all
/// combinations make sense: 5 for instance would mean up and down at
/// the same time... To simplify things I turn it into an enum which
/// is how the SDL2 docs present it anyway (using macros).
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum HatState {
    Centered = 0,
    Up = 0x01,
    Right = 0x02,
    Down = 0x04,
    Left = 0x08,
    RightUp = 0x02 | 0x01,
    RightDown = 0x02 | 0x04,
    LeftUp = 0x08 | 0x01,
    LeftDown = 0x08 | 0x04,
}

impl HatState {
    pub fn from_raw(raw: u8) -> HatState {
        match raw {
            0 => HatState::Centered,
            1 => HatState::Up,
            2 => HatState::Right,
            4 => HatState::Down,
            8 => HatState::Left,
            3 => HatState::RightUp,
            6 => HatState::RightDown,
            9 => HatState::LeftUp,
            12 => HatState::LeftDown,

            // The Xinput driver on Windows can report hat states on certain hardware that don't
            // make any sense from a gameplay perspective, and so aren't worth putting in the
            // HatState enumeration.
            _ => HatState::Centered,
        }
    }

    pub fn to_raw(self) -> u8 {
        match self {
            HatState::Centered => 0,
            HatState::Up => 1,
            HatState::Right => 2,
            HatState::Down => 4,
            HatState::Left => 8,
            HatState::RightUp => 3,
            HatState::RightDown => 6,
            HatState::LeftUp => 9,
            HatState::LeftDown => 12,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(i32)]
pub enum ConnectionState {
    Invalid = sys::joystick::SDL_JoystickConnectionState::INVALID.0,
    Unknown = sys::joystick::SDL_JoystickConnectionState::UNKNOWN.0,
    Wired = sys::joystick::SDL_JoystickConnectionState::WIRED.0,
    Wireless = sys::joystick::SDL_JoystickConnectionState::WIRELESS.0,
}

impl ConnectionState {
    pub fn from_ll(bitflags: sys::joystick::SDL_JoystickConnectionState) -> ConnectionState {
        match bitflags {
            sys::joystick::SDL_JoystickConnectionState::UNKNOWN => ConnectionState::Unknown,
            sys::joystick::SDL_JoystickConnectionState::WIRED => ConnectionState::Wired,
            sys::joystick::SDL_JoystickConnectionState::WIRELESS => ConnectionState::Wireless,
            _ => ConnectionState::Invalid,
        }
    }

    pub fn to_ll(self) -> sys::joystick::SDL_JoystickConnectionState {
        match self {
            ConnectionState::Invalid => sys::joystick::SDL_JoystickConnectionState::INVALID,
            ConnectionState::Unknown => sys::joystick::SDL_JoystickConnectionState::UNKNOWN,
            ConnectionState::Wired => sys::joystick::SDL_JoystickConnectionState::WIRED,
            ConnectionState::Wireless => sys::joystick::SDL_JoystickConnectionState::WIRELESS,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(i32)]
pub enum JoystickType {
    Unknown = sys::joystick::SDL_JoystickType::UNKNOWN.0,
    Gamepad = sys::joystick::SDL_JoystickType::GAMEPAD.0,
    Wheel = sys::joystick::SDL_JoystickType::WHEEL.0,
    ArcadeStick = sys::joystick::SDL_JoystickType::ARCADE_STICK.0,
    FlightStick = sys::joystick::SDL_JoystickType::FLIGHT_STICK.0,
    DancePad = sys::joystick::SDL_JoystickType::DANCE_PAD.0,
    Guitar = sys::joystick::SDL_JoystickType::GUITAR.0,
    DrumKit = sys::joystick::SDL_JoystickType::DRUM_KIT.0,
    ArcadePad = sys::joystick::SDL_JoystickType::ARCADE_PAD.0,
    Throttle = sys::joystick::SDL_JoystickType::THROTTLE.0,
}

impl JoystickType {
    pub fn from_ll(kind: sys::joystick::SDL_JoystickType) -> JoystickType {
        match kind {
            sys::joystick::SDL_JoystickType::GAMEPAD => JoystickType::Gamepad,
            sys::joystick::SDL_JoystickType::WHEEL => JoystickType::Wheel,
            sys::joystick::SDL_JoystickType::ARCADE_STICK => JoystickType::ArcadeStick,
            sys::joystick::SDL_JoystickType::FLIGHT_STICK => JoystickType::FlightStick,
            sys::joystick::SDL_JoystickType::DANCE_PAD => JoystickType::DancePad,
            sys::joystick::SDL_JoystickType::GUITAR => JoystickType::Guitar,
            sys::joystick::SDL_JoystickType::DRUM_KIT => JoystickType::DrumKit,
            sys::joystick::SDL_JoystickType::ARCADE_PAD => JoystickType::ArcadePad,
            sys::joystick::SDL_JoystickType::THROTTLE => JoystickType::Throttle,
            _ => JoystickType::Unknown,
        }
    }

    pub fn to_ll(self) -> sys::joystick::SDL_JoystickType {
        match self {
            JoystickType::Unknown => sys::joystick::SDL_JoystickType::UNKNOWN,
            JoystickType::Gamepad => sys::joystick::SDL_JoystickType::GAMEPAD,
            JoystickType::Wheel => sys::joystick::SDL_JoystickType::WHEEL,
            JoystickType::ArcadeStick => sys::joystick::SDL_JoystickType::ARCADE_STICK,
            JoystickType::FlightStick => sys::joystick::SDL_JoystickType::FLIGHT_STICK,
            JoystickType::DancePad => sys::joystick::SDL_JoystickType::DANCE_PAD,
            JoystickType::Guitar => sys::joystick::SDL_JoystickType::GUITAR,
            JoystickType::DrumKit => sys::joystick::SDL_JoystickType::DRUM_KIT,
            JoystickType::ArcadePad => sys::joystick::SDL_JoystickType::ARCADE_PAD,
            JoystickType::Throttle => sys::joystick::SDL_JoystickType::THROTTLE,
        }
    }
}

/// Convert C string `c_str` to a String. Return an empty string if
/// `c_str` is NULL.
fn c_str_to_string(c_str: *const c_char) -> String {
    if c_str.is_null() {
        String::new()
    } else {
        let bytes = unsafe { CStr::from_ptr(c_str as *const _).to_bytes() };

        String::from_utf8_lossy(bytes).to_string()
    }
}

/// Convert a string slice into a `CString`, truncating at the first interior
/// NUL byte. Joystick names cannot contain NUL, so silently dropping the tail
/// is preferable to panicking on user-supplied input.
fn string_to_c_str(string: &str) -> CString {
    let end = string.bytes().position(|b| b == 0).unwrap_or(string.len());
    CString::new(&string.as_bytes()[..end]).expect("interior NULs stripped above")
}

/// Represents the lifetime of a virtual joystick connection
pub struct VirtualJoystickConnection {
    inner: Joystick,
}

impl VirtualJoystickConnection {
    /// Exposes the instance ID of the attached virtual joystick so that it can be opened
    pub fn id(&self) -> JoystickId {
        sys::joystick::SDL_JoystickID(self.inner.id())
    }
}

/// When a VirtualJoystickConnection is dropped, the underlying virtual device will be disconnected.
/// For any existing virtual joysticks relying on that connection, it will be analogous to a physical
/// piece of hardware being unplugged while being used by a non-virtual joystick.
impl Drop for VirtualJoystickConnection {
    #[doc(alias = "SDL_DetachVirtualJoystick")]
    fn drop(&mut self) {
        let id = sys::joystick::SDL_JoystickID(self.inner.id());
        unsafe { sys::joystick::SDL_DetachVirtualJoystick(id) };
    }
}

/// As of SDL3, Virtual Devices must be initialized using a description.
pub struct VirtualJoystickDescription {
    name: CString,
    joystick_type: JoystickType,
    num_axes: u16,
    num_buttons: u16,
    num_hats: u16,

    // Virtual Joysticks require specification as to what each of its buttons and axes are actually
    // mapped to.
    axis_mask: u32,
    button_mask: u32,
}

impl Default for VirtualJoystickDescription {
    fn default() -> Self {
        Self::new()
    }
}

impl VirtualJoystickDescription {
    pub fn new() -> Self {
        Self {
            name: string_to_c_str("Unnamed Virtual Joystick"),
            joystick_type: JoystickType::Unknown,
            num_axes: 0,
            num_buttons: 0,
            num_hats: 0,
            axis_mask: 0,
            button_mask: 0,
        }
    }

    /// Set the joystick name. The name is truncated at the first interior NUL
    /// byte, since C strings cannot contain NUL.
    pub fn name(self, name: &str) -> Self {
        let mut desc = self;
        desc.name = string_to_c_str(name);
        desc
    }

    /// Set the joystick type
    pub fn joystick_type(self, joystick_type: JoystickType) -> Self {
        let mut desc = self;
        desc.joystick_type = joystick_type;
        desc
    }

    /// Set the number of hats
    pub fn num_hats(self, num_hats: u16) -> Self {
        let mut desc = self;
        desc.num_hats = num_hats;
        desc
    }

    /// Specifies that a given axis can be controlled by the virtual joystick
    pub fn with_axis(self, axis: crate::gamepad::Axis) -> Self {
        let mut desc = self;
        let axis_code = axis.to_ll().0 as u16;

        // num_axes must be equal to at least 1 + the highest enum value of axes added to the
        // joystick
        if axis_code >= desc.num_axes {
            desc.num_axes = axis_code + 1;
        }

        desc.axis_mask |= 1 << axis_code;
        desc
    }

    /// Specifies that a given button can be controlled by the virtual joystick
    pub fn with_button(self, button: crate::gamepad::Button) -> Self {
        let mut desc = self;
        let button_code = button.to_ll().0 as u16;

        // num_buttons must be equal to at least 1 + the highest enum value of buttons added to the
        // joystick
        if button_code >= desc.num_buttons {
            desc.num_buttons = button_code + 1;
        }

        desc.button_mask |= 1 << button_code;
        desc
    }

    /// Specifies that a given list of axes can be controlled by the virtual joystick
    pub fn with_axes<T>(self, axes: T) -> Self
    where
        T: IntoIterator<Item = crate::gamepad::Axis>,
    {
        let mut desc = self;
        for axis in axes {
            desc = desc.with_axis(axis);
        }
        desc
    }

    /// Specifies that a given list of buttons can be controlled by the virtual joystick
    pub fn with_buttons<T>(self, buttons: T) -> Self
    where
        T: IntoIterator<Item = crate::gamepad::Button>,
    {
        let mut desc = self;
        for button in buttons {
            desc = desc.with_button(button);
        }
        desc
    }
}