using System;
using System.IO;
using System.Text;
namespace StardewModdingAPI.Framework.Logging
{
/// A text writer which allows intercepting output.
internal class InterceptingTextWriter : TextWriter
{
/*********
** 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 message is written to the console directly.
public event Action OnMessageIntercepted;
/*********
** Public methods
*********/
/// Construct an instance.
/// The underlying output writer.
public InterceptingTextWriter(TextWriter output)
{
this.Out = output;
}
/// Writes a subarray of characters to the text string or stream.
/// The character array to write data from.
/// The character position in the buffer at which to start retrieving data.
/// The number of characters to write.
public override void Write(char[] buffer, int index, int count)
{
if (this.ShouldIntercept)
this.OnMessageIntercepted?.Invoke(new string(buffer, index, count).TrimEnd('\r', '\n'));
else
this.Out.Write(buffer, index, count);
}
/// Writes a character to the text string or stream.
/// The character to write to the text stream.
/// Console log messages from the game should be caught by . This method passes through anything that bypasses that method for some reason, since it's better to show it to users than hide it from everyone.
public override void Write(char ch)
{
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.OnMessageIntercepted = null;
}
}
}