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
//! LED manipulation module
pub mod anims;
use crate::Device;

/// A behavioral construct for effects and animations on the controller's LEDs.
///
/// This abstraction enables operations on the LEDs to be accumulated
/// in an additive fashion, and to easily change over time.
pub trait LedAnimation {
    /// Reset the effect's state. This usually means a rewind of the animation.
    /// The state of the animation
    /// should consider `ticks` as the initial "timestamp".
    ///
    /// In stateless animations,
    /// this function serves no purpose and should be a no-op.
    #[allow(unused)]
    fn reset(&mut self, ticks: u64) {}

    /// Update the state of the animation,
    /// applying the intended effects on the given report.
    ///
    /// `ticks` is expected to be a steadily increasing number
    /// representing how much time has passed since the beginning
    /// of a program or subroutine to which the animation applies.
    /// 
    /// Returns `Ended` if the animation has ended
    /// and no longer wishes to request for LED activations.
    fn update(&mut self, ticks: u64, report: &mut LedReport) -> AnimationEvent;
}

/// Identifier for a quadrant of the LED ring.
///
/// Quadrants are not fully disjoint:
/// they share an LED at the extremities.
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
pub enum Quadrant {
    BottomLeft = 0,
    TopLeft = 1,
    TopRight = 2,
    BottomRight = 3,
}

impl Quadrant {
    pub fn from_u8(quadrant: u8) -> Option<Self> {
        match quadrant {
            0 => Some(Quadrant::BottomLeft),
            1 => Some(Quadrant::TopLeft),
            2 => Some(Quadrant::TopRight),
            3 => Some(Quadrant::BottomRight),
            _ => None,
        }
    }
}

/// An arbitrary selection of leds in the ring.
#[derive(Debug, Default, Copy, Clone, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct LedSelection([bool; 24]);

impl LedSelection {
    pub fn new() -> Self {
        Self::default()
    }

    /// Select a single LED by index, from 0 to 23.
    pub fn single(index: u8) -> Self {
        let mut x = [false; 24];
        x[index as usize] = true;
        LedSelection(x)
    }

    /// Select a single LED by an arbitrary range of indices.
    pub fn range<R>(range: R) -> Self
    where
        R: IntoIterator<Item = u8>,
    {
        let mut x = [false; 24];
        for i in range {
            x[i as usize] = true;
        }
        LedSelection(x)
    }

    /// Select a diagonal quadrant of LEDs, from 0 to 3.
    pub fn quadrant(quadrant: u8) -> Self {
        assert!(quadrant < 4);
        let mut x = [false; 24];
        let base = quadrant as usize * 6;
        if quadrant == 3 {
            x[base..=base + 5].fill(true);
            x[0] = true;
        } else {
            x[base..=base + 6].fill(true);
        }
        LedSelection(x)
    }

    /// Select a span of LEDS comprising the center LED
    /// plus the adjacent LEDs at the given radius.
    pub fn span(center: u8, radius: u8) -> Self {
        let mut x = [false; 24];
        let center = center as usize;
        let radius = radius as usize;
        for i in 0..radius {
            if let Some(l) = x.get_mut((center + i).rem_euclid(24)) {
                *l = true;
            }
        }
        for i in 1..radius {
            if let Some(l) = x.get_mut((center as i32 - i as i32).rem_euclid(24) as usize) {
                *l = true;
            }
        }
        LedSelection(x)
    }

    /// Combine (union) with another selection.
    pub fn or(self, other: LedSelection) -> Self {
        let mut x = [false; 24];
        for (out, (v1, v2)) in x.iter_mut().zip(self.0.iter().zip(other.0.iter())) {
            *out = *v1 || *v2;
        }
        LedSelection(x)
    }

    /// Intersect (filter) with another selection.
    pub fn and(self, other: LedSelection) -> Self {
        let mut x = [false; 24];
        for (out, (v1, v2)) in x.iter_mut().zip(self.0.iter().zip(other.0.iter())) {
            *out = *v1 && *v2;
        }
        LedSelection(x)
    }
    
    /// Select all LEDs.
    pub const ALL: LedSelection = LedSelection([true; 24]);

    /// Select no LED.
    pub const NONE: LedSelection = LedSelection([false; 24]);
}

/// Structure representing a report for LED activation on the controller.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct LedReport([u8; 28]);

/// By default, an LED report will turn off all LEDs.
impl Default for LedReport {
    #[inline]
    fn default() -> Self {
        let mut arr = [0; 28];
        arr[0] = 2;
        arr[1] = 25;
        LedReport(arr)
    }
}

impl LedReport {
    /// Create a new LED report.
    ///
    /// By default, an LED report will turn off all LEDs.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new LED report filled with the given intensity value.
    #[inline]
    pub fn filled(value: u8) -> Self {
        let mut x = Self::default();
        x.fill(value);
        x
    }

    /// Turn all ring of LEDs off.
    #[inline]
    pub fn clear(&mut self) {
        self.fill(0)
    }

    /// Set all LEDs in the ring to the given value.
    #[inline]
    pub fn fill(&mut self, value: u8) {
        (&mut self.0[3..]).fill(value);
    }

    /// Set the Fuji LED to a value.
    #[inline]
    pub fn set_fuji(&mut self, value: u8) {
        self.0[2] = value;
    }

    /// Set a LED in the ring to a value.
    #[inline]
    pub fn set(&mut self, led: u8, value: u8) {
        self.0[3 + led as usize] = value;
    }

    /// Set a selection of LEDs in the ring to a value.
    #[inline]
    pub fn set_selection(&mut self, selection: LedSelection, value: u8) {
        for (led, sel) in std::iter::Iterator::zip(self.0.iter_mut().skip(3), selection.0.iter()) {
            if *sel {
                *led = value;
            }
        }
    }

    /// Invert the value of the LED in the ring.
    #[inline]
    pub fn invert(&mut self, led: u8) {
        let led = led as usize;
        self.0[3 + led] = !self.0[3 + led];
    }

    /// Invert the values of a selection of the LED in the ring.
    #[inline]
    pub fn invert_selection(&mut self, selection: LedSelection) {
        for (led, sel) in std::iter::Iterator::zip(self.0.iter_mut().skip(3), selection.0.iter()) {
            if *sel {
                *led = !*led;
            }
        }
    }

    /// Add an intensity to a LED in the ring.
    ///
    /// The addition is relative to the receiving report value,
    /// and not the current state of the LEDs in the controller.
    /// Values are automatically clamped to the limits of the device.
    #[inline]
    pub fn saturating_add(&mut self, led: u8, value_delta: i16) {
        let led = led as usize;
        let current = self.0[3 + led];
        let out = (i16::from(current) + value_delta).clamp(0, 255);
        self.0[3 + led] = out as u8;
    }

    /// Add an intensity to a selection of LEDs in the ring.
    ///
    /// The addition is relative to the receiving report value,
    /// and not the current state of the LEDs in the controller.
    /// Values are automatically clamped to the limits of the device.
    #[inline]
    pub fn saturating_add_selection(&mut self, selection: LedSelection, value_delta: i16) {
        selection
            .0
            .iter()
            .enumerate()
            .filter_map(|(i, sel)| if *sel { Some(i) } else { None })
            .for_each(|i| self.saturating_add(i as u8, value_delta))
    }

    /// Send this report as an HID message to the given device.
    ///  
    /// **Safety:** although not memory unsafe, the operation must be done
    /// on a readily available device handle for the Atari Classic Controller.
    /// The effects on any other device are unknown and potentially dangerous.
    #[inline]
    pub fn send<D>(&self, mut device: D) -> Result<(), D::Error>
    where
        D: Device,
    {
        device.write(&self.0).map(|_| ())
    }
}

impl AsRef<[u8]> for LedReport {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// Feedback from an LED animation regarding its current state after an update.
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)]
pub enum AnimationEvent {
    /// the animation is running
    Running,
    /// the animation is ended and should receive no more update events
    Ended,
}

impl Default for AnimationEvent {
    #[inline]
    fn default() -> Self {
        AnimationEvent::Running
    }
}