steering-wheel-rpi/src/widgets.cpp
2022-05-19 20:09:59 +02:00

75 lines
2.1 KiB
C++

#include "widgets.h"
#include "util.h"
#include <SDL2/SDL_image.h>
#include <fmt/format.h>
#include <stdexcept>
Widget::Widget(SDL_Renderer* renderer, SDL_Rect rect)
: renderer{renderer}, dest_rect{rect} {}
void Widget::update_rect(SDL_Rect new_rect) { dest_rect = new_rect; }
TextureWidget::TextureWidget(SDL_Renderer* renderer, SDL_Rect dest_rect,
std::optional<SDL_Texture*> texture)
: Widget{renderer, dest_rect}, texture{texture} {}
TextureWidget::~TextureWidget() {
if (texture) {
SDL_DestroyTexture(*texture);
texture = nullptr;
}
}
void TextureWidget::draw() {
if (texture) {
SDL_RenderCopy(renderer, *texture, NULL, &dest_rect);
}
}
void TextureWidget::update_texture(SDL_Texture* new_texture) {
if (texture) {
SDL_DestroyTexture(*texture);
}
texture = new_texture;
}
ImageWidget::ImageWidget(SDL_Renderer* renderer, SDL_Rect dest_rect,
const std::string& path)
: TextureWidget{renderer, dest_rect, util::load_img(renderer, path)} {}
TextWidget::TextWidget(SDL_Renderer* renderer, SDL_Rect dest_rect,
const std::string& font_path,
const std::string& initial_text)
: TextureWidget{renderer, dest_rect, std::nullopt},
font{util::load_font(font_path, 28)}, text{initial_text} {
if (text != "") {
update_texture(generate_text(text));
}
}
TextWidget::~TextWidget() { TTF_CloseFont(font); }
void TextWidget::update_text(const std::string& new_text) {
if (text != new_text) {
update_texture(generate_text(new_text));
text = new_text;
}
}
SDL_Texture* TextWidget::generate_text(const std::string& text) {
SDL_Surface* surf =
TTF_RenderText_Solid(font, text.c_str(), {0xFF, 0xFF, 0XFF, 0xFF});
if (surf == nullptr) {
throw std::runtime_error(
fmt::format("Unable to render text surface: {}", TTF_GetError()));
}
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surf);
if (texture == nullptr) {
throw std::runtime_error(fmt::format(
"Unable to create texture from text surface: {}", SDL_GetError()));
}
return texture;
}