form
library is a curses extension that supports easy
programming of on-screen forms for data entry and program control.
The form
library first appeared in AT&T System V. The
version documented here is the freeware form
code distributed
with ncurses
.
#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
. Most modern linkers
are two-pass and will accept either order, but it is still good practice
to put -lform
first and -lncurses
second.
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:
curses
.
new_field()
.
new_form()
.
form_post()
.
form_unpost()
.
free_form()
.
free_field()
.
curses
.
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.
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 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.
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 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
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 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.
When a field is created, the attributes not specified by the new_field function are copied from an invisible system default field. In attribute-setting and -fetching functions, the argument NULL is taken to mean this field. Changes to it persist as defaults until your forms application terminates.
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.
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().
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.
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.
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.
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_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.
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 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.
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:
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:
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:
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.
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.
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 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.
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_INTEGER value buffer can conveniently be interpreted with the C library function atoi(3).
int set_field_type(FIELD *field, /* field to alter */ TYPE_NUMERIC, /* type to associate */ int padding, /* # places of precision */ int vmin, int vmax); /* valid range */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).
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.
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 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.
The most important 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 field_count() function simply counts the number of fields connected to a given from. It returns -1 if the form-pointer argument is NULL.
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 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:
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.
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.
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 REQ_MOVE_RIGHT from A will go to B only if A, B, and C all share the same first line; otherwise it will skip over B to C.
The following requests support editing the field and changing the edit mode:
First, we consider REQ_NEW_LINE:
The normal behavior of REQ_NEW_LINE in insert mode is to break the current line at the position of the edit cursor, inserting the portion of the current line after the cursor as a new line following the current and moving the cursor to the beginning of that new line (you may think of this as inserting a newline in the field buffer).
The normal behavior of REQ_NEW_LINE in overlay mode is to clear the current line from the position of the edit cursor to end of line. The cursor is then moved to the beginning of the next line.
However, REQ_NEW_LINE at the beginning of a field, or on the last line of a field, instead does a REQ_NEXT_FIELD. O_NL_OVERLOAD option is off, this special action is disabled.
Now, let us consider REQ_DEL_PREV:
The normal behavior of REQ_DEL_PREV is to delete the previous character. If insert mode is on, and the cursor is at the start of a line, and the text on that line will fit on the previous one, it instead appends the contents of the current line to the previous one and deletes the current line (you may think of this as deleting a newline from the field buffer).
However, REQ_DEL_PREV at the beginning of a field is instead treated as a REQ_PREV_FIELD.
If the O_BS_OVERLOAD option is off, this special action is disabled and the forms driver just returns E_REQUEST_DENIED.
See Form Options for discussion of how to set and clear the overload options.
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.
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 set_form_fields() resets this.
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.
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:
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.
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 free_fieldtype() deallocates the argument fieldtype, freeing all storage associated with it.
Normally, a field validator is called when the user attempts to leave the field. Its first argument is a field fointer, 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.
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 set_field_type() argument, and a pointer to the pile will be passed to the validation functions.
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:
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.
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.