/* * Library of some useful-seeming functions for ncurses programs. * * Called functions are mostly from ncurses library. "man 3x foobar" * to find out what foobar() does. * * (Arguably this should be split into .h and .c files, but doing it * this way makes the Makefile simpler.) */ #include #include #include #include #include /* * declarations for all functions first, so they can appear in any * order below. */ void ncurses_start(void); void ncurses_end(void); void any_key_to_exit(WINDOW *win); void add_to_row(WINDOW *win, int N); void add_to_col(WINDOW *win, int N); void centerline(WINDOW *win, char *line); void show_with_attrib(WINDOW *win, int attr, char *msg); char *allocate_and_format(const char *fmt, ...); /* * startup for programs using ncurses */ void ncurses_start(void) { initscr(); cbreak(); noecho(); curs_set(0); /* set cursor to be invisible */ keypad(stdscr, TRUE); /* enable keypad */ } /* * cleanup-at-end for programs using ncurses */ void ncurses_end(void) { clear(); refresh(); endwin(); } /* * issue "press any key" prompt and wait for input */ void any_key_to_exit(WINDOW *win) { centerline(win, "Press any key to exit"); wrefresh(win); getch(); } /* * move cursor N rows (up or down) */ void add_to_row(WINDOW *win, int N) { int row, col; getyx(win, row, col); wmove(win, row+N, col); } /* * move cursor N cols (left or right) */ void add_to_col(WINDOW *win, int N) { int row, col; getyx(win, row, col); wmove(win, row, col+N); } /* * display line of text centered in current row */ void centerline(WINDOW *win, char *line) { int row, col; getyx(win, row, col); wmove(win, row, (COLS-strlen(line))/2); wprintw(win, "%s", line); } /* * display line of text centered in current row, with attributes * (shows the attributes "unpacked" into two 16-bit fields) */ void show_with_attrib(WINDOW *win, int attr, char *msg) { wattron(win, attr); char *line = allocate_and_format("%s (%04x %04x)", msg, (attr >> 16) & 0xffff, attr & 0xffff); if (line != NULL) { centerline(win, line); free(line); } wattroff(win, attr); } /* * create string for formatted text: * parameters are similar to those for printf (format string and list of * of expressions) * gets just enough space for formatted text using malloc * returns pointer to malloc'd line containing the result of "printing" * to a string * (caller must free line) */ char *allocate_and_format(const char *fmt, ...) { va_list args; va_start(args,fmt); int sz = vsnprintf(NULL, 0, fmt, args) + 1; va_end(args); char *line = malloc(sz); if (line != NULL) { va_start(args,fmt); vsnprintf(line, sz, fmt, args); va_end(args); } return line; }