12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280 |
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- namespace IngameDebugConsole
- {
- public enum DebugLogFilter
- {
- None = 0,
- Info = 1,
- Warning = 2,
- Error = 4,
- All = 7
- }
- public class DebugLogManager : MonoBehaviour
- {
- public static DebugLogManager Instance { get; private set; }
- #pragma warning disable 0649
- [Header( "Properties" )]
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, console window will persist between scenes (i.e. not be destroyed when scene changes)" )]
- private bool singleton = true;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "Minimum height of the console window" )]
- private float minimumHeight = 200f;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If disabled, no popup will be shown when the console window is hidden" )]
- private bool enablePopup = true;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, console will be initialized as a popup" )]
- private bool startInPopupMode = true;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, console window will initially be invisible" )]
- private bool startMinimized = false;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, pressing the Toggle Key will show/hide (i.e. toggle) the console window at runtime" )]
- private bool toggleWithKey = false;
- [SerializeField]
- [HideInInspector]
- private KeyCode toggleKey = KeyCode.BackQuote;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, the console window will have a searchbar" )]
- private bool enableSearchbar = true;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "Width of the canvas determines whether the searchbar will be located inside the menu bar or underneath the menu bar. This way, the menu bar doesn't get too crowded on narrow screens. This value determines the minimum width of the canvas for the searchbar to appear inside the menu bar" )]
- private float topSearchbarMinWidth = 360f;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, the command input field at the bottom of the console window will automatically be cleared after entering a command" )]
- private bool clearCommandAfterExecution = true;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "Console keeps track of the previously entered commands. This value determines the capacity of the command history (you can scroll through the history via up and down arrow keys while the command input field is focused)" )]
- private int commandHistorySize = 15;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, while typing a command, all of the matching commands' signatures will be displayed in a popup" )]
- private bool showCommandSuggestions = true;
- [SerializeField]
- [HideInInspector]
- [Tooltip( "If enabled, on Android platform, logcat entries of the application will also be logged to the console with the prefix \"LOGCAT: \". This may come in handy especially if you want to access the native logs of your Android plugins (like Admob)" )]
- private bool receiveLogcatLogsInAndroid = false;
- #pragma warning disable 0414
- [SerializeField]
- [HideInInspector]
- [Tooltip( "Native logs will be filtered using these arguments. If left blank, all native logs of the application will be logged to the console. But if you want to e.g. see Admob's logs only, you can enter \"-s Ads\" (without quotes) here" )]
- private string logcatArguments;
- #pragma warning restore 0414
- [SerializeField]
- [Tooltip( "If enabled, on Android and iOS devices with notch screens, the console window will be repositioned so that the cutout(s) don't obscure it" )]
- private bool avoidScreenCutout = true;
- [SerializeField]
- [Tooltip( "If a log is longer than this limit, it will be truncated. This helps avoid reaching Unity's 65000 vertex limit for UI canvases" )]
- private int maxLogLength = 10000;
- [SerializeField]
- [Tooltip( "If enabled, on standalone platforms, command input field will automatically be focused (start receiving keyboard input) after opening the console window" )]
- private bool autoFocusOnCommandInputField = true;
- [Header( "Visuals" )]
- [SerializeField]
- private DebugLogItem logItemPrefab;
- [SerializeField]
- private Text commandSuggestionPrefab;
-
- [SerializeField]
- private Sprite infoLog;
- [SerializeField]
- private Sprite warningLog;
- [SerializeField]
- private Sprite errorLog;
- private Dictionary<LogType, Sprite> logSpriteRepresentations;
- [SerializeField]
- private Color collapseButtonNormalColor;
- [SerializeField]
- private Color collapseButtonSelectedColor;
- [SerializeField]
- private Color filterButtonsNormalColor;
- [SerializeField]
- private Color filterButtonsSelectedColor;
- [SerializeField]
- private string commandSuggestionHighlightStart = "<color=orange>";
- [SerializeField]
- private string commandSuggestionHighlightEnd = "</color>";
- [Header( "Internal References" )]
- [SerializeField]
- private RectTransform logWindowTR;
- private RectTransform canvasTR;
- [SerializeField]
- private RectTransform logItemsContainer;
- [SerializeField]
- private RectTransform commandSuggestionsContainer;
- [SerializeField]
- private InputField commandInputField;
- [SerializeField]
- private Button hideButton;
- [SerializeField]
- private Button clearButton;
- [SerializeField]
- private Image collapseButton;
- [SerializeField]
- private Image filterInfoButton;
- [SerializeField]
- private Image filterWarningButton;
- [SerializeField]
- private Image filterErrorButton;
- [SerializeField]
- private Text infoEntryCountText;
- [SerializeField]
- private Text warningEntryCountText;
- [SerializeField]
- private Text errorEntryCountText;
- [SerializeField]
- private RectTransform searchbar;
- [SerializeField]
- private RectTransform searchbarSlotTop;
- [SerializeField]
- private RectTransform searchbarSlotBottom;
- [SerializeField]
- private GameObject snapToBottomButton;
-
- [SerializeField]
- private CanvasGroup logWindowCanvasGroup;
- [SerializeField]
- private DebugLogPopup popupManager;
- [SerializeField]
- private ScrollRect logItemsScrollRect;
- private RectTransform logItemsScrollRectTR;
- private Vector2 logItemsScrollRectOriginalSize;
-
- [SerializeField]
- private DebugLogRecycledListView recycledListView;
- #pragma warning restore 0649
- private bool isLogWindowVisible = true;
- public bool IsLogWindowVisible { get { return isLogWindowVisible; } }
- public bool PopupEnabled
- {
- get { return popupManager.gameObject.activeSelf; }
- set { popupManager.gameObject.SetActive( value ); }
- }
- private bool screenDimensionsChanged = true;
-
- private int infoEntryCount = 0, warningEntryCount = 0, errorEntryCount = 0;
-
- private bool isCollapseOn = false;
- private DebugLogFilter logFilter = DebugLogFilter.All;
-
- private string searchTerm;
- private bool isInSearchMode;
-
-
- private bool snapToBottom = true;
-
- private List<DebugLogEntry> collapsedLogEntries;
-
- private Dictionary<DebugLogEntry, int> collapsedLogEntriesMap;
-
-
- private DebugLogIndexList uncollapsedLogEntriesIndices;
-
- private DebugLogIndexList indicesOfListEntriesToShow;
-
- private DynamicCircularBuffer<QueuedDebugLogEntry> queuedLogEntries;
- private object logEntriesLock;
- private int pendingLogToAutoExpand;
-
- private List<Text> commandSuggestionInstances;
- private int visibleCommandSuggestionInstances = 0;
- private List<ConsoleMethodInfo> matchingCommandSuggestions;
- private List<int> commandCaretIndexIncrements;
- private StringBuilder commandSuggestionsStringBuilder;
- private string commandInputFieldPrevCommand;
- private string commandInputFieldPrevCommandName;
- private int commandInputFieldPrevParamCount = -1;
- private int commandInputFieldPrevCaretPos = -1;
- private int commandInputFieldPrevCaretArgumentIndex = -1;
-
- private List<DebugLogEntry> pooledLogEntries;
- private List<DebugLogItem> pooledLogItems;
-
- private CircularBuffer<string> commandHistory;
- private int commandHistoryIndex = -1;
-
- private PointerEventData nullPointerEventData;
- #if UNITY_EDITOR
- private bool isQuittingApplication;
- #endif
- #if !UNITY_EDITOR && UNITY_ANDROID
- private DebugLogLogcatListener logcatListener;
- #endif
- #region 显示FPS
-
- private float _fps;
- private Color _fpsColor = Color.white;
- private int _frameNumber;
- private float _lastShowFPSTime;
-
- #endregion
-
- private void Awake()
- {
-
- if( !Instance )
- {
- Instance = this;
-
- if( singleton )
- DontDestroyOnLoad( gameObject );
- }
- else if( Instance != this )
- {
- Destroy( gameObject );
- return;
- }
- pooledLogEntries = new List<DebugLogEntry>( 16 );
- pooledLogItems = new List<DebugLogItem>( 16 );
- commandSuggestionInstances = new List<Text>( 8 );
- matchingCommandSuggestions = new List<ConsoleMethodInfo>( 8 );
- commandCaretIndexIncrements = new List<int>( 8 );
- queuedLogEntries = new DynamicCircularBuffer<QueuedDebugLogEntry>( 16 );
- commandHistory = new CircularBuffer<string>( commandHistorySize );
- logEntriesLock = new object();
- commandSuggestionsStringBuilder = new StringBuilder( 128 );
- canvasTR = (RectTransform) transform;
- logItemsScrollRectTR = (RectTransform) logItemsScrollRect.transform;
- logItemsScrollRectOriginalSize = logItemsScrollRectTR.sizeDelta;
-
- logSpriteRepresentations = new Dictionary<LogType, Sprite>()
- {
- { LogType.Log, infoLog },
- { LogType.Warning, warningLog },
- { LogType.Error, errorLog },
- { LogType.Exception, errorLog },
- { LogType.Assert, errorLog }
- };
-
- filterInfoButton.color = filterButtonsSelectedColor;
- filterWarningButton.color = filterButtonsSelectedColor;
- filterErrorButton.color = filterButtonsSelectedColor;
- collapsedLogEntries = new List<DebugLogEntry>( 128 );
- collapsedLogEntriesMap = new Dictionary<DebugLogEntry, int>( 128 );
- uncollapsedLogEntriesIndices = new DebugLogIndexList();
- indicesOfListEntriesToShow = new DebugLogIndexList();
- recycledListView.Initialize( this, collapsedLogEntries, indicesOfListEntriesToShow, logItemPrefab.Transform.sizeDelta.y );
- recycledListView.UpdateItemsInTheList( true );
- if( minimumHeight < 200f )
- minimumHeight = 200f;
- if( !enableSearchbar )
- {
- searchbar = null;
- searchbarSlotTop.gameObject.SetActive( false );
- searchbarSlotBottom.gameObject.SetActive( false );
- }
- if( commandSuggestionsContainer.gameObject.activeSelf )
- commandSuggestionsContainer.gameObject.SetActive( false );
-
- commandInputField.onValidateInput += OnValidateCommand;
- commandInputField.onValueChanged.AddListener( RefreshCommandSuggestions );
- commandInputField.onEndEdit.AddListener( OnEndEditCommand );
- searchbar.GetComponent<InputField>().onValueChanged.AddListener( SearchTermChanged );
- hideButton.onClick.AddListener( HideLogWindow );
- clearButton.onClick.AddListener( ClearLogs );
- collapseButton.GetComponent<Button>().onClick.AddListener( CollapseButtonPressed );
- filterInfoButton.GetComponent<Button>().onClick.AddListener( FilterLogButtonPressed );
- filterWarningButton.GetComponent<Button>().onClick.AddListener( FilterWarningButtonPressed );
- filterErrorButton.GetComponent<Button>().onClick.AddListener( FilterErrorButtonPressed );
- snapToBottomButton.GetComponent<Button>().onClick.AddListener( () => SetSnapToBottom( true ) );
- nullPointerEventData = new PointerEventData( null );
- }
- private void OnEnable()
- {
- if( Instance != this )
- return;
-
- Application.logMessageReceivedThreaded -= ReceivedLog;
- Application.logMessageReceivedThreaded += ReceivedLog;
- if( receiveLogcatLogsInAndroid )
- {
- #if !UNITY_EDITOR && UNITY_ANDROID
- if( logcatListener == null )
- logcatListener = new DebugLogLogcatListener();
- logcatListener.Start( logcatArguments );
- #endif
- }
- DebugLogConsole.AddCommand( "save_logs", "Saves logs to a file", SaveLogsToFile );
-
-
-
-
-
- }
- private void OnDisable()
- {
- if( Instance != this )
- return;
-
- Application.logMessageReceivedThreaded -= ReceivedLog;
- #if !UNITY_EDITOR && UNITY_ANDROID
- if( logcatListener != null )
- logcatListener.Stop();
- #endif
- DebugLogConsole.RemoveCommand( "save_logs" );
- }
- private void Start()
- {
- if( ( enablePopup && startInPopupMode ) || ( !enablePopup && startMinimized ) )
- HideLogWindow();
- else
- ShowLogWindow();
- PopupEnabled = enablePopup;
- }
- #if UNITY_EDITOR
- private void OnApplicationQuit()
- {
- isQuittingApplication = true;
- }
- #endif
-
- private void OnRectTransformDimensionsChange()
- {
- screenDimensionsChanged = true;
- }
- private void Update()
- {
-
-
-
-
- if( toggleWithKey )
- {
- if( Input.GetKeyDown( toggleKey ) )
- {
- if( isLogWindowVisible )
- HideLogWindow();
- else
- ShowLogWindow();
- }
- }
-
- this._frameNumber += 1;
- float time = Time.realtimeSinceStartup - this._lastShowFPSTime;
- if (!(time >= 1)) return;
- this._fps = (this._frameNumber / time);
- this._frameNumber = 0;
- this._lastShowFPSTime = Time.realtimeSinceStartup;
- this.popupManager.NewFPSCountArrived(this._fps);
- }
- private void LateUpdate()
- {
- #if UNITY_EDITOR
- if( isQuittingApplication )
- return;
- #endif
- int queuedLogCount = queuedLogEntries.Count;
- if( queuedLogCount > 0 )
- {
- for( int i = 0; i < queuedLogCount; i++ )
- {
- QueuedDebugLogEntry logEntry;
- lock( logEntriesLock )
- {
- logEntry = queuedLogEntries.RemoveFirst();
- }
- ProcessLog( logEntry );
- }
- }
- if( showCommandSuggestions && commandInputField.isFocused && commandInputField.caretPosition != commandInputFieldPrevCaretPos )
- RefreshCommandSuggestions( commandInputField.text );
- if( screenDimensionsChanged )
- {
-
- if( isLogWindowVisible )
- recycledListView.OnViewportDimensionsChanged();
- else
- popupManager.OnViewportDimensionsChanged();
- #if UNITY_ANDROID || UNITY_IOS
- CheckScreenCutout();
- #endif
- if( searchbar )
- {
- float logWindowWidth = logWindowTR.rect.width;
- if( logWindowWidth >= topSearchbarMinWidth )
- {
- if( searchbar.parent == searchbarSlotBottom )
- {
- searchbarSlotTop.gameObject.SetActive( true );
- searchbar.SetParent( searchbarSlotTop, false );
- searchbarSlotBottom.gameObject.SetActive( false );
- logItemsScrollRectTR.anchoredPosition = Vector2.zero;
- logItemsScrollRectTR.sizeDelta = logItemsScrollRectOriginalSize;
- }
- }
- else
- {
- if( searchbar.parent == searchbarSlotTop )
- {
- searchbarSlotBottom.gameObject.SetActive( true );
- searchbar.SetParent( searchbarSlotBottom, false );
- searchbarSlotTop.gameObject.SetActive( false );
- float searchbarHeight = searchbarSlotBottom.sizeDelta.y;
- logItemsScrollRectTR.anchoredPosition = new Vector2( 0f, searchbarHeight * -0.5f );
- logItemsScrollRectTR.sizeDelta = logItemsScrollRectOriginalSize - new Vector2( 0f, searchbarHeight );
- }
- }
- }
- screenDimensionsChanged = false;
- }
-
- if( snapToBottom )
- {
- logItemsScrollRect.verticalNormalizedPosition = 0f;
- if( snapToBottomButton.activeSelf )
- snapToBottomButton.SetActive( false );
- }
- else
- {
- float scrollPos = logItemsScrollRect.verticalNormalizedPosition;
- if( snapToBottomButton.activeSelf != ( scrollPos > 1E-6f && scrollPos < 0.9999f ) )
- snapToBottomButton.SetActive( !snapToBottomButton.activeSelf );
- }
- if( isLogWindowVisible && commandInputField.isFocused )
- {
- if( Input.GetKeyDown( KeyCode.UpArrow ) )
- {
- if( commandHistoryIndex == -1 )
- commandHistoryIndex = commandHistory.Count - 1;
- else if( --commandHistoryIndex < 0 )
- commandHistoryIndex = 0;
- if( commandHistoryIndex >= 0 && commandHistoryIndex < commandHistory.Count )
- {
- commandInputField.text = commandHistory[commandHistoryIndex];
- commandInputField.caretPosition = commandInputField.text.Length;
- }
- }
- else if( Input.GetKeyDown( KeyCode.DownArrow ) )
- {
- if( commandHistoryIndex == -1 )
- commandHistoryIndex = commandHistory.Count - 1;
- else if( ++commandHistoryIndex >= commandHistory.Count )
- commandHistoryIndex = commandHistory.Count - 1;
- if( commandHistoryIndex >= 0 && commandHistoryIndex < commandHistory.Count )
- commandInputField.text = commandHistory[commandHistoryIndex];
- }
- }
- #if !UNITY_EDITOR && UNITY_ANDROID
- if( logcatListener != null )
- {
- string log;
- while( ( log = logcatListener.GetLog() ) != null )
- ReceivedLog( "LOGCAT: " + log, string.Empty, LogType.Log );
- }
- #endif
- }
- public void ShowLogWindow()
- {
-
- logWindowCanvasGroup.interactable = true;
- logWindowCanvasGroup.blocksRaycasts = true;
- logWindowCanvasGroup.alpha = 1f;
- popupManager.Hide();
-
-
- recycledListView.OnLogEntriesUpdated( true );
- #if UNITY_EDITOR || UNITY_STANDALONE
-
- if( autoFocusOnCommandInputField )
- StartCoroutine( ActivateCommandInputFieldCoroutine() );
- #endif
- isLogWindowVisible = true;
- }
- public void HideLogWindow()
- {
-
- logWindowCanvasGroup.interactable = false;
- logWindowCanvasGroup.blocksRaycasts = false;
- logWindowCanvasGroup.alpha = 0f;
- if( commandInputField.isFocused )
- commandInputField.DeactivateInputField();
- popupManager.Show();
- commandHistoryIndex = -1;
- isLogWindowVisible = false;
- }
-
- private char OnValidateCommand( string text, int charIndex, char addedChar )
- {
- if( addedChar == '\t' )
- {
- if( !string.IsNullOrEmpty( text ) )
- {
- string autoCompletedCommand = DebugLogConsole.GetAutoCompleteCommand( text );
- if( !string.IsNullOrEmpty( autoCompletedCommand ) )
- commandInputField.text = autoCompletedCommand;
- }
- return '\0';
- }
- else if( addedChar == '\n' )
- {
-
- if( clearCommandAfterExecution )
- commandInputField.text = "";
- if( text.Length > 0 )
- {
- if( commandHistory.Count == 0 || commandHistory[commandHistory.Count - 1] != text )
- commandHistory.Add( text );
- commandHistoryIndex = -1;
-
- DebugLogConsole.ExecuteCommand( text );
-
- SetSnapToBottom( true );
- }
- return '\0';
- }
- return addedChar;
- }
-
- private void ReceivedLog( string logString, string stackTrace, LogType logType )
- {
- #if UNITY_EDITOR
- if( isQuittingApplication )
- return;
- #endif
-
- int logLength = logString.Length;
- if( stackTrace == null )
- {
- if( logLength > maxLogLength )
- logString = logString.Substring( 0, maxLogLength - 11 ) + "<truncated>";
- }
- else
- {
- logLength += stackTrace.Length;
- if( logLength > maxLogLength )
- {
-
- int halfMaxLogLength = maxLogLength / 2;
- if( logString.Length >= halfMaxLogLength )
- {
- if( stackTrace.Length >= halfMaxLogLength )
- {
-
- logString = logString.Substring( 0, halfMaxLogLength - 11 ) + "<truncated>";
-
- stackTrace = stackTrace.Substring( 0, halfMaxLogLength - 12 ) + "<truncated>\n";
- }
- else
- {
-
- logString = logString.Substring( 0, maxLogLength - stackTrace.Length - 11 ) + "<truncated>";
- }
- }
- else
- {
-
- stackTrace = stackTrace.Substring( 0, maxLogLength - logString.Length - 12 ) + "<truncated>\n";
- }
- }
- }
- QueuedDebugLogEntry queuedLogEntry = new QueuedDebugLogEntry( logString, stackTrace, logType );
- lock( logEntriesLock )
- {
- queuedLogEntries.Add( queuedLogEntry );
- }
- }
-
- private void ProcessLog( QueuedDebugLogEntry queuedLogEntry )
- {
- LogType logType = queuedLogEntry.logType;
- DebugLogEntry logEntry;
- if( pooledLogEntries.Count > 0 )
- {
- logEntry = pooledLogEntries[pooledLogEntries.Count - 1];
- pooledLogEntries.RemoveAt( pooledLogEntries.Count - 1 );
- }
- else
- logEntry = new DebugLogEntry();
- logEntry.Initialize( queuedLogEntry.logString, queuedLogEntry.stackTrace );
-
- int logEntryIndex;
- bool isEntryInCollapsedEntryList = collapsedLogEntriesMap.TryGetValue( logEntry, out logEntryIndex );
- if( !isEntryInCollapsedEntryList )
- {
-
-
- logEntry.logTypeSpriteRepresentation = logSpriteRepresentations[logType];
- logEntryIndex = collapsedLogEntries.Count;
- collapsedLogEntries.Add( logEntry );
- collapsedLogEntriesMap[logEntry] = logEntryIndex;
- }
- else
- {
-
-
- pooledLogEntries.Add( logEntry );
- logEntry = collapsedLogEntries[logEntryIndex];
- logEntry.count++;
- }
-
-
- uncollapsedLogEntriesIndices.Add( logEntryIndex );
-
-
- int logEntryIndexInEntriesToShow = -1;
- Sprite logTypeSpriteRepresentation = logEntry.logTypeSpriteRepresentation;
- if( isCollapseOn && isEntryInCollapsedEntryList )
- {
- if( isLogWindowVisible )
- {
- if( !isInSearchMode && logFilter == DebugLogFilter.All )
- logEntryIndexInEntriesToShow = logEntryIndex;
- else
- logEntryIndexInEntriesToShow = indicesOfListEntriesToShow.IndexOf( logEntryIndex );
- recycledListView.OnCollapsedLogEntryAtIndexUpdated( logEntryIndexInEntriesToShow );
- }
- }
- else if( ( !isInSearchMode || queuedLogEntry.MatchesSearchTerm( searchTerm ) ) && ( logFilter == DebugLogFilter.All ||
- ( logTypeSpriteRepresentation == infoLog && ( ( logFilter & DebugLogFilter.Info ) == DebugLogFilter.Info ) ) ||
- ( logTypeSpriteRepresentation == warningLog && ( ( logFilter & DebugLogFilter.Warning ) == DebugLogFilter.Warning ) ) ||
- ( logTypeSpriteRepresentation == errorLog && ( ( logFilter & DebugLogFilter.Error ) == DebugLogFilter.Error ) ) ) )
- {
- indicesOfListEntriesToShow.Add( logEntryIndex );
- logEntryIndexInEntriesToShow = indicesOfListEntriesToShow.Count - 1;
- if( isLogWindowVisible )
- recycledListView.OnLogEntriesUpdated( false );
- }
- if( logType == LogType.Log )
- {
- infoEntryCount++;
- infoEntryCountText.text = infoEntryCount.ToString();
-
- if( !isLogWindowVisible )
- popupManager.NewInfoLogArrived();
- }
- else if( logType == LogType.Warning )
- {
- warningEntryCount++;
- warningEntryCountText.text = warningEntryCount.ToString();
-
- if( !isLogWindowVisible )
- popupManager.NewWarningLogArrived();
- }
- else
- {
- errorEntryCount++;
- errorEntryCountText.text = errorEntryCount.ToString();
-
- if( !isLogWindowVisible )
- popupManager.NewErrorLogArrived();
- }
-
- if( pendingLogToAutoExpand > 0 && --pendingLogToAutoExpand <= 0 && isLogWindowVisible && logEntryIndexInEntriesToShow >= 0 )
- recycledListView.SelectAndFocusOnLogItemAtIndex( logEntryIndexInEntriesToShow );
- }
-
- public void SetSnapToBottom( bool snapToBottom )
- {
- this.snapToBottom = snapToBottom;
- }
-
- internal void ValidateScrollPosition()
- {
- logItemsScrollRect.OnScroll( nullPointerEventData );
- }
-
- internal void ExpandLatestPendingLog()
- {
- pendingLogToAutoExpand = queuedLogEntries.Count;
- }
-
- public void ClearLogs()
- {
- snapToBottom = true;
- infoEntryCount = 0;
- warningEntryCount = 0;
- errorEntryCount = 0;
- infoEntryCountText.text = "0";
- warningEntryCountText.text = "0";
- errorEntryCountText.text = "0";
- collapsedLogEntries.Clear();
- collapsedLogEntriesMap.Clear();
- uncollapsedLogEntriesIndices.Clear();
- indicesOfListEntriesToShow.Clear();
- recycledListView.DeselectSelectedLogItem();
- recycledListView.OnLogEntriesUpdated( true );
- }
-
- private void CollapseButtonPressed()
- {
-
- isCollapseOn = !isCollapseOn;
- snapToBottom = true;
- collapseButton.color = isCollapseOn ? collapseButtonSelectedColor : collapseButtonNormalColor;
- recycledListView.SetCollapseMode( isCollapseOn );
-
- FilterLogs();
- }
-
- private void FilterLogButtonPressed()
- {
- logFilter = logFilter ^ DebugLogFilter.Info;
- if( ( logFilter & DebugLogFilter.Info ) == DebugLogFilter.Info )
- filterInfoButton.color = filterButtonsSelectedColor;
- else
- filterInfoButton.color = filterButtonsNormalColor;
- FilterLogs();
- }
-
- private void FilterWarningButtonPressed()
- {
- logFilter = logFilter ^ DebugLogFilter.Warning;
- if( ( logFilter & DebugLogFilter.Warning ) == DebugLogFilter.Warning )
- filterWarningButton.color = filterButtonsSelectedColor;
- else
- filterWarningButton.color = filterButtonsNormalColor;
- FilterLogs();
- }
-
- private void FilterErrorButtonPressed()
- {
- logFilter = logFilter ^ DebugLogFilter.Error;
- if( ( logFilter & DebugLogFilter.Error ) == DebugLogFilter.Error )
- filterErrorButton.color = filterButtonsSelectedColor;
- else
- filterErrorButton.color = filterButtonsNormalColor;
- FilterLogs();
- }
-
- private void SearchTermChanged( string searchTerm )
- {
- if( searchTerm != null )
- searchTerm = searchTerm.Trim();
- this.searchTerm = searchTerm;
- bool isInSearchMode = !string.IsNullOrEmpty( searchTerm );
- if( isInSearchMode || this.isInSearchMode )
- {
- this.isInSearchMode = isInSearchMode;
- FilterLogs();
- }
- }
-
- private void RefreshCommandSuggestions( string command )
- {
- if( !showCommandSuggestions )
- return;
- commandInputFieldPrevCaretPos = commandInputField.caretPosition;
-
- bool commandChanged = command != commandInputFieldPrevCommand;
- bool commandNameOrParametersChanged = false;
- if( commandChanged )
- {
- commandInputFieldPrevCommand = command;
- matchingCommandSuggestions.Clear();
- commandCaretIndexIncrements.Clear();
- string prevCommandName = commandInputFieldPrevCommandName;
- int numberOfParameters;
- DebugLogConsole.GetCommandSuggestions( command, matchingCommandSuggestions, commandCaretIndexIncrements, ref commandInputFieldPrevCommandName, out numberOfParameters );
- if( prevCommandName != commandInputFieldPrevCommandName || numberOfParameters != commandInputFieldPrevParamCount )
- {
- commandInputFieldPrevParamCount = numberOfParameters;
- commandNameOrParametersChanged = true;
- }
- }
- int caretArgumentIndex = 0;
- int caretPos = commandInputField.caretPosition;
- for( int i = 0; i < commandCaretIndexIncrements.Count && caretPos > commandCaretIndexIncrements[i]; i++ )
- caretArgumentIndex++;
- if( caretArgumentIndex != commandInputFieldPrevCaretArgumentIndex )
- commandInputFieldPrevCaretArgumentIndex = caretArgumentIndex;
- else if( !commandChanged || !commandNameOrParametersChanged )
- {
-
-
-
-
- return;
- }
- if( matchingCommandSuggestions.Count == 0 )
- OnEndEditCommand( command );
- else
- {
- if( !commandSuggestionsContainer.gameObject.activeSelf )
- commandSuggestionsContainer.gameObject.SetActive( true );
- int suggestionInstancesCount = commandSuggestionInstances.Count;
- int suggestionsCount = matchingCommandSuggestions.Count;
- for( int i = 0; i < suggestionsCount; i++ )
- {
- if( i >= visibleCommandSuggestionInstances )
- {
- if( i >= suggestionInstancesCount )
- commandSuggestionInstances.Add( (Text) Instantiate( commandSuggestionPrefab, commandSuggestionsContainer, false ) );
- else
- commandSuggestionInstances[i].gameObject.SetActive( true );
- visibleCommandSuggestionInstances++;
- }
- ConsoleMethodInfo suggestedCommand = matchingCommandSuggestions[i];
- commandSuggestionsStringBuilder.Length = 0;
- if( caretArgumentIndex > 0 )
- commandSuggestionsStringBuilder.Append( suggestedCommand.command );
- else
- commandSuggestionsStringBuilder.Append( commandSuggestionHighlightStart ).Append( matchingCommandSuggestions[i].command ).Append( commandSuggestionHighlightEnd );
- if( suggestedCommand.parameters.Length > 0 )
- {
- commandSuggestionsStringBuilder.Append( " " );
-
- int caretParameterIndex = caretArgumentIndex - 1;
- if( caretParameterIndex >= suggestedCommand.parameters.Length )
- caretParameterIndex = suggestedCommand.parameters.Length - 1;
- for( int j = 0; j < suggestedCommand.parameters.Length; j++ )
- {
- if( caretParameterIndex != j )
- commandSuggestionsStringBuilder.Append( suggestedCommand.parameters[j] );
- else
- commandSuggestionsStringBuilder.Append( commandSuggestionHighlightStart ).Append( suggestedCommand.parameters[j] ).Append( commandSuggestionHighlightEnd );
- }
- }
- commandSuggestionInstances[i].text = commandSuggestionsStringBuilder.ToString();
- }
- for( int i = visibleCommandSuggestionInstances - 1; i >= suggestionsCount; i-- )
- commandSuggestionInstances[i].gameObject.SetActive( false );
- visibleCommandSuggestionInstances = suggestionsCount;
- }
- }
-
- private void OnEndEditCommand( string command )
- {
- if( commandSuggestionsContainer.gameObject.activeSelf )
- commandSuggestionsContainer.gameObject.SetActive( false );
- }
-
-
-
- internal void Resize( PointerEventData eventData )
- {
-
- float newHeight = ( eventData.position.y - logWindowTR.position.y ) / -canvasTR.localScale.y + 36f;
- if( newHeight < minimumHeight )
- newHeight = minimumHeight;
- Vector2 anchorMin = logWindowTR.anchorMin;
- anchorMin.y = Mathf.Max( 0f, 1f - newHeight / canvasTR.sizeDelta.y );
- logWindowTR.anchorMin = anchorMin;
-
- recycledListView.OnViewportDimensionsChanged();
- }
-
- private void FilterLogs()
- {
- indicesOfListEntriesToShow.Clear();
- if( logFilter != DebugLogFilter.None )
- {
- if( logFilter == DebugLogFilter.All )
- {
- if( isCollapseOn )
- {
- if( !isInSearchMode )
- {
-
-
-
- for( int i = 0, count = collapsedLogEntries.Count; i < count; i++ )
- indicesOfListEntriesToShow.Add( i );
- }
- else
- {
- for( int i = 0, count = collapsedLogEntries.Count; i < count; i++ )
- {
- if( collapsedLogEntries[i].MatchesSearchTerm( searchTerm ) )
- indicesOfListEntriesToShow.Add( i );
- }
- }
- }
- else
- {
- if( !isInSearchMode )
- {
- for( int i = 0, count = uncollapsedLogEntriesIndices.Count; i < count; i++ )
- indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
- }
- else
- {
- for( int i = 0, count = uncollapsedLogEntriesIndices.Count; i < count; i++ )
- {
- if( collapsedLogEntries[uncollapsedLogEntriesIndices[i]].MatchesSearchTerm( searchTerm ) )
- indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
- }
- }
- }
- }
- else
- {
-
- bool isInfoEnabled = ( logFilter & DebugLogFilter.Info ) == DebugLogFilter.Info;
- bool isWarningEnabled = ( logFilter & DebugLogFilter.Warning ) == DebugLogFilter.Warning;
- bool isErrorEnabled = ( logFilter & DebugLogFilter.Error ) == DebugLogFilter.Error;
- if( isCollapseOn )
- {
- for( int i = 0, count = collapsedLogEntries.Count; i < count; i++ )
- {
- DebugLogEntry logEntry = collapsedLogEntries[i];
- if( isInSearchMode && !logEntry.MatchesSearchTerm( searchTerm ) )
- continue;
- if( logEntry.logTypeSpriteRepresentation == infoLog )
- {
- if( isInfoEnabled )
- indicesOfListEntriesToShow.Add( i );
- }
- else if( logEntry.logTypeSpriteRepresentation == warningLog )
- {
- if( isWarningEnabled )
- indicesOfListEntriesToShow.Add( i );
- }
- else if( isErrorEnabled )
- indicesOfListEntriesToShow.Add( i );
- }
- }
- else
- {
- for( int i = 0, count = uncollapsedLogEntriesIndices.Count; i < count; i++ )
- {
- DebugLogEntry logEntry = collapsedLogEntries[uncollapsedLogEntriesIndices[i]];
- if( isInSearchMode && !logEntry.MatchesSearchTerm( searchTerm ) )
- continue;
- if( logEntry.logTypeSpriteRepresentation == infoLog )
- {
- if( isInfoEnabled )
- indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
- }
- else if( logEntry.logTypeSpriteRepresentation == warningLog )
- {
- if( isWarningEnabled )
- indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
- }
- else if( isErrorEnabled )
- indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
- }
- }
- }
- }
-
- recycledListView.DeselectSelectedLogItem();
- recycledListView.OnLogEntriesUpdated( true );
- ValidateScrollPosition();
- }
- public string GetAllLogs()
- {
- int count = uncollapsedLogEntriesIndices.Count;
- int length = 0;
- int newLineLength = System.Environment.NewLine.Length;
- for( int i = 0; i < count; i++ )
- {
- DebugLogEntry entry = collapsedLogEntries[uncollapsedLogEntriesIndices[i]];
- length += entry.logString.Length + entry.stackTrace.Length + newLineLength * 3;
- }
- length += 100;
- StringBuilder sb = new StringBuilder( length );
- for( int i = 0; i < count; i++ )
- {
- DebugLogEntry entry = collapsedLogEntries[uncollapsedLogEntriesIndices[i]];
- sb.AppendLine( entry.logString ).AppendLine( entry.stackTrace ).AppendLine();
- }
- return sb.ToString();
- }
- private void SaveLogsToFile()
- {
- string path = Path.Combine( Application.persistentDataPath, System.DateTime.Now.ToString( "dd-MM-yyyy--HH-mm-ss" ) + ".txt" );
- File.WriteAllText( path, GetAllLogs() );
- Debug.Log( "Logs saved to: " + path );
- }
-
- private void CheckScreenCutout()
- {
- if( !avoidScreenCutout )
- return;
- #if UNITY_2017_2_OR_NEWER && !UNITY_EDITOR && ( UNITY_ANDROID || UNITY_IOS )
-
- int screenHeight = Screen.height;
- float safeYMax = Screen.safeArea.yMax;
- if( safeYMax < screenHeight - 1 )
- {
-
- float cutoutPercentage = ( screenHeight - safeYMax ) / Screen.height;
- float cutoutLocalSize = cutoutPercentage * canvasTR.rect.height;
- logWindowTR.anchoredPosition = new Vector2( 0f, -cutoutLocalSize );
- logWindowTR.sizeDelta = new Vector2( 0f, -cutoutLocalSize );
- }
- else
- {
- logWindowTR.anchoredPosition = Vector2.zero;
- logWindowTR.sizeDelta = Vector2.zero;
- }
- #endif
- }
- #if UNITY_EDITOR || UNITY_STANDALONE
- private IEnumerator ActivateCommandInputFieldCoroutine()
- {
-
- yield return null;
- commandInputField.ActivateInputField();
- yield return null;
- commandInputField.MoveTextEnd( false );
- }
- #endif
-
- internal void PoolLogItem( DebugLogItem logItem )
- {
- logItem.gameObject.SetActive( false );
- pooledLogItems.Add( logItem );
- }
-
- internal DebugLogItem PopLogItem()
- {
- DebugLogItem newLogItem;
-
-
- if( pooledLogItems.Count > 0 )
- {
- newLogItem = pooledLogItems[pooledLogItems.Count - 1];
- pooledLogItems.RemoveAt( pooledLogItems.Count - 1 );
- newLogItem.gameObject.SetActive( true );
- }
- else
- {
- newLogItem = (DebugLogItem) Instantiate( logItemPrefab, logItemsContainer, false );
- newLogItem.Initialize( recycledListView );
- }
- return newLogItem;
- }
- }
- }
|