1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
5 > NCURSES Programming HOWTO </TITLE
8 CONTENT="Modular DocBook HTML Stylesheet Version 1.79"></HEAD
24 >NCURSES Programming HOWTO</A
41 HREF="mailto:ppadala@gmail.com"
49 >v1.9, 2005-06-20<BR></P
73 >Revised by: ppadala</TD
79 >The license has been changed to the MIT-style license used
80 by NCURSES. Note that the programs are also re-licensed under this.</TD
91 >Revised by: ppadala</TD
97 >Lots of updates. Added references and perl examples.
98 Changes to examples. Many grammatical and stylistic changes to the
99 content. Changes to NCURSES history.</TD
110 >Revised by: ppadala</TD
116 >Added a README file for building and instructions
117 for building from source.</TD
128 >Revised by: ppadala</TD
134 >Added "Other formats" section and made a lot of fancy
135 changes to the programs. Inlining of programs is gone.</TD
146 >Revised by: ppadala</TD
152 >Removed the old Changelog section, cleaned the makefiles</TD
163 >Revised by: ppadala</TD
169 >Corrected a lot of spelling mistakes, added ACS variables
181 >Revised by: ppadala</TD
187 >Changed structure to present proper TOC</TD
198 >Revised by: ppadala</TD
204 >Corrected maintainers paragraph, Corrected stable release number</TD
215 >Revised by: ppadala</TD
221 >Added copyright notices to main document (LDP license)
222 and programs (GPL), Corrected
234 >Revised by: ppadala</TD
240 >Incorporated ravi's changes. Mainly to introduction, menu,
241 form, justforfun sections</TD
252 >Revised by: ppadala</TD
258 >Added "a word about window" section, Added scanw_example.</TD
275 >This document is intended to be an "All in One" guide for programming with
276 ncurses and its sister libraries. We graduate from a simple "Hello World"
277 program to more complex form manipulation. No prior experience in ncurses is
278 assumed. Send comments to <A
279 HREF="mailto:ppadala@gmail.com"
297 >Table of Contents</B
314 >What we can do with NCURSES</A
324 >Purpose/Scope of the document</A
328 HREF="#ABOUTPROGRAMS"
329 >About the Programs</A
334 >Other Formats of the document</A
341 >Readily available formats from tldp.org</A
346 >Building from source</A
376 HREF="#COMPILECURSES"
377 >Compiling With the NCURSES Library</A
388 HREF="#ABOUT-INITSCR"
394 >The mysterious refresh()</A
420 >Initialization functions</A
425 >raw() and cbreak()</A
430 >echo() and noecho()</A
445 >Miscellaneous Initialization functions</A
457 >A Word about Windows</A
469 >addch() class of functions</A
474 >mvaddch(), waddch() and mvwaddch()</A
479 >printw() class of functions</A
485 HREF="#PRINTWMVPRINTW"
486 >printw() and mvprintw</A
490 HREF="#WPRINTWMVWPRINTW"
491 >wprintw() and mvwprintw</A
500 HREF="#SIMPLEPRINTWEX"
501 >A Simple printw example</A
508 >addstr() class of functions</A
513 >A word of caution</A
527 >getch() class of functions</A
532 >scanw() class of functions</A
539 >scanw() and mvscanw</A
543 HREF="#WSCANWMVWSCANW"
544 >wscanw() and mvwscanw()</A
556 >getstr() class of functions</A
574 HREF="#ATTRIBDETAILS"
579 HREF="#ATTRONVSATTRSET"
580 >attron() vs attrset()</A
600 >chgat() functions</A
619 >Let there be a Window !!!</A
629 >The other stuff in the example</A
633 HREF="#OTHERBORDERFUNCS"
634 >Other Border functions</A
652 HREF="#CHANGECOLORDEFS"
653 >Changing Color Definitions</A
665 >Interfacing with the key board</A
677 >A Simple Key Usage example</A
684 >Interfacing with the mouse</A
695 HREF="#GETTINGEVENTS"
696 >Getting the events</A
700 HREF="#MOUSETOGETHER"
701 >Putting it all Together</A
705 HREF="#MISCMOUSEFUNCS"
706 >Miscellaneous Functions</A
713 >Screen Manipulation</A
720 >getyx() functions</A
737 >Miscellaneous features</A
749 >Temporarily Leaving Curses mode</A
777 HREF="#COMPILEPANELS"
778 >Compiling With the Panels Library</A
782 HREF="#PANELBROWSING"
783 >Panel Window Browsing</A
788 >Using User Pointers</A
792 HREF="#PANELMOVERESIZE"
793 >Moving and Resizing Panels</A
797 HREF="#PANELSHOWHIDE"
798 >Hiding and Showing Panels</A
803 >panel_above() and panel_below() Functions</A
822 >Compiling With the Menu Library</A
827 >Menu Driver: The work horse of the menu system</A
842 >Multi Columnar Menus</A
846 HREF="#MULTIVALUEMENUS"
847 >Multi Valued Menus</A
857 >The useful User Pointer</A
876 >Compiling With the Forms Library</A
881 >Playing with Fields</A
888 >Fetching Size and Location of Field</A
898 >Field Justification</A
902 HREF="#FIELDDISPATTRIB"
903 >Field Display Attributes</A
907 HREF="#FIELDOPTIONBITS"
908 >Field Option Bits</A
918 >Field User Pointer</A
922 HREF="#VARIABLESIZEFIELDS"
923 >Variable-Sized Fields</A
934 HREF="#FILEDVALIDATE"
940 >Form Driver: The work horse of the forms system</A
947 >Page Navigation Requests</A
951 HREF="#INTERFIELDNAVREQ"
952 >Inter-Field Navigation Requests</A
956 HREF="#INTRAFIELDNAVREQ"
957 >Intra-Field Navigation Requests</A
962 >Scrolling Requests</A
976 HREF="#APPLICCOMMANDS"
977 >Application Commands</A
986 >Tools and Widget Libraries</A
993 >CDK (Curses Development Kit)</A
1005 >Some Attractive Features</A
1009 HREF="#CDKCONCLUSION"
1022 >Perl Curses Modules CURSES::FORM and CURSES::WIDGETS</A
1029 >Just For Fun !!!</A
1036 >The Game of Life</A
1081 >In the olden days of teletype terminals, terminals were away from computers and
1082 were connected to them through serial cables. The terminals could be configured
1083 by sending a series of bytes. All the capabilities (such as
1084 moving the cursor to a new location, erasing part of the screen, scrolling the
1085 screen, changing modes etc.) of terminals could be accessed through these
1086 series of bytes. These control seeuqnces are usually called escape sequences,
1088 with an escape(0x1B) character. Even today, with proper emulation, we can send
1089 escape sequences to the emulator and achieve the same effect on a terminal
1092 >Suppose you wanted to print a line in color. Try typing this on your console.</P
1094 CLASS="PROGRAMLISTING"
1095 >echo "^[[0;31;40mIn Color"</PRE
1097 >The first character is an escape character, which looks like two characters ^
1098 and [. To be able to print it, you have to press CTRL+V and then the ESC key.
1099 All the others are normal printable characters. You should be able to see the
1100 string "In Color" in red. It stays that way and to revert back to the original
1103 CLASS="PROGRAMLISTING"
1104 >echo "^[[0;37;40m"</PRE
1106 >Now, what do these magic characters mean? Difficult to comprehend? They might
1107 even be different for different terminals. So the designers of UNIX invented a
1111 >. It is a file that
1112 lists all the capabilities of a particular terminal, along with the escape
1113 sequences needed to achieve a particular effect. In the later years, this was
1117 >. Without delving too
1118 much into details, this mechanism allows application
1119 programs to query the terminfo database and obtain the control characters to be
1120 sent to a terminal or terminal emulator.</P
1127 >1.1. What is NCURSES?</A
1131 You might be wondering, what the import of all this technical gibberish is. In
1132 the above scenario, every application program is supposed to query the terminfo
1133 and perform the necessary stuff (sending control characters etc.). It soon became
1134 difficult to manage this complexity and this gave birth to 'CURSES'. Curses is
1135 a pun on the name "cursor optimization". The Curses library forms a wrapper
1136 over working with raw terminal codes, and provides highly flexible and
1137 efficient API (Application Programming Interface). It provides functions to
1138 move the cursor, create windows, produce colors, play with mouse etc. The
1139 application programs need not worry about the underlying terminal capabilities.</P
1141 >So what is NCURSES? NCURSES is a clone of the original System V Release 4.0
1142 (SVr4) curses. It is a freely distributable library, fully compatible with
1143 older version of curses. In short, it is a library of functions that manages
1144 an application's display on character-cell terminals. In the remainder of the
1145 document, the terms curses and ncurses are used interchangeably. </P
1147 >A detailed history of NCURSES can be found in the NEWS file from the source
1148 distribution. The current package is maintained by
1150 HREF="mailto:dickey@his.com"
1154 You can contact the maintainers at <A
1155 HREF="mailto:bug-ncurses@gnu.org"
1157 >bug-ncurses@gnu.org</A
1166 >1.2. What we can do with NCURSES</A
1169 >NCURSES not only creates a wrapper over terminal capabilities, but also gives a
1170 robust framework to create nice looking UI (User Interface)s in text mode. It
1171 provides functions to create windows etc. Its sister libraries panel, menu and
1172 form provide an extension to the basic curses library. These libraries usually
1173 come along with curses. One can create applications that contain multiple
1174 windows, menus, panels and forms. Windows can be managed independently, can
1175 provide 'scrollability' and even can be hidden.</P
1178 Menus provide the user with an easy command selection option. Forms allow the
1179 creation of easy-to-use data entry and display windows. Panels extend the
1180 capabilities of ncurses to deal with overlapping and stacked windows.</P
1182 >These are just some of the basic things we can do with ncurses. As we move
1183 along, We will see all the capabilities of these libraries. </P
1191 >1.3. Where to get it</A
1194 >All right, now that you know what you can do with ncurses, you must be rearing
1195 to get started. NCURSES is usually shipped with your installation. In case
1196 you don't have the library or want to compile it on your own, read on.</P
1202 >Compiling the package</I
1206 >NCURSES can be obtained from <A
1207 HREF="ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz"
1209 >ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz</A
1211 sites mentioned in <A
1212 HREF="http://www.gnu.org/order/ftp.html"
1214 >http://www.gnu.org/order/ftp.html</A
1217 >Read the README and INSTALL files for details on to how to install it. It
1218 usually involves the following operations.</P
1220 CLASS="PROGRAMLISTING"
1221 > tar zxvf ncurses<version>.tar.gz # unzip and untar the archive
1222 cd ncurses<version> # cd to the directory
1223 ./configure # configure the build according to your
1226 su root # become root
1227 make install # install it</PRE
1237 >NCURSES RPM can be found and downloaded from <A
1238 HREF="http://rpmfind.net"
1240 >http://rpmfind.net </A
1241 >. The RPM can be installed with the following
1242 command after becoming root.</P
1244 CLASS="PROGRAMLISTING"
1245 > rpm -i <downloaded rpm></PRE
1253 >1.4. Purpose/Scope of the document</A
1256 >This document is intended to be a "All in One" guide for programming with
1257 ncurses and its sister libraries. We graduate from a simple "Hello World"
1258 program to more complex form manipulation. No prior experience in ncurses is
1259 assumed. The writing is informal, but a lot of detail is provided for
1260 each of the examples.</P
1267 NAME="ABOUTPROGRAMS"
1268 >1.5. About the Programs</A
1271 >All the programs in the document are available in zipped form
1273 HREF="http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs.tar.gz"
1276 >. Unzip and untar it. The directory structure looks like this.</P
1278 CLASS="PROGRAMLISTING"
1281 |----> JustForFun -- just for fun programs
1282 |----> basics -- basic programs
1283 |----> demo -- output files go into this directory after make
1285 | |----> exe -- exe files of all example programs
1286 |----> forms -- programs related to form library
1287 |----> menus -- programs related to menus library
1288 |----> panels -- programs related to panels library
1289 |----> perl -- perl equivalents of the examples (contributed
1290 | by Anuradha Ratnaweera)
1291 |----> Makefile -- the top level Makefile
1292 |----> README -- the top level README file. contains instructions
1293 |----> COPYING -- copyright notice</PRE
1295 >The individual directories contain the following files.</P
1297 CLASS="PROGRAMLISTING"
1298 >Description of files in each directory
1299 --------------------------------------
1302 |----> hanoi.c -- The Towers of Hanoi Solver
1303 |----> life.c -- The Game of Life demo
1304 |----> magic.c -- An Odd Order Magic Square builder
1305 |----> queens.c -- The famous N-Queens Solver
1306 |----> shuffle.c -- A fun game, if you have time to kill
1307 |----> tt.c -- A very trivial typing tutor
1311 |----> acs_vars.c -- ACS_ variables example
1312 |----> hello_world.c -- Simple "Hello World" Program
1313 |----> init_func_example.c -- Initialization functions example
1314 |----> key_code.c -- Shows the scan code of the key pressed
1315 |----> mouse_menu.c -- A menu accessible by mouse
1316 |----> other_border.c -- Shows usage of other border functions apa
1318 |----> printw_example.c -- A very simple printw() example
1319 |----> scanw_example.c -- A very simple getstr() example
1320 |----> simple_attr.c -- A program that can print a c file with
1321 | -- comments in attribute
1322 |----> simple_color.c -- A simple example demonstrating colors
1323 |----> simple_key.c -- A menu accessible with keyboard UP, DOWN
1325 |----> temp_leave.c -- Demonstrates temporarily leaving curses mode
1326 |----> win_border.c -- Shows Creation of windows and borders
1327 |----> with_chgat.c -- chgat() usage example
1331 |----> form_attrib.c -- Usage of field attributes
1332 |----> form_options.c -- Usage of field options
1333 |----> form_simple.c -- A simple form example
1334 |----> form_win.c -- Demo of windows associated with forms
1338 |----> menu_attrib.c -- Usage of menu attributes
1339 |----> menu_item_data.c -- Usage of item_name() etc.. functions
1340 |----> menu_multi_column.c -- Creates multi columnar menus
1341 |----> menu_scroll.c -- Demonstrates scrolling capability of menus
1342 |----> menu_simple.c -- A simple menu accessed by arrow keys
1343 |----> menu_toggle.c -- Creates multi valued menus and explains
1344 | -- REQ_TOGGLE_ITEM
1345 |----> menu_userptr.c -- Usage of user pointer
1346 |----> menu_win.c -- Demo of windows associated with menus
1350 |----> panel_browse.c -- Panel browsing through tab. Usage of user
1352 |----> panel_hide.c -- Hiding and Un hiding of panels
1353 |----> panel_resize.c -- Moving and resizing of panels
1354 |----> panel_simple.c -- A simple panel example
1357 |----> 01-10.pl -- Perl equivalents of first ten example programs</PRE
1359 >There is a top level Makefile included in the main directory. It builds all the
1360 files and puts the ready-to-use exes in demo/exe directory. You can also
1361 do selective make by going into the corresponding directory. Each directory
1362 contains a README file explaining the purpose of each c file in the directory.</P
1364 >For every example, I have included path name for the file relative to the
1365 examples directory. </P
1367 > If you prefer browsing individual programs, point your browser to
1369 HREF="http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/"
1371 >http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/</A
1374 >All the programs are released under the same license that is used by ncurses
1375 (MIT-style). This gives you the ability to do pretty much anything other than
1376 claiming them as yours. Feel free to use them in your programs as appropriate.</P
1384 >1.6. Other Formats of the document</A
1387 >This howto is also availabe in various other formats on the tldp.org site.
1388 Here are the links to other formats of this document.</P
1395 >1.6.1. Readily available formats from tldp.org</A
1403 HREF="http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/pdf/NCURSES-Programming-HOWTO.pdf"
1405 >Acrobat PDF Format</A
1411 HREF="http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/ps/NCURSES-Programming-HOWTO.ps.gz"
1413 >PostScript Format</A
1419 HREF="http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html/NCURSES-Programming-HOWTO-html.tar.gz"
1421 >In Multiple HTML pages</A
1427 HREF="http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/NCURSES-Programming-HOWTO.html"
1429 >In One big HTML format</A
1440 >1.6.2. Building from source</A
1443 >If above links are broken or if you want to experiment with sgml read on.
1445 CLASS="PROGRAMLISTING"
1446 > Get both the source and the tar,gzipped programs, available at
1447 http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
1448 NCURSES-HOWTO/NCURSES-Programming-HOWTO.sgml
1449 http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
1450 NCURSES-HOWTO/ncurses_programs.tar.gz
1452 Unzip ncurses_programs.tar.gz with
1453 tar zxvf ncurses_programs.tar.gz
1455 Use jade to create various formats. For example if you just want to create
1456 the multiple html files, you would use
1457 jade -t sgml -i html -d <path to docbook html stylesheet>
1458 NCURSES-Programming-HOWTO.sgml
1459 to get pdf, first create a single html file of the HOWTO with
1460 jade -t sgml -i html -d <path to docbook html stylesheet> -V nochunks
1461 NCURSES-Programming-HOWTO.sgml > NCURSES-ONE-BIG-FILE.html
1462 then use htmldoc to get pdf file with
1463 htmldoc --size universal -t pdf --firstpage p1 -f <output file name.pdf>
1464 NCURSES-ONE-BIG-FILE.html
1465 for ps, you would use
1466 htmldoc --size universal -t ps --firstpage p1 -f <output file name.ps>
1467 NCURSES-ONE-BIG-FILE.html</PRE
1471 HREF="http://www.tldp.org/LDP/LDP-Author-Guide/"
1473 >LDP Author guide</A
1474 > for more details. If all else failes, mail me at
1476 HREF="ppadala@gmail.com"
1478 >ppadala@gmail.com</A
1492 HREF="mailto:sharath_1@usa.net"
1495 > and Emre Akbas for
1496 helping me with few sections. The introduction was initially written by sharath.
1497 I rewrote it with few excerpts taken from his initial work. Emre helped in
1498 writing printw and scanw sections.</P
1500 >Perl equivalents of the example programs are contributed by <A
1501 HREF="mailto:Aratnaweera@virtusa.com"
1503 >Anuradha Ratnaweera</A
1507 HREF="mailto:parimi@ece.arizona.edu"
1511 dearest friend, who has been on this project before even one line was written.
1512 He constantly bombarded me with suggestions and patiently reviewed the whole
1513 text. He also checked each program on Linux and Solaris. </P
1524 >This is the wish list, in the order of priority. If you have a wish or you want
1525 to work on completing the wish, mail <A
1526 HREF="mailto:ppadala@gmail.com"
1535 >Add examples to last parts of forms section.</P
1539 >Prepare a Demo showing all the programs and allow the user to browse through
1540 description of each program. Let the user compile and see the program in action.
1541 A dialog based interface is preferred.</P
1545 >Add debug info. _tracef, _tracemouse stuff.</P
1549 >Accessing termcap, terminfo using functions provided by ncurses
1554 >Working on two terminals simultaneously.</P
1558 >Add more stuff to miscellaneous section.</P
1571 >Copyright © 2001 by Pradeep Padala. </P
1573 >Permission is hereby granted, free of charge, to any person obtaining a copy
1574 of this software and associated documentation files (the "Software"), to deal
1575 in the Software without restriction, including without limitation the rights
1576 to use, copy, modify, merge, publish, distribute, distribute with
1577 modifications, sublicense, and/or sell copies of the Software, and to permit
1578 persons to whom the Software is furnished to do so, subject to the following
1581 >The above copyright notice and this permission notice shall be included in all
1582 copies or substantial portions of the Software.</P
1584 >THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1585 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1586 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1587 ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
1588 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
1589 IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</P
1591 >Except as contained in this notice, the name(s) of the above copyright holders
1592 shall not be used in advertising or otherwise to promote the sale, use or
1593 other dealings in this Software without prior written authorization. </P
1602 >2. Hello World !!!</A
1605 >Welcome to the world of curses. Before we plunge into the library and look into
1606 its various features, let's write a simple program and say
1607 hello to the world. </P
1613 NAME="COMPILECURSES"
1614 >2.1. Compiling With the NCURSES Library</A
1617 >To use ncurses library functions, you have to include ncurses.h in your
1618 programs. To link the
1619 program with ncurses the flag -lncurses should be added.</P
1621 CLASS="PROGRAMLISTING"
1622 > #include <ncurses.h>
1627 compile and link: gcc <program file> -lncurses</PRE
1635 >Example 1. The Hello World !!! Program </B
1638 CLASS="PROGRAMLISTING"
1640 CLASS="INLINEMEDIAOBJECT"
1641 >#include <ncurses.h>
1645 initscr(); /* Start curses mode */
1646 printw("Hello World !!!"); /* Print Hello World */
1647 refresh(); /* Print it on to the real screen */
1648 getch(); /* Wait for user input */
1649 endwin(); /* End curses mode */
1666 The above program prints "Hello World !!!" to the screen and exits. This
1667 program shows how to initialize curses and do screen manipulation and
1668 end curses mode. Let's dissect it line by line. </P
1674 NAME="ABOUT-INITSCR"
1675 >2.2.1. About initscr()</A
1678 >The function initscr() initializes the terminal in curses mode. In some
1679 implementations, it clears the screen and presents a blank screen. To do any
1680 screen manipulation using curses package this has to be called first. This
1681 function initializes the curses system and allocates memory for our present
1685 >) and some other data-structures. Under extreme
1686 cases this function might fail due to insufficient memory to allocate memory
1687 for curses library's data structures. </P
1690 After this is done, we can do a variety of initializations to customize
1691 our curses settings. These details will be explained <A
1702 >2.2.2. The mysterious refresh()</A
1705 >The next line printw prints the string "Hello World !!!" on to the screen. This
1706 function is analogous to normal printf in all respects except that it prints
1707 the data on a window called stdscr at the current (y,x) co-ordinates. Since our
1708 present co-ordinates are at 0,0 the string is printed at the left hand corner
1711 >This brings us to that mysterious refresh(). Well, when we called printw
1712 the data is actually written to an imaginary window, which is not updated
1713 on the screen yet. The job of printw is to update a few flags
1714 and data structures and write the data to a buffer corresponding to stdscr.
1715 In order to show it on the screen, we need to call refresh() and tell the
1716 curses system to dump the contents on the screen.</P
1718 >The philosophy behind all this is to allow the programmer to do multiple updates
1719 on the imaginary screen or windows and do a refresh once all his screen update
1720 is done. refresh() checks the window and updates only the portion which has been
1721 changed. This improves performance and offers greater flexibility too. But, it is
1722 sometimes frustrating to beginners. A common mistake committed by beginners is
1723 to forget to call refresh() after they did some update through printw() class of
1724 functions. I still forget to add it sometimes :-) </P
1732 >2.2.3. About endwin()</A
1735 >And finally don't forget to end the curses mode. Otherwise your terminal might
1736 behave strangely after the program quits. endwin() frees the memory taken by
1737 curses sub-system and its data structures and puts the terminal in normal
1738 mode. This function must be called after you are done with the curses mode. </P
1748 >3. The Gory Details</A
1751 >Now that we have seen how to write a simple curses program let's get into the
1752 details. There are many functions that help customize what you see on screen and
1753 many features which can be put to full use. </P
1763 >4. Initialization</A
1766 >We now know that to initialize curses system the function initscr() has to be
1767 called. There are functions which can be called after this initialization to
1768 customize our curses session. We may ask the curses system to set the terminal
1769 in raw mode or initialize color or initialize the mouse etc.. Let's discuss some
1770 of the functions that are normally called immediately after initscr();</P
1777 >4.1. Initialization functions</A
1788 >4.2. raw() and cbreak()</A
1791 >Normally the terminal driver buffers the characters a user types until a new
1792 line or carriage return is encountered. But most programs require that the
1793 characters be available as soon as the user types them. The above two functions
1794 are used to disable line buffering. The difference between these two functions
1795 is in the way control characters like suspend (CTRL-Z), interrupt and quit
1796 (CTRL-C) are passed to the program. In the raw() mode these characters are
1797 directly passed to the program without generating a signal. In the
1801 > mode these control characters are
1802 interpreted as any other character by the terminal driver. I personally prefer
1803 to use raw() as I can exercise greater control over what the user does.</P
1811 >4.3. echo() and noecho()</A
1815 These functions control the echoing of characters typed by the user to the
1819 > switches off echoing. The
1820 reason you might want to do this is to gain more control over echoing or to
1821 suppress unnecessary echoing while taking input from the user through the
1822 getch() etc. functions. Most of the interactive programs call
1826 > at initialization and do the echoing
1827 of characters in a controlled manner. It gives the programmer the flexibility
1828 of echoing characters at any place in the window without updating current (y,x)
1840 >This is my favorite initialization function. It enables the reading of function
1841 keys like F1, F2, arrow keys etc. Almost every interactive program enables this,
1842 as arrow keys are a major part of any User Interface. Do
1845 >keypad(stdscr, TRUE) </TT
1846 > to enable this feature
1847 for the regular screen (stdscr). You will learn more about key management in
1848 later sections of this document.</P
1856 >4.5. halfdelay()</A
1859 >This function, though not used very often, is a useful one at times.
1860 halfdelay()is called to enable the half-delay mode, which is similar to the
1861 cbreak() mode in that characters typed are immediately available to program.
1862 However, it waits for 'X' tenths of a second for input and then returns ERR, if
1863 no input is available. 'X' is the timeout value passed to the function
1864 halfdelay(). This function is useful when you want to ask the user for input,
1865 and if he doesn't respond with in certain time, we can do some thing else. One
1866 possible example is a timeout at the password prompt. </P
1874 >4.6. Miscellaneous Initialization functions</A
1877 >There are few more functions which are called at initialization to
1878 customize curses behavior. They are not used as extensively as those mentioned
1879 above. Some of them are explained where appropriate.</P
1890 >Let's write a program which will clarify the usage of these functions.</P
1898 >Example 2. Initialization Function Usage example </B
1901 CLASS="PROGRAMLISTING"
1903 CLASS="INLINEMEDIAOBJECT"
1904 >#include <ncurses.h>
1909 initscr(); /* Start curses mode */
1910 raw(); /* Line buffering disabled */
1911 keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
1912 noecho(); /* Don't echo() while we do getch */
1914 printw("Type any character to see it in bold\n");
1915 ch = getch(); /* If raw() hadn't been called
1916 * we have to press enter before it
1917 * gets to the program */
1918 if(ch == KEY_F(1)) /* Without keypad enabled this will */
1919 printw("F1 Key pressed");/* not get to us either */
1920 /* Without noecho() some ugly escape
1921 * charachters might have been printed
1924 { printw("The pressed key is ");
1929 refresh(); /* Print it on to the real screen */
1930 getch(); /* Wait for user input */
1931 endwin(); /* End curses mode */
1938 >This program is self-explanatory. But I used functions which aren't explained
1939 yet. The function <TT
1943 character from user. It is equivalent to normal
1947 > except that we can disable the line
1948 buffering to avoid <enter> after input. Look for more about
1952 >and reading keys in the <A
1954 > key management section </A
1955 >. The functions attron and attroff
1956 are used to switch some attributes on and off respectively. In the example I
1957 used them to print the character in bold. These functions are explained in detail
1967 >5. A Word about Windows</A
1971 Before we plunge into the myriad ncurses functions, let me clear few things
1972 about windows. Windows are explained in detail in following <A
1977 >A Window is an imaginary screen defined by curses system. A window does not mean
1978 a bordered window which you usually see on Win9X platforms. When curses is
1979 initialized, it creates a default window named
1983 > which represents your 80x25 (or the size
1984 of window in which you are running) screen. If you are doing simple tasks like
1985 printing few strings, reading input etc., you can safely use this single window
1986 for all of your purposes. You can also create windows and call functions which
1987 explicitly work on the specified window.</P
1989 >For example, if you call</P
1991 CLASS="PROGRAMLISTING"
1992 > printw("Hi There !!!");
1995 >It prints the string on stdscr at the present cursor position. Similarly the
1996 call to refresh(), works on stdscr only. </P
1998 >Say you have created <A
2002 call a function with a 'w' added to the usual function.</P
2004 CLASS="PROGRAMLISTING"
2005 > wprintw(win, "Hi There !!!");
2008 >As you will see in the rest of the document, naming of functions follow the
2009 same convention. For each function there usually are three more functions.</P
2011 CLASS="PROGRAMLISTING"
2012 > printw(string); /* Print on stdscr at present cursor position */
2013 mvprintw(y, x, string);/* Move to (y, x) then print string */
2014 wprintw(win, string); /* Print on window win at present cursor position */
2016 mvwprintw(win, y, x, string); /* Move to (y, x) relative to window */
2017 /* co-ordinates and then print */</PRE
2019 >Usually the w-less functions are macros which expand to corresponding w-function
2020 with stdscr as the window parameter.</P
2028 >6. Output functions</A
2031 >I guess you can't wait any more to see some action. Back to our odyssey of
2032 curses functions. Now that curses is initialized, let's interact with
2035 >There are three classes of functions which you can use to do output on screen.
2042 >addch() class: Print single character with attributes </P
2046 >printw() class: Print formatted output similar to printf()</P
2050 >addstr() class: Print strings</P
2055 >These functions can be used interchangeably and it's a matter of style as to
2056 which class is used. Let's see each one in detail.</P
2063 >6.1. addch() class of functions</A
2066 >These functions put a single character into the current cursor location and
2067 advance the position of the cursor. You can give the character to be printed but
2068 they usually are used to print a character with some attributes. Attributes are
2069 explained in detail in later <A
2073 document. If a character is associated with an attribute(bold, reverse video
2074 etc.), when curses prints the character, it is printed in that attribute.</P
2076 >In order to combine a character with some attributes, you have two options:</P
2082 >By OR'ing a single character with the desired attribute macros. These attribute
2083 macros could be found in the header file
2087 >. For example, you want to print a
2088 character ch(of type char) bold and underlined, you would call addch() as below.
2090 CLASS="PROGRAMLISTING"
2091 > addch(ch | A_BOLD | A_UNDERLINE);</PRE
2096 >By using functions like <TT
2098 >attrset(),attron(),attroff()</TT
2099 >. These functions are explained in the <A
2102 > section. Briefly, they manipulate the current attributes of
2103 the given window. Once set, the character printed in the window are associated
2104 with the attributes until it is turned off.</P
2111 > provides some special
2112 characters for character-based graphics. You can draw tables, horizontal or
2113 vertical lines, etc. You can find all avaliable characters in the header file
2117 >. Try looking for macros beginning
2129 >6.2. mvaddch(), waddch() and mvwaddch()</A
2135 > is used to move the cursor to a
2136 given point, and then print. Thus, the calls:
2138 CLASS="PROGRAMLISTING"
2139 > move(row,col); /* moves the cursor to row<SPAN
2156 CLASS="PROGRAMLISTING"
2157 > mvaddch(row,col,ch);</PRE
2167 >, except that it adds a character into
2168 the given window. (Note that <TT
2172 character into the window <TT
2177 >In a similar fashion <TT
2181 used to add a character into the given window at the given coordinates.</P
2183 >Now, we are familiar with the basic output function
2187 >. But, if we want to print a string, it
2188 would be very annoying to print it character by character. Fortunately,
2219 >6.3. printw() class of functions</A
2222 >These functions are similar to <TT
2226 the added capability of printing at any position on the screen. </P
2232 NAME="PRINTWMVPRINTW"
2233 >6.3.1. printw() and mvprintw</A
2236 >These two functions work much like <TT
2243 > can be used to move the cursor to a
2244 position and then print. If you want to move the cursor first and then print
2252 > first and then use
2256 > though I see no point why one should
2261 flexibility to manipulate. </P
2268 NAME="WPRINTWMVWPRINTW"
2269 >6.3.2. wprintw() and mvwprintw</A
2272 >These two functions are similar to above two except that they print in the
2273 corresponding window given as argument. </P
2281 >6.3.3. vwprintw()</A
2284 >This function is similar to <TT
2288 be used when variable number of arguments are to be printed.</P
2295 NAME="SIMPLEPRINTWEX"
2296 >6.3.4. A Simple printw example</A
2305 >Example 3. A Simple printw example </B
2308 CLASS="PROGRAMLISTING"
2310 CLASS="INLINEMEDIAOBJECT"
2311 >#include <ncurses.h> /* ncurses.h includes stdio.h */
2312 #include <string.h>
2316 char mesg[]="Just a string"; /* message to be appeared on the screen */
2317 int row,col; /* to store the number of rows and *
2318 * the number of colums of the screen */
2319 initscr(); /* start the curses mode */
2320 getmaxyx(stdscr,row,col); /* get the number of rows and columns */
2321 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
2322 /* print the message at the center of the screen */
2323 mvprintw(row-2,0,"This screen has %d rows and %d columns\n",row,col);
2324 printw("Try resizing your window(if possible) and then run this program again");
2334 >Above program demonstrates how easy it is to use <TT
2337 >. You just feed the coordinates and the message to be appeared
2338 on the screen, then it does what you want.</P
2340 >The above program introduces us to a new function
2344 >, a macro defined in
2348 >. It gives the number of columns and
2349 the number of rows in a given window.
2353 > does this by updating the variables
2354 given to it. Since <TT
2358 we don't pass pointers to it, we just give two integer variables. </P
2367 >6.4. addstr() class of functions</A
2373 > is used to put a character string into
2374 a given window. This function is similar to calling
2378 > once for each character in a given
2379 string. This is true for all output functions. There are other functions from
2380 this family such as <TT
2382 >mvaddstr(),mvwaddstr()</TT
2387 >, which obey the naming convention of
2388 curses.(e.g. mvaddstr() is similar to the respective calls move() and then
2389 addstr().) Another function of this family is addnstr(), which takes an integer
2390 parameter(say n) additionally. This function puts at most n characters into the
2391 screen. If n is negative, then the entire string will be added. </P
2399 >6.5. A word of caution</A
2402 >All these functions take y co-ordinate first and then x in their arguments.
2403 A common mistake by beginners is to pass x,y in that order. If you are
2404 doing too many manipulations of (y,x) co-ordinates, think of dividing the
2405 screen into windows and manipulate each one separately. Windows are explained
2418 >7. Input functions</A
2421 >Well, printing without taking input, is boring. Let's see functions which
2422 allow us to get input from user. These functions also can be divided into
2423 three categories.</P
2430 >getch() class: Get a character</P
2434 >scanw() class: Get formatted input</P
2438 >getstr() class: Get strings</P
2447 >7.1. getch() class of functions</A
2450 >These functions read a single character from the terminal. But there are several
2451 subtle facts to consider. For example if you don't use the function cbreak(),
2452 curses will not read your input characters contiguously but will begin read them
2453 only after a new line or an EOF is encountered. In order to avoid this, the
2454 cbreak() function must used so that characters are immediately available to your
2455 program. Another widely used function is noecho(). As the name suggests, when
2456 this function is set (used), the characters that are keyed in by the user will
2457 not show up on the screen. The two functions cbreak() and noecho() are typical
2458 examples of key management. Functions of this genre are explained in the
2461 >key management section </A
2470 >7.2. scanw() class of functions</A
2473 >These functions are similar to <TT
2477 added capability of getting the input from any location on the screen.</P
2484 >7.2.1. scanw() and mvscanw</A
2487 >The usage of these functions is similar to that of
2491 >, where the line to be scanned is
2495 > function. That is, these
2496 functions call to <TT
2499 > function(explained
2500 below) and uses the resulting line for a scan. </P
2507 NAME="WSCANWMVWSCANW"
2508 >7.2.2. wscanw() and mvwscanw()</A
2511 >These are similar to above two functions except that they read from a window,
2512 which is supplied as one of the arguments to these functions. </P
2520 >7.2.3. vwscanw()</A
2523 >This function is similar to <TT
2527 be used when a variable number of arguments are to be scanned.</P
2536 >7.3. getstr() class of functions</A
2539 >These functions are used to get strings from the terminal. In essence, this
2540 function performs the same task as would be achieved by a series of calls to
2544 > until a newline, carriage return, or
2545 end-of-file is received. The resulting string of characters are pointed to by
2549 >, which is a character pointer provided by
2558 >7.4. Some examples</A
2567 >Example 4. A Simple scanw example </B
2570 CLASS="PROGRAMLISTING"
2572 CLASS="INLINEMEDIAOBJECT"
2573 >#include <ncurses.h> /* ncurses.h includes stdio.h */
2574 #include <string.h>
2578 char mesg[]="Enter a string: "; /* message to be appeared on the screen */
2580 int row,col; /* to store the number of rows and *
2581 * the number of colums of the screen */
2582 initscr(); /* start the curses mode */
2583 getmaxyx(stdscr,row,col); /* get the number of rows and columns */
2584 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
2585 /* print the message at the center of the screen */
2587 mvprintw(LINES - 2, 0, "You Entered: %s", str);
2606 >We have seen an example of how attributes can be used to print characters with
2607 some special effects. Attributes, when set prudently, can present information in
2608 an easy, understandable manner. The following program takes a C file as input
2609 and prints the file with comments in bold. Scan through the code. </P
2617 >Example 5. A Simple Attributes example </B
2620 CLASS="PROGRAMLISTING"
2622 CLASS="INLINEMEDIAOBJECT"
2623 >/* pager functionality by Joseph Spainhour" <spainhou@bellsouth.net> */
2624 #include <ncurses.h>
2625 #include <stdlib.h>
2627 int main(int argc, char *argv[])
2629 int ch, prev, row, col;
2636 printf("Usage: %s <a c file name>\n", argv[0]);
2639 fp = fopen(argv[1], "r");
2642 perror("Cannot open input file");
2645 initscr(); /* Start curses mode */
2646 getmaxyx(stdscr, row, col); /* find the boundaries of the screeen */
2647 while((ch = fgetc(fp)) != EOF) /* read the file till we reach the end */
2649 getyx(stdscr, y, x); /* get the current curser position */
2650 if(y == (row - 1)) /* are we are at the end of the screen */
2652 printw("<-Press Any Key->"); /* tell the user to press a key */
2654 clear(); /* clear the screen */
2655 move(0, 0); /* start at the beginning of the screen */
2657 if(prev == '/' && ch == '*') /* If it is / and * then only
2660 attron(A_BOLD); /* cut bold on */
2661 getyx(stdscr, y, x); /* get the current curser position */
2662 move(y, x - 1); /* back up one space */
2663 printw("%c%c", '/', ch); /* The actual printing is done here */
2668 if(prev == '*' && ch == '/')
2669 attroff(A_BOLD); /* Switch it off once we got *
2673 endwin(); /* End curses mode */
2681 Don't worry about all those initialization and other crap. Concentrate on
2682 the while loop. It reads each character in the file and searches for the
2683 pattern /*. Once it spots the pattern, it switches the BOLD attribute on with
2687 > . When we get the pattern */ it is
2694 The above program also introduces us to two useful functions
2702 >. The first function gets the
2703 co-ordinates of the present cursor into the variables y, x. Since getyx() is a
2704 macro we don't have to pass pointers to variables. The function
2708 > moves the cursor to the co-ordinates
2712 The above program is really a simple one which doesn't do much. On these lines
2713 one could write a more useful program which reads a C file, parses it and prints
2714 it in different colors. One could even extend it to other languages as well.</P
2720 NAME="ATTRIBDETAILS"
2721 >8.1. The details</A
2724 >Let's get into more details of attributes. The functions <TT
2726 >attron(), attroff(), attrset() </TT
2727 >, and their sister functions
2731 > etc.. can be used to switch
2732 attributes on/off , get attributes and produce a colorful display.</P
2734 >The functions attron and attroff take a bit-mask of attributes and switch them
2735 on or off, respectively. The following video attributes, which are defined in
2736 <curses.h> can be passed to these functions. </P
2738 CLASS="PROGRAMLISTING"
2740 A_NORMAL Normal display (no highlight)
2741 A_STANDOUT Best highlighting mode of the terminal.
2742 A_UNDERLINE Underlining
2743 A_REVERSE Reverse video
2746 A_BOLD Extra bright or bold
2747 A_PROTECT Protected mode
2748 A_INVIS Invisible or blank mode
2749 A_ALTCHARSET Alternate character set
2750 A_CHARTEXT Bit-mask to extract a character
2751 COLOR_PAIR(n) Color-pair number n
2755 The last one is the most colorful one :-) Colors are explained in the
2762 >We can OR(|) any number of above attributes to get a combined effect. If you
2763 wanted reverse video with blinking characters you can use</P
2765 CLASS="PROGRAMLISTING"
2766 > attron(A_REVERSE | A_BLINK);</PRE
2773 NAME="ATTRONVSATTRSET"
2774 >8.2. attron() vs attrset()</A
2777 >Then what is the difference between attron() and attrset()? attrset sets the
2778 attributes of window whereas attron just switches on the attribute given to it.
2779 So attrset() fully overrides whatever attributes the window previously had and
2780 sets it to the new attribute(s). Similarly attroff() just switches off the
2781 attribute(s) given to it as an argument. This gives us the flexibility of
2782 managing attributes easily.But if you use them carelessly you may loose track of
2783 what attributes the window has and garble the display. This is especially true
2784 while managing menus with colors and highlighting. So decide on a consistent
2785 policy and stick to it. You can always use <TT
2788 > which is equivalent to <TT
2790 > attrset(A_NORMAL)</TT
2791 > which turns off all attributes and brings you to normal mode.</P
2802 > The function attr_get() gets the current attributes and color pair of the
2803 window. Though we might not use this as often as the above functions, this is
2804 useful in scanning areas of screen. Say we wanted to do some complex update on
2805 screen and we are not sure what attribute each character is associated with.
2806 Then this function can be used with either attrset or attron to produce the
2807 desired effect. </P
2815 >8.4. attr_ functions</A
2818 >There are series of functions like attr_set(), attr_on etc.. These are similar
2819 to above functions except that they take parameters of type
2831 >8.5. wattr functions</A
2834 >For each of the above functions we have a corresponding function with 'w' which
2835 operates on a particular window. The above functions operate on stdscr. </P
2843 >8.6. chgat() functions</A
2846 >The function chgat() is listed in the end of the man page curs_attr. It actually
2847 is a useful one. This function can be used to set attributes for a group of
2848 characters without moving. I mean it !!! without moving the cursor :-) It
2849 changes the attributes of a given number of characters starting at the current
2852 >We can give -1 as the character count to update till end of line. If you want to
2853 change attributes of characters from current position to end of line, just use
2856 CLASS="PROGRAMLISTING"
2857 > chgat(-1, A_REVERSE, 0, NULL);</PRE
2860 This function is useful when changing attributes for characters that are
2861 already on the screen. Move to the character from which you want to change and
2862 change the attribute. </P
2864 >Other functions wchgat(), mvchgat(), wchgat() behave similarly except that the w
2865 functions operate on the particular window. The mv functions first move the
2866 cursor then perform the work given to them. Actually chgat is a macro which is
2867 replaced by a wchgat() with stdscr as the window. Most of the "w-less" functions
2876 >Example 6. Chgat() Usage example </B
2879 CLASS="PROGRAMLISTING"
2881 CLASS="INLINEMEDIAOBJECT"
2882 >#include <ncurses.h>
2884 int main(int argc, char *argv[])
2885 { initscr(); /* Start curses mode */
2886 start_color(); /* Start color functionality */
2888 init_pair(1, COLOR_CYAN, COLOR_BLACK);
2889 printw("A Big string which i didn't care to type fully ");
2890 mvchgat(0, 0, -1, A_BLINK, 1, NULL);
2892 * First two parameters specify the position at which to start
2893 * Third parameter number of characters to update. -1 means till
2895 * Forth parameter is the normal attribute you wanted to give
2897 * Fifth is the color index. It is the index given during init_pair()
2898 * use 0 if you didn't want color
2899 * Sixth one is always NULL
2903 endwin(); /* End curses mode */
2909 >This example also introduces us to the color world of curses. Colors will be
2910 explained in detail later. Use 0 for no color.</P
2922 >Windows form the most important concept in curses. You have seen the standard
2923 window stdscr above where all the functions implicitly operated on this window.
2924 Now to make design even a simplest GUI, you need to resort to windows. The main
2925 reason you may want to use windows is to manipulate parts of the screen
2926 separately, for better efficiency, by updating only the windows that need to be
2927 changed and for a better design. I would say the last reason is the most
2928 important in going for windows. You should always strive for a better and
2929 easy-to-manage design in your programs. If you are writing big, complex GUIs
2930 this is of pivotal importance before you start doing anything.</P
2940 >A Window can be created by calling the function
2944 >. It doesn't create any thing on the
2945 screen actually. It allocates memory for a structure to manipulate the window
2946 and updates the structure with data regarding the window like it's size, beginy,
2947 beginx etc.. Hence in curses, a window is just an abstraction of an imaginary
2948 window, which can be manipulated independent of other parts of screen. The
2949 function newwin() returns a pointer to structure WINDOW, which can be passed to
2950 window related functions like wprintw() etc.. Finally the window can be
2951 destroyed with delwin(). It will deallocate the memory associated with the
2952 window structure.</P
2960 >9.2. Let there be a Window !!!</A
2963 >What fun is it, if a window is created and we can't see it. So the fun part
2964 begins by displaying the window. The function
2968 > can be used to draw a border around the
2969 window. Let's explore these functions in more detail in this example.</P
2977 >Example 7. Window Border example </B
2980 CLASS="PROGRAMLISTING"
2982 CLASS="INLINEMEDIAOBJECT"
2983 >#include <ncurses.h>
2986 WINDOW *create_newwin(int height, int width, int starty, int startx);
2987 void destroy_win(WINDOW *local_win);
2989 int main(int argc, char *argv[])
2991 int startx, starty, width, height;
2994 initscr(); /* Start curses mode */
2995 cbreak(); /* Line buffering disabled, Pass on
2996 * everty thing to me */
2997 keypad(stdscr, TRUE); /* I need that nifty F1 */
3001 starty = (LINES - height) / 2; /* Calculating for a center placement */
3002 startx = (COLS - width) / 2; /* of the window */
3003 printw("Press F1 to exit");
3005 my_win = create_newwin(height, width, starty, startx);
3007 while((ch = getch()) != KEY_F(1))
3010 destroy_win(my_win);
3011 my_win = create_newwin(height, width, starty,--startx);
3014 destroy_win(my_win);
3015 my_win = create_newwin(height, width, starty,++startx);
3018 destroy_win(my_win);
3019 my_win = create_newwin(height, width, --starty,startx);
3022 destroy_win(my_win);
3023 my_win = create_newwin(height, width, ++starty,startx);
3028 endwin(); /* End curses mode */
3032 WINDOW *create_newwin(int height, int width, int starty, int startx)
3033 { WINDOW *local_win;
3035 local_win = newwin(height, width, starty, startx);
3036 box(local_win, 0 , 0); /* 0, 0 gives default characters
3037 * for the vertical and horizontal
3039 wrefresh(local_win); /* Show that box */
3044 void destroy_win(WINDOW *local_win)
3046 /* box(local_win, ' ', ' '); : This won't produce the desired
3047 * result of erasing the window. It will leave it's four corners
3048 * and so an ugly remnant of window.
3050 wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' ');
3051 /* The parameters taken are
3052 * 1. win: the window on which to operate
3053 * 2. ls: character to be used for the left side of the window
3054 * 3. rs: character to be used for the right side of the window
3055 * 4. ts: character to be used for the top side of the window
3056 * 5. bs: character to be used for the bottom side of the window
3057 * 6. tl: character to be used for the top left corner of the window
3058 * 7. tr: character to be used for the top right corner of the window
3059 * 8. bl: character to be used for the bottom left corner of the window
3060 * 9. br: character to be used for the bottom right corner of the window
3062 wrefresh(local_win);
3074 >9.3. Explanation</A
3077 >Don't scream. I know it's a big example. But I have to explain some important
3078 things here :-). This program creates a rectangular window that can be moved
3079 with left, right, up, down arrow keys. It repeatedly creates and destroys
3080 windows as user press a key. Don't go beyond the screen limits. Checking for
3081 those limits is left as an exercise for the reader. Let's dissect it by line by line.</P
3085 >create_newwin()</TT
3086 > function creates a window
3090 > and displays a border around it
3091 with box. The function <TT
3095 erases the window from screen by painting a border with ' ' character and then
3099 > to deallocate memory related
3100 to it. Depending on the key the user presses, starty or startx is changed and a
3101 new window is created.</P
3103 >In the destroy_win, as you can see, I used wborder instead of box. The reason is
3104 written in the comments (You missed it. I know. Read the code :-)). wborder
3105 draws a border around the window with the characters given to it as the 4 corner
3106 points and the 4 lines. To put it clearly, if you have called wborder as below:
3108 CLASS="PROGRAMLISTING"
3109 > wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');</PRE
3112 >it produces some thing like </P
3114 CLASS="PROGRAMLISTING"
3130 >9.4. The other stuff in the example</A
3133 >You can also see in the above examples, that I have used the variables COLS,
3134 LINES which are initialized to the screen sizes after initscr(). They can be
3135 useful in finding screen dimensions and finding the center co-ordinate of the
3136 screen as above. The function <TT
3140 gets the key from keyboard and according to the key it does the corresponding
3141 work. This type of switch- case is very common in any GUI based programs.</P
3148 NAME="OTHERBORDERFUNCS"
3149 >9.5. Other Border functions</A
3152 >Above program is grossly inefficient in that with each press of a key, a window
3153 is destroyed and another is created. So let's write a more efficient program
3154 which uses other border related functions.</P
3156 >The following program uses <TT
3163 > to achieve similar effect. These two
3164 functions are simple. They create a horizontal or vertical line of the specified
3165 length at the specified position.</P
3173 >Example 8. More border functions</B
3176 CLASS="PROGRAMLISTING"
3178 CLASS="INLINEMEDIAOBJECT"
3179 >#include <ncurses.h>
3181 typedef struct _win_border_struct {
3182 chtype ls, rs, ts, bs,
3186 typedef struct _WIN_struct {
3193 void init_win_params(WIN *p_win);
3194 void print_win_params(WIN *p_win);
3195 void create_box(WIN *win, bool flag);
3197 int main(int argc, char *argv[])
3201 initscr(); /* Start curses mode */
3202 start_color(); /* Start the color functionality */
3203 cbreak(); /* Line buffering disabled, Pass on
3204 * everty thing to me */
3205 keypad(stdscr, TRUE); /* I need that nifty F1 */
3207 init_pair(1, COLOR_CYAN, COLOR_BLACK);
3209 /* Initialize the window parameters */
3210 init_win_params(&win);
3211 print_win_params(&win);
3213 attron(COLOR_PAIR(1));
3214 printw("Press F1 to exit");
3216 attroff(COLOR_PAIR(1));
3218 create_box(&win, TRUE);
3219 while((ch = getch()) != KEY_F(1))
3222 create_box(&win, FALSE);
3224 create_box(&win, TRUE);
3227 create_box(&win, FALSE);
3229 create_box(&win, TRUE);
3232 create_box(&win, FALSE);
3234 create_box(&win, TRUE);
3237 create_box(&win, FALSE);
3239 create_box(&win, TRUE);
3243 endwin(); /* End curses mode */
3246 void init_win_params(WIN *p_win)
3248 p_win->height = 3;
3249 p_win->width = 10;
3250 p_win->starty = (LINES - p_win->height)/2;
3251 p_win->startx = (COLS - p_win->width)/2;
3253 p_win->border.ls = '|';
3254 p_win->border.rs = '|';
3255 p_win->border.ts = '-';
3256 p_win->border.bs = '-';
3257 p_win->border.tl = '+';
3258 p_win->border.tr = '+';
3259 p_win->border.bl = '+';
3260 p_win->border.br = '+';
3263 void print_win_params(WIN *p_win)
3266 mvprintw(25, 0, "%d %d %d %d", p_win->startx, p_win->starty,
3267 p_win->width, p_win->height);
3271 void create_box(WIN *p_win, bool flag)
3275 x = p_win->startx;
3276 y = p_win->starty;
3277 w = p_win->width;
3278 h = p_win->height;
3281 { mvaddch(y, x, p_win->border.tl);
3282 mvaddch(y, x + w, p_win->border.tr);
3283 mvaddch(y + h, x, p_win->border.bl);
3284 mvaddch(y + h, x + w, p_win->border.br);
3285 mvhline(y, x + 1, p_win->border.ts, w - 1);
3286 mvhline(y + h, x + 1, p_win->border.bs, w - 1);
3287 mvvline(y + 1, x, p_win->border.ls, h - 1);
3288 mvvline(y + 1, x + w, p_win->border.rs, h - 1);
3292 for(j = y; j <= y + h; ++j)
3293 for(i = x; i <= x + w; ++i)
3317 >10.1. The basics</A
3320 >Life seems dull with no colors. Curses has a nice mechanism to handle colors.
3321 Let's get into the thick of the things with a small program.</P
3329 >Example 9. A Simple Color example </B
3332 CLASS="PROGRAMLISTING"
3334 CLASS="INLINEMEDIAOBJECT"
3335 >#include <ncurses.h>
3337 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string);
3338 int main(int argc, char *argv[])
3339 { initscr(); /* Start curses mode */
3340 if(has_colors() == FALSE)
3342 printf("Your terminal does not support color\n");
3345 start_color(); /* Start color */
3346 init_pair(1, COLOR_RED, COLOR_BLACK);
3348 attron(COLOR_PAIR(1));
3349 print_in_middle(stdscr, LINES / 2, 0, 0, "Viola !!! In color ...");
3350 attroff(COLOR_PAIR(1));
3354 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string)
3368 length = strlen(string);
3369 temp = (width - length)/ 2;
3370 x = startx + (int)temp;
3371 mvwprintw(win, y, x, "%s", string);
3378 >As you can see, to start using color, you should first call the function
3382 >. After that, you can use color
3383 capabilities of your terminals using various functions. To find out whether a
3384 terminal has color capabilities or not, you can use
3388 > function, which returns FALSE if
3389 the terminal does not support color. </P
3391 >Curses initializes all the colors supported by terminal when start_color() is
3392 called. These can be accessed by the define constants like
3396 > etc. Now to actually start using
3397 colors, you have to define pairs. Colors are always used in pairs. That means
3398 you have to use the function <TT
3402 define the foreground and background for the pair number you give. After that
3403 that pair number can be used as a normal attribute with <TT
3406 >function. This may seem to be cumbersome at first.
3407 But this elegant solution allows us to manage color pairs very easily. To
3408 appreciate it, you have to look into the the source code of "dialog", a utility
3409 for displaying dialog boxes from shell scripts. The developers have defined
3410 foreground and background combinations for all the colors they might need and
3411 initialized at the beginning. This makes it very easy to set attributes just by
3412 accessing a pair which we already have defined as a constant.</P
3414 >The following colors are defined in <TT
3418 You can use these as parameters for various color functions.
3420 CLASS="PROGRAMLISTING"
3436 NAME="CHANGECOLORDEFS"
3437 >10.2. Changing Color Definitions</A
3443 >can be used to change
3444 the rgb values for the colors defined by curses initially. Say you wanted to
3445 lighten the intensity of red color by a minuscule. Then you can use this
3448 CLASS="PROGRAMLISTING"
3449 > init_color(COLOR_RED, 700, 0, 0);
3450 /* param 1 : color name
3451 * param 2, 3, 4 : rgb content min = 0, max = 1000 */</PRE
3453 >If your terminal cannot change the color definitions, the function returns ERR.
3456 >can_change_color()</TT
3458 find out whether the terminal has the capability of changing color content or
3459 not. The rgb content is scaled from 0 to 1000. Initially RED color is defined
3460 with content 1000(r), 0(g), 0(b). </P
3468 >10.3. Color Content</A
3473 >color_content()</TT
3478 > can be used to find the color
3479 content and foreground, background combination for the pair. </P
3488 >11. Interfacing with the key board</A
3496 >11.1. The Basics</A
3499 >No GUI is complete without a strong user interface and to interact with the
3500 user, a curses program should be sensitive to key presses or the mouse actions
3501 done by the user. Let's deal with the keys first.</P
3503 >As you have seen in almost all of the above examples, it's very easy to get key
3504 input from the user. A simple way of getting key presses is to use
3508 > function. The cbreak mode should be
3509 enabled to read keys when you are interested in reading individual key hits
3510 rather than complete lines of text (which usually end with a carriage return).
3511 keypad should be enabled to get the Functions keys, arrow keys etc. See the
3512 initialization section for details.</P
3517 > returns an integer corresponding to the
3518 key pressed. If it is a normal character, the integer value will be equivalent
3519 to the character. Otherwise it returns a number which can be matched with the
3520 constants defined in <TT
3524 the user presses F1, the integer returned is 265. This can be checked using the
3525 macro KEY_F() defined in curses.h. This makes reading keys portable and easy to
3528 >For example, if you call getch() like this</P
3530 CLASS="PROGRAMLISTING"
3535 >getch() will wait for the user to press a key, (unless you specified a timeout)
3536 and when user presses a key, the corresponding integer is returned. Then you can
3537 check the value returned with the constants defined in curses.h to match against
3538 the keys you want.</P
3540 >The following code piece will do that job.</P
3542 CLASS="PROGRAMLISTING"
3543 > if(ch == KEY_LEFT)
3544 printw("Left arrow is pressed\n");</PRE
3546 >Let's write a small program which creates a menu which can be navigated by up
3555 >11.2. A Simple Key Usage example</A
3564 >Example 10. A Simple Key Usage example </B
3567 CLASS="PROGRAMLISTING"
3569 CLASS="INLINEMEDIAOBJECT"
3570 >#include <stdio.h>
3571 #include <ncurses.h>
3586 int n_choices = sizeof(choices) / sizeof(char *);
3587 void print_menu(WINDOW *menu_win, int highlight);
3598 cbreak(); /* Line buffering disabled. pass on everything */
3599 startx = (80 - WIDTH) / 2;
3600 starty = (24 - HEIGHT) / 2;
3602 menu_win = newwin(HEIGHT, WIDTH, starty, startx);
3603 keypad(menu_win, TRUE);
3604 mvprintw(0, 0, "Use arrow keys to go up and down, Press enter to select a choice");
3606 print_menu(menu_win, highlight);
3608 { c = wgetch(menu_win);
3612 highlight = n_choices;
3617 if(highlight == n_choices)
3626 mvprintw(24, 0, "Charcter pressed is = %3d Hopefully it can be printed as '%c'", c, c);
3630 print_menu(menu_win, highlight);
3631 if(choice != 0) /* User did a choice come out of the infinite loop */
3634 mvprintw(23, 0, "You chose choice %d with choice string %s\n", choice, choices[choice - 1]);
3642 void print_menu(WINDOW *menu_win, int highlight)
3648 box(menu_win, 0, 0);
3649 for(i = 0; i < n_choices; ++i)
3650 { if(highlight == i + 1) /* High light the present choice */
3651 { wattron(menu_win, A_REVERSE);
3652 mvwprintw(menu_win, y, x, "%s", choices[i]);
3653 wattroff(menu_win, A_REVERSE);
3656 mvwprintw(menu_win, y, x, "%s", choices[i]);
3672 >12. Interfacing with the mouse</A
3675 >Now that you have seen how to get keys, lets do the same thing from mouse.
3676 Usually each UI allows the user to interact with both keyboard and mouse. </P
3683 >12.1. The Basics</A
3686 >Before you do any thing else, the events you want to receive have to be enabled
3692 CLASS="PROGRAMLISTING"
3693 > mousemask( mmask_t newmask, /* The events you want to listen to */
3694 mmask_t *oldmask) /* The old events mask */</PRE
3696 >The first parameter to above function is a bit mask of events you would like to
3697 listen. By default, all the events are turned off. The bit mask <TT
3699 > ALL_MOUSE_EVENTS</TT
3700 > can be used to get all the events.</P
3702 >The following are all the event masks:</P
3704 CLASS="PROGRAMLISTING"
3706 ---------------------------------------------------------------------
3707 BUTTON1_PRESSED mouse button 1 down
3708 BUTTON1_RELEASED mouse button 1 up
3709 BUTTON1_CLICKED mouse button 1 clicked
3710 BUTTON1_DOUBLE_CLICKED mouse button 1 double clicked
3711 BUTTON1_TRIPLE_CLICKED mouse button 1 triple clicked
3712 BUTTON2_PRESSED mouse button 2 down
3713 BUTTON2_RELEASED mouse button 2 up
3714 BUTTON2_CLICKED mouse button 2 clicked
3715 BUTTON2_DOUBLE_CLICKED mouse button 2 double clicked
3716 BUTTON2_TRIPLE_CLICKED mouse button 2 triple clicked
3717 BUTTON3_PRESSED mouse button 3 down
3718 BUTTON3_RELEASED mouse button 3 up
3719 BUTTON3_CLICKED mouse button 3 clicked
3720 BUTTON3_DOUBLE_CLICKED mouse button 3 double clicked
3721 BUTTON3_TRIPLE_CLICKED mouse button 3 triple clicked
3722 BUTTON4_PRESSED mouse button 4 down
3723 BUTTON4_RELEASED mouse button 4 up
3724 BUTTON4_CLICKED mouse button 4 clicked
3725 BUTTON4_DOUBLE_CLICKED mouse button 4 double clicked
3726 BUTTON4_TRIPLE_CLICKED mouse button 4 triple clicked
3727 BUTTON_SHIFT shift was down during button state change
3728 BUTTON_CTRL control was down during button state change
3729 BUTTON_ALT alt was down during button state change
3730 ALL_MOUSE_EVENTS report all button state changes
3731 REPORT_MOUSE_POSITION report mouse movement</PRE
3738 NAME="GETTINGEVENTS"
3739 >12.2. Getting the events</A
3742 >Once a class of mouse events have been enabled, getch() class of functions
3743 return KEY_MOUSE every time some mouse event happens. Then the mouse event can
3744 be retrieved with <TT
3749 >The code approximately looks like this:</P
3751 CLASS="PROGRAMLISTING"
3756 if(getmouse(&event) == OK)
3757 . /* Do some thing with the event */
3762 getmouse() returns the event into the pointer given to it. It's a structure
3765 CLASS="PROGRAMLISTING"
3768 short id; /* ID to distinguish multiple devices */
3769 int x, y, z; /* event coordinates */
3770 mmask_t bstate; /* button state bits */
3776 > is the main variable we are
3777 interested in. It tells the button state of the mouse.</P
3779 >Then with a code snippet like the following, we can find out what happened.</P
3781 CLASS="PROGRAMLISTING"
3782 > if(event.bstate & BUTTON1_PRESSED)
3783 printw("Left Button Pressed");</PRE
3790 NAME="MOUSETOGETHER"
3791 >12.3. Putting it all Together</A
3794 >That's pretty much interfacing with mouse. Let's create the same menu and enable
3795 mouse interaction. To make things simpler, key handling is removed.</P
3803 >Example 11. Access the menu with mouse !!! </B
3806 CLASS="PROGRAMLISTING"
3808 CLASS="INLINEMEDIAOBJECT"
3809 >#include <ncurses.h>
3817 char *choices[] = { "Choice 1",
3824 int n_choices = sizeof(choices) / sizeof(char *);
3826 void print_menu(WINDOW *menu_win, int highlight);
3827 void report_choice(int mouse_x, int mouse_y, int *p_choice);
3830 { int c, choice = 0;
3834 /* Initialize curses */
3838 cbreak(); //Line buffering disabled. pass on everything
3840 /* Try to put the window in the middle of screen */
3841 startx = (80 - WIDTH) / 2;
3842 starty = (24 - HEIGHT) / 2;
3845 mvprintw(23, 1, "Click on Exit to quit (Works best in a virtual console)");
3849 /* Print the menu for the first time */
3850 menu_win = newwin(HEIGHT, WIDTH, starty, startx);
3851 print_menu(menu_win, 1);
3852 /* Get all the mouse events */
3853 mousemask(ALL_MOUSE_EVENTS, NULL);
3856 { c = wgetch(menu_win);
3859 if(getmouse(&event) == OK)
3860 { /* When the user clicks left mouse button */
3861 if(event.bstate & BUTTON1_PRESSED)
3862 { report_choice(event.x + 1, event.y + 1, &choice);
3863 if(choice == -1) //Exit chosen
3865 mvprintw(22, 1, "Choice made is : %d String Chosen is \"%10s\"", choice, choices[choice - 1]);
3869 print_menu(menu_win, choice);
3879 void print_menu(WINDOW *menu_win, int highlight)
3885 box(menu_win, 0, 0);
3886 for(i = 0; i < n_choices; ++i)
3887 { if(highlight == i + 1)
3888 { wattron(menu_win, A_REVERSE);
3889 mvwprintw(menu_win, y, x, "%s", choices[i]);
3890 wattroff(menu_win, A_REVERSE);
3893 mvwprintw(menu_win, y, x, "%s", choices[i]);
3899 /* Report the choice according to mouse position */
3900 void report_choice(int mouse_x, int mouse_y, int *p_choice)
3906 for(choice = 0; choice < n_choices; ++choice)
3907 if(mouse_y == j + choice && mouse_x >= i && mouse_x <= i + strlen(choices[choice]))
3908 { if(choice == n_choices - 1)
3911 *p_choice = choice + 1;
3923 NAME="MISCMOUSEFUNCS"
3924 >12.4. Miscellaneous Functions</A
3927 >The functions mouse_trafo() and wmouse_trafo() can be used to convert to mouse
3928 co-ordinates to screen relative co-ordinates. See curs_mouse(3X) man page for details.</P
3930 >The mouseinterval function sets the maximum time (in thousands of a
3931 second) that can elapse between press and release events in order for
3932 them to be recognized as a click. This function returns the previous
3933 interval value. The default is one fifth of a second.</P
3942 >13. Screen Manipulation</A
3945 >In this section, we will look into some functions, which allow us to manage the
3946 screen efficiently and to write some fancy programs. This is especially
3947 important in writing games. </P
3954 >13.1. getyx() functions</A
3957 > The function <TT
3960 > can be used to find out
3961 the present cursor co-ordinates. It will fill the values of x and y co-ordinates
3962 in the arguments given to it. Since getyx() is a macro you don't have to pass
3963 the address of the variables. It can be called as</P
3965 CLASS="PROGRAMLISTING"
3967 /* win: window pointer
3968 * y, x: y, x co-ordinates will be put into this variables
3971 >The function getparyx() gets the beginning co-ordinates of the sub window
3972 relative to the main window. This is some times useful to update a sub window.
3973 When designing fancy stuff like writing multiple menus, it becomes difficult to
3974 store the menu positions, their first option co-ordinates etc. A simple solution
3975 to this problem, is to create menus in sub windows and later find the starting
3976 co-ordinates of the menus by using getparyx().</P
3978 >The functions getbegyx() and getmaxyx() store current window's beginning and
3979 maximum co-ordinates. These functions are useful in the same way as above in
3980 managing the windows and sub windows effectively.</P
3988 >13.2. Screen Dumping</A
3991 >While writing games, some times it becomes necessary to store the state of the
3992 screen and restore it back to the same state. The function scr_dump() can be
3993 used to dump the screen contents to a file given as an argument. Later it can be
3994 restored by scr_restore function. These two simple functions can be used
3995 effectively to maintain a fast moving game with changing scenarios. </P
4003 >13.3. Window Dumping</A
4006 >To store and restore windows, the functions
4017 the present window state into a file, which can be later restored by
4027 > can be used to copy a
4028 window completely onto another window. It takes the source and destination
4029 windows as parameters and according to the rectangle specified, it copies the
4030 rectangular region from source to destination window. It's last parameter
4031 specifies whether to overwrite or just overlay the contents on to the
4032 destination window. If this argument is true, then the copying is
4042 >14. Miscellaneous features</A
4045 >Now you know enough features to write a good curses program, with all bells and
4046 whistles. There are some miscellaneous functions which are useful in various
4047 cases. Let's go headlong into some of those.</P
4054 >14.1. curs_set()</A
4057 >This function can be used to make the cursor invisible. The parameter to this
4058 function should be </P
4060 CLASS="PROGRAMLISTING"
4063 2 : very visible.</PRE
4071 >14.2. Temporarily Leaving Curses mode</A
4074 >Some times you may want to get back to cooked mode (normal line buffering mode)
4075 temporarily. In such a case you will first need to save the tty modes with a
4078 >def_prog_mode()</TT
4083 > to end the curses mode. This will
4084 leave you in the original tty mode. To get back to curses once you are done,
4087 >reset_prog_mode() </TT
4088 >. This function returns
4089 the tty to the state stored by <TT
4091 >def_prog_mode()</TT
4092 >. Then do refresh(), and you are back to the curses mode. Here
4093 is an example showing the sequence of things to be done.</P
4101 >Example 12. Temporarily Leaving Curses Mode </B
4104 CLASS="PROGRAMLISTING"
4106 CLASS="INLINEMEDIAOBJECT"
4107 >#include <ncurses.h>
4111 initscr(); /* Start curses mode */
4112 printw("Hello World !!!\n"); /* Print Hello World */
4113 refresh(); /* Print it on to the real screen */
4114 def_prog_mode(); /* Save the tty modes */
4115 endwin(); /* End curses mode temporarily */
4116 system("/bin/sh"); /* Do whatever you like in cooked mode */
4117 reset_prog_mode(); /* Return to the previous tty mode*/
4118 /* stored by def_prog_mode() */
4119 refresh(); /* Do refresh() to restore the */
4120 /* Screen contents */
4121 printw("Another String\n"); /* Back to curses use the full */
4122 refresh(); /* capabilities of curses */
4123 endwin(); /* End curses mode */
4136 >14.3. ACS_ variables</A
4139 >If you have ever programmed in DOS, you know about those nifty characters in
4140 extended character set. They are printable only on some terminals. NCURSES
4144 > use these characters. All
4145 these variables start with ACS meaning alternative character set. You might have
4146 noticed me using these characters in some of the programs above. Here's an example
4147 showing all the characters.</P
4155 >Example 13. ACS Variables Example </B
4158 CLASS="PROGRAMLISTING"
4160 CLASS="INLINEMEDIAOBJECT"
4161 >#include <ncurses.h>
4167 printw("Upper left corner "); addch(ACS_ULCORNER); printw("\n");
4168 printw("Lower left corner "); addch(ACS_LLCORNER); printw("\n");
4169 printw("Lower right corner "); addch(ACS_LRCORNER); printw("\n");
4170 printw("Tee pointing right "); addch(ACS_LTEE); printw("\n");
4171 printw("Tee pointing left "); addch(ACS_RTEE); printw("\n");
4172 printw("Tee pointing up "); addch(ACS_BTEE); printw("\n");
4173 printw("Tee pointing down "); addch(ACS_TTEE); printw("\n");
4174 printw("Horizontal line "); addch(ACS_HLINE); printw("\n");
4175 printw("Vertical line "); addch(ACS_VLINE); printw("\n");
4176 printw("Large Plus or cross over "); addch(ACS_PLUS); printw("\n");
4177 printw("Scan Line 1 "); addch(ACS_S1); printw("\n");
4178 printw("Scan Line 3 "); addch(ACS_S3); printw("\n");
4179 printw("Scan Line 7 "); addch(ACS_S7); printw("\n");
4180 printw("Scan Line 9 "); addch(ACS_S9); printw("\n");
4181 printw("Diamond "); addch(ACS_DIAMOND); printw("\n");
4182 printw("Checker board (stipple) "); addch(ACS_CKBOARD); printw("\n");
4183 printw("Degree Symbol "); addch(ACS_DEGREE); printw("\n");
4184 printw("Plus/Minus Symbol "); addch(ACS_PLMINUS); printw("\n");
4185 printw("Bullet "); addch(ACS_BULLET); printw("\n");
4186 printw("Arrow Pointing Left "); addch(ACS_LARROW); printw("\n");
4187 printw("Arrow Pointing Right "); addch(ACS_RARROW); printw("\n");
4188 printw("Arrow Pointing Down "); addch(ACS_DARROW); printw("\n");
4189 printw("Arrow Pointing Up "); addch(ACS_UARROW); printw("\n");
4190 printw("Board of squares "); addch(ACS_BOARD); printw("\n");
4191 printw("Lantern Symbol "); addch(ACS_LANTERN); printw("\n");
4192 printw("Solid Square Block "); addch(ACS_BLOCK); printw("\n");
4193 printw("Less/Equal sign "); addch(ACS_LEQUAL); printw("\n");
4194 printw("Greater/Equal sign "); addch(ACS_GEQUAL); printw("\n");
4195 printw("Pi "); addch(ACS_PI); printw("\n");
4196 printw("Not equal "); addch(ACS_NEQUAL); printw("\n");
4197 printw("UK pound sign "); addch(ACS_STERLING); printw("\n");
4215 >15. Other libraries</A
4218 >Apart from the curses library, there are few text mode libraries, which provide
4219 more functionality and a lot of features. The following sections explain three
4220 standard libraries which are usually distributed along with curses. </P
4228 >16. Panel Library</A
4231 >Now that you are proficient in curses, you wanted to do some thing big. You
4232 created a lot of overlapping windows to give a professional windows-type look.
4233 Unfortunately, it soon becomes difficult to manage these. The multiple
4234 refreshes, updates plunge you into a nightmare. The overlapping windows create
4235 blotches, whenever you forget to refresh the windows in the proper order. </P
4237 >Don't despair. There's an elegant solution provided in panels library. In the
4238 words of developers of ncurses </P
4244 >When your interface design is such that windows may dive deeper into the
4245 visibility stack or pop to the top at runtime, the resulting book-keeping can be
4246 tedious and difficult to get right. Hence the panels library.</I
4250 >If you have lot of overlapping windows, then panels library is the way to go. It
4251 obviates the need of doing series of wnoutrefresh(), doupdate() and relieves the
4252 burden of doing it correctly(bottom up). The library maintains information about
4253 the order of windows, their overlapping and update the screen properly. So why
4254 wait? Let's take a close peek into panels.</P
4261 >16.1. The Basics</A
4264 >Panel object is a window that is implicitly treated as part of a deck including
4265 all other panel objects. The deck is treated as a stack with the top panel being
4266 completely visible and the other panels may or may not be obscured according to
4267 their positions. So the basic idea is to create a stack of overlapping panels
4268 and use panels library to display them correctly. There is a function similar to
4269 refresh() which, when called , displays panels in the correct order. Functions
4270 are provided to hide or show panels, move panels, change its size etc.. The
4271 overlapping problem is managed by the panels library during all the calls to
4272 these functions. </P
4274 >The general flow of a panel program goes like this:
4282 >Create the windows (with newwin()) to be attached to the panels.</P
4286 >Create panels with the chosen visibility order. Stack them up according to the
4287 desired visibility. The function new_panel() is used to created panels.</P
4291 >Call update_panels() to write the panels to the virtual screen in correct
4292 visibility order. Do a doupdate() to show it on the screen. </P
4296 >Mainpulate the panels with show_panel(), hide_panel(), move_panel() etc. Make
4297 use of helper functions like panel_hidden() and panel_window(). Make use of user
4298 pointer to store custom data for a panel. Use the functions set_panel_userptr()
4299 and panel_userptr() to set and get the user pointer for a panel.</P
4303 >When you are done with the panel use del_panel() to delete the panel.</P
4308 >Let's make the concepts clear, with some programs. The following is a simple
4309 program which creates 3 overlapping panels and shows them on the screen. </P
4316 NAME="COMPILEPANELS"
4317 >16.2. Compiling With the Panels Library</A
4320 >To use panels library functions, you have to include panel.h and to link the
4321 program with panels library the flag -lpanel should be added along with
4322 -lncurses in that order.</P
4324 CLASS="PROGRAMLISTING"
4325 > #include <panel.h>
4330 compile and link: gcc <program file> -lpanel -lncurses</PRE
4338 >Example 14. Panel basics</B
4341 CLASS="PROGRAMLISTING"
4343 CLASS="INLINEMEDIAOBJECT"
4344 >#include <panel.h>
4347 { WINDOW *my_wins[3];
4348 PANEL *my_panels[3];
4349 int lines = 10, cols = 40, y = 2, x = 4, i;
4355 /* Create windows for the panels */
4356 my_wins[0] = newwin(lines, cols, y, x);
4357 my_wins[1] = newwin(lines, cols, y + 1, x + 5);
4358 my_wins[2] = newwin(lines, cols, y + 2, x + 10);
4361 * Create borders around the windows so that you can see the effect
4364 for(i = 0; i < 3; ++i)
4365 box(my_wins[i], 0, 0);
4367 /* Attach a panel to each window */ /* Order is bottom up */
4368 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
4369 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
4370 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
4372 /* Update the stacking order. 2nd panel will be on top */
4375 /* Show it on the screen */
4385 >As you can see, above program follows a simple flow as explained. The windows
4386 are created with newwin() and then they are attached to panels with new_panel().
4387 As we attach one panel after another, the stack of panels gets updated. To put
4388 them on screen update_panels() and doupdate() are called.</P
4395 NAME="PANELBROWSING"
4396 >16.3. Panel Window Browsing</A
4399 >A slightly complicated example is given below. This program creates 3
4400 windows which can be cycled through using tab. Have a look at the code.</P
4408 >Example 15. Panel Window Browsing Example </B
4411 CLASS="PROGRAMLISTING"
4413 CLASS="INLINEMEDIAOBJECT"
4414 >#include <panel.h>
4419 void init_wins(WINDOW **wins, int n);
4420 void win_show(WINDOW *win, char *label, int label_color);
4421 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
4424 { WINDOW *my_wins[3];
4425 PANEL *my_panels[3];
4429 /* Initialize curses */
4434 keypad(stdscr, TRUE);
4436 /* Initialize all the colors */
4437 init_pair(1, COLOR_RED, COLOR_BLACK);
4438 init_pair(2, COLOR_GREEN, COLOR_BLACK);
4439 init_pair(3, COLOR_BLUE, COLOR_BLACK);
4440 init_pair(4, COLOR_CYAN, COLOR_BLACK);
4442 init_wins(my_wins, 3);
4444 /* Attach a panel to each window */ /* Order is bottom up */
4445 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
4446 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
4447 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
4449 /* Set up the user pointers to the next panel */
4450 set_panel_userptr(my_panels[0], my_panels[1]);
4451 set_panel_userptr(my_panels[1], my_panels[2]);
4452 set_panel_userptr(my_panels[2], my_panels[0]);
4454 /* Update the stacking order. 2nd panel will be on top */
4457 /* Show it on the screen */
4458 attron(COLOR_PAIR(4));
4459 mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)");
4460 attroff(COLOR_PAIR(4));
4464 while((ch = getch()) != KEY_F(1))
4467 top = (PANEL *)panel_userptr(top);
4478 /* Put all the windows */
4479 void init_wins(WINDOW **wins, int n)
4485 for(i = 0; i < n; ++i)
4486 { wins[i] = newwin(NLINES, NCOLS, y, x);
4487 sprintf(label, "Window Number %d", i + 1);
4488 win_show(wins[i], label, i + 1);
4494 /* Show the window with a border and a label */
4495 void win_show(WINDOW *win, char *label, int label_color)
4496 { int startx, starty, height, width;
4498 getbegyx(win, starty, startx);
4499 getmaxyx(win, height, width);
4502 mvwaddch(win, 2, 0, ACS_LTEE);
4503 mvwhline(win, 2, 1, ACS_HLINE, width - 2);
4504 mvwaddch(win, 2, width - 1, ACS_RTEE);
4506 print_in_middle(win, 1, 0, width, label, COLOR_PAIR(label_color));
4509 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
4523 length = strlen(string);
4524 temp = (width - length)/ 2;
4525 x = startx + (int)temp;
4526 wattron(win, color);
4527 mvwprintw(win, y, x, "%s", string);
4528 wattroff(win, color);
4540 >16.4. Using User Pointers</A
4543 >In the above example I used user pointers to find out the next window in the
4544 cycle. We can attach custom information to the panel by specifying a user
4545 pointer, which can point to any information you want to store. In this case I
4546 stored the pointer to the next panel in the cycle. User pointer for a panel can
4547 be set with the function <TT
4549 > set_panel_userptr()</TT
4551 It can be accessed using the function <TT
4553 >panel_userptr()</TT
4554 > which will return the user pointer for the panel given as
4555 argument. After finding the next panel in the cycle It's brought to the top by
4556 the function top_panel(). This function brings the panel given as argument to
4557 the top of the panel stack. </P
4564 NAME="PANELMOVERESIZE"
4565 >16.5. Moving and Resizing Panels</A
4571 > can be used to move a
4572 panel to the desired location. It does not change the position of the panel in
4573 the stack. Make sure that you use move_panel() instead mvwin() on the window
4574 associated with the panel.</P
4576 >Resizing a panel is slightly complex. There is no straight forward function
4577 just to resize the window associated with a panel. A solution to resize a panel
4578 is to create a new window with the desired sizes, change the window associated
4579 with the panel using replace_panel(). Don't forget to delete the old window. The
4580 window associated with a panel can be found by using the function
4583 >The following program shows these concepts, in supposedly simple program. You
4584 can cycle through the window with <TAB> as usual. To resize or move the
4585 active panel press 'r' for resize 'm' for moving. Then use arrow keys to resize
4586 or move it to the desired way and press enter to end your resizing or moving.
4587 This example makes use of user data to get the required data to do the
4596 >Example 16. Panel Moving and Resizing example </B
4599 CLASS="PROGRAMLISTING"
4601 CLASS="INLINEMEDIAOBJECT"
4602 >#include <panel.h>
4604 typedef struct _PANEL_DATA {
4614 void init_wins(WINDOW **wins, int n);
4615 void win_show(WINDOW *win, char *label, int label_color);
4616 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
4617 void set_user_ptrs(PANEL **panels, int n);
4620 { WINDOW *my_wins[3];
4621 PANEL *my_panels[3];
4624 WINDOW *temp_win, *old_win;
4626 int newx, newy, neww, newh;
4627 int size = FALSE, move = FALSE;
4629 /* Initialize curses */
4634 keypad(stdscr, TRUE);
4636 /* Initialize all the colors */
4637 init_pair(1, COLOR_RED, COLOR_BLACK);
4638 init_pair(2, COLOR_GREEN, COLOR_BLACK);
4639 init_pair(3, COLOR_BLUE, COLOR_BLACK);
4640 init_pair(4, COLOR_CYAN, COLOR_BLACK);
4642 init_wins(my_wins, 3);
4644 /* Attach a panel to each window */ /* Order is bottom up */
4645 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
4646 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
4647 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
4649 set_user_ptrs(my_panels, 3);
4650 /* Update the stacking order. 2nd panel will be on top */
4653 /* Show it on the screen */
4654 attron(COLOR_PAIR(4));
4655 mvprintw(LINES - 3, 0, "Use 'm' for moving, 'r' for resizing");
4656 mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)");
4657 attroff(COLOR_PAIR(4));
4660 stack_top = my_panels[2];
4661 top = (PANEL_DATA *)panel_userptr(stack_top);
4666 while((ch = getch()) != KEY_F(1))
4669 top = (PANEL_DATA *)panel_userptr(stack_top);
4670 top_panel(top->next);
4671 stack_top = top->next;
4672 top = (PANEL_DATA *)panel_userptr(stack_top);
4678 case 'r': /* Re-Size*/
4680 attron(COLOR_PAIR(4));
4681 mvprintw(LINES - 4, 0, "Entered Resizing :Use Arrow Keys to resize and press <ENTER> to end resizing");
4683 attroff(COLOR_PAIR(4));
4685 case 'm': /* Move */
4686 attron(COLOR_PAIR(4));
4687 mvprintw(LINES - 4, 0, "Entered Moving: Use Arrow Keys to Move and press <ENTER> to end moving");
4689 attroff(COLOR_PAIR(4));
4724 case 10: /* Enter */
4729 { old_win = panel_window(stack_top);
4730 temp_win = newwin(newh, neww, newy, newx);
4731 replace_panel(stack_top, temp_win);
4732 win_show(temp_win, top->label, top->label_color);
4737 { move_panel(stack_top, newy, newx);
4743 attron(COLOR_PAIR(4));
4744 mvprintw(LINES - 3, 0, "Use 'm' for moving, 'r' for resizing");
4745 mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)");
4746 attroff(COLOR_PAIR(4));
4755 /* Put all the windows */
4756 void init_wins(WINDOW **wins, int n)
4762 for(i = 0; i < n; ++i)
4763 { wins[i] = newwin(NLINES, NCOLS, y, x);
4764 sprintf(label, "Window Number %d", i + 1);
4765 win_show(wins[i], label, i + 1);
4771 /* Set the PANEL_DATA structures for individual panels */
4772 void set_user_ptrs(PANEL **panels, int n)
4778 ptrs = (PANEL_DATA *)calloc(n, sizeof(PANEL_DATA));
4780 for(i = 0;i < n; ++i)
4781 { win = panel_window(panels[i]);
4782 getbegyx(win, y, x);
4783 getmaxyx(win, h, w);
4788 sprintf(temp, "Window Number %d", i + 1);
4789 strcpy(ptrs[i].label, temp);
4790 ptrs[i].label_color = i + 1;
4792 ptrs[i].next = panels[0];
4794 ptrs[i].next = panels[i + 1];
4795 set_panel_userptr(panels[i], &ptrs[i]);
4799 /* Show the window with a border and a label */
4800 void win_show(WINDOW *win, char *label, int label_color)
4801 { int startx, starty, height, width;
4803 getbegyx(win, starty, startx);
4804 getmaxyx(win, height, width);
4807 mvwaddch(win, 2, 0, ACS_LTEE);
4808 mvwhline(win, 2, 1, ACS_HLINE, width - 2);
4809 mvwaddch(win, 2, width - 1, ACS_RTEE);
4811 print_in_middle(win, 1, 0, width, label, COLOR_PAIR(label_color));
4814 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
4828 length = strlen(string);
4829 temp = (width - length)/ 2;
4830 x = startx + (int)temp;
4831 wattron(win, color);
4832 mvwprintw(win, y, x, "%s", string);
4833 wattroff(win, color);
4839 >Concentrate on the main while loop. Once it finds out the type of key pressed,
4840 it takes appropriate action. If 'r' is pressed resizing mode is started. After
4841 this the new sizes are updated as the user presses the arrow keys. When the user
4842 presses <ENTER> present selection ends and panel is resized by using the
4843 concept explained. While in resizing mode the program doesn't show how the
4844 window is getting resized. It's left as an exercise to the reader to print a
4845 dotted border while it gets resized to a new position. </P
4847 >When the user presses 'm' the move mode starts. This is a bit simpler than
4848 resizing. As the arrow keys are pressed the new position is updated and
4849 pressing of <ENTER> causes the panel to be moved by calling the function
4852 >In this program the user data which is represented as PANEL_DATA, plays very
4853 important role in finding the associated information with a panel. As written in
4854 the comments, the PANEL_DATA stores the panel sizes, label, label color and a
4855 pointer to the next panel in the cycle.</P
4862 NAME="PANELSHOWHIDE"
4863 >16.6. Hiding and Showing Panels</A
4866 >A Panel can be hidden by using the function hide_panel(). This function merely
4867 removes it form the stack of panels, thus hiding it on the screen once you do
4868 update_panels() and doupdate(). It doesn't destroy the PANEL structure
4869 associated with the hidden panel. It can be shown again by using the
4870 show_panel() function.</P
4872 >The following program shows the hiding of panels. Press 'a' or 'b' or 'c' to
4873 show or hide first, second and third windows respectively. It uses a user data
4874 with a small variable hide, which keeps track of whether the window is hidden or
4875 not. For some reason the function
4879 > which tells whether a panel is
4880 hidden or not is not working. A bug report was also presented by Michael Andres
4882 HREF="http://www.geocrawler.com/archives/3/344/1999/9/0/2643549/"
4893 >Example 17. Panel Hiding and Showing example </B
4896 CLASS="PROGRAMLISTING"
4898 CLASS="INLINEMEDIAOBJECT"
4899 >#include <panel.h>
4901 typedef struct _PANEL_DATA {
4902 int hide; /* TRUE if panel is hidden */
4908 void init_wins(WINDOW **wins, int n);
4909 void win_show(WINDOW *win, char *label, int label_color);
4910 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
4913 { WINDOW *my_wins[3];
4914 PANEL *my_panels[3];
4915 PANEL_DATA panel_datas[3];
4919 /* Initialize curses */
4924 keypad(stdscr, TRUE);
4926 /* Initialize all the colors */
4927 init_pair(1, COLOR_RED, COLOR_BLACK);
4928 init_pair(2, COLOR_GREEN, COLOR_BLACK);
4929 init_pair(3, COLOR_BLUE, COLOR_BLACK);
4930 init_pair(4, COLOR_CYAN, COLOR_BLACK);
4932 init_wins(my_wins, 3);
4934 /* Attach a panel to each window */ /* Order is bottom up */
4935 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
4936 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
4937 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
4939 /* Initialize panel datas saying that nothing is hidden */
4940 panel_datas[0].hide = FALSE;
4941 panel_datas[1].hide = FALSE;
4942 panel_datas[2].hide = FALSE;
4944 set_panel_userptr(my_panels[0], &panel_datas[0]);
4945 set_panel_userptr(my_panels[1], &panel_datas[1]);
4946 set_panel_userptr(my_panels[2], &panel_datas[2]);
4948 /* Update the stacking order. 2nd panel will be on top */
4951 /* Show it on the screen */
4952 attron(COLOR_PAIR(4));
4953 mvprintw(LINES - 3, 0, "Show or Hide a window with 'a'(first window) 'b'(Second Window) 'c'(Third Window)");
4954 mvprintw(LINES - 2, 0, "F1 to Exit");
4956 attroff(COLOR_PAIR(4));
4959 while((ch = getch()) != KEY_F(1))
4962 temp = (PANEL_DATA *)panel_userptr(my_panels[0]);
4963 if(temp->hide == FALSE)
4964 { hide_panel(my_panels[0]);
4965 temp->hide = TRUE;
4968 { show_panel(my_panels[0]);
4969 temp->hide = FALSE;
4973 temp = (PANEL_DATA *)panel_userptr(my_panels[1]);
4974 if(temp->hide == FALSE)
4975 { hide_panel(my_panels[1]);
4976 temp->hide = TRUE;
4979 { show_panel(my_panels[1]);
4980 temp->hide = FALSE;
4984 temp = (PANEL_DATA *)panel_userptr(my_panels[2]);
4985 if(temp->hide == FALSE)
4986 { hide_panel(my_panels[2]);
4987 temp->hide = TRUE;
4990 { show_panel(my_panels[2]);
4991 temp->hide = FALSE;
5002 /* Put all the windows */
5003 void init_wins(WINDOW **wins, int n)
5009 for(i = 0; i < n; ++i)
5010 { wins[i] = newwin(NLINES, NCOLS, y, x);
5011 sprintf(label, "Window Number %d", i + 1);
5012 win_show(wins[i], label, i + 1);
5018 /* Show the window with a border and a label */
5019 void win_show(WINDOW *win, char *label, int label_color)
5020 { int startx, starty, height, width;
5022 getbegyx(win, starty, startx);
5023 getmaxyx(win, height, width);
5026 mvwaddch(win, 2, 0, ACS_LTEE);
5027 mvwhline(win, 2, 1, ACS_HLINE, width - 2);
5028 mvwaddch(win, 2, width - 1, ACS_RTEE);
5030 print_in_middle(win, 1, 0, width, label, COLOR_PAIR(label_color));
5033 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
5047 length = strlen(string);
5048 temp = (width - length)/ 2;
5049 x = startx + (int)temp;
5050 wattron(win, color);
5051 mvwprintw(win, y, x, "%s", string);
5052 wattroff(win, color);
5064 >16.7. panel_above() and panel_below() Functions</A
5074 > can be used to find out the panel
5075 above and below a panel. If the argument to these functions is NULL, then they
5076 return a pointer to bottom panel and top panel respectively.</P
5085 >17. Menus Library</A
5088 >The menus library provides a nice extension to basic curses, through which you
5089 can create menus. It provides a set of functions to create menus. But they have
5090 to be customized to give a nicer look, with colors etc. Let's get into the
5093 >A menu is a screen display that assists the user to choose some subset of a
5094 given set of items. To put it simple, a menu is a collection of items from which
5095 one or more items can be chosen. Some readers might not be aware of multiple
5096 item selection capability. Menu library provides functionality to write menus
5097 from which the user can chose more than one item as the preferred choice. This
5098 is dealt with in a later section. Now it is time for some rudiments.</P
5105 >17.1. The Basics</A
5108 >To create menus, you first create items, and then post the menu to the display.
5109 After that, all the processing of user responses is done in an elegant function
5110 menu_driver() which is the work horse of any menu program. </P
5112 >The general flow of control of a menu program looks like this.
5119 >Initialize curses</P
5123 >Create items using new_item(). You can specify a name and description for the
5128 >Create the menu with new_menu() by specifying the items to be attached with.</P
5132 >Post the menu with menu_post() and refresh the screen.</P
5136 >Process the user requests with a loop and do necessary updates to menu with
5141 >Unpost the menu with menu_unpost()</P
5145 >Free the memory allocated to menu by free_menu()</P
5149 >Free the memory allocated to the items with free_item() </P
5158 >Let's see a program which prints a simple menu and updates the current selection
5159 with up, down arrows. </P
5167 >17.2. Compiling With the Menu Library</A
5170 >To use menu library functions, you have to include menu.h and to link the
5171 program with menu library the flag -lmenu should be added along with -lncurses
5174 CLASS="PROGRAMLISTING"
5175 > #include <menu.h>
5180 compile and link: gcc <program file> -lmenu -lncurses</PRE
5188 >Example 18. Menu Basics </B
5191 CLASS="PROGRAMLISTING"
5193 CLASS="INLINEMEDIAOBJECT"
5194 >#include <curses.h>
5195 #include <menu.h>
5197 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
5219 keypad(stdscr, TRUE);
5221 n_choices = ARRAY_SIZE(choices);
5222 my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));
5224 for(i = 0; i < n_choices; ++i)
5225 my_items[i] = new_item(choices[i], choices[i]);
5226 my_items[n_choices] = (ITEM *)NULL;
5228 my_menu = new_menu((ITEM **)my_items);
5229 mvprintw(LINES - 2, 0, "F1 to Exit");
5233 while((c = getch()) != KEY_F(1))
5236 menu_driver(my_menu, REQ_DOWN_ITEM);
5239 menu_driver(my_menu, REQ_UP_ITEM);
5244 free_item(my_items[0]);
5245 free_item(my_items[1]);
5253 >This program demonstrates the basic concepts involved in creating a menu using
5254 menus library. First we create the items using new_item() and then attach them
5255 to the menu with new_menu() function. After posting the menu and refreshing the
5256 screen, the main processing loop starts. It reads user input and takes
5257 corresponding action. The function menu_driver() is the main work horse of the
5258 menu system. The second parameter to this function tells what's to be done with
5259 the menu. According to the parameter, menu_driver() does the corresponding task.
5260 The value can be either a menu navigational request, an ascii character, or a
5261 KEY_MOUSE special key associated with a mouse event.</P
5263 >The menu_driver accepts following navigational requests.
5265 CLASS="PROGRAMLISTING"
5266 > REQ_LEFT_ITEM Move left to an item.
5267 REQ_RIGHT_ITEM Move right to an item.
5268 REQ_UP_ITEM Move up to an item.
5269 REQ_DOWN_ITEM Move down to an item.
5270 REQ_SCR_ULINE Scroll up a line.
5271 REQ_SCR_DLINE Scroll down a line.
5272 REQ_SCR_DPAGE Scroll down a page.
5273 REQ_SCR_UPAGE Scroll up a page.
5274 REQ_FIRST_ITEM Move to the first item.
5275 REQ_LAST_ITEM Move to the last item.
5276 REQ_NEXT_ITEM Move to the next item.
5277 REQ_PREV_ITEM Move to the previous item.
5278 REQ_TOGGLE_ITEM Select/deselect an item.
5279 REQ_CLEAR_PATTERN Clear the menu pattern buffer.
5280 REQ_BACK_PATTERN Delete the previous character from the pattern buffer.
5281 REQ_NEXT_MATCH Move to the next item matching the pattern match.
5282 REQ_PREV_MATCH Move to the previous item matching the pattern match. </PRE
5285 >Don't get overwhelmed by the number of options. We will see them slowly one
5286 after another. The options of interest in this example are REQ_UP_ITEM and
5287 REQ_DOWN_ITEM. These two options when passed to menu_driver, menu driver
5288 updates the current item to one item up or down respectively.</P
5296 >17.3. Menu Driver: The work horse of the menu system</A
5299 >As you have seen in the above example, menu_driver plays an important role in
5300 updating the menu. It is very important to understand various options it takes
5301 and what they do. As explained above, the second parameter to menu_driver() can
5302 be either a navigational request, a printable character or a KEY_MOUSE key.
5303 Let's dissect the different navigational requests.</P
5313 >REQ_LEFT_ITEM and REQ_RIGHT_ITEM</I
5317 >A Menu can be displayed with multiple columns for more than one item. This can
5318 be done by using the <TT
5322 When a multi columnar menu is displayed these requests cause the menu driver to
5323 move the current selection to left or right.</P
5331 >REQ_UP_ITEM and REQ_DOWN_ITEM </I
5335 >These two options you have seen in the above example. These options when given,
5336 makes the menu_driver to move the current selection to an item up or down.</P
5344 >REQ_SCR_* options</I
5348 >The four options REQ_SCR_ULINE, REQ_SCR_DLINE, REQ_SCR_DPAGE, REQ_SCR_UPAGE are
5349 related to scrolling. If all the items in the menu cannot be displayed in the
5350 menu sub window, then the menu is scrollable. These requests can be given to the
5351 menu_driver to do the scrolling either one line up, down or one page down or up
5360 >REQ_FIRST_ITEM, REQ_LAST_ITEM, REQ_NEXT_ITEM and
5365 >These requests are self explanatory.</P
5377 >This request when given, toggles the present selection. This option is to be
5378 used only in a multi valued menu. So to use this request the option O_ONEVALUE
5379 must be off. This option can be made off or on with set_menu_opts().</P
5387 >Pattern Requests </I
5391 >Every menu has an associated pattern buffer, which is used to find the nearest
5392 match to the ascii characters entered by the user. Whenever ascii characters are
5393 given to menu_driver, it puts in to the pattern buffer. It also tries to find
5394 the nearest match to the pattern in the items list and moves current selection
5395 to that item. The request REQ_CLEAR_PATTERN clears the pattern buffer. The
5396 request REQ_BACK_PATTERN deletes the previous character in the pattern buffer.
5397 In case the pattern matches more than one item then the matched items can be
5398 cycled through REQ_NEXT_MATCH and REQ_PREV_MATCH which move the current
5399 selection to the next and previous matches respectively.</P
5411 >In case of KEY_MOUSE requests, according to the mouse position an action is
5412 taken accordingly. The action to be taken is explained in the man page as, </P
5414 CLASS="PROGRAMLISTING"
5419 > If the second argument is the KEY_MOUSE special key, the
5420 associated mouse event is translated into one of the above
5421 pre-defined requests. Currently only clicks in the user
5422 window (e.g. inside the menu display area or the decora­
5423 tion window) are handled. If you click above the display
5424 region of the menu, a REQ_SCR_ULINE is generated, if you
5425 doubleclick a REQ_SCR_UPAGE is generated and if you
5426 tripleclick a REQ_FIRST_ITEM is generated. If you click
5427 below the display region of the menu, a REQ_SCR_DLINE is
5428 generated, if you doubleclick a REQ_SCR_DPAGE is generated
5429 and if you tripleclick a REQ_LAST_ITEM is generated. If
5430 you click at an item inside the display area of the menu,
5431 the menu cursor is positioned to that item.</I
5437 >Each of the above requests will be explained in the following lines with several
5438 examples whenever appropriate.</P
5446 >17.4. Menu Windows</A
5449 >Every menu created is associated with a window and a sub window. The menu window
5450 displays any title or border associated with the menu. The menu sub window
5451 displays the menu items currently available for selection. But we didn't specify
5452 any window or sub window in the simple example. When a window is not specified,
5453 stdscr is taken as the main window, and then menu system calculates the sub
5454 window size required for the display of items. Then items are displayed in the
5455 calculated sub window. So let's play with these windows and display a menu with
5456 a border and a title.</P
5464 >Example 19. Menu Windows Usage example </B
5467 CLASS="PROGRAMLISTING"
5469 CLASS="INLINEMEDIAOBJECT"
5470 >#include <menu.h>
5472 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
5483 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
5489 WINDOW *my_menu_win;
5492 /* Initialize curses */
5497 keypad(stdscr, TRUE);
5498 init_pair(1, COLOR_RED, COLOR_BLACK);
5501 n_choices = ARRAY_SIZE(choices);
5502 my_items = (ITEM **)calloc(n_choices, sizeof(ITEM *));
5503 for(i = 0; i < n_choices; ++i)
5504 my_items[i] = new_item(choices[i], choices[i]);
5507 my_menu = new_menu((ITEM **)my_items);
5509 /* Create the window to be associated with the menu */
5510 my_menu_win = newwin(10, 40, 4, 4);
5511 keypad(my_menu_win, TRUE);
5513 /* Set main window and sub window */
5514 set_menu_win(my_menu, my_menu_win);
5515 set_menu_sub(my_menu, derwin(my_menu_win, 6, 38, 3, 1));
5517 /* Set menu mark to the string " * " */
5518 set_menu_mark(my_menu, " * ");
5520 /* Print a border around the main window and print a title */
5521 box(my_menu_win, 0, 0);
5522 print_in_middle(my_menu_win, 1, 0, 40, "My Menu", COLOR_PAIR(1));
5523 mvwaddch(my_menu_win, 2, 0, ACS_LTEE);
5524 mvwhline(my_menu_win, 2, 1, ACS_HLINE, 38);
5525 mvwaddch(my_menu_win, 2, 39, ACS_RTEE);
5526 mvprintw(LINES - 2, 0, "F1 to exit");
5531 wrefresh(my_menu_win);
5533 while((c = wgetch(my_menu_win)) != KEY_F(1))
5536 menu_driver(my_menu, REQ_DOWN_ITEM);
5539 menu_driver(my_menu, REQ_UP_ITEM);
5542 wrefresh(my_menu_win);
5545 /* Unpost and free all the memory taken up */
5546 unpost_menu(my_menu);
5548 for(i = 0; i < n_choices; ++i)
5549 free_item(my_items[i]);
5553 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
5567 length = strlen(string);
5568 temp = (width - length)/ 2;
5569 x = startx + (int)temp;
5570 wattron(win, color);
5571 mvwprintw(win, y, x, "%s", string);
5572 wattroff(win, color);
5578 >This example creates a menu with a title, border, a fancy line separating title
5579 and the items. As you can see, in order to attach a window to a menu the
5580 function set_menu_win() has to be used. Then we attach the sub window also. This
5581 displays the items in the sub window. You can also set the mark string which
5582 gets displayed to the left of the selected item with set_menu_mark().</P
5590 >17.5. Scrolling Menus</A
5593 >If the sub window given for a window is not big enough to show all the items,
5594 then the menu will be scrollable. When you are on the last item in the present
5595 list, if you send REQ_DOWN_ITEM, it gets translated into REQ_SCR_DLINE and the
5596 menu scrolls by one item. You can manually give REQ_SCR_ operations to do
5597 scrolling. Let's see how it can be done.</P
5605 >Example 20. Scrolling Menus example </B
5608 CLASS="PROGRAMLISTING"
5610 CLASS="INLINEMEDIAOBJECT"
5611 >#include <curses.h>
5612 #include <menu.h>
5614 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
5631 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
5637 WINDOW *my_menu_win;
5640 /* Initialize curses */
5645 keypad(stdscr, TRUE);
5646 init_pair(1, COLOR_RED, COLOR_BLACK);
5647 init_pair(2, COLOR_CYAN, COLOR_BLACK);
5650 n_choices = ARRAY_SIZE(choices);
5651 my_items = (ITEM **)calloc(n_choices, sizeof(ITEM *));
5652 for(i = 0; i < n_choices; ++i)
5653 my_items[i] = new_item(choices[i], choices[i]);
5656 my_menu = new_menu((ITEM **)my_items);
5658 /* Create the window to be associated with the menu */
5659 my_menu_win = newwin(10, 40, 4, 4);
5660 keypad(my_menu_win, TRUE);
5662 /* Set main window and sub window */
5663 set_menu_win(my_menu, my_menu_win);
5664 set_menu_sub(my_menu, derwin(my_menu_win, 6, 38, 3, 1));
5665 set_menu_format(my_menu, 5, 1);
5667 /* Set menu mark to the string " * " */
5668 set_menu_mark(my_menu, " * ");
5670 /* Print a border around the main window and print a title */
5671 box(my_menu_win, 0, 0);
5672 print_in_middle(my_menu_win, 1, 0, 40, "My Menu", COLOR_PAIR(1));
5673 mvwaddch(my_menu_win, 2, 0, ACS_LTEE);
5674 mvwhline(my_menu_win, 2, 1, ACS_HLINE, 38);
5675 mvwaddch(my_menu_win, 2, 39, ACS_RTEE);
5679 wrefresh(my_menu_win);
5681 attron(COLOR_PAIR(2));
5682 mvprintw(LINES - 2, 0, "Use PageUp and PageDown to scoll down or up a page of items");
5683 mvprintw(LINES - 1, 0, "Arrow Keys to navigate (F1 to Exit)");
5684 attroff(COLOR_PAIR(2));
5687 while((c = wgetch(my_menu_win)) != KEY_F(1))
5690 menu_driver(my_menu, REQ_DOWN_ITEM);
5693 menu_driver(my_menu, REQ_UP_ITEM);
5696 menu_driver(my_menu, REQ_SCR_DPAGE);
5699 menu_driver(my_menu, REQ_SCR_UPAGE);
5702 wrefresh(my_menu_win);
5705 /* Unpost and free all the memory taken up */
5706 unpost_menu(my_menu);
5708 for(i = 0; i < n_choices; ++i)
5709 free_item(my_items[i]);
5713 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
5727 length = strlen(string);
5728 temp = (width - length)/ 2;
5729 x = startx + (int)temp;
5730 wattron(win, color);
5731 mvwprintw(win, y, x, "%s", string);
5732 wattroff(win, color);
5738 >This program is self-explanatory. In this example the number of choices has been
5739 increased to ten, which is larger than our sub window size which can hold 6
5740 items. This message has to be explicitly conveyed to the menu system with the
5741 function set_menu_format(). In here we specify the number of rows and columns we
5742 want to be displayed for a single page. We can specify any number of items to be
5743 shown, in the rows variables, if it is less than the height of the sub window.
5744 If the key pressed by the user is a PAGE UP or PAGE DOWN, the menu is scrolled a
5745 page due to the requests (REQ_SCR_DPAGE and REQ_SCR_UPAGE) given to
5754 >17.6. Multi Columnar Menus</A
5757 >In the above example you have seen how to use the function set_menu_format(). I
5758 didn't mention what the cols variable (third parameter) does. Well, If your sub
5759 window is wide enough, you can opt to display more than one item per row. This
5760 can be specified in the cols variable. To make things simpler, the following
5761 example doesn't show descriptions for the items.</P
5769 >Example 21. Milt Columnar Menus Example </B
5772 CLASS="PROGRAMLISTING"
5774 CLASS="INLINEMEDIAOBJECT"
5775 >#include <curses.h>
5776 #include <menu.h>
5778 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
5782 "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Choice 5",
5783 "Choice 6", "Choice 7", "Choice 8", "Choice 9", "Choice 10",
5784 "Choice 11", "Choice 12", "Choice 13", "Choice 14", "Choice 15",
5785 "Choice 16", "Choice 17", "Choice 18", "Choice 19", "Choice 20",
5794 WINDOW *my_menu_win;
5797 /* Initialize curses */
5802 keypad(stdscr, TRUE);
5803 init_pair(1, COLOR_RED, COLOR_BLACK);
5804 init_pair(2, COLOR_CYAN, COLOR_BLACK);
5807 n_choices = ARRAY_SIZE(choices);
5808 my_items = (ITEM **)calloc(n_choices, sizeof(ITEM *));
5809 for(i = 0; i < n_choices; ++i)
5810 my_items[i] = new_item(choices[i], choices[i]);
5813 my_menu = new_menu((ITEM **)my_items);
5815 /* Set menu option not to show the description */
5816 menu_opts_off(my_menu, O_SHOWDESC);
5818 /* Create the window to be associated with the menu */
5819 my_menu_win = newwin(10, 70, 4, 4);
5820 keypad(my_menu_win, TRUE);
5822 /* Set main window and sub window */
5823 set_menu_win(my_menu, my_menu_win);
5824 set_menu_sub(my_menu, derwin(my_menu_win, 6, 68, 3, 1));
5825 set_menu_format(my_menu, 5, 3);
5826 set_menu_mark(my_menu, " * ");
5828 /* Print a border around the main window and print a title */
5829 box(my_menu_win, 0, 0);
5831 attron(COLOR_PAIR(2));
5832 mvprintw(LINES - 3, 0, "Use PageUp and PageDown to scroll");
5833 mvprintw(LINES - 2, 0, "Use Arrow Keys to navigate (F1 to Exit)");
5834 attroff(COLOR_PAIR(2));
5839 wrefresh(my_menu_win);
5841 while((c = wgetch(my_menu_win)) != KEY_F(1))
5844 menu_driver(my_menu, REQ_DOWN_ITEM);
5847 menu_driver(my_menu, REQ_UP_ITEM);
5850 menu_driver(my_menu, REQ_LEFT_ITEM);
5853 menu_driver(my_menu, REQ_RIGHT_ITEM);
5856 menu_driver(my_menu, REQ_SCR_DPAGE);
5859 menu_driver(my_menu, REQ_SCR_UPAGE);
5862 wrefresh(my_menu_win);
5865 /* Unpost and free all the memory taken up */
5866 unpost_menu(my_menu);
5868 for(i = 0; i < n_choices; ++i)
5869 free_item(my_items[i]);
5875 >Watch the function call to set_menu_format(). It specifies the number of columns
5876 to be 3, thus displaying 3 items per row. We have also switched off the showing
5877 descriptions with the function menu_opts_off(). There are couple of functions
5878 set_menu_opts(), menu_opts_on() and menu_opts() which can be used to manipulate
5879 menu options. The following menu options can be specified.</P
5881 CLASS="PROGRAMLISTING"
5883 Only one item can be selected for this menu.
5886 Display the item descriptions when the menu is
5890 Display the menu in row-major order.
5893 Ignore the case when pattern-matching.
5896 Move the cursor to within the item name while pat­
5900 Don't wrap around next-item and previous-item,
5901 requests to the other end of the menu.</PRE
5903 >All options are on by default. You can switch specific attributes on or off with
5904 menu_opts_on() and menu_opts_off() functions. You can also use set_menu_opts()
5905 to directly specify the options. The argument to this function should be a OR ed
5906 value of some of those above constants. The function menu_opts() can be used to
5907 find out a menu's present options. </P
5914 NAME="MULTIVALUEMENUS"
5915 >17.7. Multi Valued Menus</A
5918 >You might be wondering what if you switch off the option O_ONEVALUE. Then the
5919 menu becomes multi-valued. That means you can select more than one item. This
5920 brings us to the request REQ_TOGGLE_ITEM. Let's see it in action.</P
5928 >Example 22. Multi Valued Menus example </B
5931 CLASS="PROGRAMLISTING"
5933 CLASS="INLINEMEDIAOBJECT"
5934 >#include <curses.h>
5935 #include <menu.h>
5937 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
5958 /* Initialize curses */
5962 keypad(stdscr, TRUE);
5964 /* Initialize items */
5965 n_choices = ARRAY_SIZE(choices);
5966 my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));
5967 for(i = 0; i < n_choices; ++i)
5968 my_items[i] = new_item(choices[i], choices[i]);
5969 my_items[n_choices] = (ITEM *)NULL;
5971 my_menu = new_menu((ITEM **)my_items);
5973 /* Make the menu multi valued */
5974 menu_opts_off(my_menu, O_ONEVALUE);
5976 mvprintw(LINES - 3, 0, "Use <SPACE> to select or unselect an item.");
5977 mvprintw(LINES - 2, 0, "<ENTER> to see presently selected items(F1 to Exit)");
5981 while((c = getch()) != KEY_F(1))
5984 menu_driver(my_menu, REQ_DOWN_ITEM);
5987 menu_driver(my_menu, REQ_UP_ITEM);
5990 menu_driver(my_menu, REQ_TOGGLE_ITEM);
5992 case 10: /* Enter */
5996 items = menu_items(my_menu);
5998 for(i = 0; i < item_count(my_menu); ++i)
5999 if(item_value(items[i]) == TRUE)
6000 { strcat(temp, item_name(items[i]));
6005 mvprintw(20, 0, temp);
6012 free_item(my_items[0]);
6013 free_item(my_items[1]);
6021 >Whew, A lot of new functions. Let's take them one after another. Firstly, the
6022 REQ_TOGGLE_ITEM. In a multi-valued menu, the user should be allowed to select
6023 or un select more than one item. The request REQ_TOGGLE_ITEM toggles the present
6024 selection. In this case when space is pressed REQ_TOGGLE_ITEM request is sent to
6025 menu_driver to achieve the result.</P
6027 >Now when the user presses <ENTER> we show the items he presently selected.
6028 First we find out the items associated with the menu using the function
6029 menu_items(). Then we loop through the items to find out if the item is selected
6030 or not. The function item_value() returns TRUE if an item is selected. The
6031 function item_count() returns the number of items in the menu. The item name can
6032 be found with item_name(). You can also find the description associated with an
6033 item using item_description().</P
6041 >17.8. Menu Options</A
6044 >Well, by this time you must be itching for some difference in your menu, with
6045 lots of functionality. I know. You want Colors !!!. You want to create nice
6046 menus similar to those text mode <A
6047 HREF="http://www.jersey.net/~debinjoe/games/"
6051 set_menu_fore() and set_menu_back() can be used to change the attribute of the
6052 selected item and unselected item. The names are misleading. They don't change
6053 menu's foreground or background which would have been useless. </P
6055 >The function set_menu_grey() can be used to set the display attribute for the
6056 non-selectable items in the menu. This brings us to the interesting option for
6057 an item the one and only O_SELECTABLE. We can turn it off by the function
6058 item_opts_off() and after that that item is not selectable. It's like a grayed
6059 item in those fancy windows menus. Let's put these concepts in practice with
6068 >Example 23. Menu Options example </B
6071 CLASS="PROGRAMLISTING"
6073 CLASS="INLINEMEDIAOBJECT"
6074 >#include <menu.h>
6076 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
6097 /* Initialize curses */
6102 keypad(stdscr, TRUE);
6103 init_pair(1, COLOR_RED, COLOR_BLACK);
6104 init_pair(2, COLOR_GREEN, COLOR_BLACK);
6105 init_pair(3, COLOR_MAGENTA, COLOR_BLACK);
6107 /* Initialize items */
6108 n_choices = ARRAY_SIZE(choices);
6109 my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));
6110 for(i = 0; i < n_choices; ++i)
6111 my_items[i] = new_item(choices[i], choices[i]);
6112 my_items[n_choices] = (ITEM *)NULL;
6113 item_opts_off(my_items[3], O_SELECTABLE);
6114 item_opts_off(my_items[6], O_SELECTABLE);
6117 my_menu = new_menu((ITEM **)my_items);
6119 /* Set fore ground and back ground of the menu */
6120 set_menu_fore(my_menu, COLOR_PAIR(1) | A_REVERSE);
6121 set_menu_back(my_menu, COLOR_PAIR(2));
6122 set_menu_grey(my_menu, COLOR_PAIR(3));
6125 mvprintw(LINES - 3, 0, "Press <ENTER> to see the option selected");
6126 mvprintw(LINES - 2, 0, "Up and Down arrow keys to naviage (F1 to Exit)");
6130 while((c = getch()) != KEY_F(1))
6133 menu_driver(my_menu, REQ_DOWN_ITEM);
6136 menu_driver(my_menu, REQ_UP_ITEM);
6138 case 10: /* Enter */
6141 mvprintw(20, 0, "Item selected is : %s",
6142 item_name(current_item(my_menu)));
6143 pos_menu_cursor(my_menu);
6147 unpost_menu(my_menu);
6148 for(i = 0; i < n_choices; ++i)
6149 free_item(my_items[i]);
6163 >17.9. The useful User Pointer</A
6166 >We can associate a user pointer with each item in the menu. It works the same
6167 way as user pointer in panels. It's not touched by menu system. You can store
6168 any thing you like in that. I usually use it to store the function to be
6169 executed when the menu option is chosen (It's selected and may be the user
6170 pressed <ENTER>);</P
6178 >Example 24. Menu User Pointer Usage </B
6181 CLASS="PROGRAMLISTING"
6183 CLASS="INLINEMEDIAOBJECT"
6184 >#include <curses.h>
6185 #include <menu.h>
6187 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
6200 void func(char *name);
6209 /* Initialize curses */
6214 keypad(stdscr, TRUE);
6215 init_pair(1, COLOR_RED, COLOR_BLACK);
6216 init_pair(2, COLOR_GREEN, COLOR_BLACK);
6217 init_pair(3, COLOR_MAGENTA, COLOR_BLACK);
6219 /* Initialize items */
6220 n_choices = ARRAY_SIZE(choices);
6221 my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *));
6222 for(i = 0; i < n_choices; ++i)
6223 { my_items[i] = new_item(choices[i], choices[i]);
6224 /* Set the user pointer */
6225 set_item_userptr(my_items[i], func);
6227 my_items[n_choices] = (ITEM *)NULL;
6230 my_menu = new_menu((ITEM **)my_items);
6233 mvprintw(LINES - 3, 0, "Press <ENTER> to see the option selected");
6234 mvprintw(LINES - 2, 0, "Up and Down arrow keys to naviage (F1 to Exit)");
6238 while((c = getch()) != KEY_F(1))
6241 menu_driver(my_menu, REQ_DOWN_ITEM);
6244 menu_driver(my_menu, REQ_UP_ITEM);
6246 case 10: /* Enter */
6250 cur = current_item(my_menu);
6251 p = item_userptr(cur);
6252 p((char *)item_name(cur));
6253 pos_menu_cursor(my_menu);
6259 unpost_menu(my_menu);
6260 for(i = 0; i < n_choices; ++i)
6261 free_item(my_items[i]);
6266 void func(char *name)
6269 mvprintw(20, 0, "Item selected is : %s", name);
6281 >18. Forms Library</A
6284 >Well. If you have seen those forms on web pages which take input from users and
6285 do various kinds of things, you might be wondering how would any one create such
6286 forms in text mode display. It's quite difficult to write those nifty forms in
6287 plain ncurses. Forms library tries to provide a basic frame work to build and
6288 maintain forms with ease. It has lot of features(functions) which manage
6289 validation, dynamic expansion of fields etc.. Let's see it in full flow.</P
6291 >A form is a collection of fields; each field can be either a label(static text)
6292 or a data-entry location. The forms also library provides functions to divide
6293 forms into multiple pages. </P
6300 >18.1. The Basics</A
6303 >Forms are created in much the same way as menus. First the fields related to the
6304 form are created with new_field(). You can set options for the fields, so that
6305 they can be displayed with some fancy attributes, validated before the field
6306 looses focus etc.. Then the fields are attached to form. After this, the form
6307 can be posted to display and is ready to receive inputs. On the similar lines to
6308 menu_driver(), the form is manipulated with form_driver(). We can send requests
6309 to form_driver to move focus to a certain field, move cursor to end of the field
6310 etc.. After the user enters values in the fields and validation done, form can
6311 be unposted and memory allocated can be freed.</P
6313 >The general flow of control of a forms program looks like this.
6321 >Initialize curses</P
6325 >Create fields using new_field(). You can specify the height and
6326 width of the field, and its position on the form.</P
6330 >Create the forms with new_form() by specifying the fields to be
6335 >Post the form with form_post() and refresh the screen.</P
6339 >Process the user requests with a loop and do necessary updates
6340 to form with form_driver.</P
6344 >Unpost the menu with form_unpost()</P
6348 >Free the memory allocated to menu by free_form()</P
6352 >Free the memory allocated to the items with free_field()</P
6361 >As you can see, working with forms library is much similar to handling menu
6362 library. The following examples will explore various aspects of form
6363 processing. Let's start the journey with a simple example. first.</P
6371 >18.2. Compiling With the Forms Library</A
6374 >To use forms library functions, you have to include form.h and to link the
6375 program with forms library the flag -lform should be added along with -lncurses
6378 CLASS="PROGRAMLISTING"
6379 > #include <form.h>
6384 compile and link: gcc <program file> -lform -lncurses</PRE
6392 >Example 25. Forms Basics </B
6395 CLASS="PROGRAMLISTING"
6397 CLASS="INLINEMEDIAOBJECT"
6398 >#include <form.h>
6405 /* Initialize curses */
6409 keypad(stdscr, TRUE);
6411 /* Initialize the fields */
6412 field[0] = new_field(1, 10, 4, 18, 0, 0);
6413 field[1] = new_field(1, 10, 6, 18, 0, 0);
6416 /* Set field options */
6417 set_field_back(field[0], A_UNDERLINE); /* Print a line for the option */
6418 field_opts_off(field[0], O_AUTOSKIP); /* Don't go to next field when this */
6419 /* Field is filled up */
6420 set_field_back(field[1], A_UNDERLINE);
6421 field_opts_off(field[1], O_AUTOSKIP);
6423 /* Create the form and post it */
6424 my_form = new_form(field);
6428 mvprintw(4, 10, "Value 1:");
6429 mvprintw(6, 10, "Value 2:");
6432 /* Loop through to get user requests */
6433 while((ch = getch()) != KEY_F(1))
6436 /* Go to next field */
6437 form_driver(my_form, REQ_NEXT_FIELD);
6438 /* Go to the end of the present buffer */
6439 /* Leaves nicely at the last character */
6440 form_driver(my_form, REQ_END_LINE);
6443 /* Go to previous field */
6444 form_driver(my_form, REQ_PREV_FIELD);
6445 form_driver(my_form, REQ_END_LINE);
6448 /* If this is a normal character, it gets */
6450 form_driver(my_form, ch);
6455 /* Un post form and free the memory */
6456 unpost_form(my_form);
6458 free_field(field[0]);
6459 free_field(field[1]);
6467 >Above example is pretty straight forward. It creates two fields with
6471 >. new_field() takes height, width,
6472 starty, startx, number of offscreen rows and number of additional working
6473 buffers. The fifth argument number of offscreen rows specifies how much of the
6474 field to be shown. If it is zero, the entire field is always displayed otherwise
6475 the form will be scrollable when the user accesses not displayed parts of the
6476 field. The forms library allocates one buffer per field to store the data user
6477 enters. Using the last parameter to new_field() we can specify it to allocate
6478 some additional buffers. These can be used for any purpose you like.</P
6480 >After creating the fields, back ground attribute of both of them is set to an
6481 underscore with set_field_back(). The AUTOSKIP option is turned off using
6482 field_opts_off(). If this option is turned on, focus will move to the next
6483 field in the form once the active field is filled up completely.</P
6485 >After attaching the fields to the form, it is posted. Here on, user inputs are
6486 processed in the while loop, by making corresponding requests to form_driver.
6487 The details of all the requests to the form_driver() are explained later.</P
6495 >18.3. Playing with Fields</A
6498 >Each form field is associated with a lot of attributes. They can be manipulated
6499 to get the required effect and to have fun !!!. So why wait? </P
6506 >18.3.1. Fetching Size and Location of Field</A
6509 >The parameters we have given at the time of creation of a field can be retrieved
6510 with field_info(). It returns height, width, starty, startx, number of offscreen
6511 rows, and number of additional buffers into the parameters given to it. It is a
6512 sort of inverse of new_field().</P
6514 CLASS="PROGRAMLISTING"
6515 >int field_info( FIELD *field, /* field from which to fetch */
6516 int *height, *int width, /* field size */
6517 int *top, int *left, /* upper left corner */
6518 int *offscreen, /* number of offscreen rows */
6519 int *nbuf); /* number of working buffers */</PRE
6527 >18.3.2. Moving the field</A
6530 >The location of the field can be moved to a different position with
6533 CLASS="PROGRAMLISTING"
6534 >int move_field( FIELD *field, /* field to alter */
6535 int top, int left); /* new upper-left corner */</PRE
6537 >As usual, the changed position can be queried with field_infor().</P
6545 >18.3.3. Field Justification</A
6548 >The justification to be done for the field can be fixed using the function
6549 set_field_just().</P
6551 CLASS="PROGRAMLISTING"
6552 > int set_field_just(FIELD *field, /* field to alter */
6553 int justmode); /* mode to set */
6554 int field_just(FIELD *field); /* fetch justify mode of field */</PRE
6556 >The justification mode valued accepted and returned by these functions are
6557 NO_JUSTIFICATION, JUSTIFY_RIGHT, JUSTIFY_LEFT, or JUSTIFY_CENTER.</P
6564 NAME="FIELDDISPATTRIB"
6565 >18.3.4. Field Display Attributes</A
6568 >As you have seen, in the above example, display attribute for the fields can be
6569 set with set_field_fore() and setfield_back(). These functions set foreground
6570 and background attribute of the fields. You can also specify a pad character
6571 which will be filled in the unfilled portion of the field. The pad character is
6572 set with a call to set_field_pad(). Default pad value is a space. The functions
6573 field_fore(), field_back, field_pad() can be used to query the present
6574 foreground, background attributes and pad character for the field. The following
6575 list gives the usage of functions.</P
6577 CLASS="PROGRAMLISTING"
6578 > int set_field_fore(FIELD *field, /* field to alter */
6579 chtype attr); /* attribute to set */
6581 chtype field_fore(FIELD *field); /* field to query */
6582 /* returns foreground attribute */
6584 int set_field_back(FIELD *field, /* field to alter */
6585 chtype attr); /* attribute to set */
6587 chtype field_back(FIELD *field); /* field to query */
6588 /* returns background attribute */
6590 int set_field_pad(FIELD *field, /* field to alter */
6591 int pad); /* pad character to set */
6593 chtype field_pad(FIELD *field); /* field to query */
6594 /* returns present pad character */ </PRE
6596 >Though above functions seem quite simple, using colors with set_field_fore() may
6597 be frustrating in the beginning. Let me first explain about foreground and
6598 background attributes of a field. The foreground attribute is associated with
6599 the character. That means a character in the field is printed with the attribute
6600 you have set with set_field_fore(). Background attribute is the attribute used
6601 to fill background of field, whether any character is there or not. So what
6602 about colors? Since colors are always defined in pairs, what is the right way to
6603 display colored fields? Here's an example clarifying color attributes.</P
6611 >Example 26. Form Attributes example </B
6614 CLASS="PROGRAMLISTING"
6616 CLASS="INLINEMEDIAOBJECT"
6617 >#include <form.h>
6624 /* Initialize curses */
6629 keypad(stdscr, TRUE);
6631 /* Initialize few color pairs */
6632 init_pair(1, COLOR_WHITE, COLOR_BLUE);
6633 init_pair(2, COLOR_WHITE, COLOR_BLUE);
6635 /* Initialize the fields */
6636 field[0] = new_field(1, 10, 4, 18, 0, 0);
6637 field[1] = new_field(1, 10, 6, 18, 0, 0);
6640 /* Set field options */
6641 set_field_fore(field[0], COLOR_PAIR(1));/* Put the field with blue background */
6642 set_field_back(field[0], COLOR_PAIR(2));/* and white foreground (characters */
6643 /* are printed in white */
6644 field_opts_off(field[0], O_AUTOSKIP); /* Don't go to next field when this */
6645 /* Field is filled up */
6646 set_field_back(field[1], A_UNDERLINE);
6647 field_opts_off(field[1], O_AUTOSKIP);
6649 /* Create the form and post it */
6650 my_form = new_form(field);
6654 set_current_field(my_form, field[0]); /* Set focus to the colored field */
6655 mvprintw(4, 10, "Value 1:");
6656 mvprintw(6, 10, "Value 2:");
6657 mvprintw(LINES - 2, 0, "Use UP, DOWN arrow keys to switch between fields");
6660 /* Loop through to get user requests */
6661 while((ch = getch()) != KEY_F(1))
6664 /* Go to next field */
6665 form_driver(my_form, REQ_NEXT_FIELD);
6666 /* Go to the end of the present buffer */
6667 /* Leaves nicely at the last character */
6668 form_driver(my_form, REQ_END_LINE);
6671 /* Go to previous field */
6672 form_driver(my_form, REQ_PREV_FIELD);
6673 form_driver(my_form, REQ_END_LINE);
6676 /* If this is a normal character, it gets */
6678 form_driver(my_form, ch);
6683 /* Un post form and free the memory */
6684 unpost_form(my_form);
6686 free_field(field[0]);
6687 free_field(field[1]);
6695 >Play with the color pairs and try to understand the foreground and background
6696 attributes. In my programs using color attributes, I usually set only the
6697 background with set_field_back(). Curses simply doesn't allow defining
6698 individual color attributes. </P
6705 NAME="FIELDOPTIONBITS"
6706 >18.3.5. Field Option Bits</A
6709 >There is also a large collection of field option bits you can set to control
6710 various aspects of forms processing. You can manipulate them with these
6713 CLASS="PROGRAMLISTING"
6714 >int set_field_opts(FIELD *field, /* field to alter */
6715 int attr); /* attribute to set */
6717 int field_opts_on(FIELD *field, /* field to alter */
6718 int attr); /* attributes to turn on */
6720 int field_opts_off(FIELD *field, /* field to alter */
6721 int attr); /* attributes to turn off */
6723 int field_opts(FIELD *field); /* field to query */ </PRE
6725 >The function set_field_opts() can be used to directly set attributes of a field
6726 or you can choose to switch a few attributes on and off with field_opts_on() and
6727 field_opts_off() selectively. Anytime you can query the attributes of a field
6728 with field_opts(). The following is the list of available options. By default,
6729 all options are on.</P
6733 CLASS="VARIABLELIST"
6739 >Controls whether the field is visible on the screen. Can be used
6740 during form processing to hide or pop up fields depending on the value
6741 of parent fields.</P
6747 >Controls whether the field is active during forms processing (i.e.
6748 visited by form navigation keys). Can be used to make labels or derived
6749 fields with buffer values alterable by the forms application, not the user.</P
6755 >Controls whether data is displayed during field entry. If this option is
6756 turned off on a field, the library will accept and edit data in that field,
6757 but it will not be displayed and the visible field cursor will not move.
6758 You can turn off the O_PUBLIC bit to define password fields.</P
6764 >Controls whether the field's data can be modified. When this option is
6765 off, all editing requests except <TT
6767 >REQ_PREV_CHOICE</TT
6770 >REQ_NEXT_CHOICE</TT
6772 fail. Such read-only fields may be useful for help messages.</P
6778 >Controls word-wrapping in multi-line fields. Normally, when any
6779 character of a (blank-separated) word reaches the end of the current line, the
6780 entire word is wrapped to the next line (assuming there is one). When this
6781 option is off, the word will be split across the line break.</P
6787 >Controls field blanking. When this option is on, entering a character at
6788 the first field position erases the entire field (except for the just-entered
6795 >Controls automatic skip to next field when this one fills. Normally,
6796 when the forms user tries to type more data into a field than will fit,
6797 the editing location jumps to next field. When this option is off, the
6798 user's cursor will hang at the end of the field. This option is ignored
6799 in dynamic fields that have not reached their size limit.</P
6805 >Controls whether validation is applied to
6806 blank fields. Normally, it is not; the user can leave a field blank
6807 without invoking the usual validation check on exit. If this option is
6808 off on a field, exit from it will invoke a validation check.</P
6814 >Controls whether validation occurs on every exit, or only after
6815 the field is modified. Normally the latter is true. Setting O_PASSOK
6816 may be useful if your field's validation function may change during
6817 forms processing.</P
6823 >Controls whether the field is fixed to its initial dimensions. If you
6824 turn this off, the field becomes dynamic and will
6825 stretch to fit entered data.</P
6830 >A field's options cannot be changed while the field is currently selected.
6831 However, options may be changed on posted fields that are not current. </P
6833 >The option values are bit-masks and can be composed with logical-or in
6834 the obvious way. You have seen the usage of switching off O_AUTOSKIP option.
6835 The following example clarifies usage of some more options. Other options
6836 are explained where appropriate.</P
6844 >Example 27. Field Options Usage example </B
6847 CLASS="PROGRAMLISTING"
6849 CLASS="INLINEMEDIAOBJECT"
6850 >#include <form.h>
6859 { FIELD *field[N_FIELDS];
6863 /* Initialize curses */
6867 keypad(stdscr, TRUE);
6869 /* Initialize the fields */
6870 for(i = 0; i < N_FIELDS - 1; ++i)
6871 field[i] = new_field(1, WIDTH, STARTY + i * 2, STARTX, 0, 0);
6872 field[N_FIELDS - 1] = NULL;
6874 /* Set field options */
6875 set_field_back(field[1], A_UNDERLINE); /* Print a line for the option */
6877 field_opts_off(field[0], O_ACTIVE); /* This field is a static label */
6878 field_opts_off(field[1], O_PUBLIC); /* This filed is like a password field*/
6879 field_opts_off(field[1], O_AUTOSKIP); /* To avoid entering the same field */
6880 /* after last character is entered */
6882 /* Create the form and post it */
6883 my_form = new_form(field);
6887 set_field_just(field[0], JUSTIFY_CENTER); /* Center Justification */
6888 set_field_buffer(field[0], 0, "This is a static Field");
6889 /* Initialize the field */
6890 mvprintw(STARTY, STARTX - 10, "Field 1:");
6891 mvprintw(STARTY + 2, STARTX - 10, "Field 2:");
6894 /* Loop through to get user requests */
6895 while((ch = getch()) != KEY_F(1))
6898 /* Go to next field */
6899 form_driver(my_form, REQ_NEXT_FIELD);
6900 /* Go to the end of the present buffer */
6901 /* Leaves nicely at the last character */
6902 form_driver(my_form, REQ_END_LINE);
6905 /* Go to previous field */
6906 form_driver(my_form, REQ_PREV_FIELD);
6907 form_driver(my_form, REQ_END_LINE);
6910 /* If this is a normal character, it gets */
6912 form_driver(my_form, ch);
6917 /* Un post form and free the memory */
6918 unpost_form(my_form);
6920 free_field(field[0]);
6921 free_field(field[1]);
6929 >This example, though useless, shows the usage of options. If used properly, they
6930 can present information very effectively in a form. The second field being not
6931 O_PUBLIC, does not show the characters you are typing.</P
6939 >18.3.6. Field Status</A
6942 >The field status specifies whether the field has got edited or not. It is
6943 initially set to FALSE and when user enters something and the data buffer gets
6944 modified it becomes TRUE. So a field's status can be queried to find out whether
6945 it has been modified or not. The following functions can assist in those
6948 CLASS="PROGRAMLISTING"
6949 >int set_field_status(FIELD *field, /* field to alter */
6950 int status); /* status to set */
6952 int field_status(FIELD *field); /* fetch status of field */</PRE
6954 >It's better to check the field's status only after after leaving the field, as
6955 data buffer might not have been updated yet as the validation is still due. To
6956 guarantee that right status is returned, call field_status() either (1) in the
6957 field's exit validation check routine, (2) from the field's or form's
6958 initialization or termination hooks, or (3) just after a REQ_VALIDATION request
6959 has been processed by the forms driver</P
6967 >18.3.7. Field User Pointer</A
6970 >Every field structure contains one pointer that can be used by the user for
6971 various purposes. It is not touched by forms library and can be used for any
6972 purpose by the user. The following functions set and fetch user pointer.</P
6974 CLASS="PROGRAMLISTING"
6975 >int set_field_userptr(FIELD *field,
6976 char *userptr); /* the user pointer you wish to associate */
6977 /* with the field */
6979 char *field_userptr(FIELD *field); /* fetch user pointer of the field */</PRE
6986 NAME="VARIABLESIZEFIELDS"
6987 >18.3.8. Variable-Sized Fields</A
6990 >If you want a dynamically changing field with variable width, this is the
6991 feature you want to put to full use. This will allow the user to enter more data
6992 than the original size of the field and let the field grow. According to the
6993 field orientation it will scroll horizontally or vertically to incorporate the
6996 >To make a field dynamically growable, the option O_STATIC should be turned off.
6997 This can be done with a
6999 CLASS="PROGRAMLISTING"
7000 > field_opts_off(field_pointer, O_STATIC);</PRE
7003 >But it's usually not advisable to allow a field to grow infinitely. You can set
7004 a maximum limit to the growth of the field with
7006 CLASS="PROGRAMLISTING"
7007 >int set_max_field(FIELD *field, /* Field on which to operate */
7008 int max_growth); /* maximum growth allowed for the field */</PRE
7011 >The field info for a dynamically growable field can be retrieved by
7013 CLASS="PROGRAMLISTING"
7014 >int dynamic_field_info( FIELD *field, /* Field on which to operate */
7015 int *prows, /* number of rows will be filled in this */
7016 int *pcols, /* number of columns will be filled in this*/
7017 int *pmax) /* maximum allowable growth will be filled */
7020 Though field_info work as usual, it is advisable to use this function to get the
7021 proper attributes of a dynamically growable field.</P
7023 >Recall the library routine new_field; a new field created with height set to one
7024 will be defined to be a one line field. A new field created with height greater
7025 than one will be defined to be a multi line field. </P
7027 >A one line field with O_STATIC turned off (dynamically growable field) will
7028 contain a single fixed row, but the number of columns can increase if the user
7029 enters more data than the initial field will hold. The number of columns
7030 displayed will remain fixed and the additional data will scroll horizontally. </P
7032 >A multi line field with O_STATIC turned off (dynamically growable field) will
7033 contain a fixed number of columns, but the number of rows can increase if the
7034 user enters more data than the initial field will hold. The number of rows
7035 displayed will remain fixed and the additional data will scroll vertically.</P
7037 >The above two paragraphs pretty much describe a dynamically growable field's
7038 behavior. The way other parts of forms library behaves is described below:</P
7045 >The field option O_AUTOSKIP will be ignored if the option O_STATIC is off and
7046 there is no maximum growth specified for the field. Currently, O_AUTOSKIP
7047 generates an automatic REQ_NEXT_FIELD form driver request when the user types in
7048 the last character position of a field. On a growable field with no maximum
7049 growth specified, there is no last character position. If a maximum growth is
7050 specified, the O_AUTOSKIP option will work as normal if the field has grown to
7051 its maximum size. </P
7055 >The field justification will be ignored if the option O_STATIC is off.
7056 Currently, set_field_just can be used to JUSTIFY_LEFT, JUSTIFY_RIGHT,
7057 JUSTIFY_CENTER the contents of a one line field. A growable one line field will,
7058 by definition, grow and scroll horizontally and may contain more data than can
7059 be justified. The return from field_just will be unchanged. </P
7063 >The overloaded form driver request REQ_NEW_LINE will operate the same way
7064 regardless of the O_NL_OVERLOAD form option if the field option O_STATIC is off
7065 and there is no maximum growth specified for the field. Currently, if the form
7066 option O_NL_OVERLOAD is on, REQ_NEW_LINE implicitly generates a REQ_NEXT_FIELD
7067 if called from the last line of a field. If a field can grow without bound,
7068 there is no last line, so REQ_NEW_LINE will never implicitly generate a
7069 REQ_NEXT_FIELD. If a maximum growth limit is specified and the O_NL_OVERLOAD
7070 form option is on, REQ_NEW_LINE will only implicitly generate REQ_NEXT_FIELD if
7071 the field has grown to its maximum size and the user is on the last line. </P
7075 >The library call dup_field will work as usual; it will duplicate the field,
7076 including the current buffer size and contents of the field being duplicated.
7077 Any specified maximum growth will also be duplicated. </P
7081 >The library call link_field will work as usual; it will duplicate all field
7082 attributes and share buffers with the field being linked. If the O_STATIC field
7083 option is subsequently changed by a field sharing buffers, how the system reacts
7084 to an attempt to enter more data into the field than the buffer will currently
7085 hold will depend on the setting of the option in the current field. </P
7089 >The library call field_info will work as usual; the variable nrow will contain
7090 the value of the original call to new_field. The user should use
7091 dynamic_field_info, described above, to query the current size of the buffer.</P
7095 >Some of the above points make sense only after explaining form driver. We will
7096 be looking into that in next few sections.</P
7105 >18.4. Form Windows</A
7108 >The form windows concept is pretty much similar to menu windows. Every form is
7109 associated with a main window and a sub window. The form main window displays
7110 any title or border associated or whatever the user wishes. Then the sub window
7111 contains all the fields and displays them according to their position. This
7112 gives the flexibility of manipulating fancy form displaying very easily. </P
7114 >Since this is pretty much similar to menu windows, I am providing an example
7115 with out much explanation. The functions are similar and they work the same way.</P
7123 >Example 28. Form Windows Example </B
7126 CLASS="PROGRAMLISTING"
7128 CLASS="INLINEMEDIAOBJECT"
7129 >#include <form.h>
7131 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
7137 WINDOW *my_form_win;
7140 /* Initialize curses */
7145 keypad(stdscr, TRUE);
7147 /* Initialize few color pairs */
7148 init_pair(1, COLOR_RED, COLOR_BLACK);
7150 /* Initialize the fields */
7151 field[0] = new_field(1, 10, 6, 1, 0, 0);
7152 field[1] = new_field(1, 10, 8, 1, 0, 0);
7155 /* Set field options */
7156 set_field_back(field[0], A_UNDERLINE);
7157 field_opts_off(field[0], O_AUTOSKIP); /* Don't go to next field when this */
7158 /* Field is filled up */
7159 set_field_back(field[1], A_UNDERLINE);
7160 field_opts_off(field[1], O_AUTOSKIP);
7162 /* Create the form and post it */
7163 my_form = new_form(field);
7165 /* Calculate the area required for the form */
7166 scale_form(my_form, &rows, &cols);
7168 /* Create the window to be associated with the form */
7169 my_form_win = newwin(rows + 4, cols + 4, 4, 4);
7170 keypad(my_form_win, TRUE);
7172 /* Set main window and sub window */
7173 set_form_win(my_form, my_form_win);
7174 set_form_sub(my_form, derwin(my_form_win, rows, cols, 2, 2));
7176 /* Print a border around the main window and print a title */
7177 box(my_form_win, 0, 0);
7178 print_in_middle(my_form_win, 1, 0, cols + 4, "My Form", COLOR_PAIR(1));
7181 wrefresh(my_form_win);
7183 mvprintw(LINES - 2, 0, "Use UP, DOWN arrow keys to switch between fields");
7186 /* Loop through to get user requests */
7187 while((ch = wgetch(my_form_win)) != KEY_F(1))
7190 /* Go to next field */
7191 form_driver(my_form, REQ_NEXT_FIELD);
7192 /* Go to the end of the present buffer */
7193 /* Leaves nicely at the last character */
7194 form_driver(my_form, REQ_END_LINE);
7197 /* Go to previous field */
7198 form_driver(my_form, REQ_PREV_FIELD);
7199 form_driver(my_form, REQ_END_LINE);
7202 /* If this is a normal character, it gets */
7204 form_driver(my_form, ch);
7209 /* Un post form and free the memory */
7210 unpost_form(my_form);
7212 free_field(field[0]);
7213 free_field(field[1]);
7219 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
7233 length = strlen(string);
7234 temp = (width - length)/ 2;
7235 x = startx + (int)temp;
7236 wattron(win, color);
7237 mvwprintw(win, y, x, "%s", string);
7238 wattroff(win, color);
7249 NAME="FILEDVALIDATE"
7250 >18.5. Field Validation</A
7253 >By default, a field will accept any data input by the user. It is possible to
7254 attach validation to the field. Then any attempt by the user to leave the field,
7255 while it contains data that doesn't match the validation type will fail. Some
7256 validation types also have a character-validity check for each time a character
7257 is entered in the field.</P
7259 >Validation can be attached to a field with the following function.
7261 CLASS="PROGRAMLISTING"
7262 >int set_field_type(FIELD *field, /* field to alter */
7263 FIELDTYPE *ftype, /* type to associate */
7264 ...); /* additional arguments*/</PRE
7266 Once set, the validation type for a field can be queried with
7268 CLASS="PROGRAMLISTING"
7269 >FIELDTYPE *field_type(FIELD *field); /* field to query */</PRE
7272 >The form driver validates the data in a field only when data is entered by the
7273 end-user. Validation does not occur when </P
7279 >the application program changes the field value by calling set_field_buffer. </P
7283 >linked field values are changed indirectly -- by changing the field to which
7288 >The following are the pre-defined validation types. You can also specify custom
7289 validation, though it's a bit tricky and cumbersome.</P
7297 >This field type accepts alphabetic data; no blanks, no digits, no special
7298 characters (this is checked at character-entry time). It is set up with: </P
7300 CLASS="PROGRAMLISTING"
7301 >int set_field_type(FIELD *field, /* field to alter */
7302 TYPE_ALPHA, /* type to associate */
7303 int width); /* maximum width of field */</PRE
7305 >The width argument sets a minimum width of data. The user has to enter at-least
7306 width number of characters before he can leave the field. Typically
7307 you'll want to set this to the field width; if it's greater than the
7308 field width, the validation check will always fail. A minimum width
7309 of zero makes field completion optional. </P
7317 >This field type accepts alphabetic data and digits; no blanks, no special
7318 characters (this is checked at character-entry time). It is set up with: </P
7320 CLASS="PROGRAMLISTING"
7321 >int set_field_type(FIELD *field, /* field to alter */
7322 TYPE_ALNUM, /* type to associate */
7323 int width); /* maximum width of field */</PRE
7325 >The width argument sets a minimum width of data. As with
7326 TYPE_ALPHA, typically you'll want to set this to the field width; if it's
7327 greater than the field width, the validation check will always fail. A
7328 minimum width of zero makes field completion optional. </P
7336 >This type allows you to restrict a field's values to be among a specified
7337 set of string values (for example, the two-letter postal codes for U.S.
7338 states). It is set up with: </P
7340 CLASS="PROGRAMLISTING"
7341 >int set_field_type(FIELD *field, /* field to alter */
7342 TYPE_ENUM, /* type to associate */
7343 char **valuelist; /* list of possible values */
7344 int checkcase; /* case-sensitive? */
7345 int checkunique); /* must specify uniquely? */</PRE
7347 >The valuelist parameter must point at a NULL-terminated list of
7348 valid strings. The checkcase argument, if true, makes comparison
7349 with the string case-sensitive. </P
7351 >When the user exits a TYPE_ENUM field, the validation procedure tries to
7352 complete the data in the buffer to a valid entry. If a complete choice string
7353 has been entered, it is of course valid. But it is also possible to enter a
7354 prefix of a valid string and have it completed for you. </P
7356 >By default, if you enter such a prefix and it matches more than one value
7357 in the string list, the prefix will be completed to the first matching
7358 value. But the checkunique argument, if true, requires prefix
7359 matches to be unique in order to be valid. </P
7361 >The REQ_NEXT_CHOICE and REQ_PREV_CHOICE input requests can be particularly
7362 useful with these fields. </P
7370 >This field type accepts an integer. It is set up as follows: </P
7372 CLASS="PROGRAMLISTING"
7373 >int set_field_type(FIELD *field, /* field to alter */
7374 TYPE_INTEGER, /* type to associate */
7375 int padding, /* # places to zero-pad to */
7376 int vmin, int vmax); /* valid range */</PRE
7378 >Valid characters consist of an optional leading minus and digits.
7379 The range check is performed on exit. If the range maximum is less
7380 than or equal to the minimum, the range is ignored. </P
7382 >If the value passes its range check, it is padded with as many leading
7383 zero digits as necessary to meet the padding argument. </P
7385 >A TYPE_INTEGER value buffer can conveniently be interpreted with the C library
7386 function atoi(3).</P
7394 >This field type accepts a decimal number. It is set up as follows: </P
7396 CLASS="PROGRAMLISTING"
7397 >int set_field_type(FIELD *field, /* field to alter */
7398 TYPE_NUMERIC, /* type to associate */
7399 int padding, /* # places of precision */
7400 int vmin, int vmax); /* valid range */</PRE
7402 >Valid characters consist of an optional leading minus and digits. possibly
7403 including a decimal point. The range check is performed on exit. If the
7404 range maximum is less than or equal to the minimum, the range is
7407 >If the value passes its range check, it is padded with as many trailing
7408 zero digits as necessary to meet the padding argument. </P
7410 >A TYPE_NUMERIC value buffer can conveniently be interpreted with the C library
7411 function atof(3).</P
7419 >This field type accepts data matching a regular expression. It is set up
7422 CLASS="PROGRAMLISTING"
7423 >int set_field_type(FIELD *field, /* field to alter */
7424 TYPE_REGEXP, /* type to associate */
7425 char *regexp); /* expression to match */</PRE
7427 >The syntax for regular expressions is that of regcomp(3).
7428 The check for regular-expression match is performed on exit.</P
7436 >18.6. Form Driver: The work horse of the forms system</A
7439 >As in the menu system, form_driver() plays a very important role in forms
7440 system. All types of requests to forms system should be funneled through
7443 CLASS="PROGRAMLISTING"
7444 >int form_driver(FORM *form, /* form on which to operate */
7445 int request) /* form request code */</PRE
7447 >As you have seen some of the examples above, you have to be in a loop looking
7448 for user input and then decide whether it's a field data or a form request. The
7449 form requests are then passed to form_driver() to do the work.</P
7451 >The requests roughly can be divided into following categories. Different
7452 requests and their usage is explained below:</P
7459 >18.6.1. Page Navigation Requests</A
7462 >These requests cause page-level moves through the form, triggering display of a
7463 new form screen. A form can be made of multiple pages. If you have a big form
7464 with lot of fields and logical sections, then you can divide the form into
7465 pages. The function set_new_page() to set a new page at the field specified.</P
7467 CLASS="PROGRAMLISTING"
7468 >int set_new_page(FIELD *field,/* Field at which page break to be set or unset */
7469 bool new_page_flag); /* should be TRUE to put a break */</PRE
7471 >The following requests allow you to move to different pages</P
7483 > Move to the next form page.</P
7493 > Move to the previous
7504 > Move to the first form page.</P
7514 > Move to the last form page. </P
7518 >These requests treat the list as cyclic; that is, REQ_NEXT_PAGE from the
7519 last page goes to the first, and REQ_PREV_PAGE from the first page goes to
7527 NAME="INTERFIELDNAVREQ"
7528 >18.6.2. Inter-Field Navigation Requests</A
7531 >These requests handle navigation between fields on the same page.</P
7544 Move to next field. </P
7555 Move to previous field. </P
7566 Move to the first field. </P
7577 Move to the last field. </P
7588 Move to sorted next field. </P
7599 Move to sorted previous field. </P
7607 >REQ_SFIRST_FIELD</I
7610 Move to the sorted first field. </P
7621 Move to the sorted last field. </P
7632 Move left to field. </P
7643 Move right to field. </P
7654 Move up to field. </P
7665 Move down to field. </P
7669 >These requests treat the list of fields on a page as cyclic; that is,
7670 REQ_NEXT_FIELD from the last field goes to the first, and REQ_PREV_FIELD
7671 from the first field goes to the last. The order of the fields for these
7672 (and the REQ_FIRST_FIELD and REQ_LAST_FIELD requests) is simply the order of
7673 the field pointers in the form array (as set up by new_form() or
7674 set_form_fields()</P
7676 >It is also possible to traverse the fields as if they had been sorted in
7677 screen-position order, so the sequence goes left-to-right and top-to-bottom.
7678 To do this, use the second group of four sorted-movement requests.</P
7680 >Finally, it is possible to move between fields using visual directions up,
7681 down, right, and left. To accomplish this, use the third group of four
7682 requests. Note, however, that the position of a form for purposes of these
7683 requests is its upper-left corner.</P
7685 >For example, suppose you have a multi-line field B, and two single-line
7686 fields A and C on the same line with B, with A to the left of B and C to the
7687 right of B. A REQ_MOVE_RIGHT from A will go to B only if A, B, and C all
7688 share the same first line; otherwise it will skip over B to C.</P
7695 NAME="INTRAFIELDNAVREQ"
7696 >18.6.3. Intra-Field Navigation Requests</A
7699 >These requests drive movement of the edit cursor within the currently
7713 Move to next character. </P
7724 Move to previous character. </P
7735 Move to next line. </P
7746 Move to previous line. </P
7757 Move to next word. </P
7768 Move to previous word. </P
7779 Move to beginning of field. </P
7790 Move to end of field. </P
7801 Move to beginning of line. </P
7812 Move to end of line. </P
7823 Move left in field. </P
7834 Move right in field. </P
7845 Move up in field. </P
7856 Move down in field. </P
7860 >Each word is separated from the previous and next characters by whitespace.
7861 The commands to move to beginning and end of line or field look for the
7862 first or last non-pad character in their ranges.</P
7870 >18.6.4. Scrolling Requests</A
7873 >Fields that are dynamic and have grown and fields explicitly created with
7874 offscreen rows are scrollable. One-line fields scroll horizontally;
7875 multi-line fields scroll vertically. Most scrolling is triggered by editing
7876 and intra-field movement (the library scrolls the field to keep the cursor
7877 visible). It is possible to explicitly request scrolling with the following
7891 Scroll vertically forward a line. </P
7902 Scroll vertically backward a line. </P
7913 Scroll vertically forward a page. </P
7924 Scroll vertically backward a page. </P
7935 Scroll vertically forward half a page. </P
7946 Scroll vertically backward half a page. </P
7957 Scroll horizontally forward a character. </P
7968 Scroll horizontally backward a character. </P
7979 Scroll horizontally one field width forward. </P
7990 Scroll horizontally one field width backward. </P
8001 Scroll horizontally one half field width forward. </P
8012 Scroll horizontally one half field width backward. </P
8016 >For scrolling purposes, a page of a field is the height of its visible part.</P
8024 >18.6.5. Editing Requests</A
8027 >When you pass the forms driver an ASCII character, it is treated as a
8028 request to add the character to the field's data buffer. Whether this is an
8029 insertion or a replacement depends on the field's edit mode (insertion is
8032 >The following requests support editing the field and changing the edit mode:</P
8045 Set insertion mode. </P
8056 Set overlay mode. </P
8067 New line request (see below for explanation). </P
8078 Insert space at character location. </P
8089 Insert blank line at character location. </P
8100 Delete character at cursor. </P
8111 Delete previous word at cursor. </P
8122 Delete line at cursor. </P
8133 Delete word at cursor. </P
8144 Clear to end of line. </P
8155 Clear to end of field. </P
8166 Clear entire field. </P
8170 >The behavior of the REQ_NEW_LINE and REQ_DEL_PREV requests is complicated
8171 and partly controlled by a pair of forms options. The special cases are
8172 triggered when the cursor is at the beginning of a field, or on the last
8173 line of the field.</P
8175 >First, we consider REQ_NEW_LINE:</P
8177 >The normal behavior of REQ_NEW_LINE in insert mode is to break the current
8178 line at the position of the edit cursor, inserting the portion of the
8179 current line after the cursor as a new line following the current and moving
8180 the cursor to the beginning of that new line (you may think of this as
8181 inserting a newline in the field buffer).</P
8183 >The normal behavior of REQ_NEW_LINE in overlay mode is to clear the current
8184 line from the position of the edit cursor to end of line. The cursor is then
8185 moved to the beginning of the next line.</P
8187 >However, REQ_NEW_LINE at the beginning of a field, or on the last line of a
8188 field, instead does a REQ_NEXT_FIELD. O_NL_OVERLOAD option is off, this
8189 special action is disabled.</P
8191 >Now, let us consider REQ_DEL_PREV:</P
8193 >The normal behavior of REQ_DEL_PREV is to delete the previous character. If
8194 insert mode is on, and the cursor is at the start of a line, and the text on
8195 that line will fit on the previous one, it instead appends the contents of
8196 the current line to the previous one and deletes the current line (you may
8197 think of this as deleting a newline from the field buffer).</P
8199 >However, REQ_DEL_PREV at the beginning of a field is instead treated as a
8202 >If the O_BS_OVERLOAD option is off, this special action is disabled and the
8203 forms driver just returns E_REQUEST_DENIED.</P
8211 >18.6.6. Order Requests</A
8214 >If the type of your field is ordered, and has associated functions for
8215 getting the next and previous values of the type from a given value, there
8216 are requests that can fetch that value into the field buffer:</P
8229 Place the successor value of the current value in the buffer.
8241 Place the predecessor value of the current value in the buffer.
8246 >Of the built-in field types, only TYPE_ENUM has built-in successor and
8247 predecessor functions. When you define a field type of your own (see Custom
8248 Validation Types), you can associate our own ordering functions.</P
8255 NAME="APPLICCOMMANDS"
8256 >18.6.7. Application Commands</A
8259 >Form requests are represented as integers above the curses value greater than
8260 KEY_MAX and less than or equal to the constant MAX_COMMAND. A value within this
8261 range gets ignored by form_driver(). So this can be used for any purpose by the
8262 application. It can be treated as an application specific action and take
8263 corresponding action.</P
8273 >19. Tools and Widget Libraries</A
8277 Now that you have seen the capabilities of ncurses and its sister libraries, you
8278 are rolling your sleeves up and gearing for a project that heavily manipulates
8279 screen. But wait.. It can be pretty difficult to write and maintain complex GUI
8280 widgets in plain ncurses or even with the additional libraries. There are some
8281 ready-to-use tools and widget libraries that can be used instead of writing your
8282 own widgets. You can use some of them, get ideas from the code, or even extend
8290 >19.1. CDK (Curses Development Kit)</A
8293 >In the author's words </P
8300 CDK stands for 'Curses Development Kit' and it currently contains 21 ready
8301 to use widgets which facilitate the speedy development of full screen
8302 curses programs. </I
8306 >The kit provides some useful widgets, which can be used in your programs
8307 directly. It's pretty well written and the documentation is very good. The
8308 examples in the examples directory can be a good place to start for beginners.
8309 The CDK can be downloaded from <A
8310 HREF="http://invisible-island.net/cdk/"
8312 >http://invisible-island.net/cdk/</A
8314 . Follow the instructions in
8315 README file to install it.</P
8322 >19.1.1. Widget List</A
8325 >The following is the list of widgets provided with cdk and their description.</P
8327 CLASS="PROGRAMLISTING"
8328 >Widget Type Quick Description
8329 ===========================================================================
8330 Alphalist Allows a user to select from a list of words, with
8331 the ability to narrow the search list by typing in a
8332 few characters of the desired word.
8333 Buttonbox This creates a multiple button widget.
8334 Calendar Creates a little simple calendar widget.
8335 Dialog Prompts the user with a message, and the user
8336 can pick an answer from the buttons provided.
8337 Entry Allows the user to enter various types of information.
8338 File Selector A file selector built from Cdk base widgets. This
8339 example shows how to create more complicated widgets
8340 using the Cdk widget library.
8341 Graph Draws a graph.
8342 Histogram Draws a histogram.
8343 Item List Creates a pop up field which allows the user to select
8344 one of several choices in a small field. Very useful
8345 for things like days of the week or month names.
8346 Label Displays messages in a pop up box, or the label can be
8347 considered part of the screen.
8348 Marquee Displays a message in a scrolling marquee.
8349 Matrix Creates a complex matrix with lots of options.
8350 Menu Creates a pull-down menu interface.
8351 Multiple Line Entry A multiple line entry field. Very useful
8352 for long fields. (like a description
8354 Radio List Creates a radio button list.
8355 Scale Creates a numeric scale. Used for allowing a user to
8356 pick a numeric value and restrict them to a range of
8358 Scrolling List Creates a scrolling list/menu list.
8359 Scrolling Window Creates a scrolling log file viewer. Can add
8360 information into the window while its running.
8361 A good widget for displaying the progress of
8362 something. (akin to a console window)
8363 Selection List Creates a multiple option selection list.
8364 Slider Akin to the scale widget, this widget provides a
8365 visual slide bar to represent the numeric value.
8366 Template Creates a entry field with character sensitive
8367 positions. Used for pre-formatted fields like
8368 dates and phone numbers.
8369 Viewer This is a file/information viewer. Very useful
8370 when you need to display loads of information.
8371 ===========================================================================</PRE
8373 >A few of the widgets are modified by Thomas Dickey in recent versions.</P
8381 >19.1.2. Some Attractive Features</A
8384 >Apart from making our life easier with readily usable widgets, cdk solves one
8385 frustrating problem with printing multi colored strings, justified strings
8386 elegantly. Special formatting tags can be embedded in the strings which are
8387 passed to CDK functions. For Example</P
8391 CLASS="PROGRAMLISTING"
8392 >"</B/1>This line should have a yellow foreground and a blue
8393 background.<!1>"</PRE
8395 >given as a parameter to newCDKLabel(), it prints the line with yellow foreground
8396 and blue background. There are other tags available for justifying string,
8397 embedding special drawing characters etc.. Please refer to the man page
8398 cdk_display(3X) for details. The man page explains the usage with nice examples.</P
8405 NAME="CDKCONCLUSION"
8406 >19.1.3. Conclusion</A
8409 >All in all, CDK is a well-written package of widgets, which if used properly can
8410 form a strong frame work for developing complex GUI.</P
8419 >19.2. The dialog</A
8422 >Long long ago, in September 1994, when few people knew linux, Jeff Tranter wrote
8424 HREF="http://www2.linuxjournal.com/lj-issues/issue5/2807.html"
8427 > on dialog in Linux Journal. He starts the article with these words..</P
8433 >Linux is based on the Unix operating system, but also features a number of
8434 unique and useful kernel features and application programs that often go beyond
8435 what is available under Unix. One little-known gem is "dialog", a utility for
8436 creating professional-looking dialog boxes from within shell scripts. This
8437 article presents a tutorial introduction to the dialog utility, and shows
8438 examples of how and where it can be used</I
8443 As he explains, dialog is a real gem in making professional-looking dialog boxes
8444 with ease. It creates a variety of dialog boxes, menus, check lists etc.. It is
8445 usually installed by default. If not, you can download it from <A
8446 HREF="http://invisible-island.net/dialog/"
8451 >The above-mentioned article gives a very good overview of its uses and
8452 capabilites. The man page has more details. It can be used in variety of
8453 situations. One good example is building of linux kernel in text mode. Linux
8454 kernel uses a modified version of dialog tailored for its needs. </P
8456 >dialog was initially designed to be used with shell scripts. If you want to use
8457 its functionality in a c program, then you can use libdialog. The documentation
8458 regarding this is sparse. Definitive reference is the dialog.h header file which
8459 comes with the library. You may need to hack here and there to get the required
8460 output. The source is easily customizable. I have used it on a number of
8461 occasions by modifying the code.</P
8469 >19.3. Perl Curses Modules CURSES::FORM and CURSES::WIDGETS</A
8472 >The perl module Curses, Curses::Form and Curses::Widgets give access to curses
8473 from perl. If you have curses and basic perl is installed, you can get these
8475 HREF="http://www.cpan.org/modules/01modules.index.html"
8479 >. Get the three zipped modules in the Curses category.
8480 Once installed you can use these modules from perl scripts like any other
8481 module. For more information on perl modules see perlmod man page. The above
8482 modules come with good documentation and they have some demo scripts to test the
8483 functionality. Though the widgets provided are very rudimentary, these modules
8484 provide good access to curses library from perl.</P
8486 >Some of my code examples are converted to perl by Anuradha Ratnaweera and they
8487 are available in the <TT
8493 For more information see man pages Curses(3) , Curses::Form(3) and
8494 Curses::Widgets(3). These pages are installed only when the above modules are
8495 acquired and installed.</P
8504 >20. Just For Fun !!!</A
8507 >This section contains few programs written by me just for fun. They don't
8508 signify a better programming practice or the best way of using ncurses. They are
8509 provided here so as to allow beginners to get ideas and add more programs to
8510 this section. If you have written a couple of nice, simple programs in curses
8511 and want them to included here, contact <A
8512 HREF="mailto:ppadala@gmail.com"
8522 >20.1. The Game of Life</A
8525 >Game of life is a wonder of math. In
8527 HREF="http://www.math.com/students/wonders/life/life.html"
8532 CLASS="PROGRAMLISTING"
8537 >The Game of Life (or simply Life) is not a game in the conventional sense. There
8538 are no players, and no winning or losing. Once the "pieces" are placed in the
8539 starting position, the rules determine everything that happens later.
8540 Nevertheless, Life is full of surprises! In most cases, it is impossible to look
8541 at a starting position (or pattern) and see what will happen in the future. The
8542 only way to find out is to follow the rules of the game.</I
8546 >This program starts with a simple inverted U pattern and shows how wonderful
8547 life works. There is a lot of room for improvement in the program. You can let
8548 the user enter pattern of his choice or even take input from a file. You can
8549 also change rules and play with a lot of variations. Search on <A
8550 HREF="http://www.google.com"
8553 > for interesting information on game
8560 >File Path: JustForFun/life.c</I
8570 >20.2. Magic Square</A
8573 >Magic Square, another wonder of math, is very simple to understand but very
8574 difficult to make. In a magic square sum of the numbers in each row, each column
8575 is equal. Even diagnol sum can be equal. There are many variations which have
8576 special properties.</P
8578 >This program creates a simple magic square of odd order.</P
8584 >File Path: JustForFun/magic.c</I
8594 >20.3. Towers of Hanoi</A
8597 >The famous towers of hanoi solver. The aim of the game is to move the disks on
8598 the first peg to last peg, using middle peg as a temporary stay. The catch is
8599 not to place a larger disk over a small disk at any time.</P
8605 >File Path: JustForFun/hanoi.c</I
8615 >20.4. Queens Puzzle</A
8618 >The objective of the famous N-Queen puzzle is to put N queens on a N X N chess
8619 board without attacking each other. </P
8621 >This program solves it with a simple backtracking technique.</P
8627 >File Path: JustForFun/queens.c</I
8640 >A fun game, if you have time to kill. </P
8646 >File Path: JustForFun/shuffle.c</I
8656 >20.6. Typing Tutor</A
8659 >A simple typing tutor, I created more out of need than for ease of use. If you
8660 know how to put your fingers correctly on the keyboard, but lack practice, this
8667 >File Path: JustForFun/tt.c</I
8685 >NCURSES man pages </P
8690 HREF="http://invisible-island.net/ncurses/ncurses.faq.html"
8692 >http://invisible-island.net/ncurses/ncurses.faq.html</A
8698 >Writing programs with NCURSES by Eric Raymond and Zeyd M.
8701 HREF="http://invisible-island.net/ncurses/ncurses-intro.html"
8703 >http://invisible-island.net/ncurses/ncurses-intro.html</A
8705 obsolete. I was inspired by this document and the structure of this HOWTO
8706 follows from the original document</P