Programming in LUA
Programming in LUA
Contents
* Introduction
+ A Brief History of Curses
+ Scope of This Document
+ Terminology
* The Curses Library
+ An Overview of Curses
o Compiling Programs using Curses
o Updating the Screen
o Standard Windows and Function Naming Conventions
o Variables
+ Using the Library
o Starting up
o Output
o Input
o Using Forms Characters
o Character Attributes and Color
o Mouse Interfacing
o Finishing Up
+ Function Descriptions
o Initialization and Wrapup
o Causing Output to the Terminal
o Low-Level Capability Access
o Debugging
+ Hints, Tips, and Tricks
o Some Notes of Caution
o Temporarily Leaving ncurses Mode
o Using ncurses under xterm
o Handling Multiple Terminal Screens
o Testing for Terminal Capabilities
o Tuning for Speed
o Special Features of ncurses
+ Compatibility with Older Versions
o Refresh of Overlapping Windows
o 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
o Fetching Size and Location Data
o Changing the Field Location
o The Justification Attribute
o Field Display Attributes
o Field Option Bits
o Field Status
o Field User Pointer
+ Variable-Sized Fields
+ Field Validation
o TYPE_ALPHA
o TYPE_ALNUM
o TYPE_ENUM
o TYPE_INTEGER
o TYPE_NUMERIC
o TYPE_REGEXP
+ Direct Field Buffer Manipulation
+ Attributes of Forms
+ Control of Form Display
+ Input Processing in the Forms Driver
o Page Navigation Requests
o Inter-Field Navigation Requests
o Intra-Field Navigation Requests
o Scrolling Requests
o Field Editing Requests
o Order Requests
o Application Commands
+ Field Change Hooks
+ Field Change Commands
+ Form Options
+ Custom Validation Types
o Union Types
o New Field Types
o Validation Function Arguments
o Order Functions For Custom Types
o Avoiding Problems
_________________________________________________________________
Introduction
System III UNIX from Bell Labs featured a rewritten and much-improved
curses library. It introduced the terminfo format. Terminfo is based
on Berkeley's termcap database, but contains a number of improvements
and extensions. Parameterized capabilities strings were introduced,
making it possible to describe multiple video attributes, and colors
and to handle far more unusual terminals than possible with termcap.
In the later AT&T System V releases, curses evolved to use more
facilities and offer more capabilities, going far beyond BSD curses in
power and flexibility.
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.
Terminology
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.
An Overview of Curses
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.
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.
As 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.
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
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 failure (-1).
OK
error flag returned by routines when things go right.
int
main(int argc, char *argv[])
{
int num = 0;
/*
* 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++;
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 is not 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 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.
The addch() 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, curses.h will map them to
a recognizable (though ugly) set of ASCII defaults.
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 addch()
call, or any other output call that takes a chtype argument.
Once you have done an init_pair() that creates color-pair N, you can
use COLOR_PAIR(N) as a highlight that invokes that particular color
combination. Note that COLOR_PAIR(N), for constant N, is itself a
compile-time constant and can be used in initializers.
Mouse Interfacing
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).
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
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(), ripoffline(), 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.
set_term(new)
This function is used to switch to a different terminal
previously opened by newterm(). The screen reference for the
new terminal is passed as the parameter. The previous terminal
is returned by the function. All other calls affect only the
current terminal.
delscreen(sp)
The inverse of newterm(); deallocates the data structures
associated with a given SCREEN reference.
The value of term can be given as NULL, which will cause the
value of TERM in the environment to be used. The errret pointer
can also be given as NULL, meaning no error code is wanted. If
errret is defaulted, and something goes wrong, setupterm() will
print an appropriate error message and exit, rather than
returning. Thus, a simple program can call setupterm(0, 1, 0)
and not worry about initialization errors.
Debugging
NOTE: These functions are not part of the standard curses API!
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.
The ncurses 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.
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 ncurses library is not yet an
exception to this rule.
Sometimes 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 in ncurses.
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. Ncurses provides an extension which works better, the
resizeterm function. That function ensures that all windows are
limited to the new screen dimensions, and pads stdscr with blanks if
the screen is larger.
Sometimes you may want to write programs that test for the presence of
various capabilities before deciding whether to go into ncurses mode.
An easy way to do this is to call setupterm(), then use the functions
tigetflag(), tigetnum(), and tigetstr() to do your testing.
Despite our best efforts, there are some differences between ncurses
and the (undocumented!) behavior of older curses implementations.
These arise from ambiguities or omissions in the documentation of the
API.
If 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 historic curses versions were often not documented
precisely.
The ncurses library itself has not always been consistent on this
score. Due to a bug, versions 1.8.7 to 1.9.8a did entire copy.
Versions 1.8.6 and older, and versions 1.9.9 and newer, do change
copy.
The really clean way to handle this is to use the panels library. If,
when you want a screen update, you do update_panels(), it will do all
the necessary wnoutrefresh() calls for whatever panel stacking order
you have defined. Then you can do one doupdate() and there will be a
single burst of physical I/O that will do all your updates.
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).
Also, ncurses meets the XSI requirement that every macro entry point
have a corresponding function which may be linked (and will be
prototype-checked) if the macro definition is disabled with #undef.
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.
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 Panels
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 does not
change the panel's position in the deck.
Hiding Panels
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 set_panel_userptr() and panel_userptr for details.
A menu is a screen display that assists the user to choose some subset
of a given set of items. The menu library is a curses extension that
supports easy programming of menu hierarchies with a uniform but
flexible interface.
Your 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 Menus
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.
Selecting items
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 Display
The menu library calculates a minimum display size for your window,
based on the following variables:
* The number and maximum length of the menu items
* Whether the O_ROWMAJOR option is enabled
* Whether display of descriptions is enabled
* Whatever menu format may have been set by the programmer
* The length of the menu mark string used for highlighting selected
items
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 menu_mark(3x) manual page for details. The mark string length also
influences the menu page size.
The function scale_menu() returns the minimum display size that the
menu code computes from all these factors. There are other menu
display attributes including a select attribute, an attribute for
selectable items, an attribute for unselectable items, and a pad
character used to separate item name text from description text. These
have reasonable defaults which the library allows you to change (see
the menu_attribs(3x) manual page.
Menu Windows
By default, both windows are stdscr. You can set them with the
functions in menu_win(3x).
When you call post_menu(), you write the menu to its subwindow. When
you call unpost_menu(), you erase the subwindow, However, neither of
these actually modifies the screen. To do that, call wrefresh() or
some equivalent.
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 REQ_SCR_DLINE, REQ_SCR_ULINE,
REQ_SCR_DPAGE, and REQ_SCR_UPAGE.
Various menu options can affect the processing and visual appearance
and input processing of menus. See menu_opts(3x) for details.
Each item, and each menu, has an associated user pointer on which you
can hang application data. See mitem_userptr(3x) and menu_userptr(3x).
Your 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 Forms
To make forms, you create groups of fields and connect them with form
frame objects; the form library makes this relatively simple.
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.
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 have done an explicit set_form_win() call.
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 */
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.
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.
For 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.
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.
There 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 */
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_CHOICE will 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.
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:
int set_field_status(FIELD *field, /* field to alter */
int status); /* mode to set */
Setting this flag under program control can be useful if you use the
same form repeatedly, looking for modified fields each time.
Each 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 */
(Properly, this user pointer field ought to have (void *) type. The
(char *) type is retained for System V compatibility.)
Variable-Sized Fields
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.
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 does not 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.
TYPE_ALPHA
The width argument sets a minimum width of data. Typically you will
want to set this to the field width; if it is greater than the field
width, the validation check will always fail. A minimum width of zero
makes field completion optional.
TYPE_ALNUM
TYPE_ENUM
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.
TYPE_INTEGER
If the value passes its range check, it is padded with as many leading
zero digits as necessary to meet the padding argument.
TYPE_NUMERIC
TYPE_REGEXP
The 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 is 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 */
Attributes of Forms
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 */
It may also be null, in which case the old fields are disconnected
(and not freed) but no new ones are connected.
In 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 window stdscr.
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.
In order to declare your own frame window for a form, you will 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 */
The function data_behind() returns TRUE if the first (upper left hand)
character position is off-screen (not being displayed).
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.
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.
REQ_NEXT_FIELD
Move to next field.
REQ_PREV_FIELD
Move to previous field.
REQ_FIRST_FIELD
Move to the first field.
REQ_LAST_FIELD
Move to the last field.
REQ_SNEXT_FIELD
Move to sorted next field.
REQ_SPREV_FIELD
Move to sorted previous field.
REQ_SFIRST_FIELD
Move to the sorted first field.
REQ_SLAST_FIELD
Move to the sorted last field.
REQ_LEFT_FIELD
Move left to field.
REQ_RIGHT_FIELD
Move right to field.
REQ_UP_FIELD
Move up to field.
REQ_DOWN_FIELD
Move down to field.
These requests treat the list of fields on a page as cyclic; that is,
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()
These requests drive movement of the edit cursor within the currently
selected field.
REQ_NEXT_CHAR
Move to next character.
REQ_PREV_CHAR
Move to previous character.
REQ_NEXT_LINE
Move to next line.
REQ_PREV_LINE
Move to previous line.
REQ_NEXT_WORD
Move to next word.
REQ_PREV_WORD
Move to previous word.
REQ_BEG_FIELD
Move to beginning of field.
REQ_END_FIELD
Move to end of field.
REQ_BEG_LINE
Move to beginning of line.
REQ_END_LINE
Move to end of line.
REQ_LEFT_CHAR
Move left in field.
REQ_RIGHT_CHAR
Move right in field.
REQ_UP_CHAR
Move up in field.
REQ_DOWN_CHAR
Move down in field.
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:
REQ_SCR_FLINE
Scroll vertically forward a line.
REQ_SCR_BLINE
Scroll vertically backward a line.
REQ_SCR_FPAGE
Scroll vertically forward a page.
REQ_SCR_BPAGE
Scroll vertically backward a page.
REQ_SCR_FHPAGE
Scroll vertically forward half a page.
REQ_SCR_BHPAGE
Scroll vertically backward half a page.
REQ_SCR_FCHAR
Scroll horizontally forward a character.
REQ_SCR_BCHAR
Scroll horizontally backward a character.
REQ_SCR_HFLINE
Scroll horizontally one field width forward.
REQ_SCR_HBLINE
Scroll horizontally one field width backward.
REQ_SCR_HFHALF
Scroll horizontally one half field width forward.
REQ_SCR_HBHALF
Scroll horizontally one half field width backward.
The following requests support editing the field and changing the edit
mode:
REQ_INS_MODE
Set insertion mode.
REQ_OVL_MODE
Set overlay mode.
REQ_NEW_LINE
New line request (see below for explanation).
REQ_INS_CHAR
Insert space at character location.
REQ_INS_LINE
Insert blank line at character location.
REQ_DEL_CHAR
Delete character at cursor.
REQ_DEL_PREV
Delete previous word at cursor.
REQ_DEL_LINE
Delete line at cursor.
REQ_DEL_WORD
Delete word at cursor.
REQ_CLR_EOL
Clear to end of line.
REQ_CLR_EOF
Clear to end of field.
REQ_CLEAR_FIELD
Clear entire field.
See Form Options for discussion of how to set and clear the overload
options.
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
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.
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.
Form Options
Like 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 */
By default, all options are on. Here are the available option bits:
O_NL_OVERLOAD
Enable overloading of REQ_NEW_LINE as described in Editing
Requests. The value of this option is ignored on dynamic fields
that have not reached their size limit; these have no last
line, so the circumstances for triggering a REQ_NEXT_FIELD
never arise.
O_BS_OVERLOAD
Enable overloading of REQ_DEL_PREV as described in Editing
Requests.
The option values are bit-masks and can be composed with logical-or in
the obvious way.
The form 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 Types
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.
To create a field type from scratch, you need to specify one or both
of the following things:
* A character-validation function, to check each character as it is
entered.
* A field-validation function to be applied on exit from the field.
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.
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 is how:
typedef int (*INTHOOK)(); /* pointer to function returning int */
Avoiding Problems
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 exempted from the package
copyright to support this.