xref: /freebsd/contrib/ncurses/doc/html/hackguide.html (revision af23369a6deaaeb612ab266eb88b8bb8d560c322)
1<!--
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.                  *
6  *                                                                          *
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:                 *
14  *                                                                          *
15  * The above copyright notice and this permission notice shall be included  *
16  * in all copies or substantial portions of the Software.                   *
17  *                                                                          *
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.                               *
25  *                                                                          *
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       *
29  * authorization.                                                           *
30  ****************************************************************************
31-->
32<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
33
34<html>
35<head>
36  <meta name="generator" content=
37  "HTML Tidy for HTML5 for Linux version 5.2.0">
38
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"><!--
43This document is self-contained, *except* that there is one relative link to
44the ncurses-intro.html document, expected to be in the same directory with
45this one.
46-->
47</head>
48
49<body>
50  <h1>A Hacker's Guide to NCURSES</h1>
51
52  <h1>Contents</h1>
53
54  <ul>
55    <li><a href="#abstract">Abstract</a></li>
56
57    <li>
58      <a href="#objective">Objective of the Package</a>
59
60      <ul>
61        <li><a href="#whysvr4">Why System V Curses?</a></li>
62
63        <li><a href="#extensions">How to Design Extensions</a></li>
64      </ul>
65    </li>
66
67    <li><a href="#portability">Portability and 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>
237    </li>
238  </ol>
239
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
242  document).</p>
243
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>
251
252  <h1><a name="bugtrack" id="bugtrack">How to Report Bugs</a></h1>
253
254  <p>The <a name="bugreport" id="bugreport">reporting address for
255  bugs</a> is <a href=
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>
260
261  <pre>
262             subscribe &lt;name&gt;@&lt;host.domain&gt;
263</pre>
264
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>
272
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>
277
278  <ol>
279    <li>Develop a recipe to reproduce the bug.
280
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 &mdash; 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>
288    </li>
289
290    <li>Try to reproduce the bug on a different terminal type.
291
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
297      entry.</p>
298
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
303      on both.</p>
304
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 &mdash;
308      a surprising number of the bugs we have seen are either
309      triggered or masked by these.</p>
310    </li>
311
312    <li>Generate and examine a trace file for the broken behavior.
313
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
320      actually doing.</p>
321
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
328      ours.</p>
329
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>
336
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>
342    </li>
343
344    <li>Report details and symptoms, not just interpretations.
345
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
351      yourself.</p>
352
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>
356
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>
363
364      <p>If your bug produces a core-dump, please include a
365      symbolic stack trace generated by gdb(1) or your local
366      equivalent.</p>
367
368      <p>Tell us about every terminal on which you have reproduced
369      the bug &mdash; and every terminal on which you cannot.
370      Ideally, send us terminfo sources for all of these (yours
371      might differ from ours).</p>
372
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>
376    </li>
377  </ol>
378
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>
384
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>
392
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>
399
400  <h1><a name="ncurslib" id="ncurslib">A Tour of the Ncurses
401  Library</a></h1>
402
403  <h2><a name="loverview" id="loverview">Library Overview</a></h2>
404
405  <p>Most of the library is superstructure &mdash; 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>
410
411  <blockquote>
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
425    lib_window.c</code>
426  </blockquote>
427
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>
431
432  <p>These files are used only for debugging support:</p>
433
434  <blockquote>
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>
437  </blockquote>
438
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
441  reason.</p>
442
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>
447
448  <blockquote>
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
452    read_entry.c.</code>
453  </blockquote>
454
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>
458
459  <p>These files have serious hooks into the tty driver and signal
460  facilities:</p>
461
462  <blockquote>
463    <code>lib_kernel.c lib_baudrate.c lib_raw.c lib_tstp.c
464    lib_twait.c</code>
465  </blockquote>
466
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
470  category.</p>
471
472  <p>Almost all of the real work is done in the files</p>
473
474  <blockquote>
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
477    lib_vidattr.c</code>
478  </blockquote>
479
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>
484
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>
489
490  <blockquote>
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>
494  </blockquote>
495
496  <p>We will discuss these in the compiler tour.</p>
497
498  <h2><a name="engine" id="engine">The Engine Room</a></h2>
499
500  <h3><a name="input" id="input">Keyboard Input</a></h3>
501
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>
507
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>
512
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>
518
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
524  System V select.</p>
525
526  <h3><a name="mouse" id="mouse">Mouse Events</a></h3>
527
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>
532
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
540  initialization.</p>
541
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>
549
550  <p>Here are some more details about mouse event handling:</p>
551
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
556  structures.</p>
557
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>
565
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>
570
571  <h3><a name="output" id="output">Output and Screen Updating</a></h3>
572
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>
577
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>
582
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
587  this:</p>
588
589  <ul>
590    <li>
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>
599    </li>
600
601    <li>
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>
606    </li>
607
608    <li>
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>
616    </li>
617  </ul>
618
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>
625
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
631  end.</p>
632
633  <h1><a name="fmnote" id="fmnote">The Forms and Menu Libraries</a></h1>
634
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>
639
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>
643
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>
649
650  <h1><a name="tic" id="tic">A Tour of the Terminfo Compiler</a></h1>
651
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>
658
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  &ldquo;,&rdquo; or &ldquo;:&rdquo; 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>
666
667  <h2><a name="nonuse" id="nonuse">Translation of
668  Non-<strong>use</strong> Capabilities</a></h2>
669
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>
676
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
685  space).</p>
686
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>
691
692  <h2><a name="uses" id="uses">Use Capability Resolution</a></h2>
693
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>
702
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 &mdash; for one thing, it will typically
709  be running with non-root permissions.</p>
710
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>
718
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>
723  references.</p>
724
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
730  development box.</p>
731
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>
739
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>
746
747  <h2><a name="translation" id="translation">Source-Form
748  Translation</a></h2>
749
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>
754  manual page.</p>
755
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>
761
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
767  all.</p>
768
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>
775
776  <h1><a name="utils" id="utils">Other Utilities</a></h1>
777
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>
785
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>
789
790  <h1><a name="style" id="style">Style Tips for Developers</a></h1>
791
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>
794
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
802  the list.</p>
803
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>
806
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>
809
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 &mdash; that is why the fifth
815  field (flags) is there.</p>
816
817  <p>Have fun!</p>
818
819  <h1><a name="port" id="port">Porting Hints</a></h1>
820
821  <p>The following notes are intended to be a first step towards
822  DOS and Macintosh ports of the ncurses libraries.</p>
823
824  <p>The following library modules are &ldquo;pure curses&rdquo;;
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
830  ports.</p>
831
832  <blockquote>
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>
840  </blockquote>
841
842  <p>This module is pure curses, but calls outstr():</p>
843
844  <blockquote>
845    <code>lib_getstr.c</code>
846  </blockquote>
847
848  <p>These modules are pure curses, except that they use
849  <code>tputs()</code> and <code>putp()</code>:</p>
850
851  <blockquote>
852    <code>lib_beep.c lib_color.c lib_endwin.c lib_options.c
853    lib_slk.c lib_vidattr.c</code>
854  </blockquote>
855
856  <p>This modules assist in POSIX emulation on non-POSIX
857  systems:</p>
858
859  <dl>
860    <dt>sigaction.c</dt>
861
862    <dd>signal calls</dd>
863  </dl>
864
865  <p>The following source files will not be needed for a
866  single-terminal-type port.</p>
867
868  <blockquote>
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
872    write_entry.c</code>
873  </blockquote>
874
875  <p>The following modules will use
876  open()/read()/write()/close()/lseek() on files, but no other OS
877  calls.</p>
878
879  <dl>
880    <dt>lib_screen.c</dt>
881
882    <dd>used to read/write screen dumps</dd>
883
884    <dt>lib_trace.c</dt>
885
886    <dd>used to write trace data to the logfile</dd>
887  </dl>
888
889  <p>Modules that would have to be modified for a port start
890  here:</p>
891
892  <p>The following modules are &ldquo;pure curses&rdquo; but
893  contain assumptions inappropriate for a memory-mapped port.</p>
894
895  <dl>
896    <dt>lib_longname.c</dt>
897
898    <dd>assumes there may be multiple terminals</dd>
899
900    <dt>lib_acs.c</dt>
901
902    <dd>assumes acs_map as a double indirection</dd>
903
904    <dt>lib_mvcur.c</dt>
905
906    <dd>assumes cursor moves have variable cost</dd>
907
908    <dt>lib_termcap.c</dt>
909
910    <dd>assumes there may be multiple terminals</dd>
911
912    <dt>lib_ti.c</dt>
913
914    <dd>assumes there may be multiple terminals</dd>
915  </dl>
916
917  <p>The following modules use UNIX-specific calls:</p>
918
919  <dl>
920    <dt>lib_doupdate.c</dt>
921
922    <dd>input checking</dd>
923
924    <dt>lib_getch.c</dt>
925
926    <dd>read()</dd>
927
928    <dt>lib_initscr.c</dt>
929
930    <dd>getenv()</dd>
931
932    <dt>lib_newterm.c</dt>
933
934    <dt>lib_baudrate.c</dt>
935
936    <dt>lib_kernel.c</dt>
937
938    <dd>various tty-manipulation and system calls</dd>
939
940    <dt>lib_raw.c</dt>
941
942    <dd>various tty-manipulation calls</dd>
943
944    <dt>lib_setup.c</dt>
945
946    <dd>various tty-manipulation calls</dd>
947
948    <dt>lib_restart.c</dt>
949
950    <dd>various tty-manipulation calls</dd>
951
952    <dt>lib_tstp.c</dt>
953
954    <dd>signal-manipulation calls</dd>
955
956    <dt>lib_twait.c</dt>
957
958    <dd>gettimeofday(), select().</dd>
959  </dl>
960
961  <hr>
962
963  <address>
964    Eric S. Raymond &lt;esr@snark.thyrsus.com&gt;
965  </address>
966  (Note: This is <em>not</em> the <a href="#bugtrack">bug
967  address</a>!)
968</body>
969</html>
970