#include "ui/Views.hpp"
#include <SDL3/SDL.h>
#include <algorithm>
#include <cmath>
#include <map>
#include "ui/Icons.hpp"
#include "ui/Modifiers.hpp"
#include "ui/Palette.hpp"
#include "ui/TextEngine.hpp"
namespace dp::ui {
namespace {
LinkHandler g_linkHandler = [](const std::string& url) { SDL_OpenURL(url.c_str()); };
Point alignInside(const Rect& outer, Size inner, Alignment a) {
float x = outer.x, y = outer.y;
if (a.h == HAlign::Center) x += (outer.w - inner.w) / 2;
else if (a.h == HAlign::Trailing) x += outer.w - inner.w;
if (a.v == VAlign::Center) y += (outer.h - inner.h) / 2;
else if (a.v == VAlign::Bottom) y += outer.h - inner.h;
return {x, y};
}
float clampFinite(float v) { return v >= kInf / 2 ? kInf : v; }
// ---------------------------------------------------------------- Text
class TextView : public View {
public:
explicit TextView(std::vector<StyledSpan> spans) : spans_(std::move(spans)) {
for (const auto& s : spans_) if (!s.link.empty()) hasLinks_ = true;
}
std::string label() const override {
std::string out;
for (const auto& s : spans_) out += s.text;
return out;
}
bool acceptsPress() const override { return hasLinks_; }
void hits(Point p, std::vector<View*>& out) override {
if (hasLinks_ && frame_.contains(p)) out.push_back(this);
}
void onTap(Point p) override {
const TextBlock block = blockFor(frame_.w);
for (const TextLine& line : block.lines) {
const float ly = frame_.y + line.y;
if (p.y < ly || p.y >= ly + line.height) continue;
for (const TextRun& run : line.runs) {
const float rx = frame_.x + run.x;
if (!run.style.link.empty() && p.x >= rx && p.x < rx + run.width) {
g_linkHandler(run.style.link);
return;
}
}
}
}
protected:
Size compute(const Proposal& p) override {
// SwiftUI: a Text's minimum is a truncated single line, so stacks serve fixed siblings first.
if (p.w && *p.w <= 0.5f) {
const TextBlock one = blockFor(kInf);
return {0.0f, one.lines.empty() ? 0.0f : one.lines.front().height};
}
const float width = p.w ? *p.w : kInf;
const TextBlock b = blockFor(width);
return {b.size.w, b.size.h};
}
public:
void draw(Canvas& c) override {
const TextBlock block = blockFor(frame_.w);
auto& engine = TextEngine::instance();
for (const TextLine& line : block.lines) {
for (const TextRun& run : line.runs) {
const float x = frame_.x + run.x;
if (run.style.background) {
c.fillRRect({x - 3, frame_.y + line.y + 1, run.width + 6, line.height - 2}, Corners::all(4), *run.style.background);
}
BitmapPtr bmp = engine.render(run.style.font, run.style.color, run.text);
if (bmp) {
const float top = frame_.y + line.y + line.baseline - engine.ascent(run.style.font);
c.blitText(*bmp, x, top);
}
if (run.style.underline || run.style.strikethrough) {
const float by = frame_.y + line.y + line.baseline;
const float ty = run.style.underline ? by + 1.5f : by - run.style.font.size * 0.3f;
c.fillRect({x, ty, run.width, 1}, run.style.color);
}
}
}
}
private:
std::vector<TextSpan> resolve() const {
const EnvValues& env = Env::cur();
const FontSpec baseFont = env.font.value_or(FontSpec::body());
const Color baseColor = env.foreground.value_or(Palette::fg1());
std::vector<TextSpan> out;
out.reserve(spans_.size());
for (const StyledSpan& s : spans_) {
TextSpan t;
t.text = s.text;
t.style.font = s.font.value_or(baseFont);
t.style.color = s.color.value_or(baseColor);
t.style.underline = s.underline;
t.style.strikethrough = s.strikethrough;
t.style.background = s.background;
t.style.link = s.link;
out.push_back(std::move(t));
}
return out;
}
TextBlock blockFor(float width) const {
const EnvValues& env = Env::cur();
const std::uint64_t key = hashCombine(static_cast<std::uint64_t>(std::lround(std::min(width, 1.0e6f) * 8)),
hashCombine(static_cast<std::uint64_t>(env.lineLimit), static_cast<std::uint64_t>(env.multilineAlign)));
for (const auto& e : memo_) if (e.first == key) return e.second;
TextBlock b = TextLayout::layout(resolve(), width, env.lineLimit, env.multilineAlign, env.lineSpacing);
if (memo_.size() < 6) memo_.emplace_back(key, b);
return b;
}
std::vector<StyledSpan> spans_;
bool hasLinks_ = false;
mutable std::vector<std::pair<std::uint64_t, TextBlock>> memo_;
};
// ---------------------------------------------------------------- Icon
class IconView : public View {
public:
IconView(std::string name, float size) : name_(std::move(name)), size_(size) {}
protected:
Size compute(const Proposal&) override { return {size_, size_}; }
public:
void draw(Canvas& c) override {
const int px = std::max(4, static_cast<int>(std::lround(size_ * c.scale())));
BitmapPtr bmp = Icons::get(name_, px);
if (!bmp) return;
const Color color = Env::cur().foreground.value_or(Palette::fg1());
const float s = std::min(frame_.w, frame_.h);
c.drawBitmap(*bmp, {frame_.x + (frame_.w - s) / 2, frame_.y + (frame_.h - s) / 2, s, s}, 1, color);
}
private:
std::string name_;
float size_;
};
// ---------------------------------------------------------------- Image
class ImageViewImpl : public View {
public:
ImageViewImpl(std::function<BitmapPtr()> provider, ContentMode mode, ViewPtr placeholder)
: provider_(std::move(provider)), mode_(mode) {
addChild(std::move(placeholder));
}
protected:
Size compute(const Proposal& p) override {
BitmapPtr bmp = provider_();
if (!bmp) {
if (!children_.empty()) return children_[0]->measure(p);
return {p.w && *p.w < kInf / 2 ? *p.w : 0, p.h && *p.h < kInf / 2 ? *p.h : 0};
}
const float bw = static_cast<float>(bmp->width()), bh = static_cast<float>(bmp->height());
const float ratio = bw / bh;
const bool hasW = p.w && *p.w < kInf / 2, hasH = p.h && *p.h < kInf / 2;
if (mode_ == ContentMode::Fill) return {hasW ? *p.w : bw, hasH ? *p.h : bh};
if (hasW && hasH) {
float w = *p.w, h = w / ratio;
if (h > *p.h) { h = *p.h; w = h * ratio; }
return {w, h};
}
if (hasW) return {*p.w, *p.w / ratio};
if (hasH) return {*p.h * ratio, *p.h};
return {bw, bh};
}
public:
void place(const Rect& r) override {
frame_ = r;
if (!children_.empty() && !provider_()) children_[0]->place(r);
}
void draw(Canvas& c) override {
BitmapPtr bmp = provider_();
if (!bmp) {
if (!children_.empty()) children_[0]->draw(c);
return;
}
if (mode_ == ContentMode::Fit) {
c.drawBitmap(*bmp, frame_);
return;
}
const float bw = static_cast<float>(bmp->width()), bh = static_cast<float>(bmp->height());
const float s = std::max(frame_.w / bw, frame_.h / bh);
const float w = bw * s, h = bh * s;
c.pushClip(frame_);
c.drawBitmap(*bmp, {frame_.x + (frame_.w - w) / 2, frame_.y + (frame_.h - h) / 2, w, h});
c.popClip();
}
private:
std::function<BitmapPtr()> provider_;
ContentMode mode_;
};
// ---------------------------------------------------------------- Shapes
class ShapeView : public View {
public:
enum class Kind { Rect, Round, Circle, Capsule };
ShapeView(Kind k, float radius) : kind_(k), radius_(radius) {}
Color fill = Color::clear();
std::optional<std::pair<Color, Color>> gradient;
Point gradStart{0, 0}, gradEnd{1, 1};
std::optional<Color> stroke;
float strokeWidth = 1;
float strokeOpacity = 1;
protected:
Size compute(const Proposal& p) override { return {p.w ? clampFinite(*p.w) : 10, p.h ? clampFinite(*p.h) : 10}; }
public:
void draw(Canvas& c) override {
Corners r;
switch (kind_) {
case Kind::Rect: break;
case Kind::Round: r = Corners::all(radius_); break;
case Kind::Circle:
case Kind::Capsule: r = Corners::all(std::min(frame_.w, frame_.h) / 2); break;
}
if (gradient) c.fillRRectGradient(frame_, r, gradient->first, gradient->second, gradStart, gradEnd);
else if (fill.a) c.fillRRect(frame_, r, fill);
if (stroke) c.strokeRRect(frame_, r, *stroke, strokeWidth, strokeOpacity);
}
private:
Kind kind_;
float radius_;
};
// ---------------------------------------------------------------- Stack-aware leaves
class AxisAware {
public:
virtual ~AxisAware() = default;
virtual void setStackAxis(Axis a) = 0;
};
class SpacerView : public View, public AxisAware {
public:
explicit SpacerView(float min) : min_(min) {}
void setStackAxis(Axis a) override { axis_ = a; }
protected:
Size compute(const Proposal& p) override {
const float main = std::max(min_, axis_ == Axis::Horizontal ? p.w.value_or(0) : p.h.value_or(0));
return axis_ == Axis::Horizontal ? Size{main, 0} : Size{0, main};
}
private:
float min_;
Axis axis_ = Axis::Horizontal;
};
class DividerView : public View, public AxisAware {
public:
DividerView(Color c, float t) : color_(c), thickness_(t) {}
void setStackAxis(Axis a) override { axis_ = a; }
protected:
Size compute(const Proposal& p) override {
// In a vertical stack the line is horizontal (flexible width), and vice versa.
if (axis_ == Axis::Vertical) return {p.w ? clampFinite(*p.w) : 10, thickness_};
return {thickness_, p.h ? clampFinite(*p.h) : 10};
}
public:
void draw(Canvas& c) override { c.fillRect(frame_, color_); }
private:
Color color_;
float thickness_;
Axis axis_ = Axis::Vertical;
};
// ---------------------------------------------------------------- Group
class GroupView : public View {
public:
explicit GroupView(std::vector<ViewPtr> kids) {
for (auto& k : kids) addChild(std::move(k));
}
protected:
Size compute(const Proposal& p) override {
Size s;
for (auto& c : children_) {
const Size cs = c->measure(p);
s.w = std::max(s.w, cs.w);
s.h = std::max(s.h, cs.h);
}
return s;
}
};
void flatten(const ViewPtr& v, std::vector<ViewPtr>& out) {
if (!v) return;
if (auto* g = dynamic_cast<GroupView*>(v.get())) {
for (const ViewPtr& c : g->children()) flatten(c, out);
return;
}
out.push_back(v);
}
// ---------------------------------------------------------------- Stacks
class StackView : public View {
public:
StackView(Axis axis, std::vector<ViewPtr> kids, float spacing, float crossAlign)
: axis_(axis), spacing_(spacing), crossAlign_(crossAlign) {
std::vector<ViewPtr> flat;
for (auto& k : kids) flatten(k, flat);
for (auto& k : flat) {
if (auto* a = dynamic_cast<AxisAware*>(k.get())) a->setStackAxis(axis);
addChild(std::move(k));
}
}
protected:
Size compute(const Proposal& p) override {
const Plan plan = makePlan(p);
return plan.total;
}
public:
void place(const Rect& r) override {
frame_ = r;
const Plan plan = makePlan(Proposal{r.w, r.h});
const bool horiz = axis_ == Axis::Horizontal;
const float mainLen = horiz ? r.w : r.h, crossLen = horiz ? r.h : r.w;
const float totalMain = horiz ? plan.total.w : plan.total.h;
float cursor = (horiz ? r.x : r.y) + std::max(0.0f, (mainLen - totalMain) / 2);
for (std::size_t i = 0; i < children_.size(); ++i) {
const Size s = plan.sizes[i];
const float cmain = horiz ? s.w : s.h, ccross = horiz ? s.h : s.w;
const float crossOff = (horiz ? r.y : r.x) + (crossLen - ccross) * crossAlign_;
if (horiz) children_[i]->place({cursor, crossOff, s.w, s.h});
else children_[i]->place({crossOff, cursor, s.w, s.h});
cursor += cmain + spacing_;
}
}
private:
struct Plan {
std::vector<Size> sizes;
Size total;
};
Plan makePlan(const Proposal& p) {
const bool horiz = axis_ == Axis::Horizontal;
const std::size_t n = children_.size();
Plan plan;
plan.sizes.assign(n, Size{});
if (n == 0) return plan;
const std::optional<float> mainProp = horiz ? p.w : p.h;
const std::optional<float> crossProp = horiz ? p.h : p.w;
auto make = [&](std::optional<float> m) {
return horiz ? Proposal{m, crossProp} : Proposal{crossProp, m};
};
const float gaps = spacing_ * static_cast<float>(n - 1);
if (!mainProp) {
for (std::size_t i = 0; i < n; ++i) plan.sizes[i] = children_[i]->measure(make(std::nullopt));
} else {
struct Info {
std::size_t index;
float prio, flex;
};
std::vector<Info> order;
order.reserve(n);
for (std::size_t i = 0; i < n; ++i) {
const Size lo = children_[i]->measure(make(0.0f));
const Size hi = children_[i]->measure(make(kInf));
order.push_back({i, children_[i]->priority(), (horiz ? hi.w - lo.w : hi.h - lo.h)});
}
std::stable_sort(order.begin(), order.end(), [](const Info& a, const Info& b) {
if (a.prio != b.prio) return a.prio > b.prio;
return a.flex < b.flex;
});
float remaining = *mainProp >= kInf / 2 ? kInf : std::max(0.0f, *mainProp - gaps);
std::size_t left = n;
for (const Info& info : order) {
const float offer = remaining >= kInf / 2 ? kInf : std::max(0.0f, remaining / static_cast<float>(left));
const Size s = children_[info.index]->measure(make(offer));
plan.sizes[info.index] = s;
if (remaining < kInf / 2) remaining -= horiz ? s.w : s.h;
--left;
}
}
float main = gaps, cross = 0;
for (const Size& s : plan.sizes) {
main += horiz ? s.w : s.h;
cross = std::max(cross, horiz ? s.h : s.w);
}
plan.total = horiz ? Size{main, cross} : Size{cross, main};
return plan;
}
Axis axis_;
float spacing_;
float crossAlign_; // 0 leading/top, 0.5 center, 1 trailing/bottom
};
class ZStackView : public View {
public:
ZStackView(std::vector<ViewPtr> kids, Alignment a) : align_(a) {
std::vector<ViewPtr> flat;
for (auto& k : kids) flatten(k, flat);
for (auto& k : flat) addChild(std::move(k));
}
protected:
Size compute(const Proposal& p) override {
Size s;
for (auto& c : children_) {
const Size cs = c->measure(p);
s.w = std::max(s.w, cs.w);
s.h = std::max(s.h, cs.h);
}
return s;
}
public:
void place(const Rect& r) override {
frame_ = r;
for (auto& c : children_) {
const Size cs = c->measure(Proposal{r.w, r.h});
const Point o = alignInside(r, cs, align_);
c->place({o.x, o.y, cs.w, cs.h});
}
}
void hits(Point p, std::vector<View*>& out) override {
for (auto it = children_.rbegin(); it != children_.rend(); ++it) (*it)->hits(p, out);
}
private:
Alignment align_;
};
class EmptyViewImpl : public View {
protected:
Size compute(const Proposal&) override { return {0, 0}; }
};
class ViewThatFitsImpl : public View {
public:
explicit ViewThatFitsImpl(std::vector<ViewPtr> options) {
for (auto& o : options) addChild(std::move(o));
}
protected:
Size compute(const Proposal& p) override { return pick(p)->measure(p); }
public:
void place(const Rect& r) override {
frame_ = r;
View* v = pick(Proposal{r.w, r.h});
const Size s = v->measure(Proposal{r.w, r.h});
v->place({r.x, r.y, s.w, s.h});
chosen_ = v;
// Only the chosen option takes part in drawing, hit testing and lookups from now on.
for (const ViewPtr& o : children_) {
if (o.get() == v) {
ViewPtr keep = o;
children_.assign(1, keep);
break;
}
}
}
void draw(Canvas& c) override { if (chosen_) chosen_->draw(c); }
void hits(Point p, std::vector<View*>& out) override { if (chosen_) chosen_->hits(p, out); }
private:
View* pick(const Proposal& p) {
for (auto& o : children_) {
const Size s = o->measure(Proposal{std::nullopt, p.h});
if (!p.w || s.w <= *p.w + 0.01f) return o.get();
}
return children_.back().get();
}
View* chosen_ = nullptr;
};
// ---------------------------------------------------------------- Scroll
std::map<std::string, float>& scrollCommands() {
static std::map<std::string, float> m;
return m;
}
class ScrollViewImpl : public View {
public:
ScrollViewImpl(ViewPtr content, ScrollOptions o) : opts_(std::move(o)) { addChild(std::move(content)); }
bool scrollable() const override { return true; }
bool acceptsPress() const override { return false; }
void hits(Point p, std::vector<View*>& out) override {
if (!frame_.contains(p)) return;
for (auto it = children_.rbegin(); it != children_.rend(); ++it) (*it)->hits(p, out);
out.push_back(this);
}
bool scrollBy(float dx, float dy) override {
Slot& s = UiState::instance().slot(id_);
const bool vertical = opts_.axis == Axis::Vertical;
float& pos = vertical ? s.scrollY : s.scrollX;
const float delta = vertical ? dy : dx;
const float before = pos;
const float maxScroll = vertical ? maxY_ : maxX_;
float next = pos + delta;
if (vertical && opts_.onRefresh && next < 0 && dragging_) {
pos = std::max(next, -kMaxPull); // elastic pull
} else {
pos = std::clamp(next, 0.0f, maxScroll);
}
s.stamp = UiState::instance().now;
UiState::instance().animating = true;
return pos != before || (maxScroll > 0);
}
bool onScrollWheel(float dx, float dy) override { return scrollBy(dx, dy); }
void onDragBegin(Point) override { dragging_ = true; }
void releaseDrag() override {
dragging_ = false;
Slot& s = UiState::instance().slot(id_);
if (s.scrollY <= -kRefreshThreshold && opts_.onRefresh && !opts_.refreshing) opts_.onRefresh();
}
void fling(float vx, float vy) override {
Slot& s = UiState::instance().slot(id_);
s.velX = vx;
s.velY = vy;
UiState::instance().animating = true;
}
protected:
Size compute(const Proposal& p) override {
const bool vertical = opts_.axis == Axis::Vertical;
Proposal q = vertical ? Proposal{p.w && *p.w < kInf / 2 ? std::optional<float>(*p.w - opts_.contentInset.horizontal()) : std::nullopt, std::nullopt}
: Proposal{std::nullopt, p.h && *p.h < kInf / 2 ? std::optional<float>(*p.h - opts_.contentInset.vertical()) : std::nullopt};
const Size c = children_[0]->measure(q);
const float cw = c.w + opts_.contentInset.horizontal(), ch = c.h + opts_.contentInset.vertical();
if (vertical) return {p.w ? *p.w : cw, p.h ? *p.h : ch};
return {p.w ? *p.w : cw, p.h ? *p.h : ch};
}
public:
void place(const Rect& r) override {
frame_ = r;
const bool vertical = opts_.axis == Axis::Vertical;
const Insets in = opts_.contentInset;
Proposal q = vertical ? Proposal{r.w - in.horizontal(), std::nullopt} : Proposal{std::nullopt, r.h - in.vertical()};
const Size c = children_[0]->measure(q);
const float totalW = c.w + in.horizontal(), totalH = c.h + in.vertical();
maxX_ = std::max(0.0f, totalW - r.w);
maxY_ = std::max(0.0f, totalH - r.h);
Slot& s = UiState::instance().slot(id_);
UiState& ui = UiState::instance();
float anchorShift = 0;
if (opts_.anchorBottom && vertical) {
if (!s.flag) {
s.flag = true;
s.scrollY = maxY_;
} else if (maxY_ != s.lastMax && s.lastMax - s.scrollY <= opts_.anchorThreshold) {
s.scrollY = maxY_;
}
s.lastMax = maxY_;
anchorShift = std::max(0.0f, r.h - totalH);
}
const float dt = static_cast<float>(std::clamp(ui.now - lastTick_, 0.0, 0.1));
lastTick_ = ui.now;
if (!opts_.scrollKey.empty()) {
auto it = scrollCommands().find(opts_.scrollKey);
if (it != scrollCommands().end()) {
(vertical ? s.scrollY : s.scrollX) = it->second;
scrollCommands().erase(it);
s.velX = s.velY = 0;
}
}
if (!dragging_ && dt > 0) {
if (std::fabs(s.velY) > 8 || std::fabs(s.velX) > 8) {
s.scrollY += s.velY * dt;
s.scrollX += s.velX * dt;
const float decay = std::exp(-dt * 3.2f);
s.velX *= decay;
s.velY *= decay;
ui.animating = true;
} else {
s.velX = s.velY = 0;
}
if (s.scrollY < 0 && opts_.onRefresh) {
s.scrollY += (0 - s.scrollY) * std::min(1.0f, dt * 12); // spring back
if (s.scrollY > -0.5f) s.scrollY = 0;
ui.animating = true;
}
}
const float minY = (opts_.onRefresh ? -kMaxPull : 0.0f);
s.scrollY = std::clamp(s.scrollY, (dragging_ || s.scrollY < 0) ? minY : 0.0f, maxY_);
s.scrollX = std::clamp(s.scrollX, 0.0f, maxX_);
if (vertical && !ui.navScrollSet) {
ui.navScrollSet = true;
ui.nextNavScrollY = s.scrollY;
}
children_[0]->place({r.x + in.left - s.scrollX, r.y + in.top - s.scrollY + anchorShift, c.w, c.h});
if (opts_.onGeometry && vertical) opts_.onGeometry(s.scrollY, maxY_, r.h);
}
void draw(Canvas& c) override {
c.pushClip(frame_);
View::draw(c);
c.popClip();
Slot& s = UiState::instance().slot(id_);
if (opts_.refreshing || s.scrollY < -8) {
ViewPtr spin = ProgressSpinner(20);
spin->assignIds(id_, 99);
spin->place({frame_.x + frame_.w / 2 - 10, frame_.y + 14, 20, 20});
c.pushClip(frame_);
spin->draw(c);
c.popClip();
}
if (!opts_.showsIndicator) return;
const bool vertical = opts_.axis == Axis::Vertical;
const float maxScroll = vertical ? maxY_ : maxX_;
const double age = UiState::instance().now - s.stamp;
if (maxScroll <= 0 || age > 1.2) return;
const float fade = age < 0.8 ? 1.0f : static_cast<float>(1.0 - (age - 0.8) / 0.4);
if (vertical) {
const float track = frame_.h - 8;
const float th = std::max(24.0f, track * frame_.h / (frame_.h + maxY_));
const float ty = frame_.y + 4 + (track - th) * (s.scrollY / maxY_);
c.fillRRect({frame_.right() - 5, ty, 3, th}, Corners::all(1.5f), Palette::fg2(), 0.5f * fade);
} else {
const float track = frame_.w - 8;
const float tw = std::max(24.0f, track * frame_.w / (frame_.w + maxX_));
const float tx = frame_.x + 4 + (track - tw) * (s.scrollX / maxX_);
c.fillRRect({tx, frame_.bottom() - 5, tw, 3}, Corners::all(1.5f), Palette::fg2(), 0.5f * fade);
}
if (age < 1.2) UiState::instance().animating = true;
}
private:
static constexpr float kMaxPull = 90;
static constexpr float kRefreshThreshold = 60;
ScrollOptions opts_;
float maxX_ = 0, maxY_ = 0;
bool dragging_ = false;
double lastTick_ = 0;
};
// ---------------------------------------------------------------- Button
class ButtonView : public View {
public:
ButtonView(ViewPtr label, std::function<void()> action, ButtonStyleFn style)
: label_(std::move(label)), action_(std::move(action)), style_(std::move(style)) {
children_.push_back(label_);
}
bool acceptsPress() const override { return true; }
void onTap(Point) override { if (action_ && !disabled_) action_(); }
void assignIds(std::uint64_t parent, std::uint64_t index) override {
disabled_ = Env::cur().disabled;
id_ = hasKey_ ? hashCombine(parent, hashString(key_)) : hashCombine(parent, index + 1);
const bool pressed = UiState::instance().pressedId == id_ && !disabled_;
children_.clear();
children_.push_back(style_(label_, pressed));
children_[0]->assignIds(id_, 0);
}
void hits(Point p, std::vector<View*>& out) override {
if (!frame_.contains(p)) return;
View::hits(p, out);
if (!disabled_) out.push_back(this);
}
protected:
Size compute(const Proposal& p) override { return children_[0]->measure(p); }
public:
void place(const Rect& r) override {
frame_ = r;
children_[0]->place(r);
}
private:
ViewPtr label_;
std::function<void()> action_;
ButtonStyleFn style_;
bool disabled_ = false;
};
class SpinnerView : public View {
public:
explicit SpinnerView(float size) : size_(size) {}
protected:
Size compute(const Proposal&) override { return {size_, size_}; }
public:
void draw(Canvas& c) override {
UiState::instance().animating = true;
const double t = UiState::instance().now;
const int active = static_cast<int>(std::fmod(t * 12.0, 12.0));
const Color col = Env::cur().foreground.value_or(Palette::fg2());
const float cx = frame_.x + frame_.w / 2, cy = frame_.y + frame_.h / 2;
const float outer = size_ / 2, inner = size_ * 0.28f, w = std::max(1.5f, size_ * 0.09f);
for (int i = 0; i < 12; ++i) {
const float ang = static_cast<float>(i) * 3.14159265f / 6.0f;
const int age = (active - i + 12) % 12;
const float alpha = 1.0f - static_cast<float>(age) / 12.0f * 0.85f;
for (int s = 0; s <= 6; ++s) {
const float r = inner + (outer - inner) * (static_cast<float>(s) / 6.0f);
const float x = cx + std::sin(ang) * r, y = cy - std::cos(ang) * r;
c.fillRRect({x - w / 2, y - w / 2, w, w}, Corners::all(w / 2), col, alpha);
}
}
}
private:
float size_;
};
} // namespace
void setDefaultLinkHandler(LinkHandler handler) { g_linkHandler = std::move(handler); }
void invokeLinkHandler(const std::string& url) { g_linkHandler(url); }
ViewPtr Text(const std::string& text) { return std::make_shared<TextView>(std::vector<StyledSpan>{StyledSpan{text, {}, {}, false, false, {}, {}}}); }
ViewPtr RichText(std::vector<StyledSpan> spans) { return std::make_shared<TextView>(std::move(spans)); }
ViewPtr Icon(const std::string& symbol, float size) { return std::make_shared<IconView>(symbol, size); }
ViewPtr ImageView(std::function<BitmapPtr()> provider, ContentMode mode, ViewPtr placeholder) {
return std::make_shared<ImageViewImpl>(std::move(provider), mode, std::move(placeholder));
}
ViewPtr BitmapView(BitmapPtr bitmap) {
return std::make_shared<ImageViewImpl>([bitmap] { return bitmap; }, ContentMode::Fit, nullptr);
}
ViewPtr RectangleShape(Color fill) { auto s = std::make_shared<ShapeView>(ShapeView::Kind::Rect, 0); s->fill = fill; return s; }
ViewPtr RoundedRectShape(float radius, Color fill) { auto s = std::make_shared<ShapeView>(ShapeView::Kind::Round, radius); s->fill = fill; return s; }
ViewPtr CircleShape(Color fill) { auto s = std::make_shared<ShapeView>(ShapeView::Kind::Circle, 0); s->fill = fill; return s; }
ViewPtr CapsuleShape(Color fill) { auto s = std::make_shared<ShapeView>(ShapeView::Kind::Capsule, 0); s->fill = fill; return s; }
ViewPtr GradientRoundedRect(float radius, Color from, Color to, Point start, Point end) {
auto s = std::make_shared<ShapeView>(ShapeView::Kind::Round, radius);
s->gradient = std::make_pair(from, to);
s->gradStart = start;
s->gradEnd = end;
return s;
}
ViewPtr GradientCircle(Color from, Color to, Point start, Point end) {
auto s = std::make_shared<ShapeView>(ShapeView::Kind::Circle, 0);
s->gradient = std::make_pair(from, to);
s->gradStart = start;
s->gradEnd = end;
return s;
}
ViewPtr StrokedRoundedRect(float radius, Color color, float width, float opacity) {
auto s = std::make_shared<ShapeView>(ShapeView::Kind::Round, radius);
s->stroke = color;
s->strokeWidth = width;
s->strokeOpacity = opacity;
return s;
}
ViewPtr Spacer(float minLength) { return std::make_shared<SpacerView>(minLength); }
ViewPtr Divider(Color color, float thickness) { return std::make_shared<DividerView>(color, thickness); }
ViewPtr VStack(std::vector<ViewPtr> children, float spacing, HAlign align) {
const float a = align == HAlign::Leading ? 0.0f : align == HAlign::Center ? 0.5f : 1.0f;
return std::make_shared<StackView>(Axis::Vertical, std::move(children), spacing, a);
}
ViewPtr HStack(std::vector<ViewPtr> children, float spacing, VAlign align) {
const float a = align == VAlign::Top ? 0.0f : align == VAlign::Center ? 0.5f : 1.0f;
return std::make_shared<StackView>(Axis::Horizontal, std::move(children), spacing, a);
}
ViewPtr ZStack(std::vector<ViewPtr> children, Alignment align) { return std::make_shared<ZStackView>(std::move(children), align); }
ViewPtr EmptyView() { return std::make_shared<EmptyViewImpl>(); }
ViewPtr Group(std::vector<ViewPtr> children) { return std::make_shared<GroupView>(std::move(children)); }
ViewPtr ViewThatFits(std::vector<ViewPtr> options) { return std::make_shared<ViewThatFitsImpl>(std::move(options)); }
ViewPtr ScrollView(ViewPtr content, ScrollOptions options) { return std::make_shared<ScrollViewImpl>(std::move(content), std::move(options)); }
void ScrollCommand::toTop(const std::string& key) { scrollCommands()[key] = 0; }
void ScrollCommand::toOffset(const std::string& key, float y) { scrollCommands()[key] = y; }
ViewPtr Button(ViewPtr label, std::function<void()> action, ButtonStyleFn style) {
return std::make_shared<ButtonView>(std::move(label), std::move(action), std::move(style));
}
ViewPtr Button(const std::string& title, std::function<void()> action, ButtonStyleFn style) {
return Button(Text(title), std::move(action), std::move(style));
}
ButtonStyleFn ButtonStyles::automatic() {
return [](ViewPtr label, bool pressed) { return label->foreground(Palette::accent())->opacity(pressed ? 0.4f : 1.0f); };
}
ButtonStyleFn ButtonStyles::plain() {
return [](ViewPtr label, bool pressed) { return label->opacity(pressed ? 0.55f : 1.0f); };
}
ButtonStyleFn ButtonStyles::form() {
return [](ViewPtr label, bool pressed) {
return label->maxWidth(Alignment::leading())->foreground(pressed ? Palette::gray() : Palette::fg1());
};
}
ButtonStyleFn ButtonStyles::accentGradient(bool circle) {
return [circle](ViewPtr label, bool pressed) {
ViewPtr padded = label->weight(Weight::Semibold)->padding(Insets::symmetric(16, 12));
ViewPtr bg = circle ? GradientCircle(Palette::agStart(), Palette::agEnd(), {0, 0}, {1, 1})
: GradientRoundedRect(14, Palette::agStart(), Palette::agEnd(), {0, 0}, {1, 1});
bg = bg->opacity(pressed ? 0.7f : 1.0f);
ViewPtr v = padded->foreground(Palette::onGradient())->background(bg);
v = v->shadow(Palette::accent().opacity(0.5f), 5, 0, 0, circle ? Corners::all(1000) : Corners::all(14));
return v->scale(pressed ? 0.95f : 1.0f);
};
}
ButtonStyleFn ButtonStyles::none() {
return [](ViewPtr label, bool) { return label; };
}
ViewPtr ProgressSpinner(float size) { return std::make_shared<SpinnerView>(size); }
} // namespace dp::ui