1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <meta name="generator" content=
5 "HTML Tidy for Linux/x86 (vers 1st December 2004), see www.w3.org">
6 <title>NCURSES Programming HOWTO</title>
7 <meta name="GENERATOR" content=
8 "Modular DocBook HTML Stylesheet Version 1.7">
10 <body class="ARTICLE" bgcolor="#FFFFFF" text="#000000" link=
11 "#0000FF" vlink="#840084" alink="#0000FF">
13 <div class="TITLEPAGE">
14 <h1 class="TITLE"><a name="AEN2" id="AEN2">NCURSES Programming
16 <h3 class="AUTHOR"><a name="AEN4" id="AEN4">Pradeep Padala</a></h3>
17 <div class="AFFILIATION">
19 <p class="ADDRESS"><code class="EMAIL"><<a href=
20 "mailto:ppadala@gmail.com">ppadala@gmail.com</a>></code></p>
23 <p class="PUBDATE">v1.9, 2005-06-20<br></p>
24 <div class="REVHISTORY">
25 <table width="100%" border="0">
27 <th align="left" valign="top" colspan="3"><b>Revision
31 <td align="left">Revision 1.9</td>
32 <td align="left">2005-06-20</td>
33 <td align="left">Revised by: ppadala</td>
36 <td align="left" colspan="3">The license has been changed to the
37 MIT-style license used by NCURSES. Note that the programs are also
38 re-licensed under this.</td>
41 <td align="left">Revision 1.8</td>
42 <td align="left">2005-06-17</td>
43 <td align="left">Revised by: ppadala</td>
46 <td align="left" colspan="3">Lots of updates. Added references and
47 perl examples. Changes to examples. Many grammatical and stylistic
48 changes to the content. Changes to NCURSES history.</td>
51 <td align="left">Revision 1.7.1</td>
52 <td align="left">2002-06-25</td>
53 <td align="left">Revised by: ppadala</td>
56 <td align="left" colspan="3">Added a README file for building and
57 instructions for building from source.</td>
60 <td align="left">Revision 1.7</td>
61 <td align="left">2002-06-25</td>
62 <td align="left">Revised by: ppadala</td>
65 <td align="left" colspan="3">Added "Other formats" section and made
66 a lot of fancy changes to the programs. Inlining of programs is
70 <td align="left">Revision 1.6.1</td>
71 <td align="left">2002-02-24</td>
72 <td align="left">Revised by: ppadala</td>
75 <td align="left" colspan="3">Removed the old Changelog section,
76 cleaned the makefiles</td>
79 <td align="left">Revision 1.6</td>
80 <td align="left">2002-02-16</td>
81 <td align="left">Revised by: ppadala</td>
84 <td align="left" colspan="3">Corrected a lot of spelling mistakes,
85 added ACS variables section</td>
88 <td align="left">Revision 1.5</td>
89 <td align="left">2002-01-05</td>
90 <td align="left">Revised by: ppadala</td>
93 <td align="left" colspan="3">Changed structure to present proper
97 <td align="left">Revision 1.3.1</td>
98 <td align="left">2001-07-26</td>
99 <td align="left">Revised by: ppadala</td>
102 <td align="left" colspan="3">Corrected maintainers paragraph,
103 Corrected stable release number</td>
106 <td align="left">Revision 1.3</td>
107 <td align="left">2001-07-24</td>
108 <td align="left">Revised by: ppadala</td>
111 <td align="left" colspan="3">Added copyright notices to main
112 document (LDP license) and programs (GPL), Corrected
116 <td align="left">Revision 1.2</td>
117 <td align="left">2001-06-05</td>
118 <td align="left">Revised by: ppadala</td>
121 <td align="left" colspan="3">Incorporated ravi's changes. Mainly to
122 introduction, menu, form, justforfun sections</td>
125 <td align="left">Revision 1.1</td>
126 <td align="left">2001-05-22</td>
127 <td align="left">Revised by: ppadala</td>
130 <td align="left" colspan="3">Added "a word about window" section,
131 Added scanw_example.</td>
136 <div class="ABSTRACT"><a name="AEN67" id="AEN67"></a>
137 <p><em>This document is intended to be an "All in One" guide for
138 programming with ncurses and its sister libraries. We graduate from
139 a simple "Hello World" program to more complex form manipulation.
140 No prior experience in ncurses is assumed. Send comments to
141 <a href="mailto:ppadala@gmail.com" target="_top">this
148 <dt><b>Table of Contents</b></dt>
149 <dt>1. <a href="#INTRO">Introduction</a></dt>
152 <dt>1.1. <a href="#WHATIS">What is NCURSES?</a></dt>
153 <dt>1.2. <a href="#WHATCANWEDO">What we can do with
155 <dt>1.3. <a href="#WHERETOGETIT">Where to get it</a></dt>
156 <dt>1.4. <a href="#PURPOSE">Purpose/Scope of the document</a></dt>
157 <dt>1.5. <a href="#ABOUTPROGRAMS">About the Programs</a></dt>
158 <dt>1.6. <a href="#OTHERFORMATS">Other Formats of the
160 <dt>1.7. <a href="#CREDITS">Credits</a></dt>
161 <dt>1.8. <a href="#WISHLIST">Wish List</a></dt>
162 <dt>1.9. <a href="#COPYRIGHT">Copyright</a></dt>
165 <dt>2. <a href="#HELLOWORLD">Hello World !!!</a></dt>
168 <dt>2.1. <a href="#COMPILECURSES">Compiling With the NCURSES
170 <dt>2.2. <a href="#DISSECTION">Dissection</a></dt>
173 <dt>3. <a href="#GORY">The Gory Details</a></dt>
174 <dt>4. <a href="#INIT">Initialization</a></dt>
177 <dt>4.1. <a href="#ABOUTINIT">Initialization functions</a></dt>
178 <dt>4.2. <a href="#RAWCBREAK">raw() and cbreak()</a></dt>
179 <dt>4.3. <a href="#ECHONOECHO">echo() and noecho()</a></dt>
180 <dt>4.4. <a href="#KEYPAD">keypad()</a></dt>
181 <dt>4.5. <a href="#HALFDELAY">halfdelay()</a></dt>
182 <dt>4.6. <a href="#MISCINIT">Miscellaneous Initialization
184 <dt>4.7. <a href="#INITEX">An Example</a></dt>
187 <dt>5. <a href="#AWORDWINDOWS">A Word about Windows</a></dt>
188 <dt>6. <a href="#PRINTW">Output functions</a></dt>
191 <dt>6.1. <a href="#ADDCHCLASS">addch() class of functions</a></dt>
192 <dt>6.2. <a href="#AEN298">mvaddch(), waddch() and
194 <dt>6.3. <a href="#PRINTWCLASS">printw() class of
196 <dt>6.4. <a href="#ADDSTRCLASS">addstr() class of
198 <dt>6.5. <a href="#ACAUTION">A word of caution</a></dt>
201 <dt>7. <a href="#SCANW">Input functions</a></dt>
204 <dt>7.1. <a href="#GETCHCLASS">getch() class of functions</a></dt>
205 <dt>7.2. <a href="#SCANWCLASS">scanw() class of functions</a></dt>
206 <dt>7.3. <a href="#GETSTRCLASS">getstr() class of
208 <dt>7.4. <a href="#GETSTREX">Some examples</a></dt>
211 <dt>8. <a href="#ATTRIB">Attributes</a></dt>
214 <dt>8.1. <a href="#ATTRIBDETAILS">The details</a></dt>
215 <dt>8.2. <a href="#ATTRONVSATTRSET">attron() vs attrset()</a></dt>
216 <dt>8.3. <a href="#ATTR_GET">attr_get()</a></dt>
217 <dt>8.4. <a href="#ATTR_FUNCS">attr_ functions</a></dt>
218 <dt>8.5. <a href="#WATTRFUNCS">wattr functions</a></dt>
219 <dt>8.6. <a href="#CHGAT">chgat() functions</a></dt>
222 <dt>9. <a href="#WINDOWS">Windows</a></dt>
225 <dt>9.1. <a href="#WINDOWBASICS">The basics</a></dt>
226 <dt>9.2. <a href="#LETBEWINDOW">Let there be a Window !!!</a></dt>
227 <dt>9.3. <a href="#BORDEREXEXPL">Explanation</a></dt>
228 <dt>9.4. <a href="#OTHERSTUFF">The other stuff in the
230 <dt>9.5. <a href="#OTHERBORDERFUNCS">Other Border
234 <dt>10. <a href="#COLOR">Colors</a></dt>
237 <dt>10.1. <a href="#COLORBASICS">The basics</a></dt>
238 <dt>10.2. <a href="#CHANGECOLORDEFS">Changing Color
240 <dt>10.3. <a href="#COLORCONTENT">Color Content</a></dt>
243 <dt>11. <a href="#KEYS">Interfacing with the key board</a></dt>
246 <dt>11.1. <a href="#KEYSBASICS">The Basics</a></dt>
247 <dt>11.2. <a href="#SIMPLEKEYEX">A Simple Key Usage
251 <dt>12. <a href="#MOUSE">Interfacing with the mouse</a></dt>
254 <dt>12.1. <a href="#MOUSEBASICS">The Basics</a></dt>
255 <dt>12.2. <a href="#GETTINGEVENTS">Getting the events</a></dt>
256 <dt>12.3. <a href="#MOUSETOGETHER">Putting it all Together</a></dt>
257 <dt>12.4. <a href="#MISCMOUSEFUNCS">Miscellaneous
261 <dt>13. <a href="#SCREEN">Screen Manipulation</a></dt>
264 <dt>13.1. <a href="#GETYX">getyx() functions</a></dt>
265 <dt>13.2. <a href="#SCREENDUMP">Screen Dumping</a></dt>
266 <dt>13.3. <a href="#WINDOWDUMP">Window Dumping</a></dt>
269 <dt>14. <a href="#MISC">Miscellaneous features</a></dt>
272 <dt>14.1. <a href="#CURSSET">curs_set()</a></dt>
273 <dt>14.2. <a href="#TEMPLEAVE">Temporarily Leaving Curses
275 <dt>14.3. <a href="#ACSVARS">ACS_ variables</a></dt>
278 <dt>15. <a href="#OTHERLIB">Other libraries</a></dt>
279 <dt>16. <a href="#PANELS">Panel Library</a></dt>
282 <dt>16.1. <a href="#PANELBASICS">The Basics</a></dt>
283 <dt>16.2. <a href="#COMPILEPANELS">Compiling With the Panels
285 <dt>16.3. <a href="#PANELBROWSING">Panel Window Browsing</a></dt>
286 <dt>16.4. <a href="#USERPTRUSING">Using User Pointers</a></dt>
287 <dt>16.5. <a href="#PANELMOVERESIZE">Moving and Resizing
289 <dt>16.6. <a href="#PANELSHOWHIDE">Hiding and Showing
291 <dt>16.7. <a href="#PANELABOVE">panel_above() and panel_below()
295 <dt>17. <a href="#MENUS">Menus Library</a></dt>
298 <dt>17.1. <a href="#MENUBASICS">The Basics</a></dt>
299 <dt>17.2. <a href="#COMPILEMENUS">Compiling With the Menu
301 <dt>17.3. <a href="#MENUDRIVER">Menu Driver: The work horse of the
303 <dt>17.4. <a href="#MENUWINDOWS">Menu Windows</a></dt>
304 <dt>17.5. <a href="#SCROLLMENUS">Scrolling Menus</a></dt>
305 <dt>17.6. <a href="#MULTICOLUMN">Multi Columnar Menus</a></dt>
306 <dt>17.7. <a href="#MULTIVALUEMENUS">Multi Valued Menus</a></dt>
307 <dt>17.8. <a href="#MENUOPT">Menu Options</a></dt>
308 <dt>17.9. <a href="#MENUUSERPTR">The useful User Pointer</a></dt>
311 <dt>18. <a href="#FORMS">Forms Library</a></dt>
314 <dt>18.1. <a href="#FORMBASICS">The Basics</a></dt>
315 <dt>18.2. <a href="#COMPILEFORMS">Compiling With the Forms
317 <dt>18.3. <a href="#PLAYFIELDS">Playing with Fields</a></dt>
318 <dt>18.4. <a href="#FORMWINDOWS">Form Windows</a></dt>
319 <dt>18.5. <a href="#FILEDVALIDATE">Field Validation</a></dt>
320 <dt>18.6. <a href="#FORMDRIVER">Form Driver: The work horse of the
321 forms system</a></dt>
324 <dt>19. <a href="#TOOLS">Tools and Widget Libraries</a></dt>
327 <dt>19.1. <a href="#CDK">CDK (Curses Development Kit)</a></dt>
328 <dt>19.2. <a href="#DIALOG">The dialog</a></dt>
329 <dt>19.3. <a href="#PERLCURSES">Perl Curses Modules CURSES::FORM
330 and CURSES::WIDGETS</a></dt>
333 <dt>20. <a href="#JUSTFORFUN">Just For Fun !!!</a></dt>
336 <dt>20.1. <a href="#GAMEOFLIFE">The Game of Life</a></dt>
337 <dt>20.2. <a href="#MAGIC">Magic Square</a></dt>
338 <dt>20.3. <a href="#HANOI">Towers of Hanoi</a></dt>
339 <dt>20.4. <a href="#QUEENS">Queens Puzzle</a></dt>
340 <dt>20.5. <a href="#SHUFFLE">Shuffle</a></dt>
341 <dt>20.6. <a href="#TT">Typing Tutor</a></dt>
344 <dt>21. <a href="#REF">References</a></dt>
348 <h2 class="SECT1"><a name="INTRO" id="INTRO">1.
349 Introduction</a></h2>
350 <p>In the olden days of teletype terminals, terminals were away
351 from computers and were connected to them through serial cables.
352 The terminals could be configured by sending a series of bytes. All
353 the capabilities (such as moving the cursor to a new location,
354 erasing part of the screen, scrolling the screen, changing modes
355 etc.) of terminals could be accessed through these series of bytes.
356 These control seeuqnces are usually called escape sequences,
357 because they start with an escape(0x1B) character. Even today, with
358 proper emulation, we can send escape sequences to the emulator and
359 achieve the same effect on a terminal window.</p>
360 <p>Suppose you wanted to print a line in color. Try typing this on
362 <table border="0" bgcolor="#E0E0E0" width="100%">
365 <pre class="PROGRAMLISTING">
366 <font color="#000000">echo "^[[0;31;40mIn Color"</font>
370 <p>The first character is an escape character, which looks like two
371 characters ^ and [. To be able to print it, you have to press
372 CTRL+V and then the ESC key. All the others are normal printable
373 characters. You should be able to see the string "In Color" in red.
374 It stays that way and to revert back to the original mode type
376 <table border="0" bgcolor="#E0E0E0" width="100%">
379 <pre class="PROGRAMLISTING">
380 <font color="#000000">echo "^[[0;37;40m"</font>
384 <p>Now, what do these magic characters mean? Difficult to
385 comprehend? They might even be different for different terminals.
386 So the designers of UNIX invented a mechanism named <var class=
387 "LITERAL">termcap</var>. It is a file that lists all the
388 capabilities of a particular terminal, along with the escape
389 sequences needed to achieve a particular effect. In the later
390 years, this was replaced by <var class="LITERAL">terminfo</var>.
391 Without delving too much into details, this mechanism allows
392 application programs to query the terminfo database and obtain the
393 control characters to be sent to a terminal or terminal
397 <h3 class="SECT2"><a name="WHATIS" id="WHATIS">1.1. What is
399 <p>You might be wondering, what the import of all this technical
400 gibberish is. In the above scenario, every application program is
401 supposed to query the terminfo and perform the necessary stuff
402 (sending control characters etc.). It soon became difficult to
403 manage this complexity and this gave birth to 'CURSES'. Curses is a
404 pun on the name "cursor optimization". The Curses library forms a
405 wrapper over working with raw terminal codes, and provides highly
406 flexible and efficient API (Application Programming Interface). It
407 provides functions to move the cursor, create windows, produce
408 colors, play with mouse etc. The application programs need not
409 worry about the underlying terminal capabilities.</p>
410 <p>So what is NCURSES? NCURSES is a clone of the original System V
411 Release 4.0 (SVr4) curses. It is a freely distributable library,
412 fully compatible with older version of curses. In short, it is a
413 library of functions that manages an application's display on
414 character-cell terminals. In the remainder of the document, the
415 terms curses and ncurses are used interchangeably.</p>
416 <p>A detailed history of NCURSES can be found in the NEWS file from
417 the source distribution. The current package is maintained by
418 <a href="mailto:dickey@his.com" target="_top">Thomas Dickey</a>.
419 You can contact the maintainers at <a href=
420 "mailto:bug-ncurses@gnu.org" target=
421 "_top">bug-ncurses@gnu.org</a>.</p>
425 <h3 class="SECT2"><a name="WHATCANWEDO" id="WHATCANWEDO">1.2. What
426 we can do with NCURSES</a></h3>
427 <p>NCURSES not only creates a wrapper over terminal capabilities,
428 but also gives a robust framework to create nice looking UI (User
429 Interface)s in text mode. It provides functions to create windows
430 etc. Its sister libraries panel, menu and form provide an extension
431 to the basic curses library. These libraries usually come along
432 with curses. One can create applications that contain multiple
433 windows, menus, panels and forms. Windows can be managed
434 independently, can provide 'scrollability' and even can be
436 <p>Menus provide the user with an easy command selection option.
437 Forms allow the creation of easy-to-use data entry and display
438 windows. Panels extend the capabilities of ncurses to deal with
439 overlapping and stacked windows.</p>
440 <p>These are just some of the basic things we can do with ncurses.
441 As we move along, We will see all the capabilities of these
446 <h3 class="SECT2"><a name="WHERETOGETIT" id="WHERETOGETIT">1.3.
447 Where to get it</a></h3>
448 <p>All right, now that you know what you can do with ncurses, you
449 must be rearing to get started. NCURSES is usually shipped with
450 your installation. In case you don't have the library or want to
451 compile it on your own, read on.</p>
452 <p><em>Compiling the package</em></p>
453 <p>NCURSES can be obtained from <a href=
454 "ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz" target=
455 "_top">ftp://ftp.gnu.org/pub/gnu/ncurses/ncurses.tar.gz</a> or any
456 of the ftp sites mentioned in <a href=
457 "http://www.gnu.org/order/ftp.html" target=
458 "_top">http://www.gnu.org/order/ftp.html</a>.</p>
459 <p>Read the README and INSTALL files for details on to how to
460 install it. It usually involves the following operations.</p>
461 <table border="0" bgcolor="#E0E0E0" width="100%">
464 <pre class="PROGRAMLISTING">
466 "#000000"> tar zxvf ncurses<version>.tar.gz # unzip and untar the archive
467 cd ncurses<version> # cd to the directory
468 ./configure # configure the build according to your
471 su root # become root
472 make install # install it</font>
476 <p><em>Using the RPM</em></p>
477 <p>NCURSES RPM can be found and downloaded from <a href=
478 "http://rpmfind.net" target="_top">http://rpmfind.net</a> . The RPM
479 can be installed with the following command after becoming
481 <table border="0" bgcolor="#E0E0E0" width="100%">
484 <pre class="PROGRAMLISTING">
485 <font color="#000000"> rpm -i <downloaded rpm></font>
492 <h3 class="SECT2"><a name="PURPOSE" id="PURPOSE">1.4. Purpose/Scope
493 of the document</a></h3>
494 <p>This document is intended to be a "All in One" guide for
495 programming with ncurses and its sister libraries. We graduate from
496 a simple "Hello World" program to more complex form manipulation.
497 No prior experience in ncurses is assumed. The writing is informal,
498 but a lot of detail is provided for each of the examples.</p>
502 <h3 class="SECT2"><a name="ABOUTPROGRAMS" id="ABOUTPROGRAMS">1.5.
503 About the Programs</a></h3>
504 <p>All the programs in the document are available in zipped form
506 "http://www.tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs.tar.gz"
507 target="_top">here</a>. Unzip and untar it. The directory structure
509 <table border="0" bgcolor="#E0E0E0" width="100%">
512 <pre class="PROGRAMLISTING">
513 <font color="#000000">ncurses
515 |----> JustForFun -- just for fun programs
516 |----> basics -- basic programs
517 |----> demo -- output files go into this directory after make
519 | |----> exe -- exe files of all example programs
520 |----> forms -- programs related to form library
521 |----> menus -- programs related to menus library
522 |----> panels -- programs related to panels library
523 |----> perl -- perl equivalents of the examples (contributed
524 | by Anuradha Ratnaweera)
525 |----> Makefile -- the top level Makefile
526 |----> README -- the top level README file. contains instructions
527 |----> COPYING -- copyright notice</font>
531 <p>The individual directories contain the following files.</p>
532 <table border="0" bgcolor="#E0E0E0" width="100%">
535 <pre class="PROGRAMLISTING">
536 <font color="#000000">Description of files in each directory
537 --------------------------------------
540 |----> hanoi.c -- The Towers of Hanoi Solver
541 |----> life.c -- The Game of Life demo
542 |----> magic.c -- An Odd Order Magic Square builder
543 |----> queens.c -- The famous N-Queens Solver
544 |----> shuffle.c -- A fun game, if you have time to kill
545 |----> tt.c -- A very trivial typing tutor
549 |----> acs_vars.c -- ACS_ variables example
550 |----> hello_world.c -- Simple "Hello World" Program
551 |----> init_func_example.c -- Initialization functions example
552 |----> key_code.c -- Shows the scan code of the key pressed
553 |----> mouse_menu.c -- A menu accessible by mouse
554 |----> other_border.c -- Shows usage of other border functions apa
556 |----> printw_example.c -- A very simple printw() example
557 |----> scanw_example.c -- A very simple getstr() example
558 |----> simple_attr.c -- A program that can print a c file with
559 | -- comments in attribute
560 |----> simple_color.c -- A simple example demonstrating colors
561 |----> simple_key.c -- A menu accessible with keyboard UP, DOWN
563 |----> temp_leave.c -- Demonstrates temporarily leaving curses mode
564 |----> win_border.c -- Shows Creation of windows and borders
565 |----> with_chgat.c -- chgat() usage example
569 |----> form_attrib.c -- Usage of field attributes
570 |----> form_options.c -- Usage of field options
571 |----> form_simple.c -- A simple form example
572 |----> form_win.c -- Demo of windows associated with forms
576 |----> menu_attrib.c -- Usage of menu attributes
577 |----> menu_item_data.c -- Usage of item_name() etc.. functions
578 |----> menu_multi_column.c -- Creates multi columnar menus
579 |----> menu_scroll.c -- Demonstrates scrolling capability of menus
580 |----> menu_simple.c -- A simple menu accessed by arrow keys
581 |----> menu_toggle.c -- Creates multi valued menus and explains
583 |----> menu_userptr.c -- Usage of user pointer
584 |----> menu_win.c -- Demo of windows associated with menus
588 |----> panel_browse.c -- Panel browsing through tab. Usage of user
590 |----> panel_hide.c -- Hiding and Un hiding of panels
591 |----> panel_resize.c -- Moving and resizing of panels
592 |----> panel_simple.c -- A simple panel example
595 |----> 01-10.pl -- Perl equivalents of first ten example programs</font>
599 <p>There is a top level Makefile included in the main directory. It
600 builds all the files and puts the ready-to-use exes in demo/exe
601 directory. You can also do selective make by going into the
602 corresponding directory. Each directory contains a README file
603 explaining the purpose of each c file in the directory.</p>
604 <p>For every example, I have included path name for the file
605 relative to the examples directory.</p>
606 <p>If you prefer browsing individual programs, point your browser
608 "http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/"
610 "_top">http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ncurses_programs/</a></p>
611 <p>All the programs are released under the same license that is
612 used by ncurses (MIT-style). This gives you the ability to do
613 pretty much anything other than claiming them as yours. Feel free
614 to use them in your programs as appropriate.</p>
618 <h3 class="SECT2"><a name="OTHERFORMATS" id="OTHERFORMATS">1.6.
619 Other Formats of the document</a></h3>
620 <p>This howto is also availabe in various other formats on the
621 tldp.org site. Here are the links to other formats of this
625 <h4 class="SECT3"><a name="LISTFORMATS" id="LISTFORMATS">1.6.1.
626 Readily available formats from tldp.org</a></h4>
630 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/pdf/NCURSES-Programming-HOWTO.pdf"
631 target="_top">Acrobat PDF Format</a></p>
635 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/ps/NCURSES-Programming-HOWTO.ps.gz"
636 target="_top">PostScript Format</a></p>
640 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html/NCURSES-Programming-HOWTO-html.tar.gz"
641 target="_top">In Multiple HTML pages</a></p>
645 "http://www.ibiblio.org/pub/Linux/docs/HOWTO/other-formats/html_single/NCURSES-Programming-HOWTO.html"
646 target="_top">In One big HTML format</a></p>
652 <h4 class="SECT3"><a name="BUILDSOURCE" id="BUILDSOURCE">1.6.2.
653 Building from source</a></h4>
654 <p>If above links are broken or if you want to experiment with sgml
656 <table border="0" bgcolor="#E0E0E0" width="100%">
659 <pre class="PROGRAMLISTING">
661 "#000000"> Get both the source and the tar,gzipped programs, available at
662 http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
663 NCURSES-HOWTO/NCURSES-Programming-HOWTO.sgml
664 http://cvsview.tldp.org/index.cgi/LDP/howto/docbook/
665 NCURSES-HOWTO/ncurses_programs.tar.gz
667 Unzip ncurses_programs.tar.gz with
668 tar zxvf ncurses_programs.tar.gz
670 Use jade to create various formats. For example if you just want to create
671 the multiple html files, you would use
672 jade -t sgml -i html -d <path to docbook html stylesheet>
673 NCURSES-Programming-HOWTO.sgml
674 to get pdf, first create a single html file of the HOWTO with
675 jade -t sgml -i html -d <path to docbook html stylesheet> -V nochunks
676 NCURSES-Programming-HOWTO.sgml > NCURSES-ONE-BIG-FILE.html
677 then use htmldoc to get pdf file with
678 htmldoc --size universal -t pdf --firstpage p1 -f <output file name.pdf>
679 NCURSES-ONE-BIG-FILE.html
680 for ps, you would use
681 htmldoc --size universal -t ps --firstpage p1 -f <output file name.ps>
682 NCURSES-ONE-BIG-FILE.html</font>
686 <p>See <a href="http://www.tldp.org/LDP/LDP-Author-Guide/" target=
687 "_top">LDP Author guide</a> for more details. If all else failes,
688 mail me at <a href="ppadala@gmail.com" target=
689 "_top">ppadala@gmail.com</a></p>
694 <h3 class="SECT2"><a name="CREDITS" id="CREDITS">1.7.
696 <p>I thank <a href="mailto:sharath_1@usa.net" target=
697 "_top">Sharath</a> and Emre Akbas for helping me with few sections.
698 The introduction was initially written by sharath. I rewrote it
699 with few excerpts taken from his initial work. Emre helped in
700 writing printw and scanw sections.</p>
701 <p>Perl equivalents of the example programs are contributed by
702 <a href="mailto:Aratnaweera@virtusa.com" target="_top">Anuradha
704 <p>Then comes <a href="mailto:parimi@ece.arizona.edu" target=
705 "_top">Ravi Parimi</a>, my dearest friend, who has been on this
706 project before even one line was written. He constantly bombarded
707 me with suggestions and patiently reviewed the whole text. He also
708 checked each program on Linux and Solaris.</p>
712 <h3 class="SECT2"><a name="WISHLIST" id="WISHLIST">1.8. Wish
714 <p>This is the wish list, in the order of priority. If you have a
715 wish or you want to work on completing the wish, mail <a href=
716 "mailto:ppadala@gmail.com" target="_top">me</a>.</p>
719 <p>Add examples to last parts of forms section.</p>
722 <p>Prepare a Demo showing all the programs and allow the user to
723 browse through description of each program. Let the user compile
724 and see the program in action. A dialog based interface is
728 <p>Add debug info. _tracef, _tracemouse stuff.</p>
731 <p>Accessing termcap, terminfo using functions provided by ncurses
735 <p>Working on two terminals simultaneously.</p>
738 <p>Add more stuff to miscellaneous section.</p>
744 <h3 class="SECT2"><a name="COPYRIGHT" id="COPYRIGHT">1.9.
746 <p>Copyright © 2001 by Pradeep Padala.</p>
747 <p>Permission is hereby granted, free of charge, to any person
748 obtaining a copy of this software and associated documentation
749 files (the "Software"), to deal in the Software without
750 restriction, including without limitation the rights to use, copy,
751 modify, merge, publish, distribute, distribute with modifications,
752 sublicense, and/or sell copies of the Software, and to permit
753 persons to whom the Software is furnished to do so, subject to the
754 following conditions:</p>
755 <p>The above copyright notice and this permission notice shall be
756 included in all copies or substantial portions of the Software.</p>
757 <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
758 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
759 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
760 NONINFRINGEMENT. IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE
761 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
762 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
763 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
765 <p>Except as contained in this notice, the name(s) of the above
766 copyright holders shall not be used in advertising or otherwise to
767 promote the sale, use or other dealings in this Software without
768 prior written authorization.</p>
773 <h2 class="SECT1"><a name="HELLOWORLD" id="HELLOWORLD">2. Hello
775 <p>Welcome to the world of curses. Before we plunge into the
776 library and look into its various features, let's write a simple
777 program and say hello to the world.</p>
780 <h3 class="SECT2"><a name="COMPILECURSES" id="COMPILECURSES">2.1.
781 Compiling With the NCURSES Library</a></h3>
782 <p>To use ncurses library functions, you have to include ncurses.h
783 in your programs. To link the program with ncurses the flag
784 -lncurses should be added.</p>
785 <table border="0" bgcolor="#E0E0E0" width="100%">
788 <pre class="PROGRAMLISTING">
789 <font color="#000000"> #include <ncurses.h>
794 compile and link: gcc <program file> -lncurses</font>
798 <div class="EXAMPLE"><a name="BHW" id="BHW"></a>
799 <p><b>Example 1. The Hello World !!! Program</b></p>
800 <table border="0" bgcolor="#E0E0E0" width="100%">
803 <pre class="PROGRAMLISTING">
804 <font color="#000000"><span class=
805 "INLINEMEDIAOBJECT">#include <ncurses.h>
809 initscr(); /* Start curses mode */
810 printw("Hello World !!!"); /* Print Hello World */
811 refresh(); /* Print it on to the real screen */
812 getch(); /* Wait for user input */
813 endwin(); /* End curses mode */
824 <h3 class="SECT2"><a name="DISSECTION" id="DISSECTION">2.2.
826 <p>The above program prints "Hello World !!!" to the screen and
827 exits. This program shows how to initialize curses and do screen
828 manipulation and end curses mode. Let's dissect it line by
832 <h4 class="SECT3"><a name="ABOUT-INITSCR" id="ABOUT-INITSCR">2.2.1.
833 About initscr()</a></h4>
834 <p>The function initscr() initializes the terminal in curses mode.
835 In some implementations, it clears the screen and presents a blank
836 screen. To do any screen manipulation using curses package this has
837 to be called first. This function initializes the curses system and
838 allocates memory for our present window (called <var class=
839 "LITERAL">stdscr</var>) and some other data-structures. Under
840 extreme cases this function might fail due to insufficient memory
841 to allocate memory for curses library's data structures.</p>
842 <p>After this is done, we can do a variety of initializations to
843 customize our curses settings. These details will be explained
844 <a href="#INIT">later</a> .</p>
848 <h4 class="SECT3"><a name="MYST-REFRESH" id="MYST-REFRESH">2.2.2.
849 The mysterious refresh()</a></h4>
850 <p>The next line printw prints the string "Hello World !!!" on to
851 the screen. This function is analogous to normal printf in all
852 respects except that it prints the data on a window called stdscr
853 at the current (y,x) co-ordinates. Since our present co-ordinates
854 are at 0,0 the string is printed at the left hand corner of the
856 <p>This brings us to that mysterious refresh(). Well, when we
857 called printw the data is actually written to an imaginary window,
858 which is not updated on the screen yet. The job of printw is to
859 update a few flags and data structures and write the data to a
860 buffer corresponding to stdscr. In order to show it on the screen,
861 we need to call refresh() and tell the curses system to dump the
862 contents on the screen.</p>
863 <p>The philosophy behind all this is to allow the programmer to do
864 multiple updates on the imaginary screen or windows and do a
865 refresh once all his screen update is done. refresh() checks the
866 window and updates only the portion which has been changed. This
867 improves performance and offers greater flexibility too. But, it is
868 sometimes frustrating to beginners. A common mistake committed by
869 beginners is to forget to call refresh() after they did some update
870 through printw() class of functions. I still forget to add it
875 <h4 class="SECT3"><a name="ABOUT-ENDWIN" id="ABOUT-ENDWIN">2.2.3.
876 About endwin()</a></h4>
877 <p>And finally don't forget to end the curses mode. Otherwise your
878 terminal might behave strangely after the program quits. endwin()
879 frees the memory taken by curses sub-system and its data structures
880 and puts the terminal in normal mode. This function must be called
881 after you are done with the curses mode.</p>
887 <h2 class="SECT1"><a name="GORY" id="GORY">3. The Gory
889 <p>Now that we have seen how to write a simple curses program let's
890 get into the details. There are many functions that help customize
891 what you see on screen and many features which can be put to full
897 <h2 class="SECT1"><a name="INIT" id="INIT">4.
898 Initialization</a></h2>
899 <p>We now know that to initialize curses system the function
900 initscr() has to be called. There are functions which can be called
901 after this initialization to customize our curses session. We may
902 ask the curses system to set the terminal in raw mode or initialize
903 color or initialize the mouse etc.. Let's discuss some of the
904 functions that are normally called immediately after initscr();</p>
907 <h3 class="SECT2"><a name="ABOUTINIT" id="ABOUTINIT">4.1.
908 Initialization functions</a></h3>
912 <h3 class="SECT2"><a name="RAWCBREAK" id="RAWCBREAK">4.2. raw() and
914 <p>Normally the terminal driver buffers the characters a user types
915 until a new line or carriage return is encountered. But most
916 programs require that the characters be available as soon as the
917 user types them. The above two functions are used to disable line
918 buffering. The difference between these two functions is in the way
919 control characters like suspend (CTRL-Z), interrupt and quit
920 (CTRL-C) are passed to the program. In the raw() mode these
921 characters are directly passed to the program without generating a
922 signal. In the <var class="LITERAL">cbreak()</var> mode these
923 control characters are interpreted as any other character by the
924 terminal driver. I personally prefer to use raw() as I can exercise
925 greater control over what the user does.</p>
929 <h3 class="SECT2"><a name="ECHONOECHO" id="ECHONOECHO">4.3. echo()
930 and noecho()</a></h3>
931 <p>These functions control the echoing of characters typed by the
932 user to the terminal. <var class="LITERAL">noecho()</var> switches
933 off echoing. The reason you might want to do this is to gain more
934 control over echoing or to suppress unnecessary echoing while
935 taking input from the user through the getch() etc. functions. Most
936 of the interactive programs call <var class=
937 "LITERAL">noecho()</var> at initialization and do the echoing of
938 characters in a controlled manner. It gives the programmer the
939 flexibility of echoing characters at any place in the window
940 without updating current (y,x) co-ordinates.</p>
944 <h3 class="SECT2"><a name="KEYPAD" id="KEYPAD">4.4.
946 <p>This is my favorite initialization function. It enables the
947 reading of function keys like F1, F2, arrow keys etc. Almost every
948 interactive program enables this, as arrow keys are a major part of
949 any User Interface. Do <var class="LITERAL">keypad(stdscr,
950 TRUE)</var> to enable this feature for the regular screen (stdscr).
951 You will learn more about key management in later sections of this
956 <h3 class="SECT2"><a name="HALFDELAY" id="HALFDELAY">4.5.
958 <p>This function, though not used very often, is a useful one at
959 times. halfdelay()is called to enable the half-delay mode, which is
960 similar to the cbreak() mode in that characters typed are
961 immediately available to program. However, it waits for 'X' tenths
962 of a second for input and then returns ERR, if no input is
963 available. 'X' is the timeout value passed to the function
964 halfdelay(). This function is useful when you want to ask the user
965 for input, and if he doesn't respond with in certain time, we can
966 do some thing else. One possible example is a timeout at the
971 <h3 class="SECT2"><a name="MISCINIT" id="MISCINIT">4.6.
972 Miscellaneous Initialization functions</a></h3>
973 <p>There are few more functions which are called at initialization
974 to customize curses behavior. They are not used as extensively as
975 those mentioned above. Some of them are explained where
980 <h3 class="SECT2"><a name="INITEX" id="INITEX">4.7. An
982 <p>Let's write a program which will clarify the usage of these
984 <div class="EXAMPLE"><a name="BINFU" id="BINFU"></a>
985 <p><b>Example 2. Initialization Function Usage example</b></p>
986 <table border="0" bgcolor="#E0E0E0" width="100%">
989 <pre class="PROGRAMLISTING">
990 <font color="#000000"><span class=
991 "INLINEMEDIAOBJECT">#include <ncurses.h>
996 initscr(); /* Start curses mode */
997 raw(); /* Line buffering disabled */
998 keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
999 noecho(); /* Don't echo() while we do getch */
1001 printw("Type any character to see it in bold\n");
1002 ch = getch(); /* If raw() hadn't been called
1003 * we have to press enter before it
1004 * gets to the program */
1005 if(ch == KEY_F(1)) /* Without keypad enabled this will */
1006 printw("F1 Key pressed");/* not get to us either */
1007 /* Without noecho() some ugly escape
1008 * charachters might have been printed
1011 { printw("The pressed key is ");
1016 refresh(); /* Print it on to the real screen */
1017 getch(); /* Wait for user input */
1018 endwin(); /* End curses mode */
1026 <p>This program is self-explanatory. But I used functions which
1027 aren't explained yet. The function <var class=
1028 "LITERAL">getch()</var> is used to get a character from user. It is
1029 equivalent to normal <var class="LITERAL">getchar()</var> except
1030 that we can disable the line buffering to avoid <enter> after
1031 input. Look for more about <var class="LITERAL">getch()</var>and
1032 reading keys in the <a href="#KEYS">key management section</a> .
1033 The functions attron and attroff are used to switch some attributes
1034 on and off respectively. In the example I used them to print the
1035 character in bold. These functions are explained in detail
1041 <h2 class="SECT1"><a name="AWORDWINDOWS" id="AWORDWINDOWS">5. A
1042 Word about Windows</a></h2>
1043 <p>Before we plunge into the myriad ncurses functions, let me clear
1044 few things about windows. Windows are explained in detail in
1045 following <a href="#WINDOWS">sections</a></p>
1046 <p>A Window is an imaginary screen defined by curses system. A
1047 window does not mean a bordered window which you usually see on
1048 Win9X platforms. When curses is initialized, it creates a default
1049 window named <var class="LITERAL">stdscr</var> which represents
1050 your 80x25 (or the size of window in which you are running) screen.
1051 If you are doing simple tasks like printing few strings, reading
1052 input etc., you can safely use this single window for all of your
1053 purposes. You can also create windows and call functions which
1054 explicitly work on the specified window.</p>
1055 <p>For example, if you call</p>
1056 <table border="0" bgcolor="#E0E0E0" width="100%">
1059 <pre class="PROGRAMLISTING">
1060 <font color="#000000"> printw("Hi There !!!");
1065 <p>It prints the string on stdscr at the present cursor position.
1066 Similarly the call to refresh(), works on stdscr only.</p>
1067 <p>Say you have created <a href="#WINDOWS">windows</a> then you
1068 have to call a function with a 'w' added to the usual function.</p>
1069 <table border="0" bgcolor="#E0E0E0" width="100%">
1072 <pre class="PROGRAMLISTING">
1073 <font color="#000000"> wprintw(win, "Hi There !!!");
1074 wrefresh(win);</font>
1078 <p>As you will see in the rest of the document, naming of functions
1079 follow the same convention. For each function there usually are
1080 three more functions.</p>
1081 <table border="0" bgcolor="#E0E0E0" width="100%">
1084 <pre class="PROGRAMLISTING">
1086 "#000000"> printw(string); /* Print on stdscr at present cursor position */
1087 mvprintw(y, x, string);/* Move to (y, x) then print string */
1088 wprintw(win, string); /* Print on window win at present cursor position */
1090 mvwprintw(win, y, x, string); /* Move to (y, x) relative to window */
1091 /* co-ordinates and then print */</font>
1095 <p>Usually the w-less functions are macros which expand to
1096 corresponding w-function with stdscr as the window parameter.</p>
1100 <h2 class="SECT1"><a name="PRINTW" id="PRINTW">6. Output
1102 <p>I guess you can't wait any more to see some action. Back to our
1103 odyssey of curses functions. Now that curses is initialized, let's
1104 interact with world.</p>
1105 <p>There are three classes of functions which you can use to do
1106 output on screen.</p>
1109 <p>addch() class: Print single character with attributes</p>
1112 <p>printw() class: Print formatted output similar to printf()</p>
1115 <p>addstr() class: Print strings</p>
1118 <p>These functions can be used interchangeably and it's a matter of
1119 style as to which class is used. Let's see each one in detail.</p>
1122 <h3 class="SECT2"><a name="ADDCHCLASS" id="ADDCHCLASS">6.1. addch()
1123 class of functions</a></h3>
1124 <p>These functions put a single character into the current cursor
1125 location and advance the position of the cursor. You can give the
1126 character to be printed but they usually are used to print a
1127 character with some attributes. Attributes are explained in detail
1128 in later <a href="#ATTRIB">sections</a> of the document. If a
1129 character is associated with an attribute(bold, reverse video
1130 etc.), when curses prints the character, it is printed in that
1132 <p>In order to combine a character with some attributes, you have
1136 <p>By OR'ing a single character with the desired attribute macros.
1137 These attribute macros could be found in the header file
1138 <var class="LITERAL">ncurses.h</var>. For example, you want to
1139 print a character ch(of type char) bold and underlined, you would
1140 call addch() as below.</p>
1141 <table border="0" bgcolor="#E0E0E0" width="90%">
1144 <pre class="PROGRAMLISTING">
1145 <font color="#000000"> addch(ch | A_BOLD | A_UNDERLINE);</font>
1151 <p>By using functions like <var class=
1152 "LITERAL">attrset(),attron(),attroff()</var>. These functions are
1153 explained in the <a href="#ATTRIB">Attributes</a> section. Briefly,
1154 they manipulate the current attributes of the given window. Once
1155 set, the character printed in the window are associated with the
1156 attributes until it is turned off.</p>
1159 <p>Additionally, <var class="LITERAL">curses</var> provides some
1160 special characters for character-based graphics. You can draw
1161 tables, horizontal or vertical lines, etc. You can find all
1162 avaliable characters in the header file <var class=
1163 "LITERAL">ncurses.h</var>. Try looking for macros beginning with
1164 <var class="LITERAL">ACS_</var> in this file.</p>
1168 <h3 class="SECT2"><a name="AEN298" id="AEN298">6.2. mvaddch(),
1169 waddch() and mvwaddch()</a></h3>
1170 <p><var class="LITERAL">mvaddch()</var> is used to move the cursor
1171 to a given point, and then print. Thus, the calls:</p>
1172 <table border="0" bgcolor="#E0E0E0" width="100%">
1175 <pre class="PROGRAMLISTING">
1177 "#000000"> move(row,col); /* moves the cursor to row<em>th</em> row and col<em>th</em> column */
1183 <table border="0" bgcolor="#E0E0E0" width="100%">
1186 <pre class="PROGRAMLISTING">
1187 <font color="#000000"> mvaddch(row,col,ch);</font>
1191 <p><var class="LITERAL">waddch()</var> is similar to <var class=
1192 "LITERAL">addch()</var>, except that it adds a character into the
1193 given window. (Note that <var class="LITERAL">addch()</var> adds a
1194 character into the window <var class="LITERAL">stdscr</var>.)</p>
1195 <p>In a similar fashion <var class="LITERAL">mvwaddch()</var>
1196 function is used to add a character into the given window at the
1197 given coordinates.</p>
1198 <p>Now, we are familiar with the basic output function <var class=
1199 "LITERAL">addch()</var>. But, if we want to print a string, it
1200 would be very annoying to print it character by character.
1201 Fortunately, <var class="LITERAL">ncurses</var> provides
1202 <var class="LITERAL">printf</var><em>-like</em> or <var class=
1203 "LITERAL">puts</var><em>-like</em> functions.</p>
1207 <h3 class="SECT2"><a name="PRINTWCLASS" id="PRINTWCLASS">6.3.
1208 printw() class of functions</a></h3>
1209 <p>These functions are similar to <var class=
1210 "LITERAL">printf()</var> with the added capability of printing at
1211 any position on the screen.</p>
1214 <h4 class="SECT3"><a name="PRINTWMVPRINTW" id=
1215 "PRINTWMVPRINTW">6.3.1. printw() and mvprintw</a></h4>
1216 <p>These two functions work much like <var class=
1217 "LITERAL">printf()</var>. <var class="LITERAL">mvprintw()</var> can
1218 be used to move the cursor to a position and then print. If you
1219 want to move the cursor first and then print using <var class=
1220 "LITERAL">printw()</var> function, use <var class=
1221 "LITERAL">move()</var> first and then use <var class=
1222 "LITERAL">printw()</var> though I see no point why one should avoid
1223 using <var class="LITERAL">mvprintw()</var>, you have the
1224 flexibility to manipulate.</p>
1228 <h4 class="SECT3"><a name="WPRINTWMVWPRINTW" id=
1229 "WPRINTWMVWPRINTW">6.3.2. wprintw() and mvwprintw</a></h4>
1230 <p>These two functions are similar to above two except that they
1231 print in the corresponding window given as argument.</p>
1235 <h4 class="SECT3"><a name="VWPRINTW" id="VWPRINTW">6.3.3.
1237 <p>This function is similar to <var class=
1238 "LITERAL">vprintf()</var>. This can be used when variable number of
1239 arguments are to be printed.</p>
1243 <h4 class="SECT3"><a name="SIMPLEPRINTWEX" id=
1244 "SIMPLEPRINTWEX">6.3.4. A Simple printw example</a></h4>
1245 <div class="EXAMPLE"><a name="BPREX" id="BPREX"></a>
1246 <p><b>Example 3. A Simple printw example</b></p>
1247 <table border="0" bgcolor="#E0E0E0" width="100%">
1250 <pre class="PROGRAMLISTING">
1251 <font color="#000000"><span class=
1252 "INLINEMEDIAOBJECT">#include <ncurses.h> /* ncurses.h includes stdio.h */
1253 #include <string.h>
1257 char mesg[]="Just a string"; /* message to be appeared on the screen */
1258 int row,col; /* to store the number of rows and *
1259 * the number of colums of the screen */
1260 initscr(); /* start the curses mode */
1261 getmaxyx(stdscr,row,col); /* get the number of rows and columns */
1262 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
1263 /* print the message at the center of the screen */
1264 mvprintw(row-2,0,"This screen has %d rows and %d columns\n",row,col);
1265 printw("Try resizing your window(if possible) and then run this program again");
1276 <p>Above program demonstrates how easy it is to use <var class=
1277 "LITERAL">printw</var>. You just feed the coordinates and the
1278 message to be appeared on the screen, then it does what you
1280 <p>The above program introduces us to a new function <var class=
1281 "LITERAL">getmaxyx()</var>, a macro defined in <var class=
1282 "LITERAL">ncurses.h</var>. It gives the number of columns and the
1283 number of rows in a given window. <var class=
1284 "LITERAL">getmaxyx()</var> does this by updating the variables
1285 given to it. Since <var class="LITERAL">getmaxyx()</var> is not a
1286 function we don't pass pointers to it, we just give two integer
1292 <h3 class="SECT2"><a name="ADDSTRCLASS" id="ADDSTRCLASS">6.4.
1293 addstr() class of functions</a></h3>
1294 <p><var class="LITERAL">addstr()</var> is used to put a character
1295 string into a given window. This function is similar to calling
1296 <var class="LITERAL">addch()</var> once for each character in a
1297 given string. This is true for all output functions. There are
1298 other functions from this family such as <var class=
1299 "LITERAL">mvaddstr(),mvwaddstr()</var> and <var class=
1300 "LITERAL">waddstr()</var>, which obey the naming convention of
1301 curses.(e.g. mvaddstr() is similar to the respective calls move()
1302 and then addstr().) Another function of this family is addnstr(),
1303 which takes an integer parameter(say n) additionally. This function
1304 puts at most n characters into the screen. If n is negative, then
1305 the entire string will be added.</p>
1309 <h3 class="SECT2"><a name="ACAUTION" id="ACAUTION">6.5. A word of
1311 <p>All these functions take y co-ordinate first and then x in their
1312 arguments. A common mistake by beginners is to pass x,y in that
1313 order. If you are doing too many manipulations of (y,x)
1314 co-ordinates, think of dividing the screen into windows and
1315 manipulate each one separately. Windows are explained in the
1316 <a href="#WINDOWS">windows</a> section.</p>
1321 <h2 class="SECT1"><a name="SCANW" id="SCANW">7. Input
1323 <p>Well, printing without taking input, is boring. Let's see
1324 functions which allow us to get input from user. These functions
1325 also can be divided into three categories.</p>
1328 <p>getch() class: Get a character</p>
1331 <p>scanw() class: Get formatted input</p>
1334 <p>getstr() class: Get strings</p>
1339 <h3 class="SECT2"><a name="GETCHCLASS" id="GETCHCLASS">7.1. getch()
1340 class of functions</a></h3>
1341 <p>These functions read a single character from the terminal. But
1342 there are several subtle facts to consider. For example if you
1343 don't use the function cbreak(), curses will not read your input
1344 characters contiguously but will begin read them only after a new
1345 line or an EOF is encountered. In order to avoid this, the cbreak()
1346 function must used so that characters are immediately available to
1347 your program. Another widely used function is noecho(). As the name
1348 suggests, when this function is set (used), the characters that are
1349 keyed in by the user will not show up on the screen. The two
1350 functions cbreak() and noecho() are typical examples of key
1351 management. Functions of this genre are explained in the <a href=
1352 "#KEYS">key management section</a> .</p>
1356 <h3 class="SECT2"><a name="SCANWCLASS" id="SCANWCLASS">7.2. scanw()
1357 class of functions</a></h3>
1358 <p>These functions are similar to <var class=
1359 "LITERAL">scanf()</var> with the added capability of getting the
1360 input from any location on the screen.</p>
1363 <h4 class="SECT3"><a name="SCANWMVSCANW" id="SCANWMVSCANW">7.2.1.
1364 scanw() and mvscanw</a></h4>
1365 <p>The usage of these functions is similar to that of <var class=
1366 "LITERAL">sscanf()</var>, where the line to be scanned is provided
1367 by <var class="LITERAL">wgetstr()</var> function. That is, these
1368 functions call to <var class="LITERAL">wgetstr()</var>
1369 function(explained below) and uses the resulting line for a
1374 <h4 class="SECT3"><a name="WSCANWMVWSCANW" id=
1375 "WSCANWMVWSCANW">7.2.2. wscanw() and mvwscanw()</a></h4>
1376 <p>These are similar to above two functions except that they read
1377 from a window, which is supplied as one of the arguments to these
1382 <h4 class="SECT3"><a name="VWSCANW" id="VWSCANW">7.2.3.
1384 <p>This function is similar to <var class="LITERAL">vscanf()</var>.
1385 This can be used when a variable number of arguments are to be
1391 <h3 class="SECT2"><a name="GETSTRCLASS" id="GETSTRCLASS">7.3.
1392 getstr() class of functions</a></h3>
1393 <p>These functions are used to get strings from the terminal. In
1394 essence, this function performs the same task as would be achieved
1395 by a series of calls to <var class="LITERAL">getch()</var> until a
1396 newline, carriage return, or end-of-file is received. The resulting
1397 string of characters are pointed to by <var class=
1398 "LITERAL">str</var>, which is a character pointer provided by the
1403 <h3 class="SECT2"><a name="GETSTREX" id="GETSTREX">7.4. Some
1405 <div class="EXAMPLE"><a name="BSCEX" id="BSCEX"></a>
1406 <p><b>Example 4. A Simple scanw example</b></p>
1407 <table border="0" bgcolor="#E0E0E0" width="100%">
1410 <pre class="PROGRAMLISTING">
1411 <font color="#000000"><span class=
1412 "INLINEMEDIAOBJECT">#include <ncurses.h> /* ncurses.h includes stdio.h */
1413 #include <string.h>
1417 char mesg[]="Enter a string: "; /* message to be appeared on the screen */
1419 int row,col; /* to store the number of rows and *
1420 * the number of colums of the screen */
1421 initscr(); /* start the curses mode */
1422 getmaxyx(stdscr,row,col); /* get the number of rows and columns */
1423 mvprintw(row/2,(col-strlen(mesg))/2,"%s",mesg);
1424 /* print the message at the center of the screen */
1426 mvprintw(LINES - 2, 0, "You Entered: %s", str);
1440 <h2 class="SECT1"><a name="ATTRIB" id="ATTRIB">8.
1442 <p>We have seen an example of how attributes can be used to print
1443 characters with some special effects. Attributes, when set
1444 prudently, can present information in an easy, understandable
1445 manner. The following program takes a C file as input and prints
1446 the file with comments in bold. Scan through the code.</p>
1447 <div class="EXAMPLE"><a name="BSIAT" id="BSIAT"></a>
1448 <p><b>Example 5. A Simple Attributes example</b></p>
1449 <table border="0" bgcolor="#E0E0E0" width="100%">
1452 <pre class="PROGRAMLISTING">
1453 <font color="#000000"><span class=
1454 "INLINEMEDIAOBJECT">/* pager functionality by Joseph Spainhour" <spainhou@bellsouth.net> */
1455 #include <ncurses.h>
1456 #include <stdlib.h>
1458 int main(int argc, char *argv[])
1460 int ch, prev, row, col;
1467 printf("Usage: %s <a c file name>\n", argv[0]);
1470 fp = fopen(argv[1], "r");
1473 perror("Cannot open input file");
1476 initscr(); /* Start curses mode */
1477 getmaxyx(stdscr, row, col); /* find the boundaries of the screeen */
1478 while((ch = fgetc(fp)) != EOF) /* read the file till we reach the end */
1480 getyx(stdscr, y, x); /* get the current curser position */
1481 if(y == (row - 1)) /* are we are at the end of the screen */
1483 printw("<-Press Any Key->"); /* tell the user to press a key */
1485 clear(); /* clear the screen */
1486 move(0, 0); /* start at the beginning of the screen */
1488 if(prev == '/' && ch == '*') /* If it is / and * then only
1491 attron(A_BOLD); /* cut bold on */
1492 getyx(stdscr, y, x); /* get the current curser position */
1493 move(y, x - 1); /* back up one space */
1494 printw("%c%c", '/', ch); /* The actual printing is done here */
1499 if(prev == '*' && ch == '/')
1500 attroff(A_BOLD); /* Switch it off once we got *
1504 endwin(); /* End curses mode */
1512 <p>Don't worry about all those initialization and other crap.
1513 Concentrate on the while loop. It reads each character in the file
1514 and searches for the pattern /*. Once it spots the pattern, it
1515 switches the BOLD attribute on with <var class=
1516 "LITERAL">attron()</var> . When we get the pattern */ it is
1517 switched off by <var class="LITERAL">attroff()</var> .</p>
1518 <p>The above program also introduces us to two useful functions
1519 <var class="LITERAL">getyx()</var> and <var class=
1520 "LITERAL">move()</var>. The first function gets the co-ordinates of
1521 the present cursor into the variables y, x. Since getyx() is a
1522 macro we don't have to pass pointers to variables. The function
1523 <var class="LITERAL">move()</var> moves the cursor to the
1524 co-ordinates given to it.</p>
1525 <p>The above program is really a simple one which doesn't do much.
1526 On these lines one could write a more useful program which reads a
1527 C file, parses it and prints it in different colors. One could even
1528 extend it to other languages as well.</p>
1531 <h3 class="SECT2"><a name="ATTRIBDETAILS" id="ATTRIBDETAILS">8.1.
1532 The details</a></h3>
1533 <p>Let's get into more details of attributes. The functions
1534 <var class="LITERAL">attron(), attroff(), attrset()</var> , and
1535 their sister functions <var class="LITERAL">attr_get()</var> etc..
1536 can be used to switch attributes on/off , get attributes and
1537 produce a colorful display.</p>
1538 <p>The functions attron and attroff take a bit-mask of attributes
1539 and switch them on or off, respectively. The following video
1540 attributes, which are defined in <curses.h> can be passed to
1541 these functions.</p>
1542 <table border="0" bgcolor="#E0E0E0" width="100%">
1545 <pre class="PROGRAMLISTING">
1546 <font color="#000000">
1547 A_NORMAL Normal display (no highlight)
1548 A_STANDOUT Best highlighting mode of the terminal.
1549 A_UNDERLINE Underlining
1550 A_REVERSE Reverse video
1553 A_BOLD Extra bright or bold
1554 A_PROTECT Protected mode
1555 A_INVIS Invisible or blank mode
1556 A_ALTCHARSET Alternate character set
1557 A_CHARTEXT Bit-mask to extract a character
1558 COLOR_PAIR(n) Color-pair number n
1563 <p>The last one is the most colorful one :-) Colors are explained
1564 in the <a href="#color" target="_top">next sections</a>.</p>
1565 <p>We can OR(|) any number of above attributes to get a combined
1566 effect. If you wanted reverse video with blinking characters you
1568 <table border="0" bgcolor="#E0E0E0" width="100%">
1571 <pre class="PROGRAMLISTING">
1572 <font color="#000000"> attron(A_REVERSE | A_BLINK);</font>
1579 <h3 class="SECT2"><a name="ATTRONVSATTRSET" id=
1580 "ATTRONVSATTRSET">8.2. attron() vs attrset()</a></h3>
1581 <p>Then what is the difference between attron() and attrset()?
1582 attrset sets the attributes of window whereas attron just switches
1583 on the attribute given to it. So attrset() fully overrides whatever
1584 attributes the window previously had and sets it to the new
1585 attribute(s). Similarly attroff() just switches off the
1586 attribute(s) given to it as an argument. This gives us the
1587 flexibility of managing attributes easily.But if you use them
1588 carelessly you may loose track of what attributes the window has
1589 and garble the display. This is especially true while managing
1590 menus with colors and highlighting. So decide on a consistent
1591 policy and stick to it. You can always use <var class=
1592 "LITERAL">standend()</var> which is equivalent to <var class=
1593 "LITERAL">attrset(A_NORMAL)</var> which turns off all attributes
1594 and brings you to normal mode.</p>
1598 <h3 class="SECT2"><a name="ATTR_GET" id="ATTR_GET">8.3.
1600 <p>The function attr_get() gets the current attributes and color
1601 pair of the window. Though we might not use this as often as the
1602 above functions, this is useful in scanning areas of screen. Say we
1603 wanted to do some complex update on screen and we are not sure what
1604 attribute each character is associated with. Then this function can
1605 be used with either attrset or attron to produce the desired
1610 <h3 class="SECT2"><a name="ATTR_FUNCS" id="ATTR_FUNCS">8.4. attr_
1612 <p>There are series of functions like attr_set(), attr_on etc..
1613 These are similar to above functions except that they take
1614 parameters of type <var class="LITERAL">attr_t</var>.</p>
1618 <h3 class="SECT2"><a name="WATTRFUNCS" id="WATTRFUNCS">8.5. wattr
1620 <p>For each of the above functions we have a corresponding function
1621 with 'w' which operates on a particular window. The above functions
1622 operate on stdscr.</p>
1626 <h3 class="SECT2"><a name="CHGAT" id="CHGAT">8.6. chgat()
1628 <p>The function chgat() is listed in the end of the man page
1629 curs_attr. It actually is a useful one. This function can be used
1630 to set attributes for a group of characters without moving. I mean
1631 it !!! without moving the cursor :-) It changes the attributes of a
1632 given number of characters starting at the current cursor
1634 <p>We can give -1 as the character count to update till end of
1635 line. If you want to change attributes of characters from current
1636 position to end of line, just use this.</p>
1637 <table border="0" bgcolor="#E0E0E0" width="100%">
1640 <pre class="PROGRAMLISTING">
1641 <font color="#000000"> chgat(-1, A_REVERSE, 0, NULL);</font>
1645 <p>This function is useful when changing attributes for characters
1646 that are already on the screen. Move to the character from which
1647 you want to change and change the attribute.</p>
1648 <p>Other functions wchgat(), mvchgat(), wchgat() behave similarly
1649 except that the w functions operate on the particular window. The
1650 mv functions first move the cursor then perform the work given to
1651 them. Actually chgat is a macro which is replaced by a wchgat()
1652 with stdscr as the window. Most of the "w-less" functions are
1654 <div class="EXAMPLE"><a name="BWICH" id="BWICH"></a>
1655 <p><b>Example 6. Chgat() Usage example</b></p>
1656 <table border="0" bgcolor="#E0E0E0" width="100%">
1659 <pre class="PROGRAMLISTING">
1660 <font color="#000000"><span class=
1661 "INLINEMEDIAOBJECT">#include <ncurses.h>
1663 int main(int argc, char *argv[])
1664 { initscr(); /* Start curses mode */
1665 start_color(); /* Start color functionality */
1667 init_pair(1, COLOR_CYAN, COLOR_BLACK);
1668 printw("A Big string which i didn't care to type fully ");
1669 mvchgat(0, 0, -1, A_BLINK, 1, NULL);
1671 * First two parameters specify the position at which to start
1672 * Third parameter number of characters to update. -1 means till
1674 * Forth parameter is the normal attribute you wanted to give
1676 * Fifth is the color index. It is the index given during init_pair()
1677 * use 0 if you didn't want color
1678 * Sixth one is always NULL
1682 endwin(); /* End curses mode */
1689 <p>This example also introduces us to the color world of curses.
1690 Colors will be explained in detail later. Use 0 for no color.</p>
1695 <h2 class="SECT1"><a name="WINDOWS" id="WINDOWS">9.
1697 <p>Windows form the most important concept in curses. You have seen
1698 the standard window stdscr above where all the functions implicitly
1699 operated on this window. Now to make design even a simplest GUI,
1700 you need to resort to windows. The main reason you may want to use
1701 windows is to manipulate parts of the screen separately, for better
1702 efficiency, by updating only the windows that need to be changed
1703 and for a better design. I would say the last reason is the most
1704 important in going for windows. You should always strive for a
1705 better and easy-to-manage design in your programs. If you are
1706 writing big, complex GUIs this is of pivotal importance before you
1707 start doing anything.</p>
1710 <h3 class="SECT2"><a name="WINDOWBASICS" id="WINDOWBASICS">9.1. The
1712 <p>A Window can be created by calling the function <var class=
1713 "LITERAL">newwin()</var>. It doesn't create any thing on the screen
1714 actually. It allocates memory for a structure to manipulate the
1715 window and updates the structure with data regarding the window
1716 like it's size, beginy, beginx etc.. Hence in curses, a window is
1717 just an abstraction of an imaginary window, which can be
1718 manipulated independent of other parts of screen. The function
1719 newwin() returns a pointer to structure WINDOW, which can be passed
1720 to window related functions like wprintw() etc.. Finally the window
1721 can be destroyed with delwin(). It will deallocate the memory
1722 associated with the window structure.</p>
1726 <h3 class="SECT2"><a name="LETBEWINDOW" id="LETBEWINDOW">9.2. Let
1727 there be a Window !!!</a></h3>
1728 <p>What fun is it, if a window is created and we can't see it. So
1729 the fun part begins by displaying the window. The function
1730 <var class="LITERAL">box()</var> can be used to draw a border
1731 around the window. Let's explore these functions in more detail in
1733 <div class="EXAMPLE"><a name="BWIBO" id="BWIBO"></a>
1734 <p><b>Example 7. Window Border example</b></p>
1735 <table border="0" bgcolor="#E0E0E0" width="100%">
1738 <pre class="PROGRAMLISTING">
1739 <font color="#000000"><span class=
1740 "INLINEMEDIAOBJECT">#include <ncurses.h>
1743 WINDOW *create_newwin(int height, int width, int starty, int startx);
1744 void destroy_win(WINDOW *local_win);
1746 int main(int argc, char *argv[])
1748 int startx, starty, width, height;
1751 initscr(); /* Start curses mode */
1752 cbreak(); /* Line buffering disabled, Pass on
1753 * everty thing to me */
1754 keypad(stdscr, TRUE); /* I need that nifty F1 */
1758 starty = (LINES - height) / 2; /* Calculating for a center placement */
1759 startx = (COLS - width) / 2; /* of the window */
1760 printw("Press F1 to exit");
1762 my_win = create_newwin(height, width, starty, startx);
1764 while((ch = getch()) != KEY_F(1))
1767 destroy_win(my_win);
1768 my_win = create_newwin(height, width, starty,--startx);
1771 destroy_win(my_win);
1772 my_win = create_newwin(height, width, starty,++startx);
1775 destroy_win(my_win);
1776 my_win = create_newwin(height, width, --starty,startx);
1779 destroy_win(my_win);
1780 my_win = create_newwin(height, width, ++starty,startx);
1785 endwin(); /* End curses mode */
1789 WINDOW *create_newwin(int height, int width, int starty, int startx)
1790 { WINDOW *local_win;
1792 local_win = newwin(height, width, starty, startx);
1793 box(local_win, 0 , 0); /* 0, 0 gives default characters
1794 * for the vertical and horizontal
1796 wrefresh(local_win); /* Show that box */
1801 void destroy_win(WINDOW *local_win)
1803 /* box(local_win, ' ', ' '); : This won't produce the desired
1804 * result of erasing the window. It will leave it's four corners
1805 * and so an ugly remnant of window.
1807 wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' ');
1808 /* The parameters taken are
1809 * 1. win: the window on which to operate
1810 * 2. ls: character to be used for the left side of the window
1811 * 3. rs: character to be used for the right side of the window
1812 * 4. ts: character to be used for the top side of the window
1813 * 5. bs: character to be used for the bottom side of the window
1814 * 6. tl: character to be used for the top left corner of the window
1815 * 7. tr: character to be used for the top right corner of the window
1816 * 8. bl: character to be used for the bottom left corner of the window
1817 * 9. br: character to be used for the bottom right corner of the window
1819 wrefresh(local_win);
1829 <h3 class="SECT2"><a name="BORDEREXEXPL" id="BORDEREXEXPL">9.3.
1830 Explanation</a></h3>
1831 <p>Don't scream. I know it's a big example. But I have to explain
1832 some important things here :-). This program creates a rectangular
1833 window that can be moved with left, right, up, down arrow keys. It
1834 repeatedly creates and destroys windows as user press a key. Don't
1835 go beyond the screen limits. Checking for those limits is left as
1836 an exercise for the reader. Let's dissect it by line by line.</p>
1837 <p>The <var class="LITERAL">create_newwin()</var> function creates
1838 a window with <var class="LITERAL">newwin()</var> and displays a
1839 border around it with box. The function <var class=
1840 "LITERAL">destroy_win()</var> first erases the window from screen
1841 by painting a border with ' ' character and then calling
1842 <var class="LITERAL">delwin()</var> to deallocate memory related to
1843 it. Depending on the key the user presses, starty or startx is
1844 changed and a new window is created.</p>
1845 <p>In the destroy_win, as you can see, I used wborder instead of
1846 box. The reason is written in the comments (You missed it. I know.
1847 Read the code :-)). wborder draws a border around the window with
1848 the characters given to it as the 4 corner points and the 4 lines.
1849 To put it clearly, if you have called wborder as below:</p>
1850 <table border="0" bgcolor="#E0E0E0" width="100%">
1853 <pre class="PROGRAMLISTING">
1855 "#000000"> wborder(win, '|', '|', '-', '-', '+', '+', '+', '+');</font>
1859 <p>it produces some thing like</p>
1860 <table border="0" bgcolor="#E0E0E0" width="100%">
1863 <pre class="PROGRAMLISTING">
1864 <font color="#000000"> +------------+
1871 +------------+</font>
1878 <h3 class="SECT2"><a name="OTHERSTUFF" id="OTHERSTUFF">9.4. The
1879 other stuff in the example</a></h3>
1880 <p>You can also see in the above examples, that I have used the
1881 variables COLS, LINES which are initialized to the screen sizes
1882 after initscr(). They can be useful in finding screen dimensions
1883 and finding the center co-ordinate of the screen as above. The
1884 function <var class="LITERAL">getch()</var> as usual gets the key
1885 from keyboard and according to the key it does the corresponding
1886 work. This type of switch- case is very common in any GUI based
1891 <h3 class="SECT2"><a name="OTHERBORDERFUNCS" id=
1892 "OTHERBORDERFUNCS">9.5. Other Border functions</a></h3>
1893 <p>Above program is grossly inefficient in that with each press of
1894 a key, a window is destroyed and another is created. So let's write
1895 a more efficient program which uses other border related
1897 <p>The following program uses <var class="LITERAL">mvhline()</var>
1898 and <var class="LITERAL">mvvline()</var> to achieve similar effect.
1899 These two functions are simple. They create a horizontal or
1900 vertical line of the specified length at the specified
1902 <div class="EXAMPLE"><a name="BOTBO" id="BOTBO"></a>
1903 <p><b>Example 8. More border functions</b></p>
1904 <table border="0" bgcolor="#E0E0E0" width="100%">
1907 <pre class="PROGRAMLISTING">
1908 <font color="#000000"><span class=
1909 "INLINEMEDIAOBJECT">#include <ncurses.h>
1911 typedef struct _win_border_struct {
1912 chtype ls, rs, ts, bs,
1916 typedef struct _WIN_struct {
1923 void init_win_params(WIN *p_win);
1924 void print_win_params(WIN *p_win);
1925 void create_box(WIN *win, bool flag);
1927 int main(int argc, char *argv[])
1931 initscr(); /* Start curses mode */
1932 start_color(); /* Start the color functionality */
1933 cbreak(); /* Line buffering disabled, Pass on
1934 * everty thing to me */
1935 keypad(stdscr, TRUE); /* I need that nifty F1 */
1937 init_pair(1, COLOR_CYAN, COLOR_BLACK);
1939 /* Initialize the window parameters */
1940 init_win_params(&win);
1941 print_win_params(&win);
1943 attron(COLOR_PAIR(1));
1944 printw("Press F1 to exit");
1946 attroff(COLOR_PAIR(1));
1948 create_box(&win, TRUE);
1949 while((ch = getch()) != KEY_F(1))
1952 create_box(&win, FALSE);
1954 create_box(&win, TRUE);
1957 create_box(&win, FALSE);
1959 create_box(&win, TRUE);
1962 create_box(&win, FALSE);
1964 create_box(&win, TRUE);
1967 create_box(&win, FALSE);
1969 create_box(&win, TRUE);
1973 endwin(); /* End curses mode */
1976 void init_win_params(WIN *p_win)
1978 p_win->height = 3;
1979 p_win->width = 10;
1980 p_win->starty = (LINES - p_win->height)/2;
1981 p_win->startx = (COLS - p_win->width)/2;
1983 p_win->border.ls = '|';
1984 p_win->border.rs = '|';
1985 p_win->border.ts = '-';
1986 p_win->border.bs = '-';
1987 p_win->border.tl = '+';
1988 p_win->border.tr = '+';
1989 p_win->border.bl = '+';
1990 p_win->border.br = '+';
1993 void print_win_params(WIN *p_win)
1996 mvprintw(25, 0, "%d %d %d %d", p_win->startx, p_win->starty,
1997 p_win->width, p_win->height);
2001 void create_box(WIN *p_win, bool flag)
2005 x = p_win->startx;
2006 y = p_win->starty;
2007 w = p_win->width;
2008 h = p_win->height;
2011 { mvaddch(y, x, p_win->border.tl);
2012 mvaddch(y, x + w, p_win->border.tr);
2013 mvaddch(y + h, x, p_win->border.bl);
2014 mvaddch(y + h, x + w, p_win->border.br);
2015 mvhline(y, x + 1, p_win->border.ts, w - 1);
2016 mvhline(y + h, x + 1, p_win->border.bs, w - 1);
2017 mvvline(y + 1, x, p_win->border.ls, h - 1);
2018 mvvline(y + 1, x + w, p_win->border.rs, h - 1);
2022 for(j = y; j <= y + h; ++j)
2023 for(i = x; i <= x + w; ++i)
2037 <h2 class="SECT1"><a name="COLOR" id="COLOR">10. Colors</a></h2>
2039 <h3 class="SECT2"><a name="COLORBASICS" id="COLORBASICS">10.1. The
2041 <p>Life seems dull with no colors. Curses has a nice mechanism to
2042 handle colors. Let's get into the thick of the things with a small
2044 <div class="EXAMPLE"><a name="BSICO" id="BSICO"></a>
2045 <p><b>Example 9. A Simple Color example</b></p>
2046 <table border="0" bgcolor="#E0E0E0" width="100%">
2049 <pre class="PROGRAMLISTING">
2050 <font color="#000000"><span class=
2051 "INLINEMEDIAOBJECT">#include <ncurses.h>
2053 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string);
2054 int main(int argc, char *argv[])
2055 { initscr(); /* Start curses mode */
2056 if(has_colors() == FALSE)
2058 printf("Your terminal does not support color\n");
2061 start_color(); /* Start color */
2062 init_pair(1, COLOR_RED, COLOR_BLACK);
2064 attron(COLOR_PAIR(1));
2065 print_in_middle(stdscr, LINES / 2, 0, 0, "Viola !!! In color ...");
2066 attroff(COLOR_PAIR(1));
2070 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string)
2084 length = strlen(string);
2085 temp = (width - length)/ 2;
2086 x = startx + (int)temp;
2087 mvwprintw(win, y, x, "%s", string);
2095 <p>As you can see, to start using color, you should first call the
2096 function <var class="LITERAL">start_color()</var>. After that, you
2097 can use color capabilities of your terminals using various
2098 functions. To find out whether a terminal has color capabilities or
2099 not, you can use <var class="LITERAL">has_colors()</var> function,
2100 which returns FALSE if the terminal does not support color.</p>
2101 <p>Curses initializes all the colors supported by terminal when
2102 start_color() is called. These can be accessed by the define
2103 constants like <var class="LITERAL">COLOR_BLACK</var> etc. Now to
2104 actually start using colors, you have to define pairs. Colors are
2105 always used in pairs. That means you have to use the function
2106 <var class="LITERAL">init_pair()</var> to define the foreground and
2107 background for the pair number you give. After that that pair
2108 number can be used as a normal attribute with <var class=
2109 "LITERAL">COLOR_PAIR()</var>function. This may seem to be
2110 cumbersome at first. But this elegant solution allows us to manage
2111 color pairs very easily. To appreciate it, you have to look into
2112 the the source code of "dialog", a utility for displaying dialog
2113 boxes from shell scripts. The developers have defined foreground
2114 and background combinations for all the colors they might need and
2115 initialized at the beginning. This makes it very easy to set
2116 attributes just by accessing a pair which we already have defined
2118 <p>The following colors are defined in <var class=
2119 "LITERAL">curses.h</var>. You can use these as parameters for
2120 various color functions.</p>
2121 <table border="0" bgcolor="#E0E0E0" width="100%">
2124 <pre class="PROGRAMLISTING">
2125 <font color="#000000"> COLOR_BLACK 0
2132 COLOR_WHITE 7</font>
2139 <h3 class="SECT2"><a name="CHANGECOLORDEFS" id=
2140 "CHANGECOLORDEFS">10.2. Changing Color Definitions</a></h3>
2141 <p>The function <var class="LITERAL">init_color()</var>can be used
2142 to change the rgb values for the colors defined by curses
2143 initially. Say you wanted to lighten the intensity of red color by
2144 a minuscule. Then you can use this function as</p>
2145 <table border="0" bgcolor="#E0E0E0" width="100%">
2148 <pre class="PROGRAMLISTING">
2149 <font color="#000000"> init_color(COLOR_RED, 700, 0, 0);
2150 /* param 1 : color name
2151 * param 2, 3, 4 : rgb content min = 0, max = 1000 */</font>
2155 <p>If your terminal cannot change the color definitions, the
2156 function returns ERR. The function <var class=
2157 "LITERAL">can_change_color()</var> can be used to find out whether
2158 the terminal has the capability of changing color content or not.
2159 The rgb content is scaled from 0 to 1000. Initially RED color is
2160 defined with content 1000(r), 0(g), 0(b).</p>
2164 <h3 class="SECT2"><a name="COLORCONTENT" id="COLORCONTENT">10.3.
2165 Color Content</a></h3>
2166 <p>The functions <var class="LITERAL">color_content()</var> and
2167 <var class="LITERAL">pair_content()</var> can be used to find the
2168 color content and foreground, background combination for the
2174 <h2 class="SECT1"><a name="KEYS" id="KEYS">11. Interfacing with the
2177 <h3 class="SECT2"><a name="KEYSBASICS" id="KEYSBASICS">11.1. The
2179 <p>No GUI is complete without a strong user interface and to
2180 interact with the user, a curses program should be sensitive to key
2181 presses or the mouse actions done by the user. Let's deal with the
2183 <p>As you have seen in almost all of the above examples, it's very
2184 easy to get key input from the user. A simple way of getting key
2185 presses is to use <var class="LITERAL">getch()</var> function. The
2186 cbreak mode should be enabled to read keys when you are interested
2187 in reading individual key hits rather than complete lines of text
2188 (which usually end with a carriage return). keypad should be
2189 enabled to get the Functions keys, arrow keys etc. See the
2190 initialization section for details.</p>
2191 <p><var class="LITERAL">getch()</var> returns an integer
2192 corresponding to the key pressed. If it is a normal character, the
2193 integer value will be equivalent to the character. Otherwise it
2194 returns a number which can be matched with the constants defined in
2195 <var class="LITERAL">curses.h</var>. For example if the user
2196 presses F1, the integer returned is 265. This can be checked using
2197 the macro KEY_F() defined in curses.h. This makes reading keys
2198 portable and easy to manage.</p>
2199 <p>For example, if you call getch() like this</p>
2200 <table border="0" bgcolor="#E0E0E0" width="100%">
2203 <pre class="PROGRAMLISTING">
2204 <font color="#000000"> int ch;
2206 ch = getch();</font>
2210 <p>getch() will wait for the user to press a key, (unless you
2211 specified a timeout) and when user presses a key, the corresponding
2212 integer is returned. Then you can check the value returned with the
2213 constants defined in curses.h to match against the keys you
2215 <p>The following code piece will do that job.</p>
2216 <table border="0" bgcolor="#E0E0E0" width="100%">
2219 <pre class="PROGRAMLISTING">
2220 <font color="#000000"> if(ch == KEY_LEFT)
2221 printw("Left arrow is pressed\n");</font>
2225 <p>Let's write a small program which creates a menu which can be
2226 navigated by up and down arrows.</p>
2230 <h3 class="SECT2"><a name="SIMPLEKEYEX" id="SIMPLEKEYEX">11.2. A
2231 Simple Key Usage example</a></h3>
2232 <div class="EXAMPLE"><a name="BSIKE" id="BSIKE"></a>
2233 <p><b>Example 10. A Simple Key Usage example</b></p>
2234 <table border="0" bgcolor="#E0E0E0" width="100%">
2237 <pre class="PROGRAMLISTING">
2238 <font color="#000000"><span class=
2239 "INLINEMEDIAOBJECT">#include <stdio.h>
2240 #include <ncurses.h>
2255 int n_choices = sizeof(choices) / sizeof(char *);
2256 void print_menu(WINDOW *menu_win, int highlight);
2267 cbreak(); /* Line buffering disabled. pass on everything */
2268 startx = (80 - WIDTH) / 2;
2269 starty = (24 - HEIGHT) / 2;
2271 menu_win = newwin(HEIGHT, WIDTH, starty, startx);
2272 keypad(menu_win, TRUE);
2273 mvprintw(0, 0, "Use arrow keys to go up and down, Press enter to select a choice");
2275 print_menu(menu_win, highlight);
2277 { c = wgetch(menu_win);
2281 highlight = n_choices;
2286 if(highlight == n_choices)
2295 mvprintw(24, 0, "Charcter pressed is = %3d Hopefully it can be printed as '%c'", c, c);
2299 print_menu(menu_win, highlight);
2300 if(choice != 0) /* User did a choice come out of the infinite loop */
2303 mvprintw(23, 0, "You chose choice %d with choice string %s\n", choice, choices[choice - 1]);
2311 void print_menu(WINDOW *menu_win, int highlight)
2317 box(menu_win, 0, 0);
2318 for(i = 0; i < n_choices; ++i)
2319 { if(highlight == i + 1) /* High light the present choice */
2320 { wattron(menu_win, A_REVERSE);
2321 mvwprintw(menu_win, y, x, "%s", choices[i]);
2322 wattroff(menu_win, A_REVERSE);
2325 mvwprintw(menu_win, y, x, "%s", choices[i]);
2339 <h2 class="SECT1"><a name="MOUSE" id="MOUSE">12. Interfacing with
2341 <p>Now that you have seen how to get keys, lets do the same thing
2342 from mouse. Usually each UI allows the user to interact with both
2343 keyboard and mouse.</p>
2346 <h3 class="SECT2"><a name="MOUSEBASICS" id="MOUSEBASICS">12.1. The
2348 <p>Before you do any thing else, the events you want to receive
2349 have to be enabled with <var class="LITERAL">mousemask()</var>.</p>
2350 <table border="0" bgcolor="#E0E0E0" width="100%">
2353 <pre class="PROGRAMLISTING">
2355 "#000000"> mousemask( mmask_t newmask, /* The events you want to listen to */
2356 mmask_t *oldmask) /* The old events mask */</font>
2360 <p>The first parameter to above function is a bit mask of events
2361 you would like to listen. By default, all the events are turned
2362 off. The bit mask <var class="LITERAL">ALL_MOUSE_EVENTS</var> can
2363 be used to get all the events.</p>
2364 <p>The following are all the event masks:</p>
2365 <table border="0" bgcolor="#E0E0E0" width="100%">
2368 <pre class="PROGRAMLISTING">
2369 <font color="#000000"> Name Description
2370 ---------------------------------------------------------------------
2371 BUTTON1_PRESSED mouse button 1 down
2372 BUTTON1_RELEASED mouse button 1 up
2373 BUTTON1_CLICKED mouse button 1 clicked
2374 BUTTON1_DOUBLE_CLICKED mouse button 1 double clicked
2375 BUTTON1_TRIPLE_CLICKED mouse button 1 triple clicked
2376 BUTTON2_PRESSED mouse button 2 down
2377 BUTTON2_RELEASED mouse button 2 up
2378 BUTTON2_CLICKED mouse button 2 clicked
2379 BUTTON2_DOUBLE_CLICKED mouse button 2 double clicked
2380 BUTTON2_TRIPLE_CLICKED mouse button 2 triple clicked
2381 BUTTON3_PRESSED mouse button 3 down
2382 BUTTON3_RELEASED mouse button 3 up
2383 BUTTON3_CLICKED mouse button 3 clicked
2384 BUTTON3_DOUBLE_CLICKED mouse button 3 double clicked
2385 BUTTON3_TRIPLE_CLICKED mouse button 3 triple clicked
2386 BUTTON4_PRESSED mouse button 4 down
2387 BUTTON4_RELEASED mouse button 4 up
2388 BUTTON4_CLICKED mouse button 4 clicked
2389 BUTTON4_DOUBLE_CLICKED mouse button 4 double clicked
2390 BUTTON4_TRIPLE_CLICKED mouse button 4 triple clicked
2391 BUTTON_SHIFT shift was down during button state change
2392 BUTTON_CTRL control was down during button state change
2393 BUTTON_ALT alt was down during button state change
2394 ALL_MOUSE_EVENTS report all button state changes
2395 REPORT_MOUSE_POSITION report mouse movement</font>
2402 <h3 class="SECT2"><a name="GETTINGEVENTS" id="GETTINGEVENTS">12.2.
2403 Getting the events</a></h3>
2404 <p>Once a class of mouse events have been enabled, getch() class of
2405 functions return KEY_MOUSE every time some mouse event happens.
2406 Then the mouse event can be retrieved with <var class=
2407 "LITERAL">getmouse()</var>.</p>
2408 <p>The code approximately looks like this:</p>
2409 <table border="0" bgcolor="#E0E0E0" width="100%">
2412 <pre class="PROGRAMLISTING">
2413 <font color="#000000"> MEVENT event;
2417 if(getmouse(&event) == OK)
2418 . /* Do some thing with the event */
2424 <p>getmouse() returns the event into the pointer given to it. It's
2425 a structure which contains</p>
2426 <table border="0" bgcolor="#E0E0E0" width="100%">
2429 <pre class="PROGRAMLISTING">
2430 <font color="#000000"> typedef struct
2432 short id; /* ID to distinguish multiple devices */
2433 int x, y, z; /* event coordinates */
2434 mmask_t bstate; /* button state bits */
2439 <p>The <var class="LITERAL">bstate</var> is the main variable we
2440 are interested in. It tells the button state of the mouse.</p>
2441 <p>Then with a code snippet like the following, we can find out
2443 <table border="0" bgcolor="#E0E0E0" width="100%">
2446 <pre class="PROGRAMLISTING">
2447 <font color="#000000"> if(event.bstate & BUTTON1_PRESSED)
2448 printw("Left Button Pressed");</font>
2455 <h3 class="SECT2"><a name="MOUSETOGETHER" id="MOUSETOGETHER">12.3.
2456 Putting it all Together</a></h3>
2457 <p>That's pretty much interfacing with mouse. Let's create the same
2458 menu and enable mouse interaction. To make things simpler, key
2459 handling is removed.</p>
2460 <div class="EXAMPLE"><a name="BMOME" id="BMOME"></a>
2461 <p><b>Example 11. Access the menu with mouse !!!</b></p>
2462 <table border="0" bgcolor="#E0E0E0" width="100%">
2465 <pre class="PROGRAMLISTING">
2466 <font color="#000000"><span class=
2467 "INLINEMEDIAOBJECT">#include <ncurses.h>
2475 char *choices[] = { "Choice 1",
2482 int n_choices = sizeof(choices) / sizeof(char *);
2484 void print_menu(WINDOW *menu_win, int highlight);
2485 void report_choice(int mouse_x, int mouse_y, int *p_choice);
2488 { int c, choice = 0;
2492 /* Initialize curses */
2496 cbreak(); //Line buffering disabled. pass on everything
2498 /* Try to put the window in the middle of screen */
2499 startx = (80 - WIDTH) / 2;
2500 starty = (24 - HEIGHT) / 2;
2503 mvprintw(23, 1, "Click on Exit to quit (Works best in a virtual console)");
2507 /* Print the menu for the first time */
2508 menu_win = newwin(HEIGHT, WIDTH, starty, startx);
2509 print_menu(menu_win, 1);
2510 /* Get all the mouse events */
2511 mousemask(ALL_MOUSE_EVENTS, NULL);
2514 { c = wgetch(menu_win);
2517 if(getmouse(&event) == OK)
2518 { /* When the user clicks left mouse button */
2519 if(event.bstate & BUTTON1_PRESSED)
2520 { report_choice(event.x + 1, event.y + 1, &choice);
2521 if(choice == -1) //Exit chosen
2523 mvprintw(22, 1, "Choice made is : %d String Chosen is \"%10s\"", choice, choices[choice - 1]);
2527 print_menu(menu_win, choice);
2537 void print_menu(WINDOW *menu_win, int highlight)
2543 box(menu_win, 0, 0);
2544 for(i = 0; i < n_choices; ++i)
2545 { if(highlight == i + 1)
2546 { wattron(menu_win, A_REVERSE);
2547 mvwprintw(menu_win, y, x, "%s", choices[i]);
2548 wattroff(menu_win, A_REVERSE);
2551 mvwprintw(menu_win, y, x, "%s", choices[i]);
2557 /* Report the choice according to mouse position */
2558 void report_choice(int mouse_x, int mouse_y, int *p_choice)
2564 for(choice = 0; choice < n_choices; ++choice)
2565 if(mouse_y == j + choice && mouse_x >= i && mouse_x <= i + strlen(choices[choice]))
2566 { if(choice == n_choices - 1)
2569 *p_choice = choice + 1;
2580 <h3 class="SECT2"><a name="MISCMOUSEFUNCS" id=
2581 "MISCMOUSEFUNCS">12.4. Miscellaneous Functions</a></h3>
2582 <p>The functions mouse_trafo() and wmouse_trafo() can be used to
2583 convert to mouse co-ordinates to screen relative co-ordinates. See
2584 curs_mouse(3X) man page for details.</p>
2585 <p>The mouseinterval function sets the maximum time (in thousands
2586 of a second) that can elapse between press and release events in
2587 order for them to be recognized as a click. This function returns
2588 the previous interval value. The default is one fifth of a
2594 <h2 class="SECT1"><a name="SCREEN" id="SCREEN">13. Screen
2595 Manipulation</a></h2>
2596 <p>In this section, we will look into some functions, which allow
2597 us to manage the screen efficiently and to write some fancy
2598 programs. This is especially important in writing games.</p>
2601 <h3 class="SECT2"><a name="GETYX" id="GETYX">13.1. getyx()
2603 <p>The function <var class="LITERAL">getyx()</var> can be used to
2604 find out the present cursor co-ordinates. It will fill the values
2605 of x and y co-ordinates in the arguments given to it. Since getyx()
2606 is a macro you don't have to pass the address of the variables. It
2607 can be called as</p>
2608 <table border="0" bgcolor="#E0E0E0" width="100%">
2611 <pre class="PROGRAMLISTING">
2612 <font color="#000000"> getyx(win, y, x);
2613 /* win: window pointer
2614 * y, x: y, x co-ordinates will be put into this variables
2619 <p>The function getparyx() gets the beginning co-ordinates of the
2620 sub window relative to the main window. This is some times useful
2621 to update a sub window. When designing fancy stuff like writing
2622 multiple menus, it becomes difficult to store the menu positions,
2623 their first option co-ordinates etc. A simple solution to this
2624 problem, is to create menus in sub windows and later find the
2625 starting co-ordinates of the menus by using getparyx().</p>
2626 <p>The functions getbegyx() and getmaxyx() store current window's
2627 beginning and maximum co-ordinates. These functions are useful in
2628 the same way as above in managing the windows and sub windows
2633 <h3 class="SECT2"><a name="SCREENDUMP" id="SCREENDUMP">13.2. Screen
2635 <p>While writing games, some times it becomes necessary to store
2636 the state of the screen and restore it back to the same state. The
2637 function scr_dump() can be used to dump the screen contents to a
2638 file given as an argument. Later it can be restored by scr_restore
2639 function. These two simple functions can be used effectively to
2640 maintain a fast moving game with changing scenarios.</p>
2644 <h3 class="SECT2"><a name="WINDOWDUMP" id="WINDOWDUMP">13.3. Window
2646 <p>To store and restore windows, the functions <var class=
2647 "LITERAL">putwin()</var> and <var class="LITERAL">getwin()</var>
2648 can be used. <var class="LITERAL">putwin()</var> puts the present
2649 window state into a file, which can be later restored by
2650 <var class="LITERAL">getwin()</var>.</p>
2651 <p>The function <var class="LITERAL">copywin()</var> can be used to
2652 copy a window completely onto another window. It takes the source
2653 and destination windows as parameters and according to the
2654 rectangle specified, it copies the rectangular region from source
2655 to destination window. It's last parameter specifies whether to
2656 overwrite or just overlay the contents on to the destination
2657 window. If this argument is true, then the copying is
2658 non-destructive.</p>
2663 <h2 class="SECT1"><a name="MISC" id="MISC">14. Miscellaneous
2665 <p>Now you know enough features to write a good curses program,
2666 with all bells and whistles. There are some miscellaneous functions
2667 which are useful in various cases. Let's go headlong into some of
2671 <h3 class="SECT2"><a name="CURSSET" id="CURSSET">14.1.
2673 <p>This function can be used to make the cursor invisible. The
2674 parameter to this function should be</p>
2675 <table border="0" bgcolor="#E0E0E0" width="100%">
2678 <pre class="PROGRAMLISTING">
2679 <font color="#000000"> 0 : invisible or
2681 2 : very visible.</font>
2688 <h3 class="SECT2"><a name="TEMPLEAVE" id="TEMPLEAVE">14.2.
2689 Temporarily Leaving Curses mode</a></h3>
2690 <p>Some times you may want to get back to cooked mode (normal line
2691 buffering mode) temporarily. In such a case you will first need to
2692 save the tty modes with a call to <var class=
2693 "LITERAL">def_prog_mode()</var> and then call <var class=
2694 "LITERAL">endwin()</var> to end the curses mode. This will leave
2695 you in the original tty mode. To get back to curses once you are
2696 done, call <var class="LITERAL">reset_prog_mode()</var> . This
2697 function returns the tty to the state stored by <var class=
2698 "LITERAL">def_prog_mode()</var>. Then do refresh(), and you are
2699 back to the curses mode. Here is an example showing the sequence of
2700 things to be done.</p>
2701 <div class="EXAMPLE"><a name="BTELE" id="BTELE"></a>
2702 <p><b>Example 12. Temporarily Leaving Curses Mode</b></p>
2703 <table border="0" bgcolor="#E0E0E0" width="100%">
2706 <pre class="PROGRAMLISTING">
2707 <font color="#000000"><span class=
2708 "INLINEMEDIAOBJECT">#include <ncurses.h>
2712 initscr(); /* Start curses mode */
2713 printw("Hello World !!!\n"); /* Print Hello World */
2714 refresh(); /* Print it on to the real screen */
2715 def_prog_mode(); /* Save the tty modes */
2716 endwin(); /* End curses mode temporarily */
2717 system("/bin/sh"); /* Do whatever you like in cooked mode */
2718 reset_prog_mode(); /* Return to the previous tty mode*/
2719 /* stored by def_prog_mode() */
2720 refresh(); /* Do refresh() to restore the */
2721 /* Screen contents */
2722 printw("Another String\n"); /* Back to curses use the full */
2723 refresh(); /* capabilities of curses */
2724 endwin(); /* End curses mode */
2735 <h3 class="SECT2"><a name="ACSVARS" id="ACSVARS">14.3. ACS_
2737 <p>If you have ever programmed in DOS, you know about those nifty
2738 characters in extended character set. They are printable only on
2739 some terminals. NCURSES functions like <var class=
2740 "LITERAL">box()</var> use these characters. All these variables
2741 start with ACS meaning alternative character set. You might have
2742 noticed me using these characters in some of the programs above.
2743 Here's an example showing all the characters.</p>
2744 <div class="EXAMPLE"><a name="BACSVARS" id="BACSVARS"></a>
2745 <p><b>Example 13. ACS Variables Example</b></p>
2746 <table border="0" bgcolor="#E0E0E0" width="100%">
2749 <pre class="PROGRAMLISTING">
2750 <font color="#000000"><span class=
2751 "INLINEMEDIAOBJECT">#include <ncurses.h>
2757 printw("Upper left corner "); addch(ACS_ULCORNER); printw("\n");
2758 printw("Lower left corner "); addch(ACS_LLCORNER); printw("\n");
2759 printw("Lower right corner "); addch(ACS_LRCORNER); printw("\n");
2760 printw("Tee pointing right "); addch(ACS_LTEE); printw("\n");
2761 printw("Tee pointing left "); addch(ACS_RTEE); printw("\n");
2762 printw("Tee pointing up "); addch(ACS_BTEE); printw("\n");
2763 printw("Tee pointing down "); addch(ACS_TTEE); printw("\n");
2764 printw("Horizontal line "); addch(ACS_HLINE); printw("\n");
2765 printw("Vertical line "); addch(ACS_VLINE); printw("\n");
2766 printw("Large Plus or cross over "); addch(ACS_PLUS); printw("\n");
2767 printw("Scan Line 1 "); addch(ACS_S1); printw("\n");
2768 printw("Scan Line 3 "); addch(ACS_S3); printw("\n");
2769 printw("Scan Line 7 "); addch(ACS_S7); printw("\n");
2770 printw("Scan Line 9 "); addch(ACS_S9); printw("\n");
2771 printw("Diamond "); addch(ACS_DIAMOND); printw("\n");
2772 printw("Checker board (stipple) "); addch(ACS_CKBOARD); printw("\n");
2773 printw("Degree Symbol "); addch(ACS_DEGREE); printw("\n");
2774 printw("Plus/Minus Symbol "); addch(ACS_PLMINUS); printw("\n");
2775 printw("Bullet "); addch(ACS_BULLET); printw("\n");
2776 printw("Arrow Pointing Left "); addch(ACS_LARROW); printw("\n");
2777 printw("Arrow Pointing Right "); addch(ACS_RARROW); printw("\n");
2778 printw("Arrow Pointing Down "); addch(ACS_DARROW); printw("\n");
2779 printw("Arrow Pointing Up "); addch(ACS_UARROW); printw("\n");
2780 printw("Board of squares "); addch(ACS_BOARD); printw("\n");
2781 printw("Lantern Symbol "); addch(ACS_LANTERN); printw("\n");
2782 printw("Solid Square Block "); addch(ACS_BLOCK); printw("\n");
2783 printw("Less/Equal sign "); addch(ACS_LEQUAL); printw("\n");
2784 printw("Greater/Equal sign "); addch(ACS_GEQUAL); printw("\n");
2785 printw("Pi "); addch(ACS_PI); printw("\n");
2786 printw("Not equal "); addch(ACS_NEQUAL); printw("\n");
2787 printw("UK pound sign "); addch(ACS_STERLING); printw("\n");
2803 <h2 class="SECT1"><a name="OTHERLIB" id="OTHERLIB">15. Other
2805 <p>Apart from the curses library, there are few text mode
2806 libraries, which provide more functionality and a lot of features.
2807 The following sections explain three standard libraries which are
2808 usually distributed along with curses.</p>
2812 <h2 class="SECT1"><a name="PANELS" id="PANELS">16. Panel
2814 <p>Now that you are proficient in curses, you wanted to do some
2815 thing big. You created a lot of overlapping windows to give a
2816 professional windows-type look. Unfortunately, it soon becomes
2817 difficult to manage these. The multiple refreshes, updates plunge
2818 you into a nightmare. The overlapping windows create blotches,
2819 whenever you forget to refresh the windows in the proper order.</p>
2820 <p>Don't despair. There's an elegant solution provided in panels
2821 library. In the words of developers of ncurses</p>
2822 <p><em>When your interface design is such that windows may dive
2823 deeper into the visibility stack or pop to the top at runtime, the
2824 resulting book-keeping can be tedious and difficult to get right.
2825 Hence the panels library.</em></p>
2826 <p>If you have lot of overlapping windows, then panels library is
2827 the way to go. It obviates the need of doing series of
2828 wnoutrefresh(), doupdate() and relieves the burden of doing it
2829 correctly(bottom up). The library maintains information about the
2830 order of windows, their overlapping and update the screen properly.
2831 So why wait? Let's take a close peek into panels.</p>
2834 <h3 class="SECT2"><a name="PANELBASICS" id="PANELBASICS">16.1. The
2836 <p>Panel object is a window that is implicitly treated as part of a
2837 deck including all other panel objects. The deck is treated as a
2838 stack with the top panel being completely visible and the other
2839 panels may or may not be obscured according to their positions. So
2840 the basic idea is to create a stack of overlapping panels and use
2841 panels library to display them correctly. There is a function
2842 similar to refresh() which, when called , displays panels in the
2843 correct order. Functions are provided to hide or show panels, move
2844 panels, change its size etc.. The overlapping problem is managed by
2845 the panels library during all the calls to these functions.</p>
2846 <p>The general flow of a panel program goes like this:</p>
2849 <p>Create the windows (with newwin()) to be attached to the
2853 <p>Create panels with the chosen visibility order. Stack them up
2854 according to the desired visibility. The function new_panel() is
2855 used to created panels.</p>
2858 <p>Call update_panels() to write the panels to the virtual screen
2859 in correct visibility order. Do a doupdate() to show it on the
2863 <p>Mainpulate the panels with show_panel(), hide_panel(),
2864 move_panel() etc. Make use of helper functions like panel_hidden()
2865 and panel_window(). Make use of user pointer to store custom data
2866 for a panel. Use the functions set_panel_userptr() and
2867 panel_userptr() to set and get the user pointer for a panel.</p>
2870 <p>When you are done with the panel use del_panel() to delete the
2874 <p>Let's make the concepts clear, with some programs. The following
2875 is a simple program which creates 3 overlapping panels and shows
2876 them on the screen.</p>
2880 <h3 class="SECT2"><a name="COMPILEPANELS" id="COMPILEPANELS">16.2.
2881 Compiling With the Panels Library</a></h3>
2882 <p>To use panels library functions, you have to include panel.h and
2883 to link the program with panels library the flag -lpanel should be
2884 added along with -lncurses in that order.</p>
2885 <table border="0" bgcolor="#E0E0E0" width="100%">
2888 <pre class="PROGRAMLISTING">
2889 <font color="#000000"> #include <panel.h>
2894 compile and link: gcc <program file> -lpanel -lncurses</font>
2898 <div class="EXAMPLE"><a name="PPASI" id="PPASI"></a>
2899 <p><b>Example 14. Panel basics</b></p>
2900 <table border="0" bgcolor="#E0E0E0" width="100%">
2903 <pre class="PROGRAMLISTING">
2904 <font color="#000000"><span class=
2905 "INLINEMEDIAOBJECT">#include <panel.h>
2908 { WINDOW *my_wins[3];
2909 PANEL *my_panels[3];
2910 int lines = 10, cols = 40, y = 2, x = 4, i;
2916 /* Create windows for the panels */
2917 my_wins[0] = newwin(lines, cols, y, x);
2918 my_wins[1] = newwin(lines, cols, y + 1, x + 5);
2919 my_wins[2] = newwin(lines, cols, y + 2, x + 10);
2922 * Create borders around the windows so that you can see the effect
2925 for(i = 0; i < 3; ++i)
2926 box(my_wins[i], 0, 0);
2928 /* Attach a panel to each window */ /* Order is bottom up */
2929 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
2930 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
2931 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
2933 /* Update the stacking order. 2nd panel will be on top */
2936 /* Show it on the screen */
2947 <p>As you can see, above program follows a simple flow as
2948 explained. The windows are created with newwin() and then they are
2949 attached to panels with new_panel(). As we attach one panel after
2950 another, the stack of panels gets updated. To put them on screen
2951 update_panels() and doupdate() are called.</p>
2955 <h3 class="SECT2"><a name="PANELBROWSING" id="PANELBROWSING">16.3.
2956 Panel Window Browsing</a></h3>
2957 <p>A slightly complicated example is given below. This program
2958 creates 3 windows which can be cycled through using tab. Have a
2959 look at the code.</p>
2960 <div class="EXAMPLE"><a name="PPABR" id="PPABR"></a>
2961 <p><b>Example 15. Panel Window Browsing Example</b></p>
2962 <table border="0" bgcolor="#E0E0E0" width="100%">
2965 <pre class="PROGRAMLISTING">
2966 <font color="#000000"><span class=
2967 "INLINEMEDIAOBJECT">#include <panel.h>
2972 void init_wins(WINDOW **wins, int n);
2973 void win_show(WINDOW *win, char *label, int label_color);
2974 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
2977 { WINDOW *my_wins[3];
2978 PANEL *my_panels[3];
2982 /* Initialize curses */
2987 keypad(stdscr, TRUE);
2989 /* Initialize all the colors */
2990 init_pair(1, COLOR_RED, COLOR_BLACK);
2991 init_pair(2, COLOR_GREEN, COLOR_BLACK);
2992 init_pair(3, COLOR_BLUE, COLOR_BLACK);
2993 init_pair(4, COLOR_CYAN, COLOR_BLACK);
2995 init_wins(my_wins, 3);
2997 /* Attach a panel to each window */ /* Order is bottom up */
2998 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
2999 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
3000 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
3002 /* Set up the user pointers to the next panel */
3003 set_panel_userptr(my_panels[0], my_panels[1]);
3004 set_panel_userptr(my_panels[1], my_panels[2]);
3005 set_panel_userptr(my_panels[2], my_panels[0]);
3007 /* Update the stacking order. 2nd panel will be on top */
3010 /* Show it on the screen */
3011 attron(COLOR_PAIR(4));
3012 mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)");
3013 attroff(COLOR_PAIR(4));
3017 while((ch = getch()) != KEY_F(1))
3020 top = (PANEL *)panel_userptr(top);
3031 /* Put all the windows */
3032 void init_wins(WINDOW **wins, int n)
3038 for(i = 0; i < n; ++i)
3039 { wins[i] = newwin(NLINES, NCOLS, y, x);
3040 sprintf(label, "Window Number %d", i + 1);
3041 win_show(wins[i], label, i + 1);
3047 /* Show the window with a border and a label */
3048 void win_show(WINDOW *win, char *label, int label_color)
3049 { int startx, starty, height, width;
3051 getbegyx(win, starty, startx);
3052 getmaxyx(win, height, width);
3055 mvwaddch(win, 2, 0, ACS_LTEE);
3056 mvwhline(win, 2, 1, ACS_HLINE, width - 2);
3057 mvwaddch(win, 2, width - 1, ACS_RTEE);
3059 print_in_middle(win, 1, 0, width, label, COLOR_PAIR(label_color));
3062 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color)
3076 length = strlen(string);
3077 temp = (width - length)/ 2;
3078 x = startx + (int)temp;
3079 wattron(win, color);
3080 mvwprintw(win, y, x, "%s", string);
3081 wattroff(win, color);
3091 <h3 class="SECT2"><a name="USERPTRUSING" id="USERPTRUSING">16.4.
3092 Using User Pointers</a></h3>
3093 <p>In the above example I used user pointers to find out the next
3094 window in the cycle. We can attach custom information to the panel
3095 by specifying a user pointer, which can point to any information
3096 you want to store. In this case I stored the pointer to the next
3097 panel in the cycle. User pointer for a panel can be set with the
3098 function <var class="LITERAL">set_panel_userptr()</var>. It can be
3099 accessed using the function <var class=
3100 "LITERAL">panel_userptr()</var> which will return the user pointer
3101 for the panel given as argument. After finding the next panel in
3102 the cycle It's brought to the top by the function top_panel(). This
3103 function brings the panel given as argument to the top of the panel
3108 <h3 class="SECT2"><a name="PANELMOVERESIZE" id=
3109 "PANELMOVERESIZE">16.5. Moving and Resizing Panels</a></h3>
3110 <p>The function <var class="LITERAL">move_panel()</var> can be used
3111 to move a panel to the desired location. It does not change the
3112 position of the panel in the stack. Make sure that you use
3113 move_panel() instead mvwin() on the window associated with the
3115 <p>Resizing a panel is slightly complex. There is no straight
3116 forward function just to resize the window associated with a panel.
3117 A solution to resize a panel is to create a new window with the
3118 desired sizes, change the window associated with the panel using
3119 replace_panel(). Don't forget to delete the old window. The window
3120 associated with a panel can be found by using the function
3122 <p>The following program shows these concepts, in supposedly simple
3123 program. You can cycle through the window with <TAB> as
3124 usual. To resize or move the active panel press 'r' for resize 'm'
3125 for moving. Then use arrow keys to resize or move it to the desired
3126 way and press enter to end your resizing or moving. This example
3127 makes use of user data to get the required data to do the
3129 <div class="EXAMPLE"><a name="PPARE" id="PPARE"></a>
3130 <p><b>Example 16. Panel Moving and Resizing example</b></p>
3131 <table border="0" bgcolor="#E0E0E0" width="100%">
3134 <pre class="PROGRAMLISTING">
3135 <font color="#000000"><span class=
3136 "INLINEMEDIAOBJECT">#include <panel.h>
3138 typedef struct _PANEL_DATA {
3148 void init_wins(WINDOW **wins, int n);
3149 void win_show(WINDOW *win, char *label, int label_color);
3150 void print_in_middle(WINDOW *win, int starty, int startx, int width, char *string, chtype color);
3151 void set_user_ptrs(PANEL **panels, int n);
3154 { WINDOW *my_wins[3];
3155 PANEL *my_panels[3];
3158 WINDOW *temp_win, *old_win;
3160 int newx, newy, neww, newh;
3161 int size = FALSE, move = FALSE;
3163 /* Initialize curses */
3168 keypad(stdscr, TRUE);
3170 /* Initialize all the colors */
3171 init_pair(1, COLOR_RED, COLOR_BLACK);
3172 init_pair(2, COLOR_GREEN, COLOR_BLACK);
3173 init_pair(3, COLOR_BLUE, COLOR_BLACK);
3174 init_pair(4, COLOR_CYAN, COLOR_BLACK);
3176 init_wins(my_wins, 3);
3178 /* Attach a panel to each window */ /* Order is bottom up */
3179 my_panels[0] = new_panel(my_wins[0]); /* Push 0, order: stdscr-0 */
3180 my_panels[1] = new_panel(my_wins[1]); /* Push 1, order: stdscr-0-1 */
3181 my_panels[2] = new_panel(my_wins[2]); /* Push 2, order: stdscr-0-1-2 */
3183 set_user_ptrs(my_panels, 3);
3184 /* Update the stacking order. 2nd panel will be on top */
3187 /* Show it on the screen */
3188 attron(COLOR_PAIR(4));
3189 mvprintw(LINES - 3, 0, "Use 'm' for moving, 'r' for resizing");
3190 mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)");
3191 attroff(COLOR_PAIR(4));
3194 stack_top = my_panels[2];
3195 top = (PANEL_DATA *)panel_userptr(stack_top);
3200 while((ch = getch()) != KEY_F(1))
3203 top = (PANEL_DATA *)panel_userptr(stack_top);
3204 top_panel(top->next);
3205 stack_top = top->next;
3206 top = (PANEL_DATA *)panel_userptr(stack_top);
3212 case 'r': /* Re-Size*/
3214 attron(COLOR_PAIR(4));
3215 mvprintw(LINES - 4, 0, "Entered Resizing :Use Arrow Keys to resize and press <ENTER> to end resizing");
3217 attroff(COLOR_PAIR(4));
3219 case 'm': /* Move */
3220 attron(COLOR_PAIR(4));
3221 mvprintw(LINES - 4, 0, "Entered Moving: Use Arrow Keys to Move and press <ENTER> to end moving");
3223 attroff(COLOR_PAIR(4));
3258 case 10: /* Enter */
3263 { old_win = panel_window(stack_top);
3264 temp_win = newwin(newh, neww, newy, newx);
3265 replace_panel(stack_top, temp_win);
3266 win_show(temp_win, top->label, top->label_color);
3271 { move_panel(stack_top, newy, newx);
3277 attron(COLOR_PAIR(4));
3278 mvprintw(LINES - 3, 0, "Use 'm' for moving, 'r' for resizing");
3279 mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F1 to Exit)");
3280 attroff(COLOR_PAIR(4));
3289 /* Put all the windows */
3290 void init_wins(WINDOW **wins, int n)
3296 for(i = 0; i < n; ++i)
3297 { wins[i] = newwin(NLINES, NCOLS, y, x);
3298 sprintf(label, "Window Number %d", i + 1);
3299 win_show(wins[i], label, i + 1);
3305 /* Set the PANEL_DATA structures for individual panels */
3306 void set_user_ptrs(PANEL **panels, int n)
3312 ptrs = (PANEL_DATA *)calloc(n, sizeof(PANEL_DATA));
3314 for(i = 0;i < n; ++i)
3315 { win = panel_window(panels[i]);
3316 getbegyx(win, y, x);
3317 getmaxyx(win, h, w);
3322 sprintf(temp, "Window Number %d", i + 1);
3323 strcpy(ptrs[i].label, temp);
3324 ptrs[i].label_color = i + 1;
3326 ptrs[i].next = panels[0];
3328 ptrs[i].next = panels[i + 1];
3329 set_panel_userptr(panels[i], &ptrs[i]);
3333 /* Show the window with a border and a label */
3334 void win_show(WINDOW *win, char *label, int label_color)
3335 { int startx, starty, height, width;
3337 getbegyx(win, starty, startx);