Skip to content

Commit

Permalink
Add error handling
Browse files Browse the repository at this point in the history
Added error and result types, removed a lot of unwraps, expects and
panics, but there are still some left in the tarsila crate, especially
in GUI code.
  • Loading branch information
yds12 committed Apr 12, 2023
1 parent e6f550a commit 584dcf8
Show file tree
Hide file tree
Showing 16 changed files with 256 additions and 132 deletions.
55 changes: 44 additions & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ bugs, incomplete or missing features and suboptimal performance here and there.
Some of the main gaps currently are:

* Works as intended on Linux, but there are some compatibility issues with MacOS
(file dialog window does not open), and status on Windows is unknown;
* No error handling, everything panics;
(file dialog window does not open, modifier keys do not work); Windows is
reported to be working as intended;
* There are a few unit tests, but integration tests are missing, and coverage is
far from 100%;
* There is room to improve when it comes to performance
Expand Down
1 change: 1 addition & 0 deletions lapix/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ test-utils = []
bincode = "1.3.3"
image = "0.24.5"
serde = { version = "1.0.152", features = ["derive"] }
thiserror = "1.0.40"

[dev-dependencies]
test-case = "2.2.2"
21 changes: 9 additions & 12 deletions lapix/src/bitmap.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{color, Color, Point, Size};
use crate::{color, Color, Error, Point, Result, Size};

// TODO rename this trait
/// Represents a 2D matrix of pixels (an image)
Expand Down Expand Up @@ -33,29 +33,26 @@ pub trait Bitmap: Clone {

// TODO: use this and next method to save/load files
/// Get the the PNG representation of this image as a sequence of bytes
fn png_bytes(&self) -> Vec<u8> {
fn png_bytes(&self) -> Result<Vec<u8>> {
let img = image::RgbaImage::from_raw(
self.width() as u32,
self.height() as u32,
self.bytes().to_owned(),
)
.expect("Failed to generate image from bytes");
.ok_or(Error::FailedImageFromRaw)?;

let vec = Vec::<u8>::new();
let mut vec = std::io::Cursor::new(vec);
img.write_to(&mut vec, image::ImageOutputFormat::Png)
.unwrap(); // never fails
img.write_to(&mut vec, image::ImageOutputFormat::Png)?;

vec.into_inner()
Ok(vec.into_inner())
}

/// Create a new image from a sequence of bytes read from an image file
/// (e.g. PNG or JPG)
fn from_file_bytes(bytes: Vec<u8>) -> Self {
let reader = image::io::Reader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.unwrap(); // never fails
let img = reader.decode().expect("failed to decode image");
fn try_from_file_bytes(bytes: Vec<u8>) -> Result<Self> {
let reader = image::io::Reader::new(std::io::Cursor::new(bytes)).with_guessed_format()?;
let img = reader.decode()?;
let img = img.into_rgba8();

let size: Size<i32> = (img.width() as i32, img.height() as i32).into();
Expand All @@ -66,7 +63,7 @@ pub trait Bitmap: Clone {
bitmap.set_pixel((x as i32, y as i32).into(), color);
}

bitmap
Ok(bitmap)
}
}

Expand Down
23 changes: 23 additions & 0 deletions lapix/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use thiserror::Error;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Error)]
pub enum Error {
#[error("Failed to generate image from raw data")]
FailedImageFromRaw,
#[error("No free image found")]
MissingFreeImage,
#[error("Unsupported image format")]
UnsupportedImageFormat,
#[error("Drawing action has not started")]
DrawingNotStarted,
#[error("Image error: {0}")]
ImageError(#[from] image::ImageError),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
#[error("Bug: reversal list is not set")]
ReversalNotSet,
#[error("Codec error: {0}")]
CodecError(#[from] bincode::Error),
}
2 changes: 2 additions & 0 deletions lapix/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod action;
mod bitmap;
mod canvas;
pub mod color;
mod error;
mod event;
mod floating;
pub mod graphics;
Expand All @@ -20,6 +21,7 @@ use action::{Action, AtomicAction};
pub use bitmap::Bitmap;
pub use canvas::{Canvas, CanvasEffect};
pub use color::Color;
pub use error::{Error, Result};
pub use event::Event;
pub use floating::FreeImage;
pub use layer::{Layer, Layers};
Expand Down
9 changes: 5 additions & 4 deletions lapix/src/palette.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{util, Color};
use crate::{util, Color, Result};
use serde::{Deserialize, Serialize};

const MAX_PALETTE: usize = 200;
Expand Down Expand Up @@ -28,9 +28,10 @@ impl Default for Palette {
}

impl Palette {
pub fn from_file(path: &str) -> Self {
let img = util::load_img_from_file(path);
Self::from_image(img)
pub fn from_file(path: &str) -> Result<Self> {
let img = util::load_img_from_file(path)?;

Ok(Self::from_image(img))
}

fn from_image(img: image::RgbaImage) -> Self {
Expand Down

0 comments on commit 584dcf8

Please sign in to comment.