Whole document tree Writing Programs with NCURSESby Eric S. Raymond and Zeyd M. Ben-Halim Contents
IntroductionThis document is an introduction to programming withcurses . It is
not an exhaustive reference for the curses Application Programming Interface
(API); that role is filled by the curses manual pages. Rather, it
is intended to help C programmers ease into using the package.
This document is aimed at C applications programmers not yet specifically
familiar with ncurses. If you are already an experienced
The
The A Brief History of CursesHistorically, the first ancestor ofcurses was the routines written to
provide screen-handling for the game rogue ; these used the
already-existing termcap database facility for describing terminal
capabilities. These routines were abstracted into a documented library and
first released with the early BSD UNIX versions.
System III UNIX from Bell Labs featured a rewritten and much-improved
Scope of This DocumentThis document describesncurses , a free implementation of
the System V curses API with some clearly marked extensions.
It includes the following System V curses features:
The
The This document also describes the panels extension library, similarly modeled on the SVr4 panels facility. This library allows you to associate backing store with each of a stack or deck of overlapping windows, and provides operations for moving windows around in the stack that change their visibility in the natural way (handling window overlaps). Finally, this document describes in detail the menus and forms extension libraries, also cloned from System V, which support easy construction and sequences of menus and fill-in forms. TerminologyIn this document, the following terminology is used with reasonable consistency:
The Curses LibraryAn Overview of CursesCompiling Programs using CursesIn order to use the library, it is necessary to have certain types and variables defined. Therefore, the programmer must have a line:#include <curses.h>at the top of the program source. The screen package uses the Standard I/O library, so <curses.h> includes
<stdio.h> . <curses.h> also includes
<termios.h> , <termio.h> , or
<sgtty.h> depending on your system. It is redundant (but
harmless) for the programmer to do these includes, too. In linking with
curses you need to have -lncurses in your LDFLAGS or on the
command line. There is no need for any other libraries.
Updating the ScreenIn order to update the screen optimally, it is necessary for the routines to know what the screen currently looks like and what the programmer wants it to look like next. For this purpose, a data type (structure) named WINDOW is defined which describes a window image to the routines, including its starting position on the screen (the (y, x) coordinates of the upper left hand corner) and its size. One of these (calledcurscr , for current screen) is a
screen image of what the terminal currently looks like. Another screen (called
stdscr , for standard screen) is provided by default to make changes
on. A window is a purely internal representation. It is used to build and store a potential image of a portion of the terminal. It doesn't bear any necessary relation to what is really on the terminal screen; it's more like a scratchpad or write buffer.
To make the section of physical screen corresponding to a window reflect the
contents of the window structure, the routine A given physical screen section may be within the scope of any number of overlapping windows. Also, changes can be made to windows in any order, without regard to motion efficiency. Then, at will, the programmer can effectively say ``make it look like this,'' and let the package implementation determine the most efficient way to repaint the screen. Standard Windows and Function Naming ConventionsAs hinted above, the routines can use several windows, but two are automatically given:curscr , which knows what the terminal looks like,
and stdscr , which is what the programmer wants the terminal to look
like next. The user should never actually access curscr directly.
Changes should be made to through the API, and then the routine
refresh() (or wrefresh() ) called.
Many functions are defined to use
In order to move the current (y, x) coordinates from one point to another, the
routines move(y, x); addch(ch);can be replaced by mvaddch(y, x, ch);and wmove(win, y, x); waddch(win, ch);can be replaced by mvwaddch(win, y, x, ch);Note that the window description pointer (win) comes before the added (y, x) coordinates. If a function requires a window pointer, it is always the first parameter passed. VariablesThecurses library sets some variables describing the terminal
capabilities.
type name description ------------------------------------------------------------------ int LINES number of lines on the terminal int COLS number of columns on the terminalThe curses.h also introduces some #define constants and types
of general usefulness:
Using the LibraryNow we describe how to actually use the screen package. In it, we assume all updating, reading, etc. is applied tostdscr . These instructions will
work on any window, providing you change the function names and parameters as
mentioned above. Here is a sample program to motivate the discussion: #include <curses.h> #include <signal.h> static void finish(int sig); int main(int argc, char *argv[]) { int num = 0; /* initialize your non-curses data structures here */ (void) signal(SIGINT, finish); /* arrange interrupts to terminate */ (void) initscr(); /* initialize the curses library */ keypad(stdscr, TRUE); /* enable keyboard mapping */ (void) nonl(); /* tell curses not to do NL->CR/NL on output */ (void) cbreak(); /* take input chars one at a time, no wait for \n */ (void) echo(); /* echo input - in color */ if (has_colors()) { start_color(); /* * Simple color assignment, often all we need. Color pair 0 cannot * be redefined. This example uses the same value for the color * pair as for the foreground color, though of course that is not * necessary: */ init_pair(1, COLOR_RED, COLOR_BLACK); init_pair(2, COLOR_GREEN, COLOR_BLACK); init_pair(3, COLOR_YELLOW, COLOR_BLACK); init_pair(4, COLOR_BLUE, COLOR_BLACK); init_pair(5, COLOR_CYAN, COLOR_BLACK); init_pair(6, COLOR_MAGENTA, COLOR_BLACK); init_pair(7, COLOR_WHITE, COLOR_BLACK); } for (;;) { int c = getch(); /* refresh, accept single keystroke of input */ attrset(COLOR_PAIR(num % 8)); num++; /* process the command keystroke */ } finish(0); /* we're done */ } static void finish(int sig) { endwin(); /* do your non-curses wrapup here */ exit(0); } Starting upIn order to use the screen package, the routines must know about terminal characteristics, and the space forcurscr and stdscr must be
allocated. These function initscr() does both these things. Since it
must allocate space for the windows, it can overflow memory when attempting to
do so. On the rare occasions this happens, initscr() will terminate
the program with an error message. initscr() must always be called
before any of the routines which affect windows are used. If it is not, the
program will core dump as soon as either curscr or stdscr are
referenced. However, it is usually best to wait to call it until after you are
sure you will need it, like after checking for startup errors. Terminal status
changing routines like nl() and cbreak() should be called
after initscr() .
Once the screen windows have been allocated, you can set them up for
your program. If you want to, say, allow a screen to scroll, use
You can create new windows of your own using the functions OutputNow that we have set things up, we will want to actually update the terminal. The basic functions used to change what will go on a window areaddch() and move() . addch() adds a character at the
current (y, x) coordinates. move() changes the current (y, x)
coordinates to whatever you want them to be. It returns ERR if you
try to move off the window. As mentioned above, you can combine the two into
mvaddch() to do both things at once.
The other output functions, such as
After you have put on the window what you want there, when you want the portion
of the terminal covered by the window to be made to look like it, you must call
If you call InputThe complementary function toaddch() is getch() which, if
echo is set, will call addch() to echo the character. Since the
screen package needs to know what is on the terminal at all times, if
characters are to be echoed, the tty must be in raw or cbreak mode. Since
initially the terminal has echoing enabled and is in ordinary ``cooked'' mode,
one or the other has to changed before calling getch() ; otherwise,
the program's output will be unpredictable.
When you need to accept line-oriented input in a window, the functions
The example code above uses the call Using Forms CharactersTheaddch() function (and some others, including box() and
border() ) can accept some pseudo-character arguments which are specially
defined by ncurses . These are #define values set up in
the curses.h header; see there for a complete list (look for
the prefix ACS_ ).
The most useful of the ACS defines are the forms-drawing characters. You can
use these to draw boxes and simple graphs on the screen. If the terminal
does not have such characters, Character Attributes and ColorThencurses package supports screen highlights including standout,
reverse-video, underline, and blink. It also supports color, which is treated
as another kind of highlight.
Highlights are encoded, internally, as high bits of the pseudo-character type
(
There are two ways to make highlights. One is to logical-or the value of the
highlights you want into the character argument of an
The other is to set the current-highlight value. This is logical-or'ed with
any highlight you specify the first way. You do this with the functions
Once you've done an Mouse InterfacingThencurses library also provides a mouse interface.
NOTE: this facility is specific to
Presently, mouse event reporting works in the following environments:
The mouse interface is very simple. To activate it, you use the function
Once the mouse is active, your application's command loop should watch
for a return value of
Each call to The mouse structure contains two additional fields which may be significant in the future as ncurses interfaces to new kinds of pointing device. In addition to x and y coordinates, there is a slot for a z coordinate; this might be useful with touch-screens that can return a pressure or duration parameter. There is also a device ID field, which could be used to distinguish between multiple pointing devices.
The class of visible events may be changed at any time via A function to check whether a mouse event fell within a given window is also supplied. You can use this to see whether a given window should consider a mouse event relevant to it.
Because mouse event reporting will not be available in all
environments, it would be unwise to build
See the manual page Finishing UpIn order to clean up after thencurses routines, the routine
endwin() is provided. It restores tty modes to what they were when
initscr() was first called, and moves the cursor down to the
lower-left corner. Thus, anytime after the call to initscr, endwin()
should be called before exiting.
Function DescriptionsWe describe the detailed behavior of some important curses functions here, as a supplement to the manual page descriptions.Initialization and Wrapup
Causing Output to the Terminal
Low-Level Capability Access
DebuggingNOTE: These functions are not part of the standard curses API!
ncurses distribution that can alleviate
this problem somewhat; it compacts long sequences of similar operations into
more succinct single-line pseudo-operations. These pseudo-ops can be
distinguished by the fact that they are named in capital letters.
Hints, Tips, and TricksThencurses manual pages are a complete reference for this library.
In the remainder of this document, we discuss various useful methods that
may not be obvious from the manual page descriptions.
Some Notes of CautionIf you find yourself thinking you need to usenoraw() or
nocbreak() , think again and move carefully. It's probably
better design to use getstr() or one of its relatives to
simulate cooked mode. The noraw() and nocbreak()
functions try to restore cooked mode, but they may end up clobbering
some control bits set before you started your application. Also, they
have always been poorly documented, and are likely to hurt your
application's usability with other curses libraries.
Bear in mind that
You are much less likely to run into problems if you design your screen
layouts to use tiled rather than overlapping windows. Historically,
curses support for overlapping windows has been weak, fragile, and poorly
documented. The
There is a panels library included in the
Try to avoid using the global variables LINES and COLS. Use
Temporarily Leaving NCURSES ModeSometimes you will want to write a program that spends most of its time in screen mode, but occasionally returns to ordinary `cooked' mode. A common reason for this is to support shell-out. This behavior is simple to arrange inncurses .
To leave
There is a boolean function, Here is some sample code for shellout: addstr("Shelling out..."); def_prog_mode(); /* save current tty modes */ endwin(); /* restore original tty modes */ system("sh"); /* run shell */ addstr("returned.\n"); /* prepare return message */ refresh(); /* restore save modes, repaint screen */ Using NCURSES under XTERMA resize operation in X sends SIGWINCH to the application running under xterm. Thencurses library provides an experimental signal
handler, but in general does not catch this signal, because it cannot
know how you want the screen re-painted. You will usually have to write the
SIGWINCH handler yourself. Ncurses can give you some help.
The easiest way to code your SIGWINCH handler is to have it do an
That is the standard way, of course (it even works with some vendor's curses
implementations).
Its drawback is that it clears the screen to reinitialize the display, and does
not resize subwindows which must be shrunk.
Finally, ncurses can be configured to provide its own SIGWINCH handler,
based on Handling Multiple Terminal ScreensTheinitscr() function actually calls a function named
newterm() to do most of its work. If you are writing a program that
opens multiple terminals, use newterm() directly.
For each call, you will have to specify a terminal type and a pair of file
pointers; each call will return a screen reference, and Testing for Terminal CapabilitiesSometimes you may want to write programs that test for the presence of various capabilities before deciding whether to go intoncurses mode. An easy
way to do this is to call setupterm() , then use the functions
tigetflag() , tigetnum() , and tigetstr() to do your
testing.
A particularly useful case of this often comes up when you want to
test whether a given terminal type should be treated as `smart'
(cursor-addressable) or `stupid'. The right way to test this is to see
if the return value of Tuning for SpeedUse theaddchstr() family of functions for fast
screen-painting of text when you know the text doesn't contain any
control characters. Try to make attribute changes infrequent on your
screens. Don't use the immedok() option!
Special Features of NCURSESThewresize() function allows you to resize a window in place.
The associated resizeterm() function simplifies the construction
of SIGWINCH handlers, for resizing all windows.
The
The Ncurses supports up 16 colors, unlike SVr4 curses which defines only 8. While most terminals which provide color allow only 8 colors, about a quarter (including XFree86 xterm) support 16 colors. Compatibility with Older VersionsDespite our best efforts, there are some differences betweenncurses
and the (undocumented!) behavior of older curses implementations. These arise
from ambiguities or omissions in the documentation of the API.
Refresh of Overlapping WindowsIf you define two windows A and B that overlap, and then alternately scribble on and refresh them, the changes made to the overlapping region under historiccurses versions were often not documented precisely. To understand why this is a problem, remember that screen updates are calculated between two representations of the entire display. The documentation says that when you refresh a window, it is first copied to to the virtual screen, and then changes are calculated to update the physical screen (and applied to the terminal). But "copied to" is not very specific, and subtle differences in how copying works can produce different behaviors in the case where two overlapping windows are each being refreshed at unpredictable intervals.
What happens to the overlapping region depends on what
The
For most commercial curses implementations, it is not documented and not known
for sure (at least not to the
It might therefore be unwise to rely on either behavior in programs that might
have to be linked with other curses implementations. Instead, you can do an
explicit
The really clean way to handle this is to use the panels library. If,
when you want a screen update, you do Background EraseIf you have been using a very old versions ofncurses (1.8.7 or
older) you may be surprised by the behavior of the erase functions. In older
versions, erased areas of a window were filled with a blank modified by the
window's current attribute (as set by wattrset(), wattron(),
wattroff() and friends).
In newer versions, this is not so. Instead, the attribute of erased blanks
is normal unless and until it is modified by the functions
This change in behavior conforms XSI Curses ConformanceThencurses library is intended to be base-level conformant with the
XSI Curses standard from X/Open. Many extended-level features (in fact, almost
all features not directly concerned with wide characters and
internationalization) are also supported. One effect of XSI conformance is the change in behavior described under "Background Erase -- Compatibility with Old Versions".
Also, The Panels LibraryThencurses library by itself provides good support for screen
displays in which the windows are tiled (non-overlapping). In the more
general case that windows may overlap, you have to use a series of
wnoutrefresh() calls followed by a doupdate() , and be
careful about the order you do the window refreshes in. It has to be
bottom-upwards, otherwise parts of windows that should be obscured will
show through. When your interface design is such that windows may dive deeper into the visibility stack or pop to the top at runtime, the resulting book-keeping can be tedious and difficult to get right. Hence the panels library.
The Compiling With the Panels LibraryYour panels-using modules must import the panels library declarations with#include <panel.h>and must be linked explicitly with the panels library using an -lpanel argument. Note that they must also link the
ncurses library with -lncurses . Many linkers
are two-pass and will accept either order, but it is still good practice
to put -lpanel first and -lncurses second.
Overview of PanelsA panel object is a window that is implicitly treated as part of a deck including all other panel objects. The deck has an implicit bottom-to-top visibility order. The panels library includes an update function (analogous torefresh() ) that displays all panels in the
deck in the proper order to resolve overlaps. The standard window,
stdscr , is considered below all panels. Details on the panels functions are available in the man pages. We'll just hit the highlights here.
You create a panel from a window by calling
You can delete a panel (removing it from the deck) with
To move a panel's window, use
Two functions (
The function
Typically, you will want to call Panels, Input, and the Standard ScreenYou shouldn't mixwnoutrefresh() or wrefresh()
operations with panels code; this will work only if the argument window
is either in the top panel or unobscured by any other panels.
The
Note that There is presently no way to display changes to one obscured panel without repainting all panels. Hiding PanelsIt's possible to remove a panel from the deck temporarily; usehide_panel for this. Use show_panel() to render it
visible again. The predicate function panel_hidden
tests whether or not a panel is hidden.
The Miscellaneous Other FacilitiesIt's possible to navigate the deck using the functionspanel_above() and panel_below . Handed a panel
pointer, they return the panel above or below that panel. Handed
NULL , they return the bottom-most or top-most panel.
Every panel has an associated user pointer, not used by the panel code, to
which you can attach application data. See the man page documentation
of The Menu LibraryA menu is a screen display that assists the user to choose some subset of a given set of items. Themenu library is a curses
extension that supports easy programming of menu hierarchies with a
uniform but flexible interface.
The Compiling With the menu LibraryYour menu-using modules must import the menu library declarations with#include <menu.h>and must be linked explicitly with the menus library using an -lmenu argument. Note that they must also link the
ncurses library with -lncurses . Many linkers
are two-pass and will accept either order, but it is still good practice
to put -lmenu first and -lncurses second.
Overview of MenusThe menus created by this library consist of collections of items including a name string part and a description string part. To make menus, you create groups of these items and connect them with menu frame objects.The menu can then by posted, that is written to an associated window. Actually, each menu has two associated windows; a containing window in which the programmer can scribble titles or borders, and a subwindow in which the menu items proper are displayed. If this subwindow is too small to display all the items, it will be a scrollable viewport on the collection of items. A menu may also be unposted (that is, undisplayed), and finally freed to make the storage associated with it and its items available for re-use. The general flow of control of a menu program looks like this:
Selecting itemsMenus may be multi-valued or (the default) single-valued (see the manual pagemenu_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
Menu items can be made unselectable using Menu DisplayThe menu library calculates a minimum display size for your window, based on the following variables:
set_menu_format() allows you to set the
maximum size of the viewport or menu page that will be used
to display menu items. You can retrieve any format associated with a
menu with menu_format() . The default format is rows=16,
columns=1. The actual menu page may be smaller than the format size. This depends on the item number and size and whether O_ROWMAJOR is on. This option (on by default) causes menu items to be displayed in a `raster-scan' pattern, so that if more than one item will fit horizontally the first couple of items are side-by-side in the top row. The alternative is column-major display, which tries to put the first several items in the first column. As mentioned above, a menu format not large enough to allow all items to fit on-screen will result in a menu display that is vertically scrollable. You can scroll it with requests to the menu driver, which will be described in the section on menu input handling.
Each menu has a mark string used to visually tag selected items;
see the
The function Menu WindowsEach menu has, as mentioned previously, a pair of associated windows. Both these windows are painted when the menu is posted and erased when the menu is unposted.The outer or frame window is not otherwise touched by the menu routines. It exists so the programmer can associate a title, a border, or perhaps help text with the menu and have it properly refreshed or erased at post/unpost time. The inner window or subwindow is where the current menu page is displayed.
By default, both windows are
When you call Processing Menu InputThe main loop of your menu-processing code should callmenu_driver() repeatedly. The first argument of this routine
is a menu pointer; the second is a menu command code. You should write an
input-fetching routine that maps input characters to menu command codes, and
pass its output to menu_driver() . The menu command codes are
fully documented in menu_driver(3x) .
The simplest group of command codes is
There are explicit requests for scrolling which also change the
current item (because the select location does not change, but the
item there does). These are
The
Each menu has an associated pattern buffer. The
Some requests change the pattern buffer directly:
Each successful scroll or item navigation request clears the pattern
buffer. It is also possible to set the pattern buffer explicitly
with
Finally, menu driver requests above the constant Miscellaneous Other FeaturesVarious menu options can affect the processing and visual appearance and input processing of menus. Seemenu_opts(3x) for
details.
It is possible to change the current item from application code; this
is useful if you want to write your own navigation requests. It is
also possible to explicitly set the top row of the menu display. See
It is possible to set hooks to be called at menu initialization and
wrapup time, and whenever the selected item changes. See
Each item, and each menu, has an associated user pointer on which you
can hang application data. See The Forms LibraryTheform library is a curses extension that supports easy
programming of on-screen forms for data entry and program control.
The Compiling With the form LibraryYour form-using modules must import the form library declarations with#include <form.h>and must be linked explicitly with the forms library using an -lform argument. Note that they must also link the
ncurses library with -lncurses . Many linkers
are two-pass and will accept either order, but it is still good practice
to put -lform first and -lncurses second.
Overview of FormsA form is a collection of fields; each field may be either a label (explanatory text) or a data-entry location. Long forms may be segmented into pages; each entry to a new page clears the screen.To make forms, you create groups of fields and connect them with form frame objects; the form library makes this relatively simple. Once defined, a form can be posted, that is written to an associated window. Actually, each form has two associated windows; a containing window in which the programmer can scribble titles or borders, and a subwindow in which the form fields proper are displayed.
As the form user fills out the posted form, navigation and editing
keys support movement between fields, editing keys support modifying
field, and plain text adds to or changes data in a current field. The
form library allows you (the forms designer) to bind each navigation
and editing key to any keystroke accepted by Once its transaction is completed (or aborted), a form may be unposted (that is, undisplayed), and finally freed to make the storage associated with it and its items available for re-use. The general flow of control of a form program looks like this:
In forms programs, however, the `process user requests' is somewhat more complicated than for menus. Besides menu-like navigation operations, the menu driver loop has to support field editing and data validation. Creating and Freeing Fields and FormsThe basic function for creating fields isnew_field() :
FIELD *new_field(int height, int width, /* new field size */ int top, int left, /* upper left corner */ int offscreen, /* number of offscreen rows */ int nbuf); /* number of working buffers */Menu items always occupy a single row, but forms fields may have multiple rows. So new_field() requires you to specify a
width and height (the first two arguments, which mist both be greater
than zero).
You must also specify the location of the field's upper left corner on
the screen (the third and fourth arguments, which must be zero or
greater). Note that these coordinates are relative to the form
subwindow, which will coincide with
The fifth argument allows you to specify a number of off-screen rows. If
this is zero, the entire field will always be displayed. If it is
nonzero, the form will be scrollable, with only one screen-full (initially
the top part) displayed at any given time. If you make a field dynamic
and grow it so it will no longer fit on the screen, the form will become
scrollable even if the
The forms library allocates one working buffer per field; the size of
each buffer is FIELD *dup_field(FIELD *field, /* field to copy */ int top, int left); /* location of new copy */The function dup_field() duplicates an existing field at a
new location. Size and buffering information are copied; some
attribute flags and status bits are not (see the
form_field_new(3X) for details).
FIELD *link_field(FIELD *field, /* field to copy */ int top, int left); /* location of new copy */The function link_field() also duplicates an existing field
at a new location. The difference from dup_field() is that
it arranges for the new field's buffer to be shared with the old one. Besides the obvious use in making a field editable from two different form pages, linked fields give you a way to hack in dynamic labels. If you declare several fields linked to an original, and then make them inactive, changes from the original will still be propagated to the linked fields. As with duplicated fields, linked fields have attribute bits separate from the original.
As you might guess, all these field-allocations return To connect fields to a form, use FORM *new_form(FIELD **fields);This function expects to see a NULL-terminated array of field pointers. Said fields are connected to a newly-allocated form object; its address is returned (or else NULL if the allocation fails).
Note that
The functions Fetching and Changing Field AttributesEach form field has a number of location and size attributes associated with it. There are other field attributes used to control display and editing of the field. Some (for example, theO_STATIC bit)
involve sufficient complications to be covered in sections of their own
later on. We cover the functions used to get and set several basic
attributes here.
When a field is created, the attributes not specified by the
Fetching Size and Location DataYou can retrieve field sizes and locations through:int field_info(FIELD *field, /* field from which to fetch */ int *height, *int width, /* field size */ int *top, int *left, /* upper left corner */ int *offscreen, /* number of offscreen rows */ int *nbuf); /* number of working buffers */This function is a sort of inverse of new_field() ; instead of
setting size and location attributes of a new field, it fetches them
from an existing one.
Changing the Field LocationIt is possible to move a field's location on the screen:int move_field(FIELD *field, /* field to alter */ int top, int left); /* new upper-left corner */You can, of course. query the current location through field_info() .
The Justification AttributeOne-line fields may be unjustified, justified right, justified left, or centered. Here is how you manipulate this attribute:int set_field_just(FIELD *field, /* field to alter */ int justmode); /* mode to set */ int field_just(FIELD *field); /* fetch mode of field */The mode values accepted and returned by this functions are preprocessor macros NO_JUSTIFICATION , JUSTIFY_RIGHT ,
JUSTIFY_LEFT , or JUSTIFY_CENTER .
Field Display AttributesFor each field, you can set a foreground attribute for entered characters, a background attribute for the entire field, and a pad character for the unfilled portion of the field. You can also control pagination of the form.This group of four field attributes controls the visual appearance of the field on the screen, without affecting in any way the data in the field buffer. int set_field_fore(FIELD *field, /* field to alter */ chtype attr); /* attribute to set */ chtype field_fore(FIELD *field); /* field to query */ int set_field_back(FIELD *field, /* field to alter */ chtype attr); /* attribute to set */ chtype field_back(FIELD *field); /* field to query */ int set_field_pad(FIELD *field, /* field to alter */ int pad); /* pad character to set */ chtype field_pad(FIELD *field); int set_new_page(FIELD *field, /* field to alter */ int flag); /* TRUE to force new page */ chtype new_page(FIELD *field); /* field to query */The attributes set and returned by the first four functions are normal curses(3x) display attribute values (A_STANDOUT ,
A_BOLD , A_REVERSE etc).
The page bit of a field controls whether it is displayed at the start of
a new form screen.
Field Option BitsThere is also a large collection of field option bits you can set to control various aspects of forms processing. You can manipulate them with these functions:int set_field_opts(FIELD *field, /* field to alter */ int attr); /* attribute to set */ int field_opts_on(FIELD *field, /* field to alter */ int attr); /* attributes to turn on */ int field_opts_off(FIELD *field, /* field to alter */ int attr); /* attributes to turn off */ int field_opts(FIELD *field); /* field to query */By default, all options are on. Here are the available option bits:
The option values are bit-masks and can be composed with logical-or in the obvious way. Field StatusEvery field has a status flag, which is set to FALSE when the field is created and TRUE when the value in field buffer 0 changes. This flag can be queried and set directly:int set_field_status(FIELD *field, /* field to alter */ int status); /* mode to set */ int field_status(FIELD *field); /* fetch mode of field */Setting this flag under program control can be useful if you use the same form repeatedly, looking for modified fields each time.
Calling Field User PointerEach field structure contains one character pointer slot that is not used by the forms library. It is intended to be used by applications to store private per-field data. You can manipulate it with:int set_field_userptr(FIELD *field, /* field to alter */ char *userptr); /* mode to set */ char *field_userptr(FIELD *field); /* fetch mode of field */(Properly, this user pointer field ought to have (void *) type.
The (char *) type is retained for System V compatibility.)
It is valid to set the user pointer of the default field (with a
Variable-Sized FieldsNormally, a field is fixed at the size specified for it at creation time. If, however, you turn off its O_STATIC bit, it becomes dynamic and will automatically resize itself to accommodate data as it is entered. If the field has extra buffers associated with it, they will grow right along with the main input buffer.A one-line dynamic field will have a fixed height (1) but variable width, scrolling horizontally to display data within the field area as originally dimensioned and located. A multi-line dynamic field will have a fixed width, but variable height (number of rows), scrolling vertically to display data within the field area as originally dimensioned and located. Normally, a dynamic field is allowed to grow without limit. But it is possible to set an upper limit on the size of a dynamic field. You do it with this function: int set_max_field(FIELD *field, /* field to alter (may not be NULL) */ int max_size); /* upper limit on field size */If the field is one-line, max_size is taken to be a column size
limit; if it is multi-line, it is taken to be a line size limit. To disable
any limit, use an argument of zero. The growth limit can be changed whether
or not the O_STATIC bit is on, but has no effect until it is. The following properties of a field change when it becomes dynamic:
Field ValidationBy default, a field will accept any data that will fit in its input buffer. However, it is possible to attach a validation type to a field. If you do this, any attempt to leave the field while it contains data that doesn't match the validation type will fail. Some validation types also have a character-validity check for each time a character is entered in the field.
A field's validation check (if any) is not called when
The int set_field_type(FIELD *field, /* field to alter */ FIELDTYPE *ftype, /* type to associate */ ...); /* additional arguments*/ FIELDTYPE *field_type(FIELD *field); /* field to query */The validation type of a field is considered an attribute of the field. As with other field attributes, Also, doing set_field_type() with a
NULL field default will change the system default for validation of
newly-created fields. Here are the pre-defined validation types: TYPE_ALPHAThis field type accepts alphabetic data; no blanks, no digits, no special characters (this is checked at character-entry time). It is set up with:int set_field_type(FIELD *field, /* field to alter */ TYPE_ALPHA, /* type to associate */ int width); /* maximum width of field */The width argument sets a minimum width of data. Typically
you'll want to set this to the field width; if it's greater than the
field width, the validation check will always fail. A minimum width
of zero makes field completion optional.
TYPE_ALNUMThis field type accepts alphabetic data and digits; no blanks, no special characters (this is checked at character-entry time). It is set up with:int set_field_type(FIELD *field, /* field to alter */ TYPE_ALNUM, /* type to associate */ int width); /* maximum width of field */The width argument sets a minimum width of data. As with
TYPE_ALPHA, typically you'll want to set this to the field width; if it's
greater than the field width, the validation check will always fail. A
minimum width of zero makes field completion optional.
TYPE_ENUMThis type allows you to restrict a field's values to be among a specified set of string values (for example, the two-letter postal codes for U.S. states). It is set up with:int set_field_type(FIELD *field, /* field to alter */ TYPE_ENUM, /* type to associate */ char **valuelist; /* list of possible values */ int checkcase; /* case-sensitive? */ int checkunique); /* must specify uniquely? */The valuelist parameter must point at a NULL-terminated list of
valid strings. The checkcase argument, if true, makes comparison
with the string case-sensitive. When the user exits a TYPE_ENUM field, the validation procedure tries to complete the data in the buffer to a valid entry. If a complete choice string has been entered, it is of course valid. But it is also possible to enter a prefix of a valid string and have it completed for you.
By default, if you enter such a prefix and it matches more than one value
in the string list, the prefix will be completed to the first matching
value. But the
The TYPE_INTEGERThis field type accepts an integer. It is set up as follows:int set_field_type(FIELD *field, /* field to alter */ TYPE_INTEGER, /* type to associate */ int padding, /* # places to zero-pad to */ int vmin, int vmax); /* valid range */Valid characters consist of an optional leading minus and digits. The range check is performed on exit. If the range maximum is less than or equal to the minimum, the range is ignored. If the value passes its range check, it is padded with as many leading zero digits as necessary to meet the padding argument.
A TYPE_NUMERICThis field type accepts a decimal number. It is set up as follows:int set_field_type(FIELD *field, /* field to alter */ TYPE_NUMERIC, /* type to associate */ int padding, /* # places of precision */ double vmin, double vmax); /* valid range */Valid characters consist of an optional leading minus and digits. possibly including a decimal point. If your system supports locale's, the decimal point character used must be the one defined by your locale. The range check is performed on exit. If the range maximum is less than or equal to the minimum, the range is ignored. If the value passes its range check, it is padded with as many trailing zero digits as necessary to meet the padding argument.
A TYPE_REGEXPThis field type accepts data matching a regular expression. It is set up as follows:int set_field_type(FIELD *field, /* field to alter */ TYPE_REGEXP, /* type to associate */ char *regexp); /* expression to match */The syntax for regular expressions is that of regcomp(3) .
The check for regular-expression match is performed on exit.
Direct Field Buffer ManipulationThe chief attribute of a field is its buffer contents. When a form has been completed, your application usually needs to know the state of each field buffer. You can find this out with:char *field_buffer(FIELD *field, /* field to query */ int bufindex); /* number of buffer to query */Normally, the state of the zero-numbered buffer for each field is set by the user's editing actions on that field. It's sometimes useful to be able to set the value of the zero-numbered (or some other) buffer from your application: int set_field_buffer(FIELD *field, /* field to alter */ int bufindex, /* number of buffer to alter */ char *value); /* string value to set */If the field is not large enough and cannot be resized to a sufficiently large size to contain the specified value, the value will be truncated to fit.
Calling Attributes of FormsAs with field attributes, form attributes inherit a default from a system default form structure. These defaults can be queried or set by of these functions using a form-pointer argument ofNULL . The principal attribute of a form is its field list. You can query and change this list with: int set_form_fields(FORM *form, /* form to alter */ FIELD **fields); /* fields to connect */ char *form_fields(FORM *form); /* fetch fields of form */ int field_count(FORM *form); /* count connect fields */The second argument of set_form_fields() may be a
NULL-terminated field pointer array like the one required by
new_form() . In that case, the old fields of the form are
disconnected but not freed (and eligible to be connected to other
forms), then the new fields are connected. It may also be null, in which case the old fields are disconnected (and not freed) but no new ones are connected.
The Control of Form DisplayIn the overview section, you saw that to display a form you normally start by defining its size (and fields), posting it, and refreshing the screen. There is an hidden step before posting, which is the association of the form with a frame window (actually, a pair of windows) within which it will be displayed. By default, the forms library associates every form with the full-screen windowstdscr . By making this step explicit, you can associate a form with a declared frame window on your screen display. This can be useful if you want to adapt the form display to different screen sizes, dynamically tile forms on the screen, or use a form as part of an interface layout managed by panels. The two windows associated with each form have the same functions as their analogues in the menu library. Both these windows are painted when the form is posted and erased when the form is unposted. The outer or frame window is not otherwise touched by the form routines. It exists so the programmer can associate a title, a border, or perhaps help text with the form and have it properly refreshed or erased at post/unpost time. The inner window or subwindow is where the current form page is actually displayed. In order to declare your own frame window for a form, you'll need to know the size of the form's bounding rectangle. You can get this information with: int scale_form(FORM *form, /* form to query */ int *rows, /* form rows */ int *cols); /* form cols */The form dimensions are passed back in the locations pointed to by the arguments. Once you have this information, you can use it to declare of windows, then use one of these functions: int set_form_win(FORM *form, /* form to alter */ WINDOW *win); /* frame window to connect */ WINDOW *form_win(FORM *form); /* fetch frame window of form */ int set_form_sub(FORM *form, /* form to alter */ WINDOW *win); /* form subwindow to connect */ WINDOW *form_sub(FORM *form); /* fetch form subwindow of form */Note that curses operations, including refresh() , on the form,
should be done on the frame window, not the form subwindow. It is possible to check from your application whether all of a scrollable field is actually displayed within the menu subwindow. Use these functions: int data_ahead(FORM *form); /* form to be queried */ int data_behind(FORM *form); /* form to be queried */The function data_ahead() returns TRUE if (a) the current
field is one-line and has undisplayed data off to the right, (b) the current
field is multi-line and there is data off-screen below it.
The function Finally, there is a function to restore the form window's cursor to the value expected by the forms driver: int pos_form_cursor(FORM *) /* form to be queried */If your application changes the form window cursor, call this function before handing control back to the forms driver in order to re-synchronize it. Input Processing in the Forms DriverThe functionform_driver() handles virtualized input requests
for form navigation, editing, and validation requests, just as
menu_driver does for menus (see the section on menu input handling).
int form_driver(FORM *form, /* form to pass input to */ int request); /* form request code */Your input virtualization function needs to take input and then convert it to either an alphanumeric character (which is treated as data to be entered in the currently-selected field), or a forms processing request. The forms driver provides hooks (through input-validation and field-termination functions) with which your application code can check that the input taken by the driver matched what was expected. Page Navigation RequestsThese requests cause page-level moves through the form, triggering display of a new form screen.
REQ_NEXT_PAGE
from the last page goes to the first, and REQ_PREV_PAGE from
the first page goes to the last.
Inter-Field Navigation RequestsThese requests handle navigation between fields on the same page.
REQ_NEXT_FIELD from the last field goes to the first, and
REQ_PREV_FIELD from the first field goes to the last. The
order of the fields for these (and the REQ_FIRST_FIELD and
REQ_LAST_FIELD requests) is simply the order of the field
pointers in the form array (as set up by new_form() or
set_form_fields() It is also possible to traverse the fields as if they had been sorted in screen-position order, so the sequence goes left-to-right and top-to-bottom. To do this, use the second group of four sorted-movement requests. Finally, it is possible to move between fields using visual directions up, down, right, and left. To accomplish this, use the third group of four requests. Note, however, that the position of a form for purposes of these requests is its upper-left corner.
For example, suppose you have a multi-line field B, and two
single-line fields A and C on the same line with B, with A to the left
of B and C to the right of B. A Intra-Field Navigation RequestsThese requests drive movement of the edit cursor within the currently selected field.
Scrolling RequestsFields that are dynamic and have grown and fields explicitly created with offscreen rows are scrollable. One-line fields scroll horizontally; multi-line fields scroll vertically. Most scrolling is triggered by editing and intra-field movement (the library scrolls the field to keep the cursor visible). It is possible to explicitly request scrolling with the following requests:
Editing RequestsWhen you pass the forms driver an ASCII character, it is treated as a request to add the character to the field's data buffer. Whether this is an insertion or a replacement depends on the field's edit mode (insertion is the default.The following requests support editing the field and changing the edit mode:
REQ_NEW_LINE and REQ_DEL_PREV requests
is complicated and partly controlled by a pair of forms options.
The special cases are triggered when the cursor is at the beginning of
a field, or on the last line of the field.
First, we consider
The normal behavior of
The normal behavior of
However,
Now, let us consider
The normal behavior of
However, If the
See Form Options for discussion of how to set and clear the overload options. Order RequestsIf the type of your field is ordered, and has associated functions for getting the next and previous values of the type from a given value, there are requests that can fetch that value into the field buffer:
TYPE_ENUM has built-in successor
and predecessor functions. When you define a field type of your own
(see Custom Validation Types), you can associate
our own ordering functions.
Application CommandsForm requests are represented as integers above thecurses value
greater than KEY_MAX and less than or equal to the constant
MAX_COMMAND . If your input-virtualization routine returns a
value above MAX_COMMAND , the forms driver will ignore it.
Field Change HooksIt is possible to set function hooks to be executed whenever the current field or form changes. Here are the functions that support this:typedef void (*HOOK)(); /* pointer to function returning void */ int set_form_init(FORM *form, /* form to alter */ HOOK hook); /* initialization hook */ HOOK form_init(FORM *form); /* form to query */ int set_form_term(FORM *form, /* form to alter */ HOOK hook); /* termination hook */ HOOK form_term(FORM *form); /* form to query */ int set_field_init(FORM *form, /* form to alter */ HOOK hook); /* initialization hook */ HOOK field_init(FORM *form); /* form to query */ int set_field_term(FORM *form, /* form to alter */ HOOK hook); /* termination hook */ HOOK field_term(FORM *form); /* form to query */These functions allow you to either set or query four different hooks. In each of the set functions, the second argument should be the address of a hook function. These functions differ only in the timing of the hook call.
You can set a default hook for all fields by passing one of the set functions a NULL first argument. You can disable any of these hooks by (re)setting them to NULL, the default value. Field Change CommandsNormally, navigation through the form will be driven by the user's input requests. But sometimes it is useful to be able to move the focus for editing and viewing under control of your application, or ask which field it currently is in. The following functions help you accomplish this:int set_current_field(FORM *form, /* form to alter */ FIELD *field); /* field to shift to */ FIELD *current_field(FORM *form); /* form to query */ int field_index(FORM *form, /* form to query */ FIELD *field); /* field to get index of */The function field_index() returns the index of the given field
in the given form's field array (the array passed to new_form() or
set_form_fields() ).
The initial current field of a form is the first active field on the
first page. The function It is also possible to move around by pages. int set_form_page(FORM *form, /* form to alter */ int page); /* page to go to (0-origin) */ int form_page(FORM *form); /* return form's current page */The initial page of a newly-created form is 0. The function set_form_fields() resets this.
Form OptionsLike fields, forms may have control option bits. They can be changed or queried with these functions:int set_form_opts(FORM *form, /* form to alter */ int attr); /* attribute to set */ int form_opts_on(FORM *form, /* form to alter */ int attr); /* attributes to turn on */ int form_opts_off(FORM *form, /* form to alter */ int attr); /* attributes to turn off */ int form_opts(FORM *form); /* form to query */By default, all options are on. Here are the available option bits:
Custom Validation TypesTheform library gives you the capability to define custom
validation types of your own. Further, the optional additional arguments
of set_field_type effectively allow you to parameterize validation
types. Most of the complications in the validation-type interface have to
do with the handling of the additional arguments within custom validation
functions.
Union TypesThe simplest way to create a custom data type is to compose it from two preexisting ones:FIELD *link_fieldtype(FIELDTYPE *type1, FIELDTYPE *type2);This function creates a field type that will accept any of the values legal for either of its argument field types (which may be either predefined or programmer-defined). If a set_field_type() call later requires arguments, the new
composite type expects all arguments for the first type, than all arguments
for the second. Order functions (see Order Requests)
associated with the component types will work on the composite; what it does
is check the validation function for the first type, then for the second, to
figure what type the buffer contents should be treated as.
New Field TypesTo create a field type from scratch, you need to specify one or both of the following things:
typedef int (*HOOK)(); /* pointer to function returning int */ FIELDTYPE *new_fieldtype(HOOK f_validate, /* field validator */ HOOK c_validate) /* character validator */ int free_fieldtype(FIELDTYPE *ftype); /* type to free */At least one of the arguments of new_fieldtype() must be
non-NULL. The forms driver will automatically call the new type's
validation functions at appropriate points in processing a field of
the new type.
The function Normally, a field validator is called when the user attempts to leave the field. Its first argument is a field pointer, from which it can get to field buffer 0 and test it. If the function returns TRUE, the operation succeeds; if it returns FALSE, the edit cursor stays in the field. A character validator gets the character passed in as a first argument. It too should return TRUE if the character is valid, FALSE otherwise. Validation Function ArgumentsYour field- and character- validation functions will be passed a second argument as well. This second argument is the address of a structure (which we'll call a pile) built from any of the field-type-specific arguments passed toset_field_type() . If
no such arguments are defined for the field type, this pile pointer
argument will be NULL.
In order to arrange for such arguments to be passed to your validation
functions, you must associate a small set of storage-management functions
with the type. The forms driver will use these to synthesize a pile
from the trailing arguments of each Here is how you make the association: typedef char *(*PTRHOOK)(); /* pointer to function returning (char *) */ typedef void (*VOIDHOOK)(); /* pointer to function returning void */ int set_fieldtype_arg(FIELDTYPE *type, /* type to alter */ PTRHOOK make_str, /* make structure from args */ PTRHOOK copy_str, /* make copy of structure */ VOIDHOOK free_str); /* free structure storage */Here is how the storage-management hooks are used:
make_str and copy_str functions may return NULL to
signal allocation failure. The library routines will that call them will
return error indication when this happens. Thus, your validation functions
should never see a NULL file pointer and need not check specially for it.
Order Functions For Custom TypesSome custom field types are simply ordered in the same well-defined way thatTYPE_ENUM is. For such types, it is possible to define
successor and predecessor functions to support the REQ_NEXT_CHOICE
and REQ_PREV_CHOICE requests. Here's how:
typedef int (*INTHOOK)(); /* pointer to function returning int */ int set_fieldtype_arg(FIELDTYPE *type, /* type to alter */ INTHOOK succ, /* get successor value */ INTHOOK pred); /* get predecessor value */The successor and predecessor arguments will each be passed two arguments; a field pointer, and a pile pointer (as for the validation functions). They are expected to use the function field_buffer() to read the
current value, and set_field_buffer() on buffer 0 to set the next
or previous value. Either hook may return TRUE to indicate success (a
legal next or previous value was set) or FALSE to indicate failure.
Avoiding ProblemsThe interface for defining custom types is complicated and tricky. Rather than attempting to create a custom type entirely from scratch, you should start by studying the library source code for whichever of the pre-defined types seems to be closest to what you want.
Use that code as a model, and evolve it towards what you really want.
You will avoid many problems and annoyances that way. The code
in the If your custom type defines order functions, have do something intuitive with a blank field. A useful convention is to make the successor of a blank field the types minimum value, and its predecessor the maximum. |