SanAndreasUnity/Assets/Scripts/UI/Console.cs

404 lines
9.1 KiB
C#
Raw Normal View History

2020-05-31 17:07:22 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace SanAndreasUnity.UI
{
public class Console : PauseMenuWindow
{
#region Inspector Settings
/// <summary>
/// Whether to only keep a certain number of logs, useful if memory usage is a concern.
/// </summary>
public bool restrictLogCount = true;
/// <summary>
/// Number of logs to keep before removing old ones.
/// </summary>
public int maxLogCount = 1000;
#endregion
2019-07-11 18:14:29 +00:00
static readonly GUIContent s_clearLabel = new GUIContent("Clear", "Clear the contents of the console.");
static readonly GUIContent s_collapseLabel = new GUIContent("Collapse", "Hide repeated messages.");
2020-05-31 17:07:22 +00:00
private static readonly LogType[] s_allLogTypes = new LogType[] {
LogType.Log, LogType.Warning, LogType.Error, LogType.Exception, LogType.Assert
};
2019-07-11 18:14:29 +00:00
static readonly Dictionary<LogType, Color> s_logTypeColors = new Dictionary<LogType, Color>
2020-05-31 17:07:22 +00:00
{
{ LogType.Assert, Color.red },
{ LogType.Error, Color.red },
{ LogType.Exception, Color.red },
{ LogType.Log, Color.white },
{ LogType.Warning, Color.yellow },
};
2019-07-11 18:14:29 +00:00
bool m_isCollapsed;
public bool IsCollapsed { get { return this.m_isCollapsed; } set { this.m_isCollapsed = value; } }
bool ShowDetails { get; set; }
Vector2 m_detailsAreaScrollViewPos = Vector2.zero;
int m_selectedLogIndex = -1;
2019-07-11 18:12:09 +00:00
readonly List<Log> m_logs = new List<Log>();
2019-07-11 18:14:29 +00:00
readonly Utilities.ConcurrentQueue<Log> m_queuedLogs = new Utilities.ConcurrentQueue<Log>();
2020-05-31 17:07:22 +00:00
2019-07-11 18:14:29 +00:00
readonly Dictionary<LogType, bool> m_logTypeFilters = new Dictionary<LogType, bool>
2020-05-31 17:07:22 +00:00
{
{ LogType.Assert, true },
{ LogType.Error, true },
{ LogType.Exception, true },
{ LogType.Log, true },
{ LogType.Warning, true },
};
private Dictionary<LogType, int> m_numMessagesPerType = new Dictionary<LogType, int> ();
Console ()
{
this.windowName = "Console";
this.useScrollView = false;
}
#region MonoBehaviour Messages
void OnDisable()
{
Application.logMessageReceivedThreaded -= HandleLogThreaded;
}
void OnEnable()
{
Application.logMessageReceivedThreaded += HandleLogThreaded;
}
void Start ()
{
this.RegisterButtonInPauseMenu ();
// adjust rect
this.windowRect = Utilities.GUIUtils.GetCenteredRectPerc( new Vector2(0.9f, 0.8f) );
2020-05-31 17:07:22 +00:00
}
void Update()
{
UpdateQueuedLogs();
}
#endregion
static void RestoreContentColor ()
{
GUI.contentColor = Color.white;
}
void DrawCollapsedLog(Log log, int index)
2020-05-31 17:07:22 +00:00
{
bool isSelected = index == m_selectedLogIndex;
if (isSelected)
GUI.contentColor = Color.green;
2020-05-31 17:07:22 +00:00
GUILayout.BeginHorizontal();
if (GUILayout.Button(log.GetTruncatedMessage(), GUI.skin.label))
{
if(isSelected)
m_selectedLogIndex = -1;
else
m_selectedLogIndex = index;
}
2020-05-31 17:07:22 +00:00
GUILayout.FlexibleSpace();
GUILayout.Label(log.count.ToString(), GUI.skin.box);
GUILayout.EndHorizontal();
if (isSelected)
RestoreContentColor();
2020-05-31 17:07:22 +00:00
}
void DrawExpandedLog(Log log, int index)
2020-05-31 17:07:22 +00:00
{
bool isSelected = index == m_selectedLogIndex;
if (isSelected)
GUI.contentColor = Color.green;
2020-05-31 17:07:22 +00:00
for (var i = 0; i < log.count; i += 1)
{
if (GUILayout.Button(log.GetTruncatedMessage(), GUI.skin.label))
{
if(isSelected)
m_selectedLogIndex = -1;
else
m_selectedLogIndex = index;
}
2020-05-31 17:07:22 +00:00
}
if (isSelected)
RestoreContentColor();
2020-05-31 17:07:22 +00:00
}
void DrawLog(Log log, int index)
2020-05-31 17:07:22 +00:00
{
2019-07-11 18:14:29 +00:00
GUI.contentColor = s_logTypeColors[log.type];
2020-05-31 17:07:22 +00:00
2019-07-11 18:14:29 +00:00
if (m_isCollapsed)
2020-05-31 17:07:22 +00:00
{
DrawCollapsedLog(log, index);
2020-05-31 17:07:22 +00:00
}
else
{
DrawExpandedLog(log, index);
2020-05-31 17:07:22 +00:00
}
}
void DrawLogList()
{
scrollPos = GUILayout.BeginScrollView(scrollPos);
// Used to determine height of accumulated log labels.
GUILayout.BeginVertical();
foreach (LogType logType in s_allLogTypes)
m_numMessagesPerType [logType] = 0;
2019-07-11 18:12:09 +00:00
for (int i=0; i < m_logs.Count; i++)
2020-05-31 17:07:22 +00:00
{
2019-07-11 18:12:09 +00:00
Log log = m_logs[i];
2020-05-31 17:07:22 +00:00
if (IsLogVisible (log))
DrawLog (log, i);
2020-05-31 17:07:22 +00:00
2019-07-11 18:14:29 +00:00
m_numMessagesPerType [log.type] += (m_isCollapsed ? 1 : log.count);
2020-05-31 17:07:22 +00:00
}
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 DrawDetails()
{
float height = Mathf.Max( this.windowRect.height / 4, 100 );
m_detailsAreaScrollViewPos = GUILayout.BeginScrollView(m_detailsAreaScrollViewPos, GUILayout.Height(height));
2019-07-11 18:12:09 +00:00
if (m_selectedLogIndex >= 0 && m_selectedLogIndex < this.m_logs.Count)
{
2019-07-11 18:12:09 +00:00
Log log = this.m_logs[m_selectedLogIndex];
GUILayout.Label(log.message);
GUILayout.Space(5);
GUILayout.Label(log.stackTrace);
}
GUILayout.EndScrollView();
}
2020-05-31 17:07:22 +00:00
void DrawToolbar()
{
GUILayout.BeginHorizontal();
foreach (LogType logType in s_allLogTypes)
{
2019-07-11 18:14:29 +00:00
bool currentState = m_logTypeFilters[logType];
2020-05-31 17:07:22 +00:00
int count = m_numMessagesPerType [logType];
string label = logType.ToString() + ( (count > 0) ? (" [" + count + "]") : "" );
2019-07-11 18:14:29 +00:00
GUI.contentColor = s_logTypeColors [logType];
m_logTypeFilters[logType] = GUILayout.Toggle (currentState, label, GUILayout.ExpandWidth(false));
2020-05-31 17:07:22 +00:00
GUILayout.Space(15);
}
GUILayout.EndHorizontal();
RestoreContentColor ();
GUILayout.BeginHorizontal ();
2019-07-11 18:14:29 +00:00
if (GUILayout.Button (s_clearLabel, GUILayout.ExpandWidth(false)))
2020-05-31 17:07:22 +00:00
{
2019-07-11 18:12:09 +00:00
m_logs.Clear();
m_selectedLogIndex = -1;
2020-05-31 17:07:22 +00:00
}
GUILayout.Space (10);
2019-07-11 18:14:29 +00:00
m_isCollapsed = GUILayout.Toggle (m_isCollapsed, s_collapseLabel, GUILayout.ExpandWidth(false));
2020-05-31 17:07:22 +00:00
ShowDetails = GUILayout.Toggle (ShowDetails, "Show details", GUILayout.ExpandWidth(false));
2020-05-31 17:07:22 +00:00
GUILayout.EndHorizontal ();
}
void DrawWindow()
{
DrawLogList();
if (this.ShowDetails)
{
Utilities.GUIUtils.DrawHorizontalLine(2f, 3f, Color.black);
this.DrawDetails();
}
Utilities.GUIUtils.DrawHorizontalLine(2f, 3f, Color.black);
2020-05-31 17:07:22 +00:00
DrawToolbar();
}
protected override void OnWindowGUI ()
{
DrawWindow ();
}
Log? GetLastLog()
{
2019-07-11 18:12:09 +00:00
if (m_logs.Count == 0)
2020-05-31 17:07:22 +00:00
{
return null;
}
2019-07-11 18:46:39 +00:00
return m_logs[m_logs.Count - 1];
2020-05-31 17:07:22 +00:00
}
void UpdateQueuedLogs()
{
Log log;
2019-07-11 18:14:29 +00:00
while (m_queuedLogs.TryDequeue(out log))
2020-05-31 17:07:22 +00:00
{
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
2019-07-11 18:14:29 +00:00
m_queuedLogs.Enqueue(log);
2020-05-31 17:07:22 +00:00
}
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;
2019-07-11 18:12:09 +00:00
m_logs[m_logs.Count - 1] = log;
2020-05-31 17:07:22 +00:00
}
else
{
2019-07-11 18:12:09 +00:00
m_logs.Add(log);
2020-05-31 17:07:22 +00:00
TrimExcessLogs();
}
}
bool IsLogVisible(Log log)
{
2019-07-11 18:14:29 +00:00
return m_logTypeFilters[log.type];
2020-05-31 17:07:22 +00:00
}
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, scrollPos.y + outerScrollHeight);
}
void ScrollToBottom()
{
scrollPos = new Vector2(0, Int32.MaxValue);
}
void TrimExcessLogs()
{
2019-07-11 18:40:04 +00:00
if (!this.restrictLogCount)
2020-05-31 17:07:22 +00:00
{
return;
}
2019-07-11 18:40:04 +00:00
int amountToRemove = m_logs.Count - this.maxLogCount;
2020-05-31 17:07:22 +00:00
if (amountToRemove <= 0)
{
return;
}
2019-07-11 18:12:09 +00:00
m_logs.RemoveRange(0, amountToRemove);
2020-05-31 17:07:22 +00:00
}
}
/// <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);
}
}
}