summaryrefslogtreecommitdiff
path: root/src/SMAPI.Internal/ConsoleWriting/ColorfulConsoleWriter.cs
blob: 19a31c7bcb0a31a0a1e4f9177df2d50e244795f3 (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
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
#nullable disable

using System;
using System.Collections.Generic;
using StardewModdingAPI.Toolkit.Utilities;

namespace StardewModdingAPI.Internal.ConsoleWriting
{
    /// <summary>Writes color-coded text to the console.</summary>
    internal class ColorfulConsoleWriter : IConsoleWriter
    {
        /*********
        ** Fields
        *********/
        /// <summary>The console text color for each log level.</summary>
        private readonly IDictionary<ConsoleLogLevel, ConsoleColor> Colors;

        /// <summary>Whether the current console supports color formatting.</summary>
        private readonly bool SupportsColor;


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="platform">The target platform.</param>
        public ColorfulConsoleWriter(Platform platform)
            : this(platform, ColorfulConsoleWriter.GetDefaultColorSchemeConfig(MonitorColorScheme.AutoDetect)) { }

        /// <summary>Construct an instance.</summary>
        /// <param name="platform">The target platform.</param>
        /// <param name="colorConfig">The colors to use for text written to the SMAPI console.</param>
        public ColorfulConsoleWriter(Platform platform, ColorSchemeConfig colorConfig)
        {
            if (colorConfig.UseScheme == MonitorColorScheme.None)
            {
                this.SupportsColor = false;
                this.Colors = null;
            }
            else
            {
                this.SupportsColor = this.TestColorSupport();
                this.Colors = this.GetConsoleColorScheme(platform, colorConfig);
            }
        }

        /// <summary>Write a message line to the log.</summary>
        /// <param name="message">The message to log.</param>
        /// <param name="level">The log level.</param>
        public void WriteLine(string message, ConsoleLogLevel level)
        {
            if (this.SupportsColor)
            {
                if (level == ConsoleLogLevel.Critical)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine(message);
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = this.Colors[level];
                    Console.WriteLine(message);
                    Console.ResetColor();
                }
            }
            else
                Console.WriteLine(message);
        }

        /// <summary>Get the default color scheme config for cases where it's not configurable (e.g. the installer).</summary>
        /// <param name="useScheme">The default color scheme ID to use, or <see cref="MonitorColorScheme.AutoDetect"/> to select one automatically.</param>
        /// <remarks>The colors here should be kept in sync with the SMAPI config file.</remarks>
        public static ColorSchemeConfig GetDefaultColorSchemeConfig(MonitorColorScheme useScheme)
        {
            return new ColorSchemeConfig
            {
                UseScheme = useScheme,
                Schemes = new Dictionary<MonitorColorScheme, IDictionary<ConsoleLogLevel, ConsoleColor>>
                {
                    [MonitorColorScheme.DarkBackground] = new Dictionary<ConsoleLogLevel, ConsoleColor>
                    {
                        [ConsoleLogLevel.Trace] = ConsoleColor.DarkGray,
                        [ConsoleLogLevel.Debug] = ConsoleColor.DarkGray,
                        [ConsoleLogLevel.Info] = ConsoleColor.White,
                        [ConsoleLogLevel.Warn] = ConsoleColor.Yellow,
                        [ConsoleLogLevel.Error] = ConsoleColor.Red,
                        [ConsoleLogLevel.Alert] = ConsoleColor.Magenta,
                        [ConsoleLogLevel.Success] = ConsoleColor.DarkGreen
                    },
                    [MonitorColorScheme.LightBackground] = new Dictionary<ConsoleLogLevel, ConsoleColor>
                    {
                        [ConsoleLogLevel.Trace] = ConsoleColor.DarkGray,
                        [ConsoleLogLevel.Debug] = ConsoleColor.DarkGray,
                        [ConsoleLogLevel.Info] = ConsoleColor.Black,
                        [ConsoleLogLevel.Warn] = ConsoleColor.DarkYellow,
                        [ConsoleLogLevel.Error] = ConsoleColor.Red,
                        [ConsoleLogLevel.Alert] = ConsoleColor.DarkMagenta,
                        [ConsoleLogLevel.Success] = ConsoleColor.DarkGreen
                    }
                }
            };
        }


        /*********
        ** Private methods
        *********/
        /// <summary>Test whether the current console supports color formatting.</summary>
        private bool TestColorSupport()
        {
            try
            {
                Console.ForegroundColor = Console.ForegroundColor;
                return true;
            }
            catch (Exception)
            {
                return false; // Mono bug
            }
        }

        /// <summary>Get the color scheme to use for the current console.</summary>
        /// <param name="platform">The target platform.</param>
        /// <param name="colorConfig">The colors to use for text written to the SMAPI console.</param>
        private IDictionary<ConsoleLogLevel, ConsoleColor> GetConsoleColorScheme(Platform platform, ColorSchemeConfig colorConfig)
        {
            // get color scheme ID
            MonitorColorScheme schemeID = colorConfig.UseScheme;
            if (schemeID == MonitorColorScheme.AutoDetect)
            {
                schemeID = platform == Platform.Mac
                    ? MonitorColorScheme.LightBackground // macOS doesn't provide console background color info, but it's usually white.
                    : ColorfulConsoleWriter.IsDark(Console.BackgroundColor) ? MonitorColorScheme.DarkBackground : MonitorColorScheme.LightBackground;
            }

            // get colors for scheme
            return colorConfig.Schemes.TryGetValue(schemeID, out IDictionary<ConsoleLogLevel, ConsoleColor> scheme)
                ? scheme
                : throw new NotSupportedException($"Unknown color scheme '{schemeID}'.");
        }

        /// <summary>Get whether a console color should be considered dark, which is subjectively defined as 'white looks better than black on this text'.</summary>
        /// <param name="color">The color to check.</param>
        private static bool IsDark(ConsoleColor color)
        {
            switch (color)
            {
                case ConsoleColor.Black:
                case ConsoleColor.Blue:
                case ConsoleColor.DarkBlue:
                case ConsoleColor.DarkMagenta: // PowerShell
                case ConsoleColor.DarkRed:
                case ConsoleColor.Red:
                    return true;

                default:
                    return false;
            }
        }
    }
}