#pragma once
// Spec: SPEC.md UX-RENDER-01. Software canvas: anti-aliased rounded rects, gradients, shadows, bitmaps,
// clip stack. Deterministic on every machine, which makes headless screenshots comparable.
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
#include "ui/Bitmap.hpp"
#include "ui/Geometry.hpp"
namespace dp::ui {
class Canvas {
public:
void resize(int pixelWidth, int pixelHeight, float scale);
void clear(Color c);
float scale() const { return scale_; }
int pixelWidth() const { return pw_; }
int pixelHeight() const { return ph_; }
Size logicalSize() const { return {static_cast<float>(pw_) / scale_, static_cast<float>(ph_) / scale_}; }
const std::uint32_t* pixels() const { return buf_.data(); }
void fillRect(const Rect& r, Color c, float opacity = 1);
void fillRRect(const Rect& r, const Corners& radius, Color c, float opacity = 1);
void fillRRectGradient(const Rect& r, const Corners& radius, Color from, Color to, Point start, Point end,
float opacity = 1);
// Inside-aligned border (SwiftUI strokeBorder).
void strokeRRect(const Rect& r, const Corners& radius, Color c, float width, float opacity = 1);
void shadow(const Rect& r, const Corners& radius, Color c, float blurRadius, Point offset);
// Draw `bmp` scaled into `dest` (bilinear). tint: use only the alpha channel, painted in this color.
void drawBitmap(const Bitmap& bmp, const Rect& dest, float opacity = 1, std::optional<Color> tint = std::nullopt);
// Blit a pre-rendered straight-alpha ARGB text surface; (x, y) logical, snapped to device pixels.
void blitText(const Bitmap& text, float x, float y, float opacity = 1);
void pushOpacity(float f) { opacity_.push_back(opacity_.back() * f); }
void popOpacity() { if (opacity_.size() > 1) opacity_.pop_back(); }
float opacity() const { return opacity_.back(); }
void pushClip(const Rect& r, const Corners& radius = {});
void popClip();
Rect clipBounds() const;
bool savePng(const std::string& path) const;
private:
struct Clip {
Rect bounds; // device pixels, already intersected with every parent clip
Rect shape; // device pixels, the rounded shape (only meaningful when rounded)
Corners radius;
bool rounded = false;
};
struct Span {
int x0, y0, x1, y1;
};
Span spanFor(const Rect& dev) const;
float clipCoverage(float px, float py) const;
void blend(int x, int y, Color c, float coverage);
int pw_ = 0, ph_ = 0;
float scale_ = 1;
std::vector<std::uint32_t> buf_;
std::vector<Clip> clips_;
int roundedClips_ = 0;
std::vector<float> opacity_{1.0f};
};
} // namespace dp::ui