Refer the below code.
#include <iostream>
#include <vector>
#include <string>
#include <ncurses.h>
#include <unistd.h>
struct MenuItem
{
std::string text;
std::string path;
};
void renderMenu(const std::vector<MenuItem> &menu, int selected)
{
clear();
for (int i = 0; i < menu.size(); ++i)
{
if (i == selected)
{
attron(A_REVERSE);
}
mvprintw(i + 1, 1, menu[i].text.c_str());
attroff(A_REVERSE);
}
refresh();
}
int main()
{
// Initialize ncurses
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
// Define menu items
std::vector<MenuItem> menu = {
{"Item 1", "/path1"},
{"Item 2", "/path2"},
{"Item 3", "/path3"},
// Add more items as needed
};
int currentSelection = 0;
int key;
do
{
renderMenu(menu, currentSelection);
key = getch();
switch (key)
{
case KEY_UP:
currentSelection = std::max(0, currentSelection - 1);
break;
case KEY_DOWN:
currentSelection = std::min(static_cast<int>(menu.size() - 1), currentSelection + 1);
break;
case 10: // Enter key
// Perform action associated with the selected item (change directory and exit)
if (chdir(menu[currentSelection].path.c_str()) == 0)
{
endwin(); // End ncurses mode before executing new shell
execlp("zsh", "zsh", nullptr); // Start a new shell in the new directory
std::cerr << "Error executing new shell." << std::endl;
return 1;
}
else
{
std::cerr << "Error changing directory." << std::endl;
}
break;
}
} while (key != 27); // Exit when the user presses the Esc key
// Cleanup
endwin();
return 0;
}