1/****************************************************************************
2 * Copyright (c) 1998-2013,2014 Free Software Foundation, Inc.              *
3 *                                                                          *
4 * Permission is hereby granted, free of charge, to any person obtaining a  *
5 * copy of this software and associated documentation files (the            *
6 * "Software"), to deal in the Software without restriction, including      *
7 * without limitation the rights to use, copy, modify, merge, publish,      *
8 * distribute, distribute with modifications, sublicense, and/or sell       *
9 * copies of the Software, and to permit persons to whom the Software is    *
10 * furnished to do so, subject to the following conditions:                 *
11 *                                                                          *
12 * The above copyright notice and this permission notice shall be included  *
13 * in all copies or substantial portions of the Software.                   *
14 *                                                                          *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22 *                                                                          *
23 * Except as contained in this notice, the name(s) of the above copyright   *
24 * holders shall not be used in advertising or otherwise to promote the     *
25 * sale, use or other dealings in this Software without prior written       *
26 * authorization.                                                           *
27 ****************************************************************************/
28
29/****************************************************************************
30 *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31 *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32 *     and: Thomas E. Dickey                        1996-on                 *
33 *     and: Juergen Pfeifer                                                 *
34 ****************************************************************************/
35
36/*
37 * $Id: curses.priv.h,v 1.530 2014/02/01 22:09:27 tom Exp $
38 *
39 *	curses.priv.h
40 *
41 *	Header file for curses library objects which are private to
42 *	the library.
43 *
44 */
45
46#ifndef CURSES_PRIV_H
47#define CURSES_PRIV_H 1
48/* *INDENT-OFF* */
49
50#include <ncurses_dll.h>
51
52#ifdef __cplusplus
53extern "C" {
54#endif
55
56#include <ncurses_cfg.h>
57
58#if USE_RCS_IDS
59#define MODULE_ID(id) static const char Ident[] = id;
60#else
61#define MODULE_ID(id) /*nothing*/
62#endif
63
64#include <stddef.h>		/* for offsetof */
65#include <stdlib.h>
66#include <string.h>
67#include <sys/types.h>
68#include <sys/stat.h>
69
70#if HAVE_UNISTD_H
71#include <unistd.h>
72#endif
73
74#if HAVE_SYS_BSDTYPES_H
75#include <sys/bsdtypes.h>	/* needed for ISC */
76#endif
77
78#if HAVE_LIMITS_H
79# include <limits.h>
80#elif HAVE_SYS_PARAM_H
81# include <sys/param.h>
82#endif
83
84#include <assert.h>
85#include <stdio.h>
86
87#include <errno.h>
88
89#if defined __hpux
90#  ifndef EILSEQ
91#    define EILSEQ 47
92#  endif
93#endif
94
95#ifndef PATH_MAX
96# if defined(_POSIX_PATH_MAX)
97#  define PATH_MAX _POSIX_PATH_MAX
98# elif defined(MAXPATHLEN)
99#  define PATH_MAX MAXPATHLEN
100# else
101#  define PATH_MAX 255	/* the Posix minimum path-size */
102# endif
103#endif
104
105#if DECL_ERRNO
106extern int errno;
107#endif
108
109/* Some systems have a broken 'select()', but workable 'poll()'.  Use that */
110#if HAVE_WORKING_POLL
111#define USE_FUNC_POLL 1
112#if HAVE_POLL_H
113#include <poll.h>
114#else
115#include <sys/poll.h>
116#endif
117#else
118#define USE_FUNC_POLL 0
119#endif
120
121#if HAVE_INTTYPES_H
122# include <inttypes.h>
123#else
124# if HAVE_STDINT_H
125#  include <stdint.h>
126# endif
127#endif
128
129/* include signal.h before curses.h to work-around defect in glibc 2.1.3 */
130#include <signal.h>
131
132/* Alessandro Rubini's GPM (general-purpose mouse) */
133#if HAVE_LIBGPM && HAVE_GPM_H
134#define USE_GPM_SUPPORT 1
135#else
136#define USE_GPM_SUPPORT 0
137#endif
138
139/* QNX mouse support */
140#if defined(__QNX__) && !defined(__QNXNTO__)
141#define USE_QNX_MOUSE 1
142#else
143#define USE_QNX_MOUSE 0
144#endif
145
146/* EMX mouse support */
147#ifdef __EMX__
148#define USE_EMX_MOUSE 1
149#else
150#define USE_EMX_MOUSE 0
151#endif
152
153/* kLIBC keyboard/mouse support */
154#if defined(__OS2__) && defined(__KLIBC__)
155#define USE_KLIBC_KBD   1
156#define USE_KLIBC_MOUSE 1
157#else
158#define USE_KLIBC_KBD   0
159#define USE_KLIBC_MOUSE 0
160#endif
161
162#define DEFAULT_MAXCLICK 166
163#define EV_MAX		8	/* size of mouse circular event queue */
164
165/*
166 * If we don't have signals to support it, don't add a sigwinch handler.
167 * In any case, resizing is an extended feature.  Use it if we've got it.
168 */
169#if !NCURSES_EXT_FUNCS
170#undef HAVE_SIZECHANGE
171#define HAVE_SIZECHANGE 0
172#endif
173
174#if HAVE_SIZECHANGE && USE_SIGWINCH && defined(SIGWINCH)
175#define USE_SIZECHANGE 1
176#else
177#define USE_SIZECHANGE 0
178#undef USE_SIGWINCH
179#define USE_SIGWINCH 0
180#endif
181
182/*
183 * If desired, one can configure this, disabling environment variables that
184 * point to custom terminfo/termcap locations.
185 */
186#ifdef USE_ROOT_ENVIRON
187#define use_terminfo_vars() 1
188#else
189#define use_terminfo_vars() _nc_env_access()
190extern NCURSES_EXPORT(int) _nc_env_access (void);
191#endif
192
193/*
194 * Not all platforms have memmove; some have an equivalent bcopy.  (Some may
195 * have neither).
196 */
197#if USE_OK_BCOPY
198#define memmove(d,s,n) bcopy(s,d,n)
199#elif USE_MY_MEMMOVE
200#define memmove(d,s,n) _nc_memmove(d,s,n)
201extern NCURSES_EXPORT(void *) _nc_memmove (void *, const void *, size_t);
202#endif
203
204/*
205 * If we have va_copy(), use it for assigning va_list's.
206 */
207#if defined(HAVE___VA_COPY)
208#define begin_va_copy(dst,src)	__va_copy(dst, src)
209#define end_va_copy(dst)	va_end(dst)
210#elif defined(va_copy) || defined(HAVE_VA_COPY)
211#define begin_va_copy(dst,src)	va_copy(dst, src)
212#define end_va_copy(dst)	va_end(dst)
213#else
214#define begin_va_copy(dst,src) (dst) = (src)
215#define end_va_copy(dst)	/* nothing */
216#endif
217
218/*
219 * Either/both S_ISxxx and/or S_IFxxx are defined in sys/types.h; some systems
220 * lack one or the other.
221 */
222#ifndef S_ISDIR
223#define S_ISDIR(mode) ((mode & S_IFMT) == S_IFDIR)
224#endif
225
226#ifndef S_ISREG
227#define S_ISREG(mode) ((mode & S_IFMT) == S_IFREG)
228#endif
229
230/*
231 * Scroll hints are useless when hashmap is used
232 */
233#if !USE_SCROLL_HINTS
234#if !USE_HASHMAP
235#define USE_SCROLL_HINTS 1
236#else
237#define USE_SCROLL_HINTS 0
238#endif
239#endif
240
241#if USE_SCROLL_HINTS
242#define if_USE_SCROLL_HINTS(stmt) stmt
243#else
244#define if_USE_SCROLL_HINTS(stmt) /*nothing*/
245#endif
246
247#include <nc_string.h>
248
249/*
250 * Options for terminal drivers, etc...
251 */
252#ifdef USE_TERM_DRIVER
253#define USE_SP_RIPOFF     1
254#define USE_SP_TERMTYPE   1
255#define USE_SP_WINDOWLIST 1
256#endif
257
258/*
259 * Note:  ht/cbt expansion flakes out randomly under Linux 1.1.47, but only
260 * when we're throwing control codes at the screen at high volume.  To see
261 * this, re-enable USE_HARD_TABS and run worm for a while.  Other systems
262 * probably don't want to define this either due to uncertainties about tab
263 * delays and expansion in raw mode.
264 */
265
266#define TRIES struct tries
267typedef TRIES {
268	TRIES    *child;            /* ptr to child.  NULL if none          */
269	TRIES    *sibling;          /* ptr to sibling.  NULL if none        */
270	unsigned char    ch;        /* character at this node               */
271	unsigned short   value;     /* code of string so far.  0 if none.   */
272#undef TRIES
273} TRIES;
274
275/*
276 * Common/troublesome character definitions
277 */
278#define StringOf(ch) {ch, 0}
279
280#define L_BRACE '{'
281#define R_BRACE '}'
282#define S_QUOTE '\''
283#define D_QUOTE '"'
284
285#define VT_ACSC "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~"
286
287/*
288 * Structure for palette tables
289 */
290
291#define MAXCOLUMNS    135
292#define MAXLINES      66
293#define FIFO_SIZE     MAXCOLUMNS+2  /* for nocbreak mode input */
294
295#define ACS_LEN       128
296
297#define WINDOWLIST struct _win_list
298
299#if USE_WIDEC_SUPPORT
300#define _nc_bkgd    _bkgrnd
301#else
302#undef _XOPEN_SOURCE_EXTENDED
303#undef _XPG5
304#define _nc_bkgd    _bkgd
305#define wgetbkgrnd(win, wch)	*wch = win->_bkgd
306#define wbkgrnd	    wbkgd
307#endif
308
309#undef NCURSES_OPAQUE
310#define NCURSES_INTERNALS 1
311#define NCURSES_OPAQUE 0
312
313#include <curses.h>	/* we'll use -Ipath directive to get the right one! */
314
315typedef struct
316{
317    NCURSES_COLOR_T red, green, blue;	/* what color_content() returns */
318    NCURSES_COLOR_T r, g, b;		/* params to init_color() */
319    int init;			/* true if we called init_color() */
320}
321color_t;
322
323/*
324 * If curses.h did not expose the SCREEN-functions, then we do not need the
325 * parameter in the corresponding unextended functions.
326 */
327
328#define USE_SP_FUNC_SUPPORT     NCURSES_SP_FUNCS
329#define USE_EXT_SP_FUNC_SUPPORT (NCURSES_SP_FUNCS && NCURSES_EXT_FUNCS)
330
331#if NCURSES_SP_FUNCS
332#define SP_PARM         sp	/* use parameter */
333#define NCURSES_SP_ARG          SP_PARM
334#define NCURSES_SP_DCL  SCREEN *NCURSES_SP_ARG
335#define NCURSES_SP_DCL0 NCURSES_SP_DCL
336#define NCURSES_SP_ARGx         NCURSES_SP_ARG,
337#define NCURSES_SP_DCLx SCREEN *NCURSES_SP_ARGx
338#else
339#define SP_PARM         SP	/* use global variable */
340#define NCURSES_SP_ARG
341#define NCURSES_SP_DCL
342#define NCURSES_SP_DCL0 void
343#define NCURSES_SP_ARGx
344#define NCURSES_SP_DCLx
345#endif
346
347#include <nc_panel.h>
348
349#define IsPreScreen(sp)      (((sp) != 0) && sp->_prescreen)
350#define HasTerminal(sp)      (((sp) != 0) && (0 != ((sp)->_term)))
351#define IsValidScreen(sp)    (HasTerminal(sp) && !IsPreScreen(sp))
352
353#if USE_REENTRANT
354#define CurTerm              _nc_prescreen._cur_term
355#else
356#define CurTerm              cur_term
357#endif
358
359#if NCURSES_SP_FUNCS
360#define TerminalOf(sp)       ((sp) ? ((sp)->_term ? (sp)->_term : CurTerm) : CurTerm)
361#else
362#define TerminalOf(sp)       CurTerm
363#endif
364
365#include <term.h>
366#include <nc_termios.h>
367
368/*
369 * Reduce dependency on cur_term global by using terminfo data from SCREEN's
370 * pointer to this data.
371 */
372#ifdef USE_SP_TERMTYPE
373#undef CUR
374#endif
375
376#define SP_TERMTYPE TerminalOf(sp)->type.
377
378#include <term_entry.h>
379
380#include <nc_tparm.h>
381
382/*
383 * Simplify ifdef's for the "*_ATTR" macros in case italics are not configured.
384 */
385#ifdef A_ITALIC
386#define USE_ITALIC 1
387#else
388#define USE_ITALIC 0
389#define A_ITALIC 0
390#endif
391
392/*
393 * Use these macros internally, to make tracing less verbose.  But leave the
394 * option for compiling the tracing into the library.
395 */
396#if 1
397#define ColorPair(n)		NCURSES_BITS(n, 0)
398#define PairNumber(a)		(NCURSES_CAST(int,(((unsigned long)(a) & A_COLOR) >> NCURSES_ATTR_SHIFT)))
399#else
400#define ColorPair(pair)		COLOR_PAIR(pair)
401#define PairNumber(attr)	PAIR_NUMBER(attr)
402#endif
403
404#define unColor(n)		unColor2(AttrOf(n))
405#define unColor2(a)		((a) & ALL_BUT_COLOR)
406
407/*
408 * Extended-colors stores the color pair in a separate struct-member than the
409 * attributes.  But for compatibility, we handle most cases where a program
410 * written for non-extended colors stores the color in the attributes by
411 * checking for a color pair in both places.
412 */
413#if NCURSES_EXT_COLORS
414#define if_EXT_COLORS(stmt)	stmt
415#define SetPair(value,p)	SetPair2((value).ext_color, AttrOf(value), p)
416#define SetPair2(c,a,p)		c = (p), \
417				a = (unColor2(a) | (A_COLOR & (unsigned) ColorPair(oldColor(c))))
418#define GetPair(value)		GetPair2((value).ext_color, AttrOf(value))
419#define GetPair2(c,a)		((c) ? (c) : PairNumber(a))
420#define oldColor(p)		(((p) > 255) ? 255 : (p))
421#define GET_WINDOW_PAIR(w)	GetPair2((w)->_color, (w)->_attrs)
422#define SET_WINDOW_PAIR(w,p)	(w)->_color = (p)
423#define SameAttrOf(a,b)		(AttrOf(a) == AttrOf(b) && GetPair(a) == GetPair(b))
424
425#define VIDATTR(sp,attr,pair)	NCURSES_SP_NAME(vid_puts)(NCURSES_SP_ARGx attr, (short) pair, 0, NCURSES_OUTC_FUNC)
426
427#else /* !NCURSES_EXT_COLORS */
428
429#define if_EXT_COLORS(stmt)	/* nothing */
430#define SetPair(value,p)	RemAttr(value, A_COLOR), \
431				SetAttr(value, AttrOf(value) | (A_COLOR & (attr_t) ColorPair(p)))
432#define GetPair(value)		PairNumber(AttrOf(value))
433#define GET_WINDOW_PAIR(w)	PairNumber(WINDOW_ATTRS(w))
434#define SET_WINDOW_PAIR(w,p)	WINDOW_ATTRS(w) &= ALL_BUT_COLOR, \
435				WINDOW_ATTRS(w) |= (A_COLOR & (attr_t) ColorPair(p))
436#define SameAttrOf(a,b)		(AttrOf(a) == AttrOf(b))
437
438#define VIDATTR(sp,attr,pair)	NCURSES_SP_NAME(vidputs)(NCURSES_SP_ARGx attr, NCURSES_OUTC_FUNC)
439
440#endif /* NCURSES_EXT_COLORS */
441
442#define NCURSES_OUTC_FUNC       NCURSES_SP_NAME(_nc_outch)
443#define NCURSES_PUTP2(name,value)    NCURSES_SP_NAME(_nc_putp)(NCURSES_SP_ARGx name, value)
444#define NCURSES_PUTP2_FLUSH(name,value)    NCURSES_SP_NAME(_nc_putp_flush)(NCURSES_SP_ARGx name, value)
445
446#if NCURSES_NO_PADDING
447#define GetNoPadding(sp)	((sp) ? (sp)->_no_padding : _nc_prescreen._no_padding)
448#define SetNoPadding(sp)	_nc_set_no_padding(sp)
449extern NCURSES_EXPORT(void)     _nc_set_no_padding(SCREEN *);
450#else
451#define GetNoPadding(sp)	FALSE
452#define SetNoPadding(sp)	/*nothing*/
453#endif
454
455#define WINDOW_ATTRS(w)		((w)->_attrs)
456
457#define SCREEN_ATTRS(s)		(*((s)->_current_attr))
458#define GET_SCREEN_PAIR(s)	GetPair(SCREEN_ATTRS(s))
459#define SET_SCREEN_PAIR(s,p)	SetPair(SCREEN_ATTRS(s), p)
460
461#if USE_REENTRANT || NCURSES_SP_FUNCS
462NCURSES_EXPORT(int *)        _nc_ptr_Lines (SCREEN *);
463NCURSES_EXPORT(int *)        _nc_ptr_Cols (SCREEN *);
464NCURSES_EXPORT(int *)        _nc_ptr_Tabsize (SCREEN *);
465NCURSES_EXPORT(int *)        _nc_ptr_Escdelay (SCREEN *);
466#endif
467
468#if USE_REENTRANT
469
470#define ptrLines(sp)         (sp ? &(sp->_LINES) : &(_nc_prescreen._LINES))
471#define ptrCols(sp)          (sp ? &(sp->_COLS) : &(_nc_prescreen._COLS))
472#define ptrTabsize(sp)       (sp ? &(sp->_TABSIZE) : &(_nc_prescreen._TABSIZE))
473#define ptrEscdelay(sp)      (sp ? &(sp->_ESCDELAY) : &(_nc_prescreen._ESCDELAY))
474
475#define SET_LINES(value)     *_nc_ptr_Lines(SP_PARM) = value
476#define SET_COLS(value)      *_nc_ptr_Cols(SP_PARM) = value
477#define SET_TABSIZE(value)   *_nc_ptr_Tabsize(SP_PARM) = value
478#define SET_ESCDELAY(value)  *_nc_ptr_Escdelay(SP_PARM) = value
479
480#else
481
482#define ptrLines(sp)         &LINES
483#define ptrCols(sp)          &COLS
484#define ptrTabsize(sp)       &TABSIZE
485#define ptrEscdelay(sp)      &ESCDELAY
486
487#define SET_LINES(value)     LINES = value
488#define SET_COLS(value)      COLS = value
489#define SET_TABSIZE(value)   TABSIZE = value
490#define SET_ESCDELAY(value)  ESCDELAY = value
491
492#endif
493
494#define TR_MUTEX(data) _tracef("%s@%d: me:%08lX COUNT:%2u/%2d/%6d/%2d/%s%9u: " #data, \
495	    __FILE__, __LINE__, \
496	    (unsigned long) (pthread_self()), \
497	    data.__data.__lock, \
498	    data.__data.__count, \
499	    data.__data.__owner, \
500	    data.__data.__kind, \
501	    (data.__data.__nusers > 5) ? " OOPS " : "", \
502	    data.__data.__nusers)
503#define TR_GLOBAL_MUTEX(name) TR_MUTEX(_nc_globals.mutex_##name)
504
505#if USE_WEAK_SYMBOLS
506#if defined(__GNUC__)
507#  if defined __USE_ISOC99
508#    define _cat_pragma(exp)	_Pragma(#exp)
509#    define _weak_pragma(exp)	_cat_pragma(weak name)
510#  else
511#    define _weak_pragma(exp)
512#  endif
513#  define _declare(name)	__extension__ extern __typeof__(name) name
514#  define weak_symbol(name)	_weak_pragma(name) _declare(name) __attribute__((weak))
515#else
516#  undef USE_WEAK_SYMBOLS
517#  define USE_WEAK_SYMBOLS 0
518#endif
519#endif
520
521#ifdef USE_PTHREADS
522
523#if USE_REENTRANT
524#include <pthread.h>
525extern NCURSES_EXPORT(void) _nc_init_pthreads(void);
526extern NCURSES_EXPORT(void) _nc_mutex_init(pthread_mutex_t *);
527extern NCURSES_EXPORT(int) _nc_mutex_lock(pthread_mutex_t *);
528extern NCURSES_EXPORT(int) _nc_mutex_trylock(pthread_mutex_t *);
529extern NCURSES_EXPORT(int) _nc_mutex_unlock(pthread_mutex_t *);
530#define _nc_lock_global(name)	_nc_mutex_lock(&_nc_globals.mutex_##name)
531#define _nc_try_global(name)    _nc_mutex_trylock(&_nc_globals.mutex_##name)
532#define _nc_unlock_global(name)	_nc_mutex_unlock(&_nc_globals.mutex_##name)
533
534#else
535#error POSIX threads requires --enable-reentrant option
536#endif
537
538#ifdef USE_PTHREADS
539#  if USE_WEAK_SYMBOLS
540weak_symbol(pthread_sigmask);
541weak_symbol(pthread_kill);
542weak_symbol(pthread_self);
543weak_symbol(pthread_equal);
544weak_symbol(pthread_mutex_init);
545weak_symbol(pthread_mutex_lock);
546weak_symbol(pthread_mutex_unlock);
547weak_symbol(pthread_mutex_trylock);
548weak_symbol(pthread_mutexattr_settype);
549weak_symbol(pthread_mutexattr_init);
550extern NCURSES_EXPORT(int) _nc_sigprocmask(int, const sigset_t *, sigset_t *);
551#    undef  sigprocmask
552#    define sigprocmask _nc_sigprocmask
553#  endif
554#endif
555
556#if HAVE_NANOSLEEP
557#undef HAVE_NANOSLEEP
558#define HAVE_NANOSLEEP 0	/* nanosleep suspends all threads */
559#endif
560
561#else /* !USE_PTHREADS */
562
563#if USE_PTHREADS_EINTR
564#  if USE_WEAK_SYMBOLS
565#include <pthread.h>
566weak_symbol(pthread_sigmask);
567weak_symbol(pthread_kill);
568weak_symbol(pthread_self);
569weak_symbol(pthread_equal);
570extern NCURSES_EXPORT(int) _nc_sigprocmask(int, const sigset_t *, sigset_t *);
571#    undef  sigprocmask
572#    define sigprocmask _nc_sigprocmask
573#  endif
574#endif /* USE_PTHREADS_EINTR */
575
576#define _nc_init_pthreads()	/* nothing */
577#define _nc_mutex_init(obj)	/* nothing */
578
579#define _nc_lock_global(name)	/* nothing */
580#define _nc_try_global(name)    0
581#define _nc_unlock_global(name)	/* nothing */
582
583#endif /* USE_PTHREADS */
584
585/*
586 * When using sp-funcs, locks are targeted to SCREEN-level granularity.
587 * So the locking is done in the non-sp-func (which calls the sp-func) rather
588 * than in the sp-func itself.
589 *
590 * Use the _nc_nonsp_XXX functions in the function using "NCURSES_SP_NAME()".
591 * Use the _nc_sp_XXX functions in the function using "#if NCURSES_SP_FUNCS".
592 */
593#if NCURSES_SP_FUNCS
594
595#define _nc_nonsp_lock_global(name)	/* nothing */
596#define _nc_nonsp_try_global(name)    0
597#define _nc_nonsp_unlock_global(name)	/* nothing */
598
599#define _nc_sp_lock_global(name)	_nc_lock_global(name)
600#define _nc_sp_try_global(name)         _nc_try_global(name)
601#define _nc_sp_unlock_global(name)	_nc_unlock_global(name)
602
603#else
604
605#define _nc_nonsp_lock_global(name)	_nc_lock_global(name)
606#define _nc_nonsp_try_global(name)      _nc_try_global(name)
607#define _nc_nonsp_unlock_global(name)	_nc_unlock_global(name)
608
609#define _nc_sp_lock_global(name)	/* nothing */
610#define _nc_sp_try_global(name)    0
611#define _nc_sp_unlock_global(name)	/* nothing */
612
613#endif
614
615#if HAVE_GETTIMEOFDAY
616# define PRECISE_GETTIME 1
617# define TimeType struct timeval
618#else
619# define PRECISE_GETTIME 0
620# define TimeType time_t
621#endif
622
623/*
624 * Definitions for color pairs
625 */
626typedef unsigned colorpair_t;	/* type big enough to store PAIR_OF() */
627#define C_SHIFT 9		/* we need more bits than there are colors */
628#define C_MASK			((1 << C_SHIFT) - 1)
629#define PAIR_OF(fg, bg)		(colorpair_t) ((((fg) & C_MASK) << C_SHIFT) | ((bg) & C_MASK))
630#define FORE_OF(c)		(((c) >> C_SHIFT) & C_MASK)
631#define BACK_OF(c)		((c) & C_MASK)
632#define isDefaultColor(c)	((c) >= COLOR_DEFAULT || (c) < 0)
633
634#define COLOR_DEFAULT		C_MASK
635
636#if defined(USE_BUILD_CC) || (defined(USE_TERMLIB) && !defined(NEED_NCURSES_CH_T))
637
638#undef NCURSES_CH_T		/* this is not a termlib feature */
639#define NCURSES_CH_T void	/* ...but we need a pointer in SCREEN */
640
641#endif	/* USE_TERMLIB */
642
643#ifndef USE_TERMLIB
644struct ldat
645{
646	NCURSES_CH_T	*text;		/* text of the line */
647	NCURSES_SIZE_T	firstchar;	/* first changed character in the line */
648	NCURSES_SIZE_T	lastchar;	/* last changed character in the line */
649	NCURSES_SIZE_T	oldindex;	/* index of the line at last update */
650};
651#endif	/* USE_TERMLIB */
652
653typedef enum {
654	M_XTERM	= -1		/* use xterm's mouse tracking? */
655	,M_NONE = 0		/* no mouse device */
656#if USE_GPM_SUPPORT
657	,M_GPM			/* use GPM */
658#endif
659#if USE_SYSMOUSE
660	,M_SYSMOUSE		/* FreeBSD sysmouse on console */
661#endif
662#ifdef USE_TERM_DRIVER
663	,M_TERM_DRIVER		/* Win32 console, etc */
664#endif
665} MouseType;
666
667/*
668 * Structures for scrolling.
669 */
670
671typedef struct {
672	unsigned long hashval;
673	int oldcount, newcount;
674	int oldindex, newindex;
675} HASHMAP;
676
677/*
678 * Structures for soft labels.
679 */
680
681struct _SLK;
682
683#if !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
684
685typedef struct
686{
687	char *ent_text;		/* text for the label */
688	char *form_text;	/* formatted text (left/center/...) */
689	int ent_x;		/* x coordinate of this field */
690	char dirty;		/* this label has changed */
691	char visible;		/* field is visible */
692} slk_ent;
693
694typedef struct _SLK {
695	bool    dirty;		/* all labels have changed */
696	bool    hidden;		/* soft labels are hidden */
697	WINDOW  *win;
698	slk_ent *ent;
699	short   maxlab;		/* number of available labels */
700	short   labcnt;		/* number of allocated labels */
701	short   maxlen;		/* length of labels */
702	NCURSES_CH_T attr;	/* soft label attribute */
703} SLK;
704
705#endif	/* USE_TERMLIB */
706
707typedef	struct {
708	WINDOW *win;		/* the window used in the hook      */
709	int	line;		/* lines to take, < 0 => from bottom*/
710	int	(*hook)(WINDOW *, int); /* callback for user	    */
711} ripoff_t;
712
713#if USE_GPM_SUPPORT
714#undef buttons			/* term.h defines this, and gpm uses it! */
715#include <gpm.h>
716#if USE_WEAK_SYMBOLS
717weak_symbol(Gpm_Wgetch);
718#endif
719
720#ifdef HAVE_LIBDL
721/* link dynamically to GPM */
722typedef int *TYPE_gpm_fd;
723typedef int (*TYPE_Gpm_Open) (Gpm_Connect *, int);
724typedef int (*TYPE_Gpm_Close) (void);
725typedef int (*TYPE_Gpm_GetEvent) (Gpm_Event *);
726
727#define my_gpm_fd       SP_PARM->_mouse_gpm_fd
728#define my_Gpm_Open     SP_PARM->_mouse_Gpm_Open
729#define my_Gpm_Close    SP_PARM->_mouse_Gpm_Close
730#define my_Gpm_GetEvent SP_PARM->_mouse_Gpm_GetEvent
731#else
732/* link statically to GPM */
733#define my_gpm_fd       &gpm_fd
734#define my_Gpm_Open     Gpm_Open
735#define my_Gpm_Close    Gpm_Close
736#define my_Gpm_GetEvent Gpm_GetEvent
737#endif /* HAVE_LIBDL */
738#endif /* USE_GPM_SUPPORT */
739
740typedef struct {
741    long sequence;
742    bool last_used;
743    char *fix_sgr0;		/* this holds the filtered sgr0 string */
744    char *last_bufp;		/* help with fix_sgr0 leak */
745    TERMINAL *last_term;
746} TGETENT_CACHE;
747
748#define TGETENT_MAX 4
749
750/*
751 * State of tparm().
752 */
753#define STACKSIZE 20
754
755typedef struct {
756	union {
757		int	num;
758		char	*str;
759	} data;
760	bool num_type;
761} STACK_FRAME;
762
763#define NUM_VARS 26
764
765typedef struct {
766#ifdef TRACE
767	const char	*tname;
768#endif
769	const char	*tparam_base;
770
771	STACK_FRAME	stack[STACKSIZE];
772	int		stack_ptr;
773
774	char		*out_buff;
775	size_t		out_size;
776	size_t		out_used;
777
778	char		*fmt_buff;
779	size_t		fmt_size;
780
781	int		dynamic_var[NUM_VARS];
782	int		static_vars[NUM_VARS];
783} TPARM_STATE;
784
785typedef struct {
786    char *text;
787    size_t size;
788} TRACEBUF;
789
790/*
791 * The filesystem database normally uses a single-letter for the lower level
792 * of directories.  Use a hexadecimal code for filesystems which do not
793 * preserve mixed-case names.
794 */
795#if MIXEDCASE_FILENAMES
796#define LEAF_FMT "%c"
797#define LEAF_LEN 1
798#else
799#define LEAF_FMT "%02x"
800#define LEAF_LEN 2
801#endif
802
803/*
804 * TRACEMSE_FMT is no longer than 80 columns, there are 5 numbers that
805 * could at most have 10 digits, and the mask contains no more than 32 bits
806 * with each bit representing less than 15 characters.  Usually the whole
807 * string is less than 80 columns, but this buffer size is an absolute
808 * limit.
809 */
810#define TRACEMSE_MAX	(80 + (5 * 10) + (32 * 15))
811#define TRACEMSE_FMT	"id %2d  at (%2d, %2d, %2d) state %4lx = {" /* } */
812
813#ifdef USE_TERM_DRIVER
814struct DriverTCB; /* Terminal Control Block forward declaration */
815#define INIT_TERM_DRIVER()	_nc_globals.term_driver = _nc_get_driver
816#else
817#define INIT_TERM_DRIVER()	/* nothing */
818#endif
819
820typedef struct {
821    const char *name;
822    char *value;
823} ITERATOR_VARS;
824
825/*
826 * Global data which is not specific to a screen.
827 */
828typedef struct {
829	SIG_ATOMIC_T	have_sigtstp;
830	SIG_ATOMIC_T	have_sigwinch;
831	SIG_ATOMIC_T	cleanup_nested;
832
833	bool		init_signals;
834	bool		init_screen;
835
836	char		*comp_sourcename;
837	char		*comp_termtype;
838
839	bool		have_tic_directory;
840	bool		keep_tic_directory;
841	const char	*tic_directory;
842
843	char		*dbi_list;
844	int		dbi_size;
845
846	char		*first_name;
847	char		**keyname_table;
848	int		init_keyname;
849
850	int		slk_format;
851
852	char		*safeprint_buf;
853	size_t		safeprint_used;
854
855	TGETENT_CACHE	tgetent_cache[TGETENT_MAX];
856	int		tgetent_index;
857	long		tgetent_sequence;
858
859	char		*dbd_blob;	/* string-heap for dbd_list[] */
860	char		**dbd_list;	/* distinct places to look for data */
861	int		dbd_size;	/* length of dbd_list[] */
862	time_t		dbd_time;	/* cache last updated */
863	ITERATOR_VARS	dbd_vars[dbdLAST];
864
865#ifndef USE_SP_WINDOWLIST
866	WINDOWLIST	*_nc_windowlist;
867#define WindowList(sp)	_nc_globals._nc_windowlist
868#endif
869
870#if USE_HOME_TERMINFO
871	char		*home_terminfo;
872#endif
873
874#if !USE_SAFE_SPRINTF
875	int		safeprint_cols;
876	int		safeprint_rows;
877#endif
878
879#ifdef USE_TERM_DRIVER
880	int		(*term_driver)(struct DriverTCB*, const char*, int*);
881#endif
882
883#ifdef TRACE
884	bool		init_trace;
885	char		trace_fname[PATH_MAX];
886	int		trace_level;
887	FILE		*trace_fp;
888
889	char		*tracearg_buf;
890	size_t		tracearg_used;
891
892	TRACEBUF	*tracebuf_ptr;
893	size_t		tracebuf_used;
894
895	char		tracechr_buf[40];
896
897	char		*tracedmp_buf;
898	size_t		tracedmp_used;
899
900	unsigned char	*tracetry_buf;
901	size_t		tracetry_used;
902
903	char		traceatr_color_buf[2][80];
904	int		traceatr_color_sel;
905	int		traceatr_color_last;
906#if !defined(USE_PTHREADS) && USE_REENTRANT
907	int		nested_tracef;
908#endif
909#endif	/* TRACE */
910
911#ifdef USE_PTHREADS
912	pthread_mutex_t	mutex_curses;
913	pthread_mutex_t	mutex_tst_tracef;
914	pthread_mutex_t	mutex_tracef;
915	int		nested_tracef;
916	int		use_pthreads;
917#define _nc_use_pthreads	_nc_globals.use_pthreads
918#endif
919#if USE_PTHREADS_EINTR
920	pthread_t	read_thread;		/* The reading thread */
921#endif
922} NCURSES_GLOBALS;
923
924extern NCURSES_EXPORT_VAR(NCURSES_GLOBALS) _nc_globals;
925
926#define N_RIPS 5
927
928/*
929 * Global data which can be swept up into a SCREEN when one is created.
930 * It may be modified before the next SCREEN is created.
931 */
932typedef struct {
933	bool		use_env;
934	bool		filter_mode;
935	attr_t		previous_attr;
936#ifndef USE_SP_RIPOFF
937	ripoff_t	rippedoff[N_RIPS];
938	ripoff_t	*rsp;
939#endif
940	TPARM_STATE	tparm_state;
941	TTY		*saved_tty;	/* savetty/resetty information	    */
942#if NCURSES_NO_PADDING
943	bool		_no_padding;	/* flag to set if padding disabled  */
944#endif
945	NCURSES_SP_OUTC	_outch;		/* output handler if not putc */
946#if BROKEN_LINKER || USE_REENTRANT
947	chtype		*real_acs_map;
948	int		_LINES;
949	int		_COLS;
950	int		_TABSIZE;
951	int		_ESCDELAY;
952	TERMINAL	*_cur_term;
953#ifdef TRACE
954	long		_outchars;
955	const char	*_tputs_trace;
956#endif
957#endif
958	bool		use_tioctl;
959} NCURSES_PRESCREEN;
960
961/*
962 * Use screen-specific ripoff data (for softkeys) rather than global.
963 */
964#ifdef USE_SP_RIPOFF
965#define safe_ripoff_sp     (sp)->rsp
966#define safe_ripoff_stack  (sp)->rippedoff
967#else
968#define safe_ripoff_sp	   _nc_prescreen.rsp
969#define safe_ripoff_stack  _nc_prescreen.rippedoff
970#endif
971
972extern NCURSES_EXPORT_VAR(NCURSES_PRESCREEN) _nc_prescreen;
973
974/*
975 * The SCREEN structure.
976 */
977
978struct screen {
979	int		_ifd;		/* input file descriptor for screen */
980	int		_ofd;		/* output file descriptor for screen */
981	FILE		*_ofp;		/* output file ptr for screen	    */
982	char		*out_buffer;	/* output buffer		    */
983	size_t		out_limit;	/* output buffer size		    */
984	size_t		out_inuse;	/* output buffer current use	    */
985	bool		_filtered;	/* filter() was called		    */
986	bool		_prescreen;	/* is in prescreen phase	    */
987	bool		_use_env;	/* LINES & COLS from environment?   */
988	int		_checkfd;	/* filedesc for typeahead check	    */
989	TERMINAL	*_term;		/* terminal type information	    */
990	TTY		_saved_tty;	/* savetty/resetty information	    */
991	NCURSES_SIZE_T	_lines;		/* screen lines			    */
992	NCURSES_SIZE_T	_columns;	/* screen columns		    */
993
994	NCURSES_SIZE_T	_lines_avail;	/* lines available for stdscr	    */
995	NCURSES_SIZE_T	_topstolen;	/* lines stolen from top	    */
996
997	WINDOW		*_curscr;	/* current screen		    */
998	WINDOW		*_newscr;	/* virtual screen to be updated to  */
999	WINDOW		*_stdscr;	/* screen's full-window context	    */
1000
1001#define CurScreen(sp)  (sp)->_curscr
1002#define NewScreen(sp)  (sp)->_newscr
1003#define StdScreen(sp)  (sp)->_stdscr
1004
1005	TRIES		*_keytry;	/* "Try" for use with keypad mode   */
1006	TRIES		*_key_ok;	/* Disabled keys via keyok(,FALSE)  */
1007	bool		_tried;		/* keypad mode was initialized	    */
1008	bool		_keypad_on;	/* keypad mode is currently on	    */
1009
1010	bool		_called_wgetch;	/* check for recursion in wgetch()  */
1011	int		_fifo[FIFO_SIZE];	/* input push-back buffer   */
1012	short		_fifohead,	/* head of fifo queue		    */
1013			_fifotail,	/* tail of fifo queue		    */
1014			_fifopeek,	/* where to peek for next char	    */
1015			_fifohold;	/* set if breakout marked	    */
1016
1017	int		_endwin;	/* are we out of window mode?	    */
1018	NCURSES_CH_T	*_current_attr; /* holds current attributes set	    */
1019	int		_coloron;	/* is color enabled?		    */
1020	int		_color_defs;	/* are colors modified		    */
1021	int		_cursor;	/* visibility of the cursor	    */
1022	int		_cursrow;	/* physical cursor row		    */
1023	int		_curscol;	/* physical cursor column	    */
1024	bool		_notty;		/* true if we cannot switch non-tty */
1025	int		_nl;		/* True if NL -> CR/NL is on	    */
1026	int		_raw;		/* True if in raw mode		    */
1027	int		_cbreak;	/* 1 if in cbreak mode		    */
1028					/* > 1 if in halfdelay mode	    */
1029	int		_echo;		/* True if echo on		    */
1030	int		_use_meta;	/* use the meta key?		    */
1031	struct _SLK	*_slk;		/* ptr to soft key struct / NULL    */
1032	int		slk_format;	/* selected format for this screen  */
1033	/* cursor movement costs; units are 10ths of milliseconds */
1034#if NCURSES_NO_PADDING
1035	bool		_no_padding;	/* flag to set if padding disabled  */
1036#endif
1037	int		_char_padding;	/* cost of character put	    */
1038	int		_cr_cost;	/* cost of (carriage_return)	    */
1039	int		_cup_cost;	/* cost of (cursor_address)	    */
1040	int		_home_cost;	/* cost of (cursor_home)	    */
1041	int		_ll_cost;	/* cost of (cursor_to_ll)	    */
1042#if USE_HARD_TABS
1043	int		_ht_cost;	/* cost of (tab)		    */
1044	int		_cbt_cost;	/* cost of (backtab)		    */
1045#endif /* USE_HARD_TABS */
1046	int		_cub1_cost;	/* cost of (cursor_left)	    */
1047	int		_cuf1_cost;	/* cost of (cursor_right)	    */
1048	int		_cud1_cost;	/* cost of (cursor_down)	    */
1049	int		_cuu1_cost;	/* cost of (cursor_up)		    */
1050	int		_cub_cost;	/* cost of (parm_cursor_left)	    */
1051	int		_cuf_cost;	/* cost of (parm_cursor_right)	    */
1052	int		_cud_cost;	/* cost of (parm_cursor_down)	    */
1053	int		_cuu_cost;	/* cost of (parm_cursor_up)	    */
1054	int		_hpa_cost;	/* cost of (column_address)	    */
1055	int		_vpa_cost;	/* cost of (row_address)	    */
1056	/* used in tty_update.c, must be chars */
1057	int		_ed_cost;	/* cost of (clr_eos)		    */
1058	int		_el_cost;	/* cost of (clr_eol)		    */
1059	int		_el1_cost;	/* cost of (clr_bol)		    */
1060	int		_dch1_cost;	/* cost of (delete_character)	    */
1061	int		_ich1_cost;	/* cost of (insert_character)	    */
1062	int		_dch_cost;	/* cost of (parm_dch)		    */
1063	int		_ich_cost;	/* cost of (parm_ich)		    */
1064	int		_ech_cost;	/* cost of (erase_chars)	    */
1065	int		_rep_cost;	/* cost of (repeat_char)	    */
1066	int		_hpa_ch_cost;	/* cost of (column_address)	    */
1067	int		_cup_ch_cost;	/* cost of (cursor_address)	    */
1068	int		_cuf_ch_cost;	/* cost of (parm_cursor_right)	    */
1069	int		_inline_cost;	/* cost of inline-move		    */
1070	int		_smir_cost;	/* cost of (enter_insert_mode)	    */
1071	int		_rmir_cost;	/* cost of (exit_insert_mode)	    */
1072	int		_ip_cost;	/* cost of (insert_padding)	    */
1073	/* used in lib_mvcur.c */
1074	char *		_address_cursor;
1075	/* used in tty_update.c */
1076	int		_scrolling;	/* 1 if terminal's smart enough to  */
1077
1078	/* used in lib_color.c */
1079	color_t		*_color_table;	/* screen's color palette	     */
1080	int		_color_count;	/* count of colors in palette	     */
1081	colorpair_t	*_color_pairs;	/* screen's color pair list	     */
1082	int		_pair_count;	/* count of color pairs		     */
1083	int		_pair_limit;	/* actual limit of color-pairs       */
1084#if NCURSES_EXT_FUNCS
1085	bool		_assumed_color; /* use assumed colors		     */
1086	bool		_default_color; /* use default colors		     */
1087	bool		_has_sgr_39_49; /* has ECMA default color support    */
1088	int		_default_fg;	/* assumed default foreground	     */
1089	int		_default_bg;	/* assumed default background	     */
1090	int		_default_pairs;	/* count pairs using default color   */
1091#endif
1092	chtype		_ok_attributes; /* valid attributes for terminal     */
1093	chtype		_xmc_suppress;	/* attributes to suppress if xmc     */
1094	chtype		_xmc_triggers;	/* attributes to process if xmc	     */
1095	chtype *	_acs_map;	/* the real alternate-charset map    */
1096	bool *		_screen_acs_map;
1097
1098
1099	/* used in lib_vidattr.c */
1100	bool		_use_rmso;	/* true if we may use 'rmso'	     */
1101	bool		_use_rmul;	/* true if we may use 'rmul'	     */
1102#if USE_ITALIC
1103	bool		_use_ritm;	/* true if we may use 'ritm'	     */
1104#endif
1105
1106#if USE_KLIBC_KBD
1107	bool		_extended_key;	/* true if an extended key	     */
1108#endif
1109
1110	/*
1111	 * These data correspond to the state of the idcok() and idlok()
1112	 * functions.  A caveat is in order here:  the XSI and SVr4
1113	 * documentation specify that these functions apply to the window which
1114	 * is given as an argument.  However, ncurses implements this logic
1115	 * only for the newscr/curscr update process, _not_ per-window.
1116	 */
1117	bool		_nc_sp_idlok;
1118	bool		_nc_sp_idcok;
1119
1120	/*
1121	 * These are the data that support the mouse interface.
1122	 */
1123	bool		_mouse_initialized;
1124	MouseType	_mouse_type;
1125	int		_maxclick;
1126	bool		(*_mouse_event) (SCREEN *);
1127	bool		(*_mouse_inline)(SCREEN *);
1128	bool		(*_mouse_parse) (SCREEN *, int);
1129	void		(*_mouse_resume)(SCREEN *);
1130	void		(*_mouse_wrap)	(SCREEN *);
1131	int		_mouse_fd;	/* file-descriptor, if any */
1132	bool		_mouse_active;	/* true if initialized */
1133	mmask_t		_mouse_mask;	/* set via mousemask() */
1134	mmask_t		_mouse_mask2;	/* OR's in press/release bits */
1135	mmask_t		_mouse_bstate;
1136	NCURSES_CONST char *_mouse_xtermcap; /* string to enable/disable mouse */
1137	MEVENT		_mouse_events[EV_MAX];	/* hold the last mouse event seen */
1138	MEVENT		*_mouse_eventp;	/* next free slot in event queue */
1139
1140#if USE_GPM_SUPPORT
1141	bool		_mouse_gpm_loaded;
1142	bool		_mouse_gpm_found;
1143#ifdef HAVE_LIBDL
1144	void		*_dlopen_gpm;
1145	TYPE_gpm_fd	_mouse_gpm_fd;
1146	TYPE_Gpm_Open	_mouse_Gpm_Open;
1147	TYPE_Gpm_Close	_mouse_Gpm_Close;
1148	TYPE_Gpm_GetEvent _mouse_Gpm_GetEvent;
1149#endif
1150	Gpm_Connect	_mouse_gpm_connect;
1151#endif /* USE_GPM_SUPPORT */
1152
1153#if USE_EMX_MOUSE
1154	int		_emxmouse_wfd;
1155	int		_emxmouse_thread;
1156	int		_emxmouse_activated;
1157	char		_emxmouse_buttons[4];
1158#endif
1159
1160#if USE_SYSMOUSE
1161	MEVENT		_sysmouse_fifo[FIFO_SIZE];
1162	int		_sysmouse_head;
1163	int		_sysmouse_tail;
1164	int		_sysmouse_char_width;	/* character width */
1165	int		_sysmouse_char_height;	/* character height */
1166	int		_sysmouse_old_buttons;
1167	int		_sysmouse_new_buttons;
1168#endif
1169
1170#ifdef USE_TERM_DRIVER
1171	MEVENT		_drv_mouse_fifo[FIFO_SIZE];
1172	int		_drv_mouse_head;
1173	int		_drv_mouse_tail;
1174	int		_drv_mouse_old_buttons;
1175	int		_drv_mouse_new_buttons;
1176#endif
1177	/*
1178	 * This supports automatic resizing
1179	 */
1180#if USE_SIZECHANGE
1181	int		(*_resize)(NCURSES_SP_DCLx int y, int x);
1182	int		(*_ungetch)(SCREEN *, int);
1183#endif
1184
1185	/*
1186	 * These are data that support the proper handling of the panel stack on an
1187	 * per screen basis.
1188	 */
1189	struct panelhook _panelHook;
1190
1191	bool		_sig_winch;
1192	SCREEN		*_next_screen;
1193
1194	/* hashes for old and new lines */
1195	unsigned long	*oldhash, *newhash;
1196	HASHMAP		*hashtab;
1197	int		hashtab_len;
1198	int		*_oldnum_list;
1199	int		_oldnum_size;
1200
1201	NCURSES_SP_OUTC	_outch;		/* output handler if not putc */
1202
1203	int		_legacy_coding;	/* see use_legacy_coding() */
1204
1205#if USE_REENTRANT
1206	char		_ttytype[NAMESIZE];
1207	int		_ESCDELAY;
1208	int		_TABSIZE;
1209	int		_LINES;
1210	int		_COLS;
1211#ifdef TRACE
1212	long		_outchars;
1213	const char	*_tputs_trace;
1214#endif
1215#endif
1216
1217#ifdef TRACE
1218	char		tracechr_buf[40];
1219	char		tracemse_buf[TRACEMSE_MAX];
1220#endif
1221#ifdef USE_SP_WINDOWLIST
1222	WINDOWLIST*	_windowlist;
1223#define WindowList(sp)  (sp)->_windowlist
1224#endif
1225	NCURSES_OUTC	jump;
1226
1227	ripoff_t	rippedoff[N_RIPS];
1228	ripoff_t	*rsp;
1229
1230	/*
1231	 * ncurses/ncursesw are the same up to this point.
1232	 */
1233#if USE_WIDEC_SUPPORT
1234	/* recent versions of 'screen' have partially-working support for
1235	 * UTF-8, but do not permit ACS at the same time (see tty_update.c).
1236	 */
1237	bool		_screen_acs_fix;
1238	bool		_screen_unicode;
1239#endif
1240
1241	bool		_use_tioctl;
1242};
1243
1244extern NCURSES_EXPORT_VAR(SCREEN *) _nc_screen_chain;
1245extern NCURSES_EXPORT_VAR(SIG_ATOMIC_T) _nc_have_sigwinch;
1246
1247	WINDOWLIST {
1248	WINDOWLIST *next;
1249	SCREEN *screen;		/* screen containing the window */
1250	WINDOW	win;		/* WINDOW_EXT() needs to account for offset */
1251#if NCURSES_WIDECHAR
1252	char addch_work[(MB_LEN_MAX * 9) + 1];
1253	unsigned addch_used;	/* number of bytes in addch_work[] */
1254	int addch_x;		/* x-position for addch_work[] */
1255	int addch_y;		/* y-position for addch_work[] */
1256#endif
1257};
1258
1259#define WINDOW_EXT(w,m) (((WINDOWLIST *)((void *)((char *)(w) - offsetof(WINDOWLIST, win))))->m)
1260
1261#define SP_PRE_INIT(sp)                         \
1262    sp->_cursrow = -1;                          \
1263    sp->_curscol = -1;                          \
1264    sp->_nl = TRUE;                             \
1265    sp->_raw = FALSE;                           \
1266    sp->_cbreak = 0;                            \
1267    sp->_echo = TRUE;                           \
1268    sp->_fifohead = -1;                         \
1269    sp->_endwin = TRUE;                         \
1270    sp->_cursor = -1;                           \
1271    WindowList(sp) = 0;                         \
1272    sp->_outch = NCURSES_OUTC_FUNC;             \
1273    sp->jump = 0                                \
1274
1275/* usually in <limits.h> */
1276#ifndef UCHAR_MAX
1277#define UCHAR_MAX 255
1278#endif
1279
1280/* The terminfo source is assumed to be 7-bit ASCII */
1281#define is7bits(c)	((unsigned)(c) < 128)
1282
1283/* Checks for isprint() should be done on 8-bit characters (non-wide) */
1284#define is8bits(c)	((unsigned)(c) <= UCHAR_MAX)
1285
1286#ifndef min
1287#define min(a,b)	((a) > (b)  ?  (b)  :  (a))
1288#endif
1289
1290#ifndef max
1291#define max(a,b)	((a) < (b)  ?  (b)  :  (a))
1292#endif
1293
1294/* usually in <unistd.h> */
1295#ifndef STDIN_FILENO
1296#define STDIN_FILENO 0
1297#endif
1298
1299#ifndef STDOUT_FILENO
1300#define STDOUT_FILENO 1
1301#endif
1302
1303#ifndef STDERR_FILENO
1304#define STDERR_FILENO 2
1305#endif
1306
1307#ifndef EXIT_SUCCESS
1308#define EXIT_SUCCESS 0
1309#endif
1310
1311#ifndef EXIT_FAILURE
1312#define EXIT_FAILURE 1
1313#endif
1314
1315#ifndef R_OK
1316#define	R_OK	4		/* Test for read permission.  */
1317#endif
1318#ifndef W_OK
1319#define	W_OK	2		/* Test for write permission.  */
1320#endif
1321#ifndef X_OK
1322#define	X_OK	1		/* Test for execute permission.  */
1323#endif
1324#ifndef F_OK
1325#define	F_OK	0		/* Test for existence.  */
1326#endif
1327
1328#if HAVE_FCNTL_H
1329#include <fcntl.h>		/* may define O_BINARY	*/
1330#endif
1331
1332#ifndef O_BINARY
1333#define O_BINARY 0
1334#endif
1335
1336#ifdef TRACE
1337#if USE_REENTRANT
1338#define COUNT_OUTCHARS(n) _nc_count_outchars(n);
1339#else
1340#define COUNT_OUTCHARS(n) _nc_outchars += (n);
1341#endif
1342#else
1343#define COUNT_OUTCHARS(n) /* nothing */
1344#endif
1345
1346#define RESET_OUTCHARS() COUNT_OUTCHARS(-_nc_outchars)
1347
1348#define UChar(c)	((unsigned char)(c))
1349#define UShort(c)	((unsigned short)(c))
1350#define ChCharOf(c)	((chtype)(c) & (chtype)A_CHARTEXT)
1351#define ChAttrOf(c)	((chtype)(c) & (chtype)A_ATTRIBUTES)
1352
1353#ifndef MB_LEN_MAX
1354#define MB_LEN_MAX 8 /* should be >= MB_CUR_MAX, but that may be a function */
1355#endif
1356
1357#if USE_WIDEC_SUPPORT /* { */
1358#define isEILSEQ(status) (((size_t)status == (size_t)-1) && (errno == EILSEQ))
1359
1360#define init_mb(state)	memset(&state, 0, sizeof(state))
1361
1362#if NCURSES_EXT_COLORS
1363#define NulColor	, 0
1364#else
1365#define NulColor	/* nothing */
1366#endif
1367
1368#define NulChar		0,0,0,0	/* FIXME: see CCHARW_MAX */
1369#define CharOf(c)	((c).chars[0])
1370#define AttrOf(c)	((c).attr)
1371
1372#define AddAttr(c,a)	AttrOf(c) |=  ((a) & A_ATTRIBUTES)
1373#define RemAttr(c,a)	AttrOf(c) &= ~((a) & A_ATTRIBUTES)
1374#define SetAttr(c,a)	AttrOf(c) =   ((a) & A_ATTRIBUTES) | WidecExt(c)
1375
1376#define NewChar2(c,a)	{ a, { c, NulChar } NulColor }
1377#define NewChar(ch)	NewChar2(ChCharOf(ch), ChAttrOf(ch))
1378
1379#if CCHARW_MAX == 5
1380#define CharEq(a,b)	(((a).attr == (b).attr) \
1381		       && (a).chars[0] == (b).chars[0] \
1382		       && (a).chars[1] == (b).chars[1] \
1383		       && (a).chars[2] == (b).chars[2] \
1384		       && (a).chars[3] == (b).chars[3] \
1385		       && (a).chars[4] == (b).chars[4] \
1386			if_EXT_COLORS(&& (a).ext_color == (b).ext_color))
1387#else
1388#define CharEq(a,b)	(!memcmp(&(a), &(b), sizeof(a)))
1389#endif
1390
1391#define SetChar(ch,c,a) do {							    \
1392			    NCURSES_CH_T *_cp = &ch;				    \
1393			    memset(_cp, 0, sizeof(ch));				    \
1394			    _cp->chars[0] = (wchar_t) (c);			    \
1395			    _cp->attr = (a);					    \
1396			    if_EXT_COLORS(SetPair(ch, PairNumber(a)));		    \
1397			} while (0)
1398#define CHREF(wch)	(&wch)
1399#define CHDEREF(wch)	(*wch)
1400#define ARG_CH_T	NCURSES_CH_T *
1401#define CARG_CH_T	const NCURSES_CH_T *
1402#define PUTC_DATA	char PUTC_buf[MB_LEN_MAX]; int PUTC_i, PUTC_n; \
1403			mbstate_t PUT_st; wchar_t PUTC_ch
1404#define PUTC_INIT	init_mb (PUT_st)
1405#define PUTC(ch)	do { if(!isWidecExt(ch)) {				    \
1406			if (Charable(ch)) {					    \
1407			    NCURSES_OUTC_FUNC (NCURSES_SP_ARGx CharOf(ch)); \
1408			    COUNT_OUTCHARS(1);					    \
1409			} else {						    \
1410			    PUTC_INIT;						    \
1411			    for (PUTC_i = 0; PUTC_i < CCHARW_MAX; ++PUTC_i) {	    \
1412				PUTC_ch = (ch).chars[PUTC_i];			    \
1413				if (PUTC_ch == L'\0')				    \
1414				    break;					    \
1415				PUTC_n = (int) wcrtomb(PUTC_buf,		    \
1416						       (ch).chars[PUTC_i], &PUT_st); \
1417				if (PUTC_n <= 0) {				    \
1418				    if (PUTC_ch && is8bits(PUTC_ch) && PUTC_i == 0) \
1419					NCURSES_OUTC_FUNC (NCURSES_SP_ARGx CharOf(ch)); \
1420				    break;					    \
1421				} else {					    \
1422				    int PUTC_j;					    \
1423				    for (PUTC_j = 0; PUTC_j < PUTC_n; ++PUTC_j) {   \
1424					NCURSES_OUTC_FUNC (NCURSES_SP_ARGx PUTC_buf[PUTC_j]); \
1425				    }						    \
1426				}						    \
1427			    }							    \
1428			    COUNT_OUTCHARS(PUTC_i);				    \
1429			} } } while (0)
1430
1431#define BLANK		NewChar2(' ', WA_NORMAL)
1432#define ZEROS		NewChar2('\0', WA_NORMAL)
1433#define ISBLANK(ch)	((ch).chars[0] == L' ' && (ch).chars[1] == L'\0')
1434
1435	/*
1436	 * Wide characters cannot be represented in the A_CHARTEXT mask of
1437	 * attr_t's but an application might have set a narrow character there.
1438	 * But even in that case, it would only be a printable character, or
1439	 * zero.  Otherwise we can use those bits to tell if a cell is the
1440	 * first or extension part of a wide character.
1441	 */
1442#define WidecExt(ch)	(int) (AttrOf(ch) & A_CHARTEXT)
1443#define isWidecBase(ch)	(WidecExt(ch) == 1)
1444#define isWidecExt(ch)	(WidecExt(ch) > 1 && WidecExt(ch) < 32)
1445#define SetWidecExt(dst, ext)	AttrOf(dst) &= ~A_CHARTEXT,		\
1446				AttrOf(dst) |= (attr_t) (ext + 1)
1447
1448#define if_WIDEC(code)  code
1449#define Charable(ch)	((SP_PARM->_legacy_coding)			\
1450			 || (AttrOf(ch) & A_ALTCHARSET)			\
1451			 || (!isWidecExt(ch) &&				\
1452			     (ch).chars[1] == L'\0' &&			\
1453			     _nc_is_charable(CharOf(ch))))
1454
1455#define L(ch)		L ## ch
1456#else /* }{ */
1457#define CharOf(c)	ChCharOf(c)
1458#define AttrOf(c)	ChAttrOf(c)
1459#define AddAttr(c,a)	c |= (a)
1460#define RemAttr(c,a)	c &= ~((a) & A_ATTRIBUTES)
1461#define SetAttr(c,a)	c = ((c) & ~A_ATTRIBUTES) | (a)
1462#define NewChar(ch)	(ch)
1463#define NewChar2(c,a)	((c) | (a))
1464#define CharEq(a,b)	((a) == (b))
1465#define SetChar(ch,c,a)	ch = (c) | (a)
1466#define CHREF(wch)	wch
1467#define CHDEREF(wch)	wch
1468#define ARG_CH_T	NCURSES_CH_T
1469#define CARG_CH_T	NCURSES_CH_T
1470#define PUTC_DATA	/* nothing */
1471#define PUTC(ch)	NCURSES_OUTC_FUNC (NCURSES_SP_ARGx (int) ch)
1472
1473#define BLANK		(' '|A_NORMAL)
1474#define ZEROS		('\0'|A_NORMAL)
1475#define ISBLANK(ch)	(CharOf(ch) == ' ')
1476
1477#define isWidecExt(ch)	(0)
1478#define if_WIDEC(code) /* nothing */
1479
1480#define L(ch)		ch
1481#endif /* } */
1482
1483#define AttrOfD(ch)	AttrOf(CHDEREF(ch))
1484#define CharOfD(ch)	CharOf(CHDEREF(ch))
1485#define SetChar2(wch,ch)    SetChar(wch,ChCharOf(ch),ChAttrOf(ch))
1486
1487#define BLANK_ATTR	A_NORMAL
1488#define BLANK_TEXT	L(' ')
1489
1490#define CHANGED     -1
1491
1492#define LEGALYX(w, y, x) \
1493	      ((w) != 0 && \
1494		((x) >= 0 && (x) <= (w)->_maxx && \
1495		 (y) >= 0 && (y) <= (w)->_maxy))
1496
1497#define CHANGED_CELL(line,col) \
1498	if (line->firstchar == _NOCHANGE) \
1499		line->firstchar = line->lastchar = (NCURSES_SIZE_T) (col); \
1500	else if ((col) < line->firstchar) \
1501		line->firstchar = (NCURSES_SIZE_T) (col); \
1502	else if ((col) > line->lastchar) \
1503		line->lastchar = (NCURSES_SIZE_T) (col)
1504
1505#define CHANGED_RANGE(line,start,end) \
1506	if (line->firstchar == _NOCHANGE \
1507	 || line->firstchar > (start)) \
1508		line->firstchar = (NCURSES_SIZE_T) (start); \
1509	if (line->lastchar == _NOCHANGE \
1510	 || line->lastchar < (end)) \
1511		line->lastchar = (NCURSES_SIZE_T) (end)
1512
1513#define CHANGED_TO_EOL(line,start,end) \
1514	if (line->firstchar == _NOCHANGE \
1515	 || line->firstchar > (start)) \
1516		line->firstchar = (NCURSES_SIZE_T) (start); \
1517	line->lastchar = (NCURSES_SIZE_T) (end)
1518
1519#define SIZEOF(v) (sizeof(v)/sizeof(v[0]))
1520
1521#define FreeIfNeeded(p)  if ((p) != 0) free(p)
1522
1523/* FreeAndNull() is not a comma-separated expression because some compilers
1524 * do not accept a mixture of void with values.
1525 */
1526#define FreeAndNull(p)   free(p); p = 0
1527
1528#include <nc_alloc.h>
1529
1530/*
1531 * Use these for tic/infocmp malloc failures.  Generally the ncurses library
1532 * tries to limp along after a failure.
1533 */
1534#define TYPE_MALLOC(type, size, name) \
1535	name = typeMalloc(type, size); \
1536	if (name == 0) \
1537	    _nc_err_abort(MSG_NO_MEMORY)
1538
1539#define TYPE_REALLOC(type, size, name) \
1540	name = typeRealloc(type, size, name); \
1541	if (name == 0) \
1542	    _nc_err_abort(MSG_NO_MEMORY)
1543
1544/*
1545 * TTY bit definition for converting tabs to spaces.
1546 */
1547#ifdef TAB3
1548# define OFLAGS_TABS TAB3	/* POSIX specifies TAB3 */
1549#else
1550# ifdef XTABS
1551#  define OFLAGS_TABS XTABS	/* XTABS is usually the "same" */
1552# else
1553#  ifdef OXTABS
1554#   define OFLAGS_TABS OXTABS	/* the traditional BSD equivalent */
1555#  else
1556#   define OFLAGS_TABS 0
1557#  endif
1558# endif
1559#endif
1560
1561/*
1562 * Standardize/simplify common loops
1563 */
1564#define each_screen(p) p = _nc_screen_chain; p != 0; p = (p)->_next_screen
1565#define each_window(sp,p) p = WindowList(sp); p != 0; p = (p)->next
1566#define each_ripoff(p) p = safe_ripoff_stack; (p - safe_ripoff_stack) < N_RIPS; ++p
1567
1568/*
1569 * Prefixes for call/return points of library function traces.  We use these to
1570 * instrument the public functions so that the traces can be easily transformed
1571 * into regression scripts.
1572 */
1573#define T_CALLED(fmt) "called {" fmt
1574#define T_CREATE(fmt) "create :" fmt
1575#define T_RETURN(fmt) "return }" fmt
1576
1577#ifdef TRACE
1578
1579#if USE_REENTRANT
1580#define TPUTS_TRACE(s)	_nc_set_tputs_trace(s);
1581#else
1582#define TPUTS_TRACE(s)	_nc_tputs_trace = s;
1583#endif
1584
1585#define START_TRACE() \
1586	if ((_nc_tracing & TRACE_MAXIMUM) == 0) { \
1587	    int t = _nc_getenv_num("NCURSES_TRACE"); \
1588	    if (t >= 0) \
1589		trace((unsigned) t); \
1590	}
1591
1592/*
1593 * Many of the _tracef() calls use static buffers; lock the trace state before
1594 * trying to fill them.
1595 */
1596#if USE_REENTRANT
1597#define USE_TRACEF(mask) _nc_use_tracef(mask)
1598extern NCURSES_EXPORT(int)	_nc_use_tracef (unsigned);
1599extern NCURSES_EXPORT(void)	_nc_locked_tracef (const char *, ...) GCC_PRINTFLIKE(1,2);
1600#else
1601#define USE_TRACEF(mask) (_nc_tracing & (mask))
1602#define _nc_locked_tracef _tracef
1603#endif
1604
1605#define TR(n, a)	if (USE_TRACEF(n)) _nc_locked_tracef a
1606#define T(a)		TR(TRACE_CALLS, a)
1607#define TRACE_RETURN(value,type)     return _nc_retrace_##type(value)
1608#define TRACE_RETURN2(value,dst,src) return _nc_retrace_##dst##_##src(value)
1609#define TRACE_RETURN_SP(value,type)  return _nc_retrace_##type(SP_PARM, value)
1610
1611#define NonNull(s)	((s) != 0 ? s : "<null>")
1612
1613#define returnAttr(code)	TRACE_RETURN(code,attr_t)
1614#define returnBits(code)	TRACE_RETURN(code,unsigned)
1615#define returnBool(code)	TRACE_RETURN(code,bool)
1616#define returnCPtr(code)	TRACE_RETURN(code,cptr)
1617#define returnCVoidPtr(code)	TRACE_RETURN(code,cvoid_ptr)
1618#define returnChar(code)	TRACE_RETURN(code,char)
1619#define returnChtype(code)	TRACE_RETURN(code,chtype)
1620#define returnCode(code)	TRACE_RETURN(code,int)
1621#define returnIntAttr(code)	TRACE_RETURN2(code,int,attr_t)
1622#define returnMMask(code)	TRACE_RETURN_SP(code,mmask_t)
1623#define returnPtr(code)		TRACE_RETURN(code,ptr)
1624#define returnSP(code)		TRACE_RETURN(code,sp)
1625#define returnVoid		T((T_RETURN(""))); return
1626#define returnVoidPtr(code)	TRACE_RETURN(code,void_ptr)
1627#define returnWin(code)		TRACE_RETURN(code,win)
1628
1629extern NCURSES_EXPORT(NCURSES_BOOL)     _nc_retrace_bool (int);
1630extern NCURSES_EXPORT(NCURSES_CONST void *) _nc_retrace_cvoid_ptr (NCURSES_CONST void *);
1631extern NCURSES_EXPORT(SCREEN *)         _nc_retrace_sp (SCREEN *);
1632extern NCURSES_EXPORT(WINDOW *)         _nc_retrace_win (WINDOW *);
1633extern NCURSES_EXPORT(attr_t)           _nc_retrace_attr_t (attr_t);
1634extern NCURSES_EXPORT(char *)           _nc_retrace_ptr (char *);
1635extern NCURSES_EXPORT(char *)           _nc_trace_ttymode(TTY *tty);
1636extern NCURSES_EXPORT(char *)           _nc_varargs (const char *, va_list);
1637extern NCURSES_EXPORT(chtype)           _nc_retrace_chtype (chtype);
1638extern NCURSES_EXPORT(const char *)     _nc_altcharset_name(attr_t, chtype);
1639extern NCURSES_EXPORT(const char *)     _nc_retrace_cptr (const char *);
1640extern NCURSES_EXPORT(char)             _nc_retrace_char (int);
1641extern NCURSES_EXPORT(int)              _nc_retrace_int (int);
1642extern NCURSES_EXPORT(int)              _nc_retrace_int_attr_t (attr_t);
1643extern NCURSES_EXPORT(mmask_t)          _nc_retrace_mmask_t (SCREEN *, mmask_t);
1644extern NCURSES_EXPORT(unsigned)         _nc_retrace_unsigned (unsigned);
1645extern NCURSES_EXPORT(void *)           _nc_retrace_void_ptr (void *);
1646extern NCURSES_EXPORT(void)             _nc_fifo_dump (SCREEN *);
1647
1648#if USE_REENTRANT
1649NCURSES_WRAPPED_VAR(long, _nc_outchars);
1650NCURSES_WRAPPED_VAR(const char *, _nc_tputs_trace);
1651#define _nc_outchars       NCURSES_PUBLIC_VAR(_nc_outchars())
1652#define _nc_tputs_trace    NCURSES_PUBLIC_VAR(_nc_tputs_trace())
1653extern NCURSES_EXPORT(void)		_nc_set_tputs_trace (const char *);
1654extern NCURSES_EXPORT(void)		_nc_count_outchars (long);
1655#else
1656extern NCURSES_EXPORT_VAR(const char *) _nc_tputs_trace;
1657extern NCURSES_EXPORT_VAR(long)         _nc_outchars;
1658#endif
1659
1660extern NCURSES_EXPORT_VAR(unsigned)     _nc_tracing;
1661
1662#if USE_WIDEC_SUPPORT
1663extern NCURSES_EXPORT(const char *) _nc_viswbuf2 (int, const wchar_t *);
1664extern NCURSES_EXPORT(const char *) _nc_viswbufn (const wchar_t *, int);
1665#endif
1666
1667extern NCURSES_EXPORT(const char *) _nc_viscbuf2 (int, const NCURSES_CH_T *, int);
1668extern NCURSES_EXPORT(const char *) _nc_viscbuf (const NCURSES_CH_T *, int);
1669
1670#else /* !TRACE */
1671
1672#define START_TRACE() /* nothing */
1673
1674#define T(a)
1675#define TR(n, a)
1676#define TPUTS_TRACE(s)
1677
1678#define returnAttr(code)	return code
1679#define returnBits(code)	return code
1680#define returnBool(code)	return code
1681#define returnCPtr(code)	return code
1682#define returnCVoidPtr(code)	return code
1683#define returnChar(code)	return ((char) code)
1684#define returnChtype(code)	return code
1685#define returnCode(code)	return code
1686#define returnIntAttr(code)	return code
1687#define returnMMask(code)	return code
1688#define returnPtr(code)		return code
1689#define returnSP(code)		return code
1690#define returnVoid		return
1691#define returnVoidPtr(code)	return code
1692#define returnWin(code)		return code
1693
1694#endif /* TRACE/!TRACE */
1695
1696/*
1697 * Workaround for defective implementation of gcc attribute warn_unused_result
1698 */
1699#if defined(__GNUC__) && defined(_FORTIFY_SOURCE)
1700#define IGNORE_RC(func) errno = (int) func
1701#else
1702#define IGNORE_RC(func) (void) func
1703#endif /* gcc workarounds */
1704
1705/*
1706 * Return-codes for tgetent() and friends.
1707 */
1708#define TGETENT_YES  1		/* entry is found */
1709#define TGETENT_NO   0		/* entry is not found */
1710#define TGETENT_ERR -1		/* an error occurred */
1711
1712extern NCURSES_EXPORT(const char *) _nc_visbuf2 (int, const char *);
1713extern NCURSES_EXPORT(const char *) _nc_visbufn (const char *, int);
1714
1715#define EMPTY_MODULE(name) \
1716extern	NCURSES_EXPORT(void) name (void); \
1717	NCURSES_EXPORT(void) name (void) { }
1718
1719#define ALL_BUT_COLOR ((chtype)~(A_COLOR))
1720#define NONBLANK_ATTR (A_BOLD | A_DIM | A_BLINK | A_ITALIC)
1721#define TPARM_ATTR    (A_STANDOUT | A_UNDERLINE | A_REVERSE | A_BLINK | A_DIM | A_BOLD | A_ALTCHARSET | A_INVIS | A_PROTECT)
1722#define XMC_CONFLICT  (A_STANDOUT | A_UNDERLINE | A_REVERSE | A_BLINK | A_DIM | A_BOLD | A_INVIS | A_PROTECT | A_ITALIC)
1723#define XMC_CHANGES(c) ((c) & SP_PARM->_xmc_suppress)
1724
1725#define toggle_attr_on(S,at) {\
1726   if (PairNumber(at) > 0) {\
1727      (S) = ((S) & ALL_BUT_COLOR) | (attr_t) (at);\
1728   } else {\
1729      (S) |= (attr_t) (at);\
1730   }\
1731   TR(TRACE_ATTRS, ("new attribute is %s", _traceattr((S))));}
1732
1733
1734#define toggle_attr_off(S,at) {\
1735   if (PairNumber(at) > 0) {\
1736      (S) &= ~(at|A_COLOR);\
1737   } else {\
1738      (S) &= ~(at);\
1739   }\
1740   TR(TRACE_ATTRS, ("new attribute is %s", _traceattr((S))));}
1741
1742#define DelCharCost(sp,count) \
1743		((parm_dch != 0) \
1744		? sp->_dch_cost \
1745		: ((delete_character != 0) \
1746			? (sp->_dch1_cost * count) \
1747			: INFINITY))
1748
1749#define InsCharCost(sp,count) \
1750		((parm_ich != 0) \
1751		? sp->_ich_cost \
1752		: ((enter_insert_mode && exit_insert_mode) \
1753		  ? sp->_smir_cost + sp->_rmir_cost + (sp->_ip_cost * count) \
1754		  : ((insert_character != 0) \
1755		    ? ((sp->_ich1_cost + sp->_ip_cost) * count) \
1756		    : INFINITY)))
1757
1758#if USE_XMC_SUPPORT
1759#define UpdateAttrs(sp,c) if (!SameAttrOf(SCREEN_ATTRS(sp), c)) { \
1760				attr_t chg = AttrOf(SCREEN_ATTRS(sp)); \
1761				VIDATTR(sp, AttrOf(c), GetPair(c)); \
1762				if (magic_cookie_glitch > 0 \
1763				 && XMC_CHANGES((chg ^ AttrOf(SCREEN_ATTRS(sp))))) { \
1764					T(("%s @%d before glitch %d,%d", \
1765						__FILE__, __LINE__, \
1766						sp->_cursrow, \
1767						sp->_curscol)); \
1768					NCURSES_SP_NAME(_nc_do_xmc_glitch)(NCURSES_SP_ARGx chg); \
1769				} \
1770			}
1771#else
1772#define UpdateAttrs(sp,c) if (!SameAttrOf(SCREEN_ATTRS(sp), c)) { \
1773				    VIDATTR(sp, AttrOf(c), GetPair(c)); \
1774			}
1775#endif
1776
1777/*
1778 * Macros to make additional parameter to implement wgetch_events()
1779 */
1780#ifdef NCURSES_WGETCH_EVENTS
1781#define EVENTLIST_0th(param) param
1782#define EVENTLIST_1st(param) param
1783#define EVENTLIST_2nd(param) , param
1784#define TWAIT_MASK (TW_ANY | TW_EVENT)
1785#else
1786#define EVENTLIST_0th(param) void
1787#define EVENTLIST_1st(param) /* nothing */
1788#define EVENTLIST_2nd(param) /* nothing */
1789#define TWAIT_MASK TW_ANY
1790#endif
1791
1792#if NCURSES_EXPANDED && NCURSES_EXT_FUNCS
1793
1794#undef  toggle_attr_on
1795#define toggle_attr_on(S,at) _nc_toggle_attr_on(&(S), at)
1796extern NCURSES_EXPORT(void) _nc_toggle_attr_on (attr_t *, attr_t);
1797
1798#undef  toggle_attr_off
1799#define toggle_attr_off(S,at) _nc_toggle_attr_off(&(S), at)
1800extern NCURSES_EXPORT(void) _nc_toggle_attr_off (attr_t *, attr_t);
1801
1802#undef  DelCharCost
1803#define DelCharCost(sp, count) NCURSES_SP_NAME(_nc_DelCharCost)(NCURSES_SP_ARGx count)
1804
1805#undef  InsCharCost
1806#define InsCharCost(sp, count) NCURSES_SP_NAME(_nc_InsCharCost)(NCURSES_SP_ARGx count)
1807
1808extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_DelCharCost) (NCURSES_SP_DCLx int _c);
1809extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_InsCharCost) (NCURSES_SP_DCLx int _c);
1810
1811#undef  UpdateAttrs
1812#define UpdateAttrs(sp,c) NCURSES_SP_NAME(_nc_UpdateAttrs)(NCURSES_SP_ARGx CHREF(c))
1813
1814#if USE_WIDEC_SUPPORT || defined(NEED_NCURSES_CH_T)
1815extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_UpdateAttrs) (NCURSES_SP_DCLx CARG_CH_T _c);
1816#else
1817extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_UpdateAttrs) (NCURSES_SP_DCLx chtype c);
1818#endif
1819
1820#if NCURSES_SP_FUNCS
1821extern NCURSES_EXPORT(int) _nc_DelCharCost (int);
1822extern NCURSES_EXPORT(int) _nc_InsCharCost (int);
1823extern NCURSES_EXPORT(void) _nc_UpdateAttrs (CARG_CH_T);
1824#endif /* NCURSES_SP_FUNCS */
1825
1826#else
1827
1828extern NCURSES_EXPORT(void) _nc_expanded (void);
1829
1830#endif
1831
1832#if !NCURSES_EXT_FUNCS
1833#define set_escdelay(value) ESCDELAY = value
1834#endif
1835
1836#if !HAVE_GETCWD
1837#define getcwd(buf,len) getwd(buf)
1838#endif
1839
1840/* charable.c */
1841#if USE_WIDEC_SUPPORT
1842extern NCURSES_EXPORT(bool) _nc_is_charable(wchar_t);
1843extern NCURSES_EXPORT(int) _nc_to_char(wint_t);
1844extern NCURSES_EXPORT(wint_t) _nc_to_widechar(int);
1845#endif
1846
1847/* comp_captab.c */
1848typedef struct {
1849	short	nte_name;	/* offset of name to hash on */
1850	int	nte_type;	/* BOOLEAN, NUMBER or STRING */
1851	short	nte_index;	/* index of associated variable in its array */
1852	short	nte_link;	/* index in table of next hash, or -1 */
1853} name_table_data;
1854
1855typedef struct
1856{
1857	short	from;
1858	short	to;
1859	short	source;
1860} alias_table_data;
1861
1862/* doupdate.c */
1863#if USE_XMC_SUPPORT
1864extern NCURSES_EXPORT(void) _nc_do_xmc_glitch (attr_t);
1865#endif
1866
1867/* hardscroll.c */
1868#if defined(TRACE) || defined(SCROLLDEBUG) || defined(HASHDEBUG)
1869extern NCURSES_EXPORT(void) _nc_linedump (void);
1870#endif
1871
1872/* lib_acs.c */
1873extern NCURSES_EXPORT(void) _nc_init_acs (void); /* corresponds to traditional 'init_acs()' */
1874extern NCURSES_EXPORT(int)  _nc_msec_cost (const char *const, int);  /* used by 'tack' program */
1875
1876/* lib_addch.c */
1877#if USE_WIDEC_SUPPORT
1878NCURSES_EXPORT(int) _nc_build_wch(WINDOW *win, ARG_CH_T ch);
1879#endif
1880
1881/* lib_addstr.c */
1882#if USE_WIDEC_SUPPORT && !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
1883extern NCURSES_EXPORT(int) _nc_wchstrlen(const cchar_t *);
1884#endif
1885
1886/* lib_color.c */
1887extern NCURSES_EXPORT(bool) _nc_reset_colors(void);
1888
1889/* lib_getch.c */
1890extern NCURSES_EXPORT(int) _nc_wgetch(WINDOW *, int *, int EVENTLIST_2nd(_nc_eventlist *));
1891
1892/* lib_insch.c */
1893extern NCURSES_EXPORT(int) _nc_insert_ch(SCREEN *, WINDOW *, chtype);
1894
1895/* lib_mvcur.c */
1896#define INFINITY	1000000	/* cost: too high to use */
1897
1898extern NCURSES_EXPORT(int) _nc_mvcur(int yold, int xold, int ynew, int xnew);
1899
1900extern NCURSES_EXPORT(void) _nc_mvcur_init (void);
1901extern NCURSES_EXPORT(void) _nc_mvcur_resume (void);
1902extern NCURSES_EXPORT(void) _nc_mvcur_wrap (void);
1903
1904extern NCURSES_EXPORT(int) _nc_scrolln (int, int, int, int);
1905
1906extern NCURSES_EXPORT(void) _nc_screen_init (void);
1907extern NCURSES_EXPORT(void) _nc_screen_resume (void);
1908extern NCURSES_EXPORT(void) _nc_screen_wrap (void);
1909
1910/* lib_mouse.c */
1911extern NCURSES_EXPORT(bool) _nc_has_mouse (SCREEN *);
1912
1913/* lib_mvcur.c */
1914#define INFINITY	1000000	/* cost: too high to use */
1915#define BAUDBYTE	9	/* 9 = 7 bits + 1 parity + 1 stop */
1916
1917/* lib_setup.c */
1918extern NCURSES_EXPORT(char *) _nc_get_locale(void);
1919extern NCURSES_EXPORT(int)    _nc_unicode_locale(void);
1920extern NCURSES_EXPORT(int)    _nc_locale_breaks_acs(TERMINAL *);
1921extern NCURSES_EXPORT(int)    _nc_setupterm(NCURSES_CONST char *, int, int *, int);
1922extern NCURSES_EXPORT(void)   _nc_tinfo_cmdch(TERMINAL *, int);
1923
1924/* lib_set_term.c */
1925extern NCURSES_EXPORT(int)    _nc_ripoffline(int, int(*)(WINDOW*, int));
1926
1927/* lib_setup.c */
1928#define ret_error(code, fmt, arg)	if (errret) {\
1929					    *errret = code;\
1930					    returnCode(ERR);\
1931					} else {\
1932					    fprintf(stderr, fmt, arg);\
1933					    exit(EXIT_FAILURE);\
1934					}
1935
1936#define ret_error1(code, fmt, arg)	ret_error(code, "'%s': " fmt, arg)
1937
1938#define ret_error0(code, msg)		if (errret) {\
1939					    *errret = code;\
1940					    returnCode(ERR);\
1941					} else {\
1942					    fprintf(stderr, msg);\
1943					    exit(EXIT_FAILURE);\
1944					}
1945
1946/* lib_tstp.c */
1947#if USE_SIGWINCH
1948extern NCURSES_EXPORT(int) _nc_handle_sigwinch(SCREEN *);
1949#else
1950#define _nc_handle_sigwinch(a) /* nothing */
1951#endif
1952
1953/* lib_wacs.c */
1954#if USE_WIDEC_SUPPORT
1955extern NCURSES_EXPORT(void) _nc_init_wacs(void);
1956#endif
1957
1958typedef struct {
1959    char *s_head;	/* beginning of the string (may be null) */
1960    char *s_tail;	/* end of the string (may be null) */
1961    size_t s_size;	/* current remaining size available */
1962    size_t s_init;	/* total size available */
1963} string_desc;
1964
1965/* strings.c */
1966extern NCURSES_EXPORT(string_desc *) _nc_str_init (string_desc *, char *, size_t);
1967extern NCURSES_EXPORT(string_desc *) _nc_str_null (string_desc *, size_t);
1968extern NCURSES_EXPORT(string_desc *) _nc_str_copy (string_desc *, string_desc *);
1969extern NCURSES_EXPORT(bool) _nc_safe_strcat (string_desc *, const char *);
1970extern NCURSES_EXPORT(bool) _nc_safe_strcpy (string_desc *, const char *);
1971
1972#if !HAVE_STRSTR
1973#define strstr _nc_strstr
1974extern NCURSES_EXPORT(char *) _nc_strstr (const char *, const char *);
1975#endif
1976
1977/* safe_sprintf.c */
1978extern NCURSES_EXPORT(char *) _nc_printf_string (const char *, va_list);
1979
1980/* tries.c */
1981extern NCURSES_EXPORT(int) _nc_add_to_try (TRIES **, const char *, unsigned);
1982extern NCURSES_EXPORT(char *) _nc_expand_try (TRIES *, unsigned, int *, size_t);
1983extern NCURSES_EXPORT(int) _nc_remove_key (TRIES **, unsigned);
1984extern NCURSES_EXPORT(int) _nc_remove_string (TRIES **, const char *);
1985
1986/* elsewhere ... */
1987extern NCURSES_EXPORT(ENTRY *) _nc_delink_entry (ENTRY *, TERMTYPE *);
1988extern NCURSES_EXPORT(SCREEN *) _nc_screen_of (WINDOW *);
1989extern NCURSES_EXPORT(TERMINAL*) _nc_get_cur_term (void);
1990extern NCURSES_EXPORT(WINDOW *) _nc_makenew (int, int, int, int, int);
1991extern NCURSES_EXPORT(char *) _nc_trace_buf (int, size_t);
1992extern NCURSES_EXPORT(char *) _nc_trace_bufcat (int, const char *);
1993extern NCURSES_EXPORT(char *) _nc_tracechar (SCREEN *, int);
1994extern NCURSES_EXPORT(char *) _nc_tracemouse (SCREEN *, MEVENT const *);
1995extern NCURSES_EXPORT(int) _nc_access (const char *, int);
1996extern NCURSES_EXPORT(int) _nc_baudrate (int);
1997extern NCURSES_EXPORT(int) _nc_freewin (WINDOW *);
1998extern NCURSES_EXPORT(int) _nc_getenv_num (const char *);
1999extern NCURSES_EXPORT(int) _nc_keypad (SCREEN *, int);
2000extern NCURSES_EXPORT(int) _nc_ospeed (int);
2001extern NCURSES_EXPORT(int) _nc_outch (int);
2002extern NCURSES_EXPORT(int) _nc_putchar (int);
2003extern NCURSES_EXPORT(int) _nc_putp(const char *, const char *);
2004extern NCURSES_EXPORT(int) _nc_putp_flush(const char *, const char *);
2005extern NCURSES_EXPORT(int) _nc_read_termcap_entry (const char *const, TERMTYPE *const);
2006extern NCURSES_EXPORT(int) _nc_setup_tinfo(const char *, TERMTYPE *);
2007extern NCURSES_EXPORT(int) _nc_setupscreen (int, int, FILE *, int, int);
2008extern NCURSES_EXPORT(int) _nc_timed_wait (SCREEN *, int, int, int * EVENTLIST_2nd(_nc_eventlist *));
2009extern NCURSES_EXPORT(void) _nc_do_color (int, int, int, NCURSES_OUTC);
2010extern NCURSES_EXPORT(void) _nc_flush (void);
2011extern NCURSES_EXPORT(void) _nc_free_and_exit (int) GCC_NORETURN;
2012extern NCURSES_EXPORT(void) _nc_free_entry (ENTRY *, TERMTYPE *);
2013extern NCURSES_EXPORT(void) _nc_freeall (void);
2014extern NCURSES_EXPORT(void) _nc_hash_map (void);
2015extern NCURSES_EXPORT(void) _nc_init_keytry (SCREEN *);
2016extern NCURSES_EXPORT(void) _nc_keep_tic_dir (const char *);
2017extern NCURSES_EXPORT(void) _nc_make_oldhash (int i);
2018extern NCURSES_EXPORT(void) _nc_scroll_oldhash (int n, int top, int bot);
2019extern NCURSES_EXPORT(void) _nc_scroll_optimize (void);
2020extern NCURSES_EXPORT(void) _nc_set_buffer (FILE *, int);
2021extern NCURSES_EXPORT(void) _nc_setenv_num (const char *, int);
2022extern NCURSES_EXPORT(void) _nc_signal_handler (int);
2023extern NCURSES_EXPORT(void) _nc_synchook (WINDOW *);
2024extern NCURSES_EXPORT(void) _nc_trace_tries (TRIES *);
2025
2026#if NO_LEAKS
2027extern NCURSES_EXPORT(void) _nc_alloc_entry_leaks(void);
2028extern NCURSES_EXPORT(void) _nc_captoinfo_leaks(void);
2029extern NCURSES_EXPORT(void) _nc_codes_leaks(void);
2030extern NCURSES_EXPORT(void) _nc_comp_captab_leaks(void);
2031extern NCURSES_EXPORT(void) _nc_comp_error_leaks(void);
2032extern NCURSES_EXPORT(void) _nc_comp_scan_leaks(void);
2033extern NCURSES_EXPORT(void) _nc_db_iterator_leaks(void);
2034extern NCURSES_EXPORT(void) _nc_keyname_leaks(void);
2035extern NCURSES_EXPORT(void) _nc_names_leaks(void);
2036extern NCURSES_EXPORT(void) _nc_tgetent_leaks(void);
2037#endif
2038
2039#if !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
2040extern NCURSES_EXPORT(NCURSES_CH_T) _nc_render (WINDOW *, NCURSES_CH_T);
2041extern NCURSES_EXPORT(int) _nc_waddch_nosync (WINDOW *, const NCURSES_CH_T);
2042extern NCURSES_EXPORT(void) _nc_scroll_window (WINDOW *, int const, int const, int const, NCURSES_CH_T);
2043#endif
2044
2045#if USE_WIDEC_SUPPORT
2046extern NCURSES_EXPORT(int) _nc_insert_wch(WINDOW *, const cchar_t *);
2047#endif
2048
2049#if USE_WIDEC_SUPPORT && !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
2050extern NCURSES_EXPORT(size_t) _nc_wcrtomb (char *, wchar_t, mbstate_t *);
2051#endif
2052
2053#if USE_SIZECHANGE
2054extern NCURSES_EXPORT(void) _nc_update_screensize (SCREEN *);
2055#endif
2056
2057#if HAVE_RESIZETERM
2058extern NCURSES_EXPORT(void) _nc_resize_margins (WINDOW *);
2059#else
2060#define _nc_resize_margins(wp) /* nothing */
2061#endif
2062
2063#ifdef NCURSES_WGETCH_EVENTS
2064extern NCURSES_EXPORT(int) _nc_eventlist_timeout(_nc_eventlist *);
2065#else
2066#define wgetch_events(win, evl) wgetch(win)
2067#define wgetnstr_events(win, str, maxlen, evl) wgetnstr(win, str, maxlen)
2068#endif
2069
2070/*
2071 * Wide-character macros to hide some platform-differences.
2072 */
2073#if USE_WIDEC_SUPPORT
2074
2075#if defined(__MINGW32__)
2076/*
2077 * MinGW has wide-character functions, but they do not work correctly.
2078 */
2079
2080extern int __MINGW_NOTHROW _nc_wctomb(char *, wchar_t);
2081#define wctomb(s,wc) _nc_wctomb(s,wc)
2082#define wcrtomb(s,wc,n) _nc_wctomb(s,wc)
2083
2084extern int __MINGW_NOTHROW _nc_mbtowc(wchar_t *, const char *, size_t);
2085#define mbtowc(pwc,s,n) _nc_mbtowc(pwc,s,n)
2086
2087extern int __MINGW_NOTHROW _nc_mblen(const char *, size_t);
2088#define mblen(s,n) _nc_mblen(s, n)
2089
2090#endif /* __MINGW32__ */
2091
2092#if HAVE_MBTOWC && HAVE_MBLEN
2093#define reset_mbytes(state) IGNORE_RC(mblen(NULL, (size_t) 0)), IGNORE_RC(mbtowc(NULL, NULL, (size_t) 0))
2094#define count_mbytes(buffer,length,state) mblen(buffer,length)
2095#define check_mbytes(wch,buffer,length,state) \
2096	(int) mbtowc(&wch, buffer, length)
2097#define state_unused
2098#elif HAVE_MBRTOWC && HAVE_MBRLEN
2099#define reset_mbytes(state) init_mb(state)
2100#define count_mbytes(buffer,length,state) mbrlen(buffer,length,&state)
2101#define check_mbytes(wch,buffer,length,state) \
2102	(int) mbrtowc(&wch, buffer, length, &state)
2103#else
2104make an error
2105#endif
2106
2107#endif /* USE_WIDEC_SUPPORT */
2108
2109/*
2110 * Not everyone has vsscanf(), but we'd like to use it for scanw().
2111 */
2112#if !HAVE_VSSCANF
2113extern int vsscanf(const char *str, const char *format, va_list __arg);
2114#endif
2115
2116/* scroll indices */
2117extern NCURSES_EXPORT_VAR(int *) _nc_oldnums;
2118
2119#define USE_SETBUF_0 0
2120
2121#define NC_BUFFERED(sp,flag) NCURSES_SP_NAME(_nc_set_buffer)(NCURSES_SP_ARGx sp->_ofp, flag)
2122
2123#define NC_OUTPUT(sp) ((sp != 0) ? sp->_ofp : stdout)
2124
2125/*
2126 * On systems with a broken linker, define 'SP' as a function to force the
2127 * linker to pull in the data-only module with 'SP'.
2128 */
2129#define _nc_alloc_screen_sp() typeCalloc(SCREEN, 1)
2130
2131#if BROKEN_LINKER
2132#define SP _nc_screen()
2133extern NCURSES_EXPORT(SCREEN *) _nc_screen (void);
2134extern NCURSES_EXPORT(int)      _nc_alloc_screen (void);
2135extern NCURSES_EXPORT(void)     _nc_set_screen (SCREEN *);
2136#define CURRENT_SCREEN          _nc_screen()
2137#else
2138/* current screen is private data; avoid possible linking conflicts too */
2139extern NCURSES_EXPORT_VAR(SCREEN *) SP;
2140#define CURRENT_SCREEN SP
2141#define _nc_alloc_screen()      ((SP = _nc_alloc_screen_sp()) != 0)
2142#define _nc_set_screen(sp)      SP = sp
2143#endif
2144
2145#if NCURSES_SP_FUNCS
2146#define CURRENT_SCREEN_PRE      (IsPreScreen(CURRENT_SCREEN) ? CURRENT_SCREEN : new_prescr())
2147#else
2148#define CURRENT_SCREEN_PRE      CURRENT_SCREEN
2149#endif
2150
2151/*
2152 * We don't want to use the lines or columns capabilities internally, because
2153 * if the application is running multiple screens under X, it's quite possible
2154 * they could all have type xterm but have different sizes!  So...
2155 */
2156#define screen_lines(sp)        (sp)->_lines
2157#define screen_columns(sp)      (sp)->_columns
2158
2159extern NCURSES_EXPORT(int) _nc_slk_initialize (WINDOW *, int);
2160extern NCURSES_EXPORT(int) _nc_format_slks (NCURSES_SP_DCLx int _c);
2161
2162/*
2163 * Some constants related to SLK's
2164 */
2165#define MAX_SKEY_OLD	   8	/* count of soft keys */
2166#define MAX_SKEY_LEN_OLD   8	/* max length of soft key text */
2167#define MAX_SKEY_PC       12    /* This is what most PC's have */
2168#define MAX_SKEY_LEN_PC    5
2169
2170/* Macro to check whether or not we use a standard format */
2171#define SLK_STDFMT(fmt) (fmt < 3)
2172/* Macro to determine height of label window */
2173#define SLK_LINES(fmt)  (SLK_STDFMT(fmt) ? 1 : ((fmt) - 2))
2174
2175#define MAX_SKEY(fmt)     (SLK_STDFMT(fmt)? MAX_SKEY_OLD : MAX_SKEY_PC)
2176#define MAX_SKEY_LEN(fmt) (SLK_STDFMT(fmt)? MAX_SKEY_LEN_OLD : MAX_SKEY_LEN_PC)
2177
2178/*
2179 * Common error messages
2180 */
2181#define MSG_NO_MEMORY "Out of memory"
2182#define MSG_NO_INPUTS "Premature EOF"
2183
2184extern NCURSES_EXPORT(int) _nc_set_tty_mode(TTY *);
2185extern NCURSES_EXPORT(int) _nc_get_tty_mode(TTY *);
2186
2187/* timed_wait flag definitions */
2188#define TW_NONE    0
2189#define TW_INPUT   1
2190#define TW_MOUSE   2
2191#define TW_ANY     (TW_INPUT | TW_MOUSE)
2192#define TW_EVENT   4
2193
2194#define SetSafeOutcWrapper(outc)	    \
2195    SCREEN* sp = CURRENT_SCREEN;            \
2196    struct screen outc_wrapper;		    \
2197    if (sp==0) {                            \
2198	sp = &outc_wrapper;                 \
2199	memset(sp,0,sizeof(struct screen)); \
2200	sp->_outch = _nc_outc_wrapper;      \
2201    }\
2202    sp->jump = outc
2203
2204#ifdef USE_TERM_DRIVER
2205typedef void* TERM_HANDLE;
2206
2207typedef struct _termInfo
2208{
2209    bool caninit;
2210
2211    bool hascolor;
2212    bool initcolor;
2213    bool canchange;
2214
2215    int  tabsize;
2216
2217    int  maxcolors;
2218    int  maxpairs;
2219    int  nocolorvideo;
2220
2221    int  numbuttons;
2222    int  numlabels;
2223    int  labelwidth;
2224    int  labelheight;
2225
2226    const color_t* defaultPalette;
2227} TerminalInfo;
2228
2229typedef struct term_driver {
2230    bool   isTerminfo;
2231    bool   (*CanHandle)(struct DriverTCB*, const char*, int*);
2232    void   (*init)(struct DriverTCB*);
2233    void   (*release)(struct DriverTCB*);
2234    int    (*size)(struct DriverTCB*, int* Line, int *Cols);
2235    int    (*sgmode)(struct DriverTCB*, int setFlag, TTY*);
2236    chtype (*conattr)(struct DriverTCB*);
2237    int    (*hwcur)(struct DriverTCB*, int yold, int xold, int y, int x);
2238    int    (*mode)(struct DriverTCB*, int progFlag, int defFlag);
2239    bool   (*rescol)(struct DriverTCB*);
2240    bool   (*rescolors)(struct DriverTCB*);
2241    void   (*color)(struct DriverTCB*, int fore, int color, int(*)(SCREEN*, int));
2242    int    (*doBeepOrFlash)(struct DriverTCB*, int);
2243    void   (*initpair)(struct DriverTCB*, int, int, int);
2244    void   (*initcolor)(struct DriverTCB*, int, int, int, int);
2245    void   (*docolor)(struct DriverTCB*, int, int, int, int(*)(SCREEN*, int));
2246    void   (*initmouse)(struct DriverTCB*);
2247    int    (*testmouse)(struct DriverTCB*, int EVENTLIST_2nd(_nc_eventlist*));
2248    void   (*setfilter)(struct DriverTCB*);
2249    void   (*hwlabel)(struct DriverTCB*, int, char*);
2250    void   (*hwlabelOnOff)(struct DriverTCB*, int);
2251    int    (*update)(struct DriverTCB*);
2252    int    (*defaultcolors)(struct DriverTCB*, int, int);
2253    int    (*print)(struct DriverTCB*, char*, int);
2254    int    (*getsize)(struct DriverTCB*, int*, int*);
2255    int    (*setsize)(struct DriverTCB*, int, int);
2256    void   (*initacs)(struct DriverTCB*, chtype*, chtype*);
2257    void   (*scinit)(SCREEN *);
2258    void   (*scexit)(SCREEN *);
2259    int    (*twait)(struct DriverTCB*, int, int, int* EVENTLIST_2nd(_nc_eventlist*));
2260    int    (*read)(struct DriverTCB*, int*);
2261    int    (*nap)(struct DriverTCB*, int);
2262    int    (*kpad)(struct DriverTCB*, int);
2263    int    (*kyOk)(struct DriverTCB*, int, int);
2264    bool   (*kyExist)(struct DriverTCB*, int);
2265} TERM_DRIVER;
2266
2267typedef struct DriverTCB
2268{
2269    TERMINAL      term;   /* needs to be the first Element !!! */
2270    TERM_HANDLE   inp;    /* The input handle of the Terminal */
2271    TERM_HANDLE   out;    /* The output handle of the Terminal in shell mode */
2272    TERM_HANDLE   hdl;    /* The output handle of the Terminal in prog  mode */
2273    TERM_DRIVER*  drv;    /* The driver for that Terminal */
2274    SCREEN*       csp;    /* The screen that owns that Terminal */
2275    TerminalInfo  info;   /* Driver independent core capabilities of the Terminal */
2276    void*         prop;   /* Driver dependent property storage to be used by the Driver */
2277    long          magic;
2278} TERMINAL_CONTROL_BLOCK;
2279
2280#define NCDRV_MAGIC(id) (0x47110000 | (id&0xffff))
2281#define NCDRV_TINFO      0x01
2282#define NCDRV_WINCONSOLE 0x02
2283
2284#define TCBOf(sp)    ((TERMINAL_CONTROL_BLOCK*)(TerminalOf(sp)))
2285#define InfoOf(sp)   TCBOf(sp)->info
2286#define CallDriver(sp,method)                        TCBOf(sp)->drv->method(TCBOf(sp))
2287#define CallDriver_1(sp,method,arg1)                 TCBOf(sp)->drv->method(TCBOf(sp),arg1)
2288#define CallDriver_2(sp,method,arg1,arg2)            TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2)
2289#define CallDriver_3(sp,method,arg1,arg2,arg3)       TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2,arg3)
2290#define CallDriver_4(sp,method,arg1,arg2,arg3,arg4)  TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2,arg3,arg4)
2291
2292extern NCURSES_EXPORT_VAR(const color_t*) _nc_cga_palette;
2293extern NCURSES_EXPORT_VAR(const color_t*) _nc_hls_palette;
2294
2295extern NCURSES_EXPORT(int)      _nc_get_driver(TERMINAL_CONTROL_BLOCK*, const char*, int*);
2296extern NCURSES_EXPORT(void)     _nc_get_screensize_ex(SCREEN *, TERMINAL *, int *, int *);
2297#endif /* USE_TERM_DRIVER */
2298
2299/*
2300 * Entrypoints which are actually provided in the terminal driver, which would
2301 * be an sp-name otherwise.
2302 */
2303#ifdef USE_TERM_DRIVER
2304#define TINFO_HAS_KEY           _nc_tinfo_has_key
2305#define TINFO_DOUPDATE          _nc_tinfo_doupdate
2306#define TINFO_MVCUR             _nc_tinfo_mvcur
2307extern NCURSES_EXPORT(int)      TINFO_HAS_KEY(SCREEN*, int);
2308extern NCURSES_EXPORT(int)      TINFO_DOUPDATE(SCREEN *);
2309extern NCURSES_EXPORT(int)      TINFO_MVCUR(SCREEN*, int, int, int, int);
2310#else
2311#define TINFO_HAS_KEY           NCURSES_SP_NAME(has_key)
2312#define TINFO_DOUPDATE          NCURSES_SP_NAME(doupdate)
2313#define TINFO_MVCUR             NCURSES_SP_NAME(_nc_mvcur)
2314#endif
2315
2316/*
2317 * Entrypoints using an extra parameter with the terminal driver.
2318 */
2319#ifdef USE_TERM_DRIVER
2320extern NCURSES_EXPORT(void)   _nc_get_screensize(SCREEN *, TERMINAL *, int *, int *);
2321extern NCURSES_EXPORT(int)    _nc_setupterm_ex(TERMINAL **, NCURSES_CONST char *, int , int *, int);
2322#define TINFO_GET_SIZE(sp, tp, lp, cp) \
2323	_nc_get_screensize(sp, tp, lp, cp)
2324#define TINFO_SET_CURTERM(sp, tp) \
2325	NCURSES_SP_NAME(set_curterm)(sp, tp)
2326#define TINFO_SETUP_TERM(tpp, name, fd, err, reuse) \
2327	_nc_setupterm_ex(tpp, name, fd, err, reuse)
2328#else /* !USE_TERM_DRIVER */
2329extern NCURSES_EXPORT(void)   _nc_get_screensize(SCREEN *, int *, int *);
2330#define TINFO_GET_SIZE(sp, tp, lp, cp) \
2331	_nc_get_screensize(sp, lp, cp)
2332#define TINFO_SET_CURTERM(sp, tp) \
2333	set_curterm(tp)
2334#define TINFO_SETUP_TERM(tpp, name, fd, err, reuse) \
2335	_nc_setupterm(name, fd, err, reuse)
2336#endif /* !USE_TERM_DRIVER */
2337
2338#ifdef USE_TERM_DRIVER
2339#ifdef __MINGW32__
2340#include <nc_mingw.h>
2341extern NCURSES_EXPORT_VAR(TERM_DRIVER) _nc_WIN_DRIVER;
2342#endif
2343extern NCURSES_EXPORT_VAR(TERM_DRIVER) _nc_TINFO_DRIVER;
2344#endif
2345
2346#ifdef USE_TERM_DRIVER
2347#define IsTermInfo(sp)       ((TCBOf(sp) != 0) && ((TCBOf(sp)->drv->isTerminfo)))
2348#define HasTInfoTerminal(sp) ((0 != TerminalOf(sp)) && IsTermInfo(sp))
2349#else
2350#define IsTermInfo(sp)       TRUE
2351#define HasTInfoTerminal(sp) (0 != TerminalOf(sp))
2352#endif
2353
2354#define IsValidTIScreen(sp)  (HasTInfoTerminal(sp))
2355
2356/*
2357 * Exported entrypoints beyond the published API
2358 */
2359#if NCURSES_SP_FUNCS
2360extern NCURSES_EXPORT(WINDOW *) _nc_curscr_of(SCREEN*);
2361extern NCURSES_EXPORT(WINDOW *) _nc_newscr_of(SCREEN*);
2362extern NCURSES_EXPORT(WINDOW *) _nc_stdscr_of(SCREEN*);
2363extern NCURSES_EXPORT(int)      _nc_outc_wrapper(SCREEN*,int);
2364
2365#if USE_REENTRANT
2366extern NCURSES_EXPORT(int)       NCURSES_SP_NAME(_nc_TABSIZE)(SCREEN*);
2367extern NCURSES_EXPORT(char *)    NCURSES_SP_NAME(longname)(SCREEN*);
2368#endif
2369
2370#if NCURSES_EXT_FUNCS
2371extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_set_tabsize)(SCREEN*, int);
2372#endif
2373
2374/*
2375 * We put the safe versions of various calls here as they are not published
2376 * part of the API up to now
2377 */
2378extern NCURSES_EXPORT(TERMINAL*) NCURSES_SP_NAME(_nc_get_cur_term) (SCREEN *sp);
2379extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(_nc_makenew) (SCREEN*, int, int, int, int, int);
2380extern NCURSES_EXPORT(bool)     NCURSES_SP_NAME(_nc_reset_colors)(SCREEN*);
2381extern NCURSES_EXPORT(char *)   NCURSES_SP_NAME(_nc_printf_string)(SCREEN*, const char *, va_list);
2382extern NCURSES_EXPORT(chtype)   NCURSES_SP_NAME(_nc_acs_char)(SCREEN*,int);
2383extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_curs_set)(SCREEN*,int);
2384extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_get_tty_mode)(SCREEN*,TTY*);
2385extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_mcprint)(SCREEN*,char*, int);
2386extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_msec_cost)(SCREEN*, const char *, int);
2387extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_mvcur)(SCREEN*, int, int, int, int);
2388extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_outch)(SCREEN*, int);
2389extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_putchar)(SCREEN*, int);
2390extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_putp)(SCREEN*, const char *, const char*);
2391extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_putp_flush)(SCREEN*, const char *, const char *);
2392extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_resetty)(SCREEN*);
2393extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_resize_term)(SCREEN*,int,int);
2394extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_ripoffline)(SCREEN*, int, int (*)(WINDOW *,int));
2395extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_savetty)(SCREEN*);
2396extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_scr_init)(SCREEN*,const char*);
2397extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_scr_restore)(SCREEN*, const char*);
2398extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_scrolln)(SCREEN*, int, int, int, int);
2399extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_set_tty_mode)(SCREEN*, TTY*);
2400extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_setupscreen)(SCREEN**, int, int, FILE *, int, int);
2401extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_tgetent)(SCREEN*,char*,const char *);
2402extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_tigetnum)(SCREEN*,NCURSES_CONST char*);
2403extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_vid_attr)(SCREEN *, attr_t, NCURSES_COLOR_T, void *);
2404extern NCURSES_EXPORT(int)      NCURSES_SP_NAME(_nc_vidputs)(SCREEN*,chtype,int(*) (SCREEN*, int));
2405extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_do_color)(SCREEN*, int, int, int, NCURSES_SP_OUTC);
2406extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_do_xmc_glitch)(SCREEN*, attr_t);
2407extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_flush)(SCREEN*);
2408extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_free_and_exit)(SCREEN*, int) GCC_NORETURN;
2409extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_freeall)(SCREEN*);
2410extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_hash_map)(SCREEN*);
2411extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_init_acs)(SCREEN*);
2412extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_make_oldhash)(SCREEN*, int i);
2413extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_mvcur_init)(SCREEN*);
2414extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_mvcur_resume)(SCREEN*);
2415extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_mvcur_wrap)(SCREEN*);
2416extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_screen_init)(SCREEN*);
2417extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_screen_resume)(SCREEN*);
2418extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_screen_wrap)(SCREEN*);
2419extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_scroll_oldhash)(SCREEN*, int n, int top, int bot);
2420extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_scroll_optimize)(SCREEN*);
2421extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_set_buffer)(SCREEN*, FILE *, int);
2422
2423extern NCURSES_EXPORT(void)     _nc_cookie_init(SCREEN *sp);
2424
2425#if defined(TRACE) || defined(SCROLLDEBUG) || defined(HASHDEBUG)
2426extern NCURSES_EXPORT(void)     NCURSES_SP_NAME(_nc_linedump)(SCREEN*);
2427#endif
2428
2429#if USE_WIDEC_SUPPORT
2430extern NCURSES_EXPORT(wchar_t *) NCURSES_SP_NAME(_nc_wunctrl)(SCREEN*, cchar_t *);
2431#endif
2432
2433#endif /* NCURSES_SP_FUNCS */
2434
2435#if NCURSES_SP_FUNCS
2436
2437#define safe_keyname NCURSES_SP_NAME(keyname)
2438#define safe_unctrl  NCURSES_SP_NAME(unctrl)
2439#define safe_ungetch NCURSES_SP_NAME(ungetch)
2440
2441#else
2442
2443#define safe_keyname _nc_keyname
2444#define safe_unctrl  _nc_unctrl
2445#define safe_ungetch _nc_ungetch
2446
2447extern NCURSES_EXPORT(NCURSES_CONST char *) _nc_keyname (SCREEN *, int);
2448extern NCURSES_EXPORT(int) _nc_ungetch (SCREEN *, int);
2449extern NCURSES_EXPORT(NCURSES_CONST char *) _nc_unctrl (SCREEN *, chtype);
2450
2451#endif
2452
2453#ifdef __cplusplus
2454}
2455#endif
2456
2457/* *INDENT-ON* */
2458
2459#endif /* CURSES_PRIV_H */
2460