Search code examples
crubymenuncursesuser-interaction

Ncurses: how to refresh a menu without losing current position?


How can I reload the data in a menu without losing the current position?

For example, when a user "selects" an item, and an action is performed that changes the data. (Either updating the item, removing it, or adding a new item to the menu.) I'd like to reload the menu but still keep the cursor on the item that was just selected. What's the best way to do this?


For reference, this question seemed very close, but I don't think it covers the add/remove issue: How to replace a string menu item in ncurses & C

This question also seemed similar, but was too specific for me: Ncurses menu - remembering selection


Solution

  • If you rebuild a menu, your program will have to keep track of what was the "current" item before, and find that before resuming its reads via getch. The getch function refreshes the screen, and the position which your program has set for the getch becomes the apparent cursor position.

    Normally you would use item_index to ask the menu library which is the current item, and set_current_item to tell the menu-library which item the cursor would be on, but it's possible to do your calls to getch "anywhere" on the screen. Likewise, if you rebuild a menu, that index information may be stale.

    Without some specific sample program, there's only general advice which can be offered.