Programmer's Guide to NCurses Dan Gookin Programmer's Guide to NCurses Programmer's Guide to NCurses Dan Gookin P. The license has been changed to the MIT−style license used by NCURSES. document is intended to be an "All in One" guide for programming with ncurses and its sister libraries. to get pdf, first create a single html file of the HOWTO with. Dan Gookin has been writing about technology for over 20 years. He's con- tributed articles to numerous high-tech magazines and written more than
|Language:||English, Spanish, German|
|Distribution:||Free* [*Sign up for free]|
This manual is for the GNU Guile-NCurses library, (version , 8 April ). It provides bindings for the ncurses Curses Reference. .. The tutorial for the curses library is adapted from the ncurses Programming HowTo by. Pradeep Padala. Programmer's Guide to ncurses. Dan Gookin. Programmer's Guide to ncurses. bapoperetu.gq ISBN: , | an exhaustive reference for the curses Application Programming. Interface (API); that This document describes ncurses, a free implementation of the System V.
Based on the authors' experiences in developing and teaching Symbian OS, this practical guide is perfect for programmers and provides a series of example-based scenarios that show how to develop Symbian applications. Programmer's Guide to NCurses A couple weeks ago, I wanted to start playing around with the python curses module, but it's been almost forever since I've done anything with curses. Indianapolis, IN www. Linux Programmer's Guide Contents Page. Practical Design Mathematics of choice: How to count without Principles of animal taxonomy ebook download Airframe Structural Design: Transform Fear to 1.
It gives you access to the eight brighter versions of the standard eight or however many text colors available.
Brown actually becomes yellow, and black becomes a midtone gray. The best way to understand the way NCurses applies color is, naturally, with a test program such as Listing This basic program contains a simple back-and-forth conversation between two color pairs, shown in Figure Notice how the color attributes affect only the text put to the screen.
For example, you can define pink text and use it if you like. That function looks something like this: Sample output for colorme. The first color represents the new color number.
Then come values for the red r , green g , and blue b arguments, each of which ranges from 0 to , representing the intensity of that particular color. On my terminal, which cannot change text color values, the new color shows up as red, which is the default for color 1 anyway. I would call that a failure. The standard screen is the same size as the terminal screen. The function to fill the standard screen window with color or any text attribute is: Screen Background Color To set the background color, you must do three things, two of which you already know: First, activate color.
Third, use bkgd to color the entire window. The code shown in Listing demonstrates how background color is set. Any text added at this point appears with the color attribute applied automatically, in this case with white text on a blue background. Press the Enter key to end the program; then modify the code to add some text. For example, insert the following before line The NCurses chtype is a special type of variable that includes both an attribute and a character.
So, if you like, you can specify a single character as the background attribute for a window. C source code and change line 9 to read: You can also use the logical OR to apply other attributes or characters for the bkgd function. See Appendix C for more information on the chtype variable in NCurses.
Changing Color on the Fly The bkgd function affects all attributes and unused character places on the screen. Press the Enter key and the colors change to green on a white background — but the text is unchanged. Press Enter again and the text color changes to red, the background to green.
Ugly, but it proves that you can change the screen color without bothering any printed text. Noise, Too! Two functions do the job. The flash function is newer than beep, designed to get attention by flashing the screen, supposedly to assist the hearing impaired in recognizing alerts. The one way to find out is to run a test program such as Listing On my computer, I just heard another beep. Press Enter again to end the program. The key is moving the cursor.
Secondary to that, of course, is knowing how big the terminal screen or, in NCurses, the standard screen window can be, so that you keep all your text visible. That the function is named getmaxyx should help you remember that Y, or rows, comes first.
The win argument is the name of a specific window in NCurses. For the terminal screen, you use the standard screen window, which is named stdscr. The y and x arguments are int variables not pointers that will hold the maximum number of rows and columns in the named window.
See Listing Windows size is 24 rows, 80 columns. Because my terminal window is in a graphical window in a GUI, I can resize it. When I do and make the window wider, rerunning the program reports the new results: Windows size is 24 rows, 85 columns. Write your code so that your program uses getmaxyx to determine the screen size and save those values in variables; do not use constants!
The value of COLS is equal to the number of columns on the standard screen window, as well as the terminal. Moving the Cursor Around In NCurses, the cursor — that thing that tells curses where to put the next character on the screen — is moved around via the move function but also by most commands that put text to the screen.
Nothing surprising there. To provide basic cursor control, there is only one command: So follow along and learn a tad bit more about moving the cursor in NCurses. Watch Out! There are four corners on the standard screen: And you know what would just look lovely in each corner? Just like the program in Listing demonstrates: Some Compacting The folks who write and maintain NCurses came to a strong realization many years ago that any move function is usually followed by a command to actually stick text on the screen.
I mean, the following code in any program would be rather silly: No, sir, move functions are followed by some type of text output function or statement. And you already know three of them: By prefixing mv for move to each of those commands, you get a combined move-and-print command. Listing shows a modification, do-over to the original 4corner. Note the format for the mvaddch function: Again, this is just like combining the two functions, move and addch. Center that Title!
Remember that the computer does the math. Centering text on the screen is an old and ancient art. It works like this: Figure out how wide the screen is.
Figure out how wide your title text is. Subtract the title text length from the screen width. The value left over needs to be shared equally as spaces on either side of the title. Divide the value left over by two. The following program in Listing has it all done for you. You supply the row number and the line of text to center.
The center function then centers that text on the given row. N OT E Remember that the top row on the terminal screen is zero, not 1! I included several center commands with titles of varying length. Feel free to add more or experiment with the lengths. The math part is done in the center function. As with numbers, the string is right-justified: To wit: Remember that the printw function is doing the alignment. Your name: Art Grockmeister Your company: Grand Duke of Finance Date hired: This is why they were declared as constants instead of being hard-coded into the program.
Whither the Cursor? But consider the case where a program involves full-screen user input. In that example, it helps to have a function that tracks down where the booger is. The getyx function reads the logical cursor location from the window win stdscr for the standard screen and puts its row and column positions into the variables y and x.
As with the move function, the home location 0,0 is the upper-left corner of the screen. Note that the function is named getyx , not getxy. Bill is a jerk! There are functions that can insert and delete characters or lines of text, causing other text on the screen to jump around and make room or to fill in the gaps. This chapter covers those amazing functions. Inserting and Deleting Functions Writing a program that spits up text on the screen is a relatively easy task. What becomes a pain in the rear is when you have to modify the text you splash on the screen.
Face it. Some dolt somewhere is always going to change his mind. You must learn to be versatile, to plan ahead. The insch inserts a character. The insertln function scrolls in a blank line of text. The del brothers have no arguments. They delete a single character or an entire line of text from the screen. Editing Shakespeare The following source code in Listing serves as the core for the next several sets of programs.
To be, or not to be: The slings and arrows of outrageous fortune And by opposing end them? Inserting Some Lines The purpose of this lesson is to rebuild the quote properly. But just pretend the input was coming from the terminal and you needed to insert a new line of text between lines 1 and 2?
Remember that on the screen, lines 1 and 2 appear on screen rows 0 and 1. Therefore, you would need to insert a blank line at row 1 and shove in the new text there. Fortunately, the insertln function does all that: It inserts a blank line all the way across the screen and scrolls the rest of the text beneath that line down one notch see Listing At that point, you merely need to add the string of text you need. When the program runs, after the first three lines are displayed, press Enter.
That way, getch has something to eat, and then the rest of the program works. The new code starts by moving the logical cursor to row 1 the second row column 0 first column.
Next, the insertln function creates a blank line on the same line where the logical cursor is placed. It always blanks the entire line, even if the cursor is placed on the far left side of the screen.
The result is that the existing text is scrolled down and the new line is inserted. Note that insertln scrolls the entire contents of the standard screen window. If there is text on the last line, that line is scrolled off into oblivion. There are multiple ways to add that last line of text and finish the program, any one of which is acceptable as long as the results on the screen look like this: Try your own solution before looking at mine in Listing N OT E The most common mistake is forgetting that the first insertln scrolls down the rest of the text; you must move the cursor to row 3, not row 2, to insert the fourth line.
The following source code in Listing is one of those classic chestnuts, the scrolling marquee. DOW tops 15,! The insch function then displays that character at location 5,5, pushing the rest of the text on that line one notch to the left. The result is the scrolling marquee. C source code, filling the screen with text so that you can more graphically see how the insch function affects text on the screen.
My favorite is delch because I can pronounce it. Even so, the following source code in Listing shows deleteln first.
C source code, which makes typing easier. Press Enter to delete the text. Note how it scrolls up? Yes, the deleteln function is nearly the opposite of the insertln function, complete with logical reverse scrolling. Do note that deleteln does not affect the location of the cursor. After the last refresh command above, the cursor is still at location 1,0, eagerly awaiting more text to be added to the screen. Goodbye, Chunk of Text! It simply removes whichever character happens to be lurking at the current cursor position.
Any characters to the right on the same line are then shuffled over left one notch; a blank character is then added to the end of the line. So Row 2, Column Such tidy editing. For comparison purposes only, Listing shows my solution to the problem.
You can make such a thing happens, but you will have to write the code that does it. Use the napms function to create a delay between inserting and deleting each character. Or did you cheat and just use my solution, shown in Listing ?
As the for loop progress, the value of c increases, which backsteps one character at a time through the string. That difference is that clearing merely erases, replacing the text with blank characters.
Deleting, on the other hand, removes the text and tightens up the hole, which is demonstrated with the delch and deleteln functions in Chapter 5. Between the two, the clear function is more thorough, though it has more internal overhead. The Obligatory Test Program The best way to demonstrate the erase-chunks commands is to have something on the screen worthy of erasure.
C program in Listing Running the program results in a screen full of blah, as shown in Figure Clear the Screen! The first modification to blah1.
C source code shown in Listing This code shows how the clear function is used to clear the screen. The erase and clear functions are nearly identical, but the clear function does a more thorough job, ensuring that the NCurses window is completely redrawn from scratch the next time a refresh function is issued. Using the BLAH2. C source code, create a file, BLAH3. In that file, replace line 15 with: This trivia tidbit has absolutely nothing to do with NCurses. No surprises. No shocks. No Taco Bell dog dancing across the screen.
After using clrtobot , the screen looks half blank, more or less. C source code, only line 16 is changed. Replace the clrtoeol function with clrtobot. It looks something like Figure There are no NCurses commands to clear the top part of the screen, so no counterpart to clrtobot exists. Unlike the C macro getchar , which is a stream-reading command, getch hops back right away with whatever key was pressed.
Such a function helps make your programs more interactive, which can be a huge bonus. Using getch merely to read the keyboard is grand, but there is far more getch can do. In fact, this lengthy chapter discusses many of the options available to getch and how you can use it to do more than you possibly expected. Reading from the Keyboard The getch function normally waits until a key is pressed on the keyboard. This is known as a blocking call; program execution is stopped until a key is pressed.
The preceding function directs the getch function to become nonblocking for the given window, the standard screen stdscr. To restore getch to its normal blocking mode, this version of nodelay is used: Is a Character Waiting? At first, in line 11, getch carries on its normal blocking function. The program waits for a key to be pressed on the keyboard. Therefore, the while loop continues as long as getch returns the value ERR, which is what it generates when no key has been pressed. C program so that instead of any key stopping the insane loop, only the spacebar works to stop it.
Try it! C source code on your own. Change the code so that only the spacebar key stops the insane loop. There are many ways to do this, so be creative! You can press other keys on the keyboard, and the program continues to loop; only the spacebar stops it. Listing shows my solution, though it is only one of many. It was used to determine whether or not characters were waiting to be read from the keyboard buffer.
You can use nodelay and getch in NCurses to emulate this behavior somewhat but not exactly. The problem is that getch still fetches a key.
So what you need is a way to take that key and stuff it back to the keyboard input queue. The function that handles that is called, logically, ungetch. You can do this to pre-stuff characters if you like or to toss back characters when creating a kbhit -like function, as shown in Listing It also assumes that the standard screen is the input screen. Adjust these items as needed for your own use, or just assume that kbhit makes these assumptions and live with it.
Flushing Input Text typed at the computer keyboard is stored in a buffer. The various textreading, or keyboard input, functions fetch characters from that buffer as the program needs them, which is a basic description of how keyboard input works. The reason for the buffer is to allow for keyboard input while the program is doing something else.
I can think of two benefits to this: There are times, however, when you want to clear or flush the keyboard buffer. For example, suppose your program asks a very serious question and requires a Y or N key press.
There may just be a rogue Y or N in the keyboard buffer, so when your program pauses to read the keyboard, it may read that older key press instead of the one corresponding to the current question.
To prevent that from happening, you can flush input, clearing the keyboard buffer. In NCurses, the flushinp function carries out that task see Listing Type on the keyboard whilst I wait C code demonstrates the type-ahead buffer in action. The getnstr function later picks up, processes, and displays what you typed, what was waiting in the buffer. C in Listing inserts the flushinp function before getnstr.
Because input is flushed, anything you type will be erased from the buffer and getnstr will just have to wait! Go ahead and type text as you did before. Then wait. Here is what you typed: Because of the flushinp function, no text is displayed.
Silence, Please! Aside from waiting for your keyboard input, another normal behavior for getch is to echo, or display, the character typed on the screen. It was popular for old C compilers to include a getch function that did not echo the character typed; it was the companion getche function that echoed the character typed to the display. Even so, the point is that turning text-echoing off and on is something programmers desire, as shown in Listing NCurses is happy to oblige.
It would be nice to turn off the echo of characters while the password is input, right? But not if you insert the following on line Even with noecho , text is being processed by the program.
The noecho function affects only the display, not the keyboard. Reading Special Keys The amazing getch function is so incredibly handy that marketing wizards could do one of those minute, late-night infomercials on the thing. For example, when properly coddled, getch can be told to interpret nonalphanumeric keys on the keyboard. This includes function keys, arrow keys, cursor control keys, and even a few keys seldom found on the typical PC keyboard.
Keypad On! All keys on the computer keyboard generate a code when that key is pressed. For other keys, other values are returned, a bit value, a pair of 8-bit values, or perhaps even an escape sequence.
Knowing which type of value returned means you can determine exactly which key was pressed, even nonalphanumeric keys. The drawback, of course, is that not every terminal produces the same results or even has the same keys. NCurses to the rescue! H header file defines many of the extra keys found on terminal keyboards.
To activate and use those definitions, the keypad function is used: Once enabled, your program can use various defined keyboard constants to read those extra keyboard keys, as the following program in Listing demonstrates. N OT E Note that other keys display as well. N OT E You will need to turn the numeric keypad off to use the arrow keys on the 8, 4, 6, and 2 keys on the standard PC keyboard.
H to help your program read the keys.
To determine exactly which keys are available to you, refer to Table A more complete list can be found in Appendix D. You might want to run some tests to assure that NCurses on your computer can access the function keys. For example, to check for Function key 5, you would use: Also be aware that your operating system may steal the function keys from your program.
If so, you can use the raw function in NCurses to try to get the function keys passed directly to your program. Refer to Appendix A for more information on the raw function. A sample menu bar system Working the menu system involves pressing the up or down arrows on the keyboard. When you do, the highlight bar moves up or down to select an item in the menu. Pressing the Enter key selects that item. Listing shows one way to pull it off. C source code shown earlier in this chapter. Note, however, that I do turn echo off in line 41 so that extra characters typed at the prompt are not distracting.
A complementary echo command at line 61 turns on echoing for the rest of the code supposedly. The menuitem variable keeps track of which menu item is highlighted and selected. Its value is changed by pressing the up or down arrow keys. Those keys merely change the value of menuitem.
The display highlighting is more of an after effect. It displays each line of the menu one after the other. The math in line 24 assures that a blank line separates each menu command.
The advantage of NCurses here is that the refresh statement in line 28 redraws the entire screen. That avoids the work of having to find the previously highlighted text and manually unhighlighting it. After the fancy display work is done, the program can continue. Branching to the proper menu-routine is simply done by using the value of menuitem and, say, a switch-case structure. NCurses is a windowed environment. H header file. Well, not by much, at least.
Those few commands that required a window argument used stdscr, the standard screen. In the bigger picture, the standard screen is only one of many windows your programs can use in NCurses.
So be prepared for some eye-opening looks through various NCurses windows. Ye Olde Standard Screen When the initscr function initializes NCurses, it does various things performs duties, sets up memory, and so on.
One of the many tasks is to create the default window for program output, the standard screen, named stdscr. Previous chapters in this book use stdscr to represent the standard screen, the only window NCurses creates. But other window names can be used as well, the names of new windows you create yourself. More on that in a few paragraphs. The Pseudo Commands Nearly all text-output functions in NCurses require a win argument, specifying which window to send the output. H file. For example, the addch function, which adds a character to the standard screen, is really a macro.
The actual function is named waddch and here is its format: The window real version of any pseudo function has the same name as the pseudo function, but the real function is prefixed by a w.
The Other Prefix, mv NCurses actually sports two prefixes for its text output commands. In addition to w, specifying a window, there is also mv, which was explained in Chapter 4. When you prefix a command with mv, the first two arguments are the row y and column x to position the cursor before outputting text.
Remember that the first row and column are numbered zero. To direct addch to a specific window and a specific location, this format is used: Making Windows Creating a new window is simple, thanks to the newwin function: The smallest you can go is a one-character window. When the call to newwin is successful, a pointer to a window structure is returned.
This structure is declared in your program using this format: When the call fails, NULL is returned. And now: The first, naturally, is the standard screen.
But the newwin function in line 13 creates a second window, named two line 5 , as shown in Listing Press Enter to see the new window and its text. Press Enter to end the program. The new window is created. When there is a problem, this chunk of code handles the situation. So the new window most definitely is created and exists in the program. If you recall from your basic knowledge of NCurses, what is required so that you can see text output? But for a specific window, you need the wrefresh function.
In fact, the refresh function itself is merely a macro defined as wrefresh stdscr. So all the program is missing is a wrefresh to update the new window.
The following needs to be added at line This is the new window created! If the program continued, you could direct text output to one screen or the other and you can switch between the windows as well, as demonstrated in the following section. Switching between Windows There is no advantage of having multiple windows unless you can switch between them.
For example, you can have one window or a set of windows detailing help information. You can then display those windows when a user hits the Help key or some other key on the keyboard, as the code in Listing demonstrates. Note, however, that echo is off and, therefore, an addch function is required line 37 to display input. Pressing Enter then returns you to the standard screen.
The showhelp function is where the swapping takes place.
The function used to display the help screen is wrefresh function, as shown in line Likewise, a refresh function in line 50 is used to switch back to the standard screen.
Well, it does work! The wrefresh function writes only changed text to the screen. Refer to Chapter 2: Only new text written to the screen or text changed — what NCurses refers to as touched text — is written to the screen when you wrefresh. By working in that manner, NCurses is very efficient. The solution is to force NCurses to display the entire window.
Without manually going through and rewriting the thing, you can use the touchwin function: Therefore, on the next refresh or wrefresh call, the entire window will be written to the screen. To fix the code, add the following at line And add the following at line Windows of a Smaller Size There is no reason for the help menu window to be as large as it is.
C or as tiny as one character. Here is the full format for the newwin function again: The values rows and cols set the size of the new window. Remember that the newwin function fails either when not enough memory is available or part of the window hangs off the visible screen.
C source code and change line 14 as follows: But after saving, compiling, and running, you can still see the original window, stdscr, behind the help window. Most helpful customer reviews 0 of 0 people found the following review helpful.
Go retro, rogue! Curses to ye! By Mfragin Let's face it--you wouldn't be looking at this unless you're pretty unique in your use of computers--or somewhat eclectic in your hobbies.
I like ncurses for many reasons. In this day and age of complex GUI applications and operating system interfaces, ncurses allows a programmer to return to a simpler time--or to a future world where dwarfs and complex agents live in an emergent world of complexity. This is another book I feel compelled to review for two reasons: 1 there is really nothing else like it that is currently available, and 2 it's hard to imagine there being a better book on this subject.
Dan Gookin has always been a great writer for those that want to teach themselves C programming or DOS, or many other domains. I believe this book may be his most unique contribution to the field. The book has pages, but don't think it's a slow read. In fact, you'll probably find yourself flying through it, thankful that they still print tons of example code in books like this. Page is the last of the regular text in the book, the end of 14 excellent chapters that have you writing code and experimenting all along the way.