1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
6 <meta name="generator" content=
7 "HTML Tidy for Linux (vers 25 March 2009), see www.w3.org">
9 <title>NCURSES Programming HOWTO</title>
10 <meta name="GENERATOR" content=
11 "Modular DocBook HTML Stylesheet Version 1.79">
14 <body class="ARTICLE" bgcolor="#FFFFFF" text="#000000" link=
15 "#0000FF" vlink="#840084" alink="#0000FF">
17 <div class="TITLEPAGE">
18 <h1 class="TITLE"><a name="AEN2" id="AEN2">NCURSES
19 Programming HOWTO</a></h1>
21 <h3 class="AUTHOR"><a name="AEN4" id="AEN4">Pradeep
24 <div class="AFFILIATION">
26 <p class="ADDRESS"><code class="EMAIL"><<a href=
27 "mailto:ppadala@gmail.com">ppadala@gmail.com</a>></code></p>
31 <p class="PUBDATE">v1.9, 2005-06-20<br></p>
33 <div class="REVHISTORY">
34 <table width="100%" border="0" summary="revisions">
36 <th align="left" valign="top" colspan="3"><b>Revision
41 <td align="left">Revision 1.9</td>
43 <td align="left">2005-06-20</td>
45 <td align="left">Revised by: ppadala</td>
49 <td align="left" colspan="3">The license has been
50 changed to the MIT-style license used by NCURSES. Note
51 that the programs are also re-licensed under this.</td>
55 <td align="left">Revision 1.8</td>
57 <td align="left">2005-06-17</td>
59 <td align="left">Revised by: ppadala</td>
63 <td align="left" colspan="3">Lots of updates. Added
64 references and perl examples. Changes to examples. Many
65 grammatical and stylistic changes to the content.
66 Changes to NCURSES history.</td>
70 <td align="left">Revision 1.7.1</td>
72 <td align="left">2002-06-25</td>
74 <td align="left">Revised by: ppadala</td>
78 <td align="left" colspan="3">Added a README file for
79 building and instructions for building from
84 <td align="left">Revision 1.7</td>
86 <td align="left">2002-06-25</td>
88 <td align="left">Revised by: ppadala</td>
92 <td align="left" colspan="3">Added "Other formats"
93 section and made a lot of fancy changes to the
94 programs. Inlining of programs is gone.</td>
98 <td align="left">Revision 1.6.1</td>
100 <td align="left">2002-02-24</td>
102 <td align="left">Revised by: ppadala</td>
106 <td align="left" colspan="3">Removed the old Changelog
107 section, cleaned the makefiles</td>
111 <td align="left">Revision 1.6</td>
113 <td align="left">2002-02-16</td>
115 <td align="left">Revised by: ppadala</td>
119 <td align="left" colspan="3">Corrected a lot of
120 spelling mistakes, added ACS variables section</td>
124 <td align="left">Revision 1.5</td>
126 <td align="left">2002-01-05</td>
128 <td align="left">Revised by: ppadala</td>
132 <td align="left" colspan="3">Changed structure to
133 present proper TOC</td>
137 <td align="left">Revision 1.3.1</td>
139 <td align="left">2001-07-26</td>
141 <td align="left">Revised by: ppadala</td>
145 <td align="left" colspan="3">Corrected maintainers
146 paragraph, Corrected stable release number</td>
150 <td align="left">Revision 1.3</td>
152 <td align="left">2001-07-24</td>
154 <td align="left">Revised by: ppadala</td>
158 <td align="left" colspan="3">Added copyright notices to
159 main document (LDP license) and programs (GPL),
160 Corrected printw_example.</td>
164 <td align="left">Revision 1.2</td>
166 <td align="left">2001-06-05</td>
168 <td align="left">Revised by: ppadala</td>
172 <td align="left" colspan="3">Incorporated ravi's
173 changes. Mainly to introduction, menu, form, justforfun
178 <td align="left">Revision 1.1</td>
180 <td align="left">2001-05-22</td>
182 <td align="left">Revised by: ppadala</td>
186 <td align="left" colspan="3">Added "a word about
187 window" section, Added scanw_example.</td>
193 <div class="ABSTRACT">
194 <a name="AEN67" id="AEN67"></a>
196 <p><span class="emphasis"><i class="EMPHASIS">This
197 document is intended to be an "All in One" guide for
198 programming with ncurses and its sister libraries. We
199 graduate from a simple "Hello World" program to more
200 complex form manipulation. No prior experience in ncurses
201 is assumed. Send comments to <a href=
202 "mailto:ppadala@gmail.com" target="_top">this
203 address</a></i></span></p>
211 <dt><b>Table of Contents</b></dt>
213 <dt>1. <a href="#INTRO">Introduction</a></dt>
217 <dt>1.1. <a href="#WHATIS">What is NCURSES?</a></dt>
219 <dt>1.2. <a href="#WHATCANWEDO">What we can do with
222 <dt>1.3. <a href="#WHERETOGETIT">Where to get
225 <dt>1.4. <a href="#PURPOSE">Purpose/Scope of the
228 <dt>1.5. <a href="#ABOUTPROGRAMS">About the
231 <dt>1.6. <a href="#OTHERFORMATS">Other Formats of the
236 <dt>1.6.1. <a href="#LISTFORMATS">Readily available
237 formats from tldp.org</a></dt>
239 <dt>1.6.2. <a href="#BUILDSOURCE">Building from
244 <dt>1.7. <a href="#CREDITS">Credits</a></dt>
246 <dt>1.8. <a href="#WISHLIST">Wish List</a></dt>
248 <dt>1.9. <a href="#COPYRIGHT">Copyright</a></dt>
252 <dt>2. <a href="#HELLOWORLD">Hello World !!!</a></dt>
256 <dt>2.1. <a href="#COMPILECURSES">Compiling With the
257 NCURSES Library</a></dt>
259 <dt>2.2. <a href="#DISSECTION">Dissection</a></dt>
263 <dt>2.2.1. <a href="#ABOUT-INITSCR">About
266 <dt>2.2.2. <a href="#MYST-REFRESH">The mysterious
269 <dt>2.2.3. <a href="#ABOUT-ENDWIN">About
276 <dt>3. <a href="#GORY">The Gory Details</a></dt>
278 <dt>4. <a href="#INIT">Initialization</a></dt>
282 <dt>4.1. <a href="#ABOUTINIT">Initialization
285 <dt>4.2. <a href="#RAWCBREAK">raw() and
288 <dt>4.3. <a href="#ECHONOECHO">echo() and
291 <dt>4.4. <a href="#KEYPAD">keypad()</a></dt>
293 <dt>4.5. <a href="#HALFDELAY">halfdelay()</a></dt>
295 <dt>4.6. <a href="#MISCINIT">Miscellaneous
296 Initialization functions</a></dt>
298 <dt>4.7. <a href="#INITEX">An Example</a></dt>
302 <dt>5. <a href="#AWORDWINDOWS">A Word about
305 <dt>6. <a href="#PRINTW">Output functions</a></dt>
309 <dt>6.1. <a href="#ADDCHCLASS">addch() class of
312 <dt>6.2. <a href="#AEN298">mvaddch(), waddch() and
315 <dt>6.3. <a href="#PRINTWCLASS">printw() class of
320 <dt>6.3.1. <a href="#PRINTWMVPRINTW">printw() and
323 <dt>6.3.2. <a href="#WPRINTWMVWPRINTW">wprintw()
324 and mvwprintw</a></dt>
326 <dt>6.3.3. <a href="#VWPRINTW">vw_printw()</a></dt>
328 <dt>6.3.4. <a href="#SIMPLEPRINTWEX">A Simple
329 printw example</a></dt>
333 <dt>6.4. <a href="#ADDSTRCLASS">addstr() class of
336 <dt>6.5. <a href="#ACAUTION">A word of caution</a></dt>
340 <dt>7. <a href="#SCANW">Input functions</a></dt>
344 <dt>7.1. <a href="#GETCHCLASS">getch() class of
347 <dt>7.2. <a href="#SCANWCLASS">scanw() class of
352 <dt>7.2.1. <a href="#SCANWMVSCANW">scanw() and
355 <dt>7.2.2. <a href="#WSCANWMVWSCANW">wscanw() and
358 <dt>7.2.3. <a href="#VWSCANW">vw_scanw()</a></dt>
362 <dt>7.3. <a href="#GETSTRCLASS">getstr() class of
365 <dt>7.4. <a href="#GETSTREX">Some examples</a></dt>
369 <dt>8. <a href="#ATTRIB">Attributes</a></dt>
373 <dt>8.1. <a href="#ATTRIBDETAILS">The details</a></dt>
375 <dt>8.2. <a href="#ATTRONVSATTRSET">attron() vs
378 <dt>8.3. <a href="#ATTRGET">attr_get()</a></dt>
380 <dt>8.4. <a href="#ATTRFUNCS">attr_ functions</a></dt>
382 <dt>8.5. <a href="#WATTRFUNCS">wattr functions</a></dt>
384 <dt>8.6. <a href="#CHGAT">chgat() functions</a></dt>
388 <dt>9. <a href="#WINDOWS">Windows</a></dt>
392 <dt>9.1. <a href="#WINDOWBASICS">The basics</a></dt>
394 <dt>9.2. <a href="#LETBEWINDOW">Let there be a Window
397 <dt>9.3. <a href="#BORDEREXEXPL">Explanation</a></dt>
399 <dt>9.4. <a href="#OTHERSTUFF">The other stuff in the
402 <dt>9.5. <a href="#OTHERBORDERFUNCS">Other Border
407 <dt>10. <a href="#COLOR">Colors</a></dt>
411 <dt>10.1. <a href="#COLORBASICS">The basics</a></dt>
413 <dt>10.2. <a href="#CHANGECOLORDEFS">Changing Color
416 <dt>10.3. <a href="#COLORCONTENT">Color
421 <dt>11. <a href="#KEYS">Interfacing with the key
426 <dt>11.1. <a href="#KEYSBASICS">The Basics</a></dt>
428 <dt>11.2. <a href="#SIMPLEKEYEX">A Simple Key Usage
433 <dt>12. <a href="#MOUSE">Interfacing with the
438 <dt>12.1. <a href="#MOUSEBASICS">The Basics</a></dt>
440 <dt>12.2. <a href="#GETTINGEVENTS">Getting the
443 <dt>12.3. <a href="#MOUSETOGETHER">Putting it all
446 <dt>12.4. <a href="#MISCMOUSEFUNCS">Miscellaneous
451 <dt>13. <a href="#SCREEN">Screen Manipulation</a></dt>
455 <dt>13.1. <a href="#GETYX">getyx() functions</a></dt>
457 <dt>13.2. <a href="#SCREENDUMP">Screen Dumping</a></dt>
459 <dt>13.3. <a href="#WINDOWDUMP">Window Dumping</a></dt>
463 <dt>14. <a href="#MISC">Miscellaneous features</a></dt>
467 <dt>14.1. <a href="#CURSSET">curs_set()</a></dt>
469 <dt>14.2. <a href="#TEMPLEAVE">Temporarily Leaving
472 <dt>14.3. <a href="#ACSVARS">ACS_ variables</a></dt>
476 <dt>15. <a href="#OTHERLIB">Other libraries</a></dt>
478 <dt>16. <a href="#PANELS">Panel Library</a></dt>
482 <dt>16.1. <a href="#PANELBASICS">The Basics</a></dt>
484 <dt>16.2. <a href="#COMPILEPANELS">Compiling With the
485 Panels Library</a></dt>
487 <dt>16.3. <a href="#PANELBROWSING">Panel Window
490 <dt>16.4. <a href="#USERPTRUSING">Using User
493 <dt>16.5. <a href="#PANELMOVERESIZE">Moving and
494 Resizing Panels</a></dt>
496 <dt>16.6. <a href="#PANELSHOWHIDE">Hiding and Showing
499 <dt>16.7. <a href="#PANELABOVE">panel_above() and
500 panel_below() Functions</a></dt>
504 <dt>17. <a href="#MENUS">Menus Library</a></dt>
508 <dt>17.1. <a href="#MENUBASICS">The Basics</a></dt>
510 <dt>17.2. <a href="#COMPILEMENUS">Compiling With the
511 Menu Library</a></dt>
513 <dt>17.3. <a href="#MENUDRIVER">Menu Driver: The work
514 horse of the menu system</a></dt>
516 <dt>17.4. <a href="#MENUWINDOWS">Menu Windows</a></dt>
518 <dt>17.5. <a href="#SCROLLMENUS">Scrolling
521 <dt>17.6. <a href="#MULTICOLUMN">Multi Columnar
524 <dt>17.7. <a href="#MULTIVALUEMENUS">Multi Valued
527 <dt>17.8. <a href="#MENUOPT">Menu Options</a></dt>
529 <dt>17.9. <a href="#MENUUSERPTR">The useful User
534 <dt>18. <a href="#FORMS">Forms Library</a></dt>
538 <dt>18.1. <a href="#FORMBASICS">The Basics</a></dt>
540 <dt>18.2. <a href="#COMPILEFORMS">Compiling With the
541 Forms Library</a></dt>
543 <dt>18.3. <a href="#PLAYFIELDS">Playing with
548 <dt>18.3.1. <a href="#FETCHINFO">Fetching Size and
549 Location of Field</a></dt>
551 <dt>18.3.2. <a href="#MOVEFIELD">Moving the
554 <dt>18.3.3. <a href="#JUSTIFYFIELD">Field
555 Justification</a></dt>
557 <dt>18.3.4. <a href="#FIELDDISPATTRIB">Field
558 Display Attributes</a></dt>
560 <dt>18.3.5. <a href="#FIELDOPTIONBITS">Field Option
563 <dt>18.3.6. <a href="#FIELDSTATUS">Field
566 <dt>18.3.7. <a href="#FIELDUSERPTR">Field User
570 "#VARIABLESIZEFIELDS">Variable-Sized
575 <dt>18.4. <a href="#FORMWINDOWS">Form Windows</a></dt>
577 <dt>18.5. <a href="#FILEDVALIDATE">Field
580 <dt>18.6. <a href="#FORMDRIVER">Form Driver: The work
581 horse of the forms system</a></dt>
585 <dt>18.6.1. <a href="#PAGENAVREQ">Page Navigation
588 <dt>18.6.2. <a href="#INTERFIELDNAVREQ">Inter-Field
589 Navigation Requests</a></dt>
591 <dt>18.6.3. <a href="#INTRAFIELDNAVREQ">Intra-Field
592 Navigation Requests</a></dt>
594 <dt>18.6.4. <a href="#SCROLLREQ">Scrolling
597 <dt>18.6.5. <a href="#EDITREQ">Editing
600 <dt>18.6.6. <a href="#ORDERREQ">Order
603 <dt>18.6.7. <a href="#APPLICCOMMANDS">Application
610 <dt>19. <a href="#TOOLS">Tools and Widget
615 <dt>19.1. <a href="#CDK">CDK (Curses Development
620 <dt>19.1.1. <a href="#WIDGETLIST">Widget
623 <dt>19.1.2. <a href="#CDKATTRACT">Some Attractive
627 "#CDKCONCLUSION">Conclusion</a></dt>
631 <dt>19.2. <a href="#DIALOG">The dialog</a></dt>
633 <dt>19.3. <a href="#PERLCURSES">Perl Curses Modules
634 CURSES::FORM and CURSES::WIDGETS</a></dt>
638 <dt>20. <a href="#JUSTFORFUN">Just For Fun !!!</a></dt>
642 <dt>20.1. <a href="#GAMEOFLIFE">The Game of
645 <dt>20.2. <a href="#MAGIC">Magic Square</a></dt>
647 <dt>20.3. <a href="#HANOI">Towers of Hanoi</a></dt>
649 <dt>20.4. <a href="#QUEENS">Queens Puzzle</a></dt>
651 <dt>20.5. <a href="#SHUFFLE">Shuffle</a></dt>
653 <dt>20.6. <a href="#TT">Typing Tutor</a></dt>
657 <dt>21. <a href="#REF">References</a></dt>
662 <h2 class="SECT1"><a name="INTRO" id="INTRO">1.
663 Introduction</a></h2>
665 <p>In the olden days of teletype terminals, terminals were
666 away from computers and were connected to them through serial
667 cables. The terminals could be configured by sending a series
668 of bytes. All the capabilities (such as moving the cursor to
669 a new location, erasing part of the screen, scrolling the
670 screen, changing modes etc.) of terminals could be accessed
671 through these series of bytes. These control seeuqnces are
672 usually called escape sequences, because they start with an
673 escape(0x1B) character. Even today, with proper emulation, we
674 can send escape sequences to the emulator and achieve the
675 same effect on a terminal window.</p>
677 <p>Suppose you wanted to print a line in color. Try typing
678 this on your console.</p>
679 <pre class="PROGRAMLISTING">
680 echo "^[[0;31;40mIn Color"
683 <p>The first character is an escape character, which looks
684 like two characters ^ and [. To be able to print it, you have
685 to press CTRL+V and then the ESC key. All the others are
686 normal printable characters. You should be able to see the
687 string "In Color" in red. It stays that way and to revert
688 back to the original mode type this.</p>
689 <pre class="PROGRAMLISTING">
693 <p>Now, what do these magic characters mean? Difficult to
694 comprehend? They might even be different for different
695 terminals. So the designers of UNIX invented a mechanism
696 named <tt class="LITERAL">termcap</tt>. It is a file that
697 lists all the capabilities of a particular terminal, along
698 with the escape sequences needed to achieve a particular
699 effect. In the later years, this was replaced by <tt class=
700 "LITERAL">terminfo</tt>. Without delving too much into
701 details, this mechanism allows application programs to query
702 the terminfo database and obtain the control characters to be
703 sent to a terminal or terminal emulator.</p>
708 <h3 class="SECT2"><a name="WHATIS" id="WHATIS">1.1. What is
711 <p>You might be wondering, what the import of all this
712 technical gibberish is. In the above scenario, every
713 application program is supposed to query the terminfo and
714 perform the necessary stuff (sending control characters
715 etc.). It soon became difficult to manage this complexity
716 and this gave birth to 'CURSES'. Curses is a pun on the
717 name "cursor optimization". The Curses library forms a
718 wrapper over working with raw terminal codes, and provides
719 highly flexible and efficient API (Application Programming
720 Interface). It provides functions to move the cursor,
721 create windows, produce colors, play with mouse etc. The
722 application programs need not worry about the underlying
723 terminal capabilities.</p>
725 <p>So what is NCURSES? NCURSES is a clone of the original
726 System V Release 4.0 (SVr4) curses. It is a freely
727 distributable library, fully compatible with older version
728 of curses. In short, it is a library of functions that
729 manages an application's display on character-cell
730 terminals. In the remainder of the document, the terms
731 curses and ncurses are used interchangeably.</p>
733 <p>A detailed history of NCURSES can be found in the NEWS
734 file from the source distribution. The current package is
735 maintained by <a href="mailto:dickey@his.com" target=
736 "_top">Thomas Dickey</a>. You can contact the maintainers
737 at <a href="mailto:bug-ncurses@gnu.org" target=
738 "_top">bug-ncurses@gnu.org</a>.</p>
744 <h3 class="SECT2"><a name="WHATCANWEDO" id=
745 "WHATCANWEDO">1.2. What we can do with NCURSES</a></h3>
747 <p>NCURSES not only creates a wrapper over terminal
748 capabilities, but also gives a robust framework to create
749 nice looking UI (User Interface)s in text mode. It provides
750 functions to create windows etc. Its sister libraries
751 panel, menu and form provide an extension to the basic
752 curses library. These libraries usually come along with
753 curses. One can create applications that contain multiple
754 windows, menus, panels and forms. Windows can be managed
755 independently, can provide 'scrollability' and even can be
758 <p>Menus provide the user with an easy command selection
759 option. Forms allow the creation of easy-to-use data entry
760 and display windows. Panels extend the capabilities of
761 ncurses to deal with overlapping and stacked windows.</p>
763 <p>These are just some of the basic things we can do with
764 ncurses. As we move along, We will see all the capabilities
765 of these libraries.</p>
771 <h3 class="SECT2"><a name="WHERETOGETIT" id=
772 "WHERETOGETIT">1.3. Where to get it</a></h3>
774 <p>All right, now that you know what you can do with
775 ncurses, you must be rearing to get started. NCURSES is
776 usually shipped with your installation. In case you don't
777 have the library or want to compile it on your own, read
780 <p><span class="emphasis"><i class="EMPHASIS">Compiling the
781 package</i></span></p>
783 <p>NCURSES can be obtained from <a href=
784 "ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz" target=
785 "_top">ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz</a>
786 or any of the ftp sites mentioned in <a href=
787 "http://www.gnu.org/order/ftp.html" target=
788 "_top">http://www.gnu.org/order/ftp.html</a>.</p>
790 <p>Read the README and INSTALL files for details on to how
791 to install it. It usually involves the following
793 <pre class="PROGRAMLISTING">
794 tar zxvf ncurses<version>.tar.gz # unzip and untar the archive
795 cd ncurses<version> # cd to the directory
796 ./configure # configure the build according to your
799 su root # become root
800 make install # install it
803 <p><span class="emphasis"><i class="EMPHASIS">Using the
806 <p>NCURSES RPM can be found and downloaded from <a href=
807 "http://rpmfind.net" target="_top">http://rpmfind.net</a> .
808 The RPM can be installed with the following command after
810 <pre class="PROGRAMLISTING">
811 rpm -i <downloaded rpm>
818 <h3 class="SECT2"><a name="PURPOSE" id="PURPOSE">1.4.
819 Purpose/Scope of the document</a></h3>
821 <p>This document is intended to be a "All in One" guide for
822 programming with ncurses and its sister libraries. We
823 graduate from a simple "Hello World" program to more
824 complex form manipulation. No prior experience in ncurses
825 is assumed. The writing is informal, but a lot of detail is
826 provided for each of the examples.</p>
832 <h3 class="SECT2"><a name="ABOUTPROGRAMS" id=
833 "ABOUTPROGRAMS">1.5. About the Programs</a></h3>
835 <p>All the programs in the document are available in zipped
837 "http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs.tar.gz"
838 target="_top">here</a>. Unzip and untar it. The directory
839 structure looks like this.</p>
840 <pre class="PROGRAMLISTING">
843 |----> JustForFun -- just for fun programs
844 |----> basics -- basic programs
845 |----> demo -- output files go into this directory after make
847 | |----> exe -- exe files of all example programs
848 |----> forms -- programs related to form library
849 |----> menus -- programs related to menus library
850 |----> panels -- programs related to panels library
851 |----> perl -- perl equivalents of the examples (contributed
852 | by Anuradha Ratnaweera)
853 |----> Makefile -- the top level Makefile
854 |----> README -- the top level README file. contains instructions
855 |----> COPYING -- copyright notice
858 <p>The individual directories contain the following
860 <pre class="PROGRAMLISTING">
861 Description of files in each directory
862 --------------------------------------
865 |----> hanoi.c -- The Towers of Hanoi Solver
866 |----> life.c -- The Game of Life demo
867 |----> magic.c -- An Odd Order Magic Square builder
868 |----> queens.c -- The famous N-Queens Solver
869 |----> shuffle.c -- A fun game, if you have time to kill
870 |----> tt.c -- A very trivial typing tutor
874 |----> acs_vars.c -- ACS_ variables example
875 |----> hello_world.c -- Simple "Hello World" Program
876 |----> init_func_example.c -- Initialization functions example
877 |----> key_code.c -- Shows the scan code of the key pressed
878 |----> mouse_menu.c -- A menu accessible by mouse
879 |----> other_border.c -- Shows usage of other border functions apa
881 |----> printw_example.c -- A very simple printw() example
882 |----> scanw_example.c -- A very simple getstr() example
883 |----> simple_attr.c -- A program that can print a c file with
884 | -- comments in attribute
885 |----> simple_color.c -- A simple example demonstrating colors
886 |----> simple_key.c -- A menu accessible with keyboard UP, DOWN
888 |----> temp_leave.c -- Demonstrates temporarily leaving curses mode
889 |----> win_border.c -- Shows Creation of windows and borders
890 |----> with_chgat.c -- chgat() usage example
894 |----> form_attrib.c -- Usage of field attributes
895 |----> form_options.c -- Usage of field options
896 |----> form_simple.c -- A simple form example
897 |----> form_win.c -- Demo of windows associated with forms
901 |----> menu_attrib.c -- Usage of menu attributes
902 |----> menu_item_data.c -- Usage of item_name() etc.. functions
903 |----> menu_multi_column.c -- Creates multi columnar menus
904 |----> menu_scroll.c -- Demonstrates scrolling capability of menus
905 |----> menu_simple.c -- A simple menu accessed by arrow keys
906 |----> menu_toggle.c -- Creates multi valued menus and explains
908 |----> menu_userptr.c -- Usage of user pointer
909 |----> menu_win.c -- Demo of windows associated with menus
913 |----> panel_browse.c -- Panel browsing through tab. Usage of user
915 |----> panel_hide.c -- Hiding and Un hiding of panels
916 |----> panel_resize.c -- Moving and resizing of panels
917 |----> panel_simple.c -- A simple panel example
920 |----> 01-10.pl -- Perl equivalents of first ten example programs
923 <p>There is a top level Makefile included in the main
924 directory. It builds all the files and puts the
925 ready-to-use exes in demo/exe directory. You can also do
926 selective make by going into the corresponding directory.
927 Each directory contains a README file explaining the
928 purpose of each c file in the directory.</p>
930 <p>For every example, I have included path name for the
931 file relative to the examples directory.</p>
933 <p>If you prefer browsing individual programs, point your
935 "http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/"
937 "_top">http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/</a></p>
939 <p>All the programs are released under the same license
940 that is used by ncurses (MIT-style). This gives you the
941 ability to do pretty much anything other than claiming them
942 as yours. Feel free to use them in your programs as
949 <h3 class="SECT2"><a name="OTHERFORMATS" id=
950 "OTHERFORMATS">1.6. Other Formats of the document</a></h3>
952 <p>This howto is also availabe in various other formats on
953 the tldp.org site. Here are the links to other formats of
959 <h4 class="SECT3"><a name="LISTFORMATS" id=
960 "LISTFORMATS">1.6.1. Readily available formats from
966 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/pdf/NCURSES-Programming-HOWTO.pdf"
967 target="_top">Acrobat PDF Format</a></p>
972 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/ps/NCURSES-Programming-HOWTO.ps.gz"
973 target="_top">PostScript Format</a></p>
978 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html/NCURSES-Programming-HOWTO-html.tar.gz"
979 target="_top">In Multiple HTML pages</a></p>
984 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/NCURSES-Programming-HOWTO.html"
985 target="_top">In One big HTML format</a></p>
993 <h4 class="SECT3"><a name="BUILDSOURCE" id=
994 "BUILDSOURCE">1.6.2. Building from source</a></h4>
996 <p>If above links are broken or if you want to experiment
997 with sgml read on.</p>
998 <pre class="PROGRAMLISTING">
999 Get both the source and the tar,gzipped programs, available at
1000 http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
1001 NCURSES-HOWTO/NCURSES-Programming-HOWTO.sgml
1002 http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
1003 NCURSES-HOWTO/ncurses_programs.tar.gz
1005 Unzip ncurses_programs.tar.gz with
1006 tar zxvf ncurses_programs.tar.gz
1008 Use jade to create various formats. For example if you just want to create
1009 the multiple html files, you would use
1010 jade -t sgml -i html -d <path to docbook html stylesheet>
1011 NCURSES-Programming-HOWTO.sgml
1012 to get pdf, first create a single html file of the HOWTO with
1013 jade -t sgml -i html -d <path to docbook html stylesheet> -V nochunks
1014 NCURSES-Programming-HOWTO.sgml > NCURSES-ONE-BIG-FILE.html
1015 then use htmldoc to get pdf file with
1016 htmldoc --size universal -t pdf --firstpage p1 -f <output file name.pdf>
1017 NCURSES-ONE-BIG-FILE.html
1018 for ps, you would use
1019 htmldoc --size universal -t ps --firstpage p1 -f <output file name.ps>
1020 NCURSES-ONE-BIG-FILE.html
1024 "http://www.tldp.org/LDP/LDP-Author-Guide/" target=
1025 "_top">LDP Author guide</a> for more details. If all else
1026 failes, mail me at <a href="ppadala@gmail.com" target=
1027 "_top">ppadala@gmail.com</a></p>
1034 <h3 class="SECT2"><a name="CREDITS" id="CREDITS">1.7.
1037 <p>I thank <a href="mailto:sharath_1@usa.net" target=
1038 "_top">Sharath</a> and Emre Akbas for helping me with few
1039 sections. The introduction was initially written by
1040 sharath. I rewrote it with few excerpts taken from his
1041 initial work. Emre helped in writing printw and scanw
1044 <p>Perl equivalents of the example programs are contributed
1045 by <a href="mailto:Aratnaweera@virtusa.com" target=
1046 "_top">Anuradha Ratnaweera</a>.</p>
1048 <p>Then comes <a href="mailto:parimi@ece.arizona.edu"
1049 target="_top">Ravi Parimi</a>, my dearest friend, who has
1050 been on this project before even one line was written. He
1051 constantly bombarded me with suggestions and patiently
1052 reviewed the whole text. He also checked each program on
1053 Linux and Solaris.</p>
1059 <h3 class="SECT2"><a name="WISHLIST" id="WISHLIST">1.8.
1062 <p>This is the wish list, in the order of priority. If you
1063 have a wish or you want to work on completing the wish,
1064 mail <a href="mailto:ppadala@gmail.com" target=
1069 <p>Add examples to last parts of forms section.</p>
1073 <p>Prepare a Demo showing all the programs and allow
1074 the user to browse through description of each program.
1075 Let the user compile and see the program in action. A
1076 dialog based interface is preferred.</p>
1080 <p>Add debug info. _tracef, _tracemouse stuff.</p>
1084 <p>Accessing termcap, terminfo using functions provided
1085 by ncurses package.</p>
1089 <p>Working on two terminals simultaneously.</p>
1093 <p>Add more stuff to miscellaneous section.</p>
1101 <h3 class="SECT2"><a name="COPYRIGHT" id="COPYRIGHT">1.9.
1104 <p>Copyright © 2001 by Pradeep Padala.</p>
1106 <p>Permission is hereby granted, free of charge, to any
1107 person obtaining a copy of this software and associated
1108 documentation files (the "Software"), to deal in the
1109 Software without restriction, including without limitation
1110 the rights to use, copy, modify, merge, publish,
1111 distribute, distribute with modifications, sublicense,
1112 and/or sell copies of the Software, and to permit persons
1113 to whom the Software is furnished to do so, subject to the
1114 following conditions:</p>
1116 <p>The above copyright notice and this permission notice
1117 shall be included in all copies or substantial portions of
1120 <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
1121 ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
1122 THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
1123 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ABOVE
1124 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1125 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
1126 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
1127 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p>
1129 <p>Except as contained in this notice, the name(s) of the
1130 above copyright holders shall not be used in advertising or
1131 otherwise to promote the sale, use or other dealings in
1132 this Software without prior written authorization.</p>
1139 <h2 class="SECT1"><a name="HELLOWORLD" id="HELLOWORLD">2.
1140 Hello World !!!</a></h2>
1142 <p>Welcome to the world of curses. Before we plunge into the
1143 library and look into its various features, let's write a
1144 simple program and say hello to the world.</p>
1149 <h3 class="SECT2"><a name="COMPILECURSES" id=
1150 "COMPILECURSES">2.1. Compiling With the NCURSES
1153 <p>To use ncurses library functions, you have to include
1154 ncurses.h in your programs. To link the program with
1155 ncurses the flag -lncurses should be added.</p>
1156 <pre class="PROGRAMLISTING">
1157 #include <ncurses.h>
1162 compile and link: gcc <program file> -lncurses
1165 <div class="EXAMPLE">
1166 <a name="BHW" id="BHW"></a>
1168 <p><b>Example 1. The Hello World !!! Program</b></p>
1169 <pre class="PROGRAMLISTING">
1170 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
1174 initscr(); /* Start curses mode */
1175 printw("Hello World !!!"); /* Print Hello World */
1176 refresh(); /* Print it on to the real screen */
1177 getch(); /* Wait for user input */
1178 endwin(); /* End curses mode */
1189 <h3 class="SECT2"><a name="DISSECTION" id="DISSECTION">2.2.
1192 <p>The above program prints "Hello World !!!" to the screen
1193 and exits. This program shows how to initialize curses and
1194 do screen manipulation and end curses mode. Let's dissect
1195 it line by line.</p>
1200 <h4 class="SECT3"><a name="ABOUT-INITSCR" id=
1201 "ABOUT-INITSCR">2.2.1. About initscr()</a></h4>
1203 <p>The function initscr() initializes the terminal in
1204 curses mode. In some implementations, it clears the
1205 screen and presents a blank screen. To do any screen
1206 manipulation using curses package this has to be called
1207 first. This function initializes the curses system and
1208 allocates memory for our present window (called
1209 <tt class="LITERAL">stdscr</tt>) and some other
1210 data-structures. Under extreme cases this function might
1211 fail due to insufficient memory to allocate memory for
1212 curses library's data structures.</p>
1214 <p>After this is done, we can do a variety of
1215 initializations to customize our curses settings. These
1216 details will be explained <a href="#INIT">later</a> .</p>
1222 <h4 class="SECT3"><a name="MYST-REFRESH" id=
1223 "MYST-REFRESH">2.2.2. The mysterious refresh()</a></h4>
1225 <p>The next line printw prints the string "Hello World
1226 !!!" on to the screen. This function is analogous to
1227 normal printf in all respects except that it prints the
1228 data on a window called stdscr at the current (y,x)
1229 co-ordinates. Since our present co-ordinates are at 0,0
1230 the string is printed at the left hand corner of the
1233 <p>This brings us to that mysterious refresh(). Well,
1234 when we called printw the data is actually written to an
1235 imaginary window, which is not updated on the screen yet.
1236 The job of printw is to update a few flags and data
1237 structures and write the data to a buffer corresponding
1238 to stdscr. In order to show it on the screen, we need to
1239 call refresh() and tell the curses system to dump the
1240 contents on the screen.</p>
1242 <p>The philosophy behind all this is to allow the
1243 programmer to do multiple updates on the imaginary screen
1244 or windows and do a refresh once all his screen update is
1245 done. refresh() checks the window and updates only the
1246 portion which has been changed. This improves performance
1247 and offers greater flexibility too. But, it is sometimes
1248 frustrating to beginners. A common mistake committed by
1249 beginners is to forget to call refresh() after they did
1250 some update through printw() class of functions. I still
1251 forget to add it sometimes :-)</p>
1257 <h4 class="SECT3"><a name="ABOUT-ENDWIN" id=
1258 "ABOUT-ENDWIN">2.2.3. About endwin()</a></h4>
1260 <p>And finally don't forget to end the curses mode.
1261 Otherwise your terminal might behave strangely after the
1262 program quits. endwin() frees the memory taken by curses
1263 sub-system and its data structures and puts the terminal
1264 in normal mode. This function must be called after you
1265 are done with the curses mode.</p>
1273 <h2 class="SECT1"><a name="GORY" id="GORY">3. The Gory
1276 <p>Now that we have seen how to write a simple curses program
1277 let's get into the details. There are many functions that
1278 help customize what you see on screen and many features which
1279 can be put to full use.</p>
1281 <p>Here we go...</p>
1287 <h2 class="SECT1"><a name="INIT" id="INIT">4.
1288 Initialization</a></h2>
1290 <p>We now know that to initialize curses system the function
1291 initscr() has to be called. There are functions which can be
1292 called after this initialization to customize our curses
1293 session. We may ask the curses system to set the terminal in
1294 raw mode or initialize color or initialize the mouse etc..
1295 Let's discuss some of the functions that are normally called
1296 immediately after initscr();</p>
1301 <h3 class="SECT2"><a name="ABOUTINIT" id="ABOUTINIT">4.1.
1302 Initialization functions</a></h3>
1308 <h3 class="SECT2"><a name="RAWCBREAK" id="RAWCBREAK">4.2.
1309 raw() and cbreak()</a></h3>
1311 <p>Normally the terminal driver buffers the characters a
1312 user types until a new line or carriage return is
1313 encountered. But most programs require that the characters
1314 be available as soon as the user types them. The above two
1315 functions are used to disable line buffering. The
1316 difference between these two functions is in the way
1317 control characters like suspend (CTRL-Z), interrupt and
1318 quit (CTRL-C) are passed to the program. In the raw() mode
1319 these characters are directly passed to the program without
1320 generating a signal. In the <tt class=
1321 "LITERAL">cbreak()</tt> mode these control characters are
1322 interpreted as any other character by the terminal driver.
1323 I personally prefer to use raw() as I can exercise greater
1324 control over what the user does.</p>
1330 <h3 class="SECT2"><a name="ECHONOECHO" id="ECHONOECHO">4.3.
1331 echo() and noecho()</a></h3>
1333 <p>These functions control the echoing of characters typed
1334 by the user to the terminal. <tt class=
1335 "LITERAL">noecho()</tt> switches off echoing. The reason
1336 you might want to do this is to gain more control over
1337 echoing or to suppress unnecessary echoing while taking
1338 input from the user through the getch() etc. functions.
1339 Most of the interactive programs call <tt class=
1340 "LITERAL">noecho()</tt> at initialization and do the
1341 echoing of characters in a controlled manner. It gives the
1342 programmer the flexibility of echoing characters at any
1343 place in the window without updating current (y,x)
1350 <h3 class="SECT2"><a name="KEYPAD" id="KEYPAD">4.4.
1353 <p>This is my favorite initialization function. It enables
1354 the reading of function keys like F1, F2, arrow keys etc.
1355 Almost every interactive program enables this, as arrow
1356 keys are a major part of any User Interface. Do <tt class=
1357 "LITERAL">keypad(stdscr, TRUE)</tt> to enable this feature
1358 for the regular screen (stdscr). You will learn more about
1359 key management in later sections of this document.</p>
1365 <h3 class="SECT2"><a name="HALFDELAY" id="HALFDELAY">4.5.
1366 halfdelay()</a></h3>
1368 <p>This function, though not used very often, is a useful
1369 one at times. halfdelay()is called to enable the half-delay
1370 mode, which is similar to the cbreak() mode in that
1371 characters typed are immediately available to program.
1372 However, it waits for 'X' tenths of a second for input and
1373 then returns ERR, if no input is available. 'X' is the
1374 timeout value passed to the function halfdelay(). This
1375 function is useful when you want to ask the user for input,
1376 and if he doesn't respond with in certain time, we can do
1377 some thing else. One possible example is a timeout at the
1378 password prompt.</p>
1384 <h3 class="SECT2"><a name="MISCINIT" id="MISCINIT">4.6.
1385 Miscellaneous Initialization functions</a></h3>
1387 <p>There are few more functions which are called at
1388 initialization to customize curses behavior. They are not
1389 used as extensively as those mentioned above. Some of them
1390 are explained where appropriate.</p>
1396 <h3 class="SECT2"><a name="INITEX" id="INITEX">4.7. An
1399 <p>Let's write a program which will clarify the usage of
1400 these functions.</p>
1402 <div class="EXAMPLE">
1403 <a name="BINFU" id="BINFU"></a>
1405 <p><b>Example 2. Initialization Function Usage
1407 <pre class="PROGRAMLISTING">
1408 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
1413 initscr(); /* Start curses mode */
1414 raw(); /* Line buffering disabled */
1415 keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
1416 noecho(); /* Don't echo() while we do getch */
1418 printw("Type any character to see it in bold\n");
1419 ch = getch(); /* If raw() hadn't been called
1420 * we have to press enter before it
1421 * gets to the program */
1422 if(ch == KEY_F(1)) /* Without keypad enabled this will */
1423 printw("F1 Key pressed");/* not get to us either */
1424 /* Without noecho() some ugly escape
1425 * charachters might have been printed
1428 { printw("The pressed key is ");
1433 refresh(); /* Print it on to the real screen */
1434 getch(); /* Wait for user input */
1435 endwin(); /* End curses mode */
1442 <p>This program is self-explanatory. But I used functions
1443 which aren't explained yet. The function <tt class=
1444 "LITERAL">getch()</tt> is used to get a character from
1445 user. It is equivalent to normal <tt class=
1446 "LITERAL">getchar()</tt> except that we can disable the
1447 line buffering to avoid <enter> after input. Look for
1448 more about <tt class="LITERAL">getch()</tt>and reading keys
1449 in the <a href="#KEYS">key management section</a> . The
1450 functions attron and attroff are used to switch some
1451 attributes on and off respectively. In the example I used
1452 them to print the character in bold. These functions are
1453 explained in detail later.</p>
1460 <h2 class="SECT1"><a name="AWORDWINDOWS" id="AWORDWINDOWS">5.
1461 A Word about Windows</a></h2>
1463 <p>Before we plunge into the myriad ncurses functions, let me
1464 clear few things about windows. Windows are explained in
1465 detail in following <a href="#WINDOWS">sections</a></p>
1467 <p>A Window is an imaginary screen defined by curses system.
1468 A window does not mean a bordered window which you usually
1469 see on Win9X platforms. When curses is initialized, it
1470 creates a default window named <tt class=
1471 "LITERAL">stdscr</tt> which represents your 80x25 (or the
1472 size of window in which you are running) screen. If you are
1473 doing simple tasks like printing few strings, reading input
1474 etc., you can safely use this single window for all of your
1475 purposes. You can also create windows and call functions
1476 which explicitly work on the specified window.</p>
1478 <p>For example, if you call</p>
1479 <pre class="PROGRAMLISTING">
1480 printw("Hi There !!!");
1484 <p>It prints the string on stdscr at the present cursor
1485 position. Similarly the call to refresh(), works on stdscr
1488 <p>Say you have created <a href="#WINDOWS">windows</a> then
1489 you have to call a function with a 'w' added to the usual
1491 <pre class="PROGRAMLISTING">
1492 wprintw(win, "Hi There !!!");
1496 <p>As you will see in the rest of the document, naming of
1497 functions follow the same convention. For each function there
1498 usually are three more functions.</p>
1499 <pre class="PROGRAMLISTING">
1500 printw(string); /* Print on stdscr at present cursor position */
1501 mvprintw(y, x, string);/* Move to (y, x) then print string */
1502 wprintw(win, string); /* Print on window win at present cursor position */
1504 mvwprintw(win, y, x, string); /* Move to (y, x) relative to window */
1505 /* co-ordinates and then print */
1508 <p>Usually the w-less functions are macros which expand to
1509 corresponding w-function with stdscr as the window
1516 <h2 class="SECT1"><a name="PRINTW" id="PRINTW">6. Output
1519 <p>I guess you can't wait any more to see some action. Back
1520 to our odyssey of curses functions. Now that curses is
1521 initialized, let's interact with world.</p>
1523 <p>There are three classes of functions which you can use to
1524 do output on screen.</p>
1528 <p>addch() class: Print single character with
1533 <p>printw() class: Print formatted output similar to
1538 <p>addstr() class: Print strings</p>
1542 <p>These functions can be used interchangeably and it's a
1543 matter of style as to which class is used. Let's see each one
1549 <h3 class="SECT2"><a name="ADDCHCLASS" id="ADDCHCLASS">6.1.
1550 addch() class of functions</a></h3>
1552 <p>These functions put a single character into the current
1553 cursor location and advance the position of the cursor. You
1554 can give the character to be printed but they usually are
1555 used to print a character with some attributes. Attributes
1556 are explained in detail in later <a href=
1557 "#ATTRIB">sections</a> of the document. If a character is
1558 associated with an attribute(bold, reverse video etc.),
1559 when curses prints the character, it is printed in that
1562 <p>In order to combine a character with some attributes,
1563 you have two options:</p>
1567 <p>By OR'ing a single character with the desired
1568 attribute macros. These attribute macros could be found
1569 in the header file <tt class="LITERAL">ncurses.h</tt>.
1570 For example, you want to print a character ch(of type
1571 char) bold and underlined, you would call addch() as
1573 <pre class="PROGRAMLISTING">
1574 addch(ch | A_BOLD | A_UNDERLINE);
1579 <p>By using functions like <tt class=
1580 "LITERAL">attrset(),attron(),attroff()</tt>. These
1581 functions are explained in the <a href=
1582 "#ATTRIB">Attributes</a> section. Briefly, they
1583 manipulate the current attributes of the given window.
1584 Once set, the character printed in the window are
1585 associated with the attributes until it is turned
1590 <p>Additionally, <tt class="LITERAL">curses</tt> provides
1591 some special characters for character-based graphics. You
1592 can draw tables, horizontal or vertical lines, etc. You can
1593 find all avaliable characters in the header file <tt class=
1594 "LITERAL">ncurses.h</tt>. Try looking for macros beginning
1595 with <tt class="LITERAL">ACS_</tt> in this file.</p>
1601 <h3 class="SECT2"><a name="AEN298" id="AEN298">6.2.
1602 mvaddch(), waddch() and mvwaddch()</a></h3>
1604 <p><tt class="LITERAL">mvaddch()</tt> is used to move the
1605 cursor to a given point, and then print. Thus, the
1607 <pre class="PROGRAMLISTING">
1608 move(row,col); /* moves the cursor to row<span class=
1609 "emphasis"><i class=
1610 "EMPHASIS">th</i></span> row and col<span class="emphasis"><i class="EMPHASIS">th</i></span> column */
1612 </pre>can be replaced by
1613 <pre class="PROGRAMLISTING">
1614 mvaddch(row,col,ch);
1617 <p><tt class="LITERAL">waddch()</tt> is similar to
1618 <tt class="LITERAL">addch()</tt>, except that it adds a
1619 character into the given window. (Note that <tt class=
1620 "LITERAL">addch()</tt> adds a character into the window
1621 <tt class="LITERAL">stdscr</tt>.)</p>
1623 <p>In a similar fashion <tt class="LITERAL">mvwaddch()</tt>
1624 function is used to add a character into the given window
1625 at the given coordinates.</p>
1627 <p>Now, we are familiar with the basic output function
1628 <tt class="LITERAL">addch()</tt>. But, if we want to print
1629 a string, it would be very annoying to print it character
1630 by character. Fortunately, <tt class="LITERAL">ncurses</tt>
1631 provides <tt class="LITERAL">printf</tt><span class=
1632 "emphasis"><i class="EMPHASIS">-like</i></span> or
1633 <tt class="LITERAL">puts</tt><span class=
1634 "emphasis"><i class="EMPHASIS">-like</i></span>
1641 <h3 class="SECT2"><a name="PRINTWCLASS" id=
1642 "PRINTWCLASS">6.3. printw() class of functions</a></h3>
1644 <p>These functions are similar to <tt class=
1645 "LITERAL">printf()</tt> with the added capability of
1646 printing at any position on the screen.</p>
1651 <h4 class="SECT3"><a name="PRINTWMVPRINTW" id=
1652 "PRINTWMVPRINTW">6.3.1. printw() and mvprintw</a></h4>
1654 <p>These two functions work much like <tt class=
1655 "LITERAL">printf()</tt>. <tt class=
1656 "LITERAL">mvprintw()</tt> can be used to move the cursor
1657 to a position and then print. If you want to move the
1658 cursor first and then print using <tt class=
1659 "LITERAL">printw()</tt> function, use <tt class=
1660 "LITERAL">move()</tt> first and then use <tt class=
1661 "LITERAL">printw()</tt> though I see no point why one
1662 should avoid using <tt class="LITERAL">mvprintw()</tt>,
1663 you have the flexibility to manipulate.</p>
1669 <h4 class="SECT3"><a name="WPRINTWMVWPRINTW" id=
1670 "WPRINTWMVWPRINTW">6.3.2. wprintw() and
1673 <p>These two functions are similar to above two except
1674 that they print in the corresponding window given as
1681 <h4 class="SECT3"><a name="VWPRINTW" id="VWPRINTW">6.3.3.
1682 vw_printw()</a></h4>
1684 <p>This function is similar to <tt class=
1685 "LITERAL">vprintf()</tt>. This can be used when variable
1686 number of arguments are to be printed.</p>
1692 <h4 class="SECT3"><a name="SIMPLEPRINTWEX" id=
1693 "SIMPLEPRINTWEX">6.3.4. A Simple printw example</a></h4>
1695 <div class="EXAMPLE">
1696 <a name="BPREX" id="BPREX"></a>
1698 <p><b>Example 3. A Simple printw example</b></p>
1699 <pre class="PROGRAMLISTING">
1701 "INLINEMEDIAOBJECT">#include <ncurses.h> /* ncurses.h includes stdio.h */
1702 #include <string.h>
1706 char mesg[]="Just a string"; /* message to be appeared on the screen */
1707 int row,col; /* to store the number of rows and *
1708 * the number of colums of the screen */
1709 initscr(); /* start the curses mode */
1710 getmaxyx(stdscr,row,col); /* get the number of rows and columns */
1711 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
1712 /* print the message at the center of the screen */
1713 mvprintw(row-2,0,"This screen has %d rows and %d columns\n",row,col);
1714 printw("Try resizing your window(if possible) and then run this program again");
1724 <p>Above program demonstrates how easy it is to use
1725 <tt class="LITERAL">printw</tt>. You just feed the
1726 coordinates and the message to be appeared on the screen,
1727 then it does what you want.</p>
1729 <p>The above program introduces us to a new function
1730 <tt class="LITERAL">getmaxyx()</tt>, a macro defined in
1731 <tt class="LITERAL">ncurses.h</tt>. It gives the number
1732 of columns and the number of rows in a given window.
1733 <tt class="LITERAL">getmaxyx()</tt> does this by updating
1734 the variables given to it. Since <tt class=
1735 "LITERAL">getmaxyx()</tt> is not a function we don't pass
1736 pointers to it, we just give two integer variables.</p>
1743 <h3 class="SECT2"><a name="ADDSTRCLASS" id=
1744 "ADDSTRCLASS">6.4. addstr() class of functions</a></h3>
1746 <p><tt class="LITERAL">addstr()</tt> is used to put a
1747 character string into a given window. This function is
1748 similar to calling <tt class="LITERAL">addch()</tt> once
1749 for each character in a given string. This is true for all
1750 output functions. There are other functions from this
1751 family such as <tt class=
1752 "LITERAL">mvaddstr(),mvwaddstr()</tt> and <tt class=
1753 "LITERAL">waddstr()</tt>, which obey the naming convention
1754 of curses.(e.g. mvaddstr() is similar to the respective
1755 calls move() and then addstr().) Another function of this
1756 family is addnstr(), which takes an integer parameter(say
1757 n) additionally. This function puts at most n characters
1758 into the screen. If n is negative, then the entire string
1765 <h3 class="SECT2"><a name="ACAUTION" id="ACAUTION">6.5. A
1766 word of caution</a></h3>
1768 <p>All these functions take y co-ordinate first and then x
1769 in their arguments. A common mistake by beginners is to
1770 pass x,y in that order. If you are doing too many
1771 manipulations of (y,x) co-ordinates, think of dividing the
1772 screen into windows and manipulate each one separately.
1773 Windows are explained in the <a href="#WINDOWS">windows</a>
1781 <h2 class="SECT1"><a name="SCANW" id="SCANW">7. Input
1784 <p>Well, printing without taking input, is boring. Let's see
1785 functions which allow us to get input from user. These
1786 functions also can be divided into three categories.</p>
1790 <p>getch() class: Get a character</p>
1794 <p>scanw() class: Get formatted input</p>
1798 <p>getstr() class: Get strings</p>
1805 <h3 class="SECT2"><a name="GETCHCLASS" id="GETCHCLASS">7.1.
1806 getch() class of functions</a></h3>
1808 <p>These functions read a single character from the
1809 terminal. But there are several subtle facts to consider.
1810 For example if you don't use the function cbreak(), curses
1811 will not read your input characters contiguously but will
1812 begin read them only after a new line or an EOF is
1813 encountered. In order to avoid this, the cbreak() function
1814 must used so that characters are immediately available to
1815 your program. Another widely used function is noecho(). As
1816 the name suggests, when this function is set (used), the
1817 characters that are keyed in by the user will not show up
1818 on the screen. The two functions cbreak() and noecho() are
1819 typical examples of key management. Functions of this genre
1820 are explained in the <a href="#KEYS">key management
1827 <h3 class="SECT2"><a name="SCANWCLASS" id="SCANWCLASS">7.2.
1828 scanw() class of functions</a></h3>
1830 <p>These functions are similar to <tt class=
1831 "LITERAL">scanf()</tt> with the added capability of getting
1832 the input from any location on the screen.</p>
1837 <h4 class="SECT3"><a name="SCANWMVSCANW" id=
1838 "SCANWMVSCANW">7.2.1. scanw() and mvscanw</a></h4>
1840 <p>The usage of these functions is similar to that of
1841 <tt class="LITERAL">sscanf()</tt>, where the line to be
1842 scanned is provided by <tt class="LITERAL">wgetstr()</tt>
1843 function. That is, these functions call to <tt class=
1844 "LITERAL">wgetstr()</tt> function(explained below) and
1845 uses the resulting line for a scan.</p>
1851 <h4 class="SECT3"><a name="WSCANWMVWSCANW" id=
1852 "WSCANWMVWSCANW">7.2.2. wscanw() and mvwscanw()</a></h4>
1854 <p>These are similar to above two functions except that
1855 they read from a window, which is supplied as one of the
1856 arguments to these functions.</p>
1862 <h4 class="SECT3"><a name="VWSCANW" id="VWSCANW">7.2.3.
1865 <p>This function is similar to <tt class=
1866 "LITERAL">vscanf()</tt>. This can be used when a variable
1867 number of arguments are to be scanned.</p>
1874 <h3 class="SECT2"><a name="GETSTRCLASS" id=
1875 "GETSTRCLASS">7.3. getstr() class of functions</a></h3>
1877 <p>These functions are used to get strings from the
1878 terminal. In essence, this function performs the same task
1879 as would be achieved by a series of calls to <tt class=
1880 "LITERAL">getch()</tt> until a newline, carriage return, or
1881 end-of-file is received. The resulting string of characters
1882 are pointed to by <tt class="LITERAL">str</tt>, which is a
1883 character pointer provided by the user.</p>
1889 <h3 class="SECT2"><a name="GETSTREX" id="GETSTREX">7.4.
1890 Some examples</a></h3>
1892 <div class="EXAMPLE">
1893 <a name="BSCEX" id="BSCEX"></a>
1895 <p><b>Example 4. A Simple scanw example</b></p>
1896 <pre class="PROGRAMLISTING">
1898 "INLINEMEDIAOBJECT">#include <ncurses.h> /* ncurses.h includes stdio.h */
1899 #include <string.h>
1903 char mesg[]="Enter a string: "; /* message to be appeared on the screen */
1905 int row,col; /* to store the number of rows and *
1906 * the number of colums of the screen */
1907 initscr(); /* start the curses mode */
1908 getmaxyx(stdscr,row,col); /* get the number of rows and columns */
1909 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
1910 /* print the message at the center of the screen */
1912 mvprintw(LINES - 2, 0, "You Entered: %s", str);
1926 <h2 class="SECT1"><a name="ATTRIB" id="ATTRIB">8.
1929 <p>We have seen an example of how attributes can be used to
1930 print characters with some special effects. Attributes, when
1931 set prudently, can present information in an easy,
1932 understandable manner. The following program takes a C file
1933 as input and prints the file with comments in bold. Scan
1934 through the code.</p>
1936 <div class="EXAMPLE">
1937 <a name="BSIAT" id="BSIAT"></a>
1939 <p><b>Example 5. A Simple Attributes example</b></p>
1940 <pre class="PROGRAMLISTING">
1942 "INLINEMEDIAOBJECT">/* pager functionality by Joseph Spainhour" <spainhou@bellsouth.net> */
1943 #include <ncurses.h>
1944 #include <stdlib.h>
1946 int main(int argc, char *argv[])
1948 int ch, prev, row, col;
1955 printf("Usage: %s <a c file name>\n", argv[0]);
1958 fp = fopen(argv[1], "r");
1961 perror("Cannot open input file");
1964 initscr(); /* Start curses mode */
1965 getmaxyx(stdscr, row, col); /* find the boundaries of the screeen */
1966 while((ch = fgetc(fp)) != EOF) /* read the file till we reach the end */
1968 getyx(stdscr, y, x); /* get the current curser position */
1969 if(y == (row - 1)) /* are we are at the end of the screen */
1971 printw("<-Press Any Key->"); /* tell the user to press a key */
1973 clear(); /* clear the screen */
1974 move(0, 0); /* start at the beginning of the screen */
1976 if(prev == '/' && ch == '*') /* If it is / and * then only
1979 attron(A_BOLD); /* cut bold on */
1980 getyx(stdscr, y, x); /* get the current curser position */
1981 move(y, x - 1); /* back up one space */
1982 printw("%c%c", '/', ch); /* The actual printing is done here */
1987 if(prev == '*' && ch == '/')
1988 attroff(A_BOLD); /* Switch it off once we got *
1992 endwin(); /* End curses mode */
1999 <p>Don't worry about all those initialization and other crap.
2000 Concentrate on the while loop. It reads each character in the
2001 file and searches for the pattern /*. Once it spots the
2002 pattern, it switches the BOLD attribute on with <tt class=
2003 "LITERAL">attron()</tt> . When we get the pattern */ it is
2004 switched off by <tt class="LITERAL">attroff()</tt> .</p>
2006 <p>The above program also introduces us to two useful
2007 functions <tt class="LITERAL">getyx()</tt> and <tt class=
2008 "LITERAL">move()</tt>. The first function gets the
2009 co-ordinates of the present cursor into the variables y, x.
2010 Since getyx() is a macro we don't have to pass pointers to
2011 variables. The function <tt class="LITERAL">move()</tt> moves
2012 the cursor to the co-ordinates given to it.</p>
2014 <p>The above program is really a simple one which doesn't do
2015 much. On these lines one could write a more useful program
2016 which reads a C file, parses it and prints it in different
2017 colors. One could even extend it to other languages as
2023 <h3 class="SECT2"><a name="ATTRIBDETAILS" id=
2024 "ATTRIBDETAILS">8.1. The details</a></h3>
2026 <p>Let's get into more details of attributes. The functions
2027 <tt class="LITERAL">attron(), attroff(), attrset()</tt> ,
2028 and their sister functions <tt class=
2029 "LITERAL">attr_get()</tt> etc.. can be used to switch
2030 attributes on/off , get attributes and produce a colorful
2033 <p>The functions attron and attroff take a bit-mask of
2034 attributes and switch them on or off, respectively. The
2035 following video attributes, which are defined in
2036 <curses.h> can be passed to these functions.</p>
2037 <pre class="PROGRAMLISTING">
2039 A_NORMAL Normal display (no highlight)
2040 A_STANDOUT Best highlighting mode of the terminal.
2041 A_UNDERLINE Underlining
2042 A_REVERSE Reverse video
2045 A_BOLD Extra bright or bold
2046 A_PROTECT Protected mode
2047 A_INVIS Invisible or blank mode
2048 A_ALTCHARSET Alternate character set
2049 A_CHARTEXT Bit-mask to extract a character
2050 COLOR_PAIR(n) Color-pair number n
2054 <p>The last one is the most colorful one :-) Colors are
2055 explained in the <a href="#color" target="_top">next
2058 <p>We can OR(|) any number of above attributes to get a
2059 combined effect. If you wanted reverse video with blinking
2060 characters you can use</p>
2061 <pre class="PROGRAMLISTING">
2062 attron(A_REVERSE | A_BLINK);
2069 <h3 class="SECT2"><a name="ATTRONVSATTRSET" id=
2070 "ATTRONVSATTRSET">8.2. attron() vs attrset()</a></h3>
2072 <p>Then what is the difference between attron() and
2073 attrset()? attrset sets the attributes of window whereas
2074 attron just switches on the attribute given to it. So
2075 attrset() fully overrides whatever attributes the window
2076 previously had and sets it to the new attribute(s).
2077 Similarly attroff() just switches off the attribute(s)
2078 given to it as an argument. This gives us the flexibility
2079 of managing attributes easily.But if you use them
2080 carelessly you may loose track of what attributes the
2081 window has and garble the display. This is especially true
2082 while managing menus with colors and highlighting. So
2083 decide on a consistent policy and stick to it. You can
2084 always use <tt class="LITERAL">standend()</tt> which is
2085 equivalent to <tt class="LITERAL">attrset(A_NORMAL)</tt>
2086 which turns off all attributes and brings you to normal
2093 <h3 class="SECT2"><a name="ATTRGET" id="ATTRGET">8.3.
2096 <p>The function attr_get() gets the current attributes and
2097 color pair of the window. Though we might not use this as
2098 often as the above functions, this is useful in scanning
2099 areas of screen. Say we wanted to do some complex update on
2100 screen and we are not sure what attribute each character is
2101 associated with. Then this function can be used with either
2102 attrset or attron to produce the desired effect.</p>
2108 <h3 class="SECT2"><a name="ATTRFUNCS" id="ATTRFUNCS">8.4.
2109 attr_ functions</a></h3>
2111 <p>There are series of functions like attr_set(), attr_on
2112 etc.. These are similar to above functions except that they
2113 take parameters of type <tt class=
2114 "LITERAL">attr_t</tt>.</p>
2120 <h3 class="SECT2"><a name="WATTRFUNCS" id="WATTRFUNCS">8.5.
2121 wattr functions</a></h3>
2123 <p>For each of the above functions we have a corresponding
2124 function with 'w' which operates on a particular window.
2125 The above functions operate on stdscr.</p>
2131 <h3 class="SECT2"><a name="CHGAT" id="CHGAT">8.6. chgat()
2134 <p>The function chgat() is listed in the end of the man
2135 page curs_attr. It actually is a useful one. This function
2136 can be used to set attributes for a group of characters
2137 without moving. I mean it !!! without moving the cursor :-)
2138 It changes the attributes of a given number of characters
2139 starting at the current cursor location.</p>
2141 <p>We can give -1 as the character count to update till end
2142 of line. If you want to change attributes of characters
2143 from current position to end of line, just use this.</p>
2144 <pre class="PROGRAMLISTING">
2145 chgat(-1, A_REVERSE, 0, NULL);
2148 <p>This function is useful when changing attributes for
2149 characters that are already on the screen. Move to the
2150 character from which you want to change and change the
2153 <p>Other functions wchgat(), mvchgat(), wchgat() behave
2154 similarly except that the w functions operate on the
2155 particular window. The mv functions first move the cursor
2156 then perform the work given to them. Actually chgat is a
2157 macro which is replaced by a wchgat() with stdscr as the
2158 window. Most of the "w-less" functions are macros.</p>
2160 <div class="EXAMPLE">
2161 <a name="BWICH" id="BWICH"></a>
2163 <p><b>Example 6. Chgat() Usage example</b></p>
2164 <pre class="PROGRAMLISTING">
2165 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
2167 int main(int argc, char *argv[])
2168 { initscr(); /* Start curses mode */
2169 start_color(); /* Start color functionality */
2171 init_pair(1, COLOR_CYAN, COLOR_BLACK);
2172 printw("A Big string which i didn't care to type fully ");
2173 mvchgat(0, 0, -1, A_BLINK, 1, NULL);
2175 * First two parameters specify the position at which to start
2176 * Third parameter number of characters to update. -1 means till
2178 * Forth parameter is the normal attribute you wanted to give
2180 * Fifth is the color index. It is the index given during init_pair()
2181 * use 0 if you didn't want color
2182 * Sixth one is always NULL
2186 endwin(); /* End curses mode */
2192 <p>This example also introduces us to the color world of
2193 curses. Colors will be explained in detail later. Use 0 for
2201 <h2 class="SECT1"><a name="WINDOWS" id="WINDOWS">9.
2204 <p>Windows form the most important concept in curses. You
2205 have seen the standard window stdscr above where all the
2206 functions implicitly operated on this window. Now to make
2207 design even a simplest GUI, you need to resort to windows.
2208 The main reason you may want to use windows is to manipulate
2209 parts of the screen separately, for better efficiency, by
2210 updating only the windows that need to be changed and for a
2211 better design. I would say the last reason is the most
2212 important in going for windows. You should always strive for
2213 a better and easy-to-manage design in your programs. If you
2214 are writing big, complex GUIs this is of pivotal importance
2215 before you start doing anything.</p>
2220 <h3 class="SECT2"><a name="WINDOWBASICS" id=
2221 "WINDOWBASICS">9.1. The basics</a></h3>
2223 <p>A Window can be created by calling the function
2224 <tt class="LITERAL">newwin()</tt>. It doesn't create any
2225 thing on the screen actually. It allocates memory for a
2226 structure to manipulate the window and updates the
2227 structure with data regarding the window like it's size,
2228 beginy, beginx etc.. Hence in curses, a window is just an
2229 abstraction of an imaginary window, which can be
2230 manipulated independent of other parts of screen. The
2231 function newwin() returns a pointer to structure WINDOW,
2232 which can be passed to window related functions like
2233 wprintw() etc.. Finally the window can be destroyed with
2234 delwin(). It will deallocate the memory associated with the
2235 window structure.</p>
2241 <h3 class="SECT2"><a name="LETBEWINDOW" id=
2242 "LETBEWINDOW">9.2. Let there be a Window !!!</a></h3>
2244 <p>What fun is it, if a window is created and we can't see
2245 it. So the fun part begins by displaying the window. The
2246 function <tt class="LITERAL">box()</tt> can be used to draw
2247 a border around the window. Let's explore these functions
2248 in more detail in this example.</p>
2250 <div class="EXAMPLE">
2251 <a name="BWIBO" id="BWIBO"></a>
2253 <p><b>Example 7. Window Border example</b></p>
2254 <pre class="PROGRAMLISTING">
2255 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
2258 WINDOW *create_newwin(int height, int width, int starty, int startx);
2259 void destroy_win(WINDOW *local_win);
2261 int main(int argc, char *argv[])
2263 int startx, starty, width, height;
2266 initscr(); /* Start curses mode */
2267 cbreak(); /* Line buffering disabled, Pass on
2268 * everty thing to me */
2269 keypad(stdscr, TRUE); /* I need that nifty F1 */
2273 starty = (LINES - height) / 2; /* Calculating for a center placement */
2274 startx = (COLS - width) / 2; /* of the window */
2275 printw("Press F1 to exit");
2277 my_win = create_newwin(height, width, starty, startx);
2279 while((ch = getch()) != KEY_F(1))
2282 destroy_win(my_win);
2283 my_win = create_newwin(height, width, starty,--startx);
2286 destroy_win(my_win);
2287 my_win = create_newwin(height, width, starty,++startx);
2290 destroy_win(my_win);
2291 my_win = create_newwin(height, width, --starty,startx);
2294 destroy_win(my_win);
2295 my_win = create_newwin(height, width, ++starty,startx);
2300 endwin(); /* End curses mode */
2304 WINDOW *create_newwin(int height, int width, int starty, int startx)
2305 { WINDOW *local_win;
2307 local_win = newwin(height, width, starty, startx);
2308 box(local_win, 0 , 0); /* 0, 0 gives default characters
2309 * for the vertical and horizontal
2311 wrefresh(local_win); /* Show that box */
2316 void destroy_win(WINDOW *local_win)
2318 /* box(local_win, ' ', ' '); : This won't produce the desired
2319 * result of erasing the window. It will leave it's four corners
2320 * and so an ugly remnant of window.
2322 wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' ');
2323 /* The parameters taken are
2324 * 1. win: the window on which to operate
2325 * 2. ls: character to be used for the left side of the window
2326 * 3. rs: character to be used for the right side of the window
2327 * 4. ts: character to be used for the top side of the window
2328 * 5. bs: character to be used for the bottom side of the window
2329 * 6. tl: character to be used for the top left corner of the window
2330 * 7. tr: character to be used for the top right corner of the window
2331 * 8. bl: character to be used for the bottom left corner of the window
2332 * 9. br: character to be used for the bottom right corner of the window
2334 wrefresh(local_win);
2344 <h3 class="SECT2"><a name="BORDEREXEXPL" id=
2345 "BORDEREXEXPL">9.3. Explanation</a></h3>
2347 <p>Don't scream. I know it's a big example. But I have to
2348 explain some important things here :-). This program
2349 creates a rectangular window that can be moved with left,
2350 right, up, down arrow keys. It repeatedly creates and
2351 destroys windows as user press a key. Don't go beyond the
2352 screen limits. Checking for those limits is left as an
2353 exercise for the reader. Let's dissect it by line by
2356 <p>The <tt class="LITERAL">create_newwin()</tt> function
2357 creates a window with <tt class="LITERAL">newwin()</tt> and
2358 displays a border around it with box. The function
2359 <tt class="LITERAL">destroy_win()</tt> first erases the
2360 window from screen by painting a border with ' ' character
2361 and then calling <tt class="LITERAL">delwin()</tt> to
2362 deallocate memory related to it. Depending on the key the
2363 user presses, starty or startx is changed and a new window
2366 <p>In the destroy_win, as you can see, I used wborder
2367 instead of box. The reason is written in the comments (You
2368 missed it. I know. Read the code :-)). wborder draws a
2369 border around the window with the characters given to it as
2370 the 4 corner points and the 4 lines. To put it clearly, if
2371 you have called wborder as below:</p>
2372 <pre class="PROGRAMLISTING">
2373 wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');
2376 <p>it produces some thing like</p>
2377 <pre class="PROGRAMLISTING">
2392 <h3 class="SECT2"><a name="OTHERSTUFF" id="OTHERSTUFF">9.4.
2393 The other stuff in the example</a></h3>
2395 <p>You can also see in the above examples, that I have used
2396 the variables COLS, LINES which are initialized to the
2397 screen sizes after initscr(). They can be useful in finding
2398 screen dimensions and finding the center co-ordinate of the
2399 screen as above. The function <tt class=
2400 "LITERAL">getch()</tt> as usual gets the key from keyboard
2401 and according to the key it does the corresponding work.
2402 This type of switch- case is very common in any GUI based
2409 <h3 class="SECT2"><a name="OTHERBORDERFUNCS" id=
2410 "OTHERBORDERFUNCS">9.5. Other Border functions</a></h3>
2412 <p>Above program is grossly inefficient in that with each
2413 press of a key, a window is destroyed and another is
2414 created. So let's write a more efficient program which uses
2415 other border related functions.</p>
2417 <p>The following program uses <tt class=
2418 "LITERAL">mvhline()</tt> and <tt class=
2419 "LITERAL">mvvline()</tt> to achieve similar effect. These
2420 two functions are simple. They create a horizontal or
2421 vertical line of the specified length at the specified
2424 <div class="EXAMPLE">
2425 <a name="BOTBO" id="BOTBO"></a>
2427 <p><b>Example 8. More border functions</b></p>
2428 <pre class="PROGRAMLISTING">
2429 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
2431 typedef struct _win_border_struct {
2432 chtype ls, rs, ts, bs,
2436 typedef struct _WIN_struct {
2443 void init_win_params(WIN *p_win);
2444 void print_win_params(WIN *p_win);
2445 void create_box(WIN *win, bool flag);
2447 int main(int argc, char *argv[])
2451 initscr(); /* Start curses mode */
2452 start_color(); /* Start the color functionality */
2453 cbreak(); /* Line buffering disabled, Pass on
2454 * everty thing to me */
2455 keypad(stdscr, TRUE); /* I need that nifty F1 */
2457 init_pair(1, COLOR_CYAN, COLOR_BLACK);
2459 /* Initialize the window parameters */
2460 init_win_params(&win);
2461 print_win_params(&win);
2463 attron(COLOR_PAIR(1));
2464 printw("Press F1 to exit");
2466 attroff(COLOR_PAIR(1));
2468 create_box(&win, TRUE);
2469 while((ch = getch()) != KEY_F(1))
2472 create_box(&win, FALSE);
2474 create_box(&win, TRUE);
2477 create_box(&win, FALSE);
2479 create_box(&win, TRUE);
2482 create_box(&win, FALSE);
2484 create_box(&win, TRUE);
2487 create_box(&win, FALSE);
2489 create_box(&win, TRUE);
2493 endwin(); /* End curses mode */
2496 void init_win_params(WIN *p_win)
2498 p_win->height = 3;
2499 p_win->width = 10;
2500 p_win->starty = (LINES - p_win->height)/2;
2501 p_win->startx = (COLS - p_win->width)/2;
2503 p_win->border.ls = '|';
2504 p_win->border.rs = '|';
2505 p_win->border.ts = '-';
2506 p_win->border.bs = '-';
2507 p_win->border.tl = '+';
2508 p_win->border.tr = '+';
2509 p_win->border.bl = '+';
2510 p_win->border.br = '+';
2513 void print_win_params(WIN *p_win)
2516 mvprintw(25, 0, "%d %d %d %d", p_win->startx, p_win->starty,
2517 p_win->width, p_win->height);
2521 void create_box(WIN *p_win, bool flag)
2525 x = p_win->startx;
2526 y = p_win->starty;
2527 w = p_win->width;
2528 h = p_win->height;
2531 { mvaddch(y, x, p_win->border.tl);
2532 mvaddch(y, x + w, p_win->border.tr);
2533 mvaddch(y + h, x, p_win->border.bl);
2534 mvaddch(y + h, x + w, p_win->border.br);
2535 mvhline(y, x + 1, p_win->border.ts, w - 1);
2536 mvhline(y + h, x + 1, p_win->border.bs, w - 1);
2537 mvvline(y + 1, x, p_win->border.ls, h - 1);
2538 mvvline(y + 1, x + w, p_win->border.rs, h - 1);
2542 for(j = y; j <= y + h; ++j)
2543 for(i = x; i <= x + w; ++i)
2557 <h2 class="SECT1"><a name="COLOR" id="COLOR">10.
2561 <h3 class="SECT2"><a name="COLORBASICS" id=
2562 "COLORBASICS">10.1. The basics</a></h3>
2564 <p>Life seems dull with no colors. Curses has a nice
2565 mechanism to handle colors. Let's get into the thick of the
2566 things with a small program.</p>
2568 <div class="EXAMPLE">
2569 <a name="BSICO" id="BSICO"></a>
2571 <p><b>Example 9. A Simple Color example</b></p>
2572 <pre class="PROGRAMLISTING">
2573 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
2575 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string);
2576 int main(int argc, char *argv[])
2577 { initscr(); /* Start curses mode */
2578 if(has_colors() == FALSE)
2580 printf("Your terminal does not support color\n");
2583 start_color(); /* Start color */
2584 init_pair(1, COLOR_RED, COLOR_BLACK);
2586 attron(COLOR_PAIR(1));
2587 print_in_middle(stdscr, LINES / 2, 0, 0, "Viola !!! In color ...");
2588 attroff(COLOR_PAIR(1));
2592 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string)
2606 length = strlen(string);
2607 temp = (width - length)/ 2;
2608 x = startx + (int)temp;
2609 mvwprintw(win, y, x, "%s", string);
2616 <p>As you can see, to start using color, you should first
2617 call the function <tt class="LITERAL">start_color()</tt>.
2618 After that, you can use color capabilities of your
2619 terminals using various functions. To find out whether a
2620 terminal has color capabilities or not, you can use
2621 <tt class="LITERAL">has_colors()</tt> function, which
2622 returns FALSE if the terminal does not support color.</p>
2624 <p>Curses initializes all the colors supported by terminal
2625 when start_color() is called. These can be accessed by the
2626 define constants like <tt class="LITERAL">COLOR_BLACK</tt>
2627 etc. Now to actually start using colors, you have to define
2628 pairs. Colors are always used in pairs. That means you have
2629 to use the function <tt class="LITERAL">init_pair()</tt> to
2630 define the foreground and background for the pair number
2631 you give. After that that pair number can be used as a
2632 normal attribute with <tt class=
2633 "LITERAL">COLOR_PAIR()</tt>function. This may seem to be
2634 cumbersome at first. But this elegant solution allows us to
2635 manage color pairs very easily. To appreciate it, you have
2636 to look into the the source code of "dialog", a utility for
2637 displaying dialog boxes from shell scripts. The developers
2638 have defined foreground and background combinations for all
2639 the colors they might need and initialized at the
2640 beginning. This makes it very easy to set attributes just
2641 by accessing a pair which we already have defined as a
2644 <p>The following colors are defined in <tt class=
2645 "LITERAL">curses.h</tt>. You can use these as parameters
2646 for various color functions.</p>
2647 <pre class="PROGRAMLISTING">
2662 <h3 class="SECT2"><a name="CHANGECOLORDEFS" id=
2663 "CHANGECOLORDEFS">10.2. Changing Color Definitions</a></h3>
2665 <p>The function <tt class="LITERAL">init_color()</tt>can be
2666 used to change the rgb values for the colors defined by
2667 curses initially. Say you wanted to lighten the intensity
2668 of red color by a minuscule. Then you can use this function
2670 <pre class="PROGRAMLISTING">
2671 init_color(COLOR_RED, 700, 0, 0);
2672 /* param 1 : color name
2673 * param 2, 3, 4 : rgb content min = 0, max = 1000 */
2676 <p>If your terminal cannot change the color definitions,
2677 the function returns ERR. The function <tt class=
2678 "LITERAL">can_change_color()</tt> can be used to find out
2679 whether the terminal has the capability of changing color
2680 content or not. The rgb content is scaled from 0 to 1000.
2681 Initially RED color is defined with content 1000(r), 0(g),
2688 <h3 class="SECT2"><a name="COLORCONTENT" id=
2689 "COLORCONTENT">10.3. Color Content</a></h3>
2691 <p>The functions <tt class="LITERAL">color_content()</tt>
2692 and <tt class="LITERAL">pair_content()</tt> can be used to
2693 find the color content and foreground, background
2694 combination for the pair.</p>
2701 <h2 class="SECT1"><a name="KEYS" id="KEYS">11. Interfacing
2702 with the key board</a></h2>
2705 <h3 class="SECT2"><a name="KEYSBASICS" id=
2706 "KEYSBASICS">11.1. The Basics</a></h3>
2708 <p>No GUI is complete without a strong user interface and
2709 to interact with the user, a curses program should be
2710 sensitive to key presses or the mouse actions done by the
2711 user. Let's deal with the keys first.</p>
2713 <p>As you have seen in almost all of the above examples,
2714 it's very easy to get key input from the user. A simple way
2715 of getting key presses is to use <tt class=
2716 "LITERAL">getch()</tt> function. The cbreak mode should be
2717 enabled to read keys when you are interested in reading
2718 individual key hits rather than complete lines of text
2719 (which usually end with a carriage return). keypad should
2720 be enabled to get the Functions keys, arrow keys etc. See
2721 the initialization section for details.</p>
2723 <p><tt class="LITERAL">getch()</tt> returns an integer
2724 corresponding to the key pressed. If it is a normal
2725 character, the integer value will be equivalent to the
2726 character. Otherwise it returns a number which can be
2727 matched with the constants defined in <tt class=
2728 "LITERAL">curses.h</tt>. For example if the user presses
2729 F1, the integer returned is 265. This can be checked using
2730 the macro KEY_F() defined in curses.h. This makes reading
2731 keys portable and easy to manage.</p>
2733 <p>For example, if you call getch() like this</p>
2734 <pre class="PROGRAMLISTING">
2740 <p>getch() will wait for the user to press a key, (unless
2741 you specified a timeout) and when user presses a key, the
2742 corresponding integer is returned. Then you can check the
2743 value returned with the constants defined in curses.h to
2744 match against the keys you want.</p>
2746 <p>The following code piece will do that job.</p>
2747 <pre class="PROGRAMLISTING">
2749 printw("Left arrow is pressed\n");
2752 <p>Let's write a small program which creates a menu which
2753 can be navigated by up and down arrows.</p>
2759 <h3 class="SECT2"><a name="SIMPLEKEYEX" id=
2760 "SIMPLEKEYEX">11.2. A Simple Key Usage example</a></h3>
2762 <div class="EXAMPLE">
2763 <a name="BSIKE" id="BSIKE"></a>
2765 <p><b>Example 10. A Simple Key Usage example</b></p>
2766 <pre class="PROGRAMLISTING">
2767 <span class="INLINEMEDIAOBJECT">#include <stdio.h>
2768 #include <ncurses.h>
2783 int n_choices = sizeof(choices) / sizeof(char *);
2784 void print_menu(WINDOW *menu_win, int highlight);
2795 cbreak(); /* Line buffering disabled. pass on everything */
2796 startx = (80 - WIDTH) / 2;
2797 starty = (24 - HEIGHT) / 2;
2799 menu_win = newwin(HEIGHT, WIDTH, starty, startx);
2800 keypad(menu_win, TRUE);
2801 mvprintw(0, 0, "Use arrow keys to go up and down, Press enter to select a choice");
2803 print_menu(menu_win, highlight);
2805 { c = wgetch(menu_win);
2809 highlight = n_choices;
2814 if(highlight == n_choices)
2823 mvprintw(24, 0, "Charcter pressed is = %3d Hopefully it can be printed as '%c'", c, c);
2827 print_menu(menu_win, highlight);
2828 if(choice != 0) /* User did a choice come out of the infinite loop */
2831 mvprintw(23, 0, "You chose choice %d with choice string %s\n", choice, choices[choice - 1]);
2839 void print_menu(WINDOW *menu_win, int highlight)
2845 box(menu_win, 0, 0);
2846 for(i = 0; i < n_choices; ++i)
2847 { if(highlight == i + 1) /* High light the present choice */
2848 { wattron(menu_win, A_REVERSE);
2849 mvwprintw(menu_win, y, x, "%s", choices[i]);
2850 wattroff(menu_win, A_REVERSE);
2853 mvwprintw(menu_win, y, x, "%s", choices[i]);
2867 <h2 class="SECT1"><a name="MOUSE" id="MOUSE">12. Interfacing
2868 with the mouse</a></h2>
2870 <p>Now that you have seen how to get keys, lets do the same
2871 thing from mouse. Usually each UI allows the user to interact
2872 with both keyboard and mouse.</p>
2877 <h3 class="SECT2"><a name="MOUSEBASICS" id=
2878 "MOUSEBASICS">12.1. The Basics</a></h3>
2880 <p>Before you do any thing else, the events you want to
2881 receive have to be enabled with <tt class=
2882 "LITERAL">mousemask()</tt>.</p>
2883 <pre class="PROGRAMLISTING">
2884 mousemask( mmask_t newmask, /* The events you want to listen to */
2885 mmask_t *oldmask) /* The old events mask */
2888 <p>The first parameter to above function is a bit mask of
2889 events you would like to listen. By default, all the events
2890 are turned off. The bit mask <tt class=
2891 "LITERAL">ALL_MOUSE_EVENTS</tt> can be used to get all the
2894 <p>The following are all the event masks:</p>
2895 <pre class="PROGRAMLISTING">
2897 ---------------------------------------------------------------------
2898 BUTTON1_PRESSED mouse button 1 down
2899 BUTTON1_RELEASED mouse button 1 up
2900 BUTTON1_CLICKED mouse button 1 clicked
2901 BUTTON1_DOUBLE_CLICKED mouse button 1 double clicked
2902 BUTTON1_TRIPLE_CLICKED mouse button 1 triple clicked
2903 BUTTON2_PRESSED mouse button 2 down
2904 BUTTON2_RELEASED mouse button 2 up
2905 BUTTON2_CLICKED mouse button 2 clicked
2906 BUTTON2_DOUBLE_CLICKED mouse button 2 double clicked
2907 BUTTON2_TRIPLE_CLICKED mouse button 2 triple clicked
2908 BUTTON3_PRESSED mouse button 3 down
2909 BUTTON3_RELEASED mouse button 3 up
2910 BUTTON3_CLICKED mouse button 3 clicked
2911 BUTTON3_DOUBLE_CLICKED mouse button 3 double clicked
2912 BUTTON3_TRIPLE_CLICKED mouse button 3 triple clicked
2913 BUTTON4_PRESSED mouse button 4 down
2914 BUTTON4_RELEASED mouse button 4 up
2915 BUTTON4_CLICKED mouse button 4 clicked
2916 BUTTON4_DOUBLE_CLICKED mouse button 4 double clicked
2917 BUTTON4_TRIPLE_CLICKED mouse button 4 triple clicked
2918 BUTTON_SHIFT shift was down during button state change
2919 BUTTON_CTRL control was down during button state change
2920 BUTTON_ALT alt was down during button state change
2921 ALL_MOUSE_EVENTS report all button state changes
2922 REPORT_MOUSE_POSITION report mouse movement
2929 <h3 class="SECT2"><a name="GETTINGEVENTS" id=
2930 "GETTINGEVENTS">12.2. Getting the events</a></h3>
2932 <p>Once a class of mouse events have been enabled, getch()
2933 class of functions return KEY_MOUSE every time some mouse
2934 event happens. Then the mouse event can be retrieved with
2935 <tt class="LITERAL">getmouse()</tt>.</p>
2937 <p>The code approximately looks like this:</p>
2938 <pre class="PROGRAMLISTING">
2943 if(getmouse(&event) == OK)
2944 . /* Do some thing with the event */
2949 <p>getmouse() returns the event into the pointer given to
2950 it. It's a structure which contains</p>
2951 <pre class="PROGRAMLISTING">
2954 short id; /* ID to distinguish multiple devices */
2955 int x, y, z; /* event coordinates */
2956 mmask_t bstate; /* button state bits */
2960 <p>The <tt class="LITERAL">bstate</tt> is the main variable
2961 we are interested in. It tells the button state of the
2964 <p>Then with a code snippet like the following, we can find
2965 out what happened.</p>
2966 <pre class="PROGRAMLISTING">
2967 if(event.bstate & BUTTON1_PRESSED)
2968 printw("Left Button Pressed");
2975 <h3 class="SECT2"><a name="MOUSETOGETHER" id=
2976 "MOUSETOGETHER">12.3. Putting it all Together</a></h3>
2978 <p>That's pretty much interfacing with mouse. Let's create
2979 the same menu and enable mouse interaction. To make things
2980 simpler, key handling is removed.</p>
2982 <div class="EXAMPLE">
2983 <a name="BMOME" id="BMOME"></a>
2985 <p><b>Example 11. Access the menu with mouse !!!</b></p>
2986 <pre class="PROGRAMLISTING">
2987 <span class="INLINEMEDIAOBJECT">#include <ncurses.h>
2995 char *choices[] = { "Choice 1",
3002 int n_choices = sizeof(choices) / sizeof(char *);
3004 void print_menu(WINDOW *menu_win, int highlight);
3005 void report_choice(int mouse_x, int mouse_y, int *p_choice);
3008 { int c, choice = 0;
3012 /* Initialize curses */
3016 cbreak(); //Line buffering disabled. pass on everything
3018 /* Try to put the window in the middle of screen */
3019 startx = (80 - WIDTH) / 2;
3020 starty = (24 - HEIGHT) / 2;
3023 mvprintw(23, 1, "Click on Exit to quit (Works best in a virtual console)");
3027 /* Print the menu for the first time */
3028 menu_win = newwin(HEIGHT, WIDTH, starty, startx);
3029 print_menu(menu_win, 1);
3030 /* Get all the mouse events */
3031 mousemask(ALL_MOUSE_EVENTS, NULL);
3034 { c = wgetch(menu_win);
3037 if(getmouse(&event) == OK)
3038 { /* When the user clicks left mouse button */
3039 if(event.bstate & BUTTON1_PRESSED)
3040 { report_choice(event.x + 1, event.y + 1, &choice);
3041 if(choice == -1) //Exit chosen
3043 mvprintw(22, 1, "Choice made is : %d String Chosen is \"%10s\"", choice, choices[choice - 1]);
3047 print_menu(menu_win, choice);
3057 void print_menu(WINDOW *menu_win, int highlight)
3063 box(menu_win, 0, 0);
3064 for(i = 0; i < n_choices; ++i)
3065 { if(highlight == i + 1)
3066 { wattron(menu_win, A_REVERSE);
3067 mvwprintw(menu_win, y, x, "%s", choices[i]);
3068 wattroff(menu_win, A_REVERSE);
3071 mvwprintw(menu_win, y, x, "%s", choices[i]);
3077 /* Report the choice according to mouse position */
3078 void report_choice(int mouse_x, int mouse_y, int *p_choice)
3084 for(choice = 0; choice < n_choices; ++choice)
3085 if(mouse_y == j + choice && mouse_x >= i && mouse_x <= i + strlen(choices[choice]))
3086 { if(choice == n_choices - 1)
3089 *p_choice = choice + 1;
3100 <h3 class="SECT2"><a name="MISCMOUSEFUNCS" id=
3101 "MISCMOUSEFUNCS">12.4. Miscellaneous Functions</a></h3>
3103 <p>The functions mouse_trafo() and wmouse_trafo() can be
3104 used to convert to mouse co-ordinates to screen relative
3105 co-ordinates. See curs_mouse(3X) man page for details.</p>
3107 <p>The mouseinterval function sets the maximum time (in
3108 thousands of a second) that can elapse between press and
3109 release events in order for them to be recognized as a
3110 click. This function returns the previous interval value.
3111 The default is one fifth of a second.</p>
3118 <h2 class="SECT1"><a name="SCREEN" id="SCREEN">13. Screen
3119 Manipulation</a></h2>
3121 <p>In this section, we will look into some functions, which
3122 allow us to manage the screen efficiently and to write some
3123 fancy programs. This is especially important in writing
3129 <h3 class="SECT2"><a name="GETYX" id="GETYX">13.1. getyx()
3132 <p>The function <tt class="LITERAL">getyx()</tt> can be
3133 used to find out the present cursor co-ordinates. It will
3134 fill the values of x and y co-ordinates in the arguments
3135 given to it. Since getyx() is a macro you don't have to
3136 pass the address of the variables. It can be called as</p>
3137 <pre class="PROGRAMLISTING">
3139 /* win: window pointer
3140 * y, x: y, x co-ordinates will be put into this variables
3144 <p>The function getparyx() gets the beginning co-ordinates
3145 of the sub window relative to the main window. This is some
3146 times useful to update a sub window. When designing fancy
3147 stuff like writing multiple menus, it becomes difficult to
3148 store the menu positions, their first option co-ordinates
3149 etc. A simple solution to this problem, is to create menus
3150 in sub windows and later find the starting co-ordinates of
3151 the menus by using getparyx().</p>
3153 <p>The functions getbegyx() and getmaxyx() store current
3154 window's beginning and maximum co-ordinates. These
3155 functions are useful in the same way as above in managing
3156 the windows and sub windows effectively.</p>
3162 <h3 class="SECT2"><a name="SCREENDUMP" id=
3163 "SCREENDUMP">13.2. Screen Dumping</a></h3>
3165 <p>While writing games, some times it becomes necessary to
3166 store the state of the screen and restore it back to the
3167 same state. The function scr_dump() can be used to dump the
3168 screen contents to a file given as an argument. Later it
3169 can be restored by scr_restore function. These two simple
3170 functions can be used effectively to maintain a fast moving
3171 game with changing scenarios.</p>
3177 <h3 class="SECT2"><a name="WINDOWDUMP" id=
3178 "WINDOWDUMP">13.3. Window Dumping</a></h3>
3180 <p>To store and restore windows, the functions <tt class=
3181 "LITERAL">putwin()</tt> and <tt class=
3182 "LITERAL">getwin()</tt> can be used. <tt class=
3183 "LITERAL">putwin()</tt> puts the present window state into
3184 a file, which can be later restored by <tt class=
3185 "LITERAL">getwin()</tt>.</p>
3187 <p>The function <tt class="LITERAL">copywin()</tt> can be
3188 used to copy a window completely onto another window. It
3189 takes the source and destination windows as parameters and
3190 according to the rectangle specified, it copies the
3191 rectangular region from source to destination window. It's
3192 last parameter specifies whether to overwrite or just
3193 overlay the contents on to the destination window. If this
3194 argument is true, then the copying is non-destructive.</p>
3201 <h2 class="SECT1"><a name="MISC" id="MISC">14. Miscellaneous
3204 <p>Now you know enough features to write a good curses
3205 program, with all bells and whistles. There are some
3206 miscellaneous functions which are useful in various cases.
3207 Let's go headlong into some of those.</p>
3212 <h3 class="SECT2"><a name="CURSSET" id="CURSSET">14.1.
3215 <p>This function can be used to make the cursor invisible.
3216 The parameter to this function should be</p>
3217 <pre class="PROGRAMLISTING">
3227 <h3 class="SECT2"><a name="TEMPLEAVE" id="TEMPLEAVE">14.2.
3228 Temporarily Leaving Curses mode</a></h3>
3230 <p>Some times you may want to get back to cooked mode
3231 (normal line buffering mode) temporarily. In such a case