ASDV-Cpp/Assignments/MP3_CalebFontenot/simpleMenu.cpp

75 lines
2.0 KiB
C++

//
// 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.
*/
int simpleMenu(std::vector<std::string> menuItems) {
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;
//std::system("clear");
move(0, 0);
printw("%s", printMenu(selectionPointer, menuItems).c_str());
refresh();
} while ((ch = getch()) != '#');
getch();
endwin();
exit(0);
}
std::string printMenu(int *selection, std::vector<std::string> menu) {
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("Use 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");
}
return outputString;
}