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
//! Human Interface Device service.
//!
//! The HID service provides read access to user input such as [button presses](Hid::keys_down), [touch screen presses](Hid::touch_position),
//! and [circle pad information](Hid::circlepad_position). It also provides information from the [volume slider](Hid::volume_slider()),
//! the [accelerometer](Hid::accelerometer_vector()), and the [gyroscope](Hid::gyroscope_rate()).
#![doc(alias = "input")]
#![doc(alias = "controller")]
#![doc(alias = "gamepad")]

use std::sync::Mutex;

use crate::error::ResultCode;
use crate::services::ServiceReference;

use bitflags::bitflags;

static HID_ACTIVE: Mutex<()> = Mutex::new(());

bitflags! {
    /// A set of flags corresponding to the button and directional pad inputs present on the 3DS.
    #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
    pub struct KeyPad: u32 {
        /// A button.
        const A             = ctru_sys::KEY_A;
        /// B button.
        const B             = ctru_sys::KEY_B;
        /// Select button.
        const SELECT        = ctru_sys::KEY_SELECT;
        /// Start button.
        const START         = ctru_sys::KEY_START;
        /// D-Pad Right.
        const DPAD_RIGHT        = ctru_sys::KEY_DRIGHT;
        /// D-Pad Left.
        const DPAD_LEFT         = ctru_sys::KEY_DLEFT;
        /// D-Pad Up.
        const DPAD_UP           = ctru_sys::KEY_DUP;
        /// D-Pad Down.
        const DPAD_DOWN         = ctru_sys::KEY_DDOWN;
        /// R button.
        const R             = ctru_sys::KEY_R;
        /// L button.
        const L             = ctru_sys::KEY_L;
        /// X button.
        const X             = ctru_sys::KEY_X;
        /// Y button.
        const Y             = ctru_sys::KEY_Y;
        /// ZL button.
        const ZL            = ctru_sys::KEY_ZL;
        /// ZR button.
        const ZR            = ctru_sys::KEY_ZR;
        /// Touchscreen.
        const TOUCH         = ctru_sys::KEY_TOUCH;
        /// C-Stick Right.
        const CSTICK_RIGHT  = ctru_sys::KEY_CSTICK_RIGHT;
        /// C-Stick Left.
        const CSTICK_LEFT   = ctru_sys::KEY_CSTICK_LEFT;
        /// C-Stick Up.
        const CSTICK_UP     = ctru_sys::KEY_CSTICK_UP;
        /// C-Stick Down.
        const CSTICK_DOWN   = ctru_sys::KEY_CSTICK_DOWN;
        /// CirclePad Right.
        const CPAD_RIGHT    = ctru_sys::KEY_CPAD_RIGHT;
        /// CirclePad Left.
        const CPAD_LEFT     = ctru_sys::KEY_CPAD_LEFT;
        /// CirclePad Up.
        const CPAD_UP       = ctru_sys::KEY_CPAD_UP;
        /// CirclePad Down.
        const CPAD_DOWN     = ctru_sys::KEY_CPAD_DOWN;

        // Convenience catch-all for the D-Pad and the CirclePad

        /// Direction Up (either D-Pad or CirclePad).
        const UP    = KeyPad::DPAD_UP.bits()    | KeyPad::CPAD_UP.bits();
        /// Direction Down (either D-Pad or CirclePad).
        const DOWN  = KeyPad::DPAD_DOWN.bits()  | KeyPad::CPAD_DOWN.bits();
        /// Direction Left (either D-Pad or CirclePad).
        const LEFT  = KeyPad::DPAD_LEFT.bits()  | KeyPad::CPAD_LEFT.bits();
        /// Direction Right (either D-Pad or CirclePad).
        const RIGHT = KeyPad::DPAD_RIGHT.bits() | KeyPad::CPAD_RIGHT.bits();
    }
}

/// Error enum for generic errors within the [`Hid`] service.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// An attempt was made to access the accelerometer while disabled.
    UnavailableAccelerometer,
    /// An attempt was made to access the gyroscope while disabled.
    UnavailableGyroscope,
}

/// Representation of the acceleration vector read by the accelerometer.
///
/// Have a look at [`Hid::set_accelerometer()`] for more information.
#[allow(missing_docs)]
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
pub struct Acceleration {
    x: i16,
    y: i16,
    z: i16,
}

/// Representation of the angular rate read by the gyroscope.
///
/// Have a look at [`Hid::set_gyroscope()`] for more information.
#[allow(missing_docs)]
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq)]
pub struct AngularRate {
    roll: i16,
    pitch: i16,
    yaw: i16,
}

/// Handle to the HID service.
pub struct Hid {
    active_accelerometer: bool,
    active_gyroscope: bool,
    _service_handler: ServiceReference,
}

impl Hid {
    /// Initialize a new service handle.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service was unable to be initialized.
    /// Since this service requires no special or elevated permissions, errors are rare in practice.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    ///
    /// let hid = Hid::new()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidInit")]
    pub fn new() -> crate::Result<Hid> {
        let handler = ServiceReference::new(
            &HID_ACTIVE,
            || {
                ResultCode(unsafe { ctru_sys::hidInit() })?;

                Ok(())
            },
            || unsafe {
                let _ = ctru_sys::HIDUSER_DisableGyroscope();
                let _ = ctru_sys::HIDUSER_DisableAccelerometer();

                ctru_sys::hidExit();
            },
        )?;

        Ok(Self {
            active_accelerometer: false,
            active_gyroscope: false,
            _service_handler: handler,
        })
    }

    /// Scan the HID service for all user input occurring on the current frame.
    ///
    /// This function should be called on every frame when polling
    /// for user input.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidScanInput")]
    pub fn scan_input(&mut self) {
        unsafe { ctru_sys::hidScanInput() };
    }

    /// Returns a bitflag struct representing which buttons have just been pressed
    /// on the current frame (and were not pressed on the previous frame).
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::{Hid, KeyPad};
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    ///
    /// if hid.keys_down().contains(KeyPad::A) {
    ///     println!("You have pressed the A button!")
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidKeysDown")]
    pub fn keys_down(&self) -> KeyPad {
        unsafe {
            let keys = ctru_sys::hidKeysDown();
            KeyPad::from_bits_truncate(keys)
        }
    }

    /// Returns a bitflag struct representing which buttons have been held down
    /// during the current frame.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::{Hid, KeyPad};
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    ///
    /// if hid.keys_held().contains(KeyPad::START) {
    ///     println!("You are holding the START button!")
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidKeysHeld")]
    pub fn keys_held(&self) -> KeyPad {
        unsafe {
            let keys = ctru_sys::hidKeysHeld();
            KeyPad::from_bits_truncate(keys)
        }
    }

    /// Returns a bitflag struct representing which buttons have just been released on
    /// the current frame.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::{Hid, KeyPad};
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    ///
    /// if hid.keys_held().contains(KeyPad::B) {
    ///     println!("You have released the B button!")
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidKeysUp")]
    pub fn keys_up(&self) -> KeyPad {
        unsafe {
            let keys = ctru_sys::hidKeysUp();
            KeyPad::from_bits_truncate(keys)
        }
    }

    /// Returns the current touch position in pixels (x, y).
    ///
    /// # Notes
    ///
    /// (0, 0) represents the top left corner of the screen.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    ///
    /// let (touch_x, touch_y) = hid.touch_position();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidTouchRead")]
    pub fn touch_position(&self) -> (u16, u16) {
        let mut res = ctru_sys::touchPosition { px: 0, py: 0 };

        unsafe {
            ctru_sys::hidTouchRead(&mut res);
        }

        (res.px, res.py)
    }

    /// Returns the current circle pad position in relative (x, y).
    ///
    /// # Notes
    ///
    /// (0, 0) represents the center of the circle pad.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    ///
    /// let (pad_x, pad_y) = hid.circlepad_position();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidCircleRead")]
    pub fn circlepad_position(&self) -> (i16, i16) {
        let mut res = ctru_sys::circlePosition { dx: 0, dy: 0 };

        unsafe {
            ctru_sys::hidCircleRead(&mut res);
        }

        (res.dx, res.dy)
    }

    /// Returns the current volume slider position (between 0 and 1).
    ///
    /// # Notes
    ///
    /// The [`ndsp`](crate::services::ndsp) service automatically uses the volume slider's position to handle audio mixing.
    /// As such this method should not be used to programmatically change the volume.
    ///
    /// Its purpose is only to inform the program of the volume slider's position (e.g. checking if the user has muted the audio).
    ///
    /// # Example
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// hid.scan_input();
    ///
    /// let volume = hid.volume_slider();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "HIDUSER_GetSoundVolume")]
    pub fn volume_slider(&self) -> f32 {
        let mut slider = 0;

        unsafe {
            let _ = ctru_sys::HIDUSER_GetSoundVolume(&mut slider);
        }

        (slider as f32) / 63.
    }

    /// Activate/deactivate the console's acceleration sensor.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// // The accelerometer will start to register movements.
    /// hid.set_accelerometer(true).unwrap();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "HIDUSER_EnableAccelerometer")]
    #[doc(alias = "HIDUSER_DisableAccelerometer")]
    pub fn set_accelerometer(&mut self, enabled: bool) -> crate::Result<()> {
        if enabled {
            ResultCode(unsafe { ctru_sys::HIDUSER_EnableAccelerometer() })?;
        } else {
            ResultCode(unsafe { ctru_sys::HIDUSER_DisableAccelerometer() })?;
        }

        self.active_accelerometer = enabled;

        Ok(())
    }

    /// Activate/deactivate the console's gyroscopic sensor.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// // The gyroscope will start to register positions.
    /// hid.set_gyroscope(true).unwrap();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "HIDUSER_EnableGyroscope")]
    #[doc(alias = "HIDUSER_DisableGyroscope")]
    pub fn set_gyroscope(&mut self, enabled: bool) -> crate::Result<()> {
        if enabled {
            ResultCode(unsafe { ctru_sys::HIDUSER_EnableGyroscope() })?;
        } else {
            ResultCode(unsafe { ctru_sys::HIDUSER_DisableGyroscope() })?;
        }

        self.active_gyroscope = enabled;

        Ok(())
    }

    /// Returns the acceleration vector (x, y, z) registered by the accelerometer.
    ///
    /// # Errors
    ///
    /// This function will return an error if the accelerometer was not previously enabled.
    /// Have a look at [`Hid::set_accelerometer()`] to enable the accelerometer.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// // The accelerometer will start to register movements.
    /// hid.set_accelerometer(true).unwrap();
    ///
    /// // It's necessary to run `scan_input()` to update the accelerometer's readings.
    /// hid.scan_input();
    ///
    /// // This call fails if the accelerometer was not previously enabled.
    /// let acceleration = hid.accelerometer_vector()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidAccelRead")]
    pub fn accelerometer_vector(&self) -> Result<Acceleration, Error> {
        if !self.active_accelerometer {
            return Err(Error::UnavailableAccelerometer);
        }

        let mut res = ctru_sys::accelVector { x: 0, y: 0, z: 0 };

        unsafe {
            ctru_sys::hidAccelRead(&mut res);
        }

        Ok(Acceleration {
            x: res.x,
            y: res.y,
            z: res.z,
        })
    }

    /// Returns the angular rate registered by the gyroscope.
    ///
    /// # Errors
    ///
    /// This function returns an error if the gyroscope was not previously enabled.
    /// Have a look at [`Hid::set_gyroscope()`].
    ///
    /// # Example
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::hid::Hid;
    /// let mut hid = Hid::new()?;
    ///
    /// // The gyroscope will start to register positions.
    ///  hid.set_gyroscope(true).unwrap();
    ///
    /// // It's necessary to run `scan_input()` to update the gyroscope's readings.
    /// hid.scan_input();
    ///
    /// // This call fails if the gyroscope was not previously enabled.
    /// let angular_rate = hid.gyroscope_rate()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "hidGyroRead")]
    pub fn gyroscope_rate(&self) -> Result<AngularRate, Error> {
        if !self.active_gyroscope {
            return Err(Error::UnavailableGyroscope);
        }

        let mut res = ctru_sys::angularRate { x: 0, y: 0, z: 0 };

        unsafe {
            ctru_sys::hidGyroRead(&mut res);
        }

        Ok(AngularRate {
            roll: res.x,
            pitch: res.y,
            yaw: res.z,
        })
    }
}

impl From<Acceleration> for (i16, i16, i16) {
    fn from(value: Acceleration) -> (i16, i16, i16) {
        (value.x, value.y, value.z)
    }
}

impl From<AngularRate> for (i16, i16, i16) {
    fn from(value: AngularRate) -> (i16, i16, i16) {
        (value.roll, value.pitch, value.yaw)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnavailableAccelerometer => write!(f, "tried using accelerometer while disabled"),
            Self::UnavailableGyroscope => write!(f, "tried using gyroscope while disabled"),
        }
    }
}

impl std::error::Error for Error {}