Dawn/src/dawn/scene/components/ui/text/UIRichTextLabel.cpp
2023-06-14 21:14:52 -07:00

82 lines
2.3 KiB
C++

// Copyright (c) 2023 Dominic Masters
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include "UIRichTextLabel.hpp"
#include "game/DawnGame.hpp"
using namespace Dawn;
UIRichTextLabel::UIRichTextLabel(SceneItem *item) :
UILabel(item)
{
}
void UIRichTextLabel::onStart() {
UILabel::onStart();
useEffect([&]{
std::vector<struct UILabelStyle> styleStack;
struct UILabelStyle current;
styleStack.push_back(current);
std::vector<struct UILabelText> bufferTexts;
std::function<void(Xml*)> parseChildren = [&](Xml *node) {
if(node->children.empty()) {
struct UILabelText text;
text.style = current;
text.text = node->value;
bufferTexts.push_back(text);
} else {
auto itNode = node->children.begin();
while(itNode != node->children.end()) {
auto child = *itNode;
assertTrue(child->node == "font");
struct UILabelStyle style;
if(child->attributes.contains("font")) {
style.font = this->getGame()->assetManager.get<NewTrueTypeAsset>(child->attributes["font"]);
} else {
style.font = current.font;
}
if(child->attributes.contains("size")) {
style.size = std::stoi(child->attributes["size"]);
} else {
style.size = current.size;
}
if(child->attributes.contains("style")) {
std::string s = child->attributes["style"];
style.style = 0;
if(s.find("bold") != std::string::npos) style.style |= NEW_TRUETYPE_VARIANT_BOLD;
if(s.find("italic") != std::string::npos) style.style |= NEW_TRUETYPE_VARIANT_ITALICS;
} else {
style.style = current.style;
}
if(child->attributes.contains("color")) {
style.color = Color::fromString(child->attributes["color"]);
} else {
style.color = current.color;
}
styleStack.push_back(style);
current = style;
parseChildren(child);
styleStack.pop_back();
current = styleStack.back();
++itNode;
}
}
};
auto root = Xml::load("<root>" + ((std::string)this->richText) + "</root>");
parseChildren(&root);
this->rebufferQuads(bufferTexts);
}, this->richText)();
}