Repository navigation
Expand file tree
/
Copy pathFormScriptOutput.cs
More file actions
484 lines (429 loc) · 19.2 KB
/
Copy pathFormScriptOutput.cs
File metadata and controls
484 lines (429 loc) · 19.2 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
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SharpTagManager
{
partial class FormScriptOutput : Form
{
public ScriptInstance Script { private set; get;}
private Color ColorGood = Color.FromArgb(196,240,177);
private Color ColorWarning = Color.Yellow;
private Color ColorError = Color.Red;
private Color ColorRpc = Color.SkyBlue;
// Tracks the current ANSI foreground color across printed lines
private Color currentAnsiColor = default;
private bool IsLoaded = false;
// Collection of events from various console pumping threads (stdin,stderr..etc)
private readonly ConcurrentQueue<Action> pendingConsoleActions = new ConcurrentQueue<Action>();
public FormScriptOutput(ScriptInstance script)
{
InitializeComponent();
Script = script;
script.FormOutput = this;
}
public static void Show(ScriptInstance script, bool toFront=false)
{
// Make sure the creation of the form happens on the main UI thread (things go wrong later otherwise)
if (FormMain.Instance.InvokeRequired == true)
{
FormMain.Instance.Invoke((MethodInvoker)delegate {
Show(script, toFront);
});
return;
}
// Check if we already have a form
if (script.FormOutput == null || script.FormOutput.IsDisposed)
{
script.FormOutput = new FormScriptOutput(script);
script.FormOutput.Show();
}
else
{
// Bring the existing form to the front or focus on it
if (toFront)
{
script.FormOutput.BringToFront();
script.FormOutput.Focus();
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
// Fallback release for pendingRpcSuccess - see its declaration for why this exists
// and why it's a generous timeout rather than the actual ordering mechanism.
if (pendingRpcSuccess != null && (DateTime.UtcNow - pendingRpcSuccessSince).TotalMilliseconds >= RpcFallbackMs)
ReleasePendingRpcSuccess();
// Drain console output queued by background script threads - see
// pendingConsoleActions above for why this is deferred rather than printed directly.
while (pendingConsoleActions.TryDequeue(out Action action))
action();
// Script.ProcessObj can be swapped out or disposed concurrently (venv setup runs on a
// background thread; Stop() disposes the process) — HasExited throws if the reference
// we grabbed is no longer associated with a real process by the time we read it.
Process process = Script.ProcessObj;
bool? hasExited;
try
{
hasExited = process?.HasExited;
}
catch (InvalidOperationException)
{
hasExited = null;
}
if (Script.ErrorMessage != null)
{
labelStatus.Text = Script.ErrorMessage;
labelStatus.BackColor = Color.FromArgb(255, 95, 95);
}
else if (process == null || hasExited == null)
{
labelStatus.Text = "Not running";
labelStatus.BackColor = Color.FromArgb(252, 222, 222);
}
else if (hasExited == true)
{
labelStatus.Text = "Exited";
labelStatus.BackColor = Color.FromArgb(255, 252, 217);
}
else
{
labelStatus.Text = "Running";
labelStatus.BackColor = Color.FromArgb(208, 235, 195);
}
}
private void FormScriptOutput_Load(object sender, EventArgs e)
{
this.Text = $"Script output [{Script?.Name}]";
IsLoaded = true;
}
private void FormScriptOutput_KeyPress(object sender, KeyPressEventArgs e)
{
if ((Script.ProcessObj != null) && (Script.ProcessObj.HasExited == false))
{
StreamWriter processInput = Script.ProcessObj.StandardInput;
processInput.Write(e.KeyChar); // Send the key to stdin
richTextBox1_Print(e.KeyChar.ToString());
e.Handled = true;
}
}
private void FormScriptOutput_KeyDown(object sender, KeyEventArgs e)
{
if ((Script.ProcessObj != null) && (Script.ProcessObj.HasExited == false))
{
// Capture keystrokes and send to the process's stdin
char keyChar = (char)e.KeyCode;
StreamWriter processInput = Script.ProcessObj.StandardInput;
e.Handled = true; // Prevent key from being processed by the form
// Handle specific keys like Enter, Backspace, etc.
switch (e.KeyCode)
{
case Keys.Enter:
processInput.WriteLine(); // Send Enter to stdin
richTextBox1_Print("", newLine:true);
break;
case Keys.Back:
// Handle backspace if needed, send escape sequence if necessary
processInput.Write("\b");
break;
default:
// Regular character key (Handle these in KeyPress to get it in the correct case)
e.Handled = false;
break;
}
}
}
private void FormScriptOutput_FormClosed(object sender, FormClosedEventArgs e)
{
Script.FormOutput = null;
Dispose();
}
private void clearConsoleToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void restartToolStripMenuItem_Click(object sender, EventArgs e)
{
Script.Restart();
}
private void killToolStripMenuItem_Click(object sender, EventArgs e)
{
Script.Stop();
}
public void Process_RpcEvent(string str)
{
pendingConsoleActions.Enqueue(() => richTextBox1_Print($"RPC Call '{str}' ... ", ColorRpc, lineType: 6));
}
private Action pendingRpcSuccess = null;
private DateTime pendingRpcSuccessSince;
private bool stderrEnded = false;
private const int RpcFallbackMs = 5000;
private void ReleasePendingRpcSuccess()
{
if (pendingRpcSuccess == null) return;
pendingConsoleActions.Enqueue(pendingRpcSuccess);
pendingRpcSuccess = null;
}
public void Process_RpcSuccess(string data)
{
Action show = () =>
{
richTextBox1_Print($"OK", ColorRpc, lineType: 6, newLine: true);
richTextBox1_Print(data, ColorRpc, lineType: 6, newLine: true);
};
if (stderrEnded)
{
pendingConsoleActions.Enqueue(show); // stderr already fully drained for this process
}
else
{
pendingRpcSuccess = show;
pendingRpcSuccessSince = DateTime.UtcNow;
}
}
public void Process_StdioReceive(DataReceivedEventArgs e, bool isError = false)
{
if (e.Data == null)
{
if (isError)
{
stderrEnded = true;
ReleasePendingRpcSuccess();
}
return;
}
string data = e.Data; // capture now - queued closures shouldn't hold onto e itself
pendingConsoleActions.Enqueue(() => PrintStdio(data));
}
private void PrintStdio(string data)
{
// Handle carriage return: replace the current last line in-place
if (data.Contains('\r'))
{
int crIndex = data.LastIndexOf('\r');
int lastLine = richTextBox1.Lines.Length - 1;
if (lastLine >= 0)
{
int lineStart = richTextBox1.GetFirstCharIndexFromLine(lastLine);
richTextBox1.ReadOnly = false;
richTextBox1.Select(lineStart, richTextBox1.TextLength - lineStart);
richTextBox1.SelectedText = "";
richTextBox1.ReadOnly = true;
}
data = data.Substring(crIndex + 1);
if (string.IsNullOrEmpty(data)) return;
}
// Parse ANSI color sequences into colored segments and print each
var segments = ParseAnsiSegments(data);
for (int i = 0; i < segments.Count; i++)
{
var (text, color) = segments[i];
bool isLast = i == segments.Count - 1;
if (!string.IsNullOrEmpty(text) || isLast)
richTextBox1_Print(text, color, newLine: isLast);
}
}
public void Process_Exited(object sender, EventArgs e)
{
Process process = sender as Process;
if (process == null) return;
int exitCode = process.ExitCode;
pendingConsoleActions.Enqueue(() =>
{
if (exitCode == 0)
richTextBox1_Print("Process ended successfully", foreColor: ColorGood, lineType: 3, newLine: true);
else
richTextBox1_Print($"Process ended with code {exitCode}", foreColor: ColorWarning, lineType: 3, newLine: true);
});
}
public void Process_Started(object sender, EventArgs e)
{
Process process = sender as Process;
if (process == null) return;
int pid = process.Id;
// A fresh process means a fresh stderr pipe - stderrEnded (and anything still
// waiting on it) belongs to whatever process came before, if any, and no longer
// applies. Matters for scripts run sequentially over multiple images: each one-shot
// process's own stderr needs to reach its own EOF before its own "OK" shows.
stderrEnded = false;
pendingRpcSuccess = null;
pendingConsoleActions.Enqueue(() => richTextBox1_Print($"Process started as PID {pid}", foreColor: ColorGood, lineType: 3, newLine: true));
}
public void Process_Error(object sender, string err)
{
pendingConsoleActions.Enqueue(() => richTextBox1_Print(err, foreColor: ColorError, lineType: 4, newLine: true));
}
// For messages generated by the app itself (e.g. venv/uv setup progress) rather than
// captured from a subprocess's stdout/stderr stream.
public void Log(string text, bool isError = false)
{
pendingConsoleActions.Enqueue(() => richTextBox1_Print(text, foreColor: isError ? ColorError : ColorWarning, lineType: 5, newLine: true));
}
int lastLineType = -1;
bool lastLineHasText = false;
public void richTextBox1_Print(string str, Color foreColor=default, int lineType=-1, bool newLine=false)
{
if (IsLoaded == false)
return;
if (InvokeRequired)
{
this.Invoke((MethodInvoker)delegate {
richTextBox1_Print(str, foreColor, lineType,newLine);
});
return;
}
// For some reason calling this before AppendText makes the control scroll to the end as we fill it (seems to be the most efficient method to do it)
// However has a side effect of focusing the form, so we should not use if we don't already have focus
bool isFocused = this.ContainsFocus;
if (isFocused)
richTextBox1.Focus();
// Separate different types of print output with newlines (prevents status update messages getting stuck in the middle of printed output)
if ((lastLineType != lineType) && lastLineHasText)
{
richTextBox1.AppendText("\n");
richTextBox1.Select(richTextBox1.Text.Length - 1, 0);
}
lastLineType = lineType;
int start = richTextBox1.TextLength;
richTextBox1.AppendText(str);
if (newLine)
richTextBox1.AppendText("\n");
if (foreColor != default)
{
richTextBox1.Select(start, str.Length);
richTextBox1.SelectionColor = foreColor;
richTextBox1.SelectionLength = 0;
}
// Trim oldest lines when over the cap (only after complete lines to reduce overhead)
if (newLine)
{
int maxLines = AppSettings.Instance.Scripting_ConsoleLinesMax;
if (maxLines > 0 && richTextBox1.Lines.Length > maxLines)
{
int excess = richTextBox1.Lines.Length - maxLines;
int cutIndex = richTextBox1.GetFirstCharIndexFromLine(excess);
if (cutIndex > 0)
{
richTextBox1.ReadOnly = false;
richTextBox1.Select(0, cutIndex);
richTextBox1.SelectedText = "";
richTextBox1.ReadOnly = true;
}
}
}
// Alternative scrolling to the end method
if (!isFocused)
{
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}
}
// Splits a string into (text, color) segments by parsing ANSI SGR escape sequences.
// Updates currentAnsiColor as state across calls (color persists between lines).
private List<(string text, Color color)> ParseAnsiSegments(string input)
{
var segments = new List<(string text, Color color)>();
var regex = new Regex(@"\x1B\[([0-9;]*)([A-Za-z])");
int pos = 0;
foreach (Match match in regex.Matches(input))
{
if (match.Index > pos)
segments.Add((input.Substring(pos, match.Index - pos), currentAnsiColor));
char command = match.Groups[2].Value[0];
string args = match.Groups[1].Value;
if (command == 'm')
ApplyAnsiSgr(args);
else if (command == 'J' && args == "2")
richTextBox1.Clear();
// All other sequences (cursor movement etc.) are stripped
pos = match.Index + match.Length;
}
if (pos < input.Length)
segments.Add((input.Substring(pos), currentAnsiColor));
return segments;
}
// Updates currentAnsiColor based on an SGR parameter string (e.g. "1;32" or "0").
private void ApplyAnsiSgr(string args)
{
if (string.IsNullOrEmpty(args) || args == "0") { currentAnsiColor = default; return; }
int[] codes = args.Split(';').Select(s => int.TryParse(s, out int n) ? n : 0).ToArray();
for (int i = 0; i < codes.Length; i++)
{
switch (codes[i])
{
case 0: currentAnsiColor = default; break;
// Standard foreground (dark-terminal tuned)
case 30: currentAnsiColor = Color.FromArgb( 80, 80, 80); break;
case 31: currentAnsiColor = Color.FromArgb(204, 0, 0); break;
case 32: currentAnsiColor = Color.FromArgb( 78, 154, 6); break;
case 33: currentAnsiColor = Color.FromArgb(196, 160, 0); break;
case 34: currentAnsiColor = Color.FromArgb( 52, 101, 164); break;
case 35: currentAnsiColor = Color.FromArgb(117, 80, 123); break;
case 36: currentAnsiColor = Color.FromArgb( 6, 152, 154); break;
case 37: currentAnsiColor = Color.Silver; break;
// Bright foreground
case 90: currentAnsiColor = Color.Gray; break;
case 91: currentAnsiColor = Color.FromArgb(239, 41, 41); break;
case 92: currentAnsiColor = Color.FromArgb(138, 226, 52); break;
case 93: currentAnsiColor = Color.FromArgb(252, 233, 79); break;
case 94: currentAnsiColor = Color.FromArgb(114, 159, 207); break;
case 95: currentAnsiColor = Color.FromArgb(173, 127, 168); break;
case 96: currentAnsiColor = Color.FromArgb( 52, 226, 226); break;
case 97: currentAnsiColor = Color.White; break;
// 256-color: ESC[38;5;n m
case 38 when i + 2 < codes.Length && codes[i + 1] == 5:
currentAnsiColor = Ansi256ToColor(codes[i + 2]);
i += 2;
break;
// True color: ESC[38;2;r;g;b m
case 38 when i + 4 < codes.Length && codes[i + 1] == 2:
currentAnsiColor = Color.FromArgb(codes[i + 2], codes[i + 3], codes[i + 4]);
i += 4;
break;
}
}
}
private static Color Ansi256ToColor(int n)
{
if (n < 16)
{
// Standard + bright colors (same mapping as the SGR codes above)
Color[] palette =
{
Color.FromArgb( 80, 80, 80), Color.FromArgb(204, 0, 0),
Color.FromArgb( 78, 154, 6), Color.FromArgb(196, 160, 0),
Color.FromArgb( 52, 101, 164), Color.FromArgb(117, 80, 123),
Color.FromArgb( 6, 152, 154), Color.Silver,
Color.Gray, Color.FromArgb(239, 41, 41),
Color.FromArgb(138, 226, 52), Color.FromArgb(252, 233, 79),
Color.FromArgb(114, 159, 207), Color.FromArgb(173, 127, 168),
Color.FromArgb( 52, 226, 226), Color.White,
};
return palette[n];
}
if (n < 232)
{
// 6x6x6 color cube
int idx = n - 16;
int b = idx % 6; idx /= 6;
int g = idx % 6;
int r = idx / 6;
return Color.FromArgb(r == 0 ? 0 : r * 40 + 55,
g == 0 ? 0 : g * 40 + 55,
b == 0 ? 0 : b * 40 + 55);
}
// Grayscale ramp 232-255
int v = (n - 232) * 10 + 8;
return Color.FromArgb(v, v, v);
}
}
}