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
//! Low level wrapper for Leptonica C API

use super::capi;

use std::convert::TryInto;
use std::ffi::CString;
use std::path::Path;

use thiserror;

pub struct Pix {
    pub raw: *mut capi::Pix,
}

impl Pix {
    pub fn get_w(&self) -> u32 {
        unsafe { (*self.raw).w }
    }
    pub fn get_h(&self) -> u32 {
        unsafe { (*self.raw).h }
    }
}

impl Drop for Pix {
    fn drop(&mut self) {
        unsafe {
            capi::pixDestroy(&mut self.raw);
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum PixError {
    #[error("Failed to read image from {}", .0)]
    ReadFrom(&'static str),

    #[error("Path is not a valid utf8 string")]
    InvalidUtf8Path,

    #[error("Path contains invalid nul byte: {}", .source)]
    InvalidPathNulByte {
        #[from]
        source: std::ffi::NulError,
    },

    // this happens when usize has bit size 128 but leptonica only takes u64 address pointer
    #[error(transparent)]
    MemoryTooLarge {
        #[from]
        source: std::num::TryFromIntError,
    },
}

/// Read an image from a local file.
///
/// The provided path must be valid UTF-8.
pub fn pix_read(path: &Path) -> Result<Pix, PixError> {
    let s = path.to_str().ok_or(PixError::InvalidUtf8Path)?;
    let cs = CString::new(s)?;
    let pix = unsafe { capi::pixRead(cs.as_ptr()) };
    // on read errors, leptonica sets pointer to null and prints error message to stderr, so there
    // is no easy to capture and return the actual message programatically
    if pix.is_null() {
        Err(PixError::ReadFrom("file"))
    } else {
        Ok(Pix { raw: pix })
    }
}

/// Like pix_read, but redas the image from memory instead of disk
pub fn pix_read_mem(img: &[u8]) -> Result<Pix, PixError> {
    let pix = unsafe { capi::pixReadMem(img.as_ptr(), img.len().try_into()?) };
    if pix.is_null() {
        Err(PixError::ReadFrom("memory"))
    } else {
        Ok(Pix { raw: pix })
    }
}

#[derive(Debug, PartialEq)]
pub struct BoxVal {
    pub x: i32,
    pub y: i32,
    pub w: i32,
    pub h: i32,
}

pub struct Box {
    pub raw: *mut capi::Box,
}

impl Drop for Box {
    fn drop(&mut self) {
        self.destroy();
    }
}

impl Box {
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> Option<Box> {
        unsafe {
            let p = capi::boxCreateValid(x, y, width, height);
            if p.is_null() {
                None
            } else {
                Some(Box { raw: p })
            }
        }
    }

    pub fn get_val(&self) -> BoxVal {
        unsafe {
            let v = *self.raw;
            BoxVal {
                x: v.x,
                y: v.y,
                w: v.w,
                h: v.h,
            }
        }
    }

    pub fn destroy(&mut self) {
        unsafe {
            capi::boxDestroy(&mut self.raw);
        }
    }
}

pub struct Boxa {
    pub raw: *mut capi::Boxa,
}

impl Drop for Boxa {
    fn drop(&mut self) {
        self.destroy();
    }
}

impl Boxa {
    pub fn get_n(&self) -> usize {
        unsafe { (*self.raw).n as usize }
    }

    pub fn get_box(&self, i: usize, flag: i32) -> Option<Box> {
        unsafe {
            let b = capi::boxaGetBox(self.raw, i as i32, flag);
            if b.is_null() {
                return None;
            }
            Some(Box { raw: b })
        }
    }

    pub fn destroy(&mut self) {
        unsafe {
            capi::boxaDestroy(&mut self.raw);
        }
    }
}

impl IntoIterator for Boxa {
    type Item = Box;
    type IntoIter = BoxaIterator;

    fn into_iter(self) -> Self::IntoIter {
        let count = self.get_n();
        BoxaIterator {
            boxa: self,
            index: 0,
            count,
        }
    }
}

pub struct BoxaIterator {
    boxa: Boxa,
    index: usize,
    count: usize,
}

impl Iterator for BoxaIterator {
    type Item = Box;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.count {
            return None;
        }

        let re = self.boxa.get_box(self.index, capi::L_CLONE as i32);
        self.index += 1;

        re
    }
}

impl<'a> IntoIterator for &'a Boxa {
    type Item = Box;
    type IntoIter = BoxaRefIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        let count = self.get_n();
        BoxaRefIterator {
            boxa: self,
            index: 0,
            count,
        }
    }
}

pub struct BoxaRefIterator<'a> {
    boxa: &'a Boxa,
    index: usize,
    count: usize,
}

impl<'a> Iterator for BoxaRefIterator<'a> {
    type Item = Box;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.count {
            return None;
        }

        let re = self.boxa.get_box(self.index, capi::L_CLONE as i32);
        self.index += 1;

        re
    }
}