Website Summary Files Commits Branches @commit @diff @stats
path: root / src / Generic / ConsoleInterface / Menu.cpp
blob: c6e842a3fce0963674f730323b990906a2d2ab39 (plain) (blame)
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
#include "Menu.h"
#include "Toolbox.hpp"
#include <cstring>

Menu::Menu() : menuOptions() {}

unsigned indexOfCommandEnd(char* str) {
	unsigned ind = 0;
	std::cout << str[ind] << std::endl;
	
	return ind;
}

void Menu::addCommand(const Command& command) {
	menuOptions.add(command);
}

/*!
 * Prints the title, then an Error/Warning/Sucess message (if set),
 * prints all command names as an ordered list (starting from 1),
 * waits for user input to select one of those commands (by list number)
 * and finally executes the appropriate command's run() function.
 *
 * After the run() function exists, everything is reprinted.
 * The 0 list index is always "Go Back"/"Exit" and it always stops the reprinting loop.
 *
 * If there are no commands, prints "Menu is empty!".
 * If user input doesn't correspond to any command, registers an error message and reprints.
 */
void Menu::navigate() const {
	if (menuOptions.get_count() == 0) {
		printLine("Menu is empty!");
		return;
	}

	char buffer[MAX_LINE_WIDTH];
	unsigned startIndex = 0;

	while (strncmp(buffer, "quit", 4) != 0) {
		startIndex = 0;
		inputLineBox("> ", buffer, MAX_LINE_WIDTH);

		while (buffer[startIndex] == ' ') startIndex++;

		unsigned commandEnd = startIndex;
		while (buffer[commandEnd] != ' ' && buffer[commandEnd] != '\n' && buffer[commandEnd] != '\0')
			commandEnd++;

		unsigned index = menuOptions.get_count();
		std::cout << commandEnd << std::endl;
		for (unsigned i = 0; i < menuOptions.get_count(); i++) {
			if (strncmp(buffer, menuOptions[i].get_name(), commandEnd) == 0) {
				index = i;
				break;
			}
		}
		std::cout << menuOptions.get_count() << " " << index << std::endl;

		if (index == menuOptions.get_count()) {
			printLine("Invalid menu option!");
			continue;
		}

		menuOptions[index].run(buffer + startIndex + commandEnd);
	}
}