-
Notifications
You must be signed in to change notification settings - Fork 2
/
widget_menu.c
81 lines (72 loc) · 1.57 KB
/
widget_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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "termio.h"
struct Menuwidget{
int x,y,choice;
const Menudata *data;
};
Menuwidget* menu_make(int basex,int basey,const Menudata *data){
Menuwidget *mw=malloc(sizeof(Menuwidget));
if(!mw)return NULL;
mw->x=basex;
mw->y=basey;
mw->choice=0;
mw->data=data;
menu_redraw(mw);
return mw;
}
void menu_destroy(Menuwidget *mw){
assert(mw);
free(mw);
}
void menu_redraw(Menuwidget *mw){
assert(mw);
for(int i=0;i<mw->data->nitems;i++){
moveto(mw->x,mw->y+i);
tprintf("> %s",mw->data->items[i].text);
if(mw->data->items[i].hotkey!='\0'){
tputc(' ');
tputc('(');
setbold(true);
tputc(mw->data->items[i].hotkey);
setbold(false);
tputc(')');
}
}
moveto(mw->x,mw->y+mw->choice);
}
Menukey menu_handlekey(Menuwidget *mw,int key){
switch(key){
case 'k': case KEY_UP:
if(mw->choice>0){
mw->choice--;
menu_redraw(mw);
} else bel();
return MENUKEY_HANDLED;
case 'j': case KEY_DOWN:
if(mw->choice<mw->data->nitems-1){
mw->choice++;
menu_redraw(mw);
} else bel();
return MENUKEY_HANDLED;
case '\n':
if(mw->data->items[mw->choice].func){
mw->data->items[mw->choice].func(mw->choice);
return MENUKEY_CALLED;
} else return MENUKEY_QUIT;
default: {
int i;
for(i=0;i<mw->data->nitems;i++){
if(mw->data->items[i].hotkey==key)break;
}
if(i==mw->data->nitems)return MENUKEY_IGNORED;
else {
mw->choice=i;
if(mw->data->items[i].func==NULL)return MENUKEY_QUIT;
mw->data->items[i].func(i);
return MENUKEY_CALLED;
}
}
}
}