2 $Id: hackguide.html,v 1.32 2019/07/28 18:08:54 tom Exp $
3 ****************************************************************************
4 * Copyright (c) 1998-2017,2019 Free Software Foundation, Inc. *
6 * Permission is hereby granted, free of charge, to any person obtaining a *
7 * copy of this software and associated documentation files (the *
8 * "Software"), to deal in the Software without restriction, including *
9 * without limitation the rights to use, copy, modify, merge, publish, *
10 * distribute, distribute with modifications, sublicense, and/or sell *
11 * copies of the Software, and to permit persons to whom the Software is *
12 * furnished to do so, subject to the following conditions: *
14 * The above copyright notice and this permission notice shall be included *
15 * in all copies or substantial portions of the Software. *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
20 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
21 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
22 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
23 * THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
25 * Except as contained in this notice, the name(s) of the above copyright *
26 * holders shall not be used in advertising or otherwise to promote the *
27 * sale, use or other dealings in this Software without prior written *
29 ****************************************************************************
31 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
35 <meta name="generator" content=
36 "HTML Tidy for HTML5 for Linux version 5.2.0">
38 <title>A Hacker's Guide to Ncurses Internals</title>
39 <link rel="author" href="mailto:bugs-ncurses@gnu.org">
40 <meta http-equiv="Content-Type" content=
41 "text/html; charset=us-ascii"><!--
42 This document is self-contained, *except* that there is one relative link to
43 the ncurses-intro.html document, expected to be in the same directory with
49 <h1>A Hacker's Guide to NCURSES</h1>
54 <li><a href="#abstract">Abstract</a></li>
57 <a href="#objective">Objective of the Package</a>
60 <li><a href="#whysvr4">Why System V Curses?</a></li>
62 <li><a href="#extensions">How to Design Extensions</a></li>
66 <li><a href="#portability">Portability and Configuration</a></li>
68 <li><a href="#documentation">Documentation Conventions</a></li>
70 <li><a href="#bugtrack">How to Report Bugs</a></li>
73 <a href="#ncurslib">A Tour of the Ncurses Library</a>
76 <li><a href="#loverview">Library Overview</a></li>
78 <li><a href="#engine">The Engine Room</a></li>
80 <li><a href="#input">Keyboard Input</a></li>
82 <li><a href="#mouse">Mouse Events</a></li>
84 <li><a href="#output">Output and Screen Updating</a></li>
88 <li><a href="#fmnote">The Forms and Menu Libraries</a></li>
91 <a href="#tic">A Tour of the Terminfo Compiler</a>
94 <li><a href="#nonuse">Translation of
95 Non-<strong>use</strong> Capabilities</a></li>
97 <li><a href="#uses">Use Capability Resolution</a></li>
99 <li><a href="#translation">Source-Form Translation</a></li>
103 <li><a href="#utils">Other Utilities</a></li>
105 <li><a href="#style">Style Tips for Developers</a></li>
107 <li><a href="#port">Porting Hints</a></li>
110 <h1><a name="abstract" id="abstract">Abstract</a></h1>
112 <p>This document is a hacker's tour of the
113 <strong>ncurses</strong> library and utilities. It discusses
114 design philosophy, implementation methods, and the conventions
115 used for coding and documentation. It is recommended reading for
116 anyone who is interested in porting, extending or improving the
119 <h1><a name="objective" id="objective">Objective of the
122 <p>The objective of the <strong>ncurses</strong> package is to
123 provide a free software API for character-cell terminals and
124 terminal emulators with the following characteristics:</p>
127 <li>Source-compatible with historical curses implementations
128 (including the original BSD curses and System V curses.</li>
130 <li>Conformant with the XSI Curses standard issued as part of
133 <li>High-quality — stable and reliable code, wide
134 portability, good packaging, superior documentation.</li>
136 <li>Featureful — should eliminate as much of the drudgery
137 of C interface programming as possible, freeing programmers to
138 think at a higher level of design.</li>
141 <p>These objectives are in priority order. So, for example,
142 source compatibility with older version must trump featurefulness
143 — we cannot add features if it means breaking the portion
144 of the API corresponding to historical curses versions.</p>
146 <h2><a name="whysvr4" id="whysvr4">Why System V Curses?</a></h2>
148 <p>We used System V curses as a model, reverse-engineering their
149 API, in order to fulfill the first two objectives.</p>
151 <p>System V curses implementations can support BSD curses
152 programs with just a recompilation, so by capturing the System V
153 API we also capture BSD's.</p>
155 <p>More importantly for the future, the XSI Curses standard
156 issued by X/Open is explicitly and closely modeled on System V.
157 So conformance with System V took us most of the way to
158 base-level XSI conformance.</p>
160 <h2><a name="extensions" id="extensions">How to Design
163 <p>The third objective (standards conformance) requires that it
164 be easy to condition source code using <strong>ncurses</strong>
165 so that the absence of nonstandard extensions does not break the
168 <p>Accordingly, we have a policy of associating with each
169 nonstandard extension a feature macro, so that ncurses client
170 code can use this macro to condition in or out the code that
171 requires the <strong>ncurses</strong> extension.</p>
173 <p>For example, there is a macro
174 <code>NCURSES_MOUSE_VERSION</code> which XSI Curses does not
175 define, but which is defined in the <strong>ncurses</strong>
176 library header. You can use this to condition the calls to the
179 <h1><a name="portability" id="portability">Portability and
180 Configuration</a></h1>
182 <p>Code written for <strong>ncurses</strong> may assume an
183 ANSI-standard C compiler and POSIX-compatible OS interface. It
184 may also assume the presence of a System-V-compatible
185 <em>select(2)</em> call.</p>
187 <p>We encourage (but do not require) developers to make the code
188 friendly to less-capable UNIX environments wherever possible.</p>
190 <p>We encourage developers to support OS-specific optimizations
191 and methods not available under POSIX/ANSI, provided only
195 <li>All such code is properly conditioned so the build process
196 does not attempt to compile it under a plain ANSI/POSIX
199 <li>Adding such implementation methods does not introduce
200 incompatibilities in the <strong>ncurses</strong> API between
204 <p>We use GNU <code>autoconf(1)</code> as a tool to deal with
205 portability issues. The right way to leverage an OS-specific
206 feature is to modify the autoconf specification files
207 (configure.in and aclocal.m4) to set up a new feature macro,
208 which you then use to condition your code.</p>
210 <h1><a name="documentation" id="documentation">Documentation
213 <p>There are three kinds of documentation associated with this
214 package. Each has a different preferred format:</p>
217 <li>Package-internal files (README, INSTALL, TO-DO etc.)</li>
219 <li>Manual pages.</li>
221 <li>Everything else (i.e., narrative documentation).</li>
224 <p>Our conventions are simple:</p>
227 <li><strong>Maintain package-internal files in plain
228 text.</strong> The expected viewer for them <em>more(1)</em> or
229 an editor window; there is no point in elaborate mark-up.</li>
231 <li><strong>Mark up manual pages in the man macros.</strong>
232 These have to be viewable through traditional <em>man(1)</em>
235 <li><strong>Write everything else in HTML.</strong>
239 <p>When in doubt, HTMLize a master and use <em>lynx(1)</em> to
240 generate plain ASCII (as we do for the announcement
243 <p>The reason for choosing HTML is that it is (a) well-adapted
244 for on-line browsing through viewers that are everywhere; (b)
245 more easily readable as plain text than most other mark-ups, if
246 you do not have a viewer; and (c) carries enough information that
247 you can generate a nice-looking printed version from it. Also, of
248 course, it make exporting things like the announcement document
249 to WWW pretty trivial.</p>
251 <h1><a name="bugtrack" id="bugtrack">How to Report Bugs</a></h1>
253 <p>The <a name="bugreport" id="bugreport">reporting address for
255 "mailto:bug-ncurses@gnu.org">bug-ncurses@gnu.org</a>. This is a
256 majordomo list; to join, write to
257 <code>bug-ncurses-request@gnu.org</code> with a message
258 containing the line:</p>
261 subscribe <name>@<host.domain>
264 <p>The <code>ncurses</code> code is maintained by a small group
265 of volunteers. While we try our best to fix bugs promptly, we
266 simply do not have a lot of hours to spend on elementary
267 hand-holding. We rely on intelligent cooperation from our users.
268 If you think you have found a bug in <code>ncurses</code>, there
269 are some steps you can take before contacting us that will help
270 get the bug fixed quickly.</p>
272 <p>In order to use our bug-fixing time efficiently, we put people
273 who show us they have taken these steps at the head of our queue.
274 This means that if you do not, you will probably end up at the
275 tail end and have to wait a while.</p>
278 <li>Develop a recipe to reproduce the bug.
280 <p>Bugs we can reproduce are likely to be fixed very quickly,
281 often within days. The most effective single thing you can do
282 to get a quick fix is develop a way we can duplicate the bad
283 behavior — ideally, by giving us source for a small,
284 portable test program that breaks the library. (Even better
285 is a keystroke recipe using one of the test programs provided
286 with the distribution.)</p>
289 <li>Try to reproduce the bug on a different terminal type.
291 <p>In our experience, most of the behaviors people report as
292 library bugs are actually due to subtle problems in terminal
293 descriptions. This is especially likely to be true if you are
294 using a traditional asynchronous terminal or PC-based
295 terminal emulator, rather than xterm or a UNIX console
298 <p>It is therefore extremely helpful if you can tell us
299 whether or not your problem reproduces on other terminal
300 types. Usually you will have both a console type and xterm
301 available; please tell us whether or not your bug reproduces
304 <p>If you have xterm available, it is also good to collect
305 xterm reports for different window sizes. This is especially
306 true if you normally use an unusual xterm window size —
307 a surprising number of the bugs we have seen are either
308 triggered or masked by these.</p>
311 <li>Generate and examine a trace file for the broken behavior.
313 <p>Recompile your program with the debugging versions of the
314 libraries. Insert a <code>trace()</code> call with the
315 argument set to <code>TRACE_UPDATE</code>. (See <a href=
316 "ncurses-intro.html#debugging">"Writing Programs with
317 NCURSES"</a> for details on trace levels.) Reproduce your
318 bug, then look at the trace file to see what the library was
321 <p>Another frequent cause of apparent bugs is application
322 coding errors that cause the wrong things to be put on the
323 virtual screen. Looking at the virtual-screen dumps in the
324 trace file will tell you immediately if this is happening,
325 and save you from the possible embarrassment of being told
326 that the bug is in your code and is your problem rather than
329 <p>If the virtual-screen dumps look correct but the bug
330 persists, it is possible to crank up the trace level to give
331 more and more information about the library's update actions
332 and the control sequences it issues to perform them. The test
333 directory of the distribution contains a tool for digesting
334 these logs to make them less tedious to wade through.</p>
336 <p>Often you will find terminfo problems at this stage by
337 noticing that the escape sequences put out for various
338 capabilities are wrong. If not, you are likely to learn
339 enough to be able to characterize any bug in the
340 screen-update logic quite exactly.</p>
343 <li>Report details and symptoms, not just interpretations.
345 <p>If you do the preceding two steps, it is very likely that
346 you will discover the nature of the problem yourself and be
347 able to send us a fix. This will create happy feelings all
348 around and earn you good karma for the first time you run
349 into a bug you really cannot characterize and fix
352 <p>If you are still stuck, at least you will know what to
353 tell us. Remember, we need details. If you guess about what
354 is safe to leave out, you are too likely to be wrong.</p>
356 <p>If your bug produces a bad update, include a trace file.
357 Try to make the trace at the <em>least</em> voluminous level
358 that pins down the bug. Logs that have been through
359 tracemunch are OK, it does not throw away any information
360 (actually they are better than un-munched ones because they
361 are easier to read).</p>
363 <p>If your bug produces a core-dump, please include a
364 symbolic stack trace generated by gdb(1) or your local
367 <p>Tell us about every terminal on which you have reproduced
368 the bug — and every terminal on which you cannot.
369 Ideally, send us terminfo sources for all of these (yours
370 might differ from ours).</p>
372 <p>Include your ncurses version and your OS/machine type, of
373 course! You can find your ncurses version in the
374 <code>curses.h</code> file.</p>
378 <p>If your problem smells like a logic error or in cursor
379 movement or scrolling or a bad capability, there are a couple of
380 tiny test frames for the library algorithms in the progs
381 directory that may help you isolate it. These are not part of the
382 normal build, but do have their own make productions.</p>
384 <p>The most important of these is <code>mvcur</code>, a test
385 frame for the cursor-movement optimization code. With this
386 program, you can see directly what control sequences will be
387 emitted for any given cursor movement or scroll/insert/delete
388 operations. If you think you have got a bad capability
389 identified, you can disable it and test again. The program is
390 command-driven and has on-line help.</p>
392 <p>If you think the vertical-scroll optimization is broken, or
393 just want to understand how it works better, build
394 <code>hashmap</code> and read the header comments of
395 <code>hardscroll.c</code> and <code>hashmap.c</code>; then try it
396 out. You can also test the hardware-scrolling optimization
397 separately with <code>hardscroll</code>.</p>
399 <h1><a name="ncurslib" id="ncurslib">A Tour of the Ncurses
402 <h2><a name="loverview" id="loverview">Library Overview</a></h2>
404 <p>Most of the library is superstructure — fairly trivial
405 convenience interfaces to a small set of basic functions and data
406 structures used to manipulate the virtual screen (in particular,
407 none of this code does any I/O except through calls to more
408 fundamental modules described below). The files</p>
411 <code>lib_addch.c lib_bkgd.c lib_box.c lib_chgat.c lib_clear.c
412 lib_clearok.c lib_clrbot.c lib_clreol.c lib_colorset.c
413 lib_data.c lib_delch.c lib_delwin.c lib_echo.c lib_erase.c
414 lib_gen.c lib_getstr.c lib_hline.c lib_immedok.c lib_inchstr.c
415 lib_insch.c lib_insdel.c lib_insstr.c lib_instr.c
416 lib_isendwin.c lib_keyname.c lib_leaveok.c lib_move.c
417 lib_mvwin.c lib_overlay.c lib_pad.c lib_printw.c lib_redrawln.c
418 lib_scanw.c lib_screen.c lib_scroll.c lib_scrollok.c
419 lib_scrreg.c lib_set_term.c lib_slk.c lib_slkatr_set.c
420 lib_slkatrof.c lib_slkatron.c lib_slkatrset.c lib_slkattr.c
421 lib_slkclear.c lib_slkcolor.c lib_slkinit.c lib_slklab.c
422 lib_slkrefr.c lib_slkset.c lib_slktouch.c lib_touch.c
423 lib_unctrl.c lib_vline.c lib_wattroff.c lib_wattron.c
427 <p>are all in this category. They are very unlikely to need
428 change, barring bugs or some fundamental reorganization in the
429 underlying data structures.</p>
431 <p>These files are used only for debugging support:</p>
434 <code>lib_trace.c lib_traceatr.c lib_tracebits.c lib_tracechr.c
435 lib_tracedmp.c lib_tracemse.c trace_buf.c</code>
438 <p>It is rather unlikely you will ever need to change these,
439 unless you want to introduce a new debug trace level for some
442 <p>There is another group of files that do direct I/O via
443 <em>tputs()</em>, computations on the terminal capabilities, or
444 queries to the OS environment, but nevertheless have only fairly
445 low complexity. These include:</p>
448 <code>lib_acs.c lib_beep.c lib_color.c lib_endwin.c
449 lib_initscr.c lib_longname.c lib_newterm.c lib_options.c
450 lib_termcap.c lib_ti.c lib_tparm.c lib_tputs.c lib_vidattr.c
454 <p>They are likely to need revision only if ncurses is being
455 ported to an environment without an underlying terminfo
456 capability representation.</p>
458 <p>These files have serious hooks into the tty driver and signal
462 <code>lib_kernel.c lib_baudrate.c lib_raw.c lib_tstp.c
466 <p>If you run into porting snafus moving the package to another
467 UNIX, the problem is likely to be in one of these files. The file
468 <code>lib_print.c</code> uses sleep(2) and also falls in this
471 <p>Almost all of the real work is done in the files</p>
474 <code>hardscroll.c hashmap.c lib_addch.c lib_doupdate.c
475 lib_getch.c lib_mouse.c lib_mvcur.c lib_refresh.c lib_setup.c
479 <p>Most of the algorithmic complexity in the library lives in
480 these files. If there is a real bug in <strong>ncurses</strong>
481 itself, it is probably here. We will tour some of these files in
482 detail below (see <a href="#engine">The Engine Room</a>).</p>
484 <p>Finally, there is a group of files that is actually most of
485 the terminfo compiler. The reason this code lives in the
486 <strong>ncurses</strong> library is to support fallback to
487 /etc/termcap. These files include</p>
490 <code>alloc_entry.c captoinfo.c comp_captab.c comp_error.c
491 comp_hash.c comp_parse.c comp_scan.c parse_entry.c
492 read_termcap.c write_entry.c</code>
495 <p>We will discuss these in the compiler tour.</p>
497 <h2><a name="engine" id="engine">The Engine Room</a></h2>
499 <h3><a name="input" id="input">Keyboard Input</a></h3>
501 <p>All <code>ncurses</code> input funnels through the function
502 <code>wgetch()</code>, defined in <code>lib_getch.c</code>. This
503 function is tricky; it has to poll for keyboard and mouse events
504 and do a running match of incoming input against the set of
505 defined special keys.</p>
507 <p>The central data structure in this module is a FIFO queue,
508 used to match multiple-character input sequences against
509 special-key capabilities; also to implement pushback via
510 <code>ungetch()</code>.</p>
512 <p>The <code>wgetch()</code> code distinguishes between function
513 key sequences and the same sequences typed manually by doing a
514 timed wait after each input character that could lead a function
515 key sequence. If the entire sequence takes less than 1 second, it
516 is assumed to have been generated by a function key press.</p>
518 <p>Hackers bruised by previous encounters with variant
519 <code>select(2)</code> calls may find the code in
520 <code>lib_twait.c</code> interesting. It deals with the problem
521 that some BSD selects do not return a reliable time-left value.
522 The function <code>timed_wait()</code> effectively simulates a
525 <h3><a name="mouse" id="mouse">Mouse Events</a></h3>
527 <p>If the mouse interface is active, <code>wgetch()</code> polls
528 for mouse events each call, before it goes to the keyboard for
529 input. It is up to <code>lib_mouse.c</code> how the polling is
530 accomplished; it may vary for different devices.</p>
532 <p>Under xterm, however, mouse event notifications come in via
533 the keyboard input stream. They are recognized by having the
534 <strong>kmous</strong> capability as a prefix. This is kind of
535 klugey, but trying to wire in recognition of a mouse key prefix
536 without going through the function-key machinery would be just
537 too painful, and this turns out to imply having the prefix
538 somewhere in the function-key capabilities at terminal-type
541 <p>This kluge only works because <strong>kmous</strong> is not
542 actually used by any historic terminal type or curses
543 implementation we know of. Best guess is it is a relic of some
544 forgotten experiment in-house at Bell Labs that did not leave any
545 traces in the publicly-distributed System V terminfo files. If
546 System V or XPG4 ever gets serious about using it again, this
547 kluge may have to change.</p>
549 <p>Here are some more details about mouse event handling:</p>
551 <p>The <code>lib_mouse()</code> code is logically split into a
552 lower level that accepts event reports in a device-dependent
553 format and an upper level that parses mouse gestures and filters
554 events. The mediating data structure is a circular queue of event
557 <p>Functionally, the lower level's job is to pick up primitive
558 events and put them on the circular queue. This can happen in one
559 of two ways: either (a) <code>_nc_mouse_event()</code> detects a
560 series of incoming mouse reports and queues them, or (b) code in
561 <code>lib_getch.c</code> detects the <strong>kmous</strong>
562 prefix in the keyboard input stream and calls _nc_mouse_inline to
563 queue up a series of adjacent mouse reports.</p>
565 <p>In either case, <code>_nc_mouse_parse()</code> should be
566 called after the series is accepted to parse the digested mouse
567 reports (low-level events) into a gesture (a high-level or
568 composite event).</p>
570 <h3><a name="output" id="output">Output and Screen Updating</a></h3>
572 <p>With the single exception of character echoes during a
573 <code>wgetnstr()</code> call (which simulates cooked-mode line
574 editing in an ncurses window), the library normally does all its
575 output at refresh time.</p>
577 <p>The main job is to go from the current state of the screen (as
578 represented in the <code>curscr</code> window structure) to the
579 desired new state (as represented in the <code>newscr</code>
580 window structure), while doing as little I/O as possible.</p>
582 <p>The brains of this operation are the modules
583 <code>hashmap.c</code>, <code>hardscroll.c</code> and
584 <code>lib_doupdate.c</code>; the latter two use
585 <code>lib_mvcur.c</code>. Essentially, what happens looks like
590 <p>The <code>hashmap.c</code> module tries to detect vertical
591 motion changes between the real and virtual screens. This
592 information is represented by the oldindex members in the
593 newscr structure. These are modified by vertical-motion and
594 clear operations, and both are re-initialized after each
595 update. To this change-journalling information, the hashmap
596 code adds deductions made using a modified Heckel algorithm
597 on hash values generated from the line contents.</p>
601 <p>The <code>hardscroll.c</code> module computes an optimum
602 set of scroll, insertion, and deletion operations to make the
603 indices match. It calls <code>_nc_mvcur_scrolln()</code> in
604 <code>lib_mvcur.c</code> to do those motions.</p>
608 <p>Then <code>lib_doupdate.c</code> goes to work. Its job is
609 to do line-by-line transformations of <code>curscr</code>
610 lines to <code>newscr</code> lines. Its main tool is the
611 routine <code>mvcur()</code> in <code>lib_mvcur.c</code>.
612 This routine does cursor-movement optimization, attempting to
613 get from given screen location A to given location B in the
614 fewest output characters possible.</p>
618 <p>If you want to work on screen optimizations, you should use
619 the fact that (in the trace-enabled version of the library)
620 enabling the <code>TRACE_TIMES</code> trace level causes a report
621 to be emitted after each screen update giving the elapsed time
622 and a count of characters emitted during the update. You can use
623 this to tell when an update optimization improves efficiency.</p>
625 <p>In the trace-enabled version of the library, it is also
626 possible to disable and re-enable various optimizations at
627 runtime by tweaking the variable
628 <code>_nc_optimize_enable</code>. See the file
629 <code>include/curses.h.in</code> for mask values, near the
632 <h1><a name="fmnote" id="fmnote">The Forms and Menu Libraries</a></h1>
634 <p>The forms and menu libraries should work reliably in any
635 environment you can port ncurses to. The only portability issue
636 anywhere in them is what flavor of regular expressions the
637 built-in form field type TYPE_REGEXP will recognize.</p>
639 <p>The configuration code prefers the POSIX regex facility,
640 modeled on System V's, but will settle for BSD regexps if the
641 former is not available.</p>
643 <p>Historical note: the panels code was written primarily to
644 assist in porting u386mon 2.0 (comp.sources.misc v14i001-4) to
645 systems lacking panels support; u386mon 2.10 and beyond use it.
646 This version has been slightly cleaned up for
647 <code>ncurses</code>.</p>
649 <h1><a name="tic" id="tic">A Tour of the Terminfo Compiler</a></h1>
651 <p>The <strong>ncurses</strong> implementation of
652 <strong>tic</strong> is rather complex internally; it has to do a
653 trying combination of missions. This starts with the fact that,
654 in addition to its normal duty of compiling terminfo sources into
655 loadable terminfo binaries, it has to be able to handle termcap
656 syntax and compile that too into terminfo entries.</p>
658 <p>The implementation therefore starts with a table-driven,
659 dual-mode lexical analyzer (in <code>comp_scan.c</code>). The
660 lexer chooses its mode (termcap or terminfo) based on the first
661 “,” or “:” it finds in each entry. The
662 lexer does all the work of recognizing capability names and
663 values; the grammar above it is trivial, just "parse entries till
664 you run out of file".</p>
666 <h2><a name="nonuse" id="nonuse">Translation of
667 Non-<strong>use</strong> Capabilities</a></h2>
669 <p>Translation of most things besides <strong>use</strong>
670 capabilities is pretty straightforward. The lexical analyzer's
671 tokenizer hands each capability name to a hash function, which
672 drives a table lookup. The table entry yields an index which is
673 used to look up the token type in another table, and controls
674 interpretation of the value.</p>
676 <p>One possibly interesting aspect of the implementation is the
677 way the compiler tables are initialized. All the tables are
678 generated by various awk/sed/sh scripts from a master table
679 <code>include/Caps</code>; these scripts actually write C
680 initializers which are linked to the compiler. Furthermore, the
681 hash table is generated in the same way, so it doesn't have to be
682 generated at compiler startup time (another benefit of this
683 organization is that the hash table can be in shareable text
686 <p>Thus, adding a new capability is usually pretty trivial, just
687 a matter of adding one line to the <code>include/Caps</code>
688 file. We will have more to say about this in the section on
689 <a href="#translation">Source-Form Translation</a>.</p>
691 <h2><a name="uses" id="uses">Use Capability Resolution</a></h2>
693 <p>The background problem that makes <strong>tic</strong> tricky
694 is not the capability translation itself, it is the resolution of
695 <strong>use</strong> capabilities. Older versions would not
696 handle forward <strong>use</strong> references for this reason
697 (that is, a using terminal always had to follow its use target in
698 the source file). By doing this, they got away with a simple
699 implementation tactic; compile everything as it blows by, then
700 resolve uses from compiled entries.</p>
702 <p>This will not do for <strong>ncurses</strong>. The problem is
703 that that the whole compilation process has to be embeddable in
704 the <strong>ncurses</strong> library so that it can be called by
705 the startup code to translate termcap entries on the fly. The
706 embedded version cannot go promiscuously writing everything it
707 translates out to disk — for one thing, it will typically
708 be running with non-root permissions.</p>
710 <p>So our <strong>tic</strong> is designed to parse an entire
711 terminfo file into a doubly-linked circular list of entry
712 structures in-core, and then do <strong>use</strong> resolution
713 in-memory before writing everything out. This design has other
714 advantages: it makes forward and back use-references equally easy
715 (so we get the latter for free), and it makes checking for name
716 collisions before they are written out easy to do.</p>
718 <p>And this is exactly how the embedded version works. But the
719 stand-alone user-accessible version of <strong>tic</strong>
720 partly reverts to the historical strategy; it writes to disk (not
721 keeping in core) any entry with no <strong>use</strong>
724 <p>This is strictly a core-economy kluge, implemented because the
725 terminfo master file is large enough that some core-poor systems
726 swap like crazy when you compile it all in memory...there have
727 been reports of this process taking <strong>three hours</strong>,
728 rather than the twenty seconds or less typical on the author's
731 <p>So. The executable <strong>tic</strong> passes the
732 entry-parser a hook that <em>immediately</em> writes out the
733 referenced entry if it has no use capabilities. The compiler main
734 loop refrains from adding the entry to the in-core list when this
735 hook fires. If some other entry later needs to reference an entry
736 that got written immediately, that is OK; the resolution code
737 will fetch it off disk when it cannot find it in core.</p>
739 <p>Name collisions will still be detected, just not as cleanly.
740 The <code>write_entry()</code> code complains before overwriting
741 an entry that postdates the time of <strong>tic</strong>'s first
742 call to <code>write_entry()</code>, Thus it will complain about
743 overwriting entries newly made during the <strong>tic</strong>
744 run, but not about overwriting ones that predate it.</p>
746 <h2><a name="translation" id="translation">Source-Form
749 <p>Another use of <strong>tic</strong> is to do source
750 translation between various termcap and terminfo formats. There
751 are more variants out there than you might think; the ones we
752 know about are described in the <strong>captoinfo(1)</strong>
755 <p>The translation output code (<code>dump_entry()</code> in
756 <code>ncurses/dump_entry.c</code>) is shared with the
757 <strong>infocmp(1)</strong> utility. It takes the same internal
758 representation used to generate the binary form and dumps it to
759 standard output in a specified format.</p>
761 <p>The <code>include/Caps</code> file has a header comment
762 describing ways you can specify source translations for
763 nonstandard capabilities just by altering the master table. It is
764 possible to set up capability aliasing or tell the compiler to
765 plain ignore a given capability without writing any C code at
768 <p>For circumstances where you need to do algorithmic
769 translation, there are functions in <code>parse_entry.c</code>
770 called after the parse of each entry that are specifically
771 intended to encapsulate such translations. This, for example, is
772 where the AIX <strong>box1</strong> capability get translated to
773 an <strong>acsc</strong> string.</p>
775 <h1><a name="utils" id="utils">Other Utilities</a></h1>
777 <p>The <strong>infocmp</strong> utility is just a wrapper around
778 the same entry-dumping code used by <strong>tic</strong> for
779 source translation. Perhaps the one interesting aspect of the
780 code is the use of a predicate function passed in to
781 <code>dump_entry()</code> to control which capabilities are
782 dumped. This is necessary in order to handle both the ordinary
783 De-compilation case and entry difference reporting.</p>
785 <p>The <strong>tput</strong> and <strong>clear</strong> utilities
786 just do an entry load followed by a <code>tputs()</code> of a
787 selected capability.</p>
789 <h1><a name="style" id="style">Style Tips for Developers</a></h1>
791 <p>See the TO-DO file in the top-level directory of the source
792 distribution for additions that would be particularly useful.</p>
794 <p>The prefix <code>_nc_</code> should be used on library public
795 functions that are not part of the curses API in order to prevent
796 pollution of the application namespace. If you have to add to or
797 modify the function prototypes in curses.h.in, read
798 ncurses/MKlib_gen.sh first so you can avoid breaking XSI
799 conformance. Please join the ncurses mailing list. See the
800 INSTALL file in the top level of the distribution for details on
803 <p>Look for the string <code>FIXME</code> in source files to tag
804 minor bugs and potential problems that could use fixing.</p>
806 <p>Do not try to auto-detect OS features in the main body of the
807 C code. That is the job of the configuration system.</p>
809 <p>To hold down complexity, do make your code data-driven.
810 Especially, if you can drive logic from a table filtered out of
811 <code>include/Caps</code>, do it. If you find you need to augment
812 the data in that file in order to generate the proper table, that
813 is still preferable to ad-hoc code — that is why the fifth
814 field (flags) is there.</p>
818 <h1><a name="port" id="port">Porting Hints</a></h1>
820 <p>The following notes are intended to be a first step towards
821 DOS and Macintosh ports of the ncurses libraries.</p>
823 <p>The following library modules are “pure curses”;
824 they operate only on the curses internal structures, do all
825 output through other curses calls (not including
826 <code>tputs()</code> and <code>putp()</code>) and do not call any
827 other UNIX routines such as signal(2) or the stdio library. Thus,
828 they should not need to be modified for single-terminal
832 <code>lib_addch.c lib_addstr.c lib_bkgd.c lib_box.c lib_clear.c
833 lib_clrbot.c lib_clreol.c lib_delch.c lib_delwin.c lib_erase.c
834 lib_inchstr.c lib_insch.c lib_insdel.c lib_insstr.c
835 lib_keyname.c lib_move.c lib_mvwin.c lib_newwin.c lib_overlay.c
836 lib_pad.c lib_printw.c lib_refresh.c lib_scanw.c lib_scroll.c
837 lib_scrreg.c lib_set_term.c lib_touch.c lib_tparm.c lib_tputs.c
838 lib_unctrl.c lib_window.c panel.c</code>
841 <p>This module is pure curses, but calls outstr():</p>
844 <code>lib_getstr.c</code>
847 <p>These modules are pure curses, except that they use
848 <code>tputs()</code> and <code>putp()</code>:</p>
851 <code>lib_beep.c lib_color.c lib_endwin.c lib_options.c
852 lib_slk.c lib_vidattr.c</code>
855 <p>This modules assist in POSIX emulation on non-POSIX
861 <dd>signal calls</dd>
864 <p>The following source files will not be needed for a
865 single-terminal-type port.</p>
868 <code>alloc_entry.c captoinfo.c clear.c comp_captab.c
869 comp_error.c comp_hash.c comp_main.c comp_parse.c comp_scan.c
870 dump_entry.c infocmp.c parse_entry.c read_entry.c tput.c
874 <p>The following modules will use
875 open()/read()/write()/close()/lseek() on files, but no other OS
879 <dt>lib_screen.c</dt>
881 <dd>used to read/write screen dumps</dd>
885 <dd>used to write trace data to the logfile</dd>
888 <p>Modules that would have to be modified for a port start
891 <p>The following modules are “pure curses” but
892 contain assumptions inappropriate for a memory-mapped port.</p>
895 <dt>lib_longname.c</dt>
897 <dd>assumes there may be multiple terminals</dd>
901 <dd>assumes acs_map as a double indirection</dd>
905 <dd>assumes cursor moves have variable cost</dd>
907 <dt>lib_termcap.c</dt>
909 <dd>assumes there may be multiple terminals</dd>
913 <dd>assumes there may be multiple terminals</dd>
916 <p>The following modules use UNIX-specific calls:</p>
919 <dt>lib_doupdate.c</dt>
921 <dd>input checking</dd>
927 <dt>lib_initscr.c</dt>
931 <dt>lib_newterm.c</dt>
933 <dt>lib_baudrate.c</dt>
935 <dt>lib_kernel.c</dt>
937 <dd>various tty-manipulation and system calls</dd>
941 <dd>various tty-manipulation calls</dd>
945 <dd>various tty-manipulation calls</dd>
947 <dt>lib_restart.c</dt>
949 <dd>various tty-manipulation calls</dd>
953 <dd>signal-manipulation calls</dd>
957 <dd>gettimeofday(), select().</dd>
963 Eric S. Raymond <esr@snark.thyrsus.com>
965 (Note: This is <em>not</em> the <a href="#bugtrack">bug