aboutsummaryrefslogtreecommitdiff
path: root/src/engine/user/cursor.cpp
blob: 2a72663dbb71598564251b157d6b1c6aa624d1ab (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
86
87
88
89
90
91
92
#include "cursor.hpp"

#include "engine/escape.hpp"

#include <cstdlib>
#include <iostream>

CursorController::CursorController() noexcept : _position({.x = 0, .y = 0}) {}

void CursorController::move(const Vector2 &direction, const uint32_t &amount) noexcept
{
	auto direction_format = direction_format_map.at(direction);

	fmt::print(fmt::runtime(direction_format.data()), fmt::arg("esc", ESC),
			   fmt::arg("amount", amount));
	std::cout.flush();

	_position = _position.to_direction(direction, static_cast<Vector2::Value>(amount));

	notify_subscribers(CursorEvent::POSITION_CHANGE, _position);
}

void CursorController::move_to(const Vector2 &position, bool silent) noexcept
{
	fmt::print(MOVE_CURSOR_TO, fmt::arg("esc", ESC), fmt::arg("row", position.get_y()),
			   fmt::arg("column", position.get_x()));
	std::cout.flush();

	_position = position;

	if (!silent)
	{
		notify_subscribers(CursorEvent::POSITION_CHANGE, position);
	}
}

Vector2 CursorController::where() const noexcept
{
	return _position;
}

void CursorController::ensure_position() noexcept
{
	fmt::print(REQUEST_CURSOR_POSITION, fmt::arg("esc", ESC));
	std::cout.flush();

	Vector2Options vector2_options = {};

	// NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
	scanf("\033[%u;%uR", &vector2_options.y, &vector2_options.x);

	_position = Vector2(vector2_options);

	notify_subscribers(CursorEvent::POSITION_CHANGE, _position);
}

void CursorController::hide() noexcept
{
	fmt::print(CURSOR_INVISIBLE, fmt::arg("esc", ESC));
	std::cout.flush();
}

void CursorController::show() noexcept
{
	fmt::print(CURSOR_VISIBLE, fmt::arg("esc", ESC));
	std::cout.flush();
}

void CursorController::subscribe(const Event &event,
								 const Subscriber &subscriber) noexcept
{
	if (_subscribers.count(event) == 0)
	{
		_subscribers.insert({event, std::vector<Subscriber>()});
	}

	_subscribers.at(event).push_back(subscriber);
}

void CursorController::notify_subscribers(const Event &event,
										  const Context &context) const noexcept
{
	if (_subscribers.count(event) == 0)
	{
		return;
	}

	for (const auto &subscriber : _subscribers.at(event))
	{
		subscriber->update(context);
	}
}