Ncurses HTML
Ncurses HTML
Contents
● Introduction
○ A Brief History of Curses
○ Scope of This Document
○ Terminology
● The Curses Library
○ An Overview of Curses
■ Compiling Programs using Curses
■ Updating the Screen
■ Standard Windows and Function Naming Conventions
■ Variables
○ Using the Library
■ Starting up
■ Output
■ Input
■ Using Forms Characters
■ Character Attributes and Color
■ Mouse Interfacing
■ Finishing Up
○ Function Descriptions
■ Initialization and Wrapup
■ Causing Output to the Terminal
■ Low-Level Capability Access
■ Debugging
○ Hints, Tips, and Tricks
■ Some Notes of Caution
■ Temporarily Leaving ncurses Mode
■ Using ncurses under xterm
■ Handling Multiple Terminal Screens
■ Testing for Terminal Capabilities
■ Tuning for Speed
■ Special Features of ncurses
○ Compatibility with Older Versions
■ Refresh of Overlapping Windows
■ Background Erase
○ XSI Curses Conformance
● The Panels Library
○ Compiling With the Panels Library
○ Overview of Panels
○ Panels, Input, and the Standard Screen
○ Hiding Panels
○ Miscellaneous Other Facilities
● The Menu Library
○ Compiling with the menu Library
○ Overview of Menus
○ Selecting items
○ Menu Display
○ Menu Windows
○ Processing Menu Input
○ Miscellaneous Other Features
● The Forms Library
○ Compiling with the forms Library
○ Overview of Forms
○ Creating and Freeing Fields and Forms
○ Fetching and Changing Field Attributes
■ Fetching Size and Location Data
■ Changing the Field Location
■ The Justification Attribute
■ Field Display Attributes
■ Field Option Bits
■ Field Status
■ Field User Pointer
○ Variable-Sized Fields
○ Field Validation
■ TYPE_ALPHA
■ TYPE_ALNUM
■ TYPE_ENUM
■ TYPE_INTEGER
■ TYPE_NUMERIC
■ TYPE_REGEXP
○ Direct Field Buffer Manipulation
● Attributes of Forms
● Control of Form Display
● Input Processing in the Forms Driver
○ Page Navigation Requests
○ Inter-Field Navigation Requests
○ Intra-Field Navigation Requests
○ Scrolling Requests
○ Field Editing Requests
○ Order Requests
○ Application Commands
● Field Change Hooks
● Field Change Commands
● Form Options
● Custom Validation Types
○ Union Types
○ New Field Types
○ Validation Function Arguments
○ Order Functions For Custom Types
○ Avoiding Problems
Introduction
This document is an introduction to programming with curses. 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 curses programmer, you should nevertheless read the
sections on Mouse Interfacing, Debugging, Compatibility with Older Versions, and Hints, Tips,
and Tricks. These will bring you up to speed on the special features and quirks of the ncurses
implementation. If you are not so experienced, keep reading.
The curses package is a subroutine library for terminal-independent screen-painting and input-
event handling which presents a high level screen model to the programmer, hiding differences
between terminal types and doing automatic optimization of output to change one screenfull of
text into another. Curses uses terminfo, which is a database format that can describe the
capabilities of thousands of different terminals.
The curses API may seem something of an archaism on UNIX desktops increasingly dominated
by X, Motif, and Tcl/Tk. Nevertheless, UNIX still supports tty lines and X supports xterm(1); the
curses API has the advantage of (a) back-portability to character-cell terminals, and (b)
simplicity. For an application that does not require bit-mapped graphics and multiple fonts, an
interface implementation using curses will typically be a great deal simpler and less expensive
than one using an X toolkit.
● Support for multiple screen highlights (BSD curses could only handle one `standout'
highlight, usually reverse-video).
● Support for pads (windows of larger than screen size on which the screen or a subwindow
defines a viewport).
Also, this package makes use of the insert and delete line and character features of terminals
so equipped, and determines how to optimally use these features with no help from the
programmer. It allows arbitrary combinations of video attributes to be displayed, even on
terminals that leave ``magic cookies'' on the screen to mark changes in attributes.
The ncurses package can also capture and use event reports from a mouse in some
environments (notably, xterm under the X window system). This document includes tips for
using the mouse. The ncurses package was originated by Pavel Curtis. The primary maintainer
of the package is Zeyd Ben-Halim <zmbenhal@[Link]>. Eric S. Raymond
<esr@[Link]> wrote many of the new features in versions after 1.8.1 and wrote
most of this introduction.
This document also describes the 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. This
code was contributed to the project by Jürgen Pfeifer.
Terminology
In this document, the following terminology is used with reasonable consistency: window A data
structure describing a sub-rectangle of the screen (possibly the entire screen). You can write to
a window as though it were a miniature screen, scrolling independently of other windows on the
physical screen.
screens A subset of windows which are as large as the terminal screen, i.e., they start at the
upper left hand corner and encompass the lower right hand corner. One of these, stdscr, is
automatically provided for the programmer.
terminal screen The package's idea of what the terminal display currently looks like, i.e., what
the user sees now. This is a special screen.
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 Screen
In 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 (called curscr, 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 refresh() (or wrefresh() if the window is not stdscr) is called.
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.
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.
Variables
The curses 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 terminal
The curses.h also introduces some #define constants and types of general usefulness: bool
boolean type, actually a `char' (e.g., bool doneit;) TRUE boolean `true' flag (1). FALSE boolean
`false' flag (0). ERR error flag returned by routines on a fail (-1). OK error flag returned by
routines when things go right.
Using the Library
Now we describe how to actually use the screen package. In it, we assume all updating,
reading, etc. is applied to stdscr. 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>
if (has_colors())
{
start_color();
/*
* Simple color assignment, often all we need.
*/
init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
}
for (;;)
{
int c = getch(); /* refresh, accept single keystroke of
input */
exit(0);
}
Starting up
In order to use the screen package, the routines must know about terminal characteristics, and
the space for curscr 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 scrollok(). If you want the cursor to be left in place
after the last change, use leaveok(). If this isn't done, refresh() will move the cursor to the
window's current (y, x) coordinates after updating it.
You can create new windows of your own using the functions newwin(), derwin(), and subwin().
The routine delwin() will allow you to get rid of old windows. All the options described above can
be applied to any window.
Output
Now 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 are addch() 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 addstr() and printw(), all call addch() to add characters to
the window.
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 refresh(). In order to
optimize finding changes, refresh() assumes that any part of the window not changed since the
last refresh() of that window has not been changed on the terminal, i.e., that you have not
refreshed a portion of the terminal with an overlapping window. If this is not the case, the routine
touchwin() is provided to make it look like the entire window has been changed, thus making
refresh() check the whole subsection of the terminal for changes.
If you call wrefresh() with curscr as its argument, it will make the screen look like curscr thinks it
looks like. This is useful for implementing a command which would redraw the screen in case it
get messed up.
Input
The complementary function to addch() 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 wgetstr() and friends are
available. There is even a wscanw() function that can do scanf()(3)-style multi-field parsing on
window input. These pseudo-line-oriented functions turn on echoing while they execute.
The example code above uses the call keypad(stdscr, TRUE) to enable support for function-key
mapping. With this feature, the getch() code watches the input stream for character sequences
that correspond to arrow and function keys. These sequences are returned as pseudo-character
values. The #define values returned are listed in the curses.h The mapping from sequences to
#define values is determined by key_ capabilities in the terminal's terminfo entry.
Mouse Interfacing
The ncurses library also provides a mouse interface. Note: his facility is original to ncurses, it is
not part of either the XSI Curses standard, nor of System V Release 4, nor BSD curses. Thus,
we recommend that you wrap mouse-related code in an #ifdef using the feature macro
NCURSES_MOUSE_VERSION so it will not be compiled and linked on non-ncurses systems.
Presently, mouse event reporting works only under xterm. In the future, ncurses will detect the
presence of \fBgpm\fR(1), Alessandro Rubini's freeware mouse server for Linux systems, and
accept mouse reports through it.
The mouse interface is very simple. To activate it, you use the function mousemask(), passing it
as first argument a bit-mask that specifies what kinds of events you want your program to be
able to see. It will return the bit-mask of events that actually become visible, which may differ
from the argument if the mouse device is not capable of reporting some of the event types you
specify.
Once the mouse is active, your application's command loop should watch for a return value of
KEY_MOUSE from wgetch(). When you see this, a mouse event report has been queued. To
pick it off the queue, use the function getmouse() (you must do this before the next wgetch(),
otherwise another mouse event might come in and make the first one inaccessible).
Each call to getmouse() fills a structure (the address of which you'll pass it) with mouse event
data. The event data includes zero-origin, screen-relative character-cell coordinates of the
mouse pointer. It also includes an event mask. Bits in this mask will be set, corresponding to the
event type being reported.
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 touchscreens 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 mousemask(). Events that can be
reported include presses, releases, single-, double- and triple-clicks (you can set the maximum
button-down time for clicks). If you don't make clicks visible, they will be reported as press-
release pairs. In some environments, the event mask may include bits reporting the state of
shift, alt, and ctrl keys on the keyboard during the event.
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 ncurses applications that require the use of a mouse. Rather, you should use the mouse
as a shortcut for point-and-shoot commands your application would normally accept from the
keyboard. Two of the test games in the ncurses distribution (bs and knight) contain code that
illustrates how this can be done.
See the manual page curs_mouse(3X) for full details of the mouse-interface functions.
Finishing Up
In order to clean up after the ncurses 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 Descriptions
We describe the detailed behavior of some important curses functions here, as a supplement to
the manual page descriptions.
Initialization and Wrapup
initscr() The first function called should almost always be initscr(). This will determine the
terminal type and initialize curses data structures. initscr() also arranges that the first call to
refresh() will clear the screen. If an error occurs a message is written to standard error and the
program exits. Otherwise it returns a pointer to stdscr. A few functions may be called before
initscr (slk_init(), filter(), ripofflines(), use_env(), and, if you are using multiple terminals,
newterm().)
endwin() Your program should always call endwin() before exiting or shelling out of the program.
This function will restore tty modes, move the cursor to the lower left corner of the screen, reset
the terminal into the proper non-visual mode. Calling refresh() or doupdate() after a temporary
escape from the program will restore the ncurses screen from before the escape.
newterm(type, ofp, ifp) A program which outputs to more than one terminal should use
newterm() instead of initscr(). newterm() should be called once for each terminal. It returns a
variable of type SCREEN * which should be saved as a reference to that terminal. The
arguments are the type of the terminal (a string) and FILE pointers for the output and input of
the terminal. If type is NULL then the environment variable $TERM is used. endwin() should
called once at wrapup time for each terminal opened using this function.
delscreen(sp) The inverse of newterm(); deallocates the data structures associated with a given
SCREEN reference.
doupdate() and wnoutrefresh(win) These two functions allow multiple updates with more
efficiency than wrefresh. To use them, it is important to understand how curses works. In
addition to all the window structures, curses keeps two data structures representing the terminal
screen: a physical screen, describing what is actually on the screen, and a virtual screen,
describing what the programmer wants to have on the screen. wrefresh works by first copying
the named window to the virtual screen (wnoutrefresh()), and then calling the routine to update
the screen (doupdate()). If the programmer wishes to output several windows at once, a series
of calls to wrefresh will result in alternating calls to wnoutrefresh() and doupdate(), causing
several bursts of output to the screen. By calling wnoutrefresh() for each window, it is then
possible to call doupdate() once, resulting in only one burst of output, with fewer total characters
transmitted (this also avoids a visually annoying flicker at each update).
Debugging
NOTE: These functions are not part of the standard curses SPI!
trace() This function can be used to explicitly set a trace level. If the trace level is nonzero,
execution of your program will generate a file called `trace' in the current working directory
containing a report on the library's actions. Higher trace levels enable more detailed (and
verbose) reporting -- see comments attached to TRACE_ defines in the curses.h file for details.
(It is also possible to set a trace level by assigning a trace level value to the environment
variable NCURSES_TRACE). _tracef() This function can be used to output your own debugging
information. It is only available only if you link with -lncurses_g. It can be used the same way as
printf(), only it outputs a newline after the end of arguments. The output goes to a file called
trace in the current directory. Trace logs can be difficult to interpret due to the sheer volume of
data dumped in them. There is a script called tracemunch included with the 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.
Background Erase
If you have been using a very old versions of ncurses (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 bkgdset() or wbkgdset().
This change in behavior conforms ncurses to System V Release 4 and the XSI Curses
standard.
and must be linked explicitly with the panels library using an -lpanel argument. Note that they
must also link the ncurses library with -lncurses. Most modern linkers are two-pass and will
accept either order, but it is still good practice to put -lpanel first and -lncurses second.
Overview of Panels
A 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 to refresh()) 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 new_panel() on a window pointer. It then becomes
the top of the deck. The panel's window is available as the value of panel_window() called with
the panel pointer as argument.
You can delete a panel (removing it from the deck) with del_panel. This will not deallocate the
associated window; you have to do that yourself. You can replace a panel's window with a
different window by calling replace_window. The new window may be of different size; the panel
code will re-compute all overlaps. This operation doesn't change the panel's position in the
deck.
To move a panel's window, use move_panel(). The mvwin() function on the panel's window isn't
sufficient because it doesn't update the panels library's representation of where the windows
are. This operation leaves the panel's depth, contents, and size unchanged.
Two functions (top_panel(), bottom_panel()) are provided for rearranging the deck. The first
pops its argument window to the top of the deck; the second sends it to the bottom. Either
operation leaves the panel's screen location, contents, and size unchanged.
The function update_panels() does all the wnoutrefresh() calls needed to prepare for doupdate()
(which you must call yourself, afterwards).
Typically, you will want to call update_panels() and doupdate() just before accepting command
input, once in each cycle of interaction with the user. If you call update_panels() after each and
every panel write, youll generate a lot of unnecessary refresh activity and screen flicker.
Hiding Panels
It's possible to remove a panel from the deck temporarily; use hide_panel for this. You can un-
hide a panel with show_panel(). The predicate function panel_hidden tests whether or not a
panel is hidden.
The panel_update code ignores hidden panels. You cannot do top_panel() or bottom_panel on
a hidden panel(). Other panels operations are applicable.
and must be linked explicitly with the menus library using an -lmenu argument. Note that they
must also link the ncurses library with -lncurses. Most modern linkers are two-pass and will
accept either order, but it is still good practice to put -lmenu first and -lncurses second.
Overview of Menus
The 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:
1. Initialize curses.
2. Create the menu items, using new_item().
3. Create the menu using new_menu().
4. Post the menu using menu_post().
5. Refresh the screen.
6. Process user requests via an input loop.
7. Unpost the menu using menu_unpost().
8. Free the menu, using free_menu().
9. Free the items using free_item().
10. Terminate curses.
Selecting items
Menus may be multi-valued or (the default) single-valued (see the manual page mitem_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.
Menu items can be made un-selectable using set_item_opts() or item_opts_off() with the
O_SELECTABLE argument. This is the only option so far defined for menus, but it is good
practice to code as though other option bits might be on.
Menu Display
The menu library calculates a minimum display size for your window, based on the following
variables:
Menu Windows
Each 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 stdscr. You can set them with the functions in menu_win(3x).
When you call menu_post(), you write the menu to its subwindow. When you call
menu_unpost(), you erase the subwindow, However, neither of these actually modifies the
screen. To do that, call wrefresh() or some equivalent.
and must be linked explicitly with the forms library using an -lform argument. Note that they
must also link the ncurses library with -lncurses. Most modern linkers are two-pass and will
accept either order, but it is still good practice to put -lform first and -lncurses second.
Overview of Forms
A 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 curses Fields may have validation conditions on them,
so that they check input data for type and value. The form library supplies a rich set of pre-
defined field types, and makes it relatively easy to define new ones.
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:
1. Initialize curses.
2. Create the form fields, using new_field().
3. Create the form using new_form().
4. Post the form using form_post().
5. Refresh the screen.
6. Process user requests via an input loop.
7. Unpost the form using form_unpost().
8. Free the form, using free_form().
9. Free the fields using free_field().
10. Terminate curses.
Note that this looks much like a menu program; the form library handles tasks which are in
many ways similar, and its interface was obviously designed to resemble that of the menu
library wherever possible.
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.
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 stdscr by default but need not be stdscr if you've done
an explicit set_form_window() call.
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 \fBoffscreen\fR
argument was initially zero.
The forms library allocates one working buffer per field; the size of each buffer is ((height +
offscreen)*width + 1, one character for each position in the field plus a NUL terminator. The
sixth argument is the number of additional data buffers to allocate for the field; your application
can use them for its own purposes.
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 NULL if the field allocation is not possible
due to an out-of-memory error or out-of-bounds arguments.
To connect fields to a form, use
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 new_field() does not copy the pointer array into private storage; if you modify the
contents of the pointer array during forms processing, all manner of bizarre things might
happen. Also note that any given field may only be connected to one form.
The functions free_field() and free_form are available to free field and form objects. It is an error
to attempt to free a field connected to a form, but not vice-versa; thus, you will generally free
your form objects first.
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.
The mode values accepted and returned by this functions are preprocessor macros
NO_JUSTIFICATION, JUSTIFY_RIGHT, JUSTIFY_LEFT, or JUSTIFY_CENTER.
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.
By default, all options are on. Here are the available option bits: O_VISIBLE Controls whether
the field is visible on the screen. Can be used during form processing to hide or pop up fields
depending on the value of parent fields. O_ACTIVE Controls whether the field is active during
forms processing (i.e. visited by form navigation keys). Can be used to make labels or derived
fields with buffer values alterable by the forms application, not the user. O_PUBLIC Controls
whether data is displayed during field entry. If this option is turned off on a field, the library will
accept and edit data in that field, but it will not be displayed and the visible field cursor will not
move. You can turn off the O_PUBLIC bit to define password fields. O_EDIT Controls whether
the field's data can be modified. When this option is off, all editing requests except
REQ_PREV_CHOICE and REQ_NEXT_CHOICEwill fail. Such read-only fields may be useful
for help messages. O_WRAP Controls word-wrapping in multi-line fields. Normally, when any
character of a (blank-separated) word reaches the end of the current line, the entire word is
wrapped to the next line (assuming there is one). When this option is off, the word will be split
across the line break. O_BLANK Controls field blanking. When this option is on, entering a
character at the first field position erases the entire field (except for the just-entered character).
O_AUTOSKIP Controls automatic skip to next field when this one fills. Normally, when the forms
user tries to type more data into a field than will fit, the editing location jumps to next field. When
this option is off, the user's cursor will hang at the end of the field. This option is ignored in
dynamic fields that have not reached their size limit. O_NULLOK Controls whether validation is
applied to blank fields. Normally, it is not; the user can leave a field blank without invoking the
usual validation check on exit. If this option is off on a field, exit from it will invoke a validation
check. O_PASSOK Controls whether validation occurs on every exit, or only after the field is
modified. Normally the latter is true. Setting O_PASSOK may be useful if your field's validation
function may change during forms processing. O_STATIC Controls whether the field is fixed to
its initial dimensions. If you turn this off, the field becomes dynamic and will stretch to fit entered
data. A field's options cannot be changed while the field is currently selected. However, options
may be changed on posted fields that are not current.
The option values are bit-masks and can be composed with logical-or in the obvious way.
Field Status
Every 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:
Setting this flag under program control can be useful if you use the same form repeatedly,
looking for modified fields each time.
Calling field_status() on a field not currently selected for input will return a correct value. Calling
field_status() on a field that is currently selected for input may not necessarily give a correct field
status value, because entered data isn't necessarily copied to buffer zero before the exit
validation check. To guarantee that the returned status value reflects reality, call field_status()
either (1) in the field's exit validation check routine, (2) from the field's or form's initialization or
termination hooks, or (3) just after a REQ_VALIDATION request has been processed by the
forms driver.
(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 set_field_userptr() call passed a NULL
field pointer.) When a new field is created, the default-field user pointer is copied to initialize the
new field's user pointer.
Variable-Sized Fields
Normally, 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:
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:
● If there is no growth limit, there is no final position of the field; therefore O_AUTOSKIP
and O_NL_OVERLOAD are ignored.
● Field justification will be ignored (though whatever justification is set up will be retained
internally and can be queried).
● The dup_field() and link_field() calls copy dynamic-buffer sizes. If the O_STATIC option is
set on one of a collection of links, buffer resizing will occur only when the field is edited
through that link.
● The call field_info() will retrieve the original static size of the field; use
dynamic_field_info() to get the actual dynamic size.
Field Validation
By 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 set_field_buffer() modifies the input buffer,
nor when that buffer is changed through a linked field.
The form library provides a rich set of pre-defined validation types, and gives you the capability
to define custom ones of your own. You can examine and change field validation attributes with
the following functions:
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_ALPHA
This field type accepts alphabetic data; no blanks, no digits, no special characters (this is
checked at character-entry time). It is set up with:
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_ALNUM
This field type accepts alphabetic data and digits; no blanks, no special characters (this is
checked at character-entry time). It is set up with:
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_ENUM
This 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:
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 checkunique argument, if true,
requires prefix matches to be unique in order to be valid.
The REQ_NEXT_CHOICE and REQ_PREV_CHOICE input requests can be particularly useful
with these fields.
TYPE_INTEGER
This field type accepts an integer. It is set up as follows:
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_INTEGER value buffer can conveniently be interpreted with the C library function
atoi(3).
TYPE_NUMERIC
This field type accepts a decimal number. It is set up as follows:
Valid characters consist of an optional leading minus and digits. possibly including a decimal
point. 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_NUMERIC value buffer can conveniently be interpreted with the C library function
atof(3).
TYPE_REGEXP
This field type accepts data matching a regular expression. It is set up as follows:
The syntax for regular expressions is that of regcomp(3). The check for regular-expression
match is performed on exit.
Direct Field Buffer Manipulation
The most central 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:
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 field_buffer() with a null field pointer will raise an error. Calling field_buffer() on a field not
currently selected for input will return a correct value. Calling field_buffer() on a field that is
currently selected for input may not necessarily give a correct field buffer value, because
entered data isn't necessarily copied to buffer zero before the exit validation check. To
guarantee that the returned buffer value reflects on-screen reality, call field_buffer() either (1) in
the field's exit validation check routine, (2) from the field's or form's initialization or termination
hooks, or (3) just after a REQ_VALIDATION request has been processed by the forms driver.
Attributes of Forms
As 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 of
NULL.
The most important attribute of a form is its field list. You can query and change this list with:
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 field_count() function simply counts the number of fields connected to a given from. It
returns -1 if the form-pointer argument is NULL.
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
*/
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:
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 data_behind() returns TRUE if the first (upper left hand) character position is off-
screen (not being displayed).
Finally, there is a function to restore the form window's cursor to the value expected by the
forms driver:
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.
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.
REQ_NEXT_PAGE Move to the next form page. REQ_PREV_PAGE Move to the previous form
page. REQ_FIRST_PAGE Move to the first form page. REQ_LAST_PAGE Move to the last
form page. These requests treat the list as cyclic; that is, REQ_NEXT_PAGE from the last page
goes to the first, and REQ_PREV_PAGE from the first page goes to the last.
Scrolling Requests
Fields 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:
Order Requests
If 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:
REQ_NEXT_CHOICE Place the successor value of the current value in the buffer.
REQ_PREV_CHOICE Place the predecessor value of the current value in the buffer. Of the
built-in field types, only 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 Commands
Form requests are represented as integers above the curses 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.
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.
form_init This hook is called when the form is posted; also, just after each page change
operation. field_init This hook is called when the form is posted; also, just after each field
change field_term This hook is called just after field validation; that is, just before the field is
altered. It is also called when the form is unposted.
form_term This hook is called when the form is unposted; also, just before each page
change operation. Calls to these hooks may be triggered
1. When user editing requests are processed by the forms driver
2. When the current page is changed by set_current_field() call
3. When the current field is changed by a set_form_page() call
See Field Change Commands for discussion of the latter two cases.
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.
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
set_form_fields() resets this.
It is also possible to move around by pages.
The initial page of a newly-created form is 0. The function set_form_fields() resets this.
Form Options
Like fields, forms may have control option bits. They can be changed or queried with these
functions:
By default, all options are on. Here are the available option bits:
Union Types
The simplest way to create a custom data type is to compose it from two preexisting ones:
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.
make_str This function is called by set_field_type(). It gets one argument, a va_list of the type-
specific arguments passed to set_field_type(). It is expected to return a pile pointer to a data
structure that encapsulates those arguments. copy_str This function is called by form library
functions that allocate new field instances. It is expected to take a pile pointer, copy the pile to
allocated storage, and return the address of the pile copy. free_str This function is called by
field- and type-deallocation routines in the library. It takes a pile pointer argument, and is
expected to free the storage of that pile. The 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 Types
Some custom field types are simply ordered in the same well-defined way that TYPE_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:
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 Problems
The 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 ncurses library has been specifically un-
copyrighted to support this.
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.
THIS DOCUMENT IS STILL UNDER CONSTRUCTION. Full descriptions of the form library
entry points are available in the form_*.3x manual pages included with the ncurses distributions.