]> ncurses.scripts.mit.edu Git - ncurses.git/blob - doc/html/hackguide.html
ncurses 6.0 - patch 20171230
[ncurses.git] / doc / html / hackguide.html
1 <!--
2   $Id: hackguide.html,v 1.30 2017/05/05 11:50:09 tom Exp $
3   ****************************************************************************
4   * Copyright (c) 1998-2012,2017 Free Software Foundation, Inc.              *
5   *                                                                          *
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:                 *
13   *                                                                          *
14   * The above copyright notice and this permission notice shall be included  *
15   * in all copies or substantial portions of the Software.                   *
16   *                                                                          *
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.                               *
24   *                                                                          *
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       *
28   * authorization.                                                           *
29   ****************************************************************************
30 -->
31 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
32
33 <html>
34 <head>
35   <meta name="generator" content=
36   "HTML Tidy for Linux (vers 25 March 2009), see www.w3.org">
37
38   <title>A Hacker's Guide to Ncurses Internals</title>
39   <link rev="made" 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
44 this one.
45 -->
46 </head>
47
48 <body>
49   <h1>A Hacker's Guide to NCURSES</h1>
50
51   <h1>Contents</h1>
52
53   <ul>
54     <li><a href="#abstract">Abstract</a></li>
55
56     <li>
57       <a href="#objective">Objective of the Package</a>
58
59       <ul>
60         <li><a href="#whysvr4">Why System V Curses?</a></li>
61
62         <li><a href="#extensions">How to Design Extensions</a></li>
63       </ul>
64     </li>
65
66     <li><a href="#portability">Portability and
67     Configuration</a></li>
68
69     <li><a href="#documentation">Documentation Conventions</a></li>
70
71     <li><a href="#bugtrack">How to Report Bugs</a></li>
72
73     <li>
74       <a href="#ncurslib">A Tour of the Ncurses Library</a>
75
76       <ul>
77         <li><a href="#loverview">Library Overview</a></li>
78
79         <li><a href="#engine">The Engine Room</a></li>
80
81         <li><a href="#input">Keyboard Input</a></li>
82
83         <li><a href="#mouse">Mouse Events</a></li>
84
85         <li><a href="#output">Output and Screen Updating</a></li>
86       </ul>
87     </li>
88
89     <li><a href="#fmnote">The Forms and Menu Libraries</a></li>
90
91     <li>
92       <a href="#tic">A Tour of the Terminfo Compiler</a>
93
94       <ul>
95         <li><a href="#nonuse">Translation of
96         Non-<strong>use</strong> Capabilities</a></li>
97
98         <li><a href="#uses">Use Capability Resolution</a></li>
99
100         <li><a href="#translation">Source-Form Translation</a></li>
101       </ul>
102     </li>
103
104     <li><a href="#utils">Other Utilities</a></li>
105
106     <li><a href="#style">Style Tips for Developers</a></li>
107
108     <li><a href="#port">Porting Hints</a></li>
109   </ul>
110
111   <h1><a name="abstract" id="abstract">Abstract</a></h1>
112
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
118   package.</p>
119
120   <h1><a name="objective" id="objective">Objective of the
121   Package</a></h1>
122
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>
126
127   <ul>
128     <li>Source-compatible with historical curses implementations
129     (including the original BSD curses and System V curses.</li>
130
131     <li>Conformant with the XSI Curses standard issued as part of
132     XPG4 by X/Open.</li>
133
134     <li>High-quality &mdash; stable and reliable code, wide
135     portability, good packaging, superior documentation.</li>
136
137     <li>Featureful &mdash; 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>
140   </ul>
141
142   <p>These objectives are in priority order. So, for example,
143   source compatibility with older version must trump featurefulness
144   &mdash; we cannot add features if it means breaking the portion
145   of the API corresponding to historical curses versions.</p>
146
147   <h2><a name="whysvr4" id="whysvr4">Why System V Curses?</a></h2>
148
149   <p>We used System V curses as a model, reverse-engineering their
150   API, in order to fulfill the first two objectives.</p>
151
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>
155
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>
160
161   <h2><a name="extensions" id="extensions">How to Design
162   Extensions</a></h2>
163
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
167   code.</p>
168
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>
173
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
178   mouse API calls.</p>
179
180   <h1><a name="portability" id="portability">Portability and
181   Configuration</a></h1>
182
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>
187
188   <p>We encourage (but do not require) developers to make the code
189   friendly to less-capable UNIX environments wherever possible.</p>
190
191   <p>We encourage developers to support OS-specific optimizations
192   and methods not available under POSIX/ANSI, provided only
193   that:</p>
194
195   <ul>
196     <li>All such code is properly conditioned so the build process
197     does not attempt to compile it under a plain ANSI/POSIX
198     environment.</li>
199
200     <li>Adding such implementation methods does not introduce
201     incompatibilities in the <strong>ncurses</strong> API between
202     platforms.</li>
203   </ul>
204
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>
210
211   <h1><a name="documentation" id="documentation">Documentation
212   Conventions</a></h1>
213
214   <p>There are three kinds of documentation associated with this
215   package. Each has a different preferred format:</p>
216
217   <ul>
218     <li>Package-internal files (README, INSTALL, TO-DO etc.)</li>
219
220     <li>Manual pages.</li>
221
222     <li>Everything else (i.e., narrative documentation).</li>
223   </ul>
224
225   <p>Our conventions are simple:</p>
226
227   <ol>
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>
231
232     <li><strong>Mark up manual pages in the man macros.</strong>
233     These have to be viewable through traditional <em>man(1)</em>
234     programs.</li>
235
236     <li><strong>Write everything else in HTML.</strong></li>
237   </ol>
238
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
241   document).</p>
242
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>
250
251   <h1><a name="bugtrack" id="bugtrack">How to Report Bugs</a></h1>
252
253   <p>The <a name="bugreport" id="bugreport">reporting address for
254   bugs</a> is <a href=
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>
259   <pre>
260              subscribe &lt;name&gt;@&lt;host.domain&gt;
261 </pre>
262
263   <p>The <code>ncurses</code> code is maintained by a small group
264   of volunteers. While we try our best to fix bugs promptly, we
265   simply do not have a lot of hours to spend on elementary
266   hand-holding. We rely on intelligent cooperation from our users.
267   If you think you have found a bug in <code>ncurses</code>, there
268   are some steps you can take before contacting us that will help
269   get the bug fixed quickly.</p>
270
271   <p>In order to use our bug-fixing time efficiently, we put people
272   who show us they have taken these steps at the head of our queue.
273   This means that if you do not, you will probably end up at the
274   tail end and have to wait a while.</p>
275
276   <ol>
277     <li>Develop a recipe to reproduce the bug.
278
279       <p>Bugs we can reproduce are likely to be fixed very quickly,
280       often within days. The most effective single thing you can do
281       to get a quick fix is develop a way we can duplicate the bad
282       behavior &mdash; ideally, by giving us source for a small,
283       portable test program that breaks the library. (Even better
284       is a keystroke recipe using one of the test programs provided
285       with the distribution.)</p>
286     </li>
287
288     <li>Try to reproduce the bug on a different terminal type.
289
290       <p>In our experience, most of the behaviors people report as
291       library bugs are actually due to subtle problems in terminal
292       descriptions. This is especially likely to be true if you are
293       using a traditional asynchronous terminal or PC-based
294       terminal emulator, rather than xterm or a UNIX console
295       entry.</p>
296
297       <p>It is therefore extremely helpful if you can tell us
298       whether or not your problem reproduces on other terminal
299       types. Usually you will have both a console type and xterm
300       available; please tell us whether or not your bug reproduces
301       on both.</p>
302
303       <p>If you have xterm available, it is also good to collect
304       xterm reports for different window sizes. This is especially
305       true if you normally use an unusual xterm window size &mdash;
306       a surprising number of the bugs we have seen are either
307       triggered or masked by these.</p>
308     </li>
309
310     <li>Generate and examine a trace file for the broken behavior.
311
312       <p>Recompile your program with the debugging versions of the
313       libraries. Insert a <code>trace()</code> call with the
314       argument set to <code>TRACE_UPDATE</code>. (See <a href=
315       "ncurses-intro.html#debugging">"Writing Programs with
316       NCURSES"</a> for details on trace levels.) Reproduce your
317       bug, then look at the trace file to see what the library was
318       actually doing.</p>
319
320       <p>Another frequent cause of apparent bugs is application
321       coding errors that cause the wrong things to be put on the
322       virtual screen. Looking at the virtual-screen dumps in the
323       trace file will tell you immediately if this is happening,
324       and save you from the possible embarrassment of being told
325       that the bug is in your code and is your problem rather than
326       ours.</p>
327
328       <p>If the virtual-screen dumps look correct but the bug
329       persists, it is possible to crank up the trace level to give
330       more and more information about the library's update actions
331       and the control sequences it issues to perform them. The test
332       directory of the distribution contains a tool for digesting
333       these logs to make them less tedious to wade through.</p>
334
335       <p>Often you will find terminfo problems at this stage by
336       noticing that the escape sequences put out for various
337       capabilities are wrong. If not, you are likely to learn
338       enough to be able to characterize any bug in the
339       screen-update logic quite exactly.</p>
340     </li>
341
342     <li>Report details and symptoms, not just interpretations.
343
344       <p>If you do the preceding two steps, it is very likely that
345       you will discover the nature of the problem yourself and be
346       able to send us a fix. This will create happy feelings all
347       around and earn you good karma for the first time you run
348       into a bug you really cannot characterize and fix
349       yourself.</p>
350
351       <p>If you are still stuck, at least you will know what to
352       tell us. Remember, we need details. If you guess about what
353       is safe to leave out, you are too likely to be wrong.</p>
354
355       <p>If your bug produces a bad update, include a trace file.
356       Try to make the trace at the <em>least</em> voluminous level
357       that pins down the bug. Logs that have been through
358       tracemunch are OK, it does not throw away any information
359       (actually they are better than un-munched ones because they
360       are easier to read).</p>
361
362       <p>If your bug produces a core-dump, please include a
363       symbolic stack trace generated by gdb(1) or your local
364       equivalent.</p>
365
366       <p>Tell us about every terminal on which you have reproduced
367       the bug &mdash; and every terminal on which you cannot.
368       Ideally, sent us terminfo sources for all of these (yours
369       might differ from ours).</p>
370
371       <p>Include your ncurses version and your OS/machine type, of
372       course! You can find your ncurses version in the
373       <code>curses.h</code> file.</p>
374     </li>
375   </ol>
376
377   <p>If your problem smells like a logic error or in cursor
378   movement or scrolling or a bad capability, there are a couple of
379   tiny test frames for the library algorithms in the progs
380   directory that may help you isolate it. These are not part of the
381   normal build, but do have their own make productions.</p>
382
383   <p>The most important of these is <code>mvcur</code>, a test
384   frame for the cursor-movement optimization code. With this
385   program, you can see directly what control sequences will be
386   emitted for any given cursor movement or scroll/insert/delete
387   operations. If you think you have got a bad capability
388   identified, you can disable it and test again. The program is
389   command-driven and has on-line help.</p>
390
391   <p>If you think the vertical-scroll optimization is broken, or
392   just want to understand how it works better, build
393   <code>hashmap</code> and read the header comments of
394   <code>hardscroll.c</code> and <code>hashmap.c</code>; then try it
395   out. You can also test the hardware-scrolling optimization
396   separately with <code>hardscroll</code>.</p>
397
398   <h1><a name="ncurslib" id="ncurslib">A Tour of the Ncurses
399   Library</a></h1>
400
401   <h2><a name="loverview" id="loverview">Library Overview</a></h2>
402
403   <p>Most of the library is superstructure &mdash; fairly trivial
404   convenience interfaces to a small set of basic functions and data
405   structures used to manipulate the virtual screen (in particular,
406   none of this code does any I/O except through calls to more
407   fundamental modules described below). The files</p>
408
409   <blockquote>
410     <code>lib_addch.c lib_bkgd.c lib_box.c lib_chgat.c lib_clear.c
411     lib_clearok.c lib_clrbot.c lib_clreol.c lib_colorset.c
412     lib_data.c lib_delch.c lib_delwin.c lib_echo.c lib_erase.c
413     lib_gen.c lib_getstr.c lib_hline.c lib_immedok.c lib_inchstr.c
414     lib_insch.c lib_insdel.c lib_insstr.c lib_instr.c
415     lib_isendwin.c lib_keyname.c lib_leaveok.c lib_move.c
416     lib_mvwin.c lib_overlay.c lib_pad.c lib_printw.c lib_redrawln.c
417     lib_scanw.c lib_screen.c lib_scroll.c lib_scrollok.c
418     lib_scrreg.c lib_set_term.c lib_slk.c lib_slkatr_set.c
419     lib_slkatrof.c lib_slkatron.c lib_slkatrset.c lib_slkattr.c
420     lib_slkclear.c lib_slkcolor.c lib_slkinit.c lib_slklab.c
421     lib_slkrefr.c lib_slkset.c lib_slktouch.c lib_touch.c
422     lib_unctrl.c lib_vline.c lib_wattroff.c lib_wattron.c
423     lib_window.c</code>
424   </blockquote>
425
426   <p>are all in this category. They are very unlikely to need
427   change, barring bugs or some fundamental reorganization in the
428   underlying data structures.</p>
429
430   <p>These files are used only for debugging support:</p>
431
432   <blockquote>
433     <code>lib_trace.c lib_traceatr.c lib_tracebits.c lib_tracechr.c
434     lib_tracedmp.c lib_tracemse.c trace_buf.c</code>
435   </blockquote>
436
437   <p>It is rather unlikely you will ever need to change these,
438   unless you want to introduce a new debug trace level for some
439   reason.</p>
440
441   <p>There is another group of files that do direct I/O via
442   <em>tputs()</em>, computations on the terminal capabilities, or
443   queries to the OS environment, but nevertheless have only fairly
444   low complexity. These include:</p>
445
446   <blockquote>
447     <code>lib_acs.c lib_beep.c lib_color.c lib_endwin.c
448     lib_initscr.c lib_longname.c lib_newterm.c lib_options.c
449     lib_termcap.c lib_ti.c lib_tparm.c lib_tputs.c lib_vidattr.c
450     read_entry.c.</code>
451   </blockquote>
452
453   <p>They are likely to need revision only if ncurses is being
454   ported to an environment without an underlying terminfo
455   capability representation.</p>
456
457   <p>These files have serious hooks into the tty driver and signal
458   facilities:</p>
459
460   <blockquote>
461     <code>lib_kernel.c lib_baudrate.c lib_raw.c lib_tstp.c
462     lib_twait.c</code>
463   </blockquote>
464
465   <p>If you run into porting snafus moving the package to another
466   UNIX, the problem is likely to be in one of these files. The file
467   <code>lib_print.c</code> uses sleep(2) and also falls in this
468   category.</p>
469
470   <p>Almost all of the real work is done in the files</p>
471
472   <blockquote>
473     <code>hardscroll.c hashmap.c lib_addch.c lib_doupdate.c
474     lib_getch.c lib_mouse.c lib_mvcur.c lib_refresh.c lib_setup.c
475     lib_vidattr.c</code>
476   </blockquote>
477
478   <p>Most of the algorithmic complexity in the library lives in
479   these files. If there is a real bug in <strong>ncurses</strong>
480   itself, it is probably here. We will tour some of these files in
481   detail below (see <a href="#engine">The Engine Room</a>).</p>
482
483   <p>Finally, there is a group of files that is actually most of
484   the terminfo compiler. The reason this code lives in the
485   <strong>ncurses</strong> library is to support fallback to
486   /etc/termcap. These files include</p>
487
488   <blockquote>
489     <code>alloc_entry.c captoinfo.c comp_captab.c comp_error.c
490     comp_hash.c comp_parse.c comp_scan.c parse_entry.c
491     read_termcap.c write_entry.c</code>
492   </blockquote>
493
494   <p>We will discuss these in the compiler tour.</p>
495
496   <h2><a name="engine" id="engine">The Engine Room</a></h2>
497
498   <h3><a name="input" id="input">Keyboard Input</a></h3>
499
500   <p>All <code>ncurses</code> input funnels through the function
501   <code>wgetch()</code>, defined in <code>lib_getch.c</code>. This
502   function is tricky; it has to poll for keyboard and mouse events
503   and do a running match of incoming input against the set of
504   defined special keys.</p>
505
506   <p>The central data structure in this module is a FIFO queue,
507   used to match multiple-character input sequences against
508   special-key capabilities; also to implement pushback via
509   <code>ungetch()</code>.</p>
510
511   <p>The <code>wgetch()</code> code distinguishes between function
512   key sequences and the same sequences typed manually by doing a
513   timed wait after each input character that could lead a function
514   key sequence. If the entire sequence takes less than 1 second, it
515   is assumed to have been generated by a function key press.</p>
516
517   <p>Hackers bruised by previous encounters with variant
518   <code>select(2)</code> calls may find the code in
519   <code>lib_twait.c</code> interesting. It deals with the problem
520   that some BSD selects do not return a reliable time-left value.
521   The function <code>timed_wait()</code> effectively simulates a
522   System V select.</p>
523
524   <h3><a name="mouse" id="mouse">Mouse Events</a></h3>
525
526   <p>If the mouse interface is active, <code>wgetch()</code> polls
527   for mouse events each call, before it goes to the keyboard for
528   input. It is up to <code>lib_mouse.c</code> how the polling is
529   accomplished; it may vary for different devices.</p>
530
531   <p>Under xterm, however, mouse event notifications come in via
532   the keyboard input stream. They are recognized by having the
533   <strong>kmous</strong> capability as a prefix. This is kind of
534   klugey, but trying to wire in recognition of a mouse key prefix
535   without going through the function-key machinery would be just
536   too painful, and this turns out to imply having the prefix
537   somewhere in the function-key capabilities at terminal-type
538   initialization.</p>
539
540   <p>This kluge only works because <strong>kmous</strong> is not
541   actually used by any historic terminal type or curses
542   implementation we know of. Best guess is it is a relic of some
543   forgotten experiment in-house at Bell Labs that did not leave any
544   traces in the publicly-distributed System V terminfo files. If
545   System V or XPG4 ever gets serious about using it again, this
546   kluge may have to change.</p>
547
548   <p>Here are some more details about mouse event handling:</p>
549
550   <p>The <code>lib_mouse()</code>code is logically split into a
551   lower level that accepts event reports in a device-dependent
552   format and an upper level that parses mouse gestures and filters
553   events. The mediating data structure is a circular queue of event
554   structures.</p>
555
556   <p>Functionally, the lower level's job is to pick up primitive
557   events and put them on the circular queue. This can happen in one
558   of two ways: either (a) <code>_nc_mouse_event()</code> detects a
559   series of incoming mouse reports and queues them, or (b) code in
560   <code>lib_getch.c</code> detects the <strong>kmous</strong>
561   prefix in the keyboard input stream and calls _nc_mouse_inline to
562   queue up a series of adjacent mouse reports.</p>
563
564   <p>In either case, <code>_nc_mouse_parse()</code> should be
565   called after the series is accepted to parse the digested mouse
566   reports (low-level events) into a gesture (a high-level or
567   composite event).</p>
568
569   <h3><a name="output" id="output">Output and Screen
570   Updating</a></h3>
571
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>
576
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>
581
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
586   this:</p>
587
588   <p>The <code>hashmap.c</code> module tries to detect vertical
589   motion changes between the real and virtual screens. This
590   information is represented by the oldindex members in the newscr
591   structure. These are modified by vertical-motion and clear
592   operations, and both are re-initialized after each update. To
593   this change-journalling information, the hashmap code adds
594   deductions made using a modified Heckel algorithm on hash values
595   generated from the line contents.</p>
596
597   <p>The <code>hardscroll.c</code> module computes an optimum set
598   of scroll, insertion, and deletion operations to make the indices
599   match. It calls <code>_nc_mvcur_scrolln()</code> in
600   <code>lib_mvcur.c</code> to do those motions.</p>
601
602   <p>Then <code>lib_doupdate.c</code> goes to work. Its job is to
603   do line-by-line transformations of <code>curscr</code> lines to
604   <code>newscr</code> lines. Its main tool is the routine
605   <code>mvcur()</code> in <code>lib_mvcur.c</code>. This routine
606   does cursor-movement optimization, attempting to get from given
607   screen location A to given location B in the fewest output
608   characters possible.</p>
609
610   <p>If you want to work on screen optimizations, you should use
611   the fact that (in the trace-enabled version of the library)
612   enabling the <code>TRACE_TIMES</code> trace level causes a report
613   to be emitted after each screen update giving the elapsed time
614   and a count of characters emitted during the update. You can use
615   this to tell when an update optimization improves efficiency.</p>
616
617   <p>In the trace-enabled version of the library, it is also
618   possible to disable and re-enable various optimizations at
619   runtime by tweaking the variable
620   <code>_nc_optimize_enable</code>. See the file
621   <code>include/curses.h.in</code> for mask values, near the
622   end.</p>
623
624   <h1><a name="fmnote" id="fmnote">The Forms and Menu
625   Libraries</a></h1>
626
627   <p>The forms and menu libraries should work reliably in any
628   environment you can port ncurses to. The only portability issue
629   anywhere in them is what flavor of regular expressions the
630   built-in form field type TYPE_REGEXP will recognize.</p>
631
632   <p>The configuration code prefers the POSIX regex facility,
633   modeled on System V's, but will settle for BSD regexps if the
634   former is not available.</p>
635
636   <p>Historical note: the panels code was written primarily to
637   assist in porting u386mon 2.0 (comp.sources.misc v14i001-4) to
638   systems lacking panels support; u386mon 2.10 and beyond use it.
639   This version has been slightly cleaned up for
640   <code>ncurses</code>.</p>
641
642   <h1><a name="tic" id="tic">A Tour of the Terminfo
643   Compiler</a></h1>
644
645   <p>The <strong>ncurses</strong> implementation of
646   <strong>tic</strong> is rather complex internally; it has to do a
647   trying combination of missions. This starts with the fact that,
648   in addition to its normal duty of compiling terminfo sources into
649   loadable terminfo binaries, it has to be able to handle termcap
650   syntax and compile that too into terminfo entries.</p>
651
652   <p>The implementation therefore starts with a table-driven,
653   dual-mode lexical analyzer (in <code>comp_scan.c</code>). The
654   lexer chooses its mode (termcap or terminfo) based on the first
655   &ldquo;,&rdquo; or &ldquo;:&rdquo; it finds in each entry. The
656   lexer does all the work of recognizing capability names and
657   values; the grammar above it is trivial, just "parse entries till
658   you run out of file".</p>
659
660   <h2><a name="nonuse" id="nonuse">Translation of
661   Non-<strong>use</strong> Capabilities</a></h2>
662
663   <p>Translation of most things besides <strong>use</strong>
664   capabilities is pretty straightforward. The lexical analyzer's
665   tokenizer hands each capability name to a hash function, which
666   drives a table lookup. The table entry yields an index which is
667   used to look up the token type in another table, and controls
668   interpretation of the value.</p>
669
670   <p>One possibly interesting aspect of the implementation is the
671   way the compiler tables are initialized. All the tables are
672   generated by various awk/sed/sh scripts from a master table
673   <code>include/Caps</code>; these scripts actually write C
674   initializers which are linked to the compiler. Furthermore, the
675   hash table is generated in the same way, so it doesn't have to be
676   generated at compiler startup time (another benefit of this
677   organization is that the hash table can be in shareable text
678   space).</p>
679
680   <p>Thus, adding a new capability is usually pretty trivial, just
681   a matter of adding one line to the <code>include/Caps</code>
682   file. We will have more to say about this in the section on
683   <a href="#translation">Source-Form Translation</a>.</p>
684
685   <h2><a name="uses" id="uses">Use Capability Resolution</a></h2>
686
687   <p>The background problem that makes <strong>tic</strong> tricky
688   is not the capability translation itself, it is the resolution of
689   <strong>use</strong> capabilities. Older versions would not
690   handle forward <strong>use</strong> references for this reason
691   (that is, a using terminal always had to follow its use target in
692   the source file). By doing this, they got away with a simple
693   implementation tactic; compile everything as it blows by, then
694   resolve uses from compiled entries.</p>
695
696   <p>This will not do for <strong>ncurses</strong>. The problem is
697   that that the whole compilation process has to be embeddable in
698   the <strong>ncurses</strong> library so that it can be called by
699   the startup code to translate termcap entries on the fly. The
700   embedded version cannot go promiscuously writing everything it
701   translates out to disk &mdash; for one thing, it will typically
702   be running with non-root permissions.</p>
703
704   <p>So our <strong>tic</strong> is designed to parse an entire
705   terminfo file into a doubly-linked circular list of entry
706   structures in-core, and then do <strong>use</strong> resolution
707   in-memory before writing everything out. This design has other
708   advantages: it makes forward and back use-references equally easy
709   (so we get the latter for free), and it makes checking for name
710   collisions before they are written out easy to do.</p>
711
712   <p>And this is exactly how the embedded version works. But the
713   stand-alone user-accessible version of <strong>tic</strong>
714   partly reverts to the historical strategy; it writes to disk (not
715   keeping in core) any entry with no <strong>use</strong>
716   references.</p>
717
718   <p>This is strictly a core-economy kluge, implemented because the
719   terminfo master file is large enough that some core-poor systems
720   swap like crazy when you compile it all in memory...there have
721   been reports of this process taking <strong>three hours</strong>,
722   rather than the twenty seconds or less typical on the author's
723   development box.</p>
724
725   <p>So. The executable <strong>tic</strong> passes the
726   entry-parser a hook that <em>immediately</em> writes out the
727   referenced entry if it has no use capabilities. The compiler main
728   loop refrains from adding the entry to the in-core list when this
729   hook fires. If some other entry later needs to reference an entry
730   that got written immediately, that is OK; the resolution code
731   will fetch it off disk when it cannot find it in core.</p>
732
733   <p>Name collisions will still be detected, just not as cleanly.
734   The <code>write_entry()</code> code complains before overwriting
735   an entry that postdates the time of <strong>tic</strong>'s first
736   call to <code>write_entry()</code>, Thus it will complain about
737   overwriting entries newly made during the <strong>tic</strong>
738   run, but not about overwriting ones that predate it.</p>
739
740   <h2><a name="translation" id="translation">Source-Form
741   Translation</a></h2>
742
743   <p>Another use of <strong>tic</strong> is to do source
744   translation between various termcap and terminfo formats. There
745   are more variants out there than you might think; the ones we
746   know about are described in the <strong>captoinfo(1)</strong>
747   manual page.</p>
748
749   <p>The translation output code (<code>dump_entry()</code> in
750   <code>ncurses/dump_entry.c</code>) is shared with the
751   <strong>infocmp(1)</strong> utility. It takes the same internal
752   representation used to generate the binary form and dumps it to
753   standard output in a specified format.</p>
754
755   <p>The <code>include/Caps</code> file has a header comment
756   describing ways you can specify source translations for
757   nonstandard capabilities just by altering the master table. It is
758   possible to set up capability aliasing or tell the compiler to
759   plain ignore a given capability without writing any C code at
760   all.</p>
761
762   <p>For circumstances where you need to do algorithmic
763   translation, there are functions in <code>parse_entry.c</code>
764   called after the parse of each entry that are specifically
765   intended to encapsulate such translations. This, for example, is
766   where the AIX <strong>box1</strong> capability get translated to
767   an <strong>acsc</strong> string.</p>
768
769   <h1><a name="utils" id="utils">Other Utilities</a></h1>
770
771   <p>The <strong>infocmp</strong> utility is just a wrapper around
772   the same entry-dumping code used by <strong>tic</strong> for
773   source translation. Perhaps the one interesting aspect of the
774   code is the use of a predicate function passed in to
775   <code>dump_entry()</code> to control which capabilities are
776   dumped. This is necessary in order to handle both the ordinary
777   De-compilation case and entry difference reporting.</p>
778
779   <p>The <strong>tput</strong> and <strong>clear</strong> utilities
780   just do an entry load followed by a <code>tputs()</code> of a
781   selected capability.</p>
782
783   <h1><a name="style" id="style">Style Tips for Developers</a></h1>
784
785   <p>See the TO-DO file in the top-level directory of the source
786   distribution for additions that would be particularly useful.</p>
787
788   <p>The prefix <code>_nc_</code> should be used on library public
789   functions that are not part of the curses API in order to prevent
790   pollution of the application namespace. If you have to add to or
791   modify the function prototypes in curses.h.in, read
792   ncurses/MKlib_gen.sh first so you can avoid breaking XSI
793   conformance. Please join the ncurses mailing list. See the
794   INSTALL file in the top level of the distribution for details on
795   the list.</p>
796
797   <p>Look for the string <code>FIXME</code> in source files to tag
798   minor bugs and potential problems that could use fixing.</p>
799
800   <p>Do not try to auto-detect OS features in the main body of the
801   C code. That is the job of the configuration system.</p>
802
803   <p>To hold down complexity, do make your code data-driven.
804   Especially, if you can drive logic from a table filtered out of
805   <code>include/Caps</code>, do it. If you find you need to augment
806   the data in that file in order to generate the proper table, that
807   is still preferable to ad-hoc code &mdash; that is why the fifth
808   field (flags) is there.</p>
809
810   <p>Have fun!</p>
811
812   <h1><a name="port" id="port">Porting Hints</a></h1>
813
814   <p>The following notes are intended to be a first step towards
815   DOS and Macintosh ports of the ncurses libraries.</p>
816
817   <p>The following library modules are &ldquo;pure curses&rdquo;;
818   they operate only on the curses internal structures, do all
819   output through other curses calls (not including
820   <code>tputs()</code> and <code>putp()</code>) and do not call any
821   other UNIX routines such as signal(2) or the stdio library. Thus,
822   they should not need to be modified for single-terminal
823   ports.</p>
824
825   <blockquote>
826     <code>lib_addch.c lib_addstr.c lib_bkgd.c lib_box.c lib_clear.c
827     lib_clrbot.c lib_clreol.c lib_delch.c lib_delwin.c lib_erase.c
828     lib_inchstr.c lib_insch.c lib_insdel.c lib_insstr.c
829     lib_keyname.c lib_move.c lib_mvwin.c lib_newwin.c lib_overlay.c
830     lib_pad.c lib_printw.c lib_refresh.c lib_scanw.c lib_scroll.c
831     lib_scrreg.c lib_set_term.c lib_touch.c lib_tparm.c lib_tputs.c
832     lib_unctrl.c lib_window.c panel.c</code>
833   </blockquote>
834
835   <p>This module is pure curses, but calls outstr():</p>
836
837   <blockquote>
838     <code>lib_getstr.c</code>
839   </blockquote>
840
841   <p>These modules are pure curses, except that they use
842   <code>tputs()</code> and <code>putp()</code>:</p>
843
844   <blockquote>
845     <code>lib_beep.c lib_color.c lib_endwin.c lib_options.c
846     lib_slk.c lib_vidattr.c</code>
847   </blockquote>
848
849   <p>This modules assist in POSIX emulation on non-POSIX
850   systems:</p>
851
852   <dl>
853     <dt>sigaction.c</dt>
854
855     <dd>signal calls</dd>
856   </dl>
857
858   <p>The following source files will not be needed for a
859   single-terminal-type port.</p>
860
861   <blockquote>
862     <code>alloc_entry.c captoinfo.c clear.c comp_captab.c
863     comp_error.c comp_hash.c comp_main.c comp_parse.c comp_scan.c
864     dump_entry.c infocmp.c parse_entry.c read_entry.c tput.c
865     write_entry.c</code>
866   </blockquote>
867
868   <p>The following modules will use
869   open()/read()/write()/close()/lseek() on files, but no other OS
870   calls.</p>
871
872   <dl>
873     <dt>lib_screen.c</dt>
874
875     <dd>used to read/write screen dumps</dd>
876
877     <dt>lib_trace.c</dt>
878
879     <dd>used to write trace data to the logfile</dd>
880   </dl>
881
882   <p>Modules that would have to be modified for a port start
883   here:</p>
884
885   <p>The following modules are &ldquo;pure curses&rdquo; but
886   contain assumptions inappropriate for a memory-mapped port.</p>
887
888   <dl>
889     <dt>lib_longname.c</dt>
890
891     <dd>assumes there may be multiple terminals</dd>
892
893     <dt>lib_acs.c</dt>
894
895     <dd>assumes acs_map as a double indirection</dd>
896
897     <dt>lib_mvcur.c</dt>
898
899     <dd>assumes cursor moves have variable cost</dd>
900
901     <dt>lib_termcap.c</dt>
902
903     <dd>assumes there may be multiple terminals</dd>
904
905     <dt>lib_ti.c</dt>
906
907     <dd>assumes there may be multiple terminals</dd>
908   </dl>
909
910   <p>The following modules use UNIX-specific calls:</p>
911
912   <dl>
913     <dt>lib_doupdate.c</dt>
914
915     <dd>input checking</dd>
916
917     <dt>lib_getch.c</dt>
918
919     <dd>read()</dd>
920
921     <dt>lib_initscr.c</dt>
922
923     <dd>getenv()</dd>
924
925     <dt>lib_newterm.c</dt>
926
927     <dt>lib_baudrate.c</dt>
928
929     <dt>lib_kernel.c</dt>
930
931     <dd>various tty-manipulation and system calls</dd>
932
933     <dt>lib_raw.c</dt>
934
935     <dd>various tty-manipulation calls</dd>
936
937     <dt>lib_setup.c</dt>
938
939     <dd>various tty-manipulation calls</dd>
940
941     <dt>lib_restart.c</dt>
942
943     <dd>various tty-manipulation calls</dd>
944
945     <dt>lib_tstp.c</dt>
946
947     <dd>signal-manipulation calls</dd>
948
949     <dt>lib_twait.c</dt>
950
951     <dd>gettimeofday(), select().</dd>
952   </dl>
953   <hr>
954
955   <address>
956     Eric S. Raymond &lt;esr@snark.thyrsus.com&gt;
957   </address>(Note: This is <em>not</em> the <a href="#bugtrack">bug
958   address</a>!)
959 </body>
960 </html>