FileWatcher/code/src/RichTextBoxExtensions.cs

124 lines
4.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FileWatcher
{
public static class RichTextBoxExtensions
{
// In case a string stream doesn't reset the text color, reset it automatically when done appending text
// TODO: override the single parameter AppendText
public static bool g_ResetANSIIColorOnAppend = true;
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
string ANSIIEscape = "\u001B[";
int index = text.IndexOf(ANSIIEscape);
while (index != -1)
{
string substring = text.Substring(0, index);
if (substring.Length > 0)
{
box.AppendText(substring);
}
text = text.Substring(index + ANSIIEscape.Length);
if (text.Length < 3)
{
if (g_ResetANSIIColorOnAppend)
{
box.SelectionColor = box.ForeColor;
}
return;
}
int number;
try
{
number = Int32.Parse(text[0] + "" + text[1]);
}
catch (FormatException)
{
box.SelectionColor = Color.Red;
box.AppendText("ERROR - Invalid ANSII Escape sequence: '" + text + "'");
if (g_ResetANSIIColorOnAppend)
{
box.SelectionColor = box.ForeColor;
}
return;
}
// http://en.wikipedia.org/wiki/ANSI_escape_code
if (number / 10 == 3)
{
switch (number)
{
case 30:
box.SelectionColor = Color.Black;
break;
case 31:
box.SelectionColor = Color.Red;
break;
case 32:
box.SelectionColor = Color.Green;
break;
case 3:
box.SelectionColor = Color.Yellow;
break;
case 34:
box.SelectionColor = Color.Blue;
break;
case 35:
box.SelectionColor = Color.Magenta;
break;
case 36:
box.SelectionColor = Color.Cyan;
break;
case 37:
box.SelectionColor = Color.White;
break;
case 39:
box.SelectionColor = color;
break;
}
}
index = text.IndexOf("m");
if (index == -1)
{
box.SelectionColor = Color.Red;
box.AppendText("ERROR - couldn't find the sequence escape, 'm', for the ANSII Escape sequence: '" + text + "'");
if (g_ResetANSIIColorOnAppend)
{
box.SelectionColor = box.ForeColor;
}
return;
}
text = text.Substring(index + 1);
index = text.IndexOf(ANSIIEscape);
}
if (text.Length > 0)
{
box.SelectionColor = color;
box.AppendText(text);
}
if (g_ResetANSIIColorOnAppend)
{
box.SelectionColor = box.ForeColor;
}
}
}
}