blob: b8f2c34e2ffad73bff22d22de34ecfa9d5faa89c (
plain)
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
|
using System;
namespace StardewModdingAPI.Framework.Logging
{
/// <summary>Manages console output interception.</summary>
internal class ConsoleInterceptionManager : IDisposable
{
/*********
** Properties
*********/
/// <summary>The intercepting console writer.</summary>
private readonly InterceptingTextWriter Output;
/*********
** Accessors
*********/
/// <summary>Whether the current console supports color formatting.</summary>
public bool SupportsColor { get; }
/// <summary>The event raised when a message is written to the console directly.</summary>
public event Action<string> OnMessageIntercepted;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
public ConsoleInterceptionManager()
{
// redirect output through interceptor
this.Output = new InterceptingTextWriter(Console.Out);
this.Output.OnMessageIntercepted += line => this.OnMessageIntercepted?.Invoke(line);
Console.SetOut(this.Output);
// test color support
this.SupportsColor = this.TestColorSupport();
}
/// <summary>Get an exclusive lock and write to the console output without interception.</summary>
/// <param name="action">The action to perform within the exclusive write block.</param>
public void ExclusiveWriteWithoutInterception(Action action)
{
lock (Console.Out)
{
try
{
this.Output.ShouldIntercept = false;
action();
}
finally
{
this.Output.ShouldIntercept = true;
}
}
}
/// <summary>Release all resources.</summary>
public void Dispose()
{
Console.SetOut(this.Output.Out);
this.Output.Dispose();
}
/*********
** private methods
*********/
/// <summary>Test whether the current console supports color formatting.</summary>
private bool TestColorSupport()
{
try
{
this.ExclusiveWriteWithoutInterception(() =>
{
Console.ForegroundColor = Console.ForegroundColor;
});
return true;
}
catch (Exception)
{
return false; // Mono bug
}
}
}
}
|