forked from mminer/consolation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Console.cs
450 lines (374 loc) · 11.7 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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Consolation
{
/// <summary>
/// A console to display Unity's debug logs in-game.
///
/// Version: 1.1.2
/// </summary>
class Console : MonoBehaviour
{
#region Inspector Settings
/// <summary>
/// The hotkey to show and hide the console window.
/// </summary>
[Tooltip("The hotkey to show and hide the console window.")]
public KeyCode toggleKey = KeyCode.BackQuote; // Tilde
/// <summary>
/// Whether to open as soon as the game starts.
/// </summary>
[Tooltip("Whether to open as soon as the game starts.")]
public bool openOnStart = false;
/// <summary>
/// Whether to open the window by shaking the device (mobile-only).
/// </summary>
[Tooltip("Whether to open the window by shaking the device (mobile-only).")]
public bool shakeToOpen = true;
/// <summary>
/// Also require touches while shaking to avoid accidental shakes.
/// </summary>
[Tooltip("Also require touches while shaking to avoid accidental shakes.")]
public bool shakeRequiresTouch = true;
/// <summary>
/// The (squared) acceleration above which the window should open.
/// </summary>
[Tooltip("The (squared) acceleration above which the window should open.")]
public float shakeAcceleration = 3f;
/// <summary>
/// The number of seconds that have to pass between visibility toggles.
/// This threshold prevents closing again while shaking to open.
/// </summary>
[Tooltip("The number of seconds that have to pass between visibility toggles.\nThis threshold prevents closing again while shaking to open.")]
public float toggleThresholdSeconds = .5f;
float lastToggleTime;
/// <summary>
/// Whether to only keep a certain number of logs, useful if memory usage is a concern.
/// </summary>
[Tooltip("Whether to only keep a certain number of logs, useful if memory usage is a concern.")]
public bool restrictLogCount = false;
/// <summary>
/// Number of logs to keep before removing old ones.
/// </summary>
[Tooltip("Number of logs to keep before removing old ones.")]
public int maxLogCount = 1000;
/// <summary>
/// Font size to display log entries with.
/// </summary>
[Tooltip("Font size to display log entries with.")]
public int logFontSize = 12;
/// <summary>
/// Amount to scale UI by.
/// </summary>
[Tooltip("Amount to scale UI by.")]
public float scaleFactor = 2f;
/// <summary>
/// Space between the buttons.
/// </summary>
[Tooltip("Space between the buttons.")]
public float spacePixels = 10f;
/// <summary>
/// Remember Window position.
/// </summary>
[Tooltip("Remember Window position.")]
public bool rememberPos = true;
#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 float margin = 1f;
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);
float windowX = margin;
float windowY = margin;
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)
{
if (!rememberPos)
{
windowX = windowY = margin;
}
return;
}
GUI.matrix = Matrix4x4.Scale(Vector3.one * scaleFactor);
float width = (Screen.width / scaleFactor) - (margin * 2);
float height = (Screen.height / scaleFactor) - (margin * 2);
Rect windowRect = new Rect(windowX, windowY, width, height);
Rect newWindowRect = GUILayout.Window(123456, windowRect, DrawWindow, windowTitle);
windowX = newWindowRect.x;
windowY = newWindowRect.y;
}
void Start()
{
if (openOnStart)
{
isVisible = true;
}
}
void Update()
{
UpdateQueuedLogs();
float curTime = Time.realtimeSinceStartup;
if (Input.GetKeyDown(toggleKey))
{
isVisible = !isVisible;
}
if (shakeToOpen &&
Input.acceleration.sqrMagnitude > shakeAcceleration &&
curTime - lastToggleTime >= toggleThresholdSeconds &&
(!shakeRequiresTouch || Input.touchCount > 2))
{
isVisible = !isVisible;
lastToggleTime = curTime;
}
}
#endregion
void DrawLog(Log log, GUIStyle logStyle, GUIStyle badgeStyle)
{
GUI.contentColor = logTypeColors[log.type];
if (isCollapsed)
{
// Draw collapsed log with badge indicating count.
GUILayout.BeginHorizontal();
GUILayout.Label(log.GetTruncatedMessage(), logStyle);
GUILayout.FlexibleSpace();
GUILayout.Label(log.count.ToString(), GUI.skin.box);
GUILayout.EndHorizontal();
}
else
{
// Draw expanded log.
for (var i = 0; i < log.count; i += 1)
{
GUILayout.Label(log.GetTruncatedMessage(), logStyle);
}
}
GUI.contentColor = Color.white;
}
void DrawLogList()
{
GUIStyle badgeStyle = GUI.skin.box;
badgeStyle.fontSize = logFontSize;
GUIStyle logStyle = GUI.skin.label;
logStyle.fontSize = logFontSize;
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, logStyle, badgeStyle);
}
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();
}
}
void DrawToolbar()
{
GUILayout.BeginHorizontal();
if (GUILayout.Button(clearLabel))
{
// Reset Window position
windowX = margin;
windowY = margin;
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(spacePixels);
}
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>
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>
class ConcurrentQueue<T>
{
readonly Queue<T> queue = new Queue<T>();
readonly object queueLock = new object();
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;
}
}
}
}