1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 14:17:36 +00:00

LibGfx: Commonize P[BGP]M file loading contexts

Much of the code in PBM, PGM, and PPM image loaders is common. The
contexts are nearly identical. Instead of writing multiple contexts,
write 1 with a template argument to pass in the details of the given
format.
This commit is contained in:
Lenny Maiorani 2022-03-12 11:16:30 -07:00 committed by Andreas Kling
parent 5c21f963ff
commit 786b02730c
8 changed files with 109 additions and 124 deletions

View file

@ -1,5 +1,6 @@
/*
* Copyright (c) 2020, Hüseyin ASLITÜRK <asliturk@hotmail.com>
* Copyright (c) 2022, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -15,44 +16,12 @@
namespace Gfx {
struct PPMLoadingContext {
enum Type {
Unknown,
ASCII,
RAWBITS
};
enum State {
NotDecoded = 0,
Error,
MagicNumber,
Width,
Height,
Maxval,
Bitmap,
Decoded
};
static constexpr auto ascii_magic_number = '3';
static constexpr auto binary_magic_number = '6';
static constexpr auto image_type = "PPM";
Type type { Type::Unknown };
State state { State::NotDecoded };
const u8* data { nullptr };
size_t data_size { 0 };
u16 width { 0 };
u16 height { 0 };
u16 max_val { 0 };
RefPtr<Gfx::Bitmap> bitmap;
};
static bool read_image_data(PPMLoadingContext& context, Streamer& streamer)
{
Vector<Gfx::Color> color_data;
color_data.ensure_capacity(context.width * context.height);
if (context.type == PPMLoadingContext::ASCII) {
if (context.type == PPMLoadingContext::Type::ASCII) {
u16 red;
u16 green;
u16 blue;
@ -77,11 +46,11 @@ static bool read_image_data(PPMLoadingContext& context, Streamer& streamer)
break;
Color color { (u8)red, (u8)green, (u8)blue };
if (context.max_val < 255)
color = adjust_color(context.max_val, color);
if (context.format_details.max_val < 255)
color = adjust_color(context.format_details.max_val, color);
color_data.append(color);
}
} else if (context.type == PPMLoadingContext::RAWBITS) {
} else if (context.type == PPMLoadingContext::Type::RAWBITS) {
u8 pixel[3];
while (streamer.read_bytes(pixel, 3)) {
color_data.append({ pixel[0], pixel[1], pixel[2] });