Select items and multi-valued menus
Adapted from Writing Programs with NCURSES, by Eric S. Raymond and Zeyd M. Ben-Halim and NCURSES Programming HOWTO, by Pradeep Padala.
Menus may be multi-valued or (the default) single-valued (see the manual page menu_opts(3X) to see how to change the default). Both types always have a current item.
From a single-valued menu you can read the selected value simply by looking at the current item. From a multi-valued menu, you get the selected set by looping through the items applying the item_value() predicate function. Your menu-processing code can use the function set_item_value() to flag the items in the select set.
Switch off the option O_ONEVALUE and the menu becomes multi-valued: the user can select more than one item, with the request REQ_TOGGLE_ITEM.
Example: Multi Valued Menus example
#include <stdlib.h>#include <string.h>#include <curses.h>#include <menu.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))#define CTRLD 4
const char *choices[] = { "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Choice 5", "Choice 6", "Choice 7", "Exit",};
intmain(void){ int c; int n_choices, i;
n_choices = ARRAY_SIZE(choices); if ((my_items = calloc((size_t) (n_choices + 1), perror("my_items"); return EXIT_FAILURE; }
/* Initialize curses */
/* Initialize items */ for (i = 0; i < n_choices; ++i)
/* Make the menu multi valued */
"<ENTER> to see presently selected items(F1 to Exit)");
switch (c) { break; break; case ' ': break; case 10: /* Enter */ { char temp[200];
temp[0] = '\0'; strcat(temp, " "); } break; } } }
for (i = 0; i < n_choices; ++i)}In a multi-valued menu, the user should be allowed to select or deselect more than one item. The request REQ_TOGGLE_ITEM toggles the present selection. In this example, pressing space sends REQ_TOGGLE_ITEM to menu_driver().
When the user presses Enter, the program shows the items presently selected. First it finds the items associated with the menu using the function menu_items(). Then it loops through the items to find out whether each one is selected. The function item_value() returns TRUE if an item is selected. The function item_count() returns the number of items in the menu. The item name can be found with item_name(). You can also find the description associated with an item using item_description().