diff --git a/libui/CMakeLists.txt b/libui/CMakeLists.txt index 479ee00c..04dcfcdc 100644 --- a/libui/CMakeLists.txt +++ b/libui/CMakeLists.txt @@ -16,6 +16,7 @@ set(SOURCES src/Alignment.cpp src/Container.cpp src/Button.cpp + src/Label.cpp ) add_library(ui ${SOURCES}) diff --git a/libui/include/ui/Label.h b/libui/include/ui/Label.h new file mode 100644 index 00000000..b435e1c9 --- /dev/null +++ b/libui/include/ui/Label.h @@ -0,0 +1,41 @@ +/** + * @file Label.h + * @author apio (cloudapio.eu) + * @brief A simple one-line text widget. + * + * @copyright Copyright (c) 2023, the Luna authors. + * + */ + +#pragma once +#include +#include +#include + +namespace ui +{ + /** + * @brief Displays one line of text. + * + * This component does not handle newlines. + */ + class Label final : public Widget + { + public: + Label(StringView text, VerticalAlignment valign = VerticalAlignment::Center, + HorizontalAlignment halign = HorizontalAlignment::Center, SharedPtr font = Font::default_font()); + + void set_text(StringView text) + { + m_text = text; + } + + Result draw(Canvas& canvas) override; + + private: + StringView m_text; + VerticalAlignment m_valign; + HorizontalAlignment m_halign; + SharedPtr m_font; + }; +} diff --git a/libui/src/Label.cpp b/libui/src/Label.cpp new file mode 100644 index 00000000..67226eda --- /dev/null +++ b/libui/src/Label.cpp @@ -0,0 +1,36 @@ +/** + * @file Label.cpp + * @author apio (cloudapio.eu) + * @brief A simple one-line text widget. + * + * @copyright Copyright (c) 2023, the Luna authors. + * + */ + +#include +#include + +namespace ui +{ + Label::Label(StringView text, VerticalAlignment valign, HorizontalAlignment halign, SharedPtr font) + : m_text(text), m_valign(valign), m_halign(halign), m_font(font) + { + } + + Result Label::draw(Canvas& canvas) + { + ui::Rect contained; + contained.pos = { 0, 0 }; + contained.width = static_cast(m_text.length() * m_font->width()); + contained.height = m_font->height(); + auto subcanvas = + canvas.subcanvas(ui::align({ 0, 0, m_rect.width, m_rect.height }, contained, m_valign, m_halign)); + + Utf8StringDecoder decoder(m_text.chars()); + wchar_t buf[4096]; + TRY(decoder.decode(buf, sizeof(buf))); + + m_font->render(buf, ui::BLACK, subcanvas); + return {}; + } +}