]> ncurses.scripts.mit.edu Git - ncurses.git/blob - misc/ncurses-intro.doc
ncurses 4.2
[ncurses.git] / misc / ncurses-intro.doc
1
2                          Writing Programs with NCURSES
3                                        
4      by Eric S. Raymond and Zeyd M. Ben-Halim
5      
6                                    Contents
7                                        
8      * Introduction
9           + A Brief History of Curses
10           + Scope of This Document
11           + Terminology
12      * The Curses Library
13           + An Overview of Curses
14                o Compiling Programs using Curses
15                o Updating the Screen
16                o Standard Windows and Function Naming Conventions
17                o Variables
18           + Using the Library
19                o Starting up
20                o Output
21                o Input
22                o Using Forms Characters
23                o Character Attributes and Color
24                o Mouse Interfacing
25                o Finishing Up
26           + Function Descriptions
27                o Initialization and Wrapup
28                o Causing Output to the Terminal
29                o Low-Level Capability Access
30                o Debugging
31           + Hints, Tips, and Tricks
32                o Some Notes of Caution
33                o Temporarily Leaving ncurses Mode
34                o Using ncurses under xterm
35                o Handling Multiple Terminal Screens
36                o Testing for Terminal Capabilities
37                o Tuning for Speed
38                o Special Features of ncurses
39           + Compatibility with Older Versions
40                o Refresh of Overlapping Windows
41                o Background Erase
42           + XSI Curses Conformance
43      * The Panels Library
44           + Compiling With the Panels Library
45           + Overview of Panels
46           + Panels, Input, and the Standard Screen
47           + Hiding Panels
48           + Miscellaneous Other Facilities
49      * The Menu Library
50           + Compiling with the menu Library
51           + Overview of Menus
52           + Selecting items
53           + Menu Display
54           + Menu Windows
55           + Processing Menu Input
56           + Miscellaneous Other Features
57      * The Forms Library
58           + Compiling with the forms Library
59           + Overview of Forms
60           + Creating and Freeing Fields and Forms
61           + Fetching and Changing Field Attributes
62                o Fetching Size and Location Data
63                o Changing the Field Location
64                o The Justification Attribute
65                o Field Display Attributes
66                o Field Option Bits
67                o Field Status
68                o Field User Pointer
69           + Variable-Sized Fields
70           + Field Validation
71                o TYPE_ALPHA
72                o TYPE_ALNUM
73                o TYPE_ENUM
74                o TYPE_INTEGER
75                o TYPE_NUMERIC
76                o TYPE_REGEXP
77           + Direct Field Buffer Manipulation
78           + Attributes of Forms
79           + Control of Form Display
80           + Input Processing in the Forms Driver
81                o Page Navigation Requests
82                o Inter-Field Navigation Requests
83                o Intra-Field Navigation Requests
84                o Scrolling Requests
85                o Field Editing Requests
86                o Order Requests
87                o Application Commands
88           + Field Change Hooks
89           + Field Change Commands
90           + Form Options
91           + Custom Validation Types
92                o Union Types
93                o New Field Types
94                o Validation Function Arguments
95                o Order Functions For Custom Types
96                o Avoiding Problems
97      _________________________________________________________________
98    
99                                  Introduction
100                                        
101    This document is an introduction to programming with curses. It is not
102    an exhaustive reference for the curses Application Programming
103    Interface (API); that role is filled by the curses manual pages.
104    Rather, it is intended to help C programmers ease into using the
105    package.
106    
107    This document is aimed at C applications programmers not yet
108    specifically familiar with ncurses. If you are already an experienced
109    curses programmer, you should nevertheless read the sections on Mouse
110    Interfacing, Debugging, Compatibility with Older Versions, and Hints,
111    Tips, and Tricks. These will bring you up to speed on the special
112    features and quirks of the ncurses implementation. If you are not so
113    experienced, keep reading.
114    
115    The curses package is a subroutine library for terminal-independent
116    screen-painting and input-event handling which presents a high level
117    screen model to the programmer, hiding differences between terminal
118    types and doing automatic optimization of output to change one screen
119    full of text into another. Curses uses terminfo, which is a database
120    format that can describe the capabilities of thousands of different
121    terminals.
122    
123    The curses API may seem something of an archaism on UNIX desktops
124    increasingly dominated by X, Motif, and Tcl/Tk. Nevertheless, UNIX
125    still supports tty lines and X supports xterm(1); the curses API has
126    the advantage of (a) back-portability to character-cell terminals, and
127    (b) simplicity. For an application that does not require bit-mapped
128    graphics and multiple fonts, an interface implementation using curses
129    will typically be a great deal simpler and less expensive than one
130    using an X toolkit.
131    
132 A Brief History of Curses
133
134    Historically, the first ancestor of curses was the routines written to
135    provide screen-handling for the game rogue; these used the
136    already-existing termcap database facility for describing terminal
137    capabilities. These routines were abstracted into a documented library
138    and first released with the early BSD UNIX versions.
139    
140    System III UNIX from Bell Labs featured a rewritten and much-improved
141    curses library. It introduced the terminfo format. Terminfo is based
142    on Berkeley's termcap database, but contains a number of improvements
143    and extensions. Parameterized capabilities strings were introduced,
144    making it possible to describe multiple video attributes, and colors
145    and to handle far more unusual terminals than possible with termcap.
146    In the later AT&T System V releases, curses evolved to use more
147    facilities and offer more capabilities, going far beyond BSD curses in
148    power and flexibility.
149    
150 Scope of This Document
151
152    This document describes ncurses, a freeware implementation of the
153    System V curses API with some clearly marked extensions. It includes
154    the following System V curses features:
155    
156      * Support for multiple screen highlights (BSD curses could only
157        handle one `standout' highlight, usually reverse-video).
158      * Support for line- and box-drawing using forms characters.
159      * Recognition of function keys on input.
160      * Color support.
161      * Support for pads (windows of larger than screen size on which the
162        screen or a subwindow defines a viewport).
163        
164    Also, this package makes use of the insert and delete line and
165    character features of terminals so equipped, and determines how to
166    optimally use these features with no help from the programmer. It
167    allows arbitrary combinations of video attributes to be displayed,
168    even on terminals that leave ``magic cookies'' on the screen to mark
169    changes in attributes.
170    
171    The ncurses package can also capture and use event reports from a
172    mouse in some environments (notably, xterm under the X window system).
173    This document includes tips for using the mouse.
174    
175    The ncurses package was originated by Pavel Curtis. The original
176    maintainer of the package is Zeyd Ben-Halim <zmbenhal@netcom.com>.
177    Eric S. Raymond <esr@snark.thyrsus.com> wrote many of the new features
178    in versions after 1.8.1 and wrote most of this introduction. Jürgen
179    Pfeifer wrote all of the menu and forms code as well as the Ada95
180    binding. Ongoing work is being done by Thomas Dickey and Jürgen
181    Pfeifer. Florian La Roche acts as the maintainer for the Free Software
182    Foundation, which holds the copyright on ncurses. Contact the current
183    maintainers at bug-ncurses@gnu.org.
184    
185    This document also describes the panels extension library, similarly
186    modeled on the SVr4 panels facility. This library allows you to
187    associate backing store with each of a stack or deck of overlapping
188    windows, and provides operations for moving windows around in the
189    stack that change their visibility in the natural way (handling window
190    overlaps).
191    
192    Finally, this document describes in detail the menus and forms
193    extension libraries, also cloned from System V, which support easy
194    construction and sequences of menus and fill-in forms.
195    
196 Terminology
197
198    In this document, the following terminology is used with reasonable
199    consistency:
200    
201    window
202           A data structure describing a sub-rectangle of the screen
203           (possibly the entire screen). You can write to a window as
204           though it were a miniature screen, scrolling independently of
205           other windows on the physical screen.
206           
207    screens
208           A subset of windows which are as large as the terminal screen,
209           i.e., they start at the upper left hand corner and encompass
210           the lower right hand corner. One of these, stdscr, is
211           automatically provided for the programmer.
212           
213    terminal screen
214           The package's idea of what the terminal display currently looks
215           like, i.e., what the user sees now. This is a special screen.
216           
217                               The Curses Library
218                                        
219 An Overview of Curses
220
221   Compiling Programs using Curses
222   
223    In order to use the library, it is necessary to have certain types and
224    variables defined. Therefore, the programmer must have a line:
225           #include <curses.h>
226
227    at the top of the program source. The screen package uses the Standard
228    I/O library, so <curses.h> includes <stdio.h>. <curses.h> also
229    includes <termios.h>, <termio.h>, or <sgtty.h> depending on your
230    system. It is redundant (but harmless) for the programmer to do these
231    includes, too. In linking with curses you need to have -lncurses in
232    your LDFLAGS or on the command line. There is no need for any other
233    libraries.
234    
235   Updating the Screen
236   
237    In order to update the screen optimally, it is necessary for the
238    routines to know what the screen currently looks like and what the
239    programmer wants it to look like next. For this purpose, a data type
240    (structure) named WINDOW is defined which describes a window image to
241    the routines, including its starting position on the screen (the (y,
242    x) coordinates of the upper left hand corner) and its size. One of
243    these (called curscr, for current screen) is a screen image of what
244    the terminal currently looks like. Another screen (called stdscr, for
245    standard screen) is provided by default to make changes on.
246    
247    A window is a purely internal representation. It is used to build and
248    store a potential image of a portion of the terminal. It doesn't bear
249    any necessary relation to what is really on the terminal screen; it's
250    more like a scratchpad or write buffer.
251    
252    To make the section of physical screen corresponding to a window
253    reflect the contents of the window structure, the routine refresh()
254    (or wrefresh() if the window is not stdscr) is called.
255    
256    A given physical screen section may be within the scope of any number
257    of overlapping windows. Also, changes can be made to windows in any
258    order, without regard to motion efficiency. Then, at will, the
259    programmer can effectively say ``make it look like this,'' and let the
260    package implementation determine the most efficient way to repaint the
261    screen.
262    
263   Standard Windows and Function Naming Conventions
264   
265    As hinted above, the routines can use several windows, but two are
266    automatically given: curscr, which knows what the terminal looks like,
267    and stdscr, which is what the programmer wants the terminal to look
268    like next. The user should never actually access curscr directly.
269    Changes should be made to through the API, and then the routine
270    refresh() (or wrefresh()) called.
271    
272    Many functions are defined to use stdscr as a default screen. For
273    example, to add a character to stdscr, one calls addch() with the
274    desired character as argument. To write to a different window. use the
275    routine waddch() (for `w'indow-specific addch()) is provided. This
276    convention of prepending function names with a `w' when they are to be
277    applied to specific windows is consistent. The only routines which do
278    not follow it are those for which a window must always be specified.
279    
280    In order to move the current (y, x) coordinates from one point to
281    another, the routines move() and wmove() are provided. However, it is
282    often desirable to first move and then perform some I/O operation. In
283    order to avoid clumsiness, most I/O routines can be preceded by the
284    prefix 'mv' and the desired (y, x) coordinates prepended to the
285    arguments to the function. For example, the calls
286           move(y, x);
287           addch(ch);
288
289    can be replaced by
290           mvaddch(y, x, ch);
291
292    and
293           wmove(win, y, x);
294           waddch(win, ch);
295
296    can be replaced by
297           mvwaddch(win, y, x, ch);
298
299    Note that the window description pointer (win) comes before the added
300    (y, x) coordinates. If a function requires a window pointer, it is
301    always the first parameter passed.
302    
303   Variables
304   
305    The curses library sets some variables describing the terminal
306    capabilities.
307       type   name      description
308       ------------------------------------------------------------------
309       int    LINES     number of lines on the terminal
310       int    COLS      number of columns on the terminal
311
312    The curses.h also introduces some #define constants and types of
313    general usefulness:
314    
315    bool
316           boolean type, actually a `char' (e.g., bool doneit;)
317           
318    TRUE
319           boolean `true' flag (1).
320           
321    FALSE
322           boolean `false' flag (0).
323           
324    ERR
325           error flag returned by routines on a failure (-1).
326           
327    OK
328           error flag returned by routines when things go right.
329           
330 Using the Library
331
332    Now we describe how to actually use the screen package. In it, we
333    assume all updating, reading, etc. is applied to stdscr. These
334    instructions will work on any window, providing you change the
335    function names and parameters as mentioned above.
336    
337    Here is a sample program to motivate the discussion:
338    
339 #include <curses.h>
340 #include <signal.h>
341
342 static void finish(int sig);
343
344 main(int argc, char *argv[])
345 {
346     /* initialize your non-curses data structures here */
347
348     (void) signal(SIGINT, finish);      /* arrange interrupts to terminate */
349
350     (void) initscr();      /* initialize the curses library */
351     keypad(stdscr, TRUE);  /* enable keyboard mapping */
352     (void) nonl();         /* tell curses not to do NL->CR/NL on output */
353     (void) cbreak();       /* take input chars one at a time, no wait for \n */
354     (void) noecho();       /* don't echo input */
355
356     if (has_colors())
357     {
358         start_color();
359
360         /*
361          * Simple color assignment, often all we need.
362          */
363         init_pair(COLOR_BLACK, COLOR_BLACK, COLOR_BLACK);
364         init_pair(COLOR_GREEN, COLOR_GREEN, COLOR_BLACK);
365         init_pair(COLOR_RED, COLOR_RED, COLOR_BLACK);
366         init_pair(COLOR_CYAN, COLOR_CYAN, COLOR_BLACK);
367         init_pair(COLOR_WHITE, COLOR_WHITE, COLOR_BLACK);
368         init_pair(COLOR_MAGENTA, COLOR_MAGENTA, COLOR_BLACK);
369         init_pair(COLOR_BLUE, COLOR_BLUE, COLOR_BLACK);
370         init_pair(COLOR_YELLOW, COLOR_YELLOW, COLOR_BLACK);
371     }
372
373     for (;;)
374     {
375         int c = getch();     /* refresh, accept single keystroke of input */
376
377         /* process the command keystroke */
378     }
379
380     finish(0);               /* we're done */
381 }
382
383 static void finish(int sig)
384 {
385     endwin();
386
387     /* do your non-curses wrapup here */
388
389     exit(0);
390 }
391
392   Starting up
393   
394    In order to use the screen package, the routines must know about
395    terminal characteristics, and the space for curscr and stdscr must be
396    allocated. These function initscr() does both these things. Since it
397    must allocate space for the windows, it can overflow memory when
398    attempting to do so. On the rare occasions this happens, initscr()
399    will terminate the program with an error message. initscr() must
400    always be called before any of the routines which affect windows are
401    used. If it is not, the program will core dump as soon as either
402    curscr or stdscr are referenced. However, it is usually best to wait
403    to call it until after you are sure you will need it, like after
404    checking for startup errors. Terminal status changing routines like
405    nl() and cbreak() should be called after initscr().
406    
407    Once the screen windows have been allocated, you can set them up for
408    your program. If you want to, say, allow a screen to scroll, use
409    scrollok(). If you want the cursor to be left in place after the last
410    change, use leaveok(). If this isn't done, refresh() will move the
411    cursor to the window's current (y, x) coordinates after updating it.
412    
413    You can create new windows of your own using the functions newwin(),
414    derwin(), and subwin(). The routine delwin() will allow you to get rid
415    of old windows. All the options described above can be applied to any
416    window.
417    
418   Output
419   
420    Now that we have set things up, we will want to actually update the
421    terminal. The basic functions used to change what will go on a window
422    are addch() and move(). addch() adds a character at the current (y, x)
423    coordinates. move() changes the current (y, x) coordinates to whatever
424    you want them to be. It returns ERR if you try to move off the window.
425    As mentioned above, you can combine the two into mvaddch() to do both
426    things at once.
427    
428    The other output functions, such as addstr() and printw(), all call
429    addch() to add characters to the window.
430    
431    After you have put on the window what you want there, when you want
432    the portion of the terminal covered by the window to be made to look
433    like it, you must call refresh(). In order to optimize finding
434    changes, refresh() assumes that any part of the window not changed
435    since the last refresh() of that window has not been changed on the
436    terminal, i.e., that you have not refreshed a portion of the terminal
437    with an overlapping window. If this is not the case, the routine
438    touchwin() is provided to make it look like the entire window has been
439    changed, thus making refresh() check the whole subsection of the
440    terminal for changes.
441    
442    If you call wrefresh() with curscr as its argument, it will make the
443    screen look like curscr thinks it looks like. This is useful for
444    implementing a command which would redraw the screen in case it get
445    messed up.
446    
447   Input
448   
449    The complementary function to addch() is getch() which, if echo is
450    set, will call addch() to echo the character. Since the screen package
451    needs to know what is on the terminal at all times, if characters are
452    to be echoed, the tty must be in raw or cbreak mode. Since initially
453    the terminal has echoing enabled and is in ordinary ``cooked'' mode,
454    one or the other has to changed before calling getch(); otherwise, the
455    program's output will be unpredictable.
456    
457    When you need to accept line-oriented input in a window, the functions
458    wgetstr() and friends are available. There is even a wscanw() function
459    that can do scanf()(3)-style multi-field parsing on window input.
460    These pseudo-line-oriented functions turn on echoing while they
461    execute.
462    
463    The example code above uses the call keypad(stdscr, TRUE) to enable
464    support for function-key mapping. With this feature, the getch() code
465    watches the input stream for character sequences that correspond to
466    arrow and function keys. These sequences are returned as
467    pseudo-character values. The #define values returned are listed in the
468    curses.h The mapping from sequences to #define values is determined by
469    key_ capabilities in the terminal's terminfo entry.
470    
471   Using Forms Characters
472   
473    The addch() function (and some others, including box() and border())
474    can accept some pseudo-character arguments which are specially defined
475    by ncurses. These are #define values set up in the curses.h header;
476    see there for a complete list (look for the prefix ACS_).
477    
478    The most useful of the ACS defines are the forms-drawing characters.
479    You can use these to draw boxes and simple graphs on the screen. If
480    the terminal does not have such characters, curses.h will map them to
481    a recognizable (though ugly) set of ASCII defaults.
482    
483   Character Attributes and Color
484   
485    The ncurses package supports screen highlights including standout,
486    reverse-video, underline, and blink. It also supports color, which is
487    treated as another kind of highlight.
488    
489    Highlights are encoded, internally, as high bits of the
490    pseudo-character type (chtype) that curses.h uses to represent the
491    contents of a screen cell. See the curses.h header file for a complete
492    list of highlight mask values (look for the prefix A_).
493    
494    There are two ways to make highlights. One is to logical-or the value
495    of the highlights you want into the character argument of an addch()
496    call, or any other output call that takes a chtype argument.
497    
498    The other is to set the current-highlight value. This is logical-or'ed
499    with any highlight you specify the first way. You do this with the
500    functions attron(), attroff(), and attrset(); see the manual pages for
501    details. Color is a special kind of highlight. The package actually
502    thinks in terms of color pairs, combinations of foreground and
503    background colors. The sample code above sets up eight color pairs,
504    all of the guaranteed-available colors on black. Note that each color
505    pair is, in effect, given the name of its foreground color. Any other
506    range of eight non-conflicting values could have been used as the
507    first arguments of the init_pair() values.
508    
509    Once you've done an init_pair() that creates color-pair N, you can use
510    COLOR_PAIR(N) as a highlight that invokes that particular color
511    combination. Note that COLOR_PAIR(N), for constant N, is itself a
512    compile-time constant and can be used in initializers.
513    
514   Mouse Interfacing
515   
516    The ncurses library also provides a mouse interface. Note: his
517    facility is original to ncurses, it is not part of either the XSI
518    Curses standard, nor of System V Release 4, nor BSD curses. Thus, we
519    recommend that you wrap mouse-related code in an #ifdef using the
520    feature macro NCURSES_MOUSE_VERSION so it will not be compiled and
521    linked on non-ncurses systems.
522    
523    Presently, mouse event reporting works only under xterm. In the
524    future, ncurses will detect the presence of gpm(1), Alessandro
525    Rubini's freeware mouse server for Linux systems, and accept mouse
526    reports through it.
527    
528    The mouse interface is very simple. To activate it, you use the
529    function mousemask(), passing it as first argument a bit-mask that
530    specifies what kinds of events you want your program to be able to
531    see. It will return the bit-mask of events that actually become
532    visible, which may differ from the argument if the mouse device is not
533    capable of reporting some of the event types you specify.
534    
535    Once the mouse is active, your application's command loop should watch
536    for a return value of KEY_MOUSE from wgetch(). When you see this, a
537    mouse event report has been queued. To pick it off the queue, use the
538    function getmouse() (you must do this before the next wgetch(),
539    otherwise another mouse event might come in and make the first one
540    inaccessible).
541    
542    Each call to getmouse() fills a structure (the address of which you'll
543    pass it) with mouse event data. The event data includes zero-origin,
544    screen-relative character-cell coordinates of the mouse pointer. It
545    also includes an event mask. Bits in this mask will be set,
546    corresponding to the event type being reported.
547    
548    The mouse structure contains two additional fields which may be
549    significant in the future as ncurses interfaces to new kinds of
550    pointing device. In addition to x and y coordinates, there is a slot
551    for a z coordinate; this might be useful with touch-screens that can
552    return a pressure or duration parameter. There is also a device ID
553    field, which could be used to distinguish between multiple pointing
554    devices.
555    
556    The class of visible events may be changed at any time via
557    mousemask(). Events that can be reported include presses, releases,
558    single-, double- and triple-clicks (you can set the maximum
559    button-down time for clicks). If you don't make clicks visible, they
560    will be reported as press-release pairs. In some environments, the
561    event mask may include bits reporting the state of shift, alt, and
562    ctrl keys on the keyboard during the event.
563    
564    A function to check whether a mouse event fell within a given window
565    is also supplied. You can use this to see whether a given window
566    should consider a mouse event relevant to it.
567    
568    Because mouse event reporting will not be available in all
569    environments, it would be unwise to build ncurses applications that
570    require the use of a mouse. Rather, you should use the mouse as a
571    shortcut for point-and-shoot commands your application would normally
572    accept from the keyboard. Two of the test games in the ncurses
573    distribution (bs and knight) contain code that illustrates how this
574    can be done.
575    
576    See the manual page curs_mouse(3X) for full details of the
577    mouse-interface functions.
578    
579   Finishing Up
580   
581    In order to clean up after the ncurses routines, the routine endwin()
582    is provided. It restores tty modes to what they were when initscr()
583    was first called, and moves the cursor down to the lower-left corner.
584    Thus, anytime after the call to initscr, endwin() should be called
585    before exiting.
586    
587 Function Descriptions
588
589    We describe the detailed behavior of some important curses functions
590    here, as a supplement to the manual page descriptions.
591    
592   Initialization and Wrapup
593   
594    initscr()
595           The first function called should almost always be initscr().
596           This will determine the terminal type and initialize curses
597           data structures. initscr() also arranges that the first call to
598           refresh() will clear the screen. If an error occurs a message
599           is written to standard error and the program exits. Otherwise
600           it returns a pointer to stdscr. A few functions may be called
601           before initscr (slk_init(), filter(), ripofflines(), use_env(),
602           and, if you are using multiple terminals, newterm().)
603           
604    endwin()
605           Your program should always call endwin() before exiting or
606           shelling out of the program. This function will restore tty
607           modes, move the cursor to the lower left corner of the screen,
608           reset the terminal into the proper non-visual mode. Calling
609           refresh() or doupdate() after a temporary escape from the
610           program will restore the ncurses screen from before the escape.
611           
612    newterm(type, ofp, ifp)
613           A program which outputs to more than one terminal should use
614           newterm() instead of initscr(). newterm() should be called once
615           for each terminal. It returns a variable of type SCREEN * which
616           should be saved as a reference to that terminal. The arguments
617           are the type of the terminal (a string) and FILE pointers for
618           the output and input of the terminal. If type is NULL then the
619           environment variable $TERM is used. endwin() should called once
620           at wrapup time for each terminal opened using this function.
621           
622    set_term(new)
623           This function is used to switch to a different terminal
624           previously opened by newterm(). The screen reference for the
625           new terminal is passed as the parameter. The previous terminal
626           is returned by the function. All other calls affect only the
627           current terminal.
628           
629    delscreen(sp)
630           The inverse of newterm(); deallocates the data structures
631           associated with a given SCREEN reference.
632           
633   Causing Output to the Terminal
634   
635    refresh() and wrefresh(win)
636           These functions must be called to actually get any output on
637           the terminal, as other routines merely manipulate data
638           structures. wrefresh() copies the named window to the physical
639           terminal screen, taking into account what is already there in
640           order to do optimizations. refresh() does a refresh of
641           stdscr(). Unless leaveok() has been enabled, the physical
642           cursor of the terminal is left at the location of the window's
643           cursor.
644           
645    doupdate() and wnoutrefresh(win)
646           These two functions allow multiple updates with more efficiency
647           than wrefresh. To use them, it is important to understand how
648           curses works. In addition to all the window structures, curses
649           keeps two data structures representing the terminal screen: a
650           physical screen, describing what is actually on the screen, and
651           a virtual screen, describing what the programmer wants to have
652           on the screen. wrefresh works by first copying the named window
653           to the virtual screen (wnoutrefresh()), and then calling the
654           routine to update the screen (doupdate()). If the programmer
655           wishes to output several windows at once, a series of calls to
656           wrefresh will result in alternating calls to wnoutrefresh() and
657           doupdate(), causing several bursts of output to the screen. By
658           calling wnoutrefresh() for each window, it is then possible to
659           call doupdate() once, resulting in only one burst of output,
660           with fewer total characters transmitted (this also avoids a
661           visually annoying flicker at each update).
662           
663   Low-Level Capability Access
664   
665    setupterm(term, filenum, errret)
666           This routine is called to initialize a terminal's description,
667           without setting up the curses screen structures or changing the
668           tty-driver mode bits. term is the character string representing
669           the name of the terminal being used. filenum is the UNIX file
670           descriptor of the terminal to be used for output. errret is a
671           pointer to an integer, in which a success or failure indication
672           is returned. The values returned can be 1 (all is well), 0 (no
673           such terminal), or -1 (some problem locating the terminfo
674           database).
675           
676           The value of term can be given as NULL, which will cause the
677           value of TERM in the environment to be used. The errret pointer
678           can also be given as NULL, meaning no error code is wanted. If
679           errret is defaulted, and something goes wrong, setupterm() will
680           print an appropriate error message and exit, rather than
681           returning. Thus, a simple program can call setupterm(0, 1, 0)
682           and not worry about initialization errors.
683           
684           After the call to setupterm(), the global variable cur_term is
685           set to point to the current structure of terminal capabilities.
686           By calling setupterm() for each terminal, and saving and
687           restoring cur_term, it is possible for a program to use two or
688           more terminals at once. Setupterm() also stores the names
689           section of the terminal description in the global character
690           array ttytype[]. Subsequent calls to setupterm() will overwrite
691           this array, so you'll have to save it yourself if need be.
692           
693   Debugging
694   
695    NOTE: These functions are not part of the standard curses API!
696    
697    trace()
698           This function can be used to explicitly set a trace level. If
699           the trace level is nonzero, execution of your program will
700           generate a file called `trace' in the current working directory
701           containing a report on the library's actions. Higher trace
702           levels enable more detailed (and verbose) reporting -- see
703           comments attached to TRACE_ defines in the curses.h file for
704           details. (It is also possible to set a trace level by assigning
705           a trace level value to the environment variable NCURSES_TRACE).
706           
707    _tracef()
708           This function can be used to output your own debugging
709           information. It is only available only if you link with
710           -lncurses_g. It can be used the same way as printf(), only it
711           outputs a newline after the end of arguments. The output goes
712           to a file called trace in the current directory.
713           
714    Trace logs can be difficult to interpret due to the sheer volume of
715    data dumped in them. There is a script called tracemunch included with
716    the ncurses distribution that can alleviate this problem somewhat; it
717    compacts long sequences of similar operations into more succinct
718    single-line pseudo-operations. These pseudo-ops can be distinguished
719    by the fact that they are named in capital letters.
720    
721 Hints, Tips, and Tricks
722
723    The ncurses manual pages are a complete reference for this library. In
724    the remainder of this document, we discuss various useful methods that
725    may not be obvious from the manual page descriptions.
726    
727   Some Notes of Caution
728   
729    If you find yourself thinking you need to use noraw() or nocbreak(),
730    think again and move carefully. It's probably better design to use
731    getstr() or one of its relatives to simulate cooked mode. The noraw()
732    and nocbreak() functions try to restore cooked mode, but they may end
733    up clobbering some control bits set before you started your
734    application. Also, they have always been poorly documented, and are
735    likely to hurt your application's usability with other curses
736    libraries.
737    
738    Bear in mind that refresh() is a synonym for wrefresh(stdscr), and
739    don't try to mix use of stdscr with use of windows declared by
740    newwin(); a refresh() call will blow them off the screen. The right
741    way to handle this is to use subwin(), or not touch stdscr at all and
742    tile your screen with declared windows which you then wnoutrefresh()
743    somewhere in your program event loop, with a single doupdate() call to
744    trigger actual repainting.
745    
746    You are much less likely to run into problems if you design your
747    screen layouts to use tiled rather than overlapping windows.
748    Historically, curses support for overlapping windows has been weak,
749    fragile, and poorly documented. The ncurses library is not yet an
750    exception to this rule.
751    
752    There is a freeware panels library included in the ncurses
753    distribution that does a pretty good job of strengthening the
754    overlapping-windows facilities.
755    
756    Try to avoid using the global variables LINES and COLS. Use getmaxyx()
757    on the stdscr context instead. Reason: your code may be ported to run
758    in an environment with window resizes, in which case several screens
759    could be open with different sizes.
760    
761   Temporarily Leaving ncurses Mode
762   
763    Sometimes you will want to write a program that spends most of its
764    time in screen mode, but occasionally returns to ordinary `cooked'
765    mode. A common reason for this is to support shell-out. This behavior
766    is simple to arrange in ncurses.
767    
768    To leave ncurses mode, call endwin() as you would if you were
769    intending to terminate the program. This will take the screen back to
770    cooked mode; you can do your shell-out. When you want to return to
771    ncurses mode, simply call refresh() or doupdate(). This will repaint
772    the screen.
773    
774    There is a boolean function, isendwin(), which code can use to test
775    whether ncurses screen mode is active. It returns TRUE in the interval
776    between an endwin() call and the following refresh(), FALSE otherwise.
777    
778    Here is some sample code for shellout:
779     addstr("Shelling out...");
780     def_prog_mode();           /* save current tty modes */
781     endwin();                  /* restore original tty modes */
782     system("sh");              /* run shell */
783     addstr("returned.\n");     /* prepare return message */
784     refresh();                 /* restore save modes, repaint screen */
785
786   Using ncurses Under xterm
787   
788    A resize operation in X sends SIGWINCH to the application running
789    under xterm. The ncurses library does not catch this signal, because
790    it cannot in general know how you want the screen re-painted. You will
791    have to write the SIGWINCH handler yourself.
792    
793    The easiest way to code your SIGWINCH handler is to have it do an
794    endwin, followed by an refresh and a screen repaint you code yourself.
795    The refresh will pick up the new screen size from the xterm's
796    environment.
797    
798   Handling Multiple Terminal Screens
799   
800    The initscr() function actually calls a function named newterm() to do
801    most of its work. If you are writing a program that opens multiple
802    terminals, use newterm() directly.
803    
804    For each call, you will have to specify a terminal type and a pair of
805    file pointers; each call will return a screen reference, and stdscr
806    will be set to the last one allocated. You will switch between screens
807    with the set_term call. Note that you will also have to call
808    def_shell_mode and def_prog_mode on each tty yourself.
809    
810   Testing for Terminal Capabilities
811   
812    Sometimes you may want to write programs that test for the presence of
813    various capabilities before deciding whether to go into ncurses mode.
814    An easy way to do this is to call setupterm(), then use the functions
815    tigetflag(), tigetnum(), and tigetstr() to do your testing.
816    
817    A particularly useful case of this often comes up when you want to
818    test whether a given terminal type should be treated as `smart'
819    (cursor-addressable) or `stupid'. The right way to test this is to see
820    if the return value of tigetstr("cup") is non-NULL. Alternatively, you
821    can include the term.h file and test the value of the macro
822    cursor_address.
823    
824   Tuning for Speed
825   
826    Use the addchstr() family of functions for fast screen-painting of
827    text when you know the text doesn't contain any control characters.
828    Try to make attribute changes infrequent on your screens. Don't use
829    the immedok() option!
830    
831   Special Features of ncurses
832   
833    When running on PC-clones, ncurses has enhanced support for the IBM
834    high-half and ROM characters. The A_ALTCHARSET highlight, enables
835    display of both high-half ACS graphics and the PC ROM graphics 0-31
836    that are normally interpreted as control characters.
837    
838    The wresize() function allows you to resize a window in place.
839    
840 Compatibility with Older Versions
841
842    Despite our best efforts, there are some differences between ncurses
843    and the (undocumented!) behavior of older curses implementations.
844    These arise from ambiguities or omissions in the documentation of the
845    API.
846    
847   Refresh of Overlapping Windows
848   
849    If you define two windows A and B that overlap, and then alternately
850    scribble on and refresh them, the changes made to the overlapping
851    region under historic curses versions were often not documented
852    precisely.
853    
854    To understand why this is a problem, remember that screen updates are
855    calculated between two representations of the entire display. The
856    documentation says that when you refresh a window, it is first copied
857    to to the virtual screen, and then changes are calculated to update
858    the physical screen (and applied to the terminal). But "copied to" is
859    not very specific, and subtle differences in how copying works can
860    produce different behaviors in the case where two overlapping windows
861    are each being refreshed at unpredictable intervals.
862    
863    What happens to the overlapping region depends on what wnoutrefresh()
864    does with its argument -- what portions of the argument window it
865    copies to the virtual screen. Some implementations do "change copy",
866    copying down only locations in the window that have changed (or been
867    marked changed with wtouchln() and friends). Some implementations do
868    "entire copy", copying all window locations to the virtual screen
869    whether or not they have changed.
870    
871    The ncurses library itself has not always been consistent on this
872    score. Due to a bug, versions 1.8.7 to 1.9.8a did entire copy.
873    Versions 1.8.6 and older, and versions 1.9.9 and newer, do change
874    copy.
875    
876    For most commercial curses implementations, it is not documented and
877    not known for sure (at least not to the ncurses maintainers) whether
878    they do change copy or entire copy. We know that System V release 3
879    curses has logic in it that looks like an attempt to do change copy,
880    but the surrounding logic and data representations are sufficiently
881    complex, and our knowledge sufficiently indirect, that it's hard to
882    know whether this is reliable. It is not clear what the SVr4
883    documentation and XSI standard intend. The XSI Curses standard barely
884    mentions wnoutrefresh(); the SVr4 documents seem to be describing
885    entire-copy, but it is possible with some effort and straining to read
886    them the other way.
887    
888    It might therefore be unwise to rely on either behavior in programs
889    that might have to be linked with other curses implementations.
890    Instead, you can do an explicit touchwin() before the wnoutrefresh()
891    call to guarantee an entire-contents copy anywhere.
892    
893    The really clean way to handle this is to use the panels library. If,
894    when you want a screen update, you do update_panels(), it will do all
895    the necessary wnoutrfresh() calls for whatever panel stacking order
896    you have defined. Then you can do one doupdate() and there will be a
897    single burst of physical I/O that will do all your updates.
898    
899   Background Erase
900   
901    If you have been using a very old versions of ncurses (1.8.7 or older)
902    you may be surprised by the behavior of the erase functions. In older
903    versions, erased areas of a window were filled with a blank modified
904    by the window's current attribute (as set by wattrset(), wattron(),
905    wattroff() and friends).
906    
907    In newer versions, this is not so. Instead, the attribute of erased
908    blanks is normal unless and until it is modified by the functions
909    bkgdset() or wbkgdset().
910    
911    This change in behavior conforms ncurses to System V Release 4 and the
912    XSI Curses standard.
913    
914 XSI Curses Conformance
915
916    The ncurses library is intended to be base-level conformant with the
917    XSI Curses standard from X/Open. Many extended-level features (in
918    fact, almost all features not directly concerned with wide characters
919    and internationalization) are also supported.
920    
921    One effect of XSI conformance is the change in behavior described
922    under "Background Erase -- Compatibility with Old Versions".
923    
924    Also, ncurses meets the XSI requirement that every macro entry point
925    have a corresponding function which may be linked (and will be
926    prototype-checked) if the macro definition is disabled with #undef.
927    
928                               The Panels Library
929                                        
930    The ncurses library by itself provides good support for screen
931    displays in which the windows are tiled (non-overlapping). In the more
932    general case that windows may overlap, you have to use a series of
933    wnoutrefresh() calls followed by a doupdate(), and be careful about
934    the order you do the window refreshes in. It has to be bottom-upwards,
935    otherwise parts of windows that should be obscured will show through.
936    
937    When your interface design is such that windows may dive deeper into
938    the visibility stack or pop to the top at runtime, the resulting
939    book-keeping can be tedious and difficult to get right. Hence the
940    panels library.
941    
942    The panel library first appeared in AT&T System V. The version
943    documented here is the freeware panel code distributed with ncurses.
944    
945 Compiling With the Panels Library
946
947    Your panels-using modules must import the panels library declarations
948    with
949           #include <panel.h>
950
951    and must be linked explicitly with the panels library using an -lpanel
952    argument. Note that they must also link the ncurses library with
953    -lncurses. Many linkers are two-pass and will accept either order, but
954    it is still good practice to put -lpanel first and -lncurses second.
955    
956 Overview of Panels
957
958    A panel object is a window that is implicitly treated as part of a
959    deck including all other panel objects. The deck has an implicit
960    bottom-to-top visibility order. The panels library includes an update
961    function (analogous to refresh()) that displays all panels in the deck
962    in the proper order to resolve overlaps. The standard window, stdscr,
963    is considered below all panels.
964    
965    Details on the panels functions are available in the man pages. We'll
966    just hit the highlights here.
967    
968    You create a panel from a window by calling new_panel() on a window
969    pointer. It then becomes the top of the deck. The panel's window is
970    available as the value of panel_window() called with the panel pointer
971    as argument.
972    
973    You can delete a panel (removing it from the deck) with del_panel.
974    This will not deallocate the associated window; you have to do that
975    yourself. You can replace a panel's window with a different window by
976    calling replace_window. The new window may be of different size; the
977    panel code will re-compute all overlaps. This operation doesn't change
978    the panel's position in the deck.
979    
980    To move a panel's window, use move_panel(). The mvwin() function on
981    the panel's window isn't sufficient because it doesn't update the
982    panels library's representation of where the windows are. This
983    operation leaves the panel's depth, contents, and size unchanged.
984    
985    Two functions (top_panel(), bottom_panel()) are provided for
986    rearranging the deck. The first pops its argument window to the top of
987    the deck; the second sends it to the bottom. Either operation leaves
988    the panel's screen location, contents, and size unchanged.
989    
990    The function update_panels() does all the wnoutrefresh() calls needed
991    to prepare for doupdate() (which you must call yourself, afterwards).
992    
993    Typically, you will want to call update_panels() and doupdate() just
994    before accepting command input, once in each cycle of interaction with
995    the user. If you call update_panels() after each and every panel
996    write, you'll generate a lot of unnecessary refresh activity and
997    screen flicker.
998    
999 Panels, Input, and the Standard Screen
1000
1001    You shouldn't mix wnoutrefresh() or wrefresh() operations with panels
1002    code; this will work only if the argument window is either in the top
1003    panel or unobscured by any other panels.
1004    
1005    The stsdcr window is a special case. It is considered below all
1006    panels. Because changes to panels may obscure parts of stdscr, though,
1007    you should call update_panels() before doupdate() even when you only
1008    change stdscr.
1009    
1010    Note that wgetch automatically calls wrefresh. Therefore, before
1011    requesting input from a panel window, you need to be sure that the
1012    panel is totally unobscured.
1013    
1014    There is presently no way to display changes to one obscured panel
1015    without repainting all panels.
1016    
1017 Hiding Panels
1018
1019    It's possible to remove a panel from the deck temporarily; use
1020    hide_panel for this. Use show_panel() to render it visible again. The
1021    predicate function panel_hidden tests whether or not a panel is
1022    hidden.
1023    
1024    The panel_update code ignores hidden panels. You cannot do top_panel()
1025    or bottom_panel on a hidden panel(). Other panels operations are
1026    applicable.
1027    
1028 Miscellaneous Other Facilities
1029
1030    It's possible to navigate the deck using the functions panel_above()
1031    and panel_below. Handed a panel pointer, they return the panel above
1032    or below that panel. Handed NULL, they return the bottom-most or
1033    top-most panel.
1034    
1035    Every panel has an associated user pointer, not used by the panel
1036    code, to which you can attach application data. See the man page
1037    documentation of set_panel_userptr() and panel_userptr for details.
1038    
1039                                The Menu Library
1040                                        
1041    A menu is a screen display that assists the user to choose some subset
1042    of a given set of items. The menu library is a curses extension that
1043    supports easy programming of menu hierarchies with a uniform but
1044    flexible interface.
1045    
1046    The menu library first appeared in AT&T System V. The version
1047    documented here is the freeware menu code distributed with ncurses.
1048    
1049 Compiling With the menu Library
1050
1051    Your menu-using modules must import the menu library declarations with
1052           #include <menu.h>
1053
1054    and must be linked explicitly with the menus library using an -lmenu
1055    argument. Note that they must also link the ncurses library with
1056    -lncurses. Many linkers are two-pass and will accept either order, but
1057    it is still good practice to put -lmenu first and -lncurses second.
1058    
1059 Overview of Menus
1060
1061    The menus created by this library consist of collections of items
1062    including a name string part and a description string part. To make
1063    menus, you create groups of these items and connect them with menu
1064    frame objects.
1065    
1066    The menu can then by posted, that is written to an associated window.
1067    Actually, each menu has two associated windows; a containing window in
1068    which the programmer can scribble titles or borders, and a subwindow
1069    in which the menu items proper are displayed. If this subwindow is too
1070    small to display all the items, it will be a scrollable viewport on
1071    the collection of items.
1072    
1073    A menu may also be unposted (that is, undisplayed), and finally freed
1074    to make the storage associated with it and its items available for
1075    re-use.
1076    
1077    The general flow of control of a menu program looks like this:
1078     1. Initialize curses.
1079     2. Create the menu items, using new_item().
1080     3. Create the menu using new_menu().
1081     4. Post the menu using menu_post().
1082     5. Refresh the screen.
1083     6. Process user requests via an input loop.
1084     7. Unpost the menu using menu_unpost().
1085     8. Free the menu, using free_menu().
1086     9. Free the items using free_item().
1087    10. Terminate curses.
1088        
1089 Selecting items
1090
1091    Menus may be multi-valued or (the default) single-valued (see the
1092    manual page menu_opts(3x) to see how to change the default). Both
1093    types always have a current item.
1094    
1095    From a single-valued menu you can read the selected value simply by
1096    looking at the current item. From a multi-valued menu, you get the
1097    selected set by looping through the items applying the item_value()
1098    predicate function. Your menu-processing code can use the function
1099    set_item_value() to flag the items in the select set.
1100    
1101    Menu items can be made unselectable using set_item_opts() or
1102    item_opts_off() with the O_SELECTABLE argument. This is the only
1103    option so far defined for menus, but it is good practice to code as
1104    though other option bits might be on.
1105    
1106 Menu Display
1107
1108    The menu library calculates a minimum display size for your window,
1109    based on the following variables:
1110    
1111      * The number and maximum length of the menu items
1112      * Whether the O_ROWMAJOR option is enabled
1113      * Whether display of descriptions is enabled
1114      * Whatever menu format may have been set by the programmer
1115      * The length of the menu mark string used for highlighting selected
1116        items
1117        
1118    The function set_menu_format() allows you to set the maximum size of
1119    the viewport or menu page that will be used to display menu items. You
1120    can retrieve any format associated with a menu with menu_format(). The
1121    default format is rows=16, columns=1.
1122    
1123    The actual menu page may be smaller than the format size. This depends
1124    on the item number and size and whether O_ROWMAJOR is on. This option
1125    (on by default) causes menu items to be displayed in a `raster-scan'
1126    pattern, so that if more than one item will fit horizontally the first
1127    couple of items are side-by-side in the top row. The alternative is
1128    column-major display, which tries to put the first several items in
1129    the first column.
1130    
1131    As mentioned above, a menu format not large enough to allow all items
1132    to fit on-screen will result in a menu display that is vertically
1133    scrollable.
1134    
1135    You can scroll it with requests to the menu driver, which will be
1136    described in the section on menu input handling.
1137    
1138    Each menu has a mark string used to visually tag selected items; see
1139    the menu_mark(3x) manual page for details. The mark string length also
1140    influences the menu page size.
1141    
1142    The function scale_menu() returns the minimum display size that the
1143    menu code computes from all these factors. There are other menu
1144    display attributes including a select attribute, an attribute for
1145    selectable items, an attribute for unselectable items, and a pad
1146    character used to separate item name text from description text. These
1147    have reasonable defaults which the library allows you to change (see
1148    the menu_attribs(3x) manual page.
1149    
1150 Menu Windows
1151
1152    Each menu has, as mentioned previously, a pair of associated windows.
1153    Both these windows are painted when the menu is posted and erased when
1154    the menu is unposted.
1155    
1156    The outer or frame window is not otherwise touched by the menu
1157    routines. It exists so the programmer can associate a title, a border,
1158    or perhaps help text with the menu and have it properly refreshed or
1159    erased at post/unpost time. The inner window or subwindow is where the
1160    current menu page is displayed.
1161    
1162    By default, both windows are stdscr. You can set them with the
1163    functions in menu_win(3x).
1164    
1165    When you call menu_post(), you write the menu to its subwindow. When
1166    you call menu_unpost(), you erase the subwindow, However, neither of
1167    these actually modifies the screen. To do that, call wrefresh() or
1168    some equivalent.
1169    
1170 Processing Menu Input
1171
1172    The main loop of your menu-processing code should call menu_driver()
1173    repeatedly. The first argument of this routine is a menu pointer; the
1174    second is a menu command code. You should write an input-fetching
1175    routine that maps input characters to menu command codes, and pass its
1176    output to menu_driver(). The menu command codes are fully documented
1177    in menu_driver(3x).
1178    
1179    The simplest group of command codes is REQ_NEXT_ITEM, REQ_PREV_ITEM,
1180    REQ_FIRST_ITEM, REQ_LAST_ITEM, REQ_UP_ITEM, REQ_DOWN_ITEM,
1181    REQ_LEFT_ITEM, REQ_RIGHT_ITEM. These change the currently selected
1182    item. These requests may cause scrolling of the menu page if it only
1183    partially displayed.
1184    
1185    There are explicit requests for scrolling which also change the
1186    current item (because the select location does not change, but the
1187    item there does). These are REQ_SCR_DLINE, REQ_SCR_ULINE,
1188    REQ_SCR_DPAGE, and REQ_SCR_UPAGE.
1189    
1190    The REQ_TOGGLE_ITEM selects or deselects the current item. It is for
1191    use in multi-valued menus; if you use it with O_ONEVALUE on, you'll
1192    get an error return (E_REQUEST_DENIED).
1193    
1194    Each menu has an associated pattern buffer. The menu_driver() logic
1195    tries to accumulate printable ASCII characters passed in in that
1196    buffer; when it matches a prefix of an item name, that item (or the
1197    next matching item) is selected. If appending a character yields no
1198    new match, that character is deleted from the pattern buffer, and
1199    menu_driver() returns E_NO_MATCH.
1200    
1201    Some requests change the pattern buffer directly: REQ_CLEAR_PATTERN,
1202    REQ_BACK_PATTERN, REQ_NEXT_MATCH, REQ_PREV_MATCH. The latter two are
1203    useful when pattern buffer input matches more than one item in a
1204    multi-valued menu.
1205    
1206    Each successful scroll or item navigation request clears the pattern
1207    buffer. It is also possible to set the pattern buffer explicitly with
1208    set_menu_pattern().
1209    
1210    Finally, menu driver requests above the constant MAX_COMMAND are
1211    considered application-specific commands. The menu_driver() code
1212    ignores them and returns E_UNKNOWN_COMMAND.
1213    
1214 Miscellaneous Other Features
1215
1216    Various menu options can affect the processing and visual appearance
1217    and input processing of menus. See menu_opts(3x) for details.
1218    
1219    It is possible to change the current item from application code; this
1220    is useful if you want to write your own navigation requests. It is
1221    also possible to explicitly set the top row of the menu display. See
1222    mitem_current(3x). If your application needs to change the menu
1223    subwindow cursor for any reason, pos_menu_cursor() will restore it to
1224    the correct location for continuing menu driver processing.
1225    
1226    It is possible to set hooks to be called at menu initialization and
1227    wrapup time, and whenever the selected item changes. See
1228    menu_hook(3x).
1229    
1230    Each item, and each menu, has an associated user pointer on which you
1231    can hang application data. See mitem_userptr(3x) and menu_userptr(3x).
1232    
1233                                The Forms Library
1234                                        
1235    The form library is a curses extension that supports easy programming
1236    of on-screen forms for data entry and program control.
1237    
1238    The form library first appeared in AT&T System V. The version
1239    documented here is the freeware form code distributed with ncurses.
1240    
1241 Compiling With the form Library
1242
1243    Your form-using modules must import the form library declarations with
1244           #include <form.h>
1245
1246    and must be linked explicitly with the forms library using an -lform
1247    argument. Note that they must also link the ncurses library with
1248    -lncurses. Many linkers are two-pass and will accept either order, but
1249    it is still good practice to put -lform first and -lncurses second.
1250    
1251 Overview of Forms
1252
1253    A form is a collection of fields; each field may be either a label
1254    (explanatory text) or a data-entry location. Long forms may be
1255    segmented into pages; each entry to a new page clears the screen.
1256    
1257    To make forms, you create groups of fields and connect them with form
1258    frame objects; the form library makes this relatively simple.
1259    
1260    Once defined, a form can be posted, that is written to an associated
1261    window. Actually, each form has two associated windows; a containing
1262    window in which the programmer can scribble titles or borders, and a
1263    subwindow in which the form fields proper are displayed.
1264    
1265    As the form user fills out the posted form, navigation and editing
1266    keys support movement between fields, editing keys support modifying
1267    field, and plain text adds to or changes data in a current field. The
1268    form library allows you (the forms designer) to bind each navigation
1269    and editing key to any keystroke accepted by curses Fields may have
1270    validation conditions on them, so that they check input data for type
1271    and value. The form library supplies a rich set of pre-defined field
1272    types, and makes it relatively easy to define new ones.
1273    
1274    Once its transaction is completed (or aborted), a form may be unposted
1275    (that is, undisplayed), and finally freed to make the storage
1276    associated with it and its items available for re-use.
1277    
1278    The general flow of control of a form program looks like this:
1279     1. Initialize curses.
1280     2. Create the form fields, using new_field().
1281     3. Create the form using new_form().
1282     4. Post the form using form_post().
1283     5. Refresh the screen.
1284     6. Process user requests via an input loop.
1285     7. Unpost the form using form_unpost().
1286     8. Free the form, using free_form().
1287     9. Free the fields using free_field().
1288    10. Terminate curses.
1289        
1290    Note that this looks much like a menu program; the form library
1291    handles tasks which are in many ways similar, and its interface was
1292    obviously designed to resemble that of the menu library wherever
1293    possible.
1294    
1295    In forms programs, however, the `process user requests' is somewhat
1296    more complicated than for menus. Besides menu-like navigation
1297    operations, the menu driver loop has to support field editing and data
1298    validation.
1299    
1300 Creating and Freeing Fields and Forms
1301
1302    The basic function for creating fields is new_field():
1303    
1304 FIELD *new_field(int height, int width,   /* new field size */
1305                  int top, int left,       /* upper left corner */
1306                  int offscreen,           /* number of offscreen rows */
1307                  int nbuf);               /* number of working buffers */
1308
1309    Menu items always occupy a single row, but forms fields may have
1310    multiple rows. So new_field() requires you to specify a width and
1311    height (the first two arguments, which mist both be greater than
1312    zero).
1313    
1314    You must also specify the location of the field's upper left corner on
1315    the screen (the third and fourth arguments, which must be zero or
1316    greater). Note that these coordinates are relative to the form
1317    subwindow, which will coincide with stdscr by default but need not be
1318    stdscr if you've done an explicit set_form_window() call.
1319    
1320    The fifth argument allows you to specify a number of off-screen rows.
1321    If this is zero, the entire field will always be displayed. If it is
1322    nonzero, the form will be scrollable, with only one screen-full
1323    (initially the top part) displayed at any given time. If you make a
1324    field dynamic and grow it so it will no longer fit on the screen, the
1325    form will become scrollable even if the offscreen argument was
1326    initially zero.
1327    
1328    The forms library allocates one working buffer per field; the size of
1329    each buffer is ((height + offscreen)*width + 1, one character for each
1330    position in the field plus a NUL terminator. The sixth argument is the
1331    number of additional data buffers to allocate for the field; your
1332    application can use them for its own purposes.
1333    
1334 FIELD *dup_field(FIELD *field,            /* field to copy */
1335                  int top, int left);      /* location of new copy */
1336
1337    The function dup_field() duplicates an existing field at a new
1338    location. Size and buffering information are copied; some attribute
1339    flags and status bits are not (see the form_field_new(3X) for
1340    details).
1341    
1342 FIELD *link_field(FIELD *field,           /* field to copy */
1343                   int top, int left);     /* location of new copy */
1344
1345    The function link_field() also duplicates an existing field at a new
1346    location. The difference from dup_field() is that it arranges for the
1347    new field's buffer to be shared with the old one.
1348    
1349    Besides the obvious use in making a field editable from two different
1350    form pages, linked fields give you a way to hack in dynamic labels. If
1351    you declare several fields linked to an original, and then make them
1352    inactive, changes from the original will still be propagated to the
1353    linked fields.
1354    
1355    As with duplicated fields, linked fields have attribute bits separate
1356    from the original.
1357    
1358    As you might guess, all these field-allocations return NULL if the
1359    field allocation is not possible due to an out-of-memory error or
1360    out-of-bounds arguments.
1361    
1362    To connect fields to a form, use
1363    
1364 FORM *new_form(FIELD **fields);
1365
1366    This function expects to see a NULL-terminated array of field
1367    pointers. Said fields are connected to a newly-allocated form object;
1368    its address is returned (or else NULL if the allocation fails).
1369    
1370    Note that new_field() does not copy the pointer array into private
1371    storage; if you modify the contents of the pointer array during forms
1372    processing, all manner of bizarre things might happen. Also note that
1373    any given field may only be connected to one form.
1374    
1375    The functions free_field() and free_form are available to free field
1376    and form objects. It is an error to attempt to free a field connected
1377    to a form, but not vice-versa; thus, you will generally free your form
1378    objects first.
1379    
1380 Fetching and Changing Field Attributes
1381
1382    Each form field has a number of location and size attributes
1383    associated with it. There are other field attributes used to control
1384    display and editing of the field. Some (for example, the O_STATIC bit)
1385    involve sufficient complications to be covered in sections of their
1386    own later on. We cover the functions used to get and set several basic
1387    attributes here.
1388    
1389    When a field is created, the attributes not specified by the new_field
1390    function are copied from an invisible system default field. In
1391    attribute-setting and -fetching functions, the argument NULL is taken
1392    to mean this field. Changes to it persist as defaults until your forms
1393    application terminates.
1394    
1395   Fetching Size and Location Data
1396   
1397    You can retrieve field sizes and locations through:
1398    
1399 int field_info(FIELD *field,              /* field from which to fetch */
1400                int *height, *int width,   /* field size */
1401                int *top, int *left,       /* upper left corner */
1402                int *offscreen,            /* number of offscreen rows */
1403                int *nbuf);                /* number of working buffers */
1404
1405    This function is a sort of inverse of new_field(); instead of setting
1406    size and location attributes of a new field, it fetches them from an
1407    existing one.
1408    
1409   Changing the Field Location
1410   
1411    If is possible to move a field's location on the screen:
1412    
1413 int move_field(FIELD *field,              /* field to alter */
1414                int top, int left);        /* new upper-left corner */
1415
1416    You can, of course. query the current location through field_info().
1417    
1418   The Justification Attribute
1419   
1420    One-line fields may be unjustified, justified right, justified left,
1421    or centered. Here is how you manipulate this attribute:
1422    
1423 int set_field_just(FIELD *field,          /* field to alter */
1424                    int justmode);         /* mode to set */
1425
1426 int field_just(FIELD *field);             /* fetch mode of field */
1427
1428    The mode values accepted and returned by this functions are
1429    preprocessor macros NO_JUSTIFICATION, JUSTIFY_RIGHT, JUSTIFY_LEFT, or
1430    JUSTIFY_CENTER.
1431    
1432   Field Display Attributes
1433   
1434    For each field, you can set a foreground attribute for entered
1435    characters, a background attribute for the entire field, and a pad
1436    character for the unfilled portion of the field. You can also control
1437    pagination of the form.
1438    
1439    This group of four field attributes controls the visual appearance of
1440    the field on the screen, without affecting in any way the data in the
1441    field buffer.
1442    
1443 int set_field_fore(FIELD *field,          /* field to alter */
1444                    chtype attr);          /* attribute to set */
1445
1446 chtype field_fore(FIELD *field);          /* field to query */
1447
1448 int set_field_back(FIELD *field,          /* field to alter */
1449                    chtype attr);          /* attribute to set */
1450
1451 chtype field_back(FIELD *field);          /* field to query */
1452
1453 int set_field_pad(FIELD *field,           /* field to alter */
1454                  int pad);                /* pad character to set */
1455
1456 chtype field_pad(FIELD *field);
1457
1458 int set_new_page(FIELD *field,            /* field to alter */
1459                  int flag);               /* TRUE to force new page */
1460
1461 chtype new_page(FIELD *field);            /* field to query */
1462
1463    The attributes set and returned by the first four functions are normal
1464    curses(3x) display attribute values (A_STANDOUT, A_BOLD, A_REVERSE
1465    etc). The page bit of a field controls whether it is displayed at the
1466    start of a new form screen.
1467    
1468   Field Option Bits
1469   
1470    There is also a large collection of field option bits you can set to
1471    control various aspects of forms processing. You can manipulate them
1472    with these functions:
1473 int set_field_opts(FIELD *field,          /* field to alter */
1474                    int attr);             /* attribute to set */
1475
1476 int field_opts_on(FIELD *field,           /* field to alter */
1477                   int attr);              /* attributes to turn on */
1478
1479 int field_opts_off(FIELD *field,          /* field to alter */
1480                    int attr);             /* attributes to turn off */
1481
1482 int field_opts(FIELD *field);             /* field to query */
1483
1484    By default, all options are on. Here are the available option bits:
1485    
1486    O_VISIBLE
1487           Controls whether the field is visible on the screen. Can be
1488           used during form processing to hide or pop up fields depending
1489           on the value of parent fields.
1490           
1491    O_ACTIVE
1492           Controls whether the field is active during forms processing
1493           (i.e. visited by form navigation keys). Can be used to make
1494           labels or derived fields with buffer values alterable by the
1495           forms application, not the user.
1496           
1497    O_PUBLIC
1498           Controls whether data is displayed during field entry. If this
1499           option is turned off on a field, the library will accept and
1500           edit data in that field, but it will not be displayed and the
1501           visible field cursor will not move. You can turn off the
1502           O_PUBLIC bit to define password fields.
1503           
1504    O_EDIT
1505           Controls whether the field's data can be modified. When this
1506           option is off, all editing requests except REQ_PREV_CHOICE and
1507           REQ_NEXT_CHOICE will fail. Such read-only fields may be useful
1508           for help messages.
1509           
1510    O_WRAP
1511           Controls word-wrapping in multi-line fields. Normally, when any
1512           character of a (blank-separated) word reaches the end of the
1513           current line, the entire word is wrapped to the next line
1514           (assuming there is one). When this option is off, the word will
1515           be split across the line break.
1516           
1517    O_BLANK
1518           Controls field blanking. When this option is on, entering a
1519           character at the first field position erases the entire field
1520           (except for the just-entered character).
1521           
1522    O_AUTOSKIP
1523           Controls automatic skip to next field when this one fills.
1524           Normally, when the forms user tries to type more data into a
1525           field than will fit, the editing location jumps to next field.
1526           When this option is off, the user's cursor will hang at the end
1527           of the field. This option is ignored in dynamic fields that
1528           have not reached their size limit.
1529           
1530    O_NULLOK
1531           Controls whether validation is applied to blank fields.
1532           Normally, it is not; the user can leave a field blank without
1533           invoking the usual validation check on exit. If this option is
1534           off on a field, exit from it will invoke a validation check.
1535           
1536    O_PASSOK
1537           Controls whether validation occurs on every exit, or only after
1538           the field is modified. Normally the latter is true. Setting
1539           O_PASSOK may be useful if your field's validation function may
1540           change during forms processing.
1541           
1542    O_STATIC
1543           Controls whether the field is fixed to its initial dimensions.
1544           If you turn this off, the field becomes dynamic and will
1545           stretch to fit entered data.
1546           
1547    A field's options cannot be changed while the field is currently
1548    selected. However, options may be changed on posted fields that are
1549    not current.
1550    
1551    The option values are bit-masks and can be composed with logical-or in
1552    the obvious way.
1553    
1554 Field Status
1555
1556    Every field has a status flag, which is set to FALSE when the field is
1557    created and TRUE when the value in field buffer 0 changes. This flag
1558    can be queried and set directly:
1559    
1560 int set_field_status(FIELD *field,      /* field to alter */
1561                    int status);         /* mode to set */
1562
1563 int field_status(FIELD *field);         /* fetch mode of field */
1564
1565    Setting this flag under program control can be useful if you use the
1566    same form repeatedly, looking for modified fields each time.
1567    
1568    Calling field_status() on a field not currently selected for input
1569    will return a correct value. Calling field_status() on a field that is
1570    currently selected for input may not necessarily give a correct field
1571    status value, because entered data isn't necessarily copied to buffer
1572    zero before the exit validation check. To guarantee that the returned
1573    status value reflects reality, call field_status() either (1) in the
1574    field's exit validation check routine, (2) from the field's or form's
1575    initialization or termination hooks, or (3) just after a
1576    REQ_VALIDATION request has been processed by the forms driver.
1577    
1578 Field User Pointer
1579
1580    Each field structure contains one character pointer slot that is not
1581    used by the forms library. It is intended to be used by applications
1582    to store private per-field data. You can manipulate it with:
1583 int set_field_userptr(FIELD *field,       /* field to alter */
1584                    char *userptr);        /* mode to set */
1585
1586 char *field_userptr(FIELD *field);        /* fetch mode of field */
1587
1588    (Properly, this user pointer field ought to have (void *) type. The
1589    (char *) type is retained for System V compatibility.)
1590    
1591    It is valid to set the user pointer of the default field (with a
1592    set_field_userptr() call passed a NULL field pointer.) When a new
1593    field is created, the default-field user pointer is copied to
1594    initialize the new field's user pointer.
1595    
1596 Variable-Sized Fields
1597
1598    Normally, a field is fixed at the size specified for it at creation
1599    time. If, however, you turn off its O_STATIC bit, it becomes dynamic
1600    and will automatically resize itself to accommodate data as it is
1601    entered. If the field has extra buffers associated with it, they will
1602    grow right along with the main input buffer.
1603    
1604    A one-line dynamic field will have a fixed height (1) but variable
1605    width, scrolling horizontally to display data within the field area as
1606    originally dimensioned and located. A multi-line dynamic field will
1607    have a fixed width, but variable height (number of rows), scrolling
1608    vertically to display data within the field area as originally
1609    dimensioned and located.
1610    
1611    Normally, a dynamic field is allowed to grow without limit. But it is
1612    possible to set an upper limit on the size of a dynamic field. You do
1613    it with this function:
1614    
1615 int set_max_field(FIELD *field,     /* field to alter (may not be NULL) */
1616                    int max_size);   /* upper limit on field size */
1617
1618    If the field is one-line, max_size is taken to be a column size limit;
1619    if it is multi-line, it is taken to be a line size limit. To disable
1620    any limit, use an argument of zero. The growth limit can be changed
1621    whether or not the O_STATIC bit is on, but has no effect until it is.
1622    
1623    The following properties of a field change when it becomes dynamic:
1624      * If there is no growth limit, there is no final position of the
1625        field; therefore O_AUTOSKIP and O_NL_OVERLOAD are ignored.
1626      * Field justification will be ignored (though whatever justification
1627        is set up will be retained internally and can be queried).
1628      * The dup_field() and link_field() calls copy dynamic-buffer sizes.
1629        If the O_STATIC option is set on one of a collection of links,
1630        buffer resizing will occur only when the field is edited through
1631        that link.
1632      * The call field_info() will retrieve the original static size of
1633        the field; use dynamic_field_info() to get the actual dynamic
1634        size.
1635        
1636 Field Validation
1637
1638    By default, a field will accept any data that will fit in its input
1639    buffer. However, it is possible to attach a validation type to a
1640    field. If you do this, any attempt to leave the field while it
1641    contains data that doesn't match the validation type will fail. Some
1642    validation types also have a character-validity check for each time a
1643    character is entered in the field.
1644    
1645    A field's validation check (if any) is not called when
1646    set_field_buffer() modifies the input buffer, nor when that buffer is
1647    changed through a linked field.
1648    
1649    The form library provides a rich set of pre-defined validation types,
1650    and gives you the capability to define custom ones of your own. You
1651    can examine and change field validation attributes with the following
1652    functions:
1653    
1654 int set_field_type(FIELD *field,          /* field to alter */
1655                    FIELDTYPE *ftype,      /* type to associate */
1656                    ...);                  /* additional arguments*/
1657
1658 FIELDTYPE *field_type(FIELD *field);      /* field to query */
1659
1660    The validation type of a field is considered an attribute of the
1661    field. As with other field attributes, Also, doing set_field_type()
1662    with a NULL field default will change the system default for
1663    validation of newly-created fields.
1664    
1665    Here are the pre-defined validation types:
1666    
1667   TYPE_ALPHA
1668   
1669    This field type accepts alphabetic data; no blanks, no digits, no
1670    special characters (this is checked at character-entry time). It is
1671    set up with:
1672    
1673 int set_field_type(FIELD *field,          /* field to alter */
1674                    TYPE_ALPHA,            /* type to associate */
1675                    int width);            /* maximum width of field */
1676
1677    The width argument sets a minimum width of data. Typically you'll want
1678    to set this to the field width; if it's greater than the field width,
1679    the validation check will always fail. A minimum width of zero makes
1680    field completion optional.
1681    
1682   TYPE_ALNUM
1683   
1684    This field type accepts alphabetic data and digits; no blanks, no
1685    special characters (this is checked at character-entry time). It is
1686    set up with:
1687    
1688 int set_field_type(FIELD *field,          /* field to alter */
1689                    TYPE_ALNUM,            /* type to associate */
1690                    int width);            /* maximum width of field */
1691
1692    The width argument sets a minimum width of data. As with TYPE_ALPHA,
1693    typically you'll want to set this to the field width; if it's greater
1694    than the field width, the validation check will always fail. A minimum
1695    width of zero makes field completion optional.
1696    
1697   TYPE_ENUM
1698   
1699    This type allows you to restrict a field's values to be among a
1700    specified set of string values (for example, the two-letter postal
1701    codes for U.S. states). It is set up with:
1702    
1703 int set_field_type(FIELD *field,          /* field to alter */
1704                    TYPE_ENUM,             /* type to associate */
1705                    char **valuelist;      /* list of possible values */
1706                    int checkcase;         /* case-sensitive? */
1707                    int checkunique);      /* must specify uniquely? */
1708
1709    The valuelist parameter must point at a NULL-terminated list of valid
1710    strings. The checkcase argument, if true, makes comparison with the
1711    string case-sensitive.
1712    
1713    When the user exits a TYPE_ENUM field, the validation procedure tries
1714    to complete the data in the buffer to a valid entry. If a complete
1715    choice string has been entered, it is of course valid. But it is also
1716    possible to enter a prefix of a valid string and have it completed for
1717    you.
1718    
1719    By default, if you enter such a prefix and it matches more than one
1720    value in the string list, the prefix will be completed to the first
1721    matching value. But the checkunique argument, if true, requires prefix
1722    matches to be unique in order to be valid.
1723    
1724    The REQ_NEXT_CHOICE and REQ_PREV_CHOICE input requests can be
1725    particularly useful with these fields.
1726    
1727   TYPE_INTEGER
1728   
1729    This field type accepts an integer. It is set up as follows:
1730    
1731 int set_field_type(FIELD *field,          /* field to alter */
1732                    TYPE_INTEGER,          /* type to associate */
1733                    int padding,           /* # places to zero-pad to */
1734                    int vmin, int vmax);   /* valid range */
1735
1736    Valid characters consist of an optional leading minus and digits. The
1737    range check is performed on exit. If the range maximum is less than or
1738    equal to the minimum, the range is ignored.
1739    
1740    If the value passes its range check, it is padded with as many leading
1741    zero digits as necessary to meet the padding argument.
1742    
1743    A TYPE_INTEGER value buffer can conveniently be interpreted with the C
1744    library function atoi(3).
1745    
1746   TYPE_NUMERIC
1747   
1748    This field type accepts a decimal number. It is set up as follows:
1749    
1750 int set_field_type(FIELD *field,              /* field to alter */
1751                    TYPE_NUMERIC,              /* type to associate */
1752                    int padding,               /* # places of precision */
1753                    double vmin, double vmax); /* valid range */
1754
1755    Valid characters consist of an optional leading minus and digits.
1756    possibly including a decimal point. If your system supports locale's,
1757    the decimal point character used must be the one defined by your
1758    locale. The range check is performed on exit. If the range maximum is
1759    less than or equal to the minimum, the range is ignored.
1760    
1761    If the value passes its range check, it is padded with as many
1762    trailing zero digits as necessary to meet the padding argument.
1763    
1764    A TYPE_NUMERIC value buffer can conveniently be interpreted with the C
1765    library function atof(3).
1766    
1767   TYPE_REGEXP
1768   
1769    This field type accepts data matching a regular expression. It is set
1770    up as follows:
1771    
1772 int set_field_type(FIELD *field,          /* field to alter */
1773                    TYPE_REGEXP,           /* type to associate */
1774                    char *regexp);         /* expression to match */
1775
1776    The syntax for regular expressions is that of regcomp(3). The check
1777    for regular-expression match is performed on exit.
1778    
1779 Direct Field Buffer Manipulation
1780
1781    The chief attribute of a field is its buffer contents. When a form has
1782    been completed, your application usually needs to know the state of
1783    each field buffer. You can find this out with:
1784    
1785 char *field_buffer(FIELD *field,          /* field to query */
1786                    int bufindex);         /* number of buffer to query */
1787
1788    Normally, the state of the zero-numbered buffer for each field is set
1789    by the user's editing actions on that field. It's sometimes useful to
1790    be able to set the value of the zero-numbered (or some other) buffer
1791    from your application:
1792 int set_field_buffer(FIELD *field,        /* field to alter */
1793                    int bufindex,          /* number of buffer to alter */
1794                    char *value);          /* string value to set */
1795
1796    If the field is not large enough and cannot be resized to a
1797    sufficiently large size to contain the specified value, the value will
1798    be truncated to fit.
1799    
1800    Calling field_buffer() with a null field pointer will raise an error.
1801    Calling field_buffer() on a field not currently selected for input
1802    will return a correct value. Calling field_buffer() on a field that is
1803    currently selected for input may not necessarily give a correct field
1804    buffer value, because entered data isn't necessarily copied to buffer
1805    zero before the exit validation check. To guarantee that the returned
1806    buffer value reflects on-screen reality, call field_buffer() either
1807    (1) in the field's exit validation check routine, (2) from the field's
1808    or form's initialization or termination hooks, or (3) just after a
1809    REQ_VALIDATION request has been processed by the forms driver.
1810    
1811 Attributes of Forms
1812
1813    As with field attributes, form attributes inherit a default from a
1814    system default form structure. These defaults can be queried or set by
1815    of these functions using a form-pointer argument of NULL.
1816    
1817    The principal attribute of a form is its field list. You can query and
1818    change this list with:
1819    
1820 int set_form_fields(FORM *form,           /* form to alter */
1821                     FIELD **fields);      /* fields to connect */
1822
1823 char *form_fields(FORM *form);            /* fetch fields of form */
1824
1825 int field_count(FORM *form);              /* count connect fields */
1826
1827    The second argument of set_form_fields() may be a NULL-terminated
1828    field pointer array like the one required by new_form(). In that case,
1829    the old fields of the form are disconnected but not freed (and
1830    eligible to be connected to other forms), then the new fields are
1831    connected.
1832    
1833    It may also be null, in which case the old fields are disconnected
1834    (and not freed) but no new ones are connected.
1835    
1836    The field_count() function simply counts the number of fields
1837    connected to a given from. It returns -1 if the form-pointer argument
1838    is NULL.
1839    
1840 Control of Form Display
1841
1842    In the overview section, you saw that to display a form you normally
1843    start by defining its size (and fields), posting it, and refreshing
1844    the screen. There is an hidden step before posting, which is the
1845    association of the form with a frame window (actually, a pair of
1846    windows) within which it will be displayed. By default, the forms
1847    library associates every form with the full-screen window stdscr.
1848    
1849    By making this step explicit, you can associate a form with a declared
1850    frame window on your screen display. This can be useful if you want to
1851    adapt the form display to different screen sizes, dynamically tile
1852    forms on the screen, or use a form as part of an interface layout
1853    managed by panels.
1854    
1855    The two windows associated with each form have the same functions as
1856    their analogues in the menu library. Both these windows are painted
1857    when the form is posted and erased when the form is unposted.
1858    
1859    The outer or frame window is not otherwise touched by the form
1860    routines. It exists so the programmer can associate a title, a border,
1861    or perhaps help text with the form and have it properly refreshed or
1862    erased at post/unpost time. The inner window or subwindow is where the
1863    current form page is actually displayed.
1864    
1865    In order to declare your own frame window for a form, you'll need to
1866    know the size of the form's bounding rectangle. You can get this
1867    information with:
1868    
1869 int scale_form(FORM *form,                /* form to query */
1870                int *rows,                 /* form rows */
1871                int *cols);                /* form cols */
1872
1873    The form dimensions are passed back in the locations pointed to by the
1874    arguments. Once you have this information, you can use it to declare
1875    of windows, then use one of these functions:
1876 int set_form_win(FORM *form,              /* form to alter */
1877                  WINDOW *win);            /* frame window to connect */
1878
1879 WINDOW *form_win(FORM *form);             /* fetch frame window of form */
1880
1881 int set_form_sub(FORM *form,              /* form to alter */
1882                  WINDOW *win);            /* form subwindow to connect */
1883
1884 WINDOW *form_sub(FORM *form);             /* fetch form subwindow of form */
1885
1886    Note that curses operations, including refresh(), on the form, should
1887    be done on the frame window, not the form subwindow.
1888    
1889    It is possible to check from your application whether all of a
1890    scrollable field is actually displayed within the menu subwindow. Use
1891    these functions:
1892    
1893 int data_ahead(FORM *form);               /* form to be queried */
1894
1895 int data_behind(FORM *form);              /* form to be queried */
1896
1897    The function data_ahead() returns TRUE if (a) the current field is
1898    one-line and has undisplayed data off to the right, (b) the current
1899    field is multi-line and there is data off-screen below it.
1900    
1901    The function data_behind() returns TRUE if the first (upper left hand)
1902    character position is off-screen (not being displayed).
1903    
1904    Finally, there is a function to restore the form window's cursor to
1905    the value expected by the forms driver:
1906    
1907 int pos_form_cursor(FORM *)               /* form to be queried */
1908
1909    If your application changes the form window cursor, call this function
1910    before handing control back to the forms driver in order to
1911    re-synchronize it.
1912    
1913 Input Processing in the Forms Driver
1914
1915    The function form_driver() handles virtualized input requests for form
1916    navigation, editing, and validation requests, just as menu_driver does
1917    for menus (see the section on menu input handling).
1918    
1919 int form_driver(FORM *form,               /* form to pass input to */
1920                 int request);             /* form request code */
1921
1922    Your input virtualization function needs to take input and then
1923    convert it to either an alphanumeric character (which is treated as
1924    data to be entered in the currently-selected field), or a forms
1925    processing request.
1926    
1927    The forms driver provides hooks (through input-validation and
1928    field-termination functions) with which your application code can
1929    check that the input taken by the driver matched what was expected.
1930    
1931   Page Navigation Requests
1932   
1933    These requests cause page-level moves through the form, triggering
1934    display of a new form screen.
1935    
1936    REQ_NEXT_PAGE
1937           Move to the next form page.
1938           
1939    REQ_PREV_PAGE
1940           Move to the previous form page.
1941           
1942    REQ_FIRST_PAGE
1943           Move to the first form page.
1944           
1945    REQ_LAST_PAGE
1946           Move to the last form page.
1947           
1948    These requests treat the list as cyclic; that is, REQ_NEXT_PAGE from
1949    the last page goes to the first, and REQ_PREV_PAGE from the first page
1950    goes to the last.
1951    
1952   Inter-Field Navigation Requests
1953   
1954    These requests handle navigation between fields on the same page.
1955    
1956    REQ_NEXT_FIELD
1957           Move to next field.
1958           
1959    REQ_PREV_FIELD
1960           Move to previous field.
1961           
1962    REQ_FIRST_FIELD
1963           Move to the first field.
1964           
1965    REQ_LAST_FIELD
1966           Move to the last field.
1967           
1968    REQ_SNEXT_FIELD
1969           Move to sorted next field.
1970           
1971    REQ_SPREV_FIELD
1972           Move to sorted previous field.
1973           
1974    REQ_SFIRST_FIELD
1975           Move to the sorted first field.
1976           
1977    REQ_SLAST_FIELD
1978           Move to the sorted last field.
1979           
1980    REQ_LEFT_FIELD
1981           Move left to field.
1982           
1983    REQ_RIGHT_FIELD
1984           Move right to field.
1985           
1986    REQ_UP_FIELD
1987           Move up to field.
1988           
1989    REQ_DOWN_FIELD
1990           Move down to field.
1991           
1992    These requests treat the list of fields on a page as cyclic; that is,
1993    REQ_NEXT_FIELD from the last field goes to the first, and
1994    REQ_PREV_FIELD from the first field goes to the last. The order of the
1995    fields for these (and the REQ_FIRST_FIELD and REQ_LAST_FIELD requests)
1996    is simply the order of the field pointers in the form array (as set up
1997    by new_form() or set_form_fields()
1998    
1999    It is also possible to traverse the fields as if they had been sorted
2000    in screen-position order, so the sequence goes left-to-right and
2001    top-to-bottom. To do this, use the second group of four
2002    sorted-movement requests.
2003    
2004    Finally, it is possible to move between fields using visual directions
2005    up, down, right, and left. To accomplish this, use the third group of
2006    four requests. Note, however, that the position of a form for purposes
2007    of these requests is its upper-left corner.
2008    
2009    For example, suppose you have a multi-line field B, and two
2010    single-line fields A and C on the same line with B, with A to the left
2011    of B and C to the right of B. A REQ_MOVE_RIGHT from A will go to B
2012    only if A, B, and C all share the same first line; otherwise it will
2013    skip over B to C.
2014    
2015   Intra-Field Navigation Requests
2016   
2017    These requests drive movement of the edit cursor within the currently
2018    selected field.
2019    
2020    REQ_NEXT_CHAR
2021           Move to next character.
2022           
2023    REQ_PREV_CHAR
2024           Move to previous character.
2025           
2026    REQ_NEXT_LINE
2027           Move to next line.
2028           
2029    REQ_PREV_LINE
2030           Move to previous line.
2031           
2032    REQ_NEXT_WORD
2033           Move to next word.
2034           
2035    REQ_PREV_WORD
2036           Move to previous word.
2037           
2038    REQ_BEG_FIELD
2039           Move to beginning of field.
2040           
2041    REQ_END_FIELD
2042           Move to end of field.
2043           
2044    REQ_BEG_LINE
2045           Move to beginning of line.
2046           
2047    REQ_END_LINE
2048           Move to end of line.
2049           
2050    REQ_LEFT_CHAR
2051           Move left in field.
2052           
2053    REQ_RIGHT_CHAR
2054           Move right in field.
2055           
2056    REQ_UP_CHAR
2057           Move up in field.
2058           
2059    REQ_DOWN_CHAR
2060           Move down in field.
2061           
2062    Each word is separated from the previous and next characters by
2063    whitespace. The commands to move to beginning and end of line or field
2064    look for the first or last non-pad character in their ranges.
2065    
2066   Scrolling Requests
2067   
2068    Fields that are dynamic and have grown and fields explicitly created
2069    with offscreen rows are scrollable. One-line fields scroll
2070    horizontally; multi-line fields scroll vertically. Most scrolling is
2071    triggered by editing and intra-field movement (the library scrolls the
2072    field to keep the cursor visible). It is possible to explicitly
2073    request scrolling with the following requests:
2074    
2075    REQ_SCR_FLINE
2076           Scroll vertically forward a line.
2077           
2078    REQ_SCR_BLINE
2079           Scroll vertically backward a line.
2080           
2081    REQ_SCR_FPAGE
2082           Scroll vertically forward a page.
2083           
2084    REQ_SCR_BPAGE
2085           Scroll vertically backward a page.
2086           
2087    REQ_SCR_FHPAGE
2088           Scroll vertically forward half a page.
2089           
2090    REQ_SCR_BHPAGE
2091           Scroll vertically backward half a page.
2092           
2093    REQ_SCR_FCHAR
2094           Scroll horizontally forward a character.
2095           
2096    REQ_SCR_BCHAR
2097           Scroll horizontally backward a character.
2098           
2099    REQ_SCR_HFLINE
2100           Scroll horizontally one field width forward.
2101           
2102    REQ_SCR_HBLINE
2103           Scroll horizontally one field width backward.
2104           
2105    REQ_SCR_HFHALF
2106           Scroll horizontally one half field width forward.
2107           
2108    REQ_SCR_HBHALF
2109           Scroll horizontally one half field width backward.
2110           
2111    For scrolling purposes, a page of a field is the height of its visible
2112    part.
2113    
2114   Editing Requests
2115   
2116    When you pass the forms driver an ASCII character, it is treated as a
2117    request to add the character to the field's data buffer. Whether this
2118    is an insertion or a replacement depends on the field's edit mode
2119    (insertion is the default.
2120    
2121    The following requests support editing the field and changing the edit
2122    mode:
2123    
2124    REQ_INS_MODE
2125           Set insertion mode.
2126           
2127    REQ_OVL_MODE
2128           Set overlay mode.
2129           
2130    REQ_NEW_LINE
2131           New line request (see below for explanation).
2132           
2133    REQ_INS_CHAR
2134           Insert space at character location.
2135           
2136    REQ_INS_LINE
2137           Insert blank line at character location.
2138           
2139    REQ_DEL_CHAR
2140           Delete character at cursor.
2141           
2142    REQ_DEL_PREV
2143           Delete previous word at cursor.
2144           
2145    REQ_DEL_LINE
2146           Delete line at cursor.
2147           
2148    REQ_DEL_WORD
2149           Delete word at cursor.
2150           
2151    REQ_CLR_EOL
2152           Clear to end of line.
2153           
2154    REQ_CLR_EOF
2155           Clear to end of field.
2156           
2157    REQ_CLEAR_FIELD
2158           Clear entire field.
2159           
2160    The behavior of the REQ_NEW_LINE and REQ_DEL_PREV requests is
2161    complicated and partly controlled by a pair of forms options. The
2162    special cases are triggered when the cursor is at the beginning of a
2163    field, or on the last line of the field.
2164    
2165    First, we consider REQ_NEW_LINE:
2166    
2167    The normal behavior of REQ_NEW_LINE in insert mode is to break the
2168    current line at the position of the edit cursor, inserting the portion
2169    of the current line after the cursor as a new line following the
2170    current and moving the cursor to the beginning of that new line (you
2171    may think of this as inserting a newline in the field buffer).
2172    
2173    The normal behavior of REQ_NEW_LINE in overlay mode is to clear the
2174    current line from the position of the edit cursor to end of line. The
2175    cursor is then moved to the beginning of the next line.
2176    
2177    However, REQ_NEW_LINE at the beginning of a field, or on the last line
2178    of a field, instead does a REQ_NEXT_FIELD. O_NL_OVERLOAD option is
2179    off, this special action is disabled.
2180    
2181    Now, let us consider REQ_DEL_PREV:
2182    
2183    The normal behavior of REQ_DEL_PREV is to delete the previous
2184    character. If insert mode is on, and the cursor is at the start of a
2185    line, and the text on that line will fit on the previous one, it
2186    instead appends the contents of the current line to the previous one
2187    and deletes the current line (you may think of this as deleting a
2188    newline from the field buffer).
2189    
2190    However, REQ_DEL_PREV at the beginning of a field is instead treated
2191    as a REQ_PREV_FIELD.
2192    
2193    If the O_BS_OVERLOAD option is off, this special action is disabled
2194    and the forms driver just returns E_REQUEST_DENIED.
2195    
2196    See Form Options for discussion of how to set and clear the overload
2197    options.
2198    
2199   Order Requests
2200   
2201    If the type of your field is ordered, and has associated functions for
2202    getting the next and previous values of the type from a given value,
2203    there are requests that can fetch that value into the field buffer:
2204    
2205    REQ_NEXT_CHOICE
2206           Place the successor value of the current value in the buffer.
2207           
2208    REQ_PREV_CHOICE
2209           Place the predecessor value of the current value in the buffer.
2210           
2211    Of the built-in field types, only TYPE_ENUM has built-in successor and
2212    predecessor functions. When you define a field type of your own (see
2213    Custom Validation Types), you can associate our own ordering
2214    functions.
2215    
2216   Application Commands
2217   
2218    Form requests are represented as integers above the curses value
2219    greater than KEY_MAX and less than or equal to the constant
2220    MAX_COMMAND. If your input-virtualization routine returns a value
2221    above MAX_COMMAND, the forms driver will ignore it.
2222    
2223 Field Change Hooks
2224
2225    It is possible to set function hooks to be executed whenever the
2226    current field or form changes. Here are the functions that support
2227    this:
2228    
2229 typedef void    (*HOOK)();       /* pointer to function returning void */
2230
2231 int set_form_init(FORM *form,    /* form to alter */
2232                   HOOK hook);    /* initialization hook */
2233
2234 HOOK form_init(FORM *form);      /* form to query */
2235
2236 int set_form_term(FORM *form,    /* form to alter */
2237                   HOOK hook);    /* termination hook */
2238
2239 HOOK form_term(FORM *form);      /* form to query */
2240
2241 int set_field_init(FORM *form,   /* form to alter */
2242                   HOOK hook);    /* initialization hook */
2243
2244 HOOK field_init(FORM *form);     /* form to query */
2245
2246 int set_field_term(FORM *form,   /* form to alter */
2247                   HOOK hook);    /* termination hook */
2248
2249 HOOK field_term(FORM *form);     /* form to query */
2250
2251    These functions allow you to either set or query four different hooks.
2252    In each of the set functions, the second argument should be the
2253    address of a hook function. These functions differ only in the timing
2254    of the hook call.
2255    
2256    form_init
2257           This hook is called when the form is posted; also, just after
2258           each page change operation.
2259           
2260    field_init
2261           This hook is called when the form is posted; also, just after
2262           each field change
2263           
2264    field_term
2265           This hook is called just after field validation; that is, just
2266           before the field is altered. It is also called when the form is
2267           unposted.
2268           
2269    form_term
2270           This hook is called when the form is unposted; also, just
2271           before each page change operation.
2272           
2273    Calls to these hooks may be triggered
2274     1. When user editing requests are processed by the forms driver
2275     2. When the current page is changed by set_current_field() call
2276     3. When the current field is changed by a set_form_page() call
2277        
2278    See Field Change Commands for discussion of the latter two cases.
2279    
2280    You can set a default hook for all fields by passing one of the set
2281    functions a NULL first argument.
2282    
2283    You can disable any of these hooks by (re)setting them to NULL, the
2284    default value.
2285    
2286 Field Change Commands
2287
2288    Normally, navigation through the form will be driven by the user's
2289    input requests. But sometimes it is useful to be able to move the
2290    focus for editing and viewing under control of your application, or
2291    ask which field it currently is in. The following functions help you
2292    accomplish this:
2293    
2294 int set_current_field(FORM *form,         /* form to alter */
2295                       FIELD *field);      /* field to shift to */
2296
2297 FIELD *current_field(FORM *form);         /* form to query */
2298
2299 int field_index(FORM *form,               /* form to query */
2300                 FIELD *field);            /* field to get index of */
2301
2302    The function field_index() returns the index of the given field in the
2303    given form's field array (the array passed to new_form() or
2304    set_form_fields()).
2305    
2306    The initial current field of a form is the first active field on the
2307    first page. The function set_form_fields() resets this.
2308    
2309    It is also possible to move around by pages.
2310    
2311 int set_form_page(FORM *form,             /* form to alter */
2312                   int page);              /* page to go to (0-origin) */
2313
2314 int form_page(FORM *form);                /* return form's current page */
2315
2316    The initial page of a newly-created form is 0. The function
2317    set_form_fields() resets this.
2318    
2319 Form Options
2320
2321    Like fields, forms may have control option bits. They can be changed
2322    or queried with these functions:
2323    
2324 int set_form_opts(FORM *form,             /* form to alter */
2325                   int attr);              /* attribute to set */
2326
2327 int form_opts_on(FORM *form,              /* form to alter */
2328                  int attr);               /* attributes to turn on */
2329
2330 int form_opts_off(FORM *form,             /* form to alter */
2331                   int attr);              /* attributes to turn off */
2332
2333 int form_opts(FORM *form);                /* form to query */
2334
2335    By default, all options are on. Here are the available option bits:
2336    
2337    O_NL_OVERLOAD
2338           Enable overloading of REQ_NEW_LINE as described in Editing
2339           Requests. The value of this option is ignored on dynamic fields
2340           that have not reached their size limit; these have no last
2341           line, so the circumstances for triggering a REQ_NEXT_FIELD
2342           never arise.
2343           
2344    O_BS_OVERLOAD
2345           Enable overloading of REQ_DEL_PREV as described in Editing
2346           Requests.
2347           
2348    The option values are bit-masks and can be composed with logical-or in
2349    the obvious way.
2350    
2351 Custom Validation Types
2352
2353    The form library gives you the capability to define custom validation
2354    types of your own. Further, the optional additional arguments of
2355    set_field_type effectively allow you to parameterize validation types.
2356    Most of the complications in the validation-type interface have to do
2357    with the handling of the additional arguments within custom validation
2358    functions.
2359    
2360   Union Types
2361   
2362    The simplest way to create a custom data type is to compose it from
2363    two preexisting ones:
2364    
2365 FIELD *link_fieldtype(FIELDTYPE *type1,
2366                       FIELDTYPE *type2);
2367
2368    This function creates a field type that will accept any of the values
2369    legal for either of its argument field types (which may be either
2370    predefined or programmer-defined). If a set_field_type() call later
2371    requires arguments, the new composite type expects all arguments for
2372    the first type, than all arguments for the second. Order functions
2373    (see Order Requests) associated with the component types will work on
2374    the composite; what it does is check the validation function for the
2375    first type, then for the second, to figure what type the buffer
2376    contents should be treated as.
2377    
2378   New Field Types
2379   
2380    To create a field type from scratch, you need to specify one or both
2381    of the following things:
2382    
2383      * A character-validation function, to check each character as it is
2384        entered.
2385      * A field-validation function to be applied on exit from the field.
2386        
2387    Here's how you do that:
2388    
2389 typedef int     (*HOOK)();       /* pointer to function returning int */
2390
2391 FIELDTYPE *new_fieldtype(HOOK f_validate, /* field validator */
2392                          HOOK c_validate) /* character validator */
2393
2394
2395 int free_fieldtype(FIELDTYPE *ftype);     /* type to free */
2396
2397    At least one of the arguments of new_fieldtype() must be non-NULL. The
2398    forms driver will automatically call the new type's validation
2399    functions at appropriate points in processing a field of the new type.
2400    
2401    The function free_fieldtype() deallocates the argument fieldtype,
2402    freeing all storage associated with it.
2403    
2404    Normally, a field validator is called when the user attempts to leave
2405    the field. Its first argument is a field pointer, from which it can
2406    get to field buffer 0 and test it. If the function returns TRUE, the
2407    operation succeeds; if it returns FALSE, the edit cursor stays in the
2408    field.
2409    
2410    A character validator gets the character passed in as a first
2411    argument. It too should return TRUE if the character is valid, FALSE
2412    otherwise.
2413    
2414   Validation Function Arguments
2415   
2416    Your field- and character- validation functions will be passed a
2417    second argument as well. This second argument is the address of a
2418    structure (which we'll call a pile) built from any of the
2419    field-type-specific arguments passed to set_field_type(). If no such
2420    arguments are defined for the field type, this pile pointer argument
2421    will be NULL.
2422    
2423    In order to arrange for such arguments to be passed to your validation
2424    functions, you must associate a small set of storage-management
2425    functions with the type. The forms driver will use these to synthesize
2426    a pile from the trailing arguments of each set_field_type() argument,
2427    and a pointer to the pile will be passed to the validation functions.
2428    
2429    Here is how you make the association:
2430    
2431 typedef char    *(*PTRHOOK)();    /* pointer to function returning (char *) */
2432 typedef void    (*VOIDHOOK)();    /* pointer to function returning void */
2433
2434 int set_fieldtype_arg(FIELDTYPE *type,    /* type to alter */
2435                       PTRHOOK make_str,   /* make structure from args */
2436                       PTRHOOK copy_str,   /* make copy of structure */
2437                       VOIDHOOK free_str); /* free structure storage */
2438
2439    Here is how the storage-management hooks are used:
2440    
2441    make_str
2442           This function is called by set_field_type(). It gets one
2443           argument, a va_list of the type-specific arguments passed to
2444           set_field_type(). It is expected to return a pile pointer to a
2445           data structure that encapsulates those arguments.
2446           
2447    copy_str
2448           This function is called by form library functions that allocate
2449           new field instances. It is expected to take a pile pointer,
2450           copy the pile to allocated storage, and return the address of
2451           the pile copy.
2452           
2453    free_str
2454           This function is called by field- and type-deallocation
2455           routines in the library. It takes a pile pointer argument, and
2456           is expected to free the storage of that pile.
2457           
2458    The make_str and copy_str functions may return NULL to signal
2459    allocation failure. The library routines will that call them will
2460    return error indication when this happens. Thus, your validation
2461    functions should never see a NULL file pointer and need not check
2462    specially for it.
2463    
2464   Order Functions For Custom Types
2465   
2466    Some custom field types are simply ordered in the same well-defined
2467    way that TYPE_ENUM is. For such types, it is possible to define
2468    successor and predecessor functions to support the REQ_NEXT_CHOICE and
2469    REQ_PREV_CHOICE requests. Here's how:
2470    
2471 typedef int     (*INTHOOK)();     /* pointer to function returning int */
2472
2473 int set_fieldtype_arg(FIELDTYPE *type,    /* type to alter */
2474                       INTHOOK succ,       /* get successor value */
2475                       INTHOOK pred);      /* get predecessor value */
2476
2477    The successor and predecessor arguments will each be passed two
2478    arguments; a field pointer, and a pile pointer (as for the validation
2479    functions). They are expected to use the function field_buffer() to
2480    read the current value, and set_field_buffer() on buffer 0 to set the
2481    next or previous value. Either hook may return TRUE to indicate
2482    success (a legal next or previous value was set) or FALSE to indicate
2483    failure.
2484    
2485   Avoiding Problems
2486   
2487    The interface for defining custom types is complicated and tricky.
2488    Rather than attempting to create a custom type entirely from scratch,
2489    you should start by studying the library source code for whichever of
2490    the pre-defined types seems to be closest to what you want.
2491    
2492    Use that code as a model, and evolve it towards what you really want.
2493    You will avoid many problems and annoyances that way. The code in the
2494    ncurses library has been specifically exempted from the package
2495    copyright to support this.
2496    
2497    If your custom type defines order functions, have do something
2498    intuitive with a blank field. A useful convention is to make the
2499    successor of a blank field the types minimum value, and its
2500    predecessor the maximum.