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