pixelab_linux_fb/
lib.rs

1use pixelab_core::{Area, Bitmap, BitmapFormat, DisplayDevice, PixelabError};
2use pixelab_rgb8888x1::RGB8888x1;
3use std::fs::File;
4use std::io::{self, Seek, SeekFrom, Write};
5use pixelab_rgb8888x4::RGB8888x4;
6
7pub struct LinuxFB {
8    file: File,
9    area: Area,
10    bitmap: BitmapFormat,
11}
12impl LinuxFB {
13    pub fn new_rgb8888x1(
14        file: &'static str,
15        width: u16,
16        height: u16,
17    ) -> Result<Box<Self>, io::Error> {
18        let file = File::create(file)?;
19        Ok(Box::new(Self {
20            file,
21            area: Area::new(width, height),
22            bitmap: BitmapFormat::RGB8888x1(vec![]),
23        }))
24    }
25    pub fn new_rgb8888x4(
26        file: &'static str,
27        width: u16,
28        height: u16,
29    ) -> Result<Box<Self>, io::Error> {
30        let file = File::create(file)?;
31        Ok(Box::new(Self {
32            file,
33            area: Area::new(width, height),
34            bitmap: BitmapFormat::RGB8888x4(vec![]),
35        }))
36    }
37}
38impl DisplayDevice for LinuxFB {
39    fn create_bitmap(&mut self) -> Box<dyn Bitmap + 'static> {
40        match self.bitmap {
41            BitmapFormat::RGB8888x1(_) => {
42                RGB8888x1::new(self.area)
43            }
44            BitmapFormat::RGB8888x4(_) => {
45                RGB8888x4::new(self.area)
46            }
47            _ => panic!()
48        }
49    }
50
51    fn write(&mut self, bitmap: &mut Box<dyn Bitmap + 'static>) -> Result<(), PixelabError> {
52        match &bitmap.buffer() {
53            BitmapFormat::RGB8888x4(bitmap) => {
54                self.file.seek(SeekFrom::Start(0)).unwrap();
55                self.file.write(bitmap).unwrap();
56                Ok(())
57            }
58            BitmapFormat::RGB8888x1(bitmap) => {
59                self.file.seek(SeekFrom::Start(0)).unwrap();
60                self.file
61                    .write(unsafe {
62                        core::slice::from_raw_parts(
63                            bitmap.as_ptr() as *const u8,
64                            bitmap.len() * size_of::<u32>(),
65                        )
66                    })
67                    .unwrap();
68
69                Ok(())
70            }
71            _ => Err(PixelabError::BitmapFormatMismatch),
72        }
73    }
74}