From 914e14377c1f39291eaaa3495026313dfaa1a735 Mon Sep 17 00:00:00 2001 From: David Capello Date: Mon, 19 Dec 2022 12:27:30 -0300 Subject: [PATCH] [lua] Add Image.bounds and Image:shrinkBounds() --- src/app/script/image_class.cpp | 30 ++++++++++++++++++++++++++++++ tests/scripts/image.lua | 22 ++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/app/script/image_class.cpp b/src/app/script/image_class.cpp index ccdec0922..3aa4607b2 100644 --- a/src/app/script/image_class.cpp +++ b/src/app/script/image_class.cpp @@ -511,6 +511,27 @@ int Image_resize(lua_State* L) return 0; } +int Image_shrinkBounds(lua_State* L) +{ + auto obj = get_obj(L, 1); + doc::Image* img = obj->image(L); + doc::color_t refcolor; + if (lua_isnone(L, 2)) + refcolor = img->maskColor(); + else if (lua_isinteger(L, 2)) + refcolor = lua_tointeger(L, 2); + else + refcolor = convert_args_into_pixel_color(L, 2, img->pixelFormat()); + + gfx::Rect bounds; + if (!doc::algorithm::shrink_bounds(img, refcolor, nullptr, bounds)) { + bounds = gfx::Rect(); + } + + push_obj(L, bounds); + return 1; +} + int Image_get_rowStride(lua_State* L) { const auto obj = get_obj(L, 1); @@ -556,6 +577,13 @@ int Image_get_height(lua_State* L) return 1; } +int Image_get_bounds(lua_State* L) +{ + const auto obj = get_obj(L, 1); + push_obj(L, obj->image(L)->bounds()); + return 1; +} + int Image_get_colorMode(lua_State* L) { const auto obj = get_obj(L, 1); @@ -590,6 +618,7 @@ const luaL_Reg Image_methods[] = { { "isPlain", Image_isPlain }, { "saveAs", Image_saveAs }, { "resize", Image_resize }, + { "shrinkBounds", Image_shrinkBounds }, { "__gc", Image_gc }, { "__eq", Image_eq }, { nullptr, nullptr } @@ -600,6 +629,7 @@ const Property Image_properties[] = { { "bytes", Image_get_bytes, Image_set_bytes }, { "width", Image_get_width, nullptr }, { "height", Image_get_height, nullptr }, + { "bounds", Image_get_bounds, nullptr }, { "colorMode", Image_get_colorMode, nullptr }, { "spec", Image_get_spec, nullptr }, { "cel", Image_get_cel, nullptr }, diff --git a/tests/scripts/image.lua b/tests/scripts/image.lua index 3bbe430af..c429484f2 100644 --- a/tests/scripts/image.lua +++ b/tests/scripts/image.lua @@ -204,6 +204,28 @@ do expect_img(img2, cols) end +-- Bounds & shrink bounds +do + local a = Image(5, 4, ColorMode.INDEXED) + array_to_pixels({ 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, }, a) + + expect_eq(a.bounds, Rectangle(0, 0, 5, 4)) + expect_eq(a:shrinkBounds(), Rectangle(1, 1, 3, 2)) + expect_eq(a:shrinkBounds(1), Rectangle(0, 0, 5, 4)) + + array_to_pixels({ 2, 2, 2, 2, 2, + 0, 1, 0, 0, 2, + 0, 0, 0, 1, 2, + 0, 0, 0, 0, 2, }, a) + + expect_eq(a:shrinkBounds(), Rectangle(0, 0, 5, 4)) + expect_eq(a:shrinkBounds(1), Rectangle(0, 0, 5, 4)) + expect_eq(a:shrinkBounds(2), Rectangle(0, 1, 4, 3)) +end + -- Test v1.2.17 crashes do local defSpec = ImageSpec{ width=1, height=1, colorMode=ColorMode.RGB }