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 crate::sys;
use crate::ColorPercent;
use crate::DeviceType;
use crate::KeyName;
pub use crate::TargetDevice;
use crate::SDK_LOCK;
use std::ffi::CString;
use std::os::raw::c_int;
use std::sync::MutexGuard;
use std::sync::TryLockError;
use std::time::Duration;

/// Entry to Api.
///
/// This serves as proof of initalization and prevents the API from being used by other threads.
pub struct Sdk(MutexGuard<'static, ()>);

impl Sdk {
    /// Create a new sdk instance with no name.
    ///
    /// # Returns
    /// Returns None if the sdk could not be initialized.
    pub fn new() -> Option<Self> {
        let guard = match SDK_LOCK.try_lock() {
            Ok(guard) => guard,
            Err(TryLockError::WouldBlock) => return None,
            Err(TryLockError::Poisoned(e)) => e.into_inner(),
        };

        let init = unsafe { sys::LogiLedInit() };
        if !init {
            return None;
        }

        Some(Sdk(guard))
    }

    /// Create a new sdk instance with a name, where the name is the name of the application using the sdk.
    ///
    /// # Panics
    /// Panics if the name contains interior NULs.
    ///
    /// # Returns
    /// Returns None if the sdk could not be initialized.
    pub fn new_with_name(name: &str) -> Option<Self> {
        let guard = match SDK_LOCK.try_lock() {
            Ok(guard) => guard,
            Err(TryLockError::WouldBlock) => return None,
            Err(TryLockError::Poisoned(e)) => e.into_inner(),
        };

        let name = CString::new(name).expect("name contains interior NUL");
        let init = unsafe { sys::LogiLedInitWithName(name.as_ptr()) };
        if !init {
            return None;
        }

        Some(Sdk(guard))
    }

    /// Returns the sdk version.
    ///
    /// # Returns
    /// Returns a tuple of the major, minor and build numbers if successful.
    /// Returns None if the version could not be found.
    pub fn get_version(&self) -> Option<(u32, u32, u32)> {
        let mut major = 0;
        let mut minor = 0;
        let mut build = 0;

        let valid = unsafe { sys::LogiLedGetSdkVersion(&mut major, &mut minor, &mut build) };
        if !valid {
            return None;
        }

        // i32 -> u32, transmute
        Some((major as u32, minor as u32, build as u32))
    }

    /// Selects the target devices.
    ///
    /// # Returns
    /// Returns true if the target devices were selected.
    pub fn set_target(&self, target_device: TargetDevice) -> bool {
        // u32 -> i32, transmute
        unsafe { sys::LogiLedSetTargetDevice(target_device.bits() as c_int) }
    }

    /// Sets the lighting.
    ///
    /// # Returns
    /// Returns true if successful.
    pub fn set_lighting(&self, color: ColorPercent) -> bool {
        unsafe { sys::LogiLedSetLighting(color.r.into(), color.g.into(), color.b.into()) }
    }

    /// Set the lighting for a keyboard key by key name.
    ///
    /// # Returns
    /// Returns true if successful.
    pub fn set_lighting_for_key_with_name(&self, key: KeyName, color: ColorPercent) -> bool {
        unsafe {
            sys::LogiLedSetLightingForKeyWithKeyName(
                key,
                color.r.into(),
                color.g.into(),
                color.b.into(),
            )
        }
    }

    /// Sets the lighting for a keyboard key by scan code.
    ///
    /// # Returns
    /// Returns true if successful.
    pub fn set_lighting_for_key_with_scan_code(&self, scan_code: u32, color: ColorPercent) -> bool {
        unsafe {
            sys::LogiLedSetLightingForKeyWithScanCode(
                scan_code as c_int,
                color.r.into(),
                color.g.into(),
                color.b.into(),
            )
        }
    }

    /// Sets the lighting for a keyboard key by HID code.
    ///
    /// # Returns
    /// Returns true if successful.
    pub fn set_lighting_for_key_with_hid_code(&self, hid_code: u32, color: ColorPercent) -> bool {
        unsafe {
            sys::LogiLedSetLightingForKeyWithHidCode(
                hid_code as c_int,
                color.r.into(),
                color.g.into(),
                color.b.into(),
            )
        }
    }

    /// Sets the lighting for a specific device's target zone.
    ///
    /// A zone number is generally different per device, read the offical SDK docs for more info.
    ///
    /// # Returns
    /// Returns true if successful.
    pub fn set_lighting_for_target_zone(
        &self,
        device: DeviceType,
        zone: u32,
        color: ColorPercent,
    ) -> bool {
        unsafe {
            sys::LogiLedSetLightingForTargetZone(
                device,
                zone as c_int,
                color.r.into(),
                color.g.into(),
                color.b.into(),
            )
        }
    }

    /// Save the current lighting, play the effect, and restore the lighting.
    ///
    /// duration controls how long the flashes occur overall.
    /// If omitted, it will run until manually stopped.
    /// The interval is the time between flashes.
    ///
    /// # Returns
    /// Returns false if the call fails or any of the time values are too large.
    pub fn flash_lighting(
        &self,
        color: ColorPercent,
        duration: Option<Duration>,
        interval: Duration,
    ) -> bool {
        let duration = match duration.map(|duration| c_int::try_from(duration.as_millis())) {
            Some(Ok(duration)) if duration != sys::LOGI_LED_DURATION_INFINITE as c_int => duration,
            Some(Err(_)) | Some(Ok(_)) => return false,
            None => sys::LOGI_LED_DURATION_INFINITE as c_int,
        };
        let interval = match c_int::try_from(interval.as_millis()) {
            Ok(interval) => interval,
            Err(_) => return false,
        };

        unsafe {
            sys::LogiLedFlashLighting(
                color.r.into(),
                color.g.into(),
                color.b.into(),
                duration,
                interval,
            )
        }
    }

    /// Start a flashing effect on the given key.
    ///
    /// duration controls how long the flashes occur overall.
    /// If omitted, it will run until manually stopped.
    /// The interval is the time between flashes.
    ///
    /// # Returns
    /// Returns false if the call fails or any of the time values are too large.
    pub fn flash_single_key(
        &self,
        key: KeyName,
        color: ColorPercent,
        duration: Option<Duration>,
        interval: Duration,
    ) -> bool {
        let duration = match duration.map(|duration| c_int::try_from(duration.as_millis())) {
            Some(Ok(duration)) if duration != sys::LOGI_LED_DURATION_INFINITE as c_int => duration,
            Some(Err(_)) | Some(Ok(_)) => return false,
            None => sys::LOGI_LED_DURATION_INFINITE as c_int,
        };
        let interval = match c_int::try_from(interval.as_millis()) {
            Ok(interval) => interval,
            Err(_) => return false,
        };

        unsafe {
            sys::LogiLedFlashSingleKey(
                key,
                color.r.into(),
                color.g.into(),
                color.b.into(),
                duration,
                interval,
            )
        }
    }

    /// Stops all current LED effects.
    ///
    /// # Returns
    /// Returns false if the call fails.
    pub fn stop_effects(&self) -> bool {
        unsafe { sys::LogiLedStopEffects() }
    }

    /// Stops all LED effects on one key.
    ///
    /// # Returns
    /// Returns false if the call fails.
    pub fn stop_effects_on_key(&self, key: KeyName) -> bool {
        unsafe { sys::LogiLedStopEffectsOnKey(key) }
    }

    /// Save the current lighting, pulse the lighting, then restore the lighting.
    ///
    /// duration controls how long the pulses occur overall.
    /// If omitted, it will run until manually stopped.
    /// The interval is the time between pulses.
    ///
    /// # Returns
    /// Returns false if the call fails or any of the time values are too large.
    pub fn pulse_lighting(
        &self,
        color: ColorPercent,
        duration: Option<Duration>,
        interval: Duration,
    ) -> bool {
        let duration = match duration.map(|duration| c_int::try_from(duration.as_millis())) {
            Some(Ok(duration)) if duration != sys::LOGI_LED_DURATION_INFINITE as c_int => duration,
            Some(Err(_)) | Some(Ok(_)) => return false,
            None => sys::LOGI_LED_DURATION_INFINITE as c_int,
        };
        let interval = match c_int::try_from(interval.as_millis()) {
            Ok(interval) => interval,
            Err(_) => return false,
        };

        unsafe {
            sys::LogiLedPulseLighting(
                color.r.into(),
                color.g.into(),
                color.b.into(),
                duration,
                interval,
            )
        }
    }

    /// Start a pulsing effect on the given key.
    ///
    /// duration controls how long the pulses occur overall.
    ///
    /// # Returns
    /// Returns false if the call fails or any of the time values are too large.
    pub fn pulse_single_key(
        &self,
        key: KeyName,
        start_color: ColorPercent,
        end_color: ColorPercent,
        duration: Duration,
        is_infinite: bool,
    ) -> bool {
        let duration = match c_int::try_from(duration.as_millis()) {
            Ok(duration) => duration,
            Err(_) => return false,
        };

        unsafe {
            sys::LogiLedPulseSingleKey(
                key,
                start_color.r.into(),
                start_color.g.into(),
                start_color.b.into(),
                end_color.r.into(),
                end_color.g.into(),
                end_color.b.into(),
                duration,
                is_infinite,
            )
        }
    }

    /// Saves the current lighting config for the given key.
    ///
    /// # Returns
    /// Returns false if the call fails.
    pub fn save_lighting_for_key(&self, key: KeyName) -> bool {
        unsafe { sys::LogiLedSaveLightingForKey(key) }
    }

    /// Restores the current lighting config for the given key.
    ///
    /// # Returns
    /// Returns false if the call fails.
    pub fn restore_lighting_for_key(&self, key: KeyName) -> bool {
        unsafe { sys::LogiLedRestoreLightingForKey(key) }
    }
}

impl Drop for Sdk {
    fn drop(&mut self) {
        unsafe {
            sys::LogiLedShutdown();
        }
    }
}