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
/* tbff.rs
 *
 * Developed by Tim Walls <tim.walls@snowgoons.com>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
//! Trivial Bitmap File Format images.

// Imports ===================================================================
mod monochrome;
mod greyscale;

pub use monochrome::MonochromeImage;
pub use greyscale::GreyscaleImage;

use core::cell::RefCell;
use core::marker::PhantomData;
use ufmt::{Formatter, uWrite};
use avr_oxide::io::Read;
use avr_oxide::util::persist::derive::Persist;
use avr_oxide::util::persist::Persist;
use avrox_display::{GfxError, GfxResult};
use avrox_storage::{FileAddr, Seek, SeekFrom};
use avr_oxide::OxideResult::{Err,Ok};

// Declarations ==============================================================
#[allow(dead_code)]
pub enum LayerType {
  // Simple on/off monochrome bitmaps
  Monochrome,
  // Greyscale bitmap with 8-bit (256 value) greyscale data
  Greyscale8bit,
  // Colour RGB plus Alpha data (4-bits per field)
  RGBA4bit,
  // Colour RGB plus Alpha data (8-bits per field)
  RGBA8bit
}

#[derive(Clone)]
pub struct ImageFile<FILE>
where
  FILE: Read + Seek
{
  source: RefCell<FILE>,
  header: Header
}

pub trait ImageBlock {
  const SIZE: usize;

  fn empty() -> Self;

  fn load_from<FILE: Read>(&mut self, source: &mut FILE) -> GfxResult<()>;
}

#[derive(Clone)]
struct CachedBlock<BT,FILE>
where
  BT: ImageBlock,
  FILE: Read + Seek
{
  number: usize,
  data: BT,
  phantom_file: PhantomData<FILE>
}

/// The TBFF file header
#[repr(C,align(1))]
#[derive(Persist,Clone)]
#[persist(magicnumber = 0x54)]
#[cfg_attr(not(target_arch="avr"), derive(Debug))]
#[cfg_attr(target_arch="avr", derive(ufmt::derive::uDebug))]
pub struct Header {
  tag: [u8; 3],
  version: u8,
  width: u16,
  height: u16,
  layer_offsets: [u32; LayerType::count()]
}


// Code ======================================================================
impl LayerType {
  pub const fn to_layer_index(&self) -> usize {
    match self {
      LayerType::Monochrome    => 0,
      LayerType::Greyscale8bit => 1,
      LayerType::RGBA4bit      => 2,
      LayerType::RGBA8bit      => 3
    }
  }

  pub const fn count() -> usize {
    4
  }
}

#[cfg(target_arch="avr")]
impl<FILE> ufmt::uDebug for ImageFile<FILE>
where
  FILE: Read + Seek
{
  fn fmt<W>(&self, out: &mut Formatter<'_, W>) -> Result<(), W::Error> where W: uWrite + ?Sized {
    out.write_str("ImageFile { header=")?;
    self.header.fmt(out)?;
    out.write_str("}")
  }
}

impl<BT,FILE> CachedBlock<BT,FILE>
where
  BT: ImageBlock,
  FILE: Read + Seek
{
  fn empty() -> Self {
    CachedBlock {
      number: usize::MAX,
      data: BT::empty(),
      phantom_file: PhantomData::default()
    }
  }

  fn set_and_load(&mut self, number: usize, source: &mut FILE, base_addr: u32) -> GfxResult<()> {
    if number != self.number {
      source.seek(SeekFrom::Start((base_addr + ((number * BT::SIZE) as u32)) as FileAddr))?;
      self.data.load_from::<FILE>(source)?;
      self.number = number;
      Ok(())
    } else {
      // Do nothing, we already loaded this block
      Ok(())
    }
  }
}



impl<FILE> ImageFile<FILE>
where
  FILE: Read + Seek {

  pub fn with_file(mut source: FILE) -> GfxResult<Self> {
    source.rewind()?;
    let header = Header::load_from(&mut source)?;

    if header.tag == *b"BFG" {
      Ok(ImageFile{
        source: RefCell::new(source),
        header
      })
    } else {
      Err(GfxError::FileFormat)
    }
  }

  pub fn get_header(&self) -> Header {
    self.header.clone()
  }
}




// Tests =====================================================================
#[cfg(test)]
mod test {
  use avr_oxide::io::Read;
  use avrox_display::gfx::img::tbff::{ImageFile, MonochromeImage};
  use avrox_display::gfx::pixels::Monochromatic;
  use avrox_display::gfx::{fills, Point};
  use avrox_display::gfx::primitives::{ConstScaleUp, HorizontalPair, Overlay, position};
  use avrox_display::gfx::sevenseg::SevenSegmentDisplay;
  use avrox_display::gfx::test::MonochromeTestRenderer;
  use avrox_storage::{FileAddr, FileOffset, Seek, SeekFrom};
  use avr_oxide::OxideResult::{Ok,Err};
  use avrox_display::gfx::fills::SolidFill;

  pub struct TestFile {
    pub offset: usize,
    pub data: &'static [u8]
  }

  impl Read for TestFile {
    fn read(&mut self, buf: &mut [u8]) -> avr_oxide::io::Result<usize> {
      buf[0] = self.data[self.offset];
      self.offset += 1;
      Ok(1)
    }
  }
  impl Seek for TestFile {
    fn seek(&mut self, pos: SeekFrom) -> avr_oxide::io::Result<FileAddr> {
      let new_offset = match pos {
        SeekFrom::Start(addr) => { addr as usize},
        SeekFrom::End(delta) => { (((self.data.len()-1) as FileOffset) + delta) as usize },
        SeekFrom::Current(delta) => { ((self.offset as FileOffset) + delta) as usize }
      };

      self.offset = new_offset;
      Ok(self.offset as FileAddr)
    }

    fn stream_position(&mut self) -> avr_oxide::io::Result<FileAddr> {
      Ok(self.offset as FileAddr)
    }
  }

  #[should_panic]
  #[test]
  fn test_open_bad_header() {
    let mut test_file = TestFile {
      offset: 0,
      data: &[ b'X', b'X', b'X', b'F',
        0x02,
        0x00,0x0A, // Width - 10 pix
        0x00,0x0A, // Height - 10 pix

        0x00,0x00,0x00,0x19, // Layer 0 (monochrome) offset
        0x00,0x00,0x00,0x00, // Layer 1 (8bit grey) offset
        0x00,0x00,0x00,0x00, // Layer 2 (4bit RGBA) offset
        0x00,0x00,0x00,0x00, // Layer 3 (8bit RGBA) offset

        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      ]
    };

    let image = ImageFile::with_file(test_file).unwrap();
  }
}