forked from mminer/consolation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Console.cs
385 lines (316 loc) · 10.9 KB
/
Console.cs
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Consolation
{
/// <summary>
/// A console to display Unity's debug logs in-game.
/// </summary>
class Console : MonoBehaviour
{
public static Version version = new Version(1, 0, 0);
#region Inspector Settings
/// <summary>
/// The hotkey to show and hide the console window.
/// </summary>
public KeyCode toggleKey = KeyCode.BackQuote;
/// <summary>
/// Whether to open as soon as the game starts.
/// </summary>
public bool openOnStart = false;
/// <summary>
/// Whether to open the window by shaking the device (mobile-only).
/// </summary>
public bool shakeToOpen = true;
/// <summary>
/// The (squared) acceleration above which the window should open.
/// </summary>
public float shakeAcceleration = 3f;
/// <summary>
/// Whether to only keep a certain number of logs, useful if memory usage is a concern.
/// </summary>
public bool restrictLogCount = false;
/// <summary>
/// Number of logs to keep before removing old ones.
/// </summary>
public int maxLogCount = 1000;
#endregion
static readonly GUIContent clearLabel = new GUIContent("Clear", "Clear the contents of the console.");
static readonly GUIContent collapseLabel = new GUIContent("Collapse", "Hide repeated messages.");
const int margin = 20;
const string windowTitle = "Console";
static readonly Dictionary<LogType, Color> logTypeColors = new Dictionary<LogType, Color>
{
{ LogType.Assert, Color.white },
{ LogType.Error, Color.red },
{ LogType.Exception, Color.red },
{ LogType.Log, Color.white },
{ LogType.Warning, Color.yellow },
};
bool isCollapsed;
bool isVisible;
readonly List<Log> logs = new List<Log>();
readonly ConcurrentQueue<Log> queuedLogs = new ConcurrentQueue<Log>();
Vector2 scrollPosition;
readonly Rect titleBarRect = new Rect(0, 0, 10000, 20);
Rect windowRect = new Rect(margin, margin, Screen.width - (margin * 2), Screen.height - (margin * 2));
readonly Dictionary<LogType, bool> logTypeFilters = new Dictionary<LogType, bool>
{
{ LogType.Assert, true },
{ LogType.Error, true },
{ LogType.Exception, true },
{ LogType.Log, true },
{ LogType.Warning, true },
};
#region MonoBehaviour Messages
void OnDisable()
{
Application.logMessageReceivedThreaded -= HandleLogThreaded;
}
void OnEnable()
{
Application.logMessageReceivedThreaded += HandleLogThreaded;
}
void OnGUI()
{
if (!isVisible)
{
return;
}
windowRect = GUILayout.Window(123456, windowRect, DrawWindow, windowTitle);
}
void Start()
{
if (openOnStart)
{
isVisible = true;
}
}
void Update()
{
UpdateQueuedLogs();
if (Input.GetKeyDown(toggleKey))
{
isVisible = !isVisible;
}
if (shakeToOpen && Input.acceleration.sqrMagnitude > shakeAcceleration)
{
isVisible = true;
}
}
#endregion
void DrawCollapsedLog(Log log)
{
GUILayout.BeginHorizontal();
GUILayout.Label(log.GetTruncatedMessage());
GUILayout.FlexibleSpace();
GUILayout.Label(log.count.ToString(), GUI.skin.box);
GUILayout.EndHorizontal();
}
void DrawExpandedLog(Log log)
{
for (var i = 0; i < log.count; i += 1)
{
GUILayout.Label(log.GetTruncatedMessage());
}
}
void DrawLog(Log log)
{
GUI.contentColor = logTypeColors[log.type];
if (isCollapsed)
{
DrawCollapsedLog(log);
}
else
{
DrawExpandedLog(log);
}
}
void DrawLogList()
{
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
// Used to determine height of accumulated log labels.
GUILayout.BeginVertical();
var visibleLogs = logs.Where(IsLogVisible);
foreach (Log log in visibleLogs)
{
DrawLog(log);
}
GUILayout.EndVertical();
var innerScrollRect = GUILayoutUtility.GetLastRect();
GUILayout.EndScrollView();
var outerScrollRect = GUILayoutUtility.GetLastRect();
// If we're scrolled to bottom now, guarantee that it continues to be in next cycle.
if (Event.current.type == EventType.Repaint && IsScrolledToBottom(innerScrollRect, outerScrollRect))
{
ScrollToBottom();
}
// Ensure GUI colour is reset before drawing other components.
GUI.contentColor = Color.white;
}
void DrawToolbar()
{
GUILayout.BeginHorizontal();
if (GUILayout.Button(clearLabel))
{
logs.Clear();
}
foreach (LogType logType in Enum.GetValues(typeof(LogType)))
{
var currentState = logTypeFilters[logType];
var label = logType.ToString();
logTypeFilters[logType] = GUILayout.Toggle(currentState, label, GUILayout.ExpandWidth(false));
GUILayout.Space(20);
}
isCollapsed = GUILayout.Toggle(isCollapsed, collapseLabel, GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
}
void DrawWindow(int windowID)
{
DrawLogList();
DrawToolbar();
// Allow the window to be dragged by its title bar.
GUI.DragWindow(titleBarRect);
}
Log? GetLastLog()
{
if (logs.Count == 0)
{
return null;
}
return logs.Last();
}
void UpdateQueuedLogs()
{
Log log;
while (queuedLogs.TryDequeue(out log))
{
ProcessLogItem(log);
}
}
void HandleLogThreaded(string message, string stackTrace, LogType type)
{
var log = new Log
{
count = 1,
message = message,
stackTrace = stackTrace,
type = type,
};
// Queue the log into a ConcurrentQueue to be processed later in the Unity main thread,
// so that we don't get GUI-related errors for logs coming from other threads
queuedLogs.Enqueue(log);
}
void ProcessLogItem(Log log)
{
var lastLog = GetLastLog();
var isDuplicateOfLastLog = lastLog.HasValue && log.Equals(lastLog.Value);
if (isDuplicateOfLastLog)
{
// Replace previous log with incremented count instead of adding a new one.
log.count = lastLog.Value.count + 1;
logs[logs.Count - 1] = log;
}
else
{
logs.Add(log);
TrimExcessLogs();
}
}
bool IsLogVisible(Log log)
{
return logTypeFilters[log.type];
}
bool IsScrolledToBottom(Rect innerScrollRect, Rect outerScrollRect)
{
var innerScrollHeight = innerScrollRect.height;
// Take into account extra padding added to the scroll container.
var outerScrollHeight = outerScrollRect.height - GUI.skin.box.padding.vertical;
// If contents of scroll view haven't exceeded outer container, treat it as scrolled to bottom.
if (outerScrollHeight > innerScrollHeight)
{
return true;
}
// Scrolled to bottom (with error margin for float math)
return Mathf.Approximately(innerScrollHeight, scrollPosition.y + outerScrollHeight);
}
void ScrollToBottom()
{
scrollPosition = new Vector2(0, Int32.MaxValue);
}
void TrimExcessLogs()
{
if (!restrictLogCount)
{
return;
}
var amountToRemove = logs.Count - maxLogCount;
if (amountToRemove <= 0)
{
return;
}
logs.RemoveRange(0, amountToRemove);
}
}
/// <summary>
/// A basic container for log details.
/// </summary>
struct Log
{
public int count;
public string message;
public string stackTrace;
public LogType type;
/// <summary>
/// The max string length supported by UnityEngine.GUILayout.Label without triggering this error:
/// "String too long for TextMeshGenerator. Cutting off characters."
/// </summary>
private const int MaxMessageLength = 16382;
public bool Equals(Log log)
{
return message == log.message && stackTrace == log.stackTrace && type == log.type;
}
/// <summary>
/// Return a truncated message if it exceeds the max message length
/// </summary>
public string GetTruncatedMessage()
{
if (string.IsNullOrEmpty(message)) return message;
return message.Length <= MaxMessageLength ? message : message.Substring(0, MaxMessageLength);
}
}
/// <summary>
/// Alternative to System.Collections.Concurrent.ConcurrentQueue
/// (It's only available in .NET 4.0 and greater)
/// </summary>
/// <remarks>
/// It's a bit slow (as it uses locks), and only provides a small subset of the interface
/// Overall, the implementation is intended to be simple & robust
/// </remarks>
public class ConcurrentQueue<T>
{
private readonly System.Object queueLock = new System.Object();
private readonly Queue<T> queue = new Queue<T>();
public void Enqueue(T item)
{
lock (queueLock)
{
queue.Enqueue(item);
}
}
public bool TryDequeue(out T result)
{
lock (queueLock)
{
if (queue.Count == 0)
{
result = default(T);
return false;
}
result = queue.Dequeue();
return true;
}
}
}
}