]> ncurses.scripts.mit.edu Git - ncurses.git/blob - misc/hackguide.html
ncurses 4.2
[ncurses.git] / misc / hackguide.html
1 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
2 <!--
3   $Id: hackguide.html,v 1.17 1998/02/15 01:32:35 tom Exp $
4 -->
5 <HTML>
6 <HEAD>
7 <TITLE>A Hacker's Guide to Ncurses Internals</TITLE>
8 <link rev="made" href="mailto:esr@snark.thyrsus.com">
9 <!--
10 This document is self-contained, *except* that there is one relative link to 
11 the ncurses-intro.html document, expected to be in the same directory with
12 this one.
13 -->
14 </HEAD>
15 <BODY>
16
17 <H1>A Hacker's Guide to NCURSES</H1>
18
19 <H1>Contents</H1>
20 <UL>
21 <LI><A HREF="#abstract">Abstract</A>
22 <P>
23 <LI><A HREF="#objective">Objective of the Package</A>
24 <UL>
25 <LI><A HREF="#whysvr4">Why System V Curses?</A>
26 <LI><A HREF="#extensions">How to Design Extensions</A>
27 </UL>
28 <LI><A HREF="#portability">Portability and Configuration</A><UL>
29 <LI><A HREF="#fooup">If autoconf Fails</A>
30 </UL>
31 <LI><A HREF="#documentation">Documentation Conventions</A>
32 <P>
33 <LI><A HREF="#bugtrack">How to Report Bugs</A>
34 <P>
35 <LI><A HREF="#ncurslib">A Tour of the Ncurses Library</A>
36 <UL>
37 <LI><A HREF="#loverview">Library Overview</A>
38 <LI><A HREF="#engine">The Engine Room</A>
39 <LI><A HREF="#input">Keyboard Input</A>
40 <LI><A HREF="#mouse">Mouse Events</A>
41 <LI><A HREF="#output">Output and Screen Updating</A>
42 </UL>
43 <LI><A HREF="#fmnote">The Forms and Menu Libraries</A>
44 <P>
45 <LI><A HREF="#tic">A Tour of the Terminfo Compiler</A>
46 <UL>
47 <LI><A HREF="#nonuse">Translation of Non-<STRONG>use</STRONG> Capabilities</A>
48 <LI><A HREF="#uses">Use Capability Resolution</A>
49 <LI><A HREF="#translation">Source-Form Translation</A>
50 </UL>
51 <LI><A HREF="#utils">Other Utilities</A>
52 <P>
53 <LI><A HREF="#style">Style Tips for Developers</A>
54 <P>
55 <LI><A HREF="#port">Porting Hints</A>
56 </UL>
57
58 <H1><A NAME="abstract">Abstract</A></H1>
59
60 This document is a hacker's tour of the <STRONG>ncurses</STRONG> library and utilities.
61 It discusses design philosophy, implementation methods, and the
62 conventions used for coding and documentation.  It is recommended
63 reading for anyone who is interested in porting, extending or improving the
64 package. <P>
65
66 <H1><A NAME="objective">Objective of the Package</A></H1>
67
68 The objective of the <STRONG>ncurses</STRONG> package is to provide a freeware API for
69 character-cell terminals and terminal emulators with the following 
70 characteristics: <P>
71
72 <UL>
73 <LI>Source-compatible with historical curses implementations (including
74      the original BSD curses and System V curses.
75 <P>
76 <LI>Conformant with the XSI Curses standard issued as part of XPG4 by
77      X/Open. 
78 <P>
79 <LI>High-quality -- stable and reliable code, wide portability, good
80      packaging, superior documentation.
81 <P>
82 <LI>Featureful -- should eliminate as much of the drudgery of C interface
83      programming as possible, freeing programmers to think at a higher
84      level of design.
85 </UL>
86
87 These objectives are in priority order.  So, for example, source
88 compatibility with older version must trump featurefulness -- we cannot
89 add features if it means breaking the portion of the API corresponding
90 to historical curses versions. <P>
91
92 <H2><A NAME="whysvr4">Why System V Curses?</A></H2>
93
94 We used System V curses as a model, reverse-engineering their API, in
95 order to fulfill the first two objectives. <P>
96
97 System V curses implementations can support BSD curses programs with
98 just a recompilation, so by capturing the System V API we also
99 capture BSD's. <P>
100
101 More importantly for the future, the XSI Curses standard issued by X/Open
102 is explicitly and closely modeled on System V.  So conformance with
103 System V took us most of the way to base-level XSI conformance. <P>
104
105 <H2><A NAME="extensions">How to Design Extensions</A></H2>
106
107 The third objective (standards conformance) requires that it be easy to
108 condition source code using <STRONG>ncurses</STRONG> so that the absence of nonstandard
109 extensions does not break the code. <P>
110
111 Accordingly, we have a policy of associating with each nonstandard extension
112 a feature macro, so that ncurses client code can use this macro to condition
113 in or out the code that requires the <STRONG>ncurses</STRONG> extension. <P>
114
115 For example, there is a macro <CODE>NCURSES_MOUSE_VERSION</CODE> which XSI Curses
116 does not define, but which is defined in the <STRONG>ncurses</STRONG> library header.
117 You can use this to condition the calls to the mouse API calls. <P>
118
119 <H1><A NAME="portability">Portability and Configuration</A></H1>
120
121 Code written for <STRONG>ncurses</STRONG> may assume an ANSI-standard C compiler and
122 POSIX-compatible OS interface.  It may also assume the presence of a
123 System-V-compatible <EM>select(2)</EM> call. <P>
124
125 We encourage (but do not require) developers to make the code friendly
126 to less-capable UNIX environments wherever possible. <P>
127
128 We encourage developers to support OS-specific optimizations and methods
129 not available under POSIX/ANSI, provided only that:  <P>
130
131 <UL>
132 <LI>All such code is properly conditioned so the build process does not
133      attempt to compile it under a plain ANSI/POSIX environment.
134 <P>
135 <LI>Adding such implementation methods does not introduce incompatibilities
136      in the <STRONG>ncurses</STRONG> API between platforms.
137 </UL>
138
139 We use GNU <CODE>autoconf(1)</CODE> as a tool to deal with portability issues.  
140 The right way to leverage an OS-specific feature is to modify the autoconf
141 specification files (configure.in and aclocal.m4) to set up a new feature
142 macro, which you then use to condition your code. <P>
143
144 <H2><A NAME="fooup">If autoconf Fails</A></H2>
145
146 The 'configure' script usually gets your system environment right
147 automatically.  Here are some -D options you might need to compile
148 with if it fails: <P>
149 <DL>
150 <DT>-DHAVE_UNISTD_H
151 <DD>if &lt;unistd.h&gt; is present
152 <DT>-DHAVE_SIGACTION
153 <DD>if the sigaction function is present 
154 <DT>-DHAVE_USLEEP
155 <DD>if the usleep function is present
156 <DT>-DSVR4_ACTION
157 <DD>if (e.g., svr4) you need _POSIX_SOURCE to have sigaction
158 <DT>-DHAVE_TERMIOS_H
159 <DD>if you have &lt;termios.h&gt;
160 <DT>-DHAVE_TERMIO_H
161 <DD>if you have &lt;termio.h&gt;; otherwise it uses &lt;sgtty.h&gt;
162 <DT>-DBROKEN_TIOCGETWINSZ
163 <DD>on SVR4 and HPUX, the get window size ioctl is broken.
164 </DL>
165
166 <H1><A NAME="documentation">Documentation Conventions</A></H1>
167
168 There are three kinds of documentation associated with this package.  Each
169 has a different preferred format: <P>
170
171 <UL>
172 <LI>Package-internal files (README, INSTALL, TO-DO etc.)
173 <LI>Manual pages.
174 <LI>Everything else (i.e., narrative documentation).
175 </UL>
176
177 Our conventions are simple: <P>
178 <OL>
179 <LI><STRONG>Maintain package-internal files in plain text.</STRONG>
180      The expected viewer for them <EM>more(1)</EM> or an editor window; there's
181      no point in elaborate mark-up. <P>
182
183 <LI><STRONG>Mark up manual pages in the man macros.</STRONG>  These have to be viewable
184      through traditional <EM>man(1)</EM> programs. <P>
185
186 <LI><STRONG>Write everything else in HTML.</STRONG>
187 </OL>
188
189 When in doubt, HTMLize a master and use <EM>lynx(1)</EM> to generate
190 plain ASCII (as we do for the announcement document). <P>
191
192 The reason for choosing HTML is that it's (a) well-adapted for on-line
193 browsing through viewers that are everywhere; (b) more easily readable
194 as plain text than most other mark-ups, if you don't have a viewer; and (c)
195 carries enough information that you can generate a nice-looking printed
196 version from it.  Also, of course, it make exporting things like the 
197 announcement document to WWW pretty trivial.<P>
198
199 <H1><A NAME="bugtrack">How to Report Bugs</A></H1>
200
201 The <A NAME="bugreport">reporting address for bugs</A> is
202 <A HREF="mailto:bug-ncurses@gnu.org">bug-ncurses@gnu.org</A>.
203 This is a majordomo list; to join, write
204 to <CODE>ncurses-request@gnu.org</CODE> with a message containing the line:
205 <PRE>
206              subscribe &lt;name&gt;@&lt;host.domain&gt;
207 </PRE>
208
209 The <CODE>ncurses</CODE> code is maintained by a small group of
210 volunteers.  While we try our best to fix bugs promptly, we simply
211 don't have a lot of hours to spend on elementary hand-holding.  We rely
212 on intelligent cooperation from our users.  If you think you have
213 found a bug in <CODE>ncurses</CODE>, there are some steps you can take 
214 before contacting us that will help get the bug fixed quickly. <P>
215
216 In order to use our bug-fixing time efficiently, we put people who
217 show us they've taken these steps at the head of our queue.  This
218 means that if you don't, you'll probably end up at the tail end and
219 have to wait a while. <P>
220
221 <OL>
222 <LI>Develop a recipe to reproduce the bug. <P>
223
224 Bugs we can reproduce are likely to be fixed very quickly, often
225 within days.  The most effective single thing you can do to get a
226 quick fix is develop a way we can duplicate the bad behavior --
227 ideally, by giving us source for a small, portable test program that
228 breaks the library. (Even better is a keystroke recipe using one of
229 the test programs provided with the distribution.) <P>
230
231 <LI>Try to reproduce the bug on a different terminal type. <P>
232
233 In our experience, most of the behaviors people report as library bugs
234 are actually due to subtle problems in terminal descriptions.  This is
235 especially likely to be true if you're using a traditional
236 asynchronous terminal or PC-based terminal emulator, rather than xterm
237 or a UNIX console entry. <P>
238
239 It's therefore extremely helpful if you can tell us whether or not your
240 problem reproduces on other terminal types.  Usually you'll have both
241 a console type and xterm available; please tell us whether or not your
242 bug reproduces on both. <P>
243
244 If you have xterm available, it is also good to collect xterm reports for 
245 different window sizes.  This is especially true if you normally use an
246 unusual xterm window size -- a surprising number of the bugs we've seen
247 are either triggered or masked by these.  <P>
248
249 <LI>Generate and examine a trace file for the broken behavior. <P>
250
251 Recompile your program with the debugging versions of the libraries.
252 Insert a <CODE>trace()</CODE> call with the argument set to <CODE>TRACE_UPDATE</CODE>.
253 (See <A HREF="ncurses-intro.html#debugging">"Writing Programs with
254 NCURSES"</A> for details on trace levels.)
255 Reproduce your bug, then look at the trace file to see what the library
256 was actually doing. <P>
257
258 Another frequent cause of apparent bugs is application coding errors
259 that cause the wrong things to be put on the virtual screen.  Looking
260 at the virtual-screen dumps in the trace file will tell you immediately if
261 this is happening, and save you from the possible embarrassment of being
262 told that the bug is in your code and is your problem rather than ours. <P>
263
264 If the virtual-screen dumps look correct but the bug persists, it's
265 possible to crank up the trace level to give more and more information
266 about the library's update actions and the control sequences it issues
267 to perform them.  The test directory of the distribution contains a
268 tool for digesting these logs to make them less tedious to wade
269 through. <P>
270
271 Often you'll find terminfo problems at this stage by noticing that the
272 escape sequences put out for various capabilities are wrong.  If not,
273 you're likely to learn enough to be able to characterize any bug in
274 the screen-update logic quite exactly. <P>
275
276 <LI>Report details and symptoms, not just interpretations. <P>
277
278 If you do the preceding two steps, it is very likely that you'll discover
279 the nature of the problem yourself and be able to send us a fix.  This
280 will create happy feelings all around and earn you good karma for the first
281 time you run into a bug you really can't characterize and fix yourself. <P>
282
283 If you're still stuck, at least you'll know what to tell us.  Remember, we
284 need details.  If you guess about what is safe to leave out, you are too
285 likely to be wrong. <P>
286
287 If your bug produces a bad update, include a trace file.  Try to make
288 the trace at the <EM>least</EM> voluminous level that pins down the
289 bug.  Logs that have been through tracemunch are OK, it doesn't throw
290 away any information (actually they're better than un-munched ones because
291 they're easier to read). <P>
292
293 If your bug produces a core-dump, please include a symbolic stack trace
294 generated by gdb(1) or your local equivalent. <P>
295
296 Tell us about every terminal on which you've reproduced the bug -- and
297 every terminal on which you can't.  Ideally, sent us terminfo sources
298 for all of these (yours might differ from ours). <P>
299
300 Include your ncurses version and your OS/machine type, of course!  You can
301 find your ncurses version in the <CODE>curses.h</CODE> file.
302 </OL>
303
304 If your problem smells like a logic error or in cursor movement or
305 scrolling or a bad capability, there are a couple of tiny test frames
306 for the library algorithms in the progs directory that may help you
307 isolate it.  These are not part of the normal build, but do have their
308 own make productions.  <P>
309
310 The most important of these is <CODE>mvcur</CODE>, a test frame for the
311 cursor-movement optimization code.  With this program, you can see
312 directly what control sequences will be emitted for any given cursor
313 movement or scroll/insert/delete operations.  If you think you've got
314 a bad capability identified, you can disable it and test again. The
315 program is command-driven and has on-line help. <P>
316
317 If you think the vertical-scroll optimization is broken, or just want to
318 understand how it works better, build <CODE>hashmap</CODE> and read the
319 header comments of <CODE>hardscroll.c</CODE> and <CODE>hashmap.c</CODE>; then try
320 it out. You can also test the hardware-scrolling optimization separately
321 with <CODE>hardscroll</CODE>. <P>
322
323 There's one other interactive tester, <CODE>tctest</CODE>, that exercises
324 translation between termcap and terminfo formats.  If you have a serious
325 need to run this, you probably belong on our development team! <P>
326
327 <H1><A NAME="ncurslib">A Tour of the Ncurses Library</A></H1>
328
329 <H2><A NAME="loverview">Library Overview</A></H2>
330
331 Most of the library is superstructure -- fairly trivial convenience
332 interfaces to a small set of basic functions and data structures used
333 to manipulate the virtual screen (in particular, none of this code
334 does any I/O except through calls to more fundamental modules
335 described below).  The files <CODE>lib_addch.c</CODE>,
336 <CODE>lib_bkgnd.c</CODE>, <CODE>lib_box.c</CODE>, <CODE>lib_clear.c</CODE>,
337 <CODE>lib_clrbot.c</CODE>, <CODE>lib_clreol.c</CODE>, <CODE>lib_data.c</CODE>,
338 <CODE>lib_delch.c</CODE>, <CODE>lib_delwin.c</CODE>, <CODE>lib_erase.c</CODE>,
339 <CODE>lib_getstr.c</CODE>, <CODE>lib_inchstr.c</CODE>, <CODE>lib_insch.c</CODE>,
340 <CODE>lib_insdel.c</CODE>, <CODE>lib_insstr.c</CODE>, <CODE>lib_instr.c</CODE>,
341 <CODE>lib_isendwin.c</CODE>, <CODE>lib_keyname.c</CODE>, <CODE>lib_move.c</CODE>,
342 <CODE>lib_mvwin.c</CODE>, <CODE>lib_overlay.c</CODE>, <CODE>lib_pad.c</CODE>,
343 <CODE>lib_printw.c</CODE>, <CODE>lib_scanw.c</CODE>, <CODE>lib_screen.c</CODE>,
344 <CODE>lib_scroll.c</CODE>, <CODE>lib_scrreg.c</CODE>, <CODE>lib_set_term.c</CODE>,
345 <CODE>lib_slk.c</CODE>, <CODE>lib_touch.c</CODE>, <CODE>lib_unctrl.c</CODE>, and
346 <CODE>lib_window.c</CODE> are all in this category.  They are very
347 unlikely to need change, barring bugs or some fundamental
348 reorganization in the underlying data structures. <P>
349
350 The <CODE>lib_trace.c</CODE>, <CODE>lib_traceatr.c</CODE>, and
351 <CODE>lib_tracechr.c</CODE> file are used only for debugging support. 
352 It is rather unlikely you will ever need to change these, unless
353 you want to introduce a new debug trace level for some reasoon.<P>
354
355 There is another group of files that do direct I/O via <EM>tputs()</EM>,
356 computations on the terminal capabilities, or queries to the OS
357 environment, but nevertheless have only fairly low complexity.  These
358 include: <CODE>lib_acs.c</CODE>, <CODE>lib_beep.c</CODE>,
359 <CODE>lib_color.c</CODE>, <CODE>lib_endwin.c</CODE>, <CODE>lib_initscr.c</CODE>,
360 <CODE>lib_longname.c</CODE>, <CODE>lib_newterm.c</CODE>,
361 <CODE>lib_options.c</CODE>, <CODE>lib_termcap.c</CODE>, <CODE>lib_ti.c</CODE>,
362 <CODE>lib_tparm.c</CODE>, <CODE>lib_tputs.c</CODE>, <CODE>lib_vidattr.c</CODE>,
363 and <CODE>read_entry.c</CODE>.  These are likely to need revision only if
364 ncurses is being ported to an environment without an underlying
365 terminfo capability representation. <P>
366
367 The files <CODE>lib_kernel.c</CODE>, <CODE>lib_baudrate.c</CODE>, <CODE>lib_raw.c</CODE>,
368 <CODE>lib_tstp.c</CODE>, and <CODE>lib_twait.c</CODE> have serious hooks into
369 the tty driver and signal facilities.  If you run into porting snafus
370 moving the package to another UNIX, the problem is likely to be in one
371 of these files.  The file <CODE>lib_print.c</CODE> uses sleep(2) and also
372 falls in this category.<P>
373
374 Almost all of the real work is done in the files 
375 <CODE>hashmap.c</CODE>, <CODE>hardscroll.c</CODE>,
376 <CODE>lib_addch.c</CODE>, <CODE>lib_doupdate.c</CODE>, <CODE>lib_mvcur.c</CODE>,
377 <CODE>lib_getch.c</CODE>, <CODE>lib_mouse.c</CODE>, <CODE>lib_refresh.c</CODE>,
378 and <CODE>lib_setup.c</CODE>.  Most of the algorithmic complexity in the
379 library lives in these files.  If there is a real bug in <STRONG>ncurses</STRONG>
380 itself, it's probably here.  We'll tour some of these files in detail
381 below (see <A HREF="#engine">The Engine Room</A>). <P>
382
383 Finally, there is a group of files that is actually most of the
384 terminfo compiler.  The reason this code lives in the <STRONG>ncurses</STRONG>
385 library is to support fallback to /etc/termcap.  These files include
386 <CODE>alloc_entry.c</CODE>, <CODE>captoinfo.c</CODE>, <CODE>comp_captab.c</CODE>,
387 <CODE>comp_error.c</CODE>, <CODE>comp_hash.c</CODE>, <CODE>comp_parse.c</CODE>,
388 <CODE>comp_scan.c</CODE>, and <CODE>parse_entry.c</CODE>,
389 <CODE>read_termcap.c</CODE>, and <CODE>write_entry.c</CODE>.  We'll discuss these
390 in the compiler tour. <P>
391
392 <H2><A NAME="engine">The Engine Room</A></H2>
393
394 <H3><A NAME="input">Keyboard Input</A></H3>
395
396 All <CODE>ncurses</CODE> input funnels through the function
397 <CODE>wgetch()</CODE>, defined in <CODE>lib_getch.c</CODE>.  This function is
398 tricky; it has to poll for keyboard and mouse events and do a running
399 match of incoming input against the set of defined special keys. <P>
400
401 The central data structure in this module is a FIFO queue, used to
402 match multiple-character input sequences against special-key
403 capabilities; also to implement pushback via <CODE>ungetch()</CODE>. <P>
404
405 The <CODE>wgetch()</CODE> code distinguishes between function key
406 sequences and the same sequences typed manually by doing a timed wait
407 after each input character that could lead a function key sequence.
408 If the entire sequence takes less than 1 second, it is assumed to have
409 been generated by a function key press. <P>
410
411 Hackers bruised by previous encounters with variant <CODE>select(2)</CODE>
412 calls may find the code in <CODE>lib_twait.c</CODE> interesting.  It deals
413 with the problem that some BSD selects don't return a reliable
414 time-left value.  The function <CODE>timed_wait()</CODE> effectively
415 simulates a System V select. <P>
416
417 <H3><A NAME="mouse">Mouse Events</A></H3>
418
419 If the mouse interface is active, <CODE>wgetch()</CODE> polls for mouse
420 events each call, before it goes to the keyboard for input.  It is
421 up to <CODE>lib_mouse.c</CODE> how the polling is accomplished; it may vary
422 for different devices. <P>
423
424 Under xterm, however, mouse event notifications come in via the keyboard
425 input stream.  They are recognized by having the <STRONG>kmous</STRONG> capability
426 as a prefix.  This is kind of klugey, but trying to wire in recognition of
427 a mouse key prefix without going through the function-key machinery would
428 be just too painful, and this turns out to imply having the prefix somewhere
429 in the function-key capabilities at terminal-type initialization. <P>
430
431 This kluge only works because <STRONG>kmous</STRONG> isn't actually used by any
432 historic terminal type or curses implementation we know of.  Best
433 guess is it's a relic of some forgotten experiment in-house at Bell
434 Labs that didn't leave any traces in the publicly-distributed System V
435 terminfo files.  If System V or XPG4 ever gets serious about using it
436 again, this kluge may have to change. <P>
437
438 Here are some more details about mouse event handling: <P>
439
440 The <CODE>lib_mouse()</CODE>code is logically split into a lower level that
441 accepts event reports in a device-dependent format and an upper level that
442 parses mouse gestures and filters events.  The mediating data structure is a
443 circular queue of event structures. <P>
444
445 Functionally, the lower level's job is to pick up primitive events and
446 put them on the circular queue.  This can happen in one of two ways:
447 either (a) <CODE>_nc_mouse_event()</CODE> detects a series of incoming
448 mouse reports and queues them, or (b) code in <CODE>lib_getch.c</CODE> detects the
449 <STRONG>kmous</STRONG> prefix in the keyboard input stream and calls _nc_mouse_inline
450 to queue up a series of adjacent mouse reports. <P>
451
452 In either case, <CODE>_nc_mouse_parse()</CODE> should be called after the
453 series is accepted to parse the digested mouse reports (low-level
454 events) into a gesture (a high-level or composite event). <P>
455
456 <H3><A NAME="output">Output and Screen Updating</A></H3>
457
458 With the single exception of character echoes during a <CODE>wgetnstr()</CODE>
459 call (which simulates cooked-mode line editing in an ncurses window), 
460 the library normally does all its output at refresh time. <P>
461
462 The main job is to go from the current state of the screen (as represented
463 in the <CODE>curscr</CODE> window structure) to the desired new state (as 
464 represented in the <CODE>newscr</CODE> window structure), while doing as
465 little I/O as possible. <P>
466
467 The brains of this operation are the modules <CODE>hashmap.c</CODE>,
468 <CODE>hardscroll.c</CODE> and <CODE>lib_doupdate.c</CODE>; the latter two use
469 <CODE>lib_mvcur.c</CODE>.  Essentially, what happens looks like this: <P>
470
471 The <CODE>hashmap.c</CODE> module tries to detect vertical motion
472 changes between the real and virtual screens.  This information
473 is represented by the oldindex members in the newscr structure.
474 These are modified by vertical-motion and clear operations, and both are
475 re-initialized after each update. To this change-journalling
476 information, the hashmap code adds deductions made using a modified Heckel
477 algorithm on hash values generated from the line contents. <P>
478
479 The <CODE>hardscroll.c</CODE> module computes an optimum set of scroll,
480 insertion, and deletion operations to make the indices match.  It calls
481 <CODE>_nc_mvcur_scrolln()</CODE> in <CODE>lib_mvcur.c</CODE> to do those motions. <P>
482
483 Then <CODE>lib_doupdate.c</CODE> goes to work.  Its job is to do line-by-line
484 transformations of <CODE>curscr</CODE> lines to <CODE>newscr</CODE> lines.  Its main
485 tool is the routine <CODE>mvcur()</CODE> in <CODE>lib_mvcur.c</CODE>.  This routine
486 does cursor-movement optimization, attempting to get from given screen 
487 location A to given location B in the fewest output characters posible. <P>
488
489 If you want to work on screen optimizations, you should use the fact
490 that (in the trace-enabled version of the library) enabling the
491 <CODE>TRACE_TIMES</CODE> trace level causes a report to be emitted after
492 each screen update giving the elapsed time and a count of characters
493 emitted during the update.  You can use this to tell when an update
494 optimization improves efficiency. <P>
495
496 In the trace-enabled version of the library, it is also possible to disable
497 and re-enable various optimizations at runtime by tweaking the variable
498 <CODE>_nc_optimize_enable</CODE>.  See the file <CODE>include/curses.h.in</CODE>
499 for mask values, near the end. <P>
500
501 <H1><A NAME="fmnote">The Forms and Menu Libraries</A></H1>
502
503 The forms and menu libraries should work reliably in any environment you
504 can port ncurses to. The only portability issue anywhere in them is what
505 flavor of regular expressions the built-in form field type TYPE_REGEXP
506 will recognize. <P>
507
508 The configuration code prefers the POSIX regex facility, modeled on
509 System V's, but will settle for BSD regexps if the former isn't available. <P>
510
511 Historical note: the panels code was written primarily to assist in
512 porting u386mon 2.0 (comp.sources.misc v14i001-4) to systems lacking
513 panels support; u386mon 2.10 and beyond use it.  This version has been
514 slightly cleaned up for <CODE>ncurses</CODE>. <P>
515
516 <H1><A NAME="tic">A Tour of the Terminfo Compiler</A></H1>
517
518 The <STRONG>ncurses</STRONG> implementation of <STRONG>tic</STRONG> is rather complex
519 internally; it has to do a trying combination of missions. This starts
520 with the fact that, in addition to its normal duty of compiling
521 terminfo sources into loadable terminfo binaries, it has to be able to
522 handle termcap syntax and compile that too into terminfo entries. <P>
523
524 The implementation therefore starts with a table-driven, dual-mode
525 lexical analyzer (in <CODE>comp_scan.c</CODE>).  The lexer chooses its
526 mode (termcap or terminfo) based on the first `,' or `:' it finds in
527 each entry.  The lexer does all the work of recognizing capability
528 names and values; the grammar above it is trivial, just "parse entries
529 till you run out of file". <P>
530
531 <H2><A NAME="nonuse">Translation of Non-<STRONG>use</STRONG> Capabilities</A></H2>
532
533 Translation of most things besides <STRONG>use</STRONG> capabilities is pretty
534 straightforward.  The lexical analyzer's tokenizer hands each capability
535 name to a hash function, which drives a table lookup.  The table entry
536 yields an index which is used to look up the token type in another table,
537 and controls interpretation of the value. <P>
538
539 One possibly interesting aspect of the implementation is the way the
540 compiler tables are initialized.  All the tables are generated by various
541 awk/sed/sh scripts from a master table <CODE>include/Caps</CODE>; these 
542 scripts actually write C initializers which are linked to the compiler. 
543 Furthermore, the hash table is generated in the same way, so it doesn't
544 have to be generated at compiler startup time (another benefit of this
545 organization is that the hash table can be in shareable text space). <P>
546
547 Thus, adding a new capability is usually pretty trivial, just a matter
548 of adding one line to the <CODE>include/Caps</CODE> file.  We'll have more
549 to say about this in the section on <A HREF="#translation">Source-Form
550 Translation</A>. <P>
551
552 <H2><A NAME="uses">Use Capability Resolution</A></H2>
553
554 The background problem that makes <STRONG>tic</STRONG> tricky isn't the capability
555 translation itself, it's the resolution of <STRONG>use</STRONG> capabilities.  Older
556 versions would not handle forward <STRONG>use</STRONG> references for this reason 
557 (that is, a using terminal always had to follow its use target in the
558 source file).  By doing this, they got away with a simple implementation
559 tactic; compile everything as it blows by, then resolve uses from compiled
560 entries. <P>
561
562 This won't do for <STRONG>ncurses</STRONG>.  The problem is that that the whole
563 compilation process has to be embeddable in the <STRONG>ncurses</STRONG> library
564 so that it can be called by the startup code to translate termcap
565 entries on the fly.  The embedded version can't go promiscuously writing
566 everything it translates out to disk -- for one thing, it will typically
567 be running with non-root permissions. <P> 
568
569 So our <STRONG>tic</STRONG> is designed to parse an entire terminfo file into a
570 doubly-linked circular list of entry structures in-core, and then do
571 <STRONG>use</STRONG> resolution in-memory before writing everything out.  This
572 design has other advantages: it makes forward and back use-references
573 equally easy (so we get the latter for free), and it makes checking for
574 name collisions before they're written out easy to do. <P>
575
576 And this is exactly how the embedded version works.  But the stand-alone
577 user-accessible version of <STRONG>tic</STRONG> partly reverts to the historical
578 strategy; it writes to disk (not keeping in core) any entry with no
579 <STRONG>use</STRONG> references. <P>
580
581 This is strictly a core-economy kluge, implemented because the
582 terminfo master file is large enough that some core-poor systems swap
583 like crazy when you compile it all in memory...there have been reports of
584 this process taking <STRONG>three hours</STRONG>, rather than the twenty seconds
585 or less typical on the author's development box. <P>
586
587 So.  The executable <STRONG>tic</STRONG> passes the entry-parser a hook that
588 <EM>immediately</EM> writes out the referenced entry if it has no use
589 capabilities.  The compiler main loop refrains from adding the entry
590 to the in-core list when this hook fires.  If some other entry later
591 needs to reference an entry that got written immediately, that's OK;
592 the resolution code will fetch it off disk when it can't find it in
593 core. <P>
594
595 Name collisions will still be detected, just not as cleanly.  The
596 <CODE>write_entry()</CODE> code complains before overwriting an entry that
597 postdates the time of <STRONG>tic</STRONG>'s first call to
598 <CODE>write_entry()</CODE>, Thus it will complain about overwriting
599 entries newly made during the <STRONG>tic</STRONG> run, but not about
600 overwriting ones that predate it. <P>
601
602 <H2><A NAME="translation">Source-Form Translation</A></H2>
603
604 Another use of <STRONG>tic</STRONG> is to do source translation between various termcap
605 and terminfo formats.  There are more variants out there than you might
606 think; the ones we know about are described in the <STRONG>captoinfo(1)</STRONG>
607 manual page. <P>
608
609 The translation output code (<CODE>dump_entry()</CODE> in
610 <CODE>ncurses/dump_entry.c</CODE>) is shared with the <STRONG>infocmp(1)</STRONG>
611 utility.  It takes the same internal representation used to generate
612 the binary form and dumps it to standard output in a specified
613 format. <P>
614
615 The <CODE>include/Caps</CODE> file has a header comment describing ways you
616 can specify source translations for nonstandard capabilities just by
617 altering the master table.  It's possible to set up capability aliasing 
618 or tell the compiler to plain ignore a given capability without writing
619 any C code at all. <P>
620
621 For circumstances where you need to do algorithmic translation, there
622 are functions in <CODE>parse_entry.c</CODE> called after the parse of each
623 entry that are specifically intended to encapsulate such
624 translations.  This, for example, is where the AIX <STRONG>box1</STRONG> capability
625 get translated to an <STRONG>acsc</STRONG> string.<P>
626
627 <H1><A NAME="utils">Other Utilities</A></H1>
628
629 The <STRONG>infocmp</STRONG> utility is just a wrapper around the same
630 entry-dumping code used by <STRONG>tic</STRONG> for source translation.  Perhaps
631 the one interesting aspect of the code is the use of a predicate
632 function passed in to <CODE>dump_entry()</CODE> to control which
633 capabilities are dumped.  This is necessary in order to handle both
634 the ordinary De-compilation case and entry difference reporting. <P>
635
636 The <STRONG>tput</STRONG> and <STRONG>clear</STRONG> utilities just do an entry load 
637 followed by a <CODE>tputs()</CODE> of a selected capability. <P>
638
639 <H1><A NAME="style">Style Tips for Developers</A></H1>
640
641 See the TO-DO file in the top-level directory of the source distribution
642 for additions that would be particularly useful. <P>
643
644 The prefix <CODE>_nc_</CODE> should be used on library public functions that are
645 not part of the curses API in order to prevent pollution of the
646 application namespace.
647
648 If you have to add to or modify the function prototypes in curses.h.in,
649 read ncurses/MKlib_gen.sh first so you can avoid breaking XSI conformance.
650
651 Please join the ncurses mailing list.  See the INSTALL file in the
652 top level of the distribution for details on the list. <P>
653
654 Look for the string <CODE>FIXME</CODE> in source files to tag minor bugs
655 and potential problems that could use fixing. <P>
656
657 Don't try to auto-detect OS features in the main body of the C code.
658 That's the job of the configuration system. <P>
659
660 To hold down complexity, do make your code data-driven.  Especially,
661 if you can drive logic from a table filtered out of
662 <CODE>include/Caps</CODE>, do it.  If you find you need to augment the
663 data in that file in order to generate the proper table, that's still
664 preferable to ad-hoc code -- that's why the fifth field (flags) is
665 there. <P>
666
667 Have fun! <P>
668
669 <H1><A NAME="port">Porting Hints</A></H1>
670
671 The following notes are intended to be a first step towards DOS and Macintosh
672 ports of the ncurses libraries. <P>
673
674 The following library modules are `pure curses'; they operate only on
675 the curses internal structures, do all output through other curses
676 calls (not including <CODE>tputs()</CODE> and <CODE>putp()</CODE>) and do not
677 call any other UNIX routines such as signal(2) or the stdio library.
678 Thus, they should not need to be modified for single-terminal
679 ports. <P>
680
681 <CODE>
682 lib_addch.c
683 lib_addstr.c
684 lib_bkgd.c
685 lib_box.c
686 lib_clear.c
687 lib_clrbot.c
688 lib_clreol.c
689 lib_delch.c
690 lib_delwin.c
691 lib_erase.c
692 lib_inchstr.c
693 lib_insch.c
694 lib_insdel.c
695 lib_insstr.c
696 lib_keyname.c
697 lib_move.c
698 lib_mvwin.c
699 lib_newwin.c
700 lib_overlay.c
701 lib_pad.c
702 lib_printw.c
703 lib_refresh.c
704 lib_scanw.c
705 lib_scroll.c
706 lib_scrreg.c
707 lib_set_term.c
708 lib_touch.c
709 lib_tparm.c
710 lib_tputs.c
711 lib_unctrl.c
712 lib_window.c
713 panel.c 
714 </CODE>
715 <P>
716
717 This module is pure curses, but calls outstr(): <P>
718
719 <CODE>
720 lib_getstr.c
721 </CODE>
722 <P>
723
724 These modules are pure curses, except that they use <CODE>tputs()</CODE>
725 and <CODE>putp()</CODE>: <P>
726
727 <CODE>
728 lib_beep.c
729 lib_endwin.c
730 lib_color.c
731 lib_options.c
732 lib_slk.c
733 lib_vidattr.c
734 </CODE>
735 <P>
736
737 This modules assist in POSIX emulation on non-POSIX systems: <P>
738 <DL>
739 <DT> sigaction.c
740 <DD> signal calls
741 </DL>
742
743 The following source files will not be needed for a
744 single-terminal-type port. <P>
745
746 <CODE>
747 captoinfo.c
748 clear.c
749 comp_captab.c
750 comp_error.c
751 comp_hash.c
752 comp_main.c
753 comp_parse.c
754 comp_scan.c
755 alloc_entry.c
756 dump_entry.c
757 parse_entry.c
758 read_entry.c
759 write_entry.c
760 infocmp.c
761 tput.c
762 </CODE>
763 <P>
764
765 The following modules will use open()/read()/write()/close()/lseek() on files,
766 but no other OS calls. <P>
767
768 <DL>
769 <DT> lib_screen.c
770 <DD> used to read/write screen dumps
771 <DT> lib_trace.c
772 <DD> used to write trace data to the logfile
773 </DL>
774
775 Modules that would have to be modified for a port start here: <P>
776
777 The following modules are `pure curses' but contain assumptions inappropriate
778 for a memory-mapped port. <P>
779
780 <PRE>
781 lib_longname.c  -- assumes there may be multiple terminals
782         longname()              -- return long name of terminal
783 lib_acs.c       -- assumes acs_map as a double indirection
784         init_acs()              -- initialize acs map
785 lib_mvcur.c     -- assumes cursor moves have variable cost
786         mvcur_init()            -- initialize
787         mvcur()                 -- do physical cursor move
788         mvcur_wrap()            -- wrap
789         scrolln()               -- do physical scrolling
790 lib_termcap.c   -- assumes there may be multiple terminals
791         tgetent()               -- load entry
792         tgetflag()              -- get boolean capability
793         tgetnum()               -- get numeric capability
794         tgetstr()               -- get string capability
795 lib_ti.c        -- assumes there may be multiple terminals
796         tigetent()              -- load entry
797         tigetflag()             -- get boolean capability
798         tigetnum()              -- get numeric capability
799         tigetstr()              -- get string capability
800
801 The following modules use UNIX-specific calls:
802
803 lib_doupdate.c  -- input checking
804         doupdate()              -- repaint real screen to match virtual
805         _nc_outch()             -- put out a single character
806 lib_getch.c     -- read()
807         wgetch()                -- get single character
808         wungetch()              -- push back single character
809 lib_initscr.c   -- getenv()
810         initscr()               -- initialize curses functions
811 lib_newterm.c
812         newterm()               -- set up new terminal screen
813 lib_baudrate.c
814         baudrate()              -- return the baudrate
815 lib_kernel.c    -- various tty-manipulation and system calls
816         reset_prog_mode()       -- reset ccurses-raw mode
817         reset_shell_mode()      -- reset cooked mode
818         erasechar()             -- return the erase char
819         killchar()              -- return the kill character
820         flushinp()              -- flush pending input
821         savetty()               -- save tty state
822         resetty()               -- reset tty to state at last savetty() 
823 lib_raw.c       -- various tty-manipulation calls
824         raw()
825         echo()
826         nl()
827         qiflush()
828         cbreak()
829         noraw()
830         noecho()
831         nonl()
832         noqiflush()
833         nocbreak()
834 lib_setup.c     -- various tty-manipulation calls
835         use_env()
836         setupterm()
837 lib_restart.c   -- various tty-manipulation calls
838         def_shell_mode()
839         def_prog_mode()
840         set_curterm()
841         del_curterm()
842 lib_tstp.c      -- signal-manipulation calls
843         _nc_signal_handler()    -- enable/disable window-mode signal catching
844 lib_twait.c     -- gettimeofday(), select().
845         usleep()                -- microsecond sleep
846         _nc_timed_wait()        -- timed wait for input
847 </PRE>
848
849 The package kernel could be made smaller. <P>
850
851 <HR>
852 <ADDRESS>Eric S. Raymond &lt;esr@snark.thyrsus.com&gt;</ADDRESS>
853 (Note: This is <EM>not</EM> the <A HREF="#bugtrack">bug address</A>!)
854 </BODY>
855 </HTML>