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