summaryrefslogtreecommitdiff
path: root/dialog.c
blob: e80f559e63aec937942d7fe08516785181bf496d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
/*
 * $Id: dialog.c,v 1.237 2014/02/19 19:49:04 tom Exp $
 *
 *  cdialog - Display simple dialog boxes from shell scripts
 *
 *  Copyright 2000-2013,2014	Thomas E. Dickey
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License, version 2.1
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to
 *	Free Software Foundation, Inc.
 *	51 Franklin St., Fifth Floor
 *	Boston, MA 02110, USA.
 *
 *  An earlier version of this program lists as authors
 *	Savio Lam (lam836@cs.cuhk.hk)
 */

#include <dialog.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#ifdef HAVE_SETLOCALE
#include <locale.h>
#endif

#define PASSARGS             t,       av,        offset_add
#define CALLARGS const char *t, char *av[], int *offset_add
typedef int (callerFn) (CALLARGS);

typedef enum {
    o_unknown = 0
    ,o_allow_close
    ,o_and_widget
    ,o_ascii_lines
    ,o_aspect
    ,o_auto_placement
    ,o_backtitle
    ,o_beep
    ,o_beep_after
    ,o_begin
    ,o_cancel_label
    ,o_checklist
    ,o_clear
    ,o_colors
    ,o_column_separator
    ,o_cr_wrap
    ,o_create_rc
    ,o_date_format
    ,o_default_button
    ,o_default_item
    ,o_defaultno
    ,o_exit_label
    ,o_extra_button
    ,o_extra_label
    ,o_fixed_font
    ,o_form
    ,o_gauge
    ,o_help
    ,o_help_button
    ,o_help_file
    ,o_help_label
    ,o_help_line
    ,o_help_status
    ,o_help_tags
    ,o_icon
    ,o_ignore
    ,o_infobox
    ,o_input_fd
    ,o_inputbox
    ,o_inputmenu
    ,o_insecure
    ,o_item_help
    ,o_keep_colors
    ,o_keep_tite
    ,o_keep_window
    ,o_last_key
    ,o_max_input
    ,o_menu
    ,o_mixedform
    ,o_mixedgauge
    ,o_msgbox
    ,o_no_close
    ,o_no_collapse
    ,o_no_cr_wrap
    ,o_no_kill
    ,o_no_label
    ,o_no_lines
    ,o_no_mouse
    ,o_no_nl_expand
    ,o_no_shadow
    ,o_nocancel
    ,o_nook
    ,o_ok_label
    ,o_output_fd
    ,o_output_separator
    ,o_passwordbox
    ,o_passwordform
    ,o_pause
    ,o_prgbox
    ,o_print_maxsize
    ,o_print_size
    ,o_print_version
    ,o_programbox
    ,o_progressbox
    ,o_quoted
    ,o_radiolist
    ,o_screen_center
    ,o_scrollbar
    ,o_separate_output
    ,o_separate_widget
    ,o_separator
    ,o_shadow
    ,o_single_quoted
    ,o_size_err
    ,o_sleep
    ,o_smooth
    ,o_stderr
    ,o_stdout
    ,o_tab_correct
    ,o_tab_len
    ,o_tailbox
    ,o_tailboxbg
    ,o_textbox
    ,o_time_format
    ,o_timeout
    ,o_title
    ,o_trim
    ,o_under_mouse
    ,o_version
    ,o_visit_items
    ,o_wmclass
    ,o_yes_label
    ,o_yesno
#ifdef HAVE_WHIPTAIL
    ,o_fullbutton
    ,o_topleft
#endif
#ifdef HAVE_XDIALOG
    ,o_calendar
    ,o_dselect
    ,o_editbox
    ,o_fselect
    ,o_timebox
#endif
#ifdef HAVE_XDIALOG2
    ,o_buildlist
    ,o_rangebox
    ,o_treeview
#endif
#if defined(HAVE_XDIALOG2) || defined(HAVE_WHIPTAIL)
    ,o_no_items
    ,o_no_tags
#endif
#ifdef HAVE_DLG_TRACE
    ,o_trace
#endif
} eOptions;

/*
 * The bits in 'pass' are used to decide which options are applicable at
 * different stages in the program:
 *	1 flags before widgets
 *	2 widgets
 *	4 non-widget options
 */
typedef struct {
    const char *name;
    eOptions code;
    int pass;			/* 1,2,4 or combination */
    const char *help;		/* NULL to suppress, non-empty to display params */
} Options;

typedef struct {
    eOptions code;
    int argmin, argmax;
    callerFn *jumper;
} Mode;

static bool *dialog_opts;
static char **dialog_argv;

static bool ignore_unknown = FALSE;

static const char *program = "dialog";

/*
 * The options[] table is organized this way to make it simple to maintain
 * a sorted list of options for the help-message.
 */
/* *INDENT-OFF* */
static const Options options[] = {
    { "allow-close",	o_allow_close,		1, NULL },
    { "and-widget",	o_and_widget,		4, NULL },
    { "ascii-lines",	o_ascii_lines, 		1, "" },
    { "aspect",		o_aspect,		1, "<ratio>" },
    { "auto-placement", o_auto_placement,	1, NULL },
    { "backtitle",	o_backtitle,		1, "<backtitle>" },
    { "beep",		o_beep,			1, "" },
    { "beep-after",	o_beep_after,		1, "" },
    { "begin",		o_begin,		1, "<y> <x>" },
    { "cancel-label",	o_cancel_label,		1, "<str>" },
    { "checklist",	o_checklist,		2, "<text> <height> <width> <list height> <tag1> <item1> <status1>..." },
    { "clear",		o_clear,		1, "" },
    { "colors",		o_colors,		1, "" },
    { "column-separator",o_column_separator,	1, "<str>" },
    { "cr-wrap",	o_cr_wrap,		1, "" },
    { "create-rc",	o_create_rc,		1, NULL },
    { "date-format",	o_date_format,		1, "<str>" },
    { "default-button",	o_default_button,	1, "<str>" },
    { "default-item",	o_default_item,		1, "<str>" },
    { "defaultno",	o_defaultno,		1, "" },
    { "exit-label",	o_exit_label,		1, "<str>" },
    { "extra-button",	o_extra_button,		1, "" },
    { "extra-label",	o_extra_label,		1, "<str>" },
    { "fixed-font",	o_fixed_font,		1, NULL },
    { "form",		o_form,			2, "<text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1>..." },
    { "gauge",		o_gauge,		2, "<text> <height> <width> [<percent>]" },
    { "guage",		o_gauge,		2, NULL },
    { "help",		o_help,			4, "" },
    { "help-button",	o_help_button,		1, "" },
    { "help-label",	o_help_label,		1, "<str>" },
    { "help-status",	o_help_status,		1, "" },
    { "help-tags",	o_help_tags,		1, "" },
    { "hfile",		o_help_file,		1, "<str>" },
    { "hline",		o_help_line,		1, "<str>" },
    { "icon",		o_icon,			1, NULL },
    { "ignore",		o_ignore,		1, "" },
    { "infobox",	o_infobox,		2, "<text> <height> <width>" },
    { "input-fd",	o_input_fd,		1, "<fd>" },
    { "inputbox",	o_inputbox,		2, "<text> <height> <width> [<init>]" },
    { "inputmenu",	o_inputmenu,		2, "<text> <height> <width> <menu height> <tag1> <item1>..." },
    { "insecure",	o_insecure,		1, "" },
    { "item-help",	o_item_help,		1, "" },
    { "keep-colors",	o_keep_colors,		1, NULL },
    { "keep-tite",	o_keep_tite,		1, "" },
    { "keep-window",	o_keep_window,		1, "" },
    { "last-key",	o_last_key,		1, "" },
    { "max-input",	o_max_input,		1, "<n>" },
    { "menu",		o_menu,			2, "<text> <height> <width> <menu height> <tag1> <item1>..." },
    { "mixedform",	o_mixedform,		2, "<text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1> <itype>..." },
    { "mixedgauge",	o_mixedgauge,		2, "<text> <height> <width> <percent> <tag1> <item1>..." },
    { "msgbox",		o_msgbox,		2, "<text> <height> <width>" },
    { "no-cancel",	o_nocancel,		1, "" },
    { "no-close",	o_no_close,		1, NULL },
    { "no-collapse",	o_no_collapse,		1, "" },
    { "no-cr-wrap",	o_no_cr_wrap,		1, "" },
    { "no-kill",	o_no_kill,		1, "" },
    { "no-label",	o_no_label,		1, "<str>" },
    { "no-lines",	o_no_lines, 		1, "" },
    { "no-mouse",	o_no_mouse,		1, "" },
    { "no-nl-expand",	o_no_nl_expand,		1, "" },
    { "no-ok",		o_nook,			1, "" },
    { "no-shadow",	o_no_shadow,		1, "" },
    { "nocancel",	o_nocancel,		1, NULL }, /* see --no-cancel */
    { "nook",		o_nook,			1, "" }, /* See no-ok */
    { "ok-label",	o_ok_label,		1, "<str>" },
    { "output-fd",	o_output_fd,		1, "<fd>" },
    { "output-separator",o_output_separator,	1, "<str>" },
    { "passwordbox",	o_passwordbox,		2, "<text> <height> <width> [<init>]" },
    { "passwordform",	o_passwordform,		2, "<text> <height> <width> <form height> <label1> <l_y1> <l_x1> <item1> <i_y1> <i_x1> <flen1> <ilen1>..." },
    { "pause",		o_pause,		2, "<text> <height> <width> <seconds>" },
    { "prgbox",		o_prgbox,		2, "<text> <command> <height> <width>" },
    { "print-maxsize",	o_print_maxsize,	1, "" },
    { "print-size",	o_print_size,		1, "" },
    { "print-version",	o_print_version,	5, "" },
    { "programbox",	o_programbox,		2, "<text> <height> <width>" },
    { "progressbox",	o_progressbox,		2, "<text> <height> <width>" },
    { "quoted",		o_quoted,		1, "" },
    { "radiolist",	o_radiolist,		2, "<text> <height> <width> <list height> <tag1> <item1> <status1>..." },
    { "screen-center",	o_screen_center,	1, NULL },
    { "scrollbar",	o_scrollbar,		1, "" },
    { "separate-output",o_separate_output,	1, "" },
    { "separate-widget",o_separate_widget,	1, "<str>" },
    { "separator",	o_separator,		1, NULL },
    { "shadow",		o_shadow,		1, "" },
    { "single-quoted",	o_single_quoted,	1, "" },
    { "size-err",	o_size_err,		1, "" },
    { "sleep",		o_sleep,		1, "<secs>" },
    { "smooth",		o_smooth,		1, NULL },
    { "stderr",		o_stderr,		1, "" },
    { "stdout",		o_stdout,		1, "" },
    { "tab-correct",	o_tab_correct,		1, "" },
    { "tab-len",	o_tab_len,		1, "<n>" },
    { "tailbox",	o_tailbox,		2, "<file> <height> <width>" },
    { "tailboxbg",	o_tailboxbg,		2, "<file> <height> <width>" },
    { "textbox",	o_textbox,		2, "<file> <height> <width>" },
    { "time-format",	o_time_format,		1, "<str>" },
    { "timeout",	o_timeout,		1, "<secs>" },
    { "title",		o_title,		1, "<title>" },
    { "trim",		o_trim,			1, "" },
    { "under-mouse", 	o_under_mouse,		1, NULL },
    { "version",	o_version,		5, "" },
    { "visit-items", 	o_visit_items,		1, "" },
    { "wmclass",	o_wmclass,		1, NULL },
    { "yes-label",	o_yes_label,		1, "<str>" },
    { "yesno",		o_yesno,		2, "<text> <height> <width>" },
#ifdef HAVE_WHIPTAIL
    { "cancel-button",	o_cancel_label,		1, NULL },
    { "fb",		o_fullbutton,		1, NULL },
    { "fullbutton",	o_fullbutton,		1, NULL },
    { "no-button",	o_no_label,		1, NULL },
    { "ok-button",	o_ok_label,		1, NULL },
    { "scrolltext",	o_scrollbar,		1, NULL },
    { "topleft",	o_topleft,		1, NULL },
    { "yes-button",	o_yes_label,		1, NULL },
#endif
#ifdef HAVE_XDIALOG
    { "calendar",	o_calendar,		2, "<text> <height> <width> <day> <month> <year>" },
    { "dselect",	o_dselect,		2, "<directory> <height> <width>" },
    { "editbox",	o_editbox,		2, "<file> <height> <width>" },
    { "fselect",	o_fselect,		2, "<filepath> <height> <width>" },
    { "timebox",	o_timebox,		2, "<text> <height> <width> <hour> <minute> <second>" },
#endif
#ifdef HAVE_XDIALOG2
    { "buildlist",	o_buildlist,		2, "<text> <height> <width> <tag1> <item1> <status1>..." },
    { "no-items", 	o_no_items,		1, "" },
    { "no-tags", 	o_no_tags,		1, "" },
    { "rangebox",	o_rangebox,		2, "<text> <height> <width> <min-value> <max-value> <default-value>" },
    { "treeview",	o_treeview,		2, "<text> <height> <width> <list-height> <tag1> <item1> <status1> <depth1>..." },
#endif
#if defined(HAVE_XDIALOG2) || defined(HAVE_WHIPTAIL)
    { "noitem", 	o_no_items,		1, NULL },
    { "notags", 	o_no_tags,		1, NULL },
#endif
#ifdef HAVE_DLG_TRACE
    { "trace",		o_trace,		1, "<file>" },
#endif
};
/* *INDENT-ON* */

/*
 * Make an array showing which argv[] entries are options.  Use "--" as a
 * special token to escape the next argument, allowing it to begin with "--".
 * When we find a "--" argument, also remove it from argv[] and adjust argc.
 * That appears to be an undocumented feature of the popt library.
 *
 * Also, if we see a "--file", expand it into the parameter list by reading the
 * text from the given file and stripping quotes, treating whitespace outside
 * quotes as a parameter delimiter.
 *
 * Finally, if we see a "--args", dump the current list of arguments to the
 * standard error.  This is used for debugging complex --file combinations.
 */
static void
unescape_argv(int *argcp, char ***argvp)
{
    int j, k;
    int limit_includes = 20 + *argcp;
    int count_includes = 0;
    bool changed = FALSE;
    bool doalloc = FALSE;
    char *filename;

    dialog_opts = dlg_calloc(bool, (size_t) *argcp + 1);
    assert_ptr(dialog_opts, "unescape_argv");

    for (j = 1; j < *argcp; j++) {
	bool escaped = FALSE;
	if (!strcmp((*argvp)[j], "--")) {
	    escaped = TRUE;
	    changed = dlg_eat_argv(argcp, argvp, j, 1);
	} else if (!strcmp((*argvp)[j], "--args")) {
	    fprintf(stderr, "Showing arguments at arg%d\n", j);
	    for (k = 0; k < *argcp; ++k) {
		fprintf(stderr, " arg%d:%s\n", k, (*argvp)[k]);
	    }
	    changed = dlg_eat_argv(argcp, argvp, j, 1);
	    --j;
	} else if (!strcmp((*argvp)[j], "--file")) {
	    if (++count_includes > limit_includes)
		dlg_exiterr("Too many --file options");

	    if ((filename = (*argvp)[j + 1]) != 0) {
		FILE *fp;
		char **list;
		char *blob;
		int added;
		size_t bytes_read;
		size_t length;
		int n;

		if (*filename == '&') {
		    fp = fdopen(atoi(filename + sizeof(char)), "r");
		} else {
		    fp = fopen(filename, "r");
		}

		if (fp) {
		    blob = NULL;
		    length = 0;
		    do {
			blob = dlg_realloc(char, length + BUFSIZ + 1, blob);
			assert_ptr(blob, "unescape_argv");
			bytes_read = fread(blob + length,
					   sizeof(char),
					     (size_t) BUFSIZ,
					   fp);
			length += bytes_read;
			if (ferror(fp))
			    dlg_exiterr("error on filehandle in unescape_argv");
		    } while (bytes_read == BUFSIZ);
		    fclose(fp);

		    blob[length] = '\0';

		    list = dlg_string_to_argv(blob);
		    if ((added = dlg_count_argv(list)) != 0) {
			if (added > 2) {
			    size_t need = (size_t) (*argcp + added + 1);
			    if (doalloc) {
				*argvp = dlg_realloc(char *, need, *argvp);
				assert_ptr(*argvp, "unescape_argv");
			    } else {
				char **newp = dlg_malloc(char *, need);
				assert_ptr(newp, "unescape_argv");
				for (n = 0; n < *argcp; ++n) {
				    newp[n] = (*argvp)[n];
				}
				*argvp = newp;
				doalloc = TRUE;
			    }
			    dialog_opts = dlg_realloc(bool, need, dialog_opts);
			    assert_ptr(dialog_opts, "unescape_argv");
			}
			if (added > 2) {
			    for (n = *argcp; n >= j + 2; --n) {
				(*argvp)[n + added - 2] = (*argvp)[n];
				dialog_opts[n + added - 2] = dialog_opts[n];
			    }
			} else if (added == 1) {
			    for (n = j; n < *argcp; ++n) {
				(*argvp)[n] = (*argvp)[n + 1];
				dialog_opts[n] = dialog_opts[n + 1];
			    }
			}
			for (n = 0; n < added; ++n) {
			    (*argvp)[n + j] = list[n];
			    dialog_opts[n + j] = FALSE;
			}
			*argcp += added - 2;
			free(list);
			--j;	/* force rescan */
		    }
		} else {
		    dlg_exiterr("Cannot open --file %s", filename);
		}
		(*argvp)[*argcp] = 0;
		++j;
		continue;
	    } else {
		dlg_exiterr("No value given for --file");
	    }
	}
	if (!escaped
	    && (*argvp)[j] != 0
	    && !strncmp((*argvp)[j], "--", (size_t) 2)
	    && isalpha(UCH((*argvp)[j][2]))) {
	    dialog_opts[j] = TRUE;
	}
    }

    /* if we didn't find any "--" tokens, there's no reason to do the table
     * lookup in isOption()
     */
    if (!changed) {
	free(dialog_opts);
	dialog_opts = 0;
    }
    dialog_argv = (*argvp);
}

#define OptionChars "\
0123456789\
-\
abcdefghijklmnopqrstuvwxyz\
"

/*
 * Check if the given string from main's argv is an option.
 */
static bool
isOption(const char *arg)
{
    bool result = FALSE;

    if (arg != 0) {
	if (dialog_opts != 0) {
	    int n;
	    for (n = 1; dialog_argv[n] != 0; ++n) {
		if (dialog_argv[n] == arg) {
		    result = dialog_opts[n];
		    break;
		}
	    }
	} else if (!strncmp(arg, "--", (size_t) 2) && isalpha(UCH(arg[2]))) {
	    if (strlen(arg) == (strspn) (arg, OptionChars)) {
		result = TRUE;
	    } else {
		dlg_exiterr("Invalid option \"%s\"", arg);
	    }
	}
    }
    return result;
}

static eOptions
lookupOption(const char *name, int pass)
{
    unsigned n;
    eOptions result = o_unknown;

    if (isOption(name)) {
	name += 2;
	for (n = 0; n < sizeof(options) / sizeof(options[0]); n++) {
	    if ((pass & options[n].pass) != 0
		&& !strcmp(name, options[n].name)) {
		result = options[n].code;
		break;
	    }
	}
    }
    return result;
}

static void
Usage(const char *msg)
{
    dlg_exiterr("Error: %s.\nUse --help to list options.\n\n", msg);
}

/*
 * Count arguments, stopping at the end of the argument list, or on any of our
 * "--" tokens.
 */
static int
arg_rest(char *argv[])
{
    int i = 1;			/* argv[0] points to a "--" token */

    while (argv[i] != 0
	   && (!isOption(argv[i]) || lookupOption(argv[i], 7) == o_unknown))
	i++;
    return i;
}

/*
 * In MultiWidget this function is needed to count how many tags
 * a widget (menu, checklist, radiolist) has
 */
static int
howmany_tags(char *argv[], int group)
{
    int result = 0;
    int have;
    const char *format = "Expected %d arguments, found only %d";
    char temp[80];

    while (argv[0] != 0) {
	if (isOption(argv[0]))
	    break;
	if ((have = arg_rest(argv)) < group) {
	    sprintf(temp, format, group, have);
	    Usage(temp);
	}

	argv += group;
	result++;
    }

    return result;
}

static int
numeric_arg(char **av, int n)
{
    int result = 0;

    if (n < dlg_count_argv(av)) {
	char msg[80];
	char *last = 0;
	result = (int) strtol(av[n], &last, 10);

	if (last == 0 || *last != 0) {
	    sprintf(msg, "Expected a number for token %d of %.20s", n, av[0]);
	    Usage(msg);
	}
    }
    return result;
}

static char *
optional_str(char **av, int n, char *dft)
{
    char *ret = dft;
    if (arg_rest(av) > n)
	ret = av[n];
    return ret;
}

#if defined(HAVE_DLG_GAUGE) || defined(HAVE_XDIALOG)
static int
optional_num(char **av, int n, int dft)
{
    int ret = dft;
    if (arg_rest(av) > n)
	ret = numeric_arg(av, n);
    return ret;
}
#endif

/*
 * On AIX 4.x, we have to flush the output right away since there is a bug in
 * the curses package which discards stdout even when we've used newterm to
 * redirect output to /dev/tty.
 */
static int
show_result(int ret)
{
    bool either = FALSE;

    switch (ret) {
    case DLG_EXIT_OK:
    case DLG_EXIT_EXTRA:
    case DLG_EXIT_HELP:
    case DLG_EXIT_ITEM_HELP:
	if ((dialog_state.output_count > 1) && !dialog_vars.separate_output) {
	    fputs((dialog_state.separate_str
		   ? dialog_state.separate_str
		   : DEFAULT_SEPARATE_STR),
		  dialog_state.output);
	    either = TRUE;
	}
	if (dialog_vars.input_result != 0
	    && dialog_vars.input_result[0] != '\0') {
	    fputs(dialog_vars.input_result, dialog_state.output);
	    either = TRUE;
	}
	if (either) {
	    fflush(dialog_state.output);
	}
	break;
    }
    return ret;
}

/*
 * These are the widget callers.
 */

static int
call_yesno(CALLARGS)
{
    *offset_add = 4;
    return dialog_yesno(t,
			av[1],
			numeric_arg(av, 2),
			numeric_arg(av, 3));
}

static int
call_msgbox(CALLARGS)
{
    *offset_add = 4;
    return dialog_msgbox(t,
			 av[1],
			 numeric_arg(av, 2),
			 numeric_arg(av, 3), 1);
}

static int
call_infobox(CALLARGS)
{
    *offset_add = 4;
    return dialog_msgbox(t,
			 av[1],
			 numeric_arg(av, 2),
			 numeric_arg(av, 3), 0);
}

static int
call_textbox(CALLARGS)
{
    *offset_add = 4;
    return dialog_textbox(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3));
}

static int
call_menu(CALLARGS)
{
    int tags = howmany_tags(av + 5, MENUBOX_TAGS);
    *offset_add = 5 + tags * MENUBOX_TAGS;

    return dialog_menu(t,
		       av[1],
		       numeric_arg(av, 2),
		       numeric_arg(av, 3),
		       numeric_arg(av, 4),
		       tags, av + 5);
}

static int
call_inputmenu(CALLARGS)
{
    int tags = howmany_tags(av + 5, MENUBOX_TAGS);
    bool free_extra_label = FALSE;
    int result;

    dialog_vars.input_menu = TRUE;

    if (dialog_vars.max_input == 0)
	dialog_vars.max_input = MAX_LEN / 2;

    if (dialog_vars.extra_label == 0) {
	free_extra_label = TRUE;
	dialog_vars.extra_label = dlg_strclone(_("Rename"));
    }

    dialog_vars.extra_button = TRUE;

    *offset_add = 5 + tags * MENUBOX_TAGS;
    result = dialog_menu(t,
			 av[1],
			 numeric_arg(av, 2),
			 numeric_arg(av, 3),
			 numeric_arg(av, 4),
			 tags, av + 5);
    if (free_extra_label) {
	free(dialog_vars.extra_label);
	dialog_vars.extra_label = 0;
    }
    return result;
}

static int
call_checklist(CALLARGS)
{
    int tags = howmany_tags(av + 5, CHECKBOX_TAGS);
    int code;

    *offset_add = 5 + tags * CHECKBOX_TAGS;
    code = dialog_checklist(t,
			    av[1],
			    numeric_arg(av, 2),
			    numeric_arg(av, 3),
			    numeric_arg(av, 4),
			    tags, av + 5, FLAG_CHECK);
    return code;
}

static int
call_radiolist(CALLARGS)
{
    int tags = howmany_tags(av + 5, CHECKBOX_TAGS);
    *offset_add = 5 + tags * CHECKBOX_TAGS;
    return dialog_checklist(t,
			    av[1],
			    numeric_arg(av, 2),
			    numeric_arg(av, 3),
			    numeric_arg(av, 4),
			    tags, av + 5, FLAG_RADIO);
}

static int
call_inputbox(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_inputbox(t,
			   av[1],
			   numeric_arg(av, 2),
			   numeric_arg(av, 3),
			   optional_str(av, 4, 0), 0);
}

static int
call_passwordbox(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_inputbox(t,
			   av[1],
			   numeric_arg(av, 2),
			   numeric_arg(av, 3),
			   optional_str(av, 4, 0), 1);
}

#ifdef HAVE_XDIALOG
static int
call_calendar(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_calendar(t,
			   av[1],
			   numeric_arg(av, 2),
			   numeric_arg(av, 3),
			   optional_num(av, 4, -1),
			   optional_num(av, 5, -1),
			   optional_num(av, 6, -1));
}

static int
call_dselect(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_dselect(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3));
}

static int
call_editbox(CALLARGS)
{
    *offset_add = 4;
    return dialog_editbox(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3));
}

static int
call_fselect(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_fselect(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3));
}

static int
call_timebox(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_timebox(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3),
			  optional_num(av, 4, -1),
			  optional_num(av, 5, -1),
			  optional_num(av, 6, -1));
}
#endif /* HAVE_XDIALOG */

/* dialog 1.2 widgets */
#ifdef HAVE_XDIALOG2

#define DisableNoTags() \
	bool save_no_tags = dialog_vars.no_tags; \
	bool save_no_items = dialog_vars.no_items; \
	dialog_vars.no_tags = TRUE; \
	dialog_vars.no_items = FALSE

#define RestoreNoTags() \
	dialog_vars.no_tags = save_no_tags; \
	dialog_vars.no_items = save_no_items

static int
call_buildlist(CALLARGS)
{
    int tags = howmany_tags(av + 5, CHECKBOX_TAGS);
    int result;

    DisableNoTags();

    *offset_add = 5 + tags * CHECKBOX_TAGS;
    result = dialog_buildlist(t,
			      av[1],
			      numeric_arg(av, 2),
			      numeric_arg(av, 3),
			      numeric_arg(av, 4),
			      tags, av + 5,
			      TRUE);
    RestoreNoTags();
    return result;
}

static int
call_rangebox(CALLARGS)
{
    int min_value;

    *offset_add = arg_rest(av);
    min_value = numeric_arg(av, 4);
    return dialog_rangebox(t,
			   av[1],
			   numeric_arg(av, 2),
			   numeric_arg(av, 3),
			   min_value,
			   numeric_arg(av, 5),
			   (*offset_add > 6) ? numeric_arg(av, 6) : min_value);
}

static int
call_treeview(CALLARGS)
{
    int tags = howmany_tags(av + 5, TREEVIEW_TAGS);
    int result;

    DisableNoTags();

    *offset_add = arg_rest(av);
    result = dialog_treeview(t,
			     av[1],
			     numeric_arg(av, 2),
			     numeric_arg(av, 3),
			     numeric_arg(av, 4),
			     tags, av + 5, FLAG_RADIO);
    RestoreNoTags();
    return result;
}
#endif /* HAVE_XDIALOG */

#ifdef HAVE_DLG_FORMBOX
static int
call_form(CALLARGS)
{
    int group = FORMBOX_TAGS;
    int tags = howmany_tags(av + 5, group);
    *offset_add = 5 + tags * group;

    return dialog_form(t,
		       av[1],
		       numeric_arg(av, 2),
		       numeric_arg(av, 3),
		       numeric_arg(av, 4),
		       tags, av + 5);
}

static int
call_password_form(CALLARGS)
{
    unsigned save = dialog_vars.formitem_type;
    int result;

    dialog_vars.formitem_type = 1;
    result = call_form(PASSARGS);
    dialog_vars.formitem_type = save;

    return result;
}
#endif /* HAVE_DLG_FORMBOX */

#ifdef HAVE_DLG_MIXEDFORM
static int
call_mixed_form(CALLARGS)
{
    int group = MIXEDFORM_TAGS;
    int tags = howmany_tags(av + 5, group);
    *offset_add = 5 + tags * group;

    return dialog_mixedform(t,
			    av[1],
			    numeric_arg(av, 2),
			    numeric_arg(av, 3),
			    numeric_arg(av, 4),
			    tags, av + 5);
}
#endif /* HAVE_DLG_MIXEDFORM */

#ifdef HAVE_DLG_GAUGE
static int
call_gauge(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_gauge(t,
			av[1],
			numeric_arg(av, 2),
			numeric_arg(av, 3),
			optional_num(av, 4, 0));
}

static int
call_pause(CALLARGS)
{
    *offset_add = arg_rest(av);
    return dialog_pause(t,
			av[1],
			numeric_arg(av, 2),
			numeric_arg(av, 3),
			numeric_arg(av, 4));
}
#endif

#ifdef HAVE_MIXEDGAUGE
static int
call_mixed_gauge(CALLARGS)
{
#define MIXEDGAUGE_BASE 5
    int tags = howmany_tags(av + MIXEDGAUGE_BASE, MIXEDGAUGE_TAGS);
    *offset_add = MIXEDGAUGE_BASE + tags * MIXEDGAUGE_TAGS;
    return dialog_mixedgauge(t,
			     av[1],
			     numeric_arg(av, 2),
			     numeric_arg(av, 3),
			     numeric_arg(av, 4),
			     tags, av + MIXEDGAUGE_BASE);
}
#endif

#ifdef HAVE_DLG_GAUGE
static int
call_prgbox(CALLARGS)
{
    *offset_add = arg_rest(av);
    /* the original version does not accept a prompt string, but for
     * consistency we allow it.
     */
    return ((*offset_add == 5)
	    ? dialog_prgbox(t,
			    av[1],
			    av[2],
			    numeric_arg(av, 3),
			    numeric_arg(av, 4), TRUE)
	    : dialog_prgbox(t,
			    "",
			    av[1],
			    numeric_arg(av, 2),
			    numeric_arg(av, 3), TRUE));
}
#endif

#ifdef HAVE_DLG_GAUGE
static int
call_programbox(CALLARGS)
{
    int result;

    *offset_add = arg_rest(av);
    /* this function is a compromise between --prgbox and --progressbox.
     */
    result = ((*offset_add == 4)
	      ? dlg_progressbox(t,
				av[1],
				numeric_arg(av, 2),
				numeric_arg(av, 3),
				TRUE,
				dialog_state.pipe_input)
	      : dlg_progressbox(t,
				"",
				numeric_arg(av, 1),
				numeric_arg(av, 2),
				TRUE,
				dialog_state.pipe_input));
    dialog_state.pipe_input = 0;
    return result;
}
#endif

#ifdef HAVE_DLG_GAUGE
static int
call_progressbox(CALLARGS)
{
    *offset_add = arg_rest(av);
    /* the original version does not accept a prompt string, but for
     * consistency we allow it.
     */
    return ((*offset_add == 4)
	    ? dialog_progressbox(t,
				 av[1],
				 numeric_arg(av, 2),
				 numeric_arg(av, 3))
	    : dialog_progressbox(t,
				 "",
				 numeric_arg(av, 1),
				 numeric_arg(av, 2)));
}
#endif

#ifdef HAVE_DLG_TAILBOX
static int
call_tailbox(CALLARGS)
{
    *offset_add = 4;
    return dialog_tailbox(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3),
			  FALSE);
}

static int
call_tailboxbg(CALLARGS)
{
    *offset_add = 4;
    return dialog_tailbox(t,
			  av[1],
			  numeric_arg(av, 2),
			  numeric_arg(av, 3),
			  TRUE);
}
#endif
/* *INDENT-OFF* */
static const Mode modes[] =
{
    {o_yesno,           4, 4, call_yesno},
    {o_msgbox,          4, 4, call_msgbox},
    {o_infobox,         4, 4, call_infobox},
    {o_textbox,         4, 4, call_textbox},
    {o_menu,            7, 0, call_menu},
    {o_inputmenu,       7, 0, call_inputmenu},
    {o_checklist,       8, 0, call_checklist},
    {o_radiolist,       8, 0, call_radiolist},
    {o_inputbox,        4, 5, call_inputbox},
    {o_passwordbox,     4, 5, call_passwordbox},
#ifdef HAVE_DLG_GAUGE
    {o_gauge,           4, 5, call_gauge},
    {o_pause,           5, 5, call_pause},
    {o_prgbox,          4, 5, call_prgbox},
    {o_programbox,      3, 4, call_programbox},
    {o_progressbox,     3, 4, call_progressbox},
#endif
#ifdef HAVE_DLG_FORMBOX
    {o_passwordform,   13, 0, call_password_form},
    {o_form,           13, 0, call_form},
#endif
#ifdef HAVE_MIXEDGAUGE
    {o_mixedgauge,      MIXEDGAUGE_BASE, 0, call_mixed_gauge},
#endif
#ifdef HAVE_DLG_MIXEDFORM
    {o_mixedform,      13, 0, call_mixed_form},
#endif
#ifdef HAVE_DLG_TAILBOX
    {o_tailbox,         4, 4, call_tailbox},
    {o_tailboxbg,       4, 4, call_tailboxbg},
#endif
#ifdef HAVE_XDIALOG
    {o_buildlist,       4, 0, call_buildlist},
    {o_calendar,        4, 7, call_calendar},
    {o_dselect,         4, 5, call_dselect},
    {o_editbox,         4, 4, call_editbox},
    {o_fselect,         4, 5, call_fselect},
    {o_rangebox,        5, 7, call_rangebox},
    {o_timebox,         4, 7, call_timebox},
    {o_treeview,        4, 0, call_treeview},
#endif
};
/* *INDENT-ON* */

static char *
optionString(char **argv, int *num)
{
    int next = *num + 1;
    char *result = argv[next];
    if (result == 0) {
	char temp[80];
	sprintf(temp, "Expected a string-parameter for %.20s", argv[*num]);
	Usage(temp);
    }
    *num = next;
    return result;
}

static int
optionValue(char **argv, int *num)
{
    int next = *num + 1;
    char *src = argv[next];
    char *tmp = 0;
    int result = 0;

    if (src != 0) {
	result = (int) strtol(src, &tmp, 0);
	if (tmp == 0 || *tmp != 0)
	    src = 0;
    }

    if (src == 0) {
	char temp[80];
	sprintf(temp, "Expected a numeric-parameter for %.20s", argv[*num]);
	Usage(temp);
    }
    *num = next;
    return result;
}

/* Return exit-code for a named button */
static int
button_code(const char *name)
{
    /* *INDENT-OFF* */
    static struct {
	const char *name;
	int code;
    } table[] = {
	{ "ok",	    DLG_EXIT_OK },
	{ "yes",    DLG_EXIT_OK },
	{ "cancel", DLG_EXIT_CANCEL },
	{ "no",	    DLG_EXIT_CANCEL },
	{ "help",   DLG_EXIT_HELP },
	{ "extra",  DLG_EXIT_EXTRA },
    };
    /* *INDENT-ON* */

    int code = DLG_EXIT_ERROR;
    size_t i;

    for (i = 0; i < (sizeof(table) / sizeof(table[0])); i++) {
	if (!dlg_strcmp(name, table[i].name)) {
	    code = table[i].code;
	    break;
	}
    }

    if (code == DLG_EXIT_ERROR) {
	char temp[80];
	sprintf(temp, "Button name \"%.20s\" unknown", name);
	Usage(temp);
    }

    return code;
}

/*
 * Print parts of a message
 */
static void
PrintList(const char *const *list)
{
    const char *leaf = strrchr(program, '/');
    unsigned n = 0;

    if (leaf != 0)
	leaf++;
    else
	leaf = program;

    while (*list != 0) {
	fprintf(dialog_state.output, *list, n ? leaf : dialog_version());
	(void) fputc('\n', dialog_state.output);
	n = 1;
	list++;
    }
}

static const Mode *
lookupMode(eOptions code)
{
    const Mode *modePtr = 0;
    unsigned n;

    for (n = 0; n < sizeof(modes) / sizeof(modes[0]); n++) {
	if (modes[n].code == code) {
	    modePtr = &modes[n];
	    break;
	}
    }
    return modePtr;
}

static int
compare_opts(const void *a, const void *b)
{
    Options *const *p = (Options * const *) a;
    Options *const *q = (Options * const *) b;
    return strcmp((*p)->name, (*q)->name);
}

/*
 * Print program's version.
 */
static void
PrintVersion(FILE *fp)
{
    fprintf(fp, "Version: %s\n", dialog_version());
}

/*
 * Print program help-message
 */
static void
Help(void)
{
    static const char *const tbl_1[] =
    {
	"cdialog (ComeOn Dialog!) version %s",
	"Copyright 2000-2013,2014 Thomas E. Dickey",
	"This is free software; see the source for copying conditions.  There is NO",
	"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
	"",
	"* Display dialog boxes from shell scripts *",
	"",
	"Usage: %s <options> { --and-widget <options> }",
	"where options are \"common\" options, followed by \"box\" options",
	"",
#ifdef HAVE_RC_FILE
	"Special options:",
	"  [--create-rc \"file\"]",
#endif
	0
    }, *const tbl_3[] =
    {
	"",
	"Auto-size with height and width = 0. Maximize with height and width = -1.",
	"Global-auto-size if also menu_height/list_height = 0.",
	0
    };
    size_t limit = sizeof(options) / sizeof(options[0]);
    size_t j, k;
    const Options **opts;

    end_dialog();
    dialog_state.output = stdout;

    opts = dlg_calloc(const Options *, limit);
    assert_ptr(opts, "Help");
    for (j = 0; j < limit; ++j) {
	opts[j] = &(options[j]);
    }
    qsort(opts, limit, sizeof(Options *), compare_opts);

    PrintList(tbl_1);
    fprintf(dialog_state.output, "Common options:\n ");
    for (j = k = 0; j < limit; j++) {
	if ((opts[j]->pass & 1)
	    && opts[j]->help != 0) {
	    size_t len = 6 + strlen(opts[j]->name) + strlen(opts[j]->help);
	    k += len;
	    if (k > 75) {
		fprintf(dialog_state.output, "\n ");
		k = len;
	    }
	    fprintf(dialog_state.output, " [--%s%s%s]", opts[j]->name,
		    *(opts[j]->help) ? " " : "", opts[j]->help);
	}
    }
    fprintf(dialog_state.output, "\nBox options:\n");
    for (j = 0; j < limit; j++) {
	if ((opts[j]->pass & 2) != 0
	    && opts[j]->help != 0
	    && lookupMode(opts[j]->code))
	    fprintf(dialog_state.output, "  --%-12s %s\n", opts[j]->name,
		    opts[j]->help);
    }
    PrintList(tbl_3);

    free(opts);
    dlg_exit(DLG_EXIT_OK);
}

#ifdef HAVE_DLG_TRACE
/*
 * Only the first call to dlg_trace will open a trace file.  But each time
 * --trace is parsed, we show the whole parameter list as it is at that moment,
 * counting discarded parameters.  The only way to capture the whole parameter
 * list is if --trace is the first option.
 */
static void
process_trace_option(char **argv, int *offset)
{
    int j;

    if (dialog_state.trace_output == 0) {
	dlg_trace(optionString(argv, offset));
    } else {
	dlg_trace_msg("# ignore extra --trace option\n");
	*offset += 1;
    }

    dlg_trace_msg("# Parameters:\n");
    for (j = 0; argv[j] != 0; ++j) {
	dlg_trace_msg("# argv[%d] = %s\n", j, argv[j]);
    }
}
#endif

/*
 * "Common" options apply to all widgets more/less.  Most of the common options
 * set values in dialog_vars, a few set dialog_state and a couple write to the
 * output stream.
 */
static int
process_common_options(int argc, char **argv, int offset, bool output)
{
    bool done = FALSE;

    dlg_trace_msg("# process_common_options, offset %d\n", offset);

    while (offset < argc && !done) {	/* Common options */
	dlg_trace_msg("#\targv[%d] = %s\n", offset, argv[offset]);
	switch (lookupOption(argv[offset], 1)) {
	case o_title:
	    dialog_vars.title = optionString(argv, &offset);
	    break;
	case o_backtitle:
	    dialog_vars.backtitle = optionString(argv, &offset);
	    break;
	case o_separate_widget:
	    dialog_state.separate_str = optionString(argv, &offset);
	    break;
	case o_separate_output:
	    dialog_vars.separate_output = TRUE;
	    break;
	case o_colors:
	    dialog_vars.colors = TRUE;
	    break;
	case o_cr_wrap:
	    dialog_vars.cr_wrap = TRUE;
	    break;
	case o_no_nl_expand:
	    dialog_vars.no_nl_expand = TRUE;
	    break;
	case o_no_collapse:
	    dialog_vars.nocollapse = TRUE;
	    break;
	case o_no_kill:
	    dialog_vars.cant_kill = TRUE;
	    break;
	case o_nocancel:
	    dialog_vars.nocancel = TRUE;
	    break;
	case o_nook:
	    dialog_vars.nook = TRUE;
	    break;
	case o_quoted:
	    dialog_vars.quoted = TRUE;
	    break;
	case o_single_quoted:
	    dialog_vars.single_quoted = TRUE;
	    break;
	case o_size_err:
	    dialog_vars.size_err = TRUE;
	    break;
	case o_beep:
	    dialog_vars.beep_signal = TRUE;
	    break;
	case o_beep_after:
	    dialog_vars.beep_after_signal = TRUE;
	    break;
	case o_scrollbar:
	    dialog_state.use_scrollbar = TRUE;
	    break;
	case o_shadow:
	    dialog_state.use_shadow = TRUE;
	    break;
	case o_defaultno:
	    dialog_vars.defaultno = TRUE;
	    dialog_vars.default_button = DLG_EXIT_CANCEL;
	    break;
	case o_default_button:
	    dialog_vars.default_button = button_code(optionString(argv, &offset));
	    dialog_vars.defaultno = dialog_vars.default_button == DLG_EXIT_CANCEL;
	    break;
	case o_default_item:
	    dialog_vars.default_item = optionString(argv, &offset);
	    break;
	case o_insecure:
	    dialog_vars.insecure = TRUE;
	    break;
	case o_item_help:
	    dialog_vars.item_help = TRUE;
	    break;
	case o_help_line:
	    dialog_vars.help_line = optionString(argv, &offset);
	    break;
	case o_help_file:
	    dialog_vars.help_file = optionString(argv, &offset);
	    break;
	case o_help_button:
	    dialog_vars.help_button = TRUE;
	    break;
	case o_help_status:
	    dialog_vars.help_status = TRUE;
	    break;
	case o_help_tags:
	    dialog_vars.help_tags = TRUE;
	    break;
	case o_extra_button:
	    dialog_vars.extra_button = TRUE;
	    break;
	case o_ignore:
	    ignore_unknown = TRUE;
	    break;
	case o_keep_window:
	    dialog_vars.keep_window = TRUE;
	    break;
	case o_last_key:
	    dialog_vars.last_key = TRUE;
	    break;
	case o_no_shadow:
	    dialog_state.use_shadow = FALSE;
	    break;
	case o_print_size:
	    dialog_vars.print_siz = TRUE;
	    break;
	case o_print_maxsize:
	    if (output) {
		/*
		 * If this is the last option, we do not want any error
		 * messages - just our output.  Calling end_dialog() cancels
		 * the refresh() at the end of the program as well.
		 */
		if (argv[offset + 1] == 0) {
		    ignore_unknown = TRUE;
		    end_dialog();
		}
		fflush(dialog_state.output);
		fprintf(dialog_state.output, "MaxSize: %d, %d\n", SLINES, SCOLS);
	    }
	    break;
	case o_print_version:
	    if (output) {
		PrintVersion(dialog_state.output);
	    }
	    break;
	case o_separator:
	case o_output_separator:
	    dialog_vars.output_separator = optionString(argv, &offset);
	    break;
	case o_column_separator:
	    dialog_vars.column_separator = optionString(argv, &offset);
	    break;
	case o_tab_correct:
	    dialog_vars.tab_correct = TRUE;
	    break;
	case o_sleep:
	    dialog_vars.sleep_secs = optionValue(argv, &offset);
	    break;
	case o_timeout:
	    dialog_vars.timeout_secs = optionValue(argv, &offset);
	    break;
	case o_max_input:
	    dialog_vars.max_input = optionValue(argv, &offset);
	    break;
	case o_tab_len:
	    dialog_state.tab_len = optionValue(argv, &offset);
	    break;
	case o_trim:
	    dialog_vars.trim_whitespace = TRUE;
	    break;
	case o_visit_items:
	    dialog_state.visit_items = TRUE;
	    dialog_state.visit_cols = 1;
	    break;
	case o_aspect:
	    dialog_state.aspect_ratio = optionValue(argv, &offset);
	    break;
	case o_begin:
	    dialog_vars.begin_set = TRUE;
	    dialog_vars.begin_y = optionValue(argv, &offset);
	    dialog_vars.begin_x = optionValue(argv, &offset);
	    break;
	case o_clear:
	    dialog_vars.dlg_clear_screen = TRUE;
	    break;
	case o_yes_label:
	    dialog_vars.yes_label = optionString(argv, &offset);
	    break;
	case o_no_label:
	    dialog_vars.no_label = optionString(argv, &offset);
	    break;
	case o_ok_label:
	    dialog_vars.ok_label = optionString(argv, &offset);
	    break;
	case o_cancel_label:
	    dialog_vars.cancel_label = optionString(argv, &offset);
	    break;
	case o_extra_label:
	    dialog_vars.extra_label = optionString(argv, &offset);
	    break;
	case o_exit_label:
	    dialog_vars.exit_label = optionString(argv, &offset);
	    break;
	case o_help_label:
	    dialog_vars.help_label = optionString(argv, &offset);
	    break;
	case o_date_format:
	    dialog_vars.date_format = optionString(argv, &offset);
	    break;
	case o_time_format:
	    dialog_vars.time_format = optionString(argv, &offset);
	    break;
	case o_keep_tite:
	    dialog_vars.keep_tite = TRUE;
	    break;
	case o_ascii_lines:
	    dialog_vars.ascii_lines = TRUE;
	    dialog_vars.no_lines = FALSE;
	    break;
	case o_no_lines:
	    dialog_vars.no_lines = TRUE;
	    dialog_vars.ascii_lines = FALSE;
	    break;
	case o_no_mouse:
	    dialog_state.no_mouse = TRUE;
	    mouse_close();
	    break;
#ifdef HAVE_WHIPTAIL
	case o_topleft:
	    dialog_vars.begin_set = TRUE;
	    dialog_vars.begin_y = 0;
	    dialog_vars.begin_x = 0;
	    break;
	case o_fullbutton:
	    /* ignore */
	    break;
#endif
	    /* options of Xdialog which we ignore */
	case o_icon:
	case o_wmclass:
	    (void) optionString(argv, &offset);
	    /* FALLTHRU */
	case o_allow_close:
	case o_auto_placement:
	case o_fixed_font:
	case o_keep_colors:
	case o_no_close:
	case o_no_cr_wrap:
	case o_screen_center:
	case o_smooth:
	case o_under_mouse:
	    break;
	case o_unknown:
	    if (ignore_unknown)
		break;
	    /* FALLTHRU */
	default:		/* no more common options */
	    done = TRUE;
	    break;
#ifdef HAVE_DLG_TRACE
	case o_trace:
	    process_trace_option(argv, &offset);
	    break;
#endif
#if defined(HAVE_XDIALOG2) || defined(HAVE_WHIPTAIL)
	case o_no_items:
	    dialog_vars.no_items = TRUE;
	    break;
	case o_no_tags:
	    dialog_vars.no_tags = TRUE;
	    break;
#endif
	}
	if (!done)
	    offset++;
    }
    return offset;
}

/*
 * Initialize options at the start of a series of common options culminating
 * in a widget.
 */
static void
init_result(char *buffer)
{
    static bool first = TRUE;
    static char **special_argv = 0;
    static int special_argc = 0;

    dlg_trace_msg("# init_result\n");

    /* clear everything we do not save for the next widget */
    memset(&dialog_vars, 0, sizeof(dialog_vars));

    dialog_vars.input_result = buffer;
    dialog_vars.input_result[0] = '\0';

    dialog_vars.default_button = -1;

    /*
     * The first time this is called, check for common options given by an
     * environment variable.
     */
    if (first) {
	char *env = getenv("DIALOGOPTS");
	if (env != 0)
	    env = dlg_strclone(env);
	if (env != 0) {
	    special_argv = dlg_string_to_argv(env);
	    special_argc = dlg_count_argv(special_argv);
	}
	first = FALSE;
    }

    /*
     * If we are not checking memory leaks, just do the parse of the
     * environment once.
     */
    if (special_argv != 0) {
	process_common_options(special_argc, special_argv, 0, FALSE);
#ifdef NO_LEAKS
	free(special_argv[0]);
	free(special_argv);
	special_argv = 0;
	special_argc = 0;
	first = TRUE;
#endif
    }
}

int
main(int argc, char *argv[])
{
    char temp[256];
    bool esc_pressed = FALSE;
    bool keep_tite = FALSE;
    int offset = 1;
    int offset_add;
    int retval = DLG_EXIT_OK;
    int j, have;
    eOptions code;
    const Mode *modePtr;
    char my_buffer[MAX_LEN + 1];

    memset(&dialog_state, 0, sizeof(dialog_state));
    memset(&dialog_vars, 0, sizeof(dialog_vars));

#if defined(ENABLE_NLS)
    /* initialize locale support */
    setlocale(LC_ALL, "");
    bindtextdomain(NLS_TEXTDOMAIN, LOCALEDIR);
    textdomain(NLS_TEXTDOMAIN);
#elif defined(HAVE_SETLOCALE)
    (void) setlocale(LC_ALL, "");
#endif

    unescape_argv(&argc, &argv);
    program = argv[0];
    dialog_state.output = stderr;
    dialog_state.input = stdin;

    /*
     * Look for the last --stdout, --stderr or --output-fd option, and use
     * that.  We can only write to one of them.  If --stdout is used, that
     * can interfere with initializing the curses library, so we want to
     * know explicitly if it is used.
     *
     * Also, look for any --version or --help message, processing those
     * immediately.
     */
    while (offset < argc) {
	int base = offset;
	switch (lookupOption(argv[offset], 7)) {
	case o_stdout:
	    dialog_state.output = stdout;
	    break;
	case o_stderr:
	    dialog_state.output = stderr;
	    break;
	case o_input_fd:
	    if ((j = optionValue(argv, &offset)) < 0
		|| (dialog_state.input = fdopen(j, "r")) == 0)
		dlg_exiterr("Cannot open input-fd\n");
	    break;
	case o_output_fd:
	    if ((j = optionValue(argv, &offset)) < 0
		|| (dialog_state.output = fdopen(j, "w")) == 0)
		dlg_exiterr("Cannot open output-fd\n");
	    break;
	case o_keep_tite:
	    keep_tite = TRUE;
	    break;
	case o_version:
	    dialog_state.output = stdout;
	    PrintVersion(dialog_state.output);
	    exit(DLG_EXIT_OK);
	    break;
	case o_help:
	    Help();
	    break;
#ifdef HAVE_DLG_TRACE
	case o_trace:
	    /*
	     * Process/remove the --trace option if it is the first option.
	     * Otherwise, process it in more/less expected order as a
	     * "common" option.
	     */
	    if (base == 1) {
		process_trace_option(argv, &offset);
		break;
	    } else {
		++offset;
		continue;
	    }
#endif
	default:
	    ++offset;
	    continue;
	}
	dlg_trace_msg("# discarding %d parameters starting with argv[%d] (%s)\n",
		      1 + offset - base, base,
		      argv[base]);
	for (j = base; j < argc; ++j) {
	    dialog_argv[j] = dialog_argv[j + 1 + (offset - base)];
	    if (dialog_opts != 0)
		dialog_opts[j] = dialog_opts[j + 1 + (offset - base)];
	}
	argc -= (1 + offset - base);
	offset = base;
    }
    offset = 1;
    init_result(my_buffer);

    /*
     * Dialog's output may be redirected (see above).  Handle the special
     * case of options that only report information without interaction.
     */
    if (argc == 2) {
	switch (lookupOption(argv[1], 7)) {
	case o_print_maxsize:
	    (void) initscr();
	    endwin();
	    fflush(dialog_state.output);
	    fprintf(dialog_state.output, "MaxSize: %d, %d\n", SLINES, SCOLS);
	    break;
	case o_print_version:
	    PrintVersion(dialog_state.output);
	    break;
	case o_clear:
	    initscr();
	    refresh();
	    endwin();
	    break;
	case o_ignore:
	    break;
	default:
	    Help();
	    break;
	}
	return DLG_EXIT_OK;
    }

    if (argc < 2) {
	Help();
    }
#ifdef HAVE_RC_FILE
    if (lookupOption(argv[1], 7) == o_create_rc) {
	if (argc != 3) {
	    sprintf(temp, "Expected a filename for %.50s", argv[1]);
	    Usage(temp);
	}
	if (dlg_parse_rc() == -1)	/* Read the configuration file */
	    dlg_exiterr("dialog: dlg_parse_rc");
	dlg_create_rc(argv[2]);
	return DLG_EXIT_OK;
    }
#endif

    dialog_vars.keep_tite = keep_tite;	/* init_result() cleared global */

    init_dialog(dialog_state.input, dialog_state.output);

    while (offset < argc && !esc_pressed) {
	init_result(my_buffer);

	offset = process_common_options(argc, argv, offset, TRUE);

	if (argv[offset] == NULL) {
	    if (ignore_unknown)
		break;
	    Usage("Expected a box option");
	}

	if (dialog_vars.separate_output) {
	    switch (lookupOption(argv[offset], 2)) {
#ifdef HAVE_XDIALOG2
	    case o_buildlist:
	    case o_treeview:
#endif
	    case o_checklist:
		break;
	    default:
		sprintf(temp,
			"Unexpected widget with --separate-output %.20s",
			argv[offset]);
		Usage(temp);
	    }
	}

	if (dialog_state.aspect_ratio == 0)
	    dialog_state.aspect_ratio = DEFAULT_ASPECT_RATIO;

	dlg_put_backtitle();

	/* use a table to look for the requested mode, to avoid code duplication */

	modePtr = 0;
	if ((code = lookupOption(argv[offset], 2)) != o_unknown)
	    modePtr = lookupMode(code);
	if (modePtr == 0) {
	    sprintf(temp, "%s option %.20s",
		    lookupOption(argv[offset], 7) != o_unknown
		    ? "Unexpected"
		    : "Unknown",
		    argv[offset]);
	    Usage(temp);
	}

	have = arg_rest(&argv[offset]);
	if (have < modePtr->argmin) {
	    sprintf(temp, "Expected at least %d tokens for %.20s, have %d",
		    modePtr->argmin - 1, argv[offset],
		    have - 1);
	    Usage(temp);
	}
	if (modePtr->argmax && have > modePtr->argmax) {
	    sprintf(temp,
		    "Expected no more than %d tokens for %.20s, have %d",
		    modePtr->argmax - 1, argv[offset],
		    have - 1);
	    Usage(temp);
	}

	/*
	 * Trim whitespace from non-title option values, e.g., the ones that
	 * will be used as captions or prompts.   Do that only for the widget
	 * we are about to process, since the "--trim" option is reset before
	 * accumulating options for each widget.
	 */
	for (j = offset + 1; j <= offset + have; j++) {
	    switch (lookupOption(argv[j - 1], 7)) {
	    case o_unknown:
	    case o_title:
	    case o_backtitle:
	    case o_help_line:
	    case o_help_file:
		break;
	    default:
		if (argv[j] != 0) {
		    char *argv_j = strdup(argv[j]);
		    if (argv_j != 0) {
			dlg_trim_string(argv_j);
			argv[j] = argv_j;
		    } else {
			argv[j] = strdup("?");
		    }
		}
		break;
	    }
	}

	retval = show_result((*(modePtr->jumper)) (dialog_vars.title,
						   argv + offset,
						   &offset_add));
	dlg_trace_msg("# widget returns %d\n", retval);
	offset += offset_add;

	if (dialog_vars.input_result != my_buffer) {
	    free(dialog_vars.input_result);
	    dialog_vars.input_result = 0;
	}

	if (retval == DLG_EXIT_ESC) {
	    esc_pressed = TRUE;
	} else {

	    if (dialog_vars.beep_after_signal)
		(void) beep();

	    if (dialog_vars.sleep_secs)
		(void) napms(dialog_vars.sleep_secs * 1000);

	    if (offset < argc) {
		switch (lookupOption(argv[offset], 7)) {
		case o_and_widget:
		    offset++;
		    break;
		case o_unknown:
		    sprintf(temp, "Expected --and-widget, not %.20s",
			    argv[offset]);
		    Usage(temp);
		    break;
		default:
		    /* if we got a cancel, etc., stop chaining */
		    if (retval != DLG_EXIT_OK)
			esc_pressed = TRUE;
		    else
			dialog_vars.dlg_clear_screen = TRUE;
		    break;
		}
	    }
	    if (dialog_vars.dlg_clear_screen)
		dlg_clear();
	}
    }

    dlg_killall_bg(&retval);
    if (dialog_state.screen_initialized) {
	(void) refresh();
	end_dialog();
    }
    dlg_exit(retval);
}