Repository navigation
Expand file tree
/
Copy pathSixel.Supported.cs
More file actions
234 lines (205 loc) · 7.71 KB
/
Copy pathSixel.Supported.cs
File metadata and controls
234 lines (205 loc) · 7.71 KB
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
using System.Globalization;
using System.Text;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace SixPix;
public static partial class Sixel
{
private static Size? CellSize;
private const string CSI_DEVICE_ATTRIBUTES = "[c";
private const string CSI_SYNC_OUTPUT = "[?2026$p";
private const string CSI_CELL_SIZE = "[16t";
private const string CSI_WINDOW_PIXSIZE = "[14t";
private const string CSI_WINDOW_CHARSIZE = "[18t";
/// <summary>
/// Check whether current terminal support Sixel
/// <returns>bool</returns>
/// </summary>
public static bool IsSupported()
{
// Should get something like: ^[[?61;4;6;7;14;21;22;23;24;28;32;42c
// The "4" indicates Sixel support
DebugPrint($"IsSupported: ^[{CSI_DEVICE_ATTRIBUTES} => ", ConsoleColor.DarkGray);
var response = GetCtrlSeqResponse(CSI_DEVICE_ATTRIBUTES);
return response.Contains(";4;", StringComparison.Ordinal)
|| response.EndsWith(";4", StringComparison.Ordinal);
}
/// <summary>
/// Check whether current terminal support synchronized output
/// <returns>bool</returns>
/// </summary>
public static bool IsSyncSupported()
{
// Should get something like: ^[[?2026;1$yc
// The "1" indicates synchronized output support (may receive 0 in its place, or nothing at all)
DebugPrint($"IsSyncSupported: ^[{CSI_SYNC_OUTPUT} => ", ConsoleColor.DarkGray);
var response = GetCtrlSeqResponse(CSI_SYNC_OUTPUT, 'y');
return !(response == default || response.Contains("2026;0$", StringComparison.Ordinal));
}
/// <summary>
/// Get the cell size of the terminal in pixel-sixel size.
/// </summary>
/// <returns><see cref="Size"/> in pixels that will fit in a single character cell.</returns>
/// <remarks>The response to the command will look like [6;20;10t where the 20 is height and 10 is width. Is the 6 the terminal class?</remarks>
public static Size GetCellSize()
{
// cache result, doesn't change with terminal size
if (CellSize is not null)
return CellSize.Value;
DebugPrint($"GetCellSize: ^[{CSI_CELL_SIZE} => ", ConsoleColor.DarkGray);
var response = GetCtrlSeqResponse(CSI_CELL_SIZE);
try
{
Span<Range> ranges = new Range[3];
response.Split(ranges, ';');
CellSize = new()
{
Width = int.Parse(response[ranges[2]], CultureInfo.InvariantCulture),
Height = int.Parse(response[ranges[1]], CultureInfo.InvariantCulture)
};
}
catch
{
// Return the default Windows Terminal size if we can't get the size from the terminal.
return new(10, 20);
}
return CellSize.Value;
}
/// <summary>
/// Get the window size in pixels.
/// </summary>
/// <returns><see cref="Size"/> in pixels</returns>
public static Size GetWindowPixelSize()
{
// don't cache result, since the terminal can be resized
DebugPrint($"GetWindowPixelSize: ^[{CSI_WINDOW_PIXSIZE} => ", ConsoleColor.DarkGray);
var response = GetCtrlSeqResponse(CSI_WINDOW_PIXSIZE);
try
{
Span<Range> ranges = new Range[3];
response.Split(ranges, ';');
return new()
{
Width = int.Parse(response[ranges[2]], CultureInfo.InvariantCulture),
Height = int.Parse(response[ranges[1]], CultureInfo.InvariantCulture)
};
}
catch
{
return new(0, 0);
}
}
/// <summary>
/// Get the window size in characters.
/// </summary>
/// <returns><see cref="Size"/> in characters</returns>
/// <remarks>Equivalent to (Console.WindowWidth, Console.WindowHeight)</remarks>
public static Size GetWindowCharSize()
{
// don't cache result, since the terminal can be resized
return new(Console.WindowWidth, Console.WindowHeight);
/*
var response = GetCtrlSeqResponse(CSI_WINDOW_CHARSIZE);
try
{
var parts = response.Split(';', 't');
return new()
{
Width = int.Parse(parts[2]),
Height = int.Parse(parts[1]),
};
}
catch
{
return new(0, 0);
}
*/
}
private static Color _backgroundColor = Color.Transparent;
/// <summary>
/// Background color.
/// The transparent color is replaced or blend by this color when <see cref="Transparency"/> is <c>None</c>
/// </summary>
public static Color BackgroundColor
{
get
{
if (_backgroundColor != Color.Transparent)
return _backgroundColor;
_backgroundColor = TerminalBackgroundColor;
return _backgroundColor;
}
set => _backgroundColor = value;
}
private static Color _termBG = Color.Transparent;
/// <summary>
/// Terminal Background color.
/// </summary>
public static Color TerminalBackgroundColor
{
get
{
if (_termBG != Color.Transparent)
return _termBG;
// ^[]11;rgb:2828/2c2c/3434^[\
DebugPrint("GetTerminalBackgroundColor: ^[]11;?\\G => ", ConsoleColor.DarkGray);
var response = GetCtrlSeqResponse($"]11;?{(char)0x07}", '\\', (char)0x07);
var start = response.IndexOf(':') + 1;
if (start < 1)
return _termBG;
var code = response[start..];
Span<Range> rgbRange = new Range[3];
if (code.Split(rgbRange, '/') != 3)
return _termBG;
_termBG = Color.FromPixel(new Rgb48(ushort.Parse(code[rgbRange[0]], NumberStyles.HexNumber, CultureInfo.InvariantCulture),
ushort.Parse(code[rgbRange[1]], NumberStyles.HexNumber, CultureInfo.InvariantCulture),
ushort.Parse(code[rgbRange[2]], NumberStyles.HexNumber, CultureInfo.InvariantCulture)));
return _termBG;
}
set => _termBG = value;
}
/// <summary>
/// Get the response to an ANSI control sequence.
/// </summary>
/// <returns>string response</returns>
public static ReadOnlySpan<char> GetCtrlSeqResponse(string ctrlSeq, params char[] endChars)
{
var ends = endChars.Length > 0 ? endChars : [ctrlSeq[^1]];
var response = new StringBuilder();
#if DEBUG
var start = DateTime.Now;
#endif
async Task ReadKeys(CancellationToken ct)
{
while (!Console.KeyAvailable)
{
ct.ThrowIfCancellationRequested();
await Task.Delay(1, ct);
}
do
{
char c = Console.ReadKey(true).KeyChar;
DebugPrint($"{(char.IsControl(c) ? $"\\{(char)(Convert.ToByte(c) + 0x40)}" : c)}",
char.IsControl(c) ? ConsoleColor.Magenta : ConsoleColor.Red);
if (ends.Contains(c))
break;
if (!char.IsControl(c))
response.Append(c);
}
while (Console.KeyAvailable);
#if DEBUG
DebugPrint($" ({(DateTime.Now - start).TotalMilliseconds}ms)", ConsoleColor.DarkGray, true);
#endif
}
try
{
// Timeout: 100 ms
var cts = new CancellationTokenSource(100);
using var readTask = ReadKeys(cts.Token);
Console.Out.Write($"{ESC}{ctrlSeq}");
readTask.Wait(cts.Token);
}
catch (OperationCanceledException) { }
return response.ToString();
}
}