File: TermClui.py

package info (click to toggle)
libterm-clui-perl 1.76-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 368 kB
  • sloc: perl: 2,910; python: 2,096; makefile: 2
file content (2246 lines) | stat: -rw-r--r-- 72,918 bytes parent folder | download | duplicates (2)
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
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
#! /usr/bin/python3
r'''
a Python3 module offering a Command-Line User Interface

 from TermClui import *
 chosen = choose("A Title", a_list);  # single choice
 chosen = choose("A Title", a_list, multichoice=True)  # multiple choice
 x = choose("Which ?\n(Mouse, or Arrow-keys and Return)", w) # multi-line q
 x = choose("Which ?\n"+help_text(), w)    # built-in help_text
 confirm(text) and do_something()
 answer = ask(question)
 answer = ask(question, suggestion)
 password = ask_password("Enter password : ")
 filename = ask_filename("Which file ?")
 newtext = edit(title, oldtext)
 edit(filename)
 view(title, text)  # if title is not a filename
 view(textfile)    # if textfile _is_ a filename
 edit(choose("Edit which file ?", list_of_files))
 file  = select_file(Readable=True, TopDir="/home", FPat="*.html")
 files = select_file(Chdir=False, multichoice=True, FPat="*.mp3")
 os.chdir(select_file(Directory=True, Path=os.getcwd()))

TermClui.py offers a high-level user interface to give the user
of command-line applications a consistent "look and feel".  Its
metaphor for the computer is as a human-like conversation-partner;
as each question/response is completed, it is summarised to one line
and remains on screen, so that the history of the session gradually
accumulates on the screen, available for review or for cut/paste.
This user-interface can be intermixed with standard applications
which write to STDOUT or STDERR, such as make, pgp, rcs etc.

For the user, choose() uses either (since 1.50) the mouse; or arrow
keys (or hjkl) and Return or q; also SpaceBar for multiple choices.
confirm() expects y, Y, n or N.  In general, ctrl-L redraws the
(currently active bit of the) screen.  edit() and view() use the
default EDITOR and PAGER if possible.  Window-size-changes are handled,
though the screen only gets redrawn after the next keystroke (e.g. ctrl-L)

choose(), ask() and confirm() all accept multi-line questions:
the first line should be the core question (typically it will
end in a question-mark) and will remain on the screen together
with the user's answer.  The subsequent lines appear beneath the
dialogue, and will disappear when the user has given the answer.

TermClui.py does not use curses (a whole-of-screen interface), it uses
a small and portable subset of vt100 sequences.  Also (since 1.50) the
SET_ANY_EVENT_MOUSE and kmous (terminfo) sequences, which are supported
by all xterm, rxvt, konsole, screen, linux, gnome and putty terminals.

Since version 1.60, a speaking interface is provided for the visually
impaired user; it employs  eflite  or  espeak.  Speech is turned on
if the CLUI_SPEAK environment variable is set to any non-empty string.
Since version 1.62, if  speakup  is running, it is silenced while
TermClui runs, and then restored.  Because TermClui's metaphor for
the computer is a human-like conversation-partner, this works very
naturally.  The application needs no modification.

Download TermClui.py from  www.pjb.com.au/midi/free/TermClui.py  or
from http://cpansearch.perl.org/src/PJB/Term-Clui-1.70/py/TermClui.py
and put it in your PYTHONPATH.  TermClui.py depends on Python3.

TermClui.py is a translation into Python3 of the Perl CPAN Modules
Term::Clui and Term::Clui::FileSelect.  This is version 1.70
'''
import re, sys, select, signal, subprocess, os, random
import termios, fcntl, struct, stat, time, dbm

VERSION = '1.70'

def _which(s):
    for d in os.getenv('PATH').split(':'):
        f = d+'/'+str(s)
        if os.path.exists(f):
            return f
    return None
def _warn(string):
    print(string, file=sys.stderr)

def _is_writeable(arg):
    my_type = str(type(arg))
    if my_type == "<class 'str'>":
        if not os.path.exists(arg):
            return False
        my_stat_result = os.stat(arg)
    elif my_type == "<class 'posix.stat_result'>":
        my_stat_result = arg
    else:
        return False
    my_euid = os.geteuid()
    my_groups = os.getgroups()
    my_fuid = my_stat_result.st_uid
    my_fgid = my_stat_result.st_gid
    my_mode = my_stat_result.st_mode
    if (my_euid == my_fuid) and (my_mode & 0o200):
        return True
    if my_mode & 0o20:
        for gid in my_groups:
            if gid == my_fgid:
                return True
    if my_mode & 0o2:
        return True
    return False

_Eflite = None
_Eflite_FH = None # open here at top-level so one sub can silence the previous
_Espeak = None
_Espeak_PID = 0  # defined at top-level so one espeak can kill the previous
_SpeakUpSilentFile = None   # 1.62
if len(os.getenv('CLUI_SPEAK','')) > 0:
    for d in ['/sys/accessibility', '/proc']:
        if _is_writeable(d+"/speakup/silent"):
            _SpeakUpSilentFile = d+"/speakup/silent"
            break
    _Eflite = _which('eflite')
    _Espeak = _which('espeak')
    if _Eflite:
        _pipe = subprocess.Popen(_Eflite, shell=False, stdin=subprocess.PIPE)
        if _pipe:
            _Eflite_FH = _pipe.stdin
        else:
            _warn("can't run "+str(_Eflite)+": $!\n")
    elif not _Espeak:
        _warn("TermClui warning: CLUI_SPEAK set; but can't find eflite or espeak")


# ------------------------ vt100 stuff -------------------------

_A_NORMAL    =  0
_A_BOLD      =  1
_A_UNDERLINE =  2
_A_REVERSE   =  4
_KEY_UP    = 0o403
_KEY_LEFT  = 0o404
_KEY_RIGHT = 0o405
_KEY_DOWN  = 0o402
_KEY_ENTER = "\r"
_KEY_INSERT = 0o525
_KEY_DELETE = 0o524
_KEY_HOME   = 0o523
_KEY_END    = 0o522
_KEY_PPAGE  = 0o521
_KEY_NPAGE  = 0o520
_KEY_BTAB   = 0o541
_getchar = lambda: sys.stdin.read(1)
_ttyin    = 0
_ttyout   = 0
_AbsCursX = 0
_AbsCursY = 0
_TopRow   = 0
_CursorRow = 0
_LastEventWasPress = False
# _SpecialKey unneeded - we test for class int

_irow = 0   # maintained by _puts, _up, _down, _left and _right
_icol = 0
_irow_a = []  # maintined by _layout()
_icol_a = []

def _puts(s):
    global _ttyout, _irow, _icol
    _irow += s.count("\n")
    if re.search('\r$', s):
        _icol = 0
    else:
        _icol += len(s)
    print(s, end='', file=_ttyout)
    _ttyout.flush()

# could terminfo sgr0, bold, rev, cub1, cuu1, cuf1, cud1 ...
def _attrset(attr):
    global _ttyout, _A_BOLD, _A_REVERSE, _A_UNDERLINE
    if not attr:
        print("\033[0m", end='', file=_ttyout)
    else:
        if attr & _A_BOLD:
             print("\033[1m", end='', file=_ttyout)
        if attr & _A_REVERSE:
             print("\033[7m", end='', file=_ttyout)
        if attr & _A_UNDERLINE:
             print("\033[4m", end='', file=_ttyout)
    _ttyout.flush()

def _beep():
    global _ttyout
    print("\07", end='', file=_ttyout)
    _ttyout.flush()
def _clear():
    global _ttyout
    print("\033[H\033[J", end='', file=_ttyout)
    _ttyout.flush()
def _clrtoeol():
    global _ttyout
    print("\033[K", end='', file=_ttyout)
    _ttyout.flush()
def _black():
    global _ttyout
    print("\033[30m", end='', file=_ttyout)
    _ttyout.flush()
def _red():
    global _ttyout
    print("\033[31m", end='', file=_ttyout)
    _ttyout.flush()
def _green():
    global _ttyout
    print("\033[32m", end='', file=_ttyout)
    _ttyout.flush()
def _blue():
    global _ttyout
    print("\033[34m", end='', file=_ttyout)
    _ttyout.flush()
def _violet():
    global _ttyout
    print("\033[35m", end='', file=_ttyout)
    _ttyout.flush()

def _getc_wrapper(timeout):
    # may not work on openbsd...
    # on Py, the select.select seems to flush the remaining [A chars :-(
    global _getchar, _ttyin
    if timeout > 0.00001:
        nfound = select.select([_ttyin], [], [], timeout)
        if not nfound[0]:
            return None
    while (True):
        try:
            return _getchar()
        except (IOError):
            continue

def _dbc(c):
    if ord(c) < 33:
        _debug("ord(c)="+str(ord(c)))
    else:
        _debug("c="+str(c))
    return

def _getch():
    global _KEY_UP, _KEY_DOWN, _KEY_RIGHT, _KEY_LEFT
    global _KEY_PPAGE, _KEY_NPAGE, _KEY_BTAB, _KEY_HOME, _KEY_END
    global _AbsCursX, _AbsCursY
    c = _getc_wrapper(0)
    if c == "\033":
        c = _getc_wrapper(0)
        if c == None:
            return "\033" 
        if (c == 'A'):
            return _KEY_UP 
        if (c == 'B'):
            return _KEY_DOWN 
        if (c == 'C'):
            return _KEY_RIGHT 
        if (c == 'D'):
            return _KEY_LEFT 
        if (c == '2'):
            _getc_wrapper(0)
            return _KEY_INSERT
        if (c == '3'):
            _getc_wrapper(0)
            return _KEY_DELETE
        if (c == '5'):
            _getc_wrapper(0)
            return _KEY_PPAGE 
        if (c == '6'):
            _getc_wrapper(0)
            return _KEY_NPAGE 
        if (c == 'Z'):
            return _KEY_BTAB 
        if (c == 'O'):   # 1.68 Haiku wierdness, inherited from an old Suse
            c = _getc_wrapper(0)
            if (c == 'A'):
                return _KEY_UP    # 1.68
            if (c == 'B'):
                return _KEY_DOWN  # 1.68
            if (c == 'C'):
                return _KEY_RIGHT # 1.68
            if (c == 'D'):
                return _KEY_LEFT  # 1.68
            if (c == 'F'):
                return _KEY_END   # 1.68
            if (c == 'H'):
                return _KEY_HOME  # 1.68
            return c
        if (c == '['):
            c = _getc_wrapper(0)
            if (c == 'A'):
                return _KEY_UP 
            if (c == 'B'):
                return _KEY_DOWN 
            if (c == 'C'):
                return _KEY_RIGHT 
            if (c == 'D'):
                return _KEY_LEFT 
            if (c == 'F'):
                return _KEY_END  # 1.67
            if (c == 'H'):
                return _KEY_HOME  # 1.67
            if (c == 'M'):   # mouse report
                # http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
                event_type = ord(_getc_wrapper(0))-32;
                x = ord(_getc_wrapper(0))-32;
                y = ord(_getc_wrapper(0))-32;
                #event_type = ord(_ttyin.buffer.read(1))-32;
                #x = ord(_ttyin.buffer.read(1))-32;
                #y = ord(_ttyin.buffer.read(1))-32;
                # my $shift   = $event_type & 0x04; # used by wm
                # my $meta  = $event_type & 0x08;   # used by wm
                # my $control = $event_type & 0x10; # used by xterm
                button_drag = (event_type & 0x20) >> 5
                low3bits = event_type & 0x03
                if low3bits == 0x03:
                    button_pressed = 0
                else:  # button 4 means wheel-up, button 5 means wheel-down
                    if event_type & 0x40:
                         button_pressed = low3bits + 4
                    else:
                         button_pressed = low3bits + 1
                t = _handle_mouse(x,y,button_pressed,button_drag)
                if t != '':
                    return t 
                else:
                    return _getch() 
            if re.search('\d', c) != None:
                c1 = _getc_wrapper(0)
                if c1 == '~':
                    if c == '2':
                        return _KEY_INSERT
                    if c == '3':
                        return _KEY_DELETE
                    if c == '5':
                        return _KEY_PPAGE 
                    if c == '6':
                        return _KEY_NPAGE 
                else:  # cursor-position report, response to \033[6n
                    _AbsCursY = int(c)
                    while True:
                        if c1 == ';':
                            break
                        _AbsCursY = 10*_AbsCursY + int(c1)
                        c1 = _getc_wrapper(0)
                    _AbsCursX = 0
                    while True:
                        c1 = _getc_wrapper(0)
                        if c1 == 'R':
                            break
                        _AbsCursX = 10*_AbsCursX + int(c1)
                    return _getch()

            if c == 'Z':
                return _KEY_BTAB 
            return c 
        return c 
    else:
        return c 

def _up(n):
    global _irow, _ttyout
    # if (n < 0) { &down(n); return; }
    print("\033[A"*n, end='', file=_ttyout)
    _ttyout.flush()
    _irow -= n

def _down(n):
    global _irow, _ttyout
    #if (n < 0) { &up(n); return; }
    # \033[B doesn't scroll, but \n needs stty ONLRET
    print("\n"*n, end='', file=_ttyout)
    _ttyout.flush()
    _irow += n

def _right(n):
    global _icol, _ttyout
    # if (n < 0) { &up(n); return; }
    print("\033[C"*n, end='', file=_ttyout)
    _ttyout.flush()
    _icol += n

def _left(n):
    global _icol, _ttyout
    # if (n < 0) { &up(n); return; }
    print("\033[D"*n, end='', file=_ttyout)
    _ttyout.flush()
    _icol -= n

def _goto(newcol,newrow):
    global _icol, _irow
    if (newcol == 0):
        print("\r", end='', file=_ttyout)
        _ttyout.flush()
        _icol = 0
    elif (newcol > _icol):
        _right(newcol-_icol)
    elif (newcol < _icol):
        _left(_icol-newcol)
 
    if (newrow > _irow):
        _down(newrow-_irow)
    elif (newrow < _irow):
        _up(_irow-newrow)

# def move(ix,iy):   Unused...
#     printf TTY "\033[%d;%dH",$iy+1,$ix+1; }



_InitscrAlreadyRun = 0   # its a counter
# tty = True
_ttyout_fnum = 0
_old_tcattr = 0
_IsMouseMode = False
_WasMouseMode = False
_IsSpeakUpSilent  = False  # 1.62
_WasSpeakUpSilent = False  # 1.62


def _enter_mouse_mode ():   # 1.50
    global _ttyin, _IsMouseMode
    if os.getenv('CLUI_MOUSE') == 'OFF':
        return ''
    if _IsMouseMode:
        _warn("_enter_mouse_mode but already IsMouseMode\r\n")
        return 1
    #_ttyin.close()
    #_ttyin  = open("/dev/tty", mode="rb", buffering=0)
    print("\033[?1003h", end='', file=_ttyout)  # sets SET_ANY_EVENT_MOUSE mode
    #_ttyout.flush()
    _IsMouseMode = True
    return 1

def _leave_mouse_mode ():   # 1.50
    global _ttyin, _IsMouseMode
    if os.getenv('CLUI_MOUSE') == 'OFF':
        return ''
    if not _IsMouseMode:
        _warn("_leave_mouse_mode but not IsMouseMode\r\n")
        return 1
    #_ttyin.close()
    #_ttyin  = open("/dev/tty", mode="r")
    print("\033[?1003l", end='', file=_ttyout)  # cancel SET_ANY_EVENT_MOUSE
    _ttyout.flush()
    _IsMouseMode = False
    return 1

def _enter_speakup_silent ():   # 1.62
    global _ttyin, _IsSpeakUpSilent, _SpeakUpSilentFile
    if not _SpeakUpSilentFile:
        return False
    if _IsSpeakUpSilent:
        _warn("_enter_speakup_silent but already IsSpeakUpSilent\r\n")
        return True
    S = open(_SpeakUpSilentFile, 'w')
    S.write("7\n")
    # S.close()
    _IsSpeakUpSilent = True
    return True

def _leave_speakup_silent ():   # 1.62
    global _ttyin, _IsSpeakUpSilent, _SpeakUpSilentFile
    if not _SpeakUpSilentFile:
        return False
    if not _IsSpeakUpSilent:
        _warn("_leave_speakup_silent but not IsSpeakUpSilent\r\n")
        return True
    S = open(_SpeakUpSilentFile, 'w')
    S.write("4\n")
    # S.close()
    _IsSpeakUpSilent = False
    return True

def _initscr(mouse_mode=False, speakup_silent=False):
    global _ttyout_fnum, _old_tcattr, _getchar, _ttyin, _ttyout
    global _InitscrAlreadyRun, _icol,_irow
    global _IsMouseMode, _WasMouseMode, _IsSpeakUpSilent, _WasSpeakUpSilent
    if os.getenv('CLUI_MOUSE') == 'OFF':
        mouse_mode = False
    _icol = 0
    _irow = 0
    if _InitscrAlreadyRun > 0:
        _InitscrAlreadyRun+=1
        if not mouse_mode and _IsMouseMode:
            if not _leave_mouse_mode():
                return False 
        elif mouse_mode and not _IsMouseMode:
            if not _enter_mouse_mode():
                return False 
        _WasMouseMode = _IsMouseMode
        if not speakup_silent and _IsSpeakUpSilent:
            if not _leave_speakup_silent():
                return False 
        elif speakup_silent and not _IsSpeakUpSilent:
            if not _enter_speakup_silent():
                return False 
        _WasSpeakUpSilent = _IsSpeakUpSilent
        _icol = 0
        _irow = 0
        return
    else:
        _InitscrAlreadyRun = 1

    _ttyout = open("/dev/tty", mode="w")

    signal.signal(1, _cleanup)
    signal.signal(3, _cleanup)
    signal.signal(15, _cleanup)
    if mouse_mode:
        _ttyin  = open("/dev/tty", mode="r")
        _IsMouseMode = True
        # encoding_string = ':bytes';
        print("\033[?1003h", end='', file=_ttyout) # sets SET_ANY_EVENT_MOUSE
    else:
        _ttyin  = open("/dev/tty", mode="r")
        _IsMouseMode = False
    if speakup_silent and not _IsSpeakUpSilent:
        _enter_speakup_silent()
    try:
        import tty
        _ttyout_fnum = _ttyout.fileno()
        _old_tcattr = tty.tcgetattr(_ttyout_fnum)
        tty.setcbreak(_ttyout_fnum)
        mode = termios.tcgetattr(_ttyout_fnum)
        OFLAG = 1
        mode[OFLAG] = mode[OFLAG] & ~(termios.ONLCR | termios.ONLRET)
        termios.tcsetattr(_ttyout_fnum, termios.TCSANOW, mode)
        # _getchar = lambda: _ttyin.read(1)  # but ttyin will be re-opened :-(
        _getchar = lambda: _ttyin_read()
    except (ImportError, AttributeError):
        _ttyout_fnum = 0
        # _getchar = lambda: _ttyin.readline()[:-1][:1]
        _getchar = lambda: _ttyin.readline()

def _ttyin_read():
    global _ttyin
    return _ttyin.read(1)
def _ttyin_readline():
    global _ttyin
    return _ttyin.readline()[:-1][:1]
def _cleanup(num,frame):
    import tty
    global _ttyout, _ttyout_fnum, _old_tcattr
    print("\033[0m", end='', file=_ttyout)
    _leave_mouse_mode()
    _ttyout_fnum = _ttyout.fileno()
    tty.setcbreak(_ttyout_fnum)
    termios.tcsetattr(_ttyout_fnum, termios.TCSANOW, _old_tcattr)
    # raise KeyboardInterrupt
    sys.exit()

def _endwin():
    global _ttyout, _old_tcattr, _InitscrAlreadyRun
    global _IsMouseMode, _WasMouseMode, _IsSpeakUpSilent, _WasSpeakUpSilent
    print("\033[0m", end='', file=_ttyout)
    if _InitscrAlreadyRun > 1:
        if _IsMouseMode and not _WasMouseMode:
            _leave_mouse_mode()
        elif not _IsMouseMode and _WasMouseMode:
            _enter_mouse_mode()
        if _IsSpeakUpSilent and not _WasSpeakUpSilent:
            _leave_speakup_silent()
        elif not _IsSpeakUpSilent and _WasSpeakUpSilent:
            _enter_speakup_silent()
        _InitscrAlreadyRun -= 1
        return
    print("\033[?1003l", end='', file=_ttyout)
    _ttyout.flush()
    __IsMouseMode = False
    if _IsSpeakUpSilent:
        _leave_speakup_silent()
    import tty
    _ttyout_fnum = _ttyout.fileno()
    tty.setcbreak(_ttyout_fnum)
    termios.tcsetattr(_ttyout_fnum, termios.TCSANOW, _old_tcattr)
    _InitscrAlreadyRun = 0

# ----------------------- size handling ----------------------

_maxcols      = 79
_maxrows      = 24
_size_changed = True
_otherlines   = ''
_notherlines  = 0

def _check_size():
    global _size_changed, _maxcols, _maxrows, _ttyout_fnum
    global _otherlines, _notherlines
    if not _size_changed:
        return
    # http://bytes.com/groups/python/607757-getting-terminal-display-size
    s = struct.pack("HHHH", 0, 0, 0, 0)
    x = fcntl.ioctl(_ttyout_fnum, termios.TIOCGWINSZ, s)
    [_maxrows, _maxcols, xpixels, ypixels] = struct.unpack("HHHH", x)
    _maxcols -= 1

    if _notherlines:
        _otherlines_a = _fmt(_otherlines)
        _notherlines = len(_otherlines_a)
    _size_changed = False;

# $SIG{'WINCH'} = sub { $size_changed = 1; };
def _set_size_changed(signum,stackframe):
    global _size_changed
    _size_changed=True

signal.signal(28, _set_size_changed)

# ------------------------ ask stuff -------------------------

# Options such as integer, real, positive, >x, >=x, <x <=x,
# non-null, max-length, min-length, silent  ...
# default could be just one more option, and backward compatibilty
# could be preserved by checking whether the 2nd arg is a hashref ...

_silent = False
def ask_password(question):
    r'''Like ask, but with no echo. Use it for passwords.'''
    global _silent
    _silent = True
    return ask(question)

def ask_filename(question):
    r'''Uses the readline module to provide filename-completion with the Tab
key, but also displays multi-line questions in the same way as ask()
and choose() do.  This function was introduced in version 1.65.'''
    import readline
    _initscr(speakup_silent=True)
    nol = _display_question(question)
    _endwin()
    # to what extent can this readline do anything but complete py builtins?
    #$term = new Term::ReadLine 'ProgramName';
    ## print STDERR "$question ";
    #my $filename = $term->readline('');
    #print STDERR "\e[J";
    #return $filename;
    return ask(question)

def ask(question, default=''):
  try:
    r'''Prints the question and, on the same line, expects the user
to input a string. Left- and Right-arrow and Backspace work
as usual, ctrl-A goes to the beginning and ctrl-E to the end.
If default is specified, it appears on the line initially.
ask() returns the string when the user presses Enter.
'''
    global _silent, _KEY_LEFT, _KEY_RIGHT
    if not question:
        return ''
    _initscr(speakup_silent=True)
    nol = _display_question(question)

    i = 0    # cursor position
    n = 0    # string length
    s_a = []   # list of letters in string
    if default:
        _speak(question+', default is '+default)
        default = re.sub('\t', '    ', default)
        s_a = [y for y in default]
        n = len(default)
        #i = n
        #for j in range(len(s_a)):
        #    _puts(s_a[j])
        _puts(default)
        _left(n)
    else:
        _speak(question)

    while True:
        c = _getch()
        if c == "\r" or c == "\n":
            _erase_lines(1)
            break
        if _size_changed:
            _erase_lines(0)
            nol = _display_question(question)
        if c == _KEY_LEFT:
            if i > 0:
                i-=1
                _left(1)
        elif c == _KEY_RIGHT and i < n:
            _puts('x') if _silent else _puts(s_a[j])
            i+=1
        elif c == _KEY_DELETE and i < n:
            n -= 1
            s_a.pop(i)   # splice(@s, $i, 1)
            j = i
            while j < n:
                _puts('x') if _silent else _puts(s_a[j])
                j += 1
            _clrtoeol()
            _left(n-i)
        elif (c == "\b") or (c == "\177"):
            if i > 0:
                n -= 1
                i -= 1
                if not _silent:   # 1.63
                    _speak(s_a[i])
                s_a.pop(i)   # splice(@s, $i, 1)
                _left(1)
                j = i
                while j < n:
                    _puts('x') if _silent else _puts(s_a[j])
                    j += 1
                _clrtoeol()
                _left(n-i)
        elif c == "\030" or c == "\004":  # clear ...
            _left(i)
            i = 0
            n = 0
            _clrtoeol()
            s_a = []
        elif c == "\001" or c == _KEY_HOME:  # 1.67
            _left(i)
            i = 0
        elif c == "\005" or c == _KEY_END:  # 1.67
            _right(n-i)
            i = n
        elif c == "\014":
            _speak("".join(s_a))
        elif str(type(c)) == "<class 'int'>":
            _beep()
        elif ord(c) >= 32:
            _beep()
            # splice(@s, $i, 0, $c);
            s_a.insert(i, c)
            n+=1
            i+=1
            if _silent:
                _puts('x')
            else:
                _puts(c)
                _speak(c)
            j = i
            while j < n:
                _puts(s_a[j])
                j += 1
            _clrtoeol()
            _left(n-i)
        else:
            _beep()
    _speak("".join(s_a), True)
    _endwin()
    _silent = False
    return "".join(s_a)
  except Exception as err:
    # print("handling ask exception")
    _endwin()
    subprocess.call(['stty','sane'])
    _warn(err)
    sys.exit()

# ----------------------- choose stuff -------------------------
def _debug(string):
    tmp = open("/tmp/clui_debug", mode="a")
    print(string, file=tmp)
    tmp.close()

# my (%irow, %icol, $nrows, $clue_has_been_given, $choice, $this_cell);
random.seed(None)
_HOME = os.getenv('HOME') or os.getenv('LOGDIR') or os.path.expanduser('~')
_marked    = []
_clue_has_been_given = False
_this_cell = 0
_choice    = ''
_list      = []

def choose(question, a_list, multichoice=False):
  try:
    r'''
Prints the question, then a compact formatting of the list of strings
with one (the cursor) highlit. Initially, the cursor is on that string
which the user chose previously in response to this same question.
The user then uses arrow keys (or hjkl) and Return, or q to quit.
The Return key causes choose() to return the string under the cursor;
q or ctrl-X for Quit causes choose() to return None.

If there are too many choices to fit on the screen, the user is
prompted for a (case-sensitive) clue, which is used to narrow down
the choices until they do fit.

If the environment variable CLUI_MOUSE is set to OFF
then choose() will not interpret mouse-clicks as making a choice.
The advantage of this is that the mouse can then be used
to highlight and paste text from this window as usual.``

If multichoice is set, the SpaceBar works to select (or deselect)
the various choices (the choice under the cursor when Return is
pressed is also selected), and choose() returns a list of strings.
'''
    # wantarray doesn't exist in Python because no $ or @
    global _maxcols, _marked, _list, _size_changed, _nrows, _icol_a, _irow_a
    global _irow, _otherlines, _notherlines, _otherlines_a
    global _ttyout, _this_cell, _clue_has_been_given, _choice, _CursorRow
    _list = a_list
    for i in range(len(_list)):
        _list[i] = re.sub('[\r\n]+$', '', _list[i])   # chop final \n if any
    a_list = _list
    icell = 0
    _marked = [False for item in _list]
    question = re.sub('[\r\n]+$', '', question)
    question = re.sub('^[\r\n]+', '', question)

    _otherlines = ''
    _otherlines_a = []
    lines = re.split('\r?\n', question, 1)
    firstline = lines[0]
    firstlinelength = len(firstline)
    _choice = get_default(firstline)
    chosen = []
    _initscr(mouse_mode=True, speakup_silent=True)
    _size_and_layout(0)
    if (len(lines) > 1):
       _otherlines = lines[1]
       _otherlines_a = _fmt(lines[1])
    #if len(otherlines_a):
    #    puts("\r\n" + "\r\n".join(otherlines_a) + "\r")
    #    goto(1+len(firstline), 0)
    _notherlines = len(_otherlines_a)
    if multichoice:
        if (firstlinelength < _maxcols-30):
            _puts(firstline+" (multiple choice with spacebar)")
        elif (firstlinelength < _maxcols-16):
            _puts(firstline + "(multiple choice)")
        elif (firstlinelength < _maxcols-9):
            _puts(firstline + "(multiple)")
        else:
            _puts(firstline)
        if _nrows >= _maxrows:
            _speak(firstline+', ', wait=True)
        else:
            _speak(firstline+', multiple choice, '+_list[_this_cell])
    else:
        _puts(firstline)
        if _nrows >= _maxrows:
            _speak(firstline+', ', wait=True)
        else:
            _speak(firstline+', choose '+_list[_this_cell])
    _clrtoeol()

    if _nrows >= _maxrows:
        _list = _narrow_the_search(_list)
        if not _list:
            _up(1)
            _clrtoeol()
            _endwin()
            _clue_has_been_given = False
            if multichoice:
                return []
            else:
                return None
        _speak('choose '+_list[_this_cell])
    _wr_screen()
    print("\033[6n", end='', file=_ttyout)  # u7 will set _AbsCursX, _AbsCur
    _ttyout.flush()
    _CursorRow = _irow_a[_this_cell]  # global, needed by handle_mouse

    while True:
        c = _getch()
        if _size_changed:
            _size_and_layout(_nrows)
            if _nrows >= _maxrows:
                _list = _narrow_the_search(_list)
                if not _list:
                    _up(1)
                    _clrtoeol()
                    _endwin()
                    _clue_has_been_given = False
                    if multichoice:
                        return []
                    else:
                        return None
            _wr_screen()
            _speak('choose '+_list[_this_cell])
        if (c == "q" or c == "\004" or c == "\030"):
            _erase_lines(1)
            if _clue_has_been_given:
                re_clue = confirm("Do you want to change your clue ?")
                _up(1)
                _clrtoeol()   # erase the confirm
                if re_clue:
                    _irow = 1
                    _list = _narrow_the_search(a_list)
                    _wr_screen()
                    _speak('choose '+_list[_this_cell])
                    continue
                else:
                    _up(1)
                    _clrtoeol()
                    _endwin()
                    _clue_has_been_given = False
                    if multichoice:
                        return []
                    else:
                        return None
            _goto(0,0)
            _clrtoeol()
            _endwin()
            _clue_has_been_given = False
            if multichoice:
                return []
            else:
                return None
        elif (c == "\t") and (_this_cell < (len(_list)-1)):
            _this_cell+=1
            _wr_cell(_this_cell-1)
            _wr_cell(_this_cell)
            _speak(_list[_this_cell])
        elif (((c == "l") or (c == _KEY_RIGHT)) and (_this_cell < (len(_list)-1)) and (_irow_a[_this_cell] == _irow_a[_this_cell+1])):
            _this_cell+=1
            _wr_cell(_this_cell-1)
            _wr_cell(_this_cell)
            _speak(_list[_this_cell])
        elif (((c == "\010") or (c == _KEY_BTAB)) and (_this_cell > 0)):
            _this_cell-=1
            _wr_cell(_this_cell+1)
            _wr_cell(_this_cell)
            _speak(_list[_this_cell])
        elif (((c == "h") or (c == _KEY_LEFT)) and (_this_cell > 0) and (_irow_a[_this_cell] == _irow_a[_this_cell-1])):
            _this_cell-=1
            _wr_cell(_this_cell+1)
            _wr_cell(_this_cell)
            _speak(_list[_this_cell])
        elif (((c == "j") or (c == _KEY_DOWN)) and (_irow < _nrows)):
            mid_col = _icol_a[_this_cell] + int(0.5*len(_list[_this_cell]))
            left_of_target = 1000
            inew=_this_cell+1
            while inew < len(_list):
                if _icol_a[inew] < mid_col:
                    break    # skip rest of row
                inew+=1
            while inew < len(_list):
                new_mid_col = _icol_a[inew] + int(0.5*len(_list[inew]))
                if new_mid_col >= mid_col:        # we've reached it
                    break
                if (inew == (len(_list)-1)) or (_icol_a[inew+1]<=_icol_a[inew]):
                    break    # we're at EOL
                left_of_target = mid_col - new_mid_col
                inew+=1
            if ((new_mid_col - mid_col) > left_of_target):
                inew-=1
            iold = _this_cell
            _this_cell = inew
            _wr_cell(iold)
            _wr_cell(_this_cell)
            _speak(_list[_this_cell])
        elif (((c == "k") or (c == _KEY_UP)) and (_irow > 1)):
            mid_col = _icol_a[_this_cell] + int(0.5*len(_list[_this_cell]))
            right_of_target = 1000
            inew = _this_cell-1
            while inew > 0:
                if _irow_a[inew] < _irow_a[_this_cell]:    # skip rest of row
                    break
                inew-=1
            while (inew > 0):
                if not _icol_a[inew]:
                    break
                new_mid_col = _icol_a[inew] + int(0.5*len(_list[inew]))
                if new_mid_col <= mid_col:         # we're past it or aligned
                    break
                right_of_target = new_mid_col - mid_col
                inew-=1
            if ((mid_col - new_mid_col) > right_of_target):
                inew+=1
            iold = _this_cell
            _this_cell = inew
            _wr_cell(iold)
            _wr_cell(_this_cell)
            _speak(_list[_this_cell])
        elif c == "\014":
            if _size_changed:
                _size_and_layout(_nrows)
                if _nrows >= _maxrows:
                    _list = _narrow_the_search(_list);
                    if not _list:
                        _up(1)
                        _clrtoeol()
                        _endwin()
                        _clue_has_been_given = False
                        if multichoice:
                            return []
                        else:
                            return None
            _wr_screen()
        elif (c == "\r") or (c == "\n"):
            _erase_lines(1)
            _goto(firstlinelength+1, 0)
            if multichoice:
                i = 0
                while i < len(_list):
                    if _marked[i] or (i==_this_cell):
                        chosen.append(_list[i])
                    i+=1
                _clrtoeol()
                remaining = _maxcols-firstlinelength
                last = chosen.pop()
                dotsprinted = False
                for item in chosen:
                    if ((remaining - len(item)) < 4):
                        dotsprinted = True
                        _puts("...")
                        remaining -= 3
                        break
                    else:
                        _puts(item+", ")
                        remaining -= (2 + len(item))
                if not dotsprinted:
                    if (remaining - len(last)) > 0:
                        _puts(last)
                    elif remaining > 2:
                        _puts('...')
                _puts("\n\r");
                chosen.append(last)
            else:
                _puts(_list[_this_cell]+"\n\r")
            _endwin()
            set_default(firstline, _list[_this_cell]); # join ($,,@chosen) ?
            _clue_has_been_given = False
            if multichoice:
                _speak(' and '.join(chosen), wait=True)
                return chosen
            else:
                _speak(_list[_this_cell], wait=True)
                return _list[_this_cell]
        elif c == " ":
            if multichoice:
                _marked[_this_cell] = not _marked[_this_cell]
                # if (_this_cell < (len(_list)-1)):  # 1.50
                #    _this_cell+=1
                #    _wr_cell(_this_cell-1)
                _wr_cell(_this_cell)
                _speak('marked')
            #elif (_this_cell < (len(_list)-1)):
            #    _this_cell+=1
            #    _wr_cell(_this_cell-1)
            #    _wr_cell(_this_cell)

    _endwin()
    print("choose: shouldn't reach here ...\n", file=sys.stderr)
  except KeyboardInterrupt:
    # print("handling exception")
    _leave_mouse_mode()
    _endwin()
    subprocess.call(['stty','sane'])
    return ''

def _layout(my_list):
    global _irow_a, _icol_a, _this_cell, _maxcols, _maxrows, _choice
    _irow_a = []
    _icol_a = []
    _this_cell = 0
    my_irow = 1
    my_icol = 0
    l = []
    i = 0
    while (i < len(my_list)):
        l.append(len(my_list[i]) + 2)
        if (l[i] > _maxcols-1):
            l[i] = _maxcols-1
        if ((my_icol + l[i]) >= _maxcols):
            my_irow += 1
            my_icol = 0

        if my_irow > _maxrows:
            return my_irow
        _irow_a.append(my_irow)
        _icol_a.append(my_icol)
        my_icol += l[i]
        if my_list[i] == _choice:
            _this_cell = i
        i += 1
    return my_irow

def _wr_screen():
    global _otherlines, _notherlines, _nrows, _maxrows, _list, _this_cell
    i = 0
    while (i < len(_list)):
        if not  i == _this_cell:
            _wr_cell(i)
        i += 1
    if (_notherlines and (_nrows+_notherlines) < _maxrows):
        _puts("\r\n" + "\r\n".join(_otherlines_a) + "\r")
    _wr_cell(_this_cell)

def _wr_cell(i):
    global _icol_a, _irow_a, _icol, _marked, _this_cell, _list
    global _A_BOLD, _A_REVERSE, _A_NORMAL, _A_UNDERLINE
    _goto(_icol_a[i], _irow_a[i]);
    if _marked[i]:
        _attrset(_A_BOLD | _A_UNDERLINE)
    if i == _this_cell:
        _attrset(_A_REVERSE)
    no_tabs = _list[i]
    no_tabs = re.sub("\t", " ", no_tabs)
    no_tabs = " " + no_tabs + " "
    _puts(no_tabs[:_maxcols])  # 1.42, 1.54
    if _marked[i] or (i == _this_cell):
        _attrset(_A_NORMAL)

def _size_and_layout(erase_rows):
    global _maxrows, _nrows, _list
    _check_size()
    if (erase_rows):
        if (erase_rows > _maxrows):
            erase_rows = _maxrows
        _erase_lines(1)
    _nrows = _layout(_list)

def _narrow_the_search(a_list):
    global _maxrows, _nrows, _KEY_LEFT, _KEY_RIGHT, _clue_has_been_given
    global _IsMouseMode
    nchoices = len(a_list)
    n = 0
    i = 0
    s_a = []
    s = ''
    my_list = a_list
    _clue_has_been_given = True
    if _IsMouseMode:  # 1.55
        _leave_mouse_mode()
    _ask_for_clue(nchoices, i, s);
    while True:
        c = _getch()
        if _size_changed:
            _size_and_layout(0)
            if _nrows < _maxrows:
                _erase_lines(1)
                _enter_mouse_mode()
                return my_list
        if c == _KEY_LEFT and i > 0:
             i-=1
             _left(1)
             continue
        elif c == _KEY_RIGHT:
            if i < n:
                _puts(s_a[i])
                i+=1
                continue
        elif c == "\b" or c == "\177":
            if i > 0:
                n-=1
                i-=1
                _speak(s_a[i], wait=True)   # 1.63
                s_a.pop(i)
                _left(1)
                j = i
                while j < n:
                    _puts(s_a[j])
                    j += 1
                _clrtoeol()
                _left(n-i)
        elif c == "\003" or c == "\030" or c == "\004":
            if not s_a:
                _clue_has_been_given = False
                _erase_lines(1)
                _enter_mouse_mode()
                return []
            _left(i)
            i = 0
            n = 0
            s_a = []
            _clrtoeol()
        elif c == "\002":
            _left(i)
            i = 0
            continue
        elif c == "\005":
            _right(n-i)
            i = n
            continue
        elif c == "\014":
            x = i   # do nothing
        elif str(type(c)) == "<class 'int'>":
            _beep()
        else:
            if ord(c) >= 32:  # nchoices and ?
                s_a.insert(i, c)
                n+=1
                i+=1
                _puts(c)
                j = i
                while j < n:
                    _puts(s_a[j])
                    j += 1
                _clrtoeol()
                _left(n-i)
                _speak(c, wait=True)   # 1.63
            else:
                _beep()

        # grep, and if $nchoices=1 return
        s = "".join(s_a);
        # list = grep($[ <= index($_,$s), @biglist);
        if s:
            # a lambda function can't refer to s :-(
            # my_list = list(filter(lambda x: s.find(x)>=0, biglist))
            my_list = []
            for tmp_str in a_list:
                tmp_str.find(s)>=0 and my_list.append(tmp_str)
        else:
            my_list = a_list
        nchoices = len(my_list)
        _nrows = _layout(my_list)
        if (nchoices==1 or (nchoices and (_nrows<_maxrows))):
            _puts("\r")
            _clrtoeol()
            _up(1)
            _clrtoeol()
            _enter_mouse_mode()
            return my_list
        _ask_for_clue(nchoices, i, s)

    print("_narrow_the_search: shouldn't reach here ...", file=sys.stderr)

def _ask_for_clue(nchoices, i, s):
    if nchoices:
        if s:
            headstr = "the choices won't fit; there are still";
            _goto(0,1)
            _puts(headstr+" "+str(nchoices)+" of them")
            _clrtoeol()
            _goto(0,2)
            _puts("lengthen the clue : ")
            _right(i)
            _speak("still "+str(nchoices)+" choices, lengthen the clue")
        else:
            headstr = "the choices won't fit; there are"
            _goto(0,1)
            _puts(headstr+" "+str(nchoices)+" of them")
            _clrtoeol()
            _goto(0,2)
            _puts("   give me a clue :             (or ctrl-X to quit)")
            _left(31)   # 1.62
            _speak(str(nchoices)+" choices, give me a clue, or control-X to quit")
    else:
        _goto(0,1)
        _puts("No choices fit this clue !")
        _clrtoeol();
        _goto(0,2)
        _puts(" shorten the clue : ")
        _right(i)
        _speak("no choices fit, shorten the clue")

def get_default(question):
    r'''Returns (what the dbm database remembers as) the choice the
user made the last time they were asked this question.
'''
    if os.getenv('CLUI_DIR') == 'OFF':
        return ''
    if not question:
        return ''
    n_tries = 5
    while n_tries > 0:
        try:
            CHOICES = dbm.open (_dbm_file(), 'c', 0o600)
            break
        except NameError:
            return ''
        except IOError:
            if n_tries < 2:
                return ''
            select.select([], [], [], random.uniform(0.0, 0.45))
        else:
            return ''
        n_tries -= 1
    my_choice = CHOICES.get(question)
    CHOICES.close()
    if my_choice:
        return my_choice.decode()
    else:
        return ''

def set_default(question, answer):
    r'''Overwrites the choice the user made the last time they
were confronted with this question. This can be useful in
an application where one task typically follows another,
to set the next default choice.
'''
    if os.getenv('CLUI_DIR') == 'OFF':
        return None
    if not question:
        return None
    n_tries = 5
    while n_tries > 0:
        try:
            CHOICES = dbm.open (_dbm_file(), 'c', 0o600)
            break
        except NameError:
            return None
        except IOError:
            if n_tries < 2:
                return ''
            select.select([], [], [], random.uniform(0.0, 0.45))
        else:
            return None
        n_tries -= 1
    CHOICES[question] = answer
    CHOICES.close()
    return answer

def _dbm_file():
    global _HOME
    if (os.getenv('CLUI_DIR') == 'OFF'):
        return None
    if (os.getenv('CLUI_DIR')):
        db_dir = os.getenv('CLUI_DIR')
        db_dir = re.sub('^~', _HOME, db_dir)
    else:
        db_dir = _HOME+"/.clui_dir"
    os.path.exists(db_dir) or os.mkdir(db_dir, 0o750)
    return db_dir+"/choices"

def _handle_mouse(x, y, button_pressed, button_drag):  # 1.50 
    global _TopRow, _AbsCursY, _CursorRow, _LastEventWasPress
    global _this_cell, _irow_a, _icol_a, _list
    _TopRow = _AbsCursY - _CursorRow
    if _LastEventWasPress:
        _LastEventWasPress = False
        return ''
    if y < _TopRow:
        return ''
    mouse_row = y - _TopRow
    mouse_col = x - 1
    found = False
    for i in range(len(_irow_a)):
        if _irow_a[i] == mouse_row:
            if _icol_a[i] < mouse_col and (_icol_a[i]+len(_list[i])) >= mouse_col:
                found = True
                break
            if _irow_a[i] > mouse_row:
                break
        i += 1
    if not found:
        return ''
    # if xterm doesn't receive a button-up event it thinks it's dragging
    return_char = ''
    if button_pressed == 1 and not button_drag:
        _LastEventWasPress = True
        return_char = _KEY_ENTER
    elif button_pressed == 3 and not button_drag:
        _LastEventWasPress = True
        return_char = ' '
    if i != _this_cell:
        t = _this_cell
        _this_cell = i
        _wr_cell(t)
        _wr_cell(_this_cell)
    return return_char


# ----------------------- confirm stuff -------------------------

def confirm(question):
    '''Print the question, and the user replies Yes or No using
"y", "Y", "n" or "N".  confirm() returns True or False.
'''
    global _ttyin, _ttyout
    if not question:
        return(False)
    # return(0) unless -t STDERR
    if not os.isatty(sys.stdout.fileno()):
        return(None)
    _initscr(speakup_silent=True)
    nol = _display_question(question)
    _puts (" (y/n) ")
    _speak(question + ', y or n')
    while (True):
        response=_getch()
        if (re.match('[yYnN]', response)):
            break
        _beep()

    _left(6)
    _clrtoeol()
    if (re.match('[yY]', response)):
        _puts("Yes")
        _speak('yess', wait=True)
    else:
        _puts("No")
        _speak('know', wait=True)
    _erase_lines(1)
    _endwin()
    if (re.match('[yY]', response)):
        return True
    else:
        return False

# ----------------------- edit stuff -------------------------

def edit(title='', text=''):
    r'''If there's no text and the "title" is a filename that exists
and is writeable, then the user's default EDITOR is invoked on
that file.  If the file is only readable, the user's default
PAGER is used.  If there is text, the editor is invoked on that
text, and the title is displayed within the temporary file-name.
In either case, the resulting text is returned.
'''
    # my ($dirname, $basename, $rcsdir, $rcsfile, $rcs_ok);

    editor = os.getenv('EDITOR') or "vi"; # should also get_default()
    if not title:    # start editor session with no preloaded file
        subprocess.call([editor])
    elif text:
        # must create tmp file with title embedded in name
        tmpdir = '/tmp/';
        safename = re.sub('[\W_]+', '_', title)
        fname = tmpdir + safename + str(os.getpid())
        try:
            fh = open(fname, mode="w")
        except EnvironmentError as err:
            sorry("can't open "+fname+": "+str(err))
            return ''
        print(text, file=fh)
        fh.close()
        subprocess.call([editor, fname])
        try:
            fh = open(fname, mode="r")
        except EnvironmentError as err:
            sorry("can't read "+fname+": "+str(err))
            return ''
        text = fh.read()
        fh.close()
        try:
            os.unlink(fname)
        except EnvironmentError as err:
            sorry("couldn't unlink "+fname+": "+str(err))
        return text
    else:    # its a file, we will try RCS ...
        file = title

        # weed out no-go situations
        file_stat = os.stat(file)
        # if os.path.isdir(file):  # less yukky, but does an extra stat
        if stat.S_ISDIR(file_stat.st_mode):  # YUK
            sorry(file+" is already a directory")
            return ''
        #if (-B _ and -s _):
        #    sorry(file+" is not a text file")
        #    return ''
        #if (-T _ and !-w _):
        if not _is_writeable(file_stat):
            view(file)
            return True

        # it's a writeable text file, so work out the locations
        if file.find(os.path.sep) >= 0:
            rcsdir   = os.path.dirname(file)+'/RCS'
            basename = os.path.basename(file)
            rcsfile  = rcsdir+os.path.sep+basename+',v'
        else:
            basename = file
            rcsdir   = "RCS"
            rcsfile  = rcsdir+os.path.sep+os.path.basename(file)+',v'

        rcslog = rcsdir+'/log'

        # we no longer create the RCS directory if it doesn't exist,
        # so you have to `mkdir RCS' to enable rcs in a directory ...
        rcs_ok = True
        if not os.path.isdir(rcsdir):
            rcs_ok = False
        elif not _is_writeable(rcsdir):
            rcs_ok = False
            print("can't write in "+rcsdir, file=sys.stderr)

        # if the file doesn't exist, but the RCS does, then check it out
        if rcs_ok and os.path.isfile(rcsfile) and not os.path.isfile(file):
            subprocess.call(["co", "-l", file, rcsfile])

        starttime = time.time()
        subprocess.call([editor, file])
        elapsedtime = time.time() - starttime;
        # could be output or logged, for worktime accounting

        # if (rcs_ok and -T file):     # check it in
        if rcs_ok:
            if not os.path.isfile(rcsfile):
                msg = ask (file+' is new. Please describe it:');
                if msg:
                    quotedmsg = re.sub("'","'\"'\"'", msg)
                    # system "ci -q -l -t-'$quotedmsg' -i $file $rcsfile";
                    subprocess.call(["ci", "-q", "-l", "-t-'"+quotedmsg+"'", file, rcsfile])
                    _logit(rcslog, basename, msg)
            else:
                msg = ask('What changes have you made to '+file+' ?')
                quotedmsg = re.sub(r"'", "'\"'\"'", msg)
                if msg:
                    subprocess.call(["ci", "-q", "-l", "-m'"+quotedmsg+"'", file, rcsfile])
                    _logit(rcslog, basename, msg)

def _logit(rcslog, file, msg):
    logfile = open(rcslog, mode="a")
    print(_timestamp()+' '+file+' '+os.getlogin()+' '+msg, file=logfile)
    logfile.close()

def _timestamp():
    # returns current date and time in "199403011 113520" format
    x = time.localtime(time.time())
    return '{0:0=4}{1:0=2}{2:0=2} {3:0=2}{4:0=2}{5:0=2}'.format(x.tm_year, x.tm_mon, x.tm_mday, x.tm_hour, x.tm_min, x.tm_sec)

# -------------------------- filetests --------------------------

def _re_grep(regexp, a_list):
    '''greps a regexp in a list of strings'''
    l = []
    for tmpstr in a_list:
        if re.match(regexp, tmpstr):
            l.append(tmpstr)
    return l


def _is_readable(arg):
    my_type = str(type(arg))
    if my_type == "<class 'str'>":
        if not os.path.exists(arg):
            return False
        my_stat_result = os.stat(arg)
    elif my_type == "<class 'posix.stat_result'>":
        my_stat_result = arg
    else:
        return False
    my_euid = os.geteuid()
    my_groups = os.getgroups()
    my_fuid = my_stat_result.st_uid
    my_fgid = my_stat_result.st_gid
    my_mode = my_stat_result.st_mode
    if (my_euid == my_fuid) and (my_mode & 0o400):
        return True
    if my_mode & 0o40:
        for gid in my_groups:
            if gid == my_fgid:
                return True
    if my_mode & 0o4:
        return True
    return False

def _is_executable(arg):
    my_type = str(type(arg))
    if my_type == "<class 'str'>":
        if not os.path.exists(arg):
            return False
        my_stat_result = os.stat(arg)
    elif my_type == "<class 'posix.stat_result'>":
        my_stat_result = arg
    else:
        return False
    my_euid = os.geteuid()
    my_groups = os.getgroups()
    my_fuid = my_stat_result.st_uid
    my_fgid = my_stat_result.st_gid
    my_mode = my_stat_result.st_mode
    if (my_euid == my_fuid) and (my_mode & 0o400) and (my_mode & 0o100):
        return True
    if (my_mode & 0o40) and (my_mode & 0o10):
        for gid in my_groups:
            if gid == my_fgid:
                return True
    if (my_mode & 0o4) and (my_mode & 0o1):
        return True
    return False


def _is_textfile(arg):   # arg must be a str, the filename
    my_type = str(type(arg))
    if my_type == "<class 'str'>":
        if not os.path.exists(arg):
            return False
    else:
        return False
    try:
        f = open(arg, mode='br')
    except EnvironmentError as err:
        print("can't open "+arg+": "+err, file=sys.stderr)
    ascii = 0
    nonascii = 0
    for byte in f.read(2048):
        # if ord(c) > 127:
        if (byte > 127) or (byte<9) or ((byte>14) and (byte<32)):
            nonascii += 1
        else:
            ascii += 1
    f.close()
    if ascii == 0:
        return None
    elif (nonascii/ascii) > 0.10:
        return False
    else:
        return True

def _is_owned(arg):
    my_type = str(type(arg))
    if my_type == "<class 'str'>":
        if not os.path.exists(arg):
            return False
        my_stat_result = os.stat(arg)
    elif my_type == "<class 'posix.stat_result'>":
        my_stat_result = arg
    else:
        return False
    my_euid = os.geteuid()
    my_fuid = my_stat_result.st_uid
    if my_euid == my_fuid:
        return True
    return False


# ----------------------- sorry stuff -------------------------

def sorry(msg):   # warns user of an error condition
    r'''Prints the message to stderr preceded by the word "Sorry, "
'''
    print('Sorry, '+str(msg), file=sys.stderr)
    _speak('Sorry, '+str(msg), wait=True)

def inform(msg):
    r'''Prints the message to /dev/tty or to stderr.
'''
    msg = re.sub('[\r\n]+$', '', msg)
    try:
        ttyout = open('/dev/tty', mode='w')
        print(msg, file=ttyout)
        ttyout.close()
    except:
       print(str(msg), file=sys.stderr)
    _speak(str(msg), wait=True)

# ----------------------- view stuff -------------------------

def view(title='', text=''):    # or ($filename) =
    r'''If there's no text and the "title" is a filename that exists
and is readable, then a pager is invoked on that file.  Else,
a pager is invoked on the text, and the title is displayed
somewhere as a title.  If the text covers 60% or more of the
screen, the user's default PAGER is used; if the text is two lines
or less, it is just printed; in between, a built-in tiny pager is
used which offers the user the choices "q" to clear the text and
continue, or Enter to leave the text on the screen and continue.
'''
    # 1.65 if it's a .doc file, then wvText, antiword or catdoc should be used
    global _OpenFile
    pager = os.getenv('PAGER')
    if not pager:
        for f in ["/usr/bin/less", "/usr/bin/more"]:
            if os.path.exists(f):
                default_pager = f
                break
    if (not text) and os.path.exists(title) and _Open(title, mode='r'):
        nlines = 0
        for line in _OpenFile:
            nlines += 1
            if (nlines > _maxrows):
                break
        _OpenFile.close()
        if (nlines > int(0.6*_maxrows)):
            subprocess.call(pager, title)
        else:
            fh = open(title, mode='r')
            text = fh.read()
            fh.close()
            _tiview(title, text);
    else:
        lines = re.split('\r?\n', text, _maxrows-1)
        if len(lines) < 21:
            _tiview (title, text)
        else:
            tmpdir = '/tmp/'
            safename = re.sub('[\W_]+', '_', title)
            fname = tmpdir + safename + os.getpid()
            if not _Open(fname, mode="w"):
                return ''
            _OpenFile.print(text)
            _OpenFile.close()
            subprocess.call(pager, fname)
            _Unlink(tmp)

def _tiview(title='', text=''):
    global _icol, _irow
    if not text:
        return False
    title = re.sub('\t', ' ', title)
    titlelength = len(title)

    _check_size()
    rows = _fmt(text, nofill=True);
    _initscr();
    if 3 > len(rows):
        _puts(title+"\r\n"+("\r\n".join(rows))+"\r\n")
        _speak(title+', '+(' '.join(rows)), wait=True)
        _endwin()
        return True
    if titlelength > (_maxcols-35):
        _puts (title+"\r\n")
    else:
        _puts (title+"   (<enter> to continue, q to clear)\r\n")

    _puts("\r" + "\r\n".join(rows) + "\r")  # the perl version does clrtoeol
    _speak(title+', enter to continue,'+(' '.join(rows)))
    _icol = 0
    _irow = len(rows)
    _goto(titlelength+1, 0)

    while (True):
        c = _getch()
        if (c == 'q' or c == "\030" or c == "\027" or c == "\030" or c == "\003" or c == "\c\\"):
            _erase_lines(0)
            _endwin()
            return True
        elif (c == "\r" or c == "\n"):    # <enter> retains text on screen
            _clrtoeol()
            _goto(0, len(rows)+1)
            _endwin()
            return True
        elif (c == "\014"):
            _puts("\r")
            _endwin()
            _tiview(title, text)
            return True

    print("_tiview: shouldn't reach here\n", file=sys.stderr)
    return False

# ----------------------- help_text --------------------------

def help_text(mode=''):
    '''
This returns a short help message for the user.  If mode is "ask" then
the text describes the keys the user has available when responding to an
ask() question;  If mode is "multi" then the text describes the keys and
mouse actions the user has available when responding to a multiple-choice
choose() question;  otherwise, it describes the keys and mouse actions
the user has available when responding to a single-choice choose().
'''
    if mode == 'ask':
        return "\nLeft and Right arrowkeys, Backspace, Delete; control-B = beginning; control-E = end; control-X = clear; then Return."
    if os.getenv('CLUI_MOUSE') == 'OFF':
        text = "\nmove around with Arrowkeys (or hjkl);"
    else:
        text = "\nmove around with Mouse or Arrowkeys (or hjkl);"
    if re.match('mult',mode):
        text += " multiselect with Rightclick or Spacebar;"
    text += " then either q or ctrl-X for quit,"
    if os.getenv('CLUI_MOUSE') == 'OFF':
        text += " or Return to choose."
    else:
        text += " or choose with Leftclick or Return."
    return text
# -------------------------- infrastructure -------------------------

SpeakMode = set()
def _speak(text, wait=None):   # 1.60
    global _Eflite_FH, _Espeak, _Espeak_PID
    if (not _Eflite_FH and not _Espeak) or not text or len(text) == 0:
        return None
    if 'dot' in SpeakMode:
        text = re.sub('\s*\.\s*', ' dot ', text)
        text = re.sub(r'\s*\.(\w)', r' dot \1', text)
    if _Eflite_FH:
        if len(text) == 1:
            if text == '.':
                _Eflite_FH.write(bytes("s\nq { dot }\nd\n",'ISO-8859-1'))
            else:
                _Eflite_FH.write(bytes("s\nl {"+text+"}\n",'ISO-8859-1'))
            _Eflite_FH.flush()
            if wait:
                time.sleep(0.5)
        else:
            _Eflite_FH.write(bytes("s\nq {"+text+"}\nd\n",'ISO-8859-1'))
            _Eflite_FH.flush()
            # useless emacspeak op: tts_sy nc_state all 0 0  1 225\nq {[:np  ]}
            if wait:
                time.sleep(0.3+0.07*len(text))
    elif _Espeak:
        if _Espeak_PID > 0.5:
            os.kill(_Espeak_PID, signal.SIGHUP)
            os.wait()
            _Espeak_PID = None;
        _Espeak_PID = os.fork()
        if _Espeak_PID > 0.5:
            if wait:
                if len(text) == 1:
                    time.sleep(0.6)
                else:
                    time.sleep(0.4+0.07*len(text))
        else:
            pipe = subprocess.Popen(_Espeak, stdin=subprocess.PIPE)
            if not pipe:
                sys.exit()
            def _huphandler(signum,stackframe):
                pipe.kill()
                os.wait()
                sys.exit()
            signal.signal(signal.SIGHUP, _huphandler)
            if text == '.':
                text = 'dot'
            pipe.stdin.write(text.encode('utf8')+b"\n")
            pipe.stdin.flush()
            pipe.stdin.close()
            os.wait()
            sys.exit()


_OpenFile = 0
def _Open(filename, mode="r"):
    global _OpenFile
    try:
        _OpenFile = open(filename, mode=mode)
        return True
    except EnvironmentError as err:
        print("\ncan't open "+filename+': '+str(err), file=sys.stderr)
        return False

def _Unlink(filename):
    try:
        os.unlink(filename)
        return True
    except EnvironmentError as err:
        print("\ncan't unlink "+filename+": "+str(err), file=sys.stderr)
        return False

def _display_question(question, nofirstline=False):
    '''used by ask() and confirm(), but not by choose() ...'''
    _check_size()
    otherlines_a = []
    # my ($firstline, @otherlines);
    if nofirstline:
        otherlines_a = _fmt(question)
    else:
        # [firstline,otherlines] = re.split('\r?\n', question, 2)
        lines = re.split('\r?\n', question, 1)
        if (lines[0]):
            _puts(lines[0] + " ")
        if (len(lines) > 1):
           otherlines_a = _fmt(lines[1])
    if len(otherlines_a):
        _puts("\r\n" + "\r\n".join(otherlines_a) + "\r")
        _goto(1+len(lines[0]), 0)
    return len(otherlines_a)

def _erase_lines(nline):
    '''leaves cursor at beginning of line nline and clears rest of screen'''
    global _ttyout
    _goto(0, nline)
    print("\033[J", end='', file=_ttyout)
    _ttyout.flush()

def _fmt(text, nofill=False):
    '''Used by _tiview, ask and confirm; formats the text within maxcols cols'''
    # my (@i_words, $o_line, @o_lines, $o_length, $last_line_empty, $w_length);
    # my (@i_lines, $initial_space);
    global _maxcols
    o_line = ''
    o_lines = []
    o_length = 0
    last_line_empty = False
    i_lines = re.split('\r?\n',text)
    for i_line in i_lines:
        if (re.search('^\s*$', i_line)):
            if (o_line):
                o_lines.append(o_line)
                o_line=''
                o_length=0
            if (not last_line_empty):
               o_lines.append('')
               last_line_empty = True
            continue

        last_line_empty = False

        if nofill:
            o_lines.append(i_line[0:_maxcols])
            continue

        # if ($i_line =~ s/^(\s+)//) {   # line begins with space ?
        split_list = re.split(r'^(\s+)', i_line, 1)
        if (len(split_list) > 2):
            i_line = split_list[2]
            initial_space = re.sub(r'\t', '   ', split_list[1])
            if (o_line):
                o_lines.append(o_line)
            o_line = initial_space
            o_length = len(initial_space)
        else:
            initial_space = ''

        i_words = re.split(r'\s+', i_line)
        for i_word in i_words:
            w_length = len(i_word)
            if ((o_length + w_length) >= _maxcols):  # >= 1.54
                o_lines.append(o_line)
                o_line = initial_space
                o_length = len(initial_space)

            if (w_length > _maxcols):   # chop it !
                o_lines,append(i_word[0:_maxcols])
                continue

            if (o_line):
                o_line += ' '
                o_length += 1
            o_line += i_word
            o_length += w_length

    if (o_line):
        o_lines.append(o_line)
    if (len(o_lines) < _maxrows-2):
        return (o_lines)
    else:
        return o_lines[0, _maxrows-2]

def back_up():
    r'''Moves the cursor up one line, to the beginning of the line,
and clears the line.  Useful if your application is validating
the results of an ask() and wishes to re-pose the question.
'''
    ttyout = open("/dev/tty", mode="w")
    print("\r\033[K\033[A\033[K", end='', file = ttyout)
    ttyout.close

def select_file(Chdir=True, Create=False, ShowAll=False,
    DisableShowAll=False, SelDir=False, FPat='*', File='',
    Path='', Title='', TopDir='/', TextFile=False, Readable=False,
    Writeable=False, Executable=False, Owned=False, Directory=False,
    multichoice=False):
    r'''
This function asks the user to select a file from the filesystem.
It offers Rescan and ShowAll buttons.  The options are modelled
on those of Tk::FileDialog but with various new options: TopDir,
TextFile, Readable, Writeable, Executable, Owned and Directory

Multiple choice is possible in a limited circumstance; when
select_file() is invoked with multichoice=True, with Chdir=False
and without Create.  It is not possible to select multiple files
lying in different directories.

Three problem filenames: 'Create New File', 'Show DotFiles' and
'Hide DotFiles' will, if present in your filesystem, cause confusion.

Chdir

Enable the user to change directories. The default is True.
If it is set to False, and multichoice to True, and Create is
not set, then the user can select multiple files.

Create

Enables the user to specify a file that does not exist.
The default is False.

ShowAll

Determines whether hidden files (.*) are displayed.
The default is False.

DisableShowAll

Disables the ability of the user to change the status of the
ShowAll flag. By default the user is allowed to change the status).

SelDir

If True, enables selection of a directory rather than a file.
The default is False.  To _enforce_ selection of a directory,
use the Directory option.

FPat

Sets the default file selection pattern, in glob format, e.g.
'*.html'.  Only files matching this pattern will be displayed.
If you want multiple patterns, you can use formats like
'*.[ch]' or see glob.glob for details.  The default is '*'.

File

The file selected, or the default file.  The default default
is whatever the user selected last time in this directory.

Path

The path of the selected file, or the initial path.
The default is $HOME.

Title

The Title of the dialog box.  If Title is specified, then
select_file() dynamically appends "in </where/ever>" to it.
The default title is "in directory /where/ever".

TopDir

Restricts the user to remain within a directory or its
subdirectories.  The default is "/".

TextFile

Only text files will be displayed. The default is False.

Readable

Only readable files will be displayed. The default is False.

Writeable

Only writeable files will be displayed. The default is False.

Executable

Only executable files will be displayed.  The default is False.

Owned

Only files owned by the current user will be displayed.  This is
useful if the user is being asked to choose a file for a os.chmod()
or chgrp operation, for example.  The default is False.

Directory

Only directories will be displayed.  The default is False.
    '''
    import glob
#    if (!defined $option{'-Path'}) { $option{'-Path'}=$option{'-initialdir'}; }
#    if (!defined $option{'-FPat'}) { $option{'-FPat'}=$option{'-filter'}; }
#    if (!defined $option{'-ShowAll'}) {$option{'-ShowAll'}=$option{'-dotfiles'};}
#    if ($option{'-Directory'}) { $option{'-Chdir'}=1; $option{'-SelDir'}=1; }
#    my $multichoice = 0;
#    if (wantarray && !$option{'-Chdir'} && !$option{'-Create'}) {
#        $option{'-DisableShowAll'} = 1;
#        $multichoice = 1;
    if multichoice and not Chdir and not Create:
        DisableShowAll = True
    else:
        multichoice = False
#    } elsif (!defined $option{'-Chdir'}) {
#        $option{'-Chdir'} = 1;
#    }

    if Path and os.path.isdir(Path):
        dir = re.sub('([^/])$', r'\1/', Path)
    else:
        dir = re.sub('([^/])$', r'\1/', _HOME)
 
    if TopDir:
        if os.path.isdir(TopDir):
            TopDir = re.sub('([^/])$', r'\1/', TopDir)
        if TopDir.find(dir) >= 0:
            dir = TopDir

    #my ($new, $file, @allfiles, @files, @dirs, @pre, @post, %seen, $isnew);
    #my @dotfiles;

    while True:
        if SelDir:
            pre = ['./']
        else:
            pre = []
        post = []
        try:
            allfiles = sorted(os.listdir(dir))
        except EnvironmentError as err:
            sorry(str(err))
            return None
        dotfiles = _re_grep(r'^\.', allfiles)
        if ShowAll:
            if dotfiles and not DisableShowAll:
                post=['Hide DotFiles']
        else:
            allfiles = _re_grep(r'^[^.]', allfiles)
            if dotfiles and not DisableShowAll:
                post=['Show DotFiles']
 
        # split @allfiles into @files and @dirs for option processing ...
        # @dirs  = grep(-d "$dir/$_" and -r "$dir/$_", @allfiles);
        dirs = []
        for f in allfiles:
            ff= os.path.join(dir, f)
            if os.path.isdir(ff) and _is_readable(ff):
                dirs.append(f)
        files = []
        if Directory:
            pass
        elif FPat:
            baselength = len(dir) + len(os.path.sep) -1
            for ff in glob.glob(os.path.join(dir,FPat)):
                if not os.path.isdir(ff):
                    f = ff[baselength:]
                    files.append(f)
        else:
            for f in allfiles:
                ff= os.path.join(dir, f)
                if not os.path.isdir(ff) and _is_readable(ff):
                    files.append(f)
 
        if Chdir:
            for i in range(len(dirs)):
                dirs[i] += os.path.sep
            if TopDir:
                up = re.sub('[^/]+/?$', '', dir)  # find parent directory
                if up.find(TopDir) >= 0:
                    pre.insert(0, '../')
                # must check for symlinks to outside the TopDir ...
            else:
                pre.insert(0, '../')
 
        elif not SelDir:
            dirs = []
 
        if Create:
            post.insert(0, 'Create New File')
        if TextFile:
            #@files = grep(-T "$dir/$_", @files); }
            i = 0
            while i < len(files):
                ff= os.path.join(dir, files[i])
                if not _is_textfile(ff):
                    files.pop(i)
                else:
                    i += 1
        if Owned:
            #@files = grep(-o "$dir/$_", @files); }
            i = 0
            while i < len(files):
                ff= os.path.join(dir, files[i])
                if not _is_owned(ff):
                    files.pop(i)
                else:
                    i += 1
        if Executable:
            #@files = grep(-x "$dir/$_", @files); }
            i = 0
            while i < len(files):
                ff= os.path.join(dir, files[i])
                if not _is_executable(ff):
                    files.pop(i)
                else:
                    i += 1
        if Writeable:
            #@files = grep(-w "$dir/$_", @files); }
            i = 0
            while i < len(files):
                ff= os.path.join(dir, files[i])
                if not _is_writeable(ff):
                    files.pop(i)
                else:
                    i += 1
        if Readable:
            #@files = grep(-r "$dir/$_", @files); }
            i = 0
            while i < len(files):
                ff= os.path.join(dir, files[i])
                if not _is_readable(ff):
                    files.pop(i)
                else:
                    i += 1

        allfiles = pre + sorted(dirs+files) + post  # reconstitute allfiles

        if Title:
            title = Title+" in "+dir
        else:
            title = "in directory "+dir+" ?"

        if File:
             set_default(title, File)
 
        SpeakMode.add('dot')
        if multichoice:
            new = choose(title, allfiles, multichoice=True)
            SpeakMode.remove('dot')
            if not new:
                return []
            for i in range(len(new)):
                new[i] = dir+new[i]
            return new

        new = choose (title, allfiles)
        SpeakMode.remove('dot')

        if (ShowAll and new == 'Hide DotFiles'):
            ShowAll = False
            _up(1)
            continue  # ARGHHHhhh no redo :-(
        elif (not ShowAll and new == 'Show DotFiles'):
            ShowAll = True
            _up(1)
            continue  # ARGHHHhhh no redo :-(
 
        if new == "Create New File":
            new = ask("new file name ?")  # validating this is a chore :-(
            if not new:
                continue
            if re.match('^/', new):
                file = new; 
            else:
                file = dir+new
            file = re.sub('//+', '/', file)  # simplify //// down to /
            while re.match(r'./\.\./', file):
                file = re.sub(r'[^/]*/\.\./', '', file)  # zap /../
            file = re.sub(r'/[^/]*/\.\.$', '', file)  # and /.. at end
            if TopDir:  # check against escape from TopDir
                if file.find(TopDir) > -1:
                    dir = TopDir
                    continue

            if os.path.isdir(file):  # pre-existing directory ?
                if SelDir:
                    return file
                else:
                    dir=file
                    if re.match('[^/]$', dir):
                        dir += '/'
                        continue
 
            #$file =~ m#^(.*/)([^/]+)$#;
            dirname = os.path.dirname(file)
            basename = os.path.basename(file)
            if os.path.exists(file):
                continue
            # must check for createbility (e.g. dir exists and is writeable)
            if os.path.isdir(dirname) and _is_writeable(dirname):
                return file
            if not _is_writeable(dirname):
                sorry ("directory "+dirname+" does not exist.")
                continue
            sorry ("directory "+dirname+" is not writeable.")
            continue

        if not new:
            return None
        if (new == './') and SelDir:
            return dir

        if re.match('^/', new):
            file = new      # abs filename
        else:
            file = dir+new  # rel filename (slash always at end)

        if (new == '../'):
            dir = re.sub('[^/]+/?$', '', dir)
            back_up()
            continue
        elif new == './':
            if SelDir:
                return dir
            file = dir
        elif re.search('/$', file):
            dir = file
            back_up()
            continue
        elif os.path.isfile(file):
            return file