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