using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; // Receives debug entries and custom events (e.g. Clear, Collapse, Filter by Type) // and notifies the recycled list view of changes to the list of debug entries // // - Vocabulary - // Debug/Log entry: a Debug.Log/LogError/LogWarning/LogException/LogAssertion request made by // the client and intercepted by this manager object // Debug/Log item: a visual (uGUI) representation of a debug entry // // There can be a lot of debug entries in the system but there will only be a handful of log items // to show their properties on screen (these log items are recycled as the list is scrolled) // An enum to represent filtered log types 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; #if UNITY_EDITOR || UNITY_STANDALONE [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; #endif [Header( "Visuals" )] [SerializeField] private DebugLogItem logItemPrefab; [SerializeField] private Text commandSuggestionPrefab; // Visuals for different log types [SerializeField] private Sprite infoLog; [SerializeField] private Sprite warningLog; [SerializeField] private Sprite errorLog; private Dictionary logSpriteRepresentations; [SerializeField] private Color collapseButtonNormalColor; [SerializeField] private Color collapseButtonSelectedColor; [SerializeField] private Color filterButtonsNormalColor; [SerializeField] private Color filterButtonsSelectedColor; [SerializeField] private string commandSuggestionHighlightStart = ""; [SerializeField] private string commandSuggestionHighlightEnd = ""; [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; // Canvas group to modify visibility of the log window [SerializeField] private CanvasGroup logWindowCanvasGroup; [SerializeField] private DebugLogPopup popupManager; [SerializeField] private ScrollRect logItemsScrollRect; private RectTransform logItemsScrollRectTR; private Vector2 logItemsScrollRectOriginalSize; // Recycled list view to handle the log items efficiently [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; // Number of entries filtered by their types private int infoEntryCount = 0, warningEntryCount = 0, errorEntryCount = 0; // Number of new entries received this frame private int newInfoEntryCount = 0, newWarningEntryCount = 0, newErrorEntryCount = 0; // Filters to apply to the list of debug entries to show private bool isCollapseOn = false; private DebugLogFilter logFilter = DebugLogFilter.All; // Search filter private string searchTerm; private bool isInSearchMode; // If the last log item is completely visible (scrollbar is at the bottom), // scrollbar will remain at the bottom when new debug entries are received private bool snapToBottom = true; // List of unique debug entries (duplicates of entries are not kept) private List collapsedLogEntries; // Dictionary to quickly find if a log already exists in collapsedLogEntries private Dictionary collapsedLogEntriesMap; // The order the collapsedLogEntries are received // (duplicate entries have the same index (value)) private DebugLogIndexList uncollapsedLogEntriesIndices; // Filtered list of debug entries to show private DebugLogIndexList indicesOfListEntriesToShow; // The log entry that must be focused this frame private int indexOfLogEntryToSelectAndFocus = -1; // Whether or not logs list view should be updated this frame private bool shouldUpdateRecycledListView = false; // Logs that should be registered in Update-loop private DynamicCircularBuffer queuedLogEntries; private object logEntriesLock; private int pendingLogToAutoExpand; // Command suggestions that match the currently entered command private List commandSuggestionInstances; private int visibleCommandSuggestionInstances = 0; private List matchingCommandSuggestions; private List commandCaretIndexIncrements; private StringBuilder commandSuggestionsStringBuilder; private string commandInputFieldPrevCommand; private string commandInputFieldPrevCommandName; private int commandInputFieldPrevParamCount = -1; private int commandInputFieldPrevCaretPos = -1; private int commandInputFieldPrevCaretArgumentIndex = -1; // Pools for memory efficiency private List pooledLogEntries; private List pooledLogItems; // History of the previously entered commands private CircularBuffer commandHistory; private int commandHistoryIndex = -1; private string unfinishedCommand; // Required in ValidateScrollPosition() function private PointerEventData nullPointerEventData; // Callbacks for log window show/hide events public System.Action OnLogWindowShown, OnLogWindowHidden; #if UNITY_EDITOR private bool isQuittingApplication; #endif #if !UNITY_EDITOR && UNITY_ANDROID private DebugLogLogcatListener logcatListener; #endif private void Awake() { // Only one instance of debug console is allowed if( !Instance ) { Instance = this; // If it is a singleton object, don't destroy it between scene changes if( singleton ) DontDestroyOnLoad( gameObject ); } else if( Instance != this ) { Destroy( gameObject ); return; } pooledLogEntries = new List( 16 ); pooledLogItems = new List( 16 ); commandSuggestionInstances = new List( 8 ); matchingCommandSuggestions = new List( 8 ); commandCaretIndexIncrements = new List( 8 ); queuedLogEntries = new DynamicCircularBuffer( 16 ); commandHistory = new CircularBuffer( commandHistorySize ); logEntriesLock = new object(); commandSuggestionsStringBuilder = new StringBuilder( 128 ); canvasTR = (RectTransform) transform; logItemsScrollRectTR = (RectTransform) logItemsScrollRect.transform; logItemsScrollRectOriginalSize = logItemsScrollRectTR.sizeDelta; // Associate sprites with log types logSpriteRepresentations = new Dictionary() { { LogType.Log, infoLog }, { LogType.Warning, warningLog }, { LogType.Error, errorLog }, { LogType.Exception, errorLog }, { LogType.Assert, errorLog } }; // Initially, all log types are visible filterInfoButton.color = filterButtonsSelectedColor; filterWarningButton.color = filterButtonsSelectedColor; filterErrorButton.color = filterButtonsSelectedColor; collapsedLogEntries = new List( 128 ); collapsedLogEntriesMap = new Dictionary( 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.GetComponent().onValueChanged.AddListener( SearchTermChanged ); else { searchbar = null; searchbarSlotTop.gameObject.SetActive( false ); searchbarSlotBottom.gameObject.SetActive( false ); } if( commandSuggestionsContainer.gameObject.activeSelf ) commandSuggestionsContainer.gameObject.SetActive( false ); // Register to UI events commandInputField.onValidateInput += OnValidateCommand; commandInputField.onValueChanged.AddListener( RefreshCommandSuggestions ); commandInputField.onEndEdit.AddListener( OnEndEditCommand ); hideButton.onClick.AddListener( HideLogWindow ); clearButton.onClick.AddListener( ClearLogs ); collapseButton.GetComponent