ASDV-Cpp/Assignments/MP6_CalebFontenot/simpleMenu.cpp

78 lines
2.2 KiB
C++

2024-04-24 10:49:28 +07:00
//
// Created by caleb on 3/16/24.
//
#include <vector>
#include <iostream>
#include <ncurses.h>
#include "simpleMenu.h"
/*
* Code ported over from my MP2 Project that generates a menu,
* except now it's been modified so that it has a generic interface.
* 4/12/2024 Update: It now has an option to display a menu title.
*/
int simpleMenu(std::vector<std::string>& menuItems, std::string menuTitle) {
static int selection = 0;
static int *selectionPointer = &selection;
initscr();
raw();
keypad(stdscr, TRUE);
noecho();
//clear();
int ch;
do {
switch (ch) {
case KEY_UP:
--selection;
break;
case KEY_DOWN:
++selection;
break;
case '\n':
getch();
endwin();
return selection;
break;
default:
break;
}
// Ensure selection stays within bounds
selection = (selection < 0) ? (menuItems.size() - 1) : selection;
selection = (selection > (menuItems.size() - 1)) ? 0 : selection;
clear();
move(0, 0);
printw("%s", printMenu(selectionPointer, menuItems, menuTitle).c_str());
refresh();
} while ((ch = getch()) != '#');
getch();
endwin();
exit(0);
}
std::string printMenu(const int *selection, std::vector<std::string>& menu, std::string menuTitle) {
std::string outputString = "";
std::vector<std::string> cursor = {"> "};
// append empty space to cursor var
for (int i = 0; i < (menu.size() - 1); ++i) {
cursor.emplace_back(" ");
}
std::string temp;
for (int j = 0; j < *selection; ++j) {
temp = cursor[j];
cursor[j] = cursor[j + 1];
cursor[j + 1] = temp;
}
//cursor[0] = temp;
outputString.append(menuTitle);
outputString.append("\nUse the arrow keys to navigate the menu. Press # to exit.\n");
for (int i = 0; i < menu.size(); ++i) {
outputString.append(cursor[i]);
outputString.append(menu[i]);
outputString.append("\n");
}
outputString.append("Current Selection: ").append(std::to_string(*selection)).append("\n");
return outputString;
}