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