-
Notifications
You must be signed in to change notification settings - Fork 0
/
escapes.d
108 lines (85 loc) · 2.32 KB
/
escapes.d
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
module escapes;
import std.conv;
import std.process;
import std.typecons;
import std.string;
struct Keys
{
static:
string alternateScreenOn;
string alternateScreenOff;
string[256] colorFG;
string[256] colorBG;
string terminator;
/// undoes cursorInvisible
string cursorNormal;
string cursorInvisible;
string cursorR;
string cursorL;
string cursorU;
string cursorD;
/// also returns cursor to home
string eraseDisplay;
string eraseLine;
private string[int][int] cursorAtCache;
string cursorAt(short l, short c)
{
return cursorAtCache.require(l).require(c, callTput("cup "~to!string(l)~" "~to!string(c)));
}
/**
* interrogates terminfo to discover escape codes
*
* go read man 5 terminfo
*
* from what I can gather, it is possible to initialize static
* members with functions, but only at compile time (so if the
* function can go through CTFE). Well, it's only a theory;
* either that or DMD has one more bug.
*/
void discover()
{
alternateScreenOn = callTput("smcup");
alternateScreenOff = callTput("rmcup");
if (to!int(callTput("colors")) < 256)
throw new Exception("Your terminal does not support 256 colors !");
colorFG = getColorEscapes(0,colorFG.length, "f");
colorBG = getColorEscapes(0,colorBG.length, "b");
terminator = callTput("sgr0");
cursorNormal = callTput("cnorm");
cursorInvisible = callTput("civis");
cursorR = callTput("cuf1");
cursorL = callTput("cub1");
cursorU = callTput("cuu1");
cursorD = callTput("cud1");
eraseDisplay = callTput("clear");
eraseLine = callTput("dl1");
}
}
string callTput(string args)
{
string command = "tput ";
command~=args;
auto sh = pipeShell(command, Redirect.stdout);
wait(sh.pid);
auto result = to!string(sh.stdout.byLine().front);
sh.stdout.close();
return strip(result);
}
/**
* calls tput setab on each number to find out the escape code
* bORf : background or foreground, as one letter
*/
string[] getColorEscapes(int min, int max, string bORf)
{
string[] result;
result.length = max;
for (int i=min ; i<max; i++)
{
string command = "tput seta"~bORf~" "~to!string(i);
auto sh = pipeShell(command, Redirect.stdout);
wait(sh.pid);
result[i] = to!string(sh.stdout.byLine().front);
sh.stdout.close();
}
return result;
}