using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace StardewModdingAPI.Framework.Logging
{
/// A text writer which allows intercepting output.
internal class InterceptingTextWriter : TextWriter
{
/*********
** Properties
*********/
/// The current line being intercepted.
private readonly List Line = new List();
/*********
** Accessors
*********/
/// The underlying console output.
public TextWriter Out { get; }
/// The character encoding in which the output is written.
public override Encoding Encoding => this.Out.Encoding;
/// Whether to intercept console output.
public bool ShouldIntercept { get; set; }
/// The event raised when a line of text is intercepted.
public event Action OnLineIntercepted;
/*********
** Public methods
*********/
/// Construct an instance.
/// The underlying output writer.
public InterceptingTextWriter(TextWriter output)
{
this.Out = output;
}
/// Writes a character to the text string or stream.
/// The character to write to the text stream.
public override void Write(char ch)
{
// intercept
if (this.ShouldIntercept)
{
switch (ch)
{
case '\r':
return;
case '\n':
this.OnLineIntercepted?.Invoke(new string(this.Line.ToArray()));
this.Line.Clear();
break;
default:
this.Line.Add(ch);
break;
}
}
// pass through
else
this.Out.Write(ch);
}
/// Releases the unmanaged resources used by the and optionally releases the managed resources.
/// true to release both managed and unmanaged resources; false to release only unmanaged resources.
protected override void Dispose(bool disposing)
{
this.OnLineIntercepted = null;
}
}
}