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