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
/*
 * Copyright 2018 Christian Ebner
 *
 * This file is part of dmio.
 *
 * dmio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dmio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dmio.  If not, see <http://www.gnu.org/licenses/>.
 */

#![allow(dead_code)]
#![feature(test)]

extern crate byteorder;
extern crate test;
#[macro_use]
extern crate log;

mod dmreader;
mod dmwriter;
mod dmtypes;
mod taggroup_entries;
mod create_tgs;
#[cfg(test)]
mod tests;


use std::fs::OpenOptions;
use std::path::Path;
use std::mem;
use std::ops;

use taggroup_entries::{Key, Tag, TagGroup};
use taggroup_entries::Key::*;
use taggroup_entries::Tag::*;
use dmtypes::{SORTED, OPEN};
use dmreader::DMImageReader;
use dmwriter::{DMImageWriter, DMImageWriteByVersion};

pub type DM3Reader = dmtypes::DM3Reader;
pub type DM4Reader = dmtypes::DM4Reader;
pub type DM3Writer = dmtypes::DM3Writer;
pub type DM4Writer = dmtypes::DM4Writer;
pub type Result<T> = std::result::Result<T, Box<std::error::Error + Send + Sync>>;

#[derive(Debug, Default)]
pub struct DMImage {
    path: Option<String>,
    root: TagGroup,
    data: Tag,
    sizex: Tag,
    sizey: Tag,
    sizez: Tag,
    version: usize,
    tg_size: usize,
    bigendian: bool,
}

impl ops::Index<[usize; 3]> for DMImage {
    type Output = f32;

    fn index(&self, index: [usize; 3]) -> &f32 {
        let z_offset = index[2] * self.sizex() * self.sizey();
        let y_offset = index[1] * self.sizex();
        let x_offset = index[0];
        &self.data()[z_offset + y_offset + x_offset]
    }
}

impl ops::IndexMut<[usize; 3]> for DMImage {
    fn index_mut(&mut self, index: [usize; 3]) -> &mut f32 {
        let z_offset = index[2] * self.sizex() * self.sizey();
        let y_offset = index[1] * self.sizex();
        let x_offset = index[0];
        &mut self.data_mut()[z_offset + y_offset + x_offset]
    }
}

impl ops::Index<[usize; 2]> for DMImage {
    type Output = f32;

    fn index(&self, index: [usize; 2]) -> &f32 {
        let y_offset = index[1] * self.sizex();
        let x_offset = index[0];
        &self.data()[y_offset + x_offset]
    }
}

impl ops::IndexMut<[usize; 2]> for DMImage {
    fn index_mut(&mut self, index: [usize; 2]) -> &mut f32 {
        let y_offset = index[1] * self.sizex();
        let x_offset = index[0];
        &mut self.data_mut()[y_offset + x_offset]
    }
}

impl DMImage {
    /// Returns the element at given indices by reference.
    ///
    /// Panics if the element at given indices does not exist.
    pub fn ind(&self, x: usize, y: usize, z: usize) -> &f32 {
        let z_offset = z * self.sizex() * self.sizey();
        let y_offset = y * self.sizex();
        let x_offset = x;
        &self.data()[z_offset + y_offset + x_offset]
    }

    /// Returns the number of image pixels on the x-axis.
    #[inline]
    pub fn sizex(&self) -> usize {
        match self.sizex {
            ULong(sizex) => sizex as usize,
            _ => 0usize,
        }
    }

    /// Returns the number of image pixels on the y-axis.
    #[inline]
    pub fn sizey(&self) -> usize {
        match self.sizey {
            ULong(sizey) => sizey as usize,
            _ => 0usize,
        }
    }

    /// Returns the number of image pixels on the z-axis.
    #[inline]
    pub fn sizez(&self) -> usize {
        match self.sizez {
            ULong(sizey) => sizey as usize,
            _ => 0usize,
        }
    }

    pub fn shape(&self) -> Vec<usize> {
        let mut shape: Vec<usize> = Vec::new();
        match self.sizex {
            ULong(sizex) => shape.push(sizex as usize),
            _ => return shape,
        }
        match self.sizey {
            ULong(sizey) => shape.push(sizey as usize),
            _ => return shape,
        }
        match self.sizez {
            ULong(sizez) => shape.push(sizez as usize),
            _ => return shape,
        }
        shape
    }

    /// Returns true if image has endianess `BigEndian`.
    #[inline]
    pub fn is_bigendian(&self) -> bool {
        self.bigendian
    }

    /// Returns a reference to the raw data vector of the image.
    ///
    /// On error panics.
    // TODO impl for other datatypes as well
    #[inline]
    pub fn data(&self) -> &Vec<f32> {
        match self.data {
            ArrayFloat(ref array) => array,
            _ => panic!("Inconsistent data, exiting..."),
        }
    }

    /// Returns a mutable reference to the raw data vector of the image.
    ///
    /// On error panics.
    // TODO impl for other datatypes as well
    #[inline]
    pub fn data_mut(&mut self) -> &mut Vec<f32> {
        match self.data {
            ArrayFloat(ref mut array) => array,
            _ => panic!("Inconsistent data, exiting..."),
        }
    }

    /// The use of this function is deprecated, use the `DMImage::new()` function instead or
    /// operate directly on the data of an opened image
    // TODO impl for other datatypes as well
    pub unsafe fn replace_data_with(&mut self, new_data: Vec<f32>, shape: &[usize]) -> Result<()> {
        match self.data {
            ArrayFloat(ref mut array) => {
                mem::replace(array, new_data);
            }
            _ => {
                return Err(From::from(
                    "Error while replacing the image data, operation not performed...",
                ))
            }
        }

        self.swap_data();
        for (dim_ind, &size) in shape.iter().enumerate() {
            match *self.root
                .get_mut("ImageList").unwrap()
                .get_tag_mut(&Key::Index(1)).unwrap()
                .get_mut("ImageData").unwrap()
                .get_mut("Dimensions").unwrap() {
                TagGroupEntry(ref mut tg) => {
                    let _ = tg.insert(Index(dim_ind), ULong(size as u32));
                }
                _ => return Err(From::from("Unexpected tag type for 'Dimensions'")),
            }
        }
        self.swap_data();

        Ok(())
    }

    /// Creates a new, empty image.
    pub fn new(shape: &[usize]) -> DMImage {
        info!("Called dm3io::DMImage::new()");
        let mut image = DMImage {
            path: None,
            root: TagGroup::new(SORTED, !OPEN),
            data: Empty,
            sizex: Empty,
            sizey: Empty,
            sizez: Empty,
            version: 3usize,
            tg_size: 0usize,
            bigendian: false,
        };

        let app_bounds = Struct(vec![Long(0), Long(0), Long(944), Long(1524)]);
        image.root.insert(
            Key::from_str("ApplicationBounds"),
            app_bounds,
        );
        image.root.insert(
            Key::from_str("DocumentObjectList"),
            create_tgs::document_object_list(),
        );
        let dt = TagGroup::new(SORTED, !OPEN);
        image.root.insert(
            Key::from_str("DocumentTags"),
            TagGroupEntry(dt),
        );
        image.root.insert(
            Key::from_str("HasWindowPosition"),
            Boolean(false),
        );
        image.root.insert(
            Key::from_str("Image Behavior"),
            create_tgs::image_behavior(),
        );
        let image_type = 2u32;
        image.root.insert(
            Key::from_str("ImageList"),
            create_tgs::image_list(shape, image_type),
        );
        image.root.insert(
            Key::from_str("ImageSourceList"),
            create_tgs::image_source_list(),
        );
        image.root.insert(
            Key::from_str("InImageMode"),
            Boolean(false),
        );
        image.root.insert(
            Key::from_str("LayoutType"),
            ArrayUShort(vec![85, 110, 107, 110, 111, 119, 110]),
        );
        // TODO It seems that this stuff is not needed neccessarily, remove it completely if that
        // is indeed the case
        //image.root.insert(Key::from_str("MinVersionList"), create_tgs::min_version_list());
        //image.root.insert(Key::from_str("NextDocumentObjectID"), ULong(9));
        //image.root.insert(Key::from_str("Page Behavior"), create_tgs::page_behavior());
        //image.root.insert(Key::from_str("PageSetup"), create_tgs::page_setup());
        //let sl = TagGroup::new(!SORTED, !OPEN)
        //image.root.insert(Key::from_str("SentinelList"), TagGroupEntry(sl));
        image.root.insert(
            Key::from_str("Thumbnails"),
            create_tgs::thumbnails(),
        );
        //image.root.insert(Key::from_str("WindowPosition"),
        //    Struct(vec![Long(62), Long(20), Long(190), Long(148)]));
        image.swap_data();

        image
    }

    /// Opens and reads an existing DMImage given by the path and returns it as `Result<DMImage>`.
    ///
    /// If open fails, an std::io::Error is returned.
    pub fn open(filepath: &str) -> Result<DMImage> {
        debug!("DMImage::open({})", filepath);
        let path = Path::new(filepath);
        let file = OpenOptions::new().read(true).open(path)?;
        // Load the full image into memory and parse the image content
        let mut reader = DMImageReader::new(file)?;
        let mut image = reader.parse()?;
        // Swaps the data to the DMImage handle for faster access,
        // this needs to be reversed before writing the image to file
        image.swap_data();

        Ok(image)
    }

    // TODO impl this
    // fn save(&self) -> Result<usize, Error> {
    //
    // }

    /// Save DMImage to file given by filepath.
    pub fn save_as<R: DMImageWriteByVersion>(&mut self, filepath: &str) -> Result<()> {
        debug!("DMImage::save_as({})", filepath);
        let path = Path::new(filepath);
        let mut options = OpenOptions::new();
        let file = options.create(true).write(true).truncate(true).open(path)?;
        // Need to swap data back into the root before saving
        self.swap_data();
        {
            let mut writer = DMImageWriter::from(self);
            writer.write_to_file::<R>(file)?;
        }
        // Now that the data is written, we switch it back from the root
        self.swap_data();
        Ok(())
    }

    /// Returns the smallest value in the image.
    // TODO impl for other datatypes as well
    pub fn get_min(&self) -> f32 {
        let mut min = self.data()[0];

        for val in self.data() {
            if *val < min {
                min = *val
            }
        }

        min
    }

    /// Returns the smallest value in the image.
    // TODO impl for other datatypes as well
    pub fn get_max(&self) -> f32 {
        let mut max = self.data()[0];

        for val in self.data() {
            if *val > max {
                max = *val
            }
        }

        max
    }

    /// Returns the image as rgb values in a raw vector `Vec<u8>`.
    // TODO impl for other datatypes as well
    pub fn to_raw_rgb(&self) -> Vec<u8> {
        match self.data {
            ArrayFloat(_) => {
                const RGB_BITS: usize = 3;
                const DEPTH: f32 = 255.0;

                let mut buf = Vec::with_capacity(self.sizex()*self.sizey()*RGB_BITS);
                let min_val = self.get_min();
                let max_val = self.get_max();
                let slot = if (max_val - min_val).abs() < std::f32::EPSILON {
                    (max_val - min_val) / DEPTH
                } else {
                    1f32
                };

                for val in self.data() {
                    let temp = (val - min_val) / slot;
                    let grayvalue = temp.trunc() as u8;
                    // Push RGB values
                    buf.push(grayvalue);
                    buf.push(grayvalue);
                    buf.push(grayvalue);
                }

                buf
            },
            _ => panic!("Inconsistent data in `DMImage::to_raw_data()`"),
        }
    }

    fn swap_data(&mut self) {
        match self.root
            .get_mut("ImageList")
            .unwrap()
            .get_tag_mut(&Index(1))
            .unwrap()
            .get_mut("ImageData")
            .unwrap()
            .get_mut("Data") {
            Some(ref mut tg_data) => mem::swap(&mut self.data, tg_data),
            None => panic!("Inconsistent data, exiting..."),
        }
        if let Some(ref mut tg_sizex) =
            self.root
                .get_mut("ImageList")
                .unwrap()
                .get_tag_mut(&Index(1))
                .unwrap()
                .get_mut("ImageData")
                .unwrap()
                .get_mut("Dimensions")
                .unwrap()
                .get_tag_mut(&Index(0))
        {
            mem::swap(&mut self.sizex, tg_sizex);
        };
        if let Some(ref mut tg_sizey) =
            self.root
                .get_mut("ImageList")
                .unwrap()
                .get_tag_mut(&Index(1))
                .unwrap()
                .get_mut("ImageData")
                .unwrap()
                .get_mut("Dimensions")
                .unwrap()
                .get_tag_mut(&Index(1))
        {
            mem::swap(&mut self.sizey, tg_sizey);
        }
        if let Some(ref mut tg_sizez) =
            self.root
                .get_mut("ImageList")
                .unwrap()
                .get_tag_mut(&Index(1))
                .unwrap()
                .get_mut("ImageData")
                .unwrap()
                .get_mut("Dimensions")
                .unwrap()
                .get_tag_mut(&Index(2))
        {
            mem::swap(&mut self.sizez, tg_sizez);
        };
    }
}