dialog.c revision 251843
1/*
2 * $Id: dialog.c,v 1.230 2013/03/15 09:07:30 tom Exp $
3 *
4 *  cdialog - Display simple dialog boxes from shell scripts
5 *
6 *  Copyright 2000-2012,2013	Thomas E. Dickey
7 *
8 *  This program is free software; you can redistribute it and/or modify
9 *  it under the terms of the GNU Lesser General Public License, version 2.1
10 *  as published by the Free Software Foundation.
11 *
12 *  This program is distributed in the hope that it will be useful, but
13 *  WITHOUT ANY WARRANTY; without even the implied warranty of
14 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 *  Lesser General Public License for more details.
16 *
17 *  You should have received a copy of the GNU Lesser General Public
18 *  License along with this program; if not, write to
19 *	Free Software Foundation, Inc.
20 *	51 Franklin St., Fifth Floor
21 *	Boston, MA 02110, USA.
22 *
23 *  An earlier version of this program lists as authors
24 *	Savio Lam (lam836@cs.cuhk.hk)
25 */
26
27#include <dialog.h>
28#include <string.h>
29#include <sys/types.h>
30#include <sys/stat.h>
31
32#ifdef HAVE_SETLOCALE
33#include <locale.h>
34#endif
35
36#define PASSARGS             t,       av,        offset_add
37#define CALLARGS const char *t, char *av[], int *offset_add
38typedef int (callerFn) (CALLARGS);
39
40typedef enum {
41    o_unknown = 0
42    ,o_allow_close
43    ,o_and_widget
44    ,o_ascii_lines
45    ,o_aspect
46    ,o_auto_placement
47    ,o_backtitle
48    ,o_beep
49    ,o_beep_after
50    ,o_begin
51    ,o_cancel_label
52    ,o_checklist
53    ,o_clear
54    ,o_colors
55    ,o_column_separator
56    ,o_cr_wrap
57    ,o_create_rc
58    ,o_date_format
59    ,o_default_button
60    ,o_default_item
61    ,o_defaultno
62    ,o_exit_label
63    ,o_extra_button
64    ,o_extra_label
65    ,o_fixed_font
66    ,o_form
67    ,o_gauge
68    ,o_help
69    ,o_help_button
70    ,o_help_file
71    ,o_help_label
72    ,o_help_line
73    ,o_help_status
74    ,o_icon
75    ,o_ignore
76    ,o_infobox
77    ,o_input_fd
78    ,o_inputbox
79    ,o_inputmenu
80    ,o_insecure
81    ,o_item_help
82    ,o_keep_colors
83    ,o_keep_tite
84    ,o_keep_window
85    ,o_last_key
86    ,o_max_input
87    ,o_menu
88    ,o_mixedform
89    ,o_mixedgauge
90    ,o_msgbox
91    ,o_no_close
92    ,o_no_collapse
93    ,o_no_cr_wrap
94    ,o_no_kill
95    ,o_no_label
96    ,o_no_lines
97    ,o_no_mouse
98    ,o_no_nl_expand
99    ,o_no_shadow
100    ,o_nocancel
101    ,o_nook
102    ,o_ok_label
103    ,o_output_fd
104    ,o_output_separator
105    ,o_passwordbox
106    ,o_passwordform
107    ,o_pause
108    ,o_prgbox
109    ,o_print_maxsize
110    ,o_print_size
111    ,o_print_version
112    ,o_programbox
113    ,o_progressbox
114    ,o_quoted
115    ,o_radiolist
116    ,o_screen_center
117    ,o_scrollbar
118    ,o_separate_output
119    ,o_separate_widget
120    ,o_separator
121    ,o_shadow
122    ,o_single_quoted
123    ,o_size_err
124    ,o_sleep
125    ,o_smooth
126    ,o_stderr
127    ,o_stdout
128    ,o_tab_correct
129    ,o_tab_len
130    ,o_tailbox
131    ,o_tailboxbg
132    ,o_textbox
133    ,o_time_format
134    ,o_timeout
135    ,o_title
136    ,o_trim
137    ,o_under_mouse
138    ,o_version
139    ,o_visit_items
140    ,o_wmclass
141    ,o_yes_label
142    ,o_yesno
143#ifdef HAVE_WHIPTAIL
144    ,o_fullbutton
145    ,o_topleft
146#endif
147#ifdef HAVE_XDIALOG
148    ,o_calendar
149    ,o_dselect
150    ,o_editbox
151    ,o_fselect
152    ,o_timebox
153#endif
154#ifdef HAVE_XDIALOG2
155    ,o_buildlist
156    ,o_rangebox
157    ,o_treeview
158#endif
159#if defined(HAVE_XDIALOG2) || defined(HAVE_WHIPTAIL)
160    ,o_no_items
161    ,o_no_tags
162#endif
163#ifdef HAVE_DLG_TRACE
164    ,o_trace
165#endif
166} eOptions;
167
168/*
169 * The bits in 'pass' are used to decide which options are applicable at
170 * different stages in the program:
171 *	1 flags before widgets
172 *	2 widgets
173 *	4 non-widget options
174 */
175typedef struct {
176    const char *name;
177    eOptions code;
178    int pass;			/* 1,2,4 or combination */
179    const char *help;		/* NULL to suppress, non-empty to display params */
180} Options;
181
182typedef struct {
183    eOptions code;
184    int argmin, argmax;
185    callerFn *jumper;
186} Mode;
187
188static bool *dialog_opts;
189static char **dialog_argv;
190
191static bool ignore_unknown = FALSE;
192
193static const char *program = "dialog";
194
195/*
196 * The options[] table is organized this way to make it simple to maintain
197 * a sorted list of options for the help-message.
198 */
199/* *INDENT-OFF* */
200static const Options options[] = {
201    { "allow-close",	o_allow_close,		1, NULL },
202    { "and-widget",	o_and_widget,		4, NULL },
203    { "ascii-lines",	o_ascii_lines, 		1, "" },
204    { "aspect",		o_aspect,		1, "<ratio>" },
205    { "auto-placement", o_auto_placement,	1, NULL },
206    { "backtitle",	o_backtitle,		1, "<backtitle>" },
207    { "beep",		o_beep,			1, "" },
208    { "beep-after",	o_beep_after,		1, "" },
209    { "begin",		o_begin,		1, "<y> <x>" },
210    { "cancel-label",	o_cancel_label,		1, "<str>" },
211    { "checklist",	o_checklist,		2, "<text> <height> <width> <list height> <tag1> <item1> <status1>..." },
212    { "clear",		o_clear,		1, "" },
213    { "colors",		o_colors,		1, "" },
214    { "column-separator",o_column_separator,	1, "<str>" },
215    { "cr-wrap",	o_cr_wrap,		1, "" },
216    { "create-rc",	o_create_rc,		1, NULL },
217    { "date-format",	o_date_format,		1, "<str>" },
218    { "default-button",	o_default_button,	1, "<str>" },
219    { "default-item",	o_default_item,		1, "<str>" },
220    { "defaultno",	o_defaultno,		1, "" },
221    { "exit-label",	o_exit_label,		1, "<str>" },
222    { "extra-button",	o_extra_button,		1, "" },
223    { "extra-label",	o_extra_label,		1, "<str>" },
224    { "fixed-font",	o_fixed_font,		1, NULL },
225    { "form",		o_form,			2, "<text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1>..." },
226    { "gauge",		o_gauge,		2, "<text> <height> <width> [<percent>]" },
227    { "guage",		o_gauge,		2, NULL },
228    { "help",		o_help,			4, "" },
229    { "help-button",	o_help_button,		1, "" },
230    { "help-label",	o_help_label,		1, "<str>" },
231    { "help-status",	o_help_status,		1, "" },
232    { "hfile",		o_help_file,		1, "<str>" },
233    { "hline",		o_help_line,		1, "<str>" },
234    { "icon",		o_icon,			1, NULL },
235    { "ignore",		o_ignore,		1, "" },
236    { "infobox",	o_infobox,		2, "<text> <height> <width>" },
237    { "input-fd",	o_input_fd,		1, "<fd>" },
238    { "inputbox",	o_inputbox,		2, "<text> <height> <width> [<init>]" },
239    { "inputmenu",	o_inputmenu,		2, "<text> <height> <width> <menu height> <tag1> <item1>..." },
240    { "insecure",	o_insecure,		1, "" },
241    { "item-help",	o_item_help,		1, "" },
242    { "keep-colors",	o_keep_colors,		1, NULL },
243    { "keep-tite",	o_keep_tite,		1, "" },
244    { "keep-window",	o_keep_window,		1, "" },
245    { "last-key",	o_last_key,		1, "" },
246    { "max-input",	o_max_input,		1, "<n>" },
247    { "menu",		o_menu,			2, "<text> <height> <width> <menu height> <tag1> <item1>..." },
248    { "mixedform",	o_mixedform,		2, "<text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1> <itype>..." },
249    { "mixedgauge",	o_mixedgauge,		2, "<text> <height> <width> <percent> <tag1> <item1>..." },
250    { "msgbox",		o_msgbox,		2, "<text> <height> <width>" },
251    { "no-cancel",	o_nocancel,		1, "" },
252    { "no-close",	o_no_close,		1, NULL },
253    { "no-collapse",	o_no_collapse,		1, "" },
254    { "no-cr-wrap",	o_no_cr_wrap,		1, "" },
255    { "no-kill",	o_no_kill,		1, "" },
256    { "no-label",	o_no_label,		1, "<str>" },
257    { "no-lines",	o_no_lines, 		1, "" },
258    { "no-mouse",	o_no_mouse,		1, "" },
259    { "no-nl-expand",	o_no_nl_expand,		1, "" },
260    { "no-ok",		o_nook,			1, "" },
261    { "no-shadow",	o_no_shadow,		1, "" },
262    { "nocancel",	o_nocancel,		1, NULL }, /* see --no-cancel */
263    { "nook",		o_nook,			1, "" }, /* See no-ok */
264    { "ok-label",	o_ok_label,		1, "<str>" },
265    { "output-fd",	o_output_fd,		1, "<fd>" },
266    { "output-separator",o_output_separator,	1, "<str>" },
267    { "passwordbox",	o_passwordbox,		2, "<text> <height> <width> [<init>]" },
268    { "passwordform",	o_passwordform,		2, "<text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1>..." },
269    { "pause",		o_pause,		2, "<text> <height> <width> <seconds>" },
270    { "prgbox",		o_prgbox,		2, "<text> <command> <height> <width>" },
271    { "print-maxsize",	o_print_maxsize,	1, "" },
272    { "print-size",	o_print_size,		1, "" },
273    { "print-version",	o_print_version,	5, "" },
274    { "programbox",	o_programbox,		2, "<text> <height> <width>" },
275    { "progressbox",	o_progressbox,		2, "<text> <height> <width>" },
276    { "quoted",		o_quoted,		1, "" },
277    { "radiolist",	o_radiolist,		2, "<text> <height> <width> <list height> <tag1> <item1> <status1>..." },
278    { "screen-center",	o_screen_center,	1, NULL },
279    { "scrollbar",	o_scrollbar,		1, "" },
280    { "separate-output",o_separate_output,	1, "" },
281    { "separate-widget",o_separate_widget,	1, "<str>" },
282    { "separator",	o_separator,		1, NULL },
283    { "shadow",		o_shadow,		1, "" },
284    { "single-quoted",	o_single_quoted,	1, "" },
285    { "size-err",	o_size_err,		1, "" },
286    { "sleep",		o_sleep,		1, "<secs>" },
287    { "smooth",		o_smooth,		1, NULL },
288    { "stderr",		o_stderr,		1, "" },
289    { "stdout",		o_stdout,		1, "" },
290    { "tab-correct",	o_tab_correct,		1, "" },
291    { "tab-len",	o_tab_len,		1, "<n>" },
292    { "tailbox",	o_tailbox,		2, "<file> <height> <width>" },
293    { "tailboxbg",	o_tailboxbg,		2, "<file> <height> <width>" },
294    { "textbox",	o_textbox,		2, "<file> <height> <width>" },
295    { "time-format",	o_time_format,		1, "<str>" },
296    { "timeout",	o_timeout,		1, "<secs>" },
297    { "title",		o_title,		1, "<title>" },
298    { "trim",		o_trim,			1, "" },
299    { "under-mouse", 	o_under_mouse,		1, NULL },
300    { "version",	o_version,		5, "" },
301    { "visit-items", 	o_visit_items,		1, "" },
302    { "wmclass",	o_wmclass,		1, NULL },
303    { "yes-label",	o_yes_label,		1, "<str>" },
304    { "yesno",		o_yesno,		2, "<text> <height> <width>" },
305#ifdef HAVE_WHIPTAIL
306    { "cancel-button",	o_cancel_label,		1, NULL },
307    { "fb",		o_fullbutton,		1, NULL },
308    { "fullbutton",	o_fullbutton,		1, NULL },
309    { "no-button",	o_no_label,		1, NULL },
310    { "ok-button",	o_ok_label,		1, NULL },
311    { "scrolltext",	o_scrollbar,		1, NULL },
312    { "topleft",	o_topleft,		1, NULL },
313    { "yes-button",	o_yes_label,		1, NULL },
314#endif
315#ifdef HAVE_XDIALOG
316    { "calendar",	o_calendar,		2, "<text> <height> <width> <day> <month> <year>" },
317    { "dselect",	o_dselect,		2, "<directory> <height> <width>" },
318    { "editbox",	o_editbox,		2, "<file> <height> <width>" },
319    { "fselect",	o_fselect,		2, "<filepath> <height> <width>" },
320    { "timebox",	o_timebox,		2, "<text> <height> <width> <hour> <minute> <second>" },
321#endif
322#ifdef HAVE_XDIALOG2
323    { "buildlist",	o_buildlist,		2, "<text> <height> <width> <tag1> <item1> <status1>..." },
324    { "no-items", 	o_no_items,		1, "" },
325    { "no-tags", 	o_no_tags,		1, "" },
326    { "rangebox",	o_rangebox,		2, "<text> <height> <width> <min-value> <max-value> <default-value>" },
327    { "treeview",	o_treeview,		2, "<text> <height> <width> <list-height> <tag1> <item1> <status1> <depth1>..." },
328#endif
329#if defined(HAVE_XDIALOG2) || defined(HAVE_WHIPTAIL)
330    { "noitem", 	o_no_items,		1, NULL },
331    { "notags", 	o_no_tags,		1, NULL },
332#endif
333#ifdef HAVE_DLG_TRACE
334    { "trace",		o_trace,		1, "<file>" },
335#endif
336};
337/* *INDENT-ON* */
338
339/*
340 * Make an array showing which argv[] entries are options.  Use "--" as a
341 * special token to escape the next argument, allowing it to begin with "--".
342 * When we find a "--" argument, also remove it from argv[] and adjust argc.
343 * That appears to be an undocumented feature of the popt library.
344 *
345 * Also, if we see a "--file", expand it into the parameter list by reading the
346 * text from the given file and stripping quotes, treating whitespace outside
347 * quotes as a parameter delimiter.
348 *
349 * Finally, if we see a "--args", dump the current list of arguments to the
350 * standard error.  This is used for debugging complex --file combinations.
351 */
352static void
353unescape_argv(int *argcp, char ***argvp)
354{
355    int j, k;
356    int limit_includes = 20 + *argcp;
357    int count_includes = 0;
358    bool changed = FALSE;
359    bool doalloc = FALSE;
360    char *filename;
361
362    dialog_opts = dlg_calloc(bool, (size_t) *argcp + 1);
363    assert_ptr(dialog_opts, "unescape_argv");
364
365    for (j = 1; j < *argcp; j++) {
366	bool escaped = FALSE;
367	if (!strcmp((*argvp)[j], "--")) {
368	    escaped = TRUE;
369	    changed = dlg_eat_argv(argcp, argvp, j, 1);
370	} else if (!strcmp((*argvp)[j], "--args")) {
371	    fprintf(stderr, "Showing arguments at arg%d\n", j);
372	    for (k = 0; k < *argcp; ++k) {
373		fprintf(stderr, " arg%d:%s\n", k, (*argvp)[k]);
374	    }
375	    changed = dlg_eat_argv(argcp, argvp, j, 1);
376	} else if (!strcmp((*argvp)[j], "--file")) {
377	    if (++count_includes > limit_includes)
378		dlg_exiterr("Too many --file options");
379
380	    if ((filename = (*argvp)[j + 1]) != 0) {
381		FILE *fp;
382		char **list;
383		char *blob;
384		int added;
385		size_t bytes_read;
386		size_t length;
387		int n;
388
389		if (*filename == '&') {
390		    fp = fdopen(atoi(filename + sizeof(char)), "r");
391		} else {
392		    fp = fopen(filename, "r");
393		}
394
395		if (fp) {
396		    blob = NULL;
397		    length = 0;
398		    do {
399			blob = dlg_realloc(char, length + BUFSIZ + 1, blob);
400			assert_ptr(blob, "unescape_argv");
401			bytes_read = fread(blob + length,
402					   sizeof(char),
403					     (size_t) BUFSIZ,
404					   fp);
405			length += bytes_read;
406			if (ferror(fp))
407			    dlg_exiterr("error on filehandle in unescape_argv");
408		    } while (bytes_read == BUFSIZ);
409		    fclose(fp);
410
411		    blob[length] = '\0';
412
413		    list = dlg_string_to_argv(blob);
414		    if ((added = dlg_count_argv(list)) != 0) {
415			if (added > 2) {
416			    size_t need = (size_t) (*argcp + added + 1);
417			    if (doalloc) {
418				*argvp = dlg_realloc(char *, need, *argvp);
419				assert_ptr(*argvp, "unescape_argv");
420			    } else {
421				char **newp = dlg_malloc(char *, need);
422				assert_ptr(newp, "unescape_argv");
423				for (n = 0; n < *argcp; ++n) {
424				    newp[n] = (*argvp)[n];
425				}
426				*argvp = newp;
427				doalloc = TRUE;
428			    }
429			    dialog_opts = dlg_realloc(bool, need, dialog_opts);
430			    assert_ptr(dialog_opts, "unescape_argv");
431			}
432			for (n = *argcp; n >= j + 2; --n) {
433			    (*argvp)[n + added - 2] = (*argvp)[n];
434			    dialog_opts[n + added - 2] = dialog_opts[n];
435			}
436			for (n = 0; n < added; ++n) {
437			    (*argvp)[n + j] = list[n];
438			    dialog_opts[n + j] = FALSE;
439			}
440			*argcp += added - 2;
441			free(list);
442		    }
443		} else {
444		    dlg_exiterr("Cannot open --file %s", filename);
445		}
446		(*argvp)[*argcp] = 0;
447		++j;
448		continue;
449	    } else {
450		dlg_exiterr("No value given for --file");
451	    }
452	}
453	if (!escaped
454	    && (*argvp)[j] != 0
455	    && !strncmp((*argvp)[j], "--", (size_t) 2)
456	    && isalpha(UCH((*argvp)[j][2]))) {
457	    dialog_opts[j] = TRUE;
458	}
459    }
460
461    /* if we didn't find any "--" tokens, there's no reason to do the table
462     * lookup in isOption()
463     */
464    if (!changed) {
465	free(dialog_opts);
466	dialog_opts = 0;
467    }
468    dialog_argv = (*argvp);
469}
470
471#define OptionChars "\
4720123456789\
473-\
474abcdefghijklmnopqrstuvwxyz\
475"
476
477/*
478 * Check if the given string from main's argv is an option.
479 */
480static bool
481isOption(const char *arg)
482{
483    bool result = FALSE;
484
485    if (arg != 0) {
486	if (dialog_opts != 0) {
487	    int n;
488	    for (n = 1; dialog_argv[n] != 0; ++n) {
489		if (dialog_argv[n] == arg) {
490		    result = dialog_opts[n];
491		    break;
492		}
493	    }
494	} else if (!strncmp(arg, "--", (size_t) 2) && isalpha(UCH(arg[2]))) {
495	    if (strlen(arg) == strspn(arg, OptionChars)) {
496		result = TRUE;
497	    } else {
498		dlg_exiterr("Invalid option \"%s\"", arg);
499	    }
500	}
501    }
502    return result;
503}
504
505static eOptions
506lookupOption(const char *name, int pass)
507{
508    unsigned n;
509    eOptions result = o_unknown;
510
511    if (isOption(name)) {
512	name += 2;
513	for (n = 0; n < sizeof(options) / sizeof(options[0]); n++) {
514	    if ((pass & options[n].pass) != 0
515		&& !strcmp(name, options[n].name)) {
516		result = options[n].code;
517		break;
518	    }
519	}
520    }
521    return result;
522}
523
524static void
525Usage(const char *msg)
526{
527    dlg_exiterr("Error: %s.\nUse --help to list options.\n\n", msg);
528}
529
530/*
531 * Count arguments, stopping at the end of the argument list, or on any of our
532 * "--" tokens.
533 */
534static int
535arg_rest(char *argv[])
536{
537    int i = 1;			/* argv[0] points to a "--" token */
538
539    while (argv[i] != 0
540	   && (!isOption(argv[i]) || lookupOption(argv[i], 7) == o_unknown))
541	i++;
542    return i;
543}
544
545/*
546 * In MultiWidget this function is needed to count how many tags
547 * a widget (menu, checklist, radiolist) has
548 */
549static int
550howmany_tags(char *argv[], int group)
551{
552    int result = 0;
553    int have;
554    const char *format = "Expected %d arguments, found only %d";
555    char temp[80];
556
557    while (argv[0] != 0) {
558	if (isOption(argv[0]))
559	    break;
560	if ((have = arg_rest(argv)) < group) {
561	    sprintf(temp, format, group, have);
562	    Usage(temp);
563	}
564
565	argv += group;
566	result++;
567    }
568
569    return result;
570}
571
572static int
573numeric_arg(char **av, int n)
574{
575    int result = 0;
576
577    if (n < dlg_count_argv(av)) {
578	char msg[80];
579	char *last = 0;
580	result = (int) strtol(av[n], &last, 10);
581
582	if (last == 0 || *last != 0) {
583	    sprintf(msg, "Expected a number for token %d of %.20s", n, av[0]);
584	    Usage(msg);
585	}
586    }
587    return result;
588}
589
590static char *
591optional_str(char **av, int n, char *dft)
592{
593    char *ret = dft;
594    if (arg_rest(av) > n)
595	ret = av[n];
596    return ret;
597}
598
599#if defined(HAVE_DLG_GAUGE) || defined(HAVE_XDIALOG)
600static int
601optional_num(char **av, int n, int dft)
602{
603    int ret = dft;
604    if (arg_rest(av) > n)
605	ret = numeric_arg(av, n);
606    return ret;
607}
608#endif
609
610/*
611 * On AIX 4.x, we have to flush the output right away since there is a bug in
612 * the curses package which discards stdout even when we've used newterm to
613 * redirect output to /dev/tty.
614 */
615static int
616show_result(int ret)
617{
618    bool either = FALSE;
619
620    switch (ret) {
621    case DLG_EXIT_OK:
622    case DLG_EXIT_EXTRA:
623    case DLG_EXIT_HELP:
624    case DLG_EXIT_ITEM_HELP:
625	if ((dialog_state.output_count > 1) && !dialog_vars.separate_output) {
626	    fputs((dialog_state.separate_str
627		   ? dialog_state.separate_str
628		   : DEFAULT_SEPARATE_STR),
629		  dialog_state.output);
630	    either = TRUE;
631	}
632	if (dialog_vars.input_result != 0
633	    && dialog_vars.input_result[0] != '\0') {
634	    fputs(dialog_vars.input_result, dialog_state.output);
635	    either = TRUE;
636	}
637	if (either) {
638	    fflush(dialog_state.output);
639	}
640	break;
641    }
642    return ret;
643}
644
645/*
646 * These are the widget callers.
647 */
648
649static int
650call_yesno(CALLARGS)
651{
652    *offset_add = 4;
653    return dialog_yesno(t,
654			av[1],
655			numeric_arg(av, 2),
656			numeric_arg(av, 3));
657}
658
659static int
660call_msgbox(CALLARGS)
661{
662    *offset_add = 4;
663    return dialog_msgbox(t,
664			 av[1],
665			 numeric_arg(av, 2),
666			 numeric_arg(av, 3), 1);
667}
668
669static int
670call_infobox(CALLARGS)
671{
672    *offset_add = 4;
673    return dialog_msgbox(t,
674			 av[1],
675			 numeric_arg(av, 2),
676			 numeric_arg(av, 3), 0);
677}
678
679static int
680call_textbox(CALLARGS)
681{
682    *offset_add = 4;
683    return dialog_textbox(t,
684			  av[1],
685			  numeric_arg(av, 2),
686			  numeric_arg(av, 3));
687}
688
689static int
690call_menu(CALLARGS)
691{
692    int tags = howmany_tags(av + 5, MENUBOX_TAGS);
693    *offset_add = 5 + tags * MENUBOX_TAGS;
694
695    return dialog_menu(t,
696		       av[1],
697		       numeric_arg(av, 2),
698		       numeric_arg(av, 3),
699		       numeric_arg(av, 4),
700		       tags, av + 5);
701}
702
703static int
704call_inputmenu(CALLARGS)
705{
706    int tags = howmany_tags(av + 5, MENUBOX_TAGS);
707    bool free_extra_label = FALSE;
708    int result;
709
710    dialog_vars.input_menu = TRUE;
711
712    if (dialog_vars.max_input == 0)
713	dialog_vars.max_input = MAX_LEN / 2;
714
715    if (dialog_vars.extra_label == 0) {
716	free_extra_label = TRUE;
717	dialog_vars.extra_label = dlg_strclone(_("Rename"));
718    }
719
720    dialog_vars.extra_button = TRUE;
721
722    *offset_add = 5 + tags * MENUBOX_TAGS;
723    result = dialog_menu(t,
724			 av[1],
725			 numeric_arg(av, 2),
726			 numeric_arg(av, 3),
727			 numeric_arg(av, 4),
728			 tags, av + 5);
729    if (free_extra_label) {
730	free(dialog_vars.extra_label);
731	dialog_vars.extra_label = 0;
732    }
733    return result;
734}
735
736static int
737call_checklist(CALLARGS)
738{
739    int tags = howmany_tags(av + 5, CHECKBOX_TAGS);
740    int code;
741
742    *offset_add = 5 + tags * CHECKBOX_TAGS;
743    code = dialog_checklist(t,
744			    av[1],
745			    numeric_arg(av, 2),
746			    numeric_arg(av, 3),
747			    numeric_arg(av, 4),
748			    tags, av + 5, FLAG_CHECK);
749    return code;
750}
751
752static int
753call_radiolist(CALLARGS)
754{
755    int tags = howmany_tags(av + 5, CHECKBOX_TAGS);
756    *offset_add = 5 + tags * CHECKBOX_TAGS;
757    return dialog_checklist(t,
758			    av[1],
759			    numeric_arg(av, 2),
760			    numeric_arg(av, 3),
761			    numeric_arg(av, 4),
762			    tags, av + 5, FLAG_RADIO);
763}
764
765static int
766call_inputbox(CALLARGS)
767{
768    *offset_add = arg_rest(av);
769    return dialog_inputbox(t,
770			   av[1],
771			   numeric_arg(av, 2),
772			   numeric_arg(av, 3),
773			   optional_str(av, 4, 0), 0);
774}
775
776static int
777call_passwordbox(CALLARGS)
778{
779    *offset_add = arg_rest(av);
780    return dialog_inputbox(t,
781			   av[1],
782			   numeric_arg(av, 2),
783			   numeric_arg(av, 3),
784			   optional_str(av, 4, 0), 1);
785}
786
787#ifdef HAVE_XDIALOG
788static int
789call_calendar(CALLARGS)
790{
791    *offset_add = arg_rest(av);
792    return dialog_calendar(t,
793			   av[1],
794			   numeric_arg(av, 2),
795			   numeric_arg(av, 3),
796			   optional_num(av, 4, -1),
797			   optional_num(av, 5, -1),
798			   optional_num(av, 6, -1));
799}
800
801static int
802call_dselect(CALLARGS)
803{
804    *offset_add = arg_rest(av);
805    return dialog_dselect(t,
806			  av[1],
807			  numeric_arg(av, 2),
808			  numeric_arg(av, 3));
809}
810
811static int
812call_editbox(CALLARGS)
813{
814    *offset_add = 4;
815    return dialog_editbox(t,
816			  av[1],
817			  numeric_arg(av, 2),
818			  numeric_arg(av, 3));
819}
820
821static int
822call_fselect(CALLARGS)
823{
824    *offset_add = arg_rest(av);
825    return dialog_fselect(t,
826			  av[1],
827			  numeric_arg(av, 2),
828			  numeric_arg(av, 3));
829}
830
831static int
832call_timebox(CALLARGS)
833{
834    *offset_add = arg_rest(av);
835    return dialog_timebox(t,
836			  av[1],
837			  numeric_arg(av, 2),
838			  numeric_arg(av, 3),
839			  optional_num(av, 4, -1),
840			  optional_num(av, 5, -1),
841			  optional_num(av, 6, -1));
842}
843#endif /* HAVE_XDIALOG */
844
845/* dialog 1.2 widgets */
846#ifdef HAVE_XDIALOG2
847
848#define DisableNoTags() \
849	bool save_no_tags = dialog_vars.no_tags; \
850	bool save_no_items = dialog_vars.no_items; \
851	dialog_vars.no_tags = TRUE; \
852	dialog_vars.no_items = FALSE
853
854#define RestoreNoTags() \
855	dialog_vars.no_tags = save_no_tags; \
856	dialog_vars.no_items = save_no_items
857
858static int
859call_buildlist(CALLARGS)
860{
861    int tags = howmany_tags(av + 5, CHECKBOX_TAGS);
862    int result;
863
864    DisableNoTags();
865
866    *offset_add = 5 + tags * CHECKBOX_TAGS;
867    result = dialog_buildlist(t,
868			      av[1],
869			      numeric_arg(av, 2),
870			      numeric_arg(av, 3),
871			      numeric_arg(av, 4),
872			      tags, av + 5,
873			      TRUE);
874    RestoreNoTags();
875    return result;
876}
877
878static int
879call_rangebox(CALLARGS)
880{
881    int min_value;
882
883    *offset_add = arg_rest(av);
884    min_value = numeric_arg(av, 4);
885    return dialog_rangebox(t,
886			   av[1],
887			   numeric_arg(av, 2),
888			   numeric_arg(av, 3),
889			   min_value,
890			   numeric_arg(av, 5),
891			   (*offset_add > 6) ? numeric_arg(av, 6) : min_value);
892}
893
894static int
895call_treeview(CALLARGS)
896{
897    int tags = howmany_tags(av + 5, TREEVIEW_TAGS);
898    int result;
899
900    DisableNoTags();
901
902    *offset_add = arg_rest(av);
903    result = dialog_treeview(t,
904			     av[1],
905			     numeric_arg(av, 2),
906			     numeric_arg(av, 3),
907			     numeric_arg(av, 4),
908			     tags, av + 5, FLAG_RADIO);
909    RestoreNoTags();
910    return result;
911}
912#endif /* HAVE_XDIALOG */
913
914#ifdef HAVE_DLG_FORMBOX
915static int
916call_form(CALLARGS)
917{
918    int group = FORMBOX_TAGS;
919    int tags = howmany_tags(av + 5, group);
920    *offset_add = 5 + tags * group;
921
922    return dialog_form(t,
923		       av[1],
924		       numeric_arg(av, 2),
925		       numeric_arg(av, 3),
926		       numeric_arg(av, 4),
927		       tags, av + 5);
928}
929
930static int
931call_password_form(CALLARGS)
932{
933    unsigned save = dialog_vars.formitem_type;
934    int result;
935
936    dialog_vars.formitem_type = 1;
937    result = call_form(PASSARGS);
938    dialog_vars.formitem_type = save;
939
940    return result;
941}
942#endif /* HAVE_DLG_FORMBOX */
943
944#ifdef HAVE_DLG_MIXEDFORM
945static int
946call_mixed_form(CALLARGS)
947{
948    int group = MIXEDFORM_TAGS;
949    int tags = howmany_tags(av + 5, group);
950    *offset_add = 5 + tags * group;
951
952    return dialog_mixedform(t,
953			    av[1],
954			    numeric_arg(av, 2),
955			    numeric_arg(av, 3),
956			    numeric_arg(av, 4),
957			    tags, av + 5);
958}
959#endif /* HAVE_DLG_MIXEDFORM */
960
961#ifdef HAVE_DLG_GAUGE
962static int
963call_gauge(CALLARGS)
964{
965    *offset_add = arg_rest(av);
966    return dialog_gauge(t,
967			av[1],
968			numeric_arg(av, 2),
969			numeric_arg(av, 3),
970			optional_num(av, 4, 0));
971}
972
973static int
974call_pause(CALLARGS)
975{
976    *offset_add = arg_rest(av);
977    return dialog_pause(t,
978			av[1],
979			numeric_arg(av, 2),
980			numeric_arg(av, 3),
981			numeric_arg(av, 4));
982}
983#endif
984
985#ifdef HAVE_MIXEDGAUGE
986static int
987call_mixed_gauge(CALLARGS)
988{
989#define MIXEDGAUGE_BASE 5
990    int tags = howmany_tags(av + MIXEDGAUGE_BASE, MIXEDGAUGE_TAGS);
991    *offset_add = MIXEDGAUGE_BASE + tags * MIXEDGAUGE_TAGS;
992    return dialog_mixedgauge(t,
993			     av[1],
994			     numeric_arg(av, 2),
995			     numeric_arg(av, 3),
996			     numeric_arg(av, 4),
997			     tags, av + MIXEDGAUGE_BASE);
998}
999#endif
1000
1001#ifdef HAVE_DLG_GAUGE
1002static int
1003call_prgbox(CALLARGS)
1004{
1005    *offset_add = arg_rest(av);
1006    /* the original version does not accept a prompt string, but for
1007     * consistency we allow it.
1008     */
1009    return ((*offset_add == 5)
1010	    ? dialog_prgbox(t,
1011			    av[1],
1012			    av[2],
1013			    numeric_arg(av, 3),
1014			    numeric_arg(av, 4), TRUE)
1015	    : dialog_prgbox(t,
1016			    "",
1017			    av[1],
1018			    numeric_arg(av, 2),
1019			    numeric_arg(av, 3), TRUE));
1020}
1021#endif
1022
1023#ifdef HAVE_DLG_GAUGE
1024static int
1025call_programbox(CALLARGS)
1026{
1027    int result;
1028
1029    *offset_add = arg_rest(av);
1030    /* this function is a compromise between --prgbox and --progressbox.
1031     */
1032    result = ((*offset_add == 4)
1033	      ? dlg_progressbox(t,
1034				av[1],
1035				numeric_arg(av, 2),
1036				numeric_arg(av, 3),
1037				TRUE,
1038				dialog_state.pipe_input)
1039	      : dlg_progressbox(t,
1040				"",
1041				numeric_arg(av, 1),
1042				numeric_arg(av, 2),
1043				TRUE,
1044				dialog_state.pipe_input));
1045    dialog_state.pipe_input = 0;
1046    return result;
1047}
1048#endif
1049
1050#ifdef HAVE_DLG_GAUGE
1051static int
1052call_progressbox(CALLARGS)
1053{
1054    *offset_add = arg_rest(av);
1055    /* the original version does not accept a prompt string, but for
1056     * consistency we allow it.
1057     */
1058    return ((*offset_add == 4)
1059	    ? dialog_progressbox(t,
1060				 av[1],
1061				 numeric_arg(av, 2),
1062				 numeric_arg(av, 3))
1063	    : dialog_progressbox(t,
1064				 "",
1065				 numeric_arg(av, 1),
1066				 numeric_arg(av, 2)));
1067}
1068#endif
1069
1070#ifdef HAVE_DLG_TAILBOX
1071static int
1072call_tailbox(CALLARGS)
1073{
1074    *offset_add = 4;
1075    return dialog_tailbox(t,
1076			  av[1],
1077			  numeric_arg(av, 2),
1078			  numeric_arg(av, 3),
1079			  FALSE);
1080}
1081
1082static int
1083call_tailboxbg(CALLARGS)
1084{
1085    *offset_add = 4;
1086    return dialog_tailbox(t,
1087			  av[1],
1088			  numeric_arg(av, 2),
1089			  numeric_arg(av, 3),
1090			  TRUE);
1091}
1092#endif
1093/* *INDENT-OFF* */
1094static const Mode modes[] =
1095{
1096    {o_yesno,           4, 4, call_yesno},
1097    {o_msgbox,          4, 4, call_msgbox},
1098    {o_infobox,         4, 4, call_infobox},
1099    {o_textbox,         4, 4, call_textbox},
1100    {o_menu,            7, 0, call_menu},
1101    {o_inputmenu,       7, 0, call_inputmenu},
1102    {o_checklist,       8, 0, call_checklist},
1103    {o_radiolist,       8, 0, call_radiolist},
1104    {o_inputbox,        4, 5, call_inputbox},
1105    {o_passwordbox,     4, 5, call_passwordbox},
1106#ifdef HAVE_DLG_GAUGE
1107    {o_gauge,           4, 5, call_gauge},
1108    {o_pause,           5, 5, call_pause},
1109    {o_prgbox,          4, 5, call_prgbox},
1110    {o_programbox,      3, 4, call_programbox},
1111    {o_progressbox,     3, 4, call_progressbox},
1112#endif
1113#ifdef HAVE_DLG_FORMBOX
1114    {o_passwordform,   13, 0, call_password_form},
1115    {o_form,           13, 0, call_form},
1116#endif
1117#ifdef HAVE_MIXEDGAUGE
1118    {o_mixedgauge,      MIXEDGAUGE_BASE, 0, call_mixed_gauge},
1119#endif
1120#ifdef HAVE_DLG_MIXEDFORM
1121    {o_mixedform,      13, 0, call_mixed_form},
1122#endif
1123#ifdef HAVE_DLG_TAILBOX
1124    {o_tailbox,         4, 4, call_tailbox},
1125    {o_tailboxbg,       4, 4, call_tailboxbg},
1126#endif
1127#ifdef HAVE_XDIALOG
1128    {o_buildlist,       4, 0, call_buildlist},
1129    {o_calendar,        4, 7, call_calendar},
1130    {o_dselect,         4, 5, call_dselect},
1131    {o_editbox,         4, 4, call_editbox},
1132    {o_fselect,         4, 5, call_fselect},
1133    {o_rangebox,        5, 7, call_rangebox},
1134    {o_timebox,         4, 7, call_timebox},
1135    {o_treeview,        4, 0, call_treeview},
1136#endif
1137};
1138/* *INDENT-ON* */
1139
1140static char *
1141optionString(char **argv, int *num)
1142{
1143    int next = *num + 1;
1144    char *result = argv[next];
1145    if (result == 0) {
1146	char temp[80];
1147	sprintf(temp, "Expected a string-parameter for %.20s", argv[*num]);
1148	Usage(temp);
1149    }
1150    *num = next;
1151    return result;
1152}
1153
1154static int
1155optionValue(char **argv, int *num)
1156{
1157    int next = *num + 1;
1158    char *src = argv[next];
1159    char *tmp = 0;
1160    int result = 0;
1161
1162    if (src != 0) {
1163	result = (int) strtol(src, &tmp, 0);
1164	if (tmp == 0 || *tmp != 0)
1165	    src = 0;
1166    }
1167
1168    if (src == 0) {
1169	char temp[80];
1170	sprintf(temp, "Expected a numeric-parameter for %.20s", argv[*num]);
1171	Usage(temp);
1172    }
1173    *num = next;
1174    return result;
1175}
1176
1177/* Return exit-code for a named button */
1178static int
1179button_code(const char *name)
1180{
1181    /* *INDENT-OFF* */
1182    static struct {
1183	const char *name;
1184	int code;
1185    } table[] = {
1186	{ "ok",	    DLG_EXIT_OK },
1187	{ "yes",    DLG_EXIT_OK },
1188	{ "cancel", DLG_EXIT_CANCEL },
1189	{ "no",	    DLG_EXIT_CANCEL },
1190	{ "help",   DLG_EXIT_HELP },
1191	{ "extra",  DLG_EXIT_EXTRA },
1192    };
1193    /* *INDENT-ON* */
1194
1195    int code = DLG_EXIT_ERROR;
1196    size_t i;
1197
1198    for (i = 0; i < (sizeof(table) / sizeof(table[0])); i++) {
1199	if (!dlg_strcmp(name, table[i].name)) {
1200	    code = table[i].code;
1201	    break;
1202	}
1203    }
1204
1205    if (code == DLG_EXIT_ERROR) {
1206	char temp[80];
1207	sprintf(temp, "Button name \"%.20s\" unknown", name);
1208	Usage(temp);
1209    }
1210
1211    return code;
1212}
1213
1214/*
1215 * Print parts of a message
1216 */
1217static void
1218PrintList(const char *const *list)
1219{
1220    const char *leaf = strrchr(program, '/');
1221    unsigned n = 0;
1222
1223    if (leaf != 0)
1224	leaf++;
1225    else
1226	leaf = program;
1227
1228    while (*list != 0) {
1229	fprintf(dialog_state.output, *list, n ? leaf : dialog_version());
1230	(void) fputc('\n', dialog_state.output);
1231	n = 1;
1232	list++;
1233    }
1234}
1235
1236static const Mode *
1237lookupMode(eOptions code)
1238{
1239    const Mode *modePtr = 0;
1240    unsigned n;
1241
1242    for (n = 0; n < sizeof(modes) / sizeof(modes[0]); n++) {
1243	if (modes[n].code == code) {
1244	    modePtr = &modes[n];
1245	    break;
1246	}
1247    }
1248    return modePtr;
1249}
1250
1251static int
1252compare_opts(const void *a, const void *b)
1253{
1254    Options *const *p = (Options * const *) a;
1255    Options *const *q = (Options * const *) b;
1256    return strcmp((*p)->name, (*q)->name);
1257}
1258
1259/*
1260 * Print program's version.
1261 */
1262static void
1263PrintVersion(FILE *fp)
1264{
1265    fprintf(fp, "Version: %s\n", dialog_version());
1266}
1267
1268/*
1269 * Print program help-message
1270 */
1271static void
1272Help(void)
1273{
1274    static const char *const tbl_1[] =
1275    {
1276	"cdialog (ComeOn Dialog!) version %s",
1277	"Copyright 2000-2012,2013 Thomas E. Dickey",
1278	"This is free software; see the source for copying conditions.  There is NO",
1279	"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
1280	"",
1281	"* Display dialog boxes from shell scripts *",
1282	"",
1283	"Usage: %s <options> { --and-widget <options> }",
1284	"where options are \"common\" options, followed by \"box\" options",
1285	"",
1286#ifdef HAVE_RC_FILE
1287	"Special options:",
1288	"  [--create-rc \"file\"]",
1289#endif
1290	0
1291    }, *const tbl_3[] =
1292    {
1293	"",
1294	"Auto-size with height and width = 0. Maximize with height and width = -1.",
1295	"Global-auto-size if also menu_height/list_height = 0.",
1296	0
1297    };
1298    size_t limit = sizeof(options) / sizeof(options[0]);
1299    size_t j, k;
1300    const Options **opts;
1301
1302    end_dialog();
1303    dialog_state.output = stdout;
1304
1305    opts = dlg_calloc(const Options *, limit);
1306    assert_ptr(opts, "Help");
1307    for (j = 0; j < limit; ++j) {
1308	opts[j] = &(options[j]);
1309    }
1310    qsort(opts, limit, sizeof(Options *), compare_opts);
1311
1312    PrintList(tbl_1);
1313    fprintf(dialog_state.output, "Common options:\n ");
1314    for (j = k = 0; j < limit; j++) {
1315	if ((opts[j]->pass & 1)
1316	    && opts[j]->help != 0) {
1317	    size_t len = 6 + strlen(opts[j]->name) + strlen(opts[j]->help);
1318	    k += len;
1319	    if (k > 75) {
1320		fprintf(dialog_state.output, "\n ");
1321		k = len;
1322	    }
1323	    fprintf(dialog_state.output, " [--%s%s%s]", opts[j]->name,
1324		    *(opts[j]->help) ? " " : "", opts[j]->help);
1325	}
1326    }
1327    fprintf(dialog_state.output, "\nBox options:\n");
1328    for (j = 0; j < limit; j++) {
1329	if ((opts[j]->pass & 2) != 0
1330	    && opts[j]->help != 0
1331	    && lookupMode(opts[j]->code))
1332	    fprintf(dialog_state.output, "  --%-12s %s\n", opts[j]->name,
1333		    opts[j]->help);
1334    }
1335    PrintList(tbl_3);
1336
1337    free(opts);
1338    dlg_exit(DLG_EXIT_OK);
1339}
1340
1341#ifdef HAVE_DLG_TRACE
1342/*
1343 * Only the first call to dlg_trace will open a trace file.  But each time
1344 * --trace is parsed, we show the whole parameter list as it is at that moment,
1345 * counting discarded parameters.  The only way to capture the whole parameter
1346 * list is if --trace is the first option.
1347 */
1348static void
1349process_trace_option(char **argv, int *offset)
1350{
1351    int j;
1352
1353    if (dialog_state.trace_output == 0) {
1354	dlg_trace(optionString(argv, offset));
1355    } else {
1356	dlg_trace_msg("# ignore extra --trace option\n");
1357	*offset += 1;
1358    }
1359
1360    dlg_trace_msg("# Parameters:\n");
1361    for (j = 0; argv[j] != 0; ++j) {
1362	dlg_trace_msg("# argv[%d] = %s\n", j, argv[j]);
1363    }
1364}
1365#endif
1366
1367/*
1368 * "Common" options apply to all widgets more/less.  Most of the common options
1369 * set values in dialog_vars, a few set dialog_state and a couple write to the
1370 * output stream.
1371 */
1372static int
1373process_common_options(int argc, char **argv, int offset, bool output)
1374{
1375    bool done = FALSE;
1376
1377    dlg_trace_msg("# process_common_options, offset %d\n", offset);
1378
1379    while (offset < argc && !done) {	/* Common options */
1380	dlg_trace_msg("#\targv[%d] = %s\n", offset, argv[offset]);
1381	switch (lookupOption(argv[offset], 1)) {
1382	case o_title:
1383	    dialog_vars.title = optionString(argv, &offset);
1384	    break;
1385	case o_backtitle:
1386	    dialog_vars.backtitle = optionString(argv, &offset);
1387	    break;
1388	case o_separate_widget:
1389	    dialog_state.separate_str = optionString(argv, &offset);
1390	    break;
1391	case o_separate_output:
1392	    dialog_vars.separate_output = TRUE;
1393	    break;
1394	case o_colors:
1395	    dialog_vars.colors = TRUE;
1396	    break;
1397	case o_cr_wrap:
1398	    dialog_vars.cr_wrap = TRUE;
1399	    break;
1400	case o_no_nl_expand:
1401	    dialog_vars.no_nl_expand = TRUE;
1402	    break;
1403	case o_no_collapse:
1404	    dialog_vars.nocollapse = TRUE;
1405	    break;
1406	case o_no_kill:
1407	    dialog_vars.cant_kill = TRUE;
1408	    break;
1409	case o_nocancel:
1410	    dialog_vars.nocancel = TRUE;
1411	    break;
1412	case o_nook:
1413	    dialog_vars.nook = TRUE;
1414	    break;
1415	case o_quoted:
1416	    dialog_vars.quoted = TRUE;
1417	    break;
1418	case o_single_quoted:
1419	    dialog_vars.single_quoted = TRUE;
1420	    break;
1421	case o_size_err:
1422	    dialog_vars.size_err = TRUE;
1423	    break;
1424	case o_beep:
1425	    dialog_vars.beep_signal = TRUE;
1426	    break;
1427	case o_beep_after:
1428	    dialog_vars.beep_after_signal = TRUE;
1429	    break;
1430	case o_scrollbar:
1431	    dialog_state.use_scrollbar = TRUE;
1432	    break;
1433	case o_shadow:
1434	    dialog_state.use_shadow = TRUE;
1435	    break;
1436	case o_defaultno:
1437	    dialog_vars.defaultno = TRUE;
1438	    dialog_vars.default_button = DLG_EXIT_CANCEL;
1439	    break;
1440	case o_default_button:
1441	    dialog_vars.default_button = button_code(optionString(argv, &offset));
1442	    dialog_vars.defaultno = dialog_vars.default_button == DLG_EXIT_CANCEL;
1443	    break;
1444	case o_default_item:
1445	    dialog_vars.default_item = optionString(argv, &offset);
1446	    break;
1447	case o_insecure:
1448	    dialog_vars.insecure = TRUE;
1449	    break;
1450	case o_item_help:
1451	    dialog_vars.item_help = TRUE;
1452	    break;
1453	case o_help_line:
1454	    dialog_vars.help_line = optionString(argv, &offset);
1455	    break;
1456	case o_help_file:
1457	    dialog_vars.help_file = optionString(argv, &offset);
1458	    break;
1459	case o_help_button:
1460	    dialog_vars.help_button = TRUE;
1461	    break;
1462	case o_help_status:
1463	    dialog_vars.help_status = TRUE;
1464	    break;
1465	case o_extra_button:
1466	    dialog_vars.extra_button = TRUE;
1467	    break;
1468	case o_ignore:
1469	    ignore_unknown = TRUE;
1470	    break;
1471	case o_keep_window:
1472	    dialog_vars.keep_window = TRUE;
1473	    break;
1474	case o_last_key:
1475	    dialog_vars.last_key = TRUE;
1476	    break;
1477	case o_no_shadow:
1478	    dialog_state.use_shadow = FALSE;
1479	    break;
1480	case o_print_size:
1481	    dialog_vars.print_siz = TRUE;
1482	    break;
1483	case o_print_maxsize:
1484	    if (output) {
1485		/*
1486		 * If this is the last option, we do not want any error
1487		 * messages - just our output.  Calling end_dialog() cancels
1488		 * the refresh() at the end of the program as well.
1489		 */
1490		if (argv[offset + 1] == 0) {
1491		    ignore_unknown = TRUE;
1492		    end_dialog();
1493		}
1494		fflush(dialog_state.output);
1495		fprintf(dialog_state.output, "MaxSize: %d, %d\n", SLINES, SCOLS);
1496	    }
1497	    break;
1498	case o_print_version:
1499	    if (output) {
1500		PrintVersion(dialog_state.output);
1501	    }
1502	    break;
1503	case o_separator:
1504	case o_output_separator:
1505	    dialog_vars.output_separator = optionString(argv, &offset);
1506	    break;
1507	case o_column_separator:
1508	    dialog_vars.column_separator = optionString(argv, &offset);
1509	    break;
1510	case o_tab_correct:
1511	    dialog_vars.tab_correct = TRUE;
1512	    break;
1513	case o_sleep:
1514	    dialog_vars.sleep_secs = optionValue(argv, &offset);
1515	    break;
1516	case o_timeout:
1517	    dialog_vars.timeout_secs = optionValue(argv, &offset);
1518	    break;
1519	case o_max_input:
1520	    dialog_vars.max_input = optionValue(argv, &offset);
1521	    break;
1522	case o_tab_len:
1523	    dialog_state.tab_len = optionValue(argv, &offset);
1524	    break;
1525	case o_trim:
1526	    dialog_vars.trim_whitespace = TRUE;
1527	    break;
1528	case o_visit_items:
1529	    dialog_state.visit_items = TRUE;
1530	    dialog_state.visit_cols = 1;
1531	    break;
1532	case o_aspect:
1533	    dialog_state.aspect_ratio = optionValue(argv, &offset);
1534	    break;
1535	case o_begin:
1536	    dialog_vars.begin_set = TRUE;
1537	    dialog_vars.begin_y = optionValue(argv, &offset);
1538	    dialog_vars.begin_x = optionValue(argv, &offset);
1539	    break;
1540	case o_clear:
1541	    dialog_vars.dlg_clear_screen = TRUE;
1542	    break;
1543	case o_yes_label:
1544	    dialog_vars.yes_label = optionString(argv, &offset);
1545	    break;
1546	case o_no_label:
1547	    dialog_vars.no_label = optionString(argv, &offset);
1548	    break;
1549	case o_ok_label:
1550	    dialog_vars.ok_label = optionString(argv, &offset);
1551	    break;
1552	case o_cancel_label:
1553	    dialog_vars.cancel_label = optionString(argv, &offset);
1554	    break;
1555	case o_extra_label:
1556	    dialog_vars.extra_label = optionString(argv, &offset);
1557	    break;
1558	case o_exit_label:
1559	    dialog_vars.exit_label = optionString(argv, &offset);
1560	    break;
1561	case o_help_label:
1562	    dialog_vars.help_label = optionString(argv, &offset);
1563	    break;
1564	case o_date_format:
1565	    dialog_vars.date_format = optionString(argv, &offset);
1566	    break;
1567	case o_time_format:
1568	    dialog_vars.time_format = optionString(argv, &offset);
1569	    break;
1570	case o_keep_tite:
1571	    dialog_vars.keep_tite = TRUE;
1572	    break;
1573	case o_ascii_lines:
1574	    dialog_vars.ascii_lines = TRUE;
1575	    dialog_vars.no_lines = FALSE;
1576	    break;
1577	case o_no_lines:
1578	    dialog_vars.no_lines = TRUE;
1579	    dialog_vars.ascii_lines = FALSE;
1580	    break;
1581	case o_no_mouse:
1582	    dialog_state.no_mouse = TRUE;
1583	    mouse_close();
1584	    break;
1585#ifdef HAVE_WHIPTAIL
1586	case o_topleft:
1587	    dialog_vars.begin_set = TRUE;
1588	    dialog_vars.begin_y = 0;
1589	    dialog_vars.begin_x = 0;
1590	    break;
1591	case o_fullbutton:
1592	    /* ignore */
1593	    break;
1594#endif
1595	    /* options of Xdialog which we ignore */
1596	case o_icon:
1597	case o_wmclass:
1598	    (void) optionString(argv, &offset);
1599	    /* FALLTHRU */
1600	case o_allow_close:
1601	case o_auto_placement:
1602	case o_fixed_font:
1603	case o_keep_colors:
1604	case o_no_close:
1605	case o_no_cr_wrap:
1606	case o_screen_center:
1607	case o_smooth:
1608	case o_under_mouse:
1609	    break;
1610	case o_unknown:
1611	    if (ignore_unknown)
1612		break;
1613	    /* FALLTHRU */
1614	default:		/* no more common options */
1615	    done = TRUE;
1616	    break;
1617#ifdef HAVE_DLG_TRACE
1618	case o_trace:
1619	    process_trace_option(argv, &offset);
1620	    break;
1621#endif
1622#if defined(HAVE_XDIALOG2) || defined(HAVE_WHIPTAIL)
1623	case o_no_items:
1624	    dialog_vars.no_items = TRUE;
1625	    break;
1626	case o_no_tags:
1627	    dialog_vars.no_tags = TRUE;
1628	    break;
1629#endif
1630	}
1631	if (!done)
1632	    offset++;
1633    }
1634    return offset;
1635}
1636
1637/*
1638 * Initialize options at the start of a series of common options culminating
1639 * in a widget.
1640 */
1641static void
1642init_result(char *buffer)
1643{
1644    static bool first = TRUE;
1645    static char **special_argv = 0;
1646    static int special_argc = 0;
1647
1648    dlg_trace_msg("# init_result\n");
1649
1650    /* clear everything we do not save for the next widget */
1651    memset(&dialog_vars, 0, sizeof(dialog_vars));
1652
1653    dialog_vars.input_result = buffer;
1654    dialog_vars.input_result[0] = '\0';
1655
1656    dialog_vars.default_button = -1;
1657
1658    /*
1659     * The first time this is called, check for common options given by an
1660     * environment variable.
1661     */
1662    if (first) {
1663	char *env = getenv("DIALOGOPTS");
1664	if (env != 0)
1665	    env = dlg_strclone(env);
1666	if (env != 0) {
1667	    special_argv = dlg_string_to_argv(env);
1668	    special_argc = dlg_count_argv(special_argv);
1669	}
1670	first = FALSE;
1671    }
1672
1673    /*
1674     * If we are not checking memory leaks, just do the parse of the
1675     * environment once.
1676     */
1677    if (special_argv != 0) {
1678	process_common_options(special_argc, special_argv, 0, FALSE);
1679#ifdef NO_LEAKS
1680	free(special_argv[0]);
1681	free(special_argv);
1682	special_argv = 0;
1683	special_argc = 0;
1684	first = TRUE;
1685#endif
1686    }
1687}
1688
1689int
1690main(int argc, char *argv[])
1691{
1692    char temp[256];
1693    bool esc_pressed = FALSE;
1694    bool keep_tite = FALSE;
1695    int offset = 1;
1696    int offset_add;
1697    int retval = DLG_EXIT_OK;
1698    int j, have;
1699    eOptions code;
1700    const Mode *modePtr;
1701    char my_buffer[MAX_LEN + 1];
1702
1703    memset(&dialog_state, 0, sizeof(dialog_state));
1704    memset(&dialog_vars, 0, sizeof(dialog_vars));
1705
1706#if defined(ENABLE_NLS)
1707    /* initialize locale support */
1708    setlocale(LC_ALL, "");
1709    bindtextdomain(NLS_TEXTDOMAIN, LOCALEDIR);
1710    textdomain(NLS_TEXTDOMAIN);
1711#elif defined(HAVE_SETLOCALE)
1712    (void) setlocale(LC_ALL, "");
1713#endif
1714
1715    unescape_argv(&argc, &argv);
1716    program = argv[0];
1717    dialog_state.output = stderr;
1718    dialog_state.input = stdin;
1719
1720    /*
1721     * Look for the last --stdout, --stderr or --output-fd option, and use
1722     * that.  We can only write to one of them.  If --stdout is used, that
1723     * can interfere with initializing the curses library, so we want to
1724     * know explicitly if it is used.
1725     *
1726     * Also, look for any --version or --help message, processing those
1727     * immediately.
1728     */
1729    while (offset < argc) {
1730	int base = offset;
1731	switch (lookupOption(argv[offset], 7)) {
1732	case o_stdout:
1733	    dialog_state.output = stdout;
1734	    break;
1735	case o_stderr:
1736	    dialog_state.output = stderr;
1737	    break;
1738	case o_input_fd:
1739	    if ((j = optionValue(argv, &offset)) < 0
1740		|| (dialog_state.input = fdopen(j, "r")) == 0)
1741		dlg_exiterr("Cannot open input-fd\n");
1742	    break;
1743	case o_output_fd:
1744	    if ((j = optionValue(argv, &offset)) < 0
1745		|| (dialog_state.output = fdopen(j, "w")) == 0)
1746		dlg_exiterr("Cannot open output-fd\n");
1747	    break;
1748	case o_keep_tite:
1749	    keep_tite = TRUE;
1750	    break;
1751	case o_version:
1752	    dialog_state.output = stdout;
1753	    PrintVersion(dialog_state.output);
1754	    exit(DLG_EXIT_OK);
1755	    break;
1756	case o_help:
1757	    Help();
1758	    break;
1759#ifdef HAVE_DLG_TRACE
1760	case o_trace:
1761	    /*
1762	     * Process/remove the --trace option if it is the first option.
1763	     * Otherwise, process it in more/less expected order as a
1764	     * "common" option.
1765	     */
1766	    if (base == 1) {
1767		process_trace_option(argv, &offset);
1768		break;
1769	    } else {
1770		++offset;
1771		continue;
1772	    }
1773#endif
1774	default:
1775	    ++offset;
1776	    continue;
1777	}
1778	dlg_trace_msg("# discarding %d parameters starting with argv[%d] (%s)\n",
1779		      1 + offset - base, base,
1780		      argv[base]);
1781	for (j = base; j < argc; ++j) {
1782	    dialog_argv[j] = dialog_argv[j + 1 + (offset - base)];
1783	    if (dialog_opts != 0)
1784		dialog_opts[j] = dialog_opts[j + 1 + (offset - base)];
1785	}
1786	argc -= (1 + offset - base);
1787	offset = base;
1788    }
1789    offset = 1;
1790    init_result(my_buffer);
1791
1792    /*
1793     * Dialog's output may be redirected (see above).  Handle the special
1794     * case of options that only report information without interaction.
1795     */
1796    if (argc == 2) {
1797	switch (lookupOption(argv[1], 7)) {
1798	case o_print_maxsize:
1799	    (void) initscr();
1800	    endwin();
1801	    fflush(dialog_state.output);
1802	    fprintf(dialog_state.output, "MaxSize: %d, %d\n", SLINES, SCOLS);
1803	    break;
1804	case o_print_version:
1805	    PrintVersion(dialog_state.output);
1806	    break;
1807	case o_clear:
1808	    initscr();
1809	    refresh();
1810	    endwin();
1811	    break;
1812	case o_ignore:
1813	    break;
1814	default:
1815	    Help();
1816	    break;
1817	}
1818	return DLG_EXIT_OK;
1819    }
1820
1821    if (argc < 2) {
1822	Help();
1823    }
1824#ifdef HAVE_RC_FILE
1825    if (lookupOption(argv[1], 7) == o_create_rc) {
1826	if (argc != 3) {
1827	    sprintf(temp, "Expected a filename for %.50s", argv[1]);
1828	    Usage(temp);
1829	}
1830	if (dlg_parse_rc() == -1)	/* Read the configuration file */
1831	    dlg_exiterr("dialog: dlg_parse_rc");
1832	dlg_create_rc(argv[2]);
1833	return DLG_EXIT_OK;
1834    }
1835#endif
1836
1837    dialog_vars.keep_tite = keep_tite;	/* init_result() cleared global */
1838
1839    init_dialog(dialog_state.input, dialog_state.output);
1840
1841    while (offset < argc && !esc_pressed) {
1842	init_result(my_buffer);
1843
1844	offset = process_common_options(argc, argv, offset, TRUE);
1845
1846	if (argv[offset] == NULL) {
1847	    if (ignore_unknown)
1848		break;
1849	    Usage("Expected a box option");
1850	}
1851
1852	if (lookupOption(argv[offset], 2) != o_checklist
1853	    && dialog_vars.separate_output) {
1854	    sprintf(temp, "Expected --checklist, not %.20s", argv[offset]);
1855	    Usage(temp);
1856	}
1857
1858	if (dialog_state.aspect_ratio == 0)
1859	    dialog_state.aspect_ratio = DEFAULT_ASPECT_RATIO;
1860
1861	dlg_put_backtitle();
1862
1863	/* use a table to look for the requested mode, to avoid code duplication */
1864
1865	modePtr = 0;
1866	if ((code = lookupOption(argv[offset], 2)) != o_unknown)
1867	    modePtr = lookupMode(code);
1868	if (modePtr == 0) {
1869	    sprintf(temp, "%s option %.20s",
1870		    lookupOption(argv[offset], 7) != o_unknown
1871		    ? "Unexpected"
1872		    : "Unknown",
1873		    argv[offset]);
1874	    Usage(temp);
1875	}
1876
1877	have = arg_rest(&argv[offset]);
1878	if (have < modePtr->argmin) {
1879	    sprintf(temp, "Expected at least %d tokens for %.20s, have %d",
1880		    modePtr->argmin - 1, argv[offset],
1881		    have - 1);
1882	    Usage(temp);
1883	}
1884	if (modePtr->argmax && have > modePtr->argmax) {
1885	    sprintf(temp,
1886		    "Expected no more than %d tokens for %.20s, have %d",
1887		    modePtr->argmax - 1, argv[offset],
1888		    have - 1);
1889	    Usage(temp);
1890	}
1891
1892	/*
1893	 * Trim whitespace from non-title option values, e.g., the ones that
1894	 * will be used as captions or prompts.   Do that only for the widget
1895	 * we are about to process, since the "--trim" option is reset before
1896	 * accumulating options for each widget.
1897	 */
1898	for (j = offset + 1; j <= offset + have; j++) {
1899	    switch (lookupOption(argv[j - 1], 7)) {
1900	    case o_unknown:
1901	    case o_title:
1902	    case o_backtitle:
1903	    case o_help_line:
1904	    case o_help_file:
1905		break;
1906	    default:
1907		if (argv[j] != 0) {
1908		    char *argv_j = strdup(argv[j]);
1909		    if (argv_j != 0) {
1910			dlg_trim_string(argv_j);
1911			argv[j] = argv_j;
1912		    } else {
1913			argv[j] = strdup("?");
1914		    }
1915		}
1916		break;
1917	    }
1918	}
1919
1920	retval = show_result((*(modePtr->jumper)) (dialog_vars.title,
1921						   argv + offset,
1922						   &offset_add));
1923	dlg_trace_msg("# widget returns %d\n", retval);
1924	offset += offset_add;
1925
1926	if (dialog_vars.input_result != my_buffer) {
1927	    free(dialog_vars.input_result);
1928	    dialog_vars.input_result = 0;
1929	}
1930
1931	if (retval == DLG_EXIT_ESC) {
1932	    esc_pressed = TRUE;
1933	} else {
1934
1935	    if (dialog_vars.beep_after_signal)
1936		(void) beep();
1937
1938	    if (dialog_vars.sleep_secs)
1939		(void) napms(dialog_vars.sleep_secs * 1000);
1940
1941	    if (offset < argc) {
1942		switch (lookupOption(argv[offset], 7)) {
1943		case o_and_widget:
1944		    offset++;
1945		    break;
1946		case o_unknown:
1947		    sprintf(temp, "Expected --and-widget, not %.20s",
1948			    argv[offset]);
1949		    Usage(temp);
1950		    break;
1951		default:
1952		    /* if we got a cancel, etc., stop chaining */
1953		    if (retval != DLG_EXIT_OK)
1954			esc_pressed = TRUE;
1955		    else
1956			dialog_vars.dlg_clear_screen = TRUE;
1957		    break;
1958		}
1959	    }
1960	    if (dialog_vars.dlg_clear_screen)
1961		dlg_clear();
1962	}
1963    }
1964
1965    dlg_killall_bg(&retval);
1966    if (dialog_state.screen_initialized) {
1967	(void) refresh();
1968	end_dialog();
1969    }
1970    dlg_exit(retval);
1971}
1972