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
//! Start with [`Handle::new`]

use std::ffi::{CStr, CString};
use std::mem;
use std::os::raw::c_char;
use std::ptr::{null_mut, NonNull};

use rusb::{DeviceHandle, UsbContext};

use crate::callback::CallbackData;
use array_iterator::ArrayIterator;
use dir::{DirItem, DirList};
pub use error::*;
use info::Info;
use libnspire_sys::{
    free, nspire_attr, nspire_device_info, nspire_devinfo, nspire_dir_create, nspire_dir_delete,
    nspire_dirlist, nspire_file_copy, nspire_file_delete, nspire_file_move, nspire_file_read,
    nspire_file_write, nspire_free, nspire_handle, nspire_image, nspire_init, nspire_os_send,
    nspire_screenshot,
};
use std::convert::TryFrom;

mod callback;
pub mod dir;
mod error;
pub mod info;

/// The USB vendor ID used by all Nspire calculators.
pub const VID: u16 = 0x0451;
/// The USB vendor ID used by all non-CX and original CX calculators.
pub const PID: u16 = 0xe012;
/// The USB vendor ID used by all CX II calculators.
pub const PID_CX2: u16 = 0xe022;

/// A handle to a calculator.
pub struct Handle<T: UsbContext> {
    handle: NonNull<nspire_handle>,
    device: DeviceHandle<T>,
}

fn is_cx_ii<T: UsbContext>(device: &DeviceHandle<T>) -> Result<bool> {
    Ok(device.device().device_descriptor()?.product_id() == PID_CX2)
}

impl<T: UsbContext> Handle<T> {
    /// Create a new handle to a USB device.
    pub fn new(device: DeviceHandle<T>) -> Result<Self> {
        let mut handle: *mut nspire_handle = null_mut();
        err(unsafe { nspire_init(&mut handle, device.as_raw() as _, is_cx_ii(&device)?) })?;
        Ok(Handle {
            handle: NonNull::new(handle).ok_or(Error::NoDevice)?,
            device,
        })
    }

    /// Whether this device is a CX II, CAS or non-CAS.
    pub fn is_cx_ii(&self) -> Result<bool> {
        is_cx_ii(&self.device)
    }

    pub fn info(&self) -> Result<Info> {
        unsafe {
            let mut info: nspire_devinfo = mem::zeroed();
            err(nspire_device_info(self.handle.as_ptr(), &mut info))?;
            Ok(info.into())
        }
    }

    /// Take a screenshot.
    pub fn screenshot(&self) -> Result<Image> {
        unsafe {
            let mut image: *mut nspire_image = null_mut();
            err(nspire_screenshot(self.handle.as_ptr(), &mut image))?;
            let width = (*image).width;
            let height = (*image).height;
            let bbp = (*image).bbp;
            let len = (width as u32 * height as u32 * bbp as u32) / 8;
            let data = (*image).data.as_slice(len as usize).into();
            free(image as _);
            Ok(Image {
                width,
                height,
                bpp: bbp,
                data,
            })
        }
    }

    /// Move/rename a file.
    pub fn move_file(&self, src: &str, dest: &str) -> Result<()> {
        let src = CString::new(src)?;
        let dest = CString::new(dest)?;
        unsafe {
            err(nspire_file_move(
                self.handle.as_ptr(),
                src.as_ptr(),
                dest.as_ptr(),
            ))
        }
    }

    /// Get the attributes of a file or directory.
    pub fn file_attr(&self, src: &str) -> Result<DirItem> {
        let src = CString::new(src)?;
        unsafe {
            let mut item = mem::zeroed();
            err(nspire_attr(self.handle.as_ptr(), src.as_ptr(), &mut item))?;
            Ok(item.into())
        }
    }

    /// Copy a file.
    pub fn copy_file(&self, src: &str, dest: &str) -> Result<()> {
        let src = CString::new(src)?;
        let dest = CString::new(dest)?;
        unsafe {
            err(nspire_file_copy(
                self.handle.as_ptr(),
                src.as_ptr(),
                dest.as_ptr(),
            ))
        }
    }

    /// Delete a file.
    pub fn delete_file(&self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        unsafe { err(nspire_file_delete(self.handle.as_ptr(), path.as_ptr())) }
    }

    /// Read a file. Returns the number of bytes read. You must pass a buffer
    /// large enough to read the entire file (or smaller if that's all you care
    /// about).
    pub fn read_file(
        &self,
        path: &str,
        buf: &mut [u8],
        progress: &mut dyn FnMut(usize),
    ) -> Result<usize> {
        let path = CString::new(path)?;
        let mut bytes = 0;
        let mut cb = CallbackData(progress);
        unsafe {
            err(nspire_file_read(
                self.handle.as_ptr(),
                path.as_ptr(),
                buf.as_mut_ptr() as _,
                buf.len() as _,
                &mut bytes,
                Some(CallbackData::callback),
                cb.as_mut_void(),
            ))?;
        }
        Ok(bytes as usize)
    }

    /// Write a file.
    pub fn write_file(
        &self,
        path: &str,
        buf: &[u8],
        progress: &mut dyn FnMut(usize),
    ) -> Result<()> {
        let path = CString::new(path)?;
        let mut cb = CallbackData(progress);
        unsafe {
            err(nspire_file_write(
                self.handle.as_ptr(),
                path.as_ptr(),
                buf.as_ptr() as _,
                buf.len() as _,
                Some(CallbackData::callback),
                cb.as_mut_void(),
            ))
        }
    }

    /// Send an OS update.
    pub fn send_os(&self, buf: &[u8], progress: &mut dyn FnMut(usize)) -> Result<()> {
        let mut cb = CallbackData(progress);
        unsafe {
            err(nspire_os_send(
                self.handle.as_ptr(),
                buf.as_ptr() as _,
                buf.len() as _,
                Some(CallbackData::callback),
                cb.as_mut_void(),
            ))
        }
    }

    /// Create a directory.
    pub fn create_dir(&self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        unsafe { err(nspire_dir_create(self.handle.as_ptr(), path.as_ptr())) }
    }

    /// Delete a directory.
    pub fn delete_dir(&self, path: &str) -> Result<()> {
        let path = CString::new(path)?;
        unsafe { err(nspire_dir_delete(self.handle.as_ptr(), path.as_ptr())) }
    }

    /// Get the contents of a directory.
    pub fn list_dir(&self, path: &str) -> Result<DirList> {
        let path = CString::new(path)?;
        unsafe {
            let mut list = null_mut();
            err(nspire_dirlist(
                self.handle.as_ptr(),
                path.as_ptr(),
                &mut list,
            ))?;
            Ok(DirList::from_raw(list))
        }
    }
}

unsafe impl<T: UsbContext> Send for Handle<T> {}
unsafe impl<T: UsbContext> Sync for Handle<T> {}

impl<T: UsbContext> TryFrom<DeviceHandle<T>> for Handle<T> {
    type Error = Error;

    fn try_from(device: DeviceHandle<T>) -> Result<Self> {
        Handle::new(device)
    }
}

impl<T: UsbContext> Drop for Handle<T> {
    fn drop(&mut self) {
        unsafe { nspire_free(self.handle.as_ptr()) }
    }
}

/// An image from a screenshot.
pub struct Image {
    pub width: u16,
    pub height: u16,
    /// The number of bits per pixel. Either 8 for non-color calculators or 16
    /// for color calculators.
    pub bpp: u8,
    pub data: Vec<u8>,
}
const MAX_R: u8 = ((1usize << 5) - 1) as u8;
const MAX_G: u8 = ((1usize << 6) - 1) as u8;
const MAX_B: u8 = ((1usize << 5) - 1) as u8;
/// Convert color channel values from one bit depth to another.
const fn convert_channel(value: u8, from_max: u8) -> u8 {
    ((value as u16 * 255u16 + from_max as u16 / 2) / from_max as u16) as u8
}

#[cfg(feature = "image")]
impl TryFrom<Image> for image::DynamicImage {
    type Error = Error;

    /// Currently broken.
    fn try_from(image: Image) -> Result<Self> {
        use image::ImageBuffer;
        match image.bpp {
            8 => Ok(image::DynamicImage::ImageLuma8(
                ImageBuffer::from_vec(image.width as u32, image.height as u32, image.data).unwrap(),
            )),
            16 => {
                let data: Vec<u8> = image
                    .data
                    .chunks(2)
                    .flat_map(|d| {
                        let color = u16::from_ne_bytes([d[0], d[1]]);
                        ArrayIterator::new([
                            convert_channel(color as u8 & MAX_R, MAX_R),
                            convert_channel((color >> 5) as u8 & MAX_G, MAX_G),
                            convert_channel((color >> 11) as u8 & MAX_B, MAX_B),
                        ])
                    })
                    .collect();
                dbg!(data.len());
                Ok(image::DynamicImage::ImageRgb8(
                    ImageBuffer::from_vec(image.width as u32, image.height as u32, data).unwrap(),
                ))
            }
            other => Err(Error::UnknownBpp(other)),
        }
    }
}

unsafe fn c_str(s: &[c_char]) -> String {
    CStr::from_ptr(s.as_ptr()).to_string_lossy().to_string()
}