-
Notifications
You must be signed in to change notification settings - Fork 0
/
menu.c
110 lines (93 loc) · 2.88 KB
/
menu.c
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <curses.h>
#include "menu.h"
#include "keys.h"
#define CHOICE_STR "->"
#define CLEAR_CHOICE_STR " "
#define PAUSE_STR " PAUSED "
#define CHOICE_STR_LEN (sizeof(CHOICE_STR)-1)
#define PAUSE_STR_LEN (sizeof(PAUSE_STR)-1)
/* Creates a window centered in the terminal. */
WINDOW* createCenteredWindow(int width, int height);
/* Draws the window, including all the choices and the current choice
* indicator. */
void drawChoices(WINDOW* win, char* title, int choiceCount, int currentChoice,
char** choices);
int menu_choice(char* title, int choiceCount, char** choices) {
int winHeight, winWidth, i, choice, c;
bool chosen;
size_t longestChoice;
WINDOW* menuWin;
winHeight = choiceCount + 1 /* for the title bar */ +
2 /* for the top and bottom bar */;
longestChoice = 0;
for (i = 0; i < choiceCount; i++) {
size_t newLen = strlen(choices[i]);
if (newLen > longestChoice) {
longestChoice = newLen;
}
}
winWidth = (int)(longestChoice + CHOICE_STR_LEN * 2 + 2);
menuWin = createCenteredWindow(winHeight, winWidth);
// drawing
choice = 0;
chosen = false;
while (!chosen) {
drawChoices(menuWin, title, choiceCount, choice, choices);
c = getch();
switch (c) {
case KEY_ENTER:
chosen = true;
break;
case KEY_UP:
if (choice > 0) {
choice--;
}
break;
case KEY_DOWN:
if (choice < choiceCount-1) {
choice++;
}
break;
}
}
delwin(menuWin);
if (chosen) {
return choice;
} else {
return -1;
}
}
void menu_pauseMenu() {
int winHeight = 3; // height of a line plus a padding
int winWidth = PAUSE_STR_LEN + 2;
WINDOW* pauseWin = createCenteredWindow(winHeight, winWidth);
mvwprintw(pauseWin, 1, 1, PAUSE_STR);
box(pauseWin, 0, 0);
wrefresh(pauseWin);
while (getch() != KEY_PAUSE) {}
delwin(pauseWin);
}
WINDOW* createCenteredWindow(int height, int width) {
int termWidth = 0, termHeight = 0;
getmaxyx(stdscr, termHeight, termWidth);
return newwin(height, width, (termHeight-height)/2, (termWidth-width)/2);
}
void drawChoices(WINDOW* win, char* title, int choiceCount, int currentChoice,
char** choices) {
int winWidth, winHeight, i;
getmaxyx(win, winHeight, winWidth);
box(win, 0, 0);
mvwprintw(win, 1, (winWidth-(int)strlen(title))/2, title);
for (i = 0; i < choiceCount; i++) {
mvwprintw(win, i+2, CHOICE_STR_LEN+1, choices[i]);
if (i == currentChoice) {
mvwprintw(win, i+2, 1, CHOICE_STR);
} else {
mvwprintw(win, i+2, 1, CLEAR_CHOICE_STR);
}
}
wrefresh(win);
}