#include "ui/Bitmap.hpp" #include #include #include #include "nanosvg/nanosvg.h" #include "nanosvg/nanosvgrast.h" #include "stb/stb_image.h" namespace dp::ui { namespace { bool looksLikeSvg(const std::string& bytes) { const std::size_t n = std::min(bytes.size(), 512); const std::string head = bytes.substr(0, n); return head.find("(bytes.data()), static_cast(bytes.size()), &w, &h, &comp, 4); if (!data) return nullptr; if (w <= 0 || h <= 0 || w > Bitmap::kMaxDimension || h > Bitmap::kMaxDimension || static_cast(w) * static_cast(h) * 4 > Bitmap::kMaxBytes) { stbi_image_free(data); return nullptr; } auto bmp = std::make_shared(w, h); std::uint32_t* out = bmp->data(); const std::size_t count = static_cast(w) * static_cast(h); for (std::size_t i = 0; i < count; ++i) { const unsigned char* p = data + i * 4; out[i] = (static_cast(p[3]) << 24) | (static_cast(p[0]) << 16) | (static_cast(p[1]) << 8) | p[2]; } stbi_image_free(data); return bmp; } BitmapPtr decodeSvg(const std::string& bytes, int targetPx) { std::string copy = bytes; // nsvgParse mutates the buffer NSVGimage* image = nsvgParse(copy.data(), "px", 96.0f); if (!image) return nullptr; if (image->width <= 0 || image->height <= 0) { nsvgDelete(image); return nullptr; } const float longest = std::max(image->width, image->height); const float scale = static_cast(std::clamp(targetPx, 8, 2048)) / longest; const int w = std::max(1, static_cast(image->width * scale + 0.5f)); const int h = std::max(1, static_cast(image->height * scale + 0.5f)); NSVGrasterizer* rast = nsvgCreateRasterizer(); std::vector buf(static_cast(w) * static_cast(h) * 4, 0); nsvgRasterize(rast, image, 0, 0, scale, buf.data(), w, h, w * 4); nsvgDeleteRasterizer(rast); nsvgDelete(image); auto bmp = std::make_shared(w, h); std::uint32_t* out = bmp->data(); const std::size_t count = static_cast(w) * static_cast(h); for (std::size_t i = 0; i < count; ++i) { const unsigned char* p = buf.data() + i * 4; out[i] = (static_cast(p[3]) << 24) | (static_cast(p[0]) << 16) | (static_cast(p[1]) << 8) | p[2]; } return bmp; } } // namespace BitmapPtr Bitmap::decode(const std::string& bytes, int svgTargetPx) { if (bytes.empty() || bytes.size() > kMaxBytes) return nullptr; if (looksLikeSvg(bytes)) return decodeSvg(bytes, svgTargetPx); return decodeRaster(bytes); } } // namespace dp::ui