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