dorne/cli/curse.c

103 lines
2.2 KiB
C
Raw Normal View History

2025-09-10 22:49:05 +10:00
#include <locale.h>
#include <unistd.h>
#include "curse.h"
#define BASE_DELAY 1000000
#define CRS_LOCALE "en_US.UTF-8"
/* Set ncurses terminal mode (buffering, character processing,
* Key->SIG handling, and other termios(3) functionality).
*/
2025-09-11 17:37:01 +10:00
int termmode(const enum crs_termmode mode) {
2025-09-10 22:49:05 +10:00
switch (mode) {
2025-09-10 23:05:07 +10:00
case TMODE_CBREAK:
2025-09-10 22:49:05 +10:00
return cbreak();
2025-09-10 23:05:07 +10:00
case TMODE_RAW:
2025-09-10 22:49:05 +10:00
return raw();
2025-09-10 23:05:07 +10:00
case TMODE_NOCBREAK:
2025-09-10 22:49:05 +10:00
return nocbreak();
2025-09-10 23:05:07 +10:00
case TMODE_NORAW:
2025-09-10 22:49:05 +10:00
return noraw();
2025-09-11 17:37:01 +10:00
default:
2025-09-10 22:49:05 +10:00
/* defaulting is not possible. */
2025-09-11 17:37:01 +10:00
return 1;
2025-09-10 22:49:05 +10:00
}
}
/* Initialise ncurses for our usecase.
* WARNING: This function should only be called once.
*/
2025-09-11 17:37:01 +10:00
void init_ncurses(void) {
2025-09-10 22:49:05 +10:00
// ncurses expects a locale for consistent behaviour
setlocale(LC_ALL, CRS_LOCALE);
/* NCurses Init */
start_color();
/* Screen Configuration */
2025-09-10 23:05:07 +10:00
termmode(TMODE_CBREAK);
noecho(); // manually echo from getch(3x)
2025-09-10 22:49:05 +10:00
curs_set(0); // hide cursor
}
2025-09-10 23:05:07 +10:00
/* Apply a default IO configuration for an ncurses WINDOW.
*/
2025-09-11 17:37:01 +10:00
static inline void __conf_window(WINDOW *const win) {
nodelay(win, TRUE); // getch(3x) nonblocking IO
keypad(win, TRUE); // allow function keys
// intrflush(3x) - flush terminal input buffer on interrupt key
intrflush(win, FALSE);
2025-09-10 23:05:07 +10:00
}
2025-09-11 17:37:01 +10:00
/* Initialise (with default IO configuration) a new ncurses WINDOW.
2025-09-10 23:05:07 +10:00
*/
2025-09-11 17:37:01 +10:00
WINDOW *new_window(const int x, const int y, const int width,
const int height) {
2025-09-10 23:05:07 +10:00
WINDOW *win = newwin(height, width, y, x);
__conf_window(win);
return win;
}
2025-09-10 23:05:07 +10:00
/* Initialise (with default IO configuration) the root ncurses WINDOW.
* NOTE: This is typically done via initscr(3x) and called "stdscr".
*/
2025-09-11 17:37:01 +10:00
WINDOW *root_window(void) {
2025-09-10 23:05:07 +10:00
WINDOW *rootwin = new_window(0, 0, 0, 0);
__conf_window(rootwin);
return rootwin;
}
2025-09-11 17:39:49 +10:00
/*
int main(const int argc, const char *const argv[]) {
init_ncurses();
2025-09-10 23:05:07 +10:00
WINDOW *stdscr = new_window(0, 0, 0, 0);
2025-09-10 22:49:05 +10:00
// Set background
wbkgd(stdscr, COLOR_PAIR(1));
attron(COLOR_PAIR(1));
attron(A_BOLD);
int counter = 0;
while (1) {
mvprintw(0, 0, "COUNTER %d", counter++);
refresh();
switch (getch()) {
case 'q':
goto end;
default:
break;
}
usleep(BASE_DELAY);
}
end:
endwin();
return 0;
}
2025-09-11 17:39:49 +10:00
*/