aboutsummaryrefslogtreecommitdiff
path: root/src/engine/graphics/component_renderer.cpp
blob: eb024bc05cd6057fba4d4825de5dc7c47703796f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "component_renderer.hpp"

#include "engine/escape.hpp"
#include "util/color.hpp"

#include <fmt/core.h>

#include <iostream>
#include <utility>

ComponentRenderer::ComponentRenderer(
	std::shared_ptr<ICursorController> cursor_controller) noexcept
	: _cursor_controller(std::move(cursor_controller))
{
}

void ComponentRenderer::render(
	const std::shared_ptr<IComponent> &component,
	const Vector2 &position) noexcept
{
	const auto previous_pos = _cursor_controller->where();

	_cursor_controller->hide();
	_cursor_controller->move_to(position);

	_use_component_colors(component);

	const auto component_matrix = component->get();

	for (const auto &row : *component_matrix)
	{
		for (const auto &element : row)
		{
			if (element.style.reset_before)
			{
				fmt::print(RESET_ALL_MODES, fmt::arg("esc", ESC));
				_use_component_colors(component);
			}

			const auto opt_element_fg_color = element.style.fg_color;
			const auto opt_element_bg_color = element.style.bg_color;

			if (opt_element_fg_color.has_value())
			{
				fmt::print("{}", get_foreground_esc_seq(opt_element_fg_color.value()));
			}

			if (opt_element_bg_color.has_value())
			{
				fmt::print("{}", get_background_esc_seq(opt_element_bg_color.value()));
			}

			if (element.style.bold)
			{
				fmt::print(SET_BOLD_MODE, fmt::arg("esc", ESC));
			}

			std::cout.put(element.value);
		}

		const auto current_pos = _cursor_controller->where();

		_cursor_controller->move_to(
			Vector2({.x = previous_pos.get_x(), .y = current_pos.get_y() - 1}));
	}

	fmt::print(RESET_ALL_MODES, fmt::arg("esc", ESC));

	std::cout.flush();

	_cursor_controller->move_to(previous_pos);
	_cursor_controller->show();
}

void ComponentRenderer::_use_component_colors(
	const std::shared_ptr<IComponent> &component) noexcept
{
	const auto foreground_color = component->get_foreground_color();
	const auto background_color = component->get_background_color();

	fmt::print(
		"{}{}",
		get_background_esc_seq(background_color),
		get_foreground_esc_seq(foreground_color));
}