console_command.cpp 1.78 KB
Newer Older
Florian Oetke's avatar
Florian Oetke committed
1
2
3
4
#include <mirrage/utils/console_command.hpp>

#include <mirrage/utils/log.hpp>
#include <mirrage/utils/ranges.hpp>
5
#include <mirrage/utils/small_vector.hpp>
Florian Oetke's avatar
Florian Oetke committed
6
7
8
9
10
11
12


namespace mirrage::util {
	Console_command_container::~Console_command_container()
	{
		auto& cmds = all_commands();
		for(auto iter = cmds.begin(); iter != cmds.end();) {
13
14
			if(std::find(_command_ids.begin(), _command_ids.end(), iter->second->id())
			   != _command_ids.end()) {
Florian Oetke's avatar
Florian Oetke committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
				iter = cmds.erase(iter);
			} else {
				iter++;
			}
		}
	}
	auto Console_command_container::call(std::string_view cmd) -> bool
	{
		auto arg_sep      = cmd.find(" ");
		auto cmd_name     = std::string(cmd.substr(0, arg_sep));
		auto [begin, end] = all_commands().equal_range(cmd_name);

		if(begin == end) {
			LOG(plog::error) << "Unknown console command: " << cmd_name;
			return false;
		}

32
33
34
35
36
		auto commands = util::small_vector<Console_command*, 1>();
		for(auto& [key, value] : util::range(begin, end)) {
			commands.emplace_back(value.get());
		}

37
		auto args = arg_sep != std::string::npos ? cmd.substr(arg_sep) : std::string_view{};
Florian Oetke's avatar
Florian Oetke committed
38

39
40
41
42
		for(auto&& cmd : commands) {
			LOG(plog::debug) << "CMD Call " << cmd << " to " << cmd->id();
			cmd->call(args);
		}
Florian Oetke's avatar
Florian Oetke committed
43
44
45
46
47
48
49
50
51
52
53

		return true;
	}

	auto Console_command_container::complete(std::string_view input) -> std::vector<Console_command*>
	{
		auto cmd = input.substr(0, input.find(" "));

		auto matches = std::vector<Console_command*>();
		for(auto&& [key, value] : all_commands()) {
			if(cmd.size() <= key.size() && std::string_view(key.c_str(), cmd.size()) == cmd) {
54
				matches.emplace_back(value.get());
Florian Oetke's avatar
Florian Oetke committed
55
56
57
			}
		}

58
59
60
		std::sort(
		        begin(matches), end(matches), [](auto& lhs, auto& rhs) { return lhs->name() < rhs->name(); });

Florian Oetke's avatar
Florian Oetke committed
61
62
63
		if(matches.size() > 5)
			matches.resize(5);

Florian Oetke's avatar
Florian Oetke committed
64
65
66
		return matches;
	}
} // namespace mirrage::util