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