DebugLogManager.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. using UnityEngine.EventSystems;
  8. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  9. using UnityEngine.InputSystem;
  10. #endif
  11. #if UNITY_EDITOR && UNITY_2021_1_OR_NEWER
  12. using Screen = UnityEngine.Device.Screen; // To support Device Simulator on Unity 2021.1+
  13. #endif
  14. // Receives debug entries and custom events (e.g. Clear, Collapse, Filter by Type)
  15. // and notifies the recycled list view of changes to the list of debug entries
  16. //
  17. // - Vocabulary -
  18. // Debug/Log entry: a Debug.Log/LogError/LogWarning/LogException/LogAssertion request made by
  19. // the client and intercepted by this manager object
  20. // Debug/Log item: a visual (uGUI) representation of a debug entry
  21. //
  22. // There can be a lot of debug entries in the system but there will only be a handful of log items
  23. // to show their properties on screen (these log items are recycled as the list is scrolled)
  24. // An enum to represent filtered log types
  25. namespace IngameDebugConsole
  26. {
  27. public enum DebugLogFilter
  28. {
  29. None = 0,
  30. Info = 1,
  31. Warning = 2,
  32. Error = 4,
  33. All = 7
  34. }
  35. public class DebugLogManager : MonoBehaviour
  36. {
  37. public static DebugLogManager Instance { get; private set; }
  38. #pragma warning disable 0649
  39. [Header( "Properties" )]
  40. [SerializeField]
  41. [HideInInspector]
  42. [Tooltip( "If enabled, console window will persist between scenes (i.e. not be destroyed when scene changes)" )]
  43. private bool singleton = true;
  44. [SerializeField]
  45. [HideInInspector]
  46. [Tooltip( "Minimum height of the console window" )]
  47. private float minimumHeight = 200f;
  48. [SerializeField]
  49. [HideInInspector]
  50. [Tooltip( "If enabled, console window can be resized horizontally, as well" )]
  51. private bool enableHorizontalResizing = false;
  52. [SerializeField]
  53. [HideInInspector]
  54. [Tooltip( "If enabled, console window's resize button will be located at bottom-right corner. Otherwise, it will be located at bottom-left corner" )]
  55. private bool resizeFromRight = true;
  56. [SerializeField]
  57. [HideInInspector]
  58. [Tooltip( "Minimum width of the console window" )]
  59. private float minimumWidth = 240f;
  60. [SerializeField]
  61. [HideInInspector]
  62. [Tooltip( "If disabled, no popup will be shown when the console window is hidden" )]
  63. private bool enablePopup = true;
  64. [SerializeField]
  65. [HideInInspector]
  66. [Tooltip( "If enabled, console will be initialized as a popup" )]
  67. private bool startInPopupMode = true;
  68. [SerializeField]
  69. [HideInInspector]
  70. [Tooltip( "If enabled, console window will initially be invisible" )]
  71. private bool startMinimized = false;
  72. [SerializeField]
  73. [HideInInspector]
  74. [Tooltip( "If enabled, pressing the Toggle Key will show/hide (i.e. toggle) the console window at runtime" )]
  75. private bool toggleWithKey = false;
  76. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  77. [SerializeField]
  78. [HideInInspector]
  79. public InputAction toggleBinding = new InputAction( "Toggle Binding", type: InputActionType.Button, binding: "<Keyboard>/backquote", expectedControlType: "Button" );
  80. #else
  81. [SerializeField]
  82. [HideInInspector]
  83. private KeyCode toggleKey = KeyCode.BackQuote;
  84. #endif
  85. [SerializeField]
  86. [HideInInspector]
  87. [Tooltip( "If enabled, the console window will have a searchbar" )]
  88. private bool enableSearchbar = true;
  89. [SerializeField]
  90. [HideInInspector]
  91. [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" )]
  92. private float topSearchbarMinWidth = 360f;
  93. [SerializeField]
  94. [HideInInspector]
  95. [Tooltip( "If enabled, the arrival times of logs will be recorded and displayed when a log is expanded" )]
  96. private bool captureLogTimestamps = false;
  97. [SerializeField]
  98. [HideInInspector]
  99. [Tooltip( "If enabled, timestamps will be displayed for logs even if they aren't expanded" )]
  100. internal bool alwaysDisplayTimestamps = false;
  101. [SerializeField]
  102. [HideInInspector]
  103. [Tooltip( "If enabled, the command input field at the bottom of the console window will automatically be cleared after entering a command" )]
  104. private bool clearCommandAfterExecution = true;
  105. [SerializeField]
  106. [HideInInspector]
  107. [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)" )]
  108. private int commandHistorySize = 15;
  109. [SerializeField]
  110. [HideInInspector]
  111. [Tooltip( "If enabled, while typing a command, all of the matching commands' signatures will be displayed in a popup" )]
  112. private bool showCommandSuggestions = true;
  113. [SerializeField]
  114. [HideInInspector]
  115. [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)" )]
  116. private bool receiveLogcatLogsInAndroid = false;
  117. #pragma warning disable 0414
  118. #if UNITY_2018_3_OR_NEWER // On older Unity versions, disabling CS0169 is problematic: "Cannot restore warning 'CS0169' because it was disabled globally"
  119. #pragma warning disable 0169
  120. #endif
  121. [SerializeField]
  122. [HideInInspector]
  123. [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" )]
  124. private string logcatArguments;
  125. #if UNITY_2018_3_OR_NEWER
  126. #pragma warning restore 0169
  127. #endif
  128. #pragma warning restore 0414
  129. [SerializeField]
  130. [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" )]
  131. private bool avoidScreenCutout = true;
  132. [SerializeField]
  133. [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" )]
  134. private int maxLogLength = 10000;
  135. #if UNITY_EDITOR || UNITY_STANDALONE
  136. [SerializeField]
  137. [Tooltip( "If enabled, on standalone platforms, command input field will automatically be focused (start receiving keyboard input) after opening the console window" )]
  138. private bool autoFocusOnCommandInputField = true;
  139. #endif
  140. [Header( "Visuals" )]
  141. [SerializeField]
  142. private DebugLogItem logItemPrefab;
  143. [SerializeField]
  144. private Text commandSuggestionPrefab;
  145. // Visuals for different log types
  146. [SerializeField]
  147. private Sprite infoLog;
  148. [SerializeField]
  149. private Sprite warningLog;
  150. [SerializeField]
  151. private Sprite errorLog;
  152. // Visuals for resize button
  153. [SerializeField]
  154. private Sprite resizeIconAllDirections;
  155. [SerializeField]
  156. private Sprite resizeIconVerticalOnly;
  157. private Dictionary<LogType, Sprite> logSpriteRepresentations;
  158. [SerializeField]
  159. private Color collapseButtonNormalColor;
  160. [SerializeField]
  161. private Color collapseButtonSelectedColor;
  162. [SerializeField]
  163. private Color filterButtonsNormalColor;
  164. [SerializeField]
  165. private Color filterButtonsSelectedColor;
  166. [SerializeField]
  167. private string commandSuggestionHighlightStart = "<color=orange>";
  168. [SerializeField]
  169. private string commandSuggestionHighlightEnd = "</color>";
  170. [Header( "Internal References" )]
  171. [SerializeField]
  172. private RectTransform logWindowTR;
  173. internal RectTransform canvasTR;
  174. [SerializeField]
  175. private RectTransform logItemsContainer;
  176. [SerializeField]
  177. private RectTransform commandSuggestionsContainer;
  178. [SerializeField]
  179. private InputField commandInputField;
  180. [SerializeField]
  181. private Button hideButton;
  182. [SerializeField]
  183. private Button clearButton;
  184. [SerializeField]
  185. private Image collapseButton;
  186. [SerializeField]
  187. private Image filterInfoButton;
  188. [SerializeField]
  189. private Image filterWarningButton;
  190. [SerializeField]
  191. private Image filterErrorButton;
  192. [SerializeField]
  193. private Text infoEntryCountText;
  194. [SerializeField]
  195. private Text warningEntryCountText;
  196. [SerializeField]
  197. private Text errorEntryCountText;
  198. [SerializeField]
  199. private RectTransform searchbar;
  200. [SerializeField]
  201. private RectTransform searchbarSlotTop;
  202. [SerializeField]
  203. private RectTransform searchbarSlotBottom;
  204. [SerializeField]
  205. private Image resizeButton;
  206. [SerializeField]
  207. private GameObject snapToBottomButton;
  208. // Canvas group to modify visibility of the log window
  209. [SerializeField]
  210. private CanvasGroup logWindowCanvasGroup;
  211. [SerializeField]
  212. private DebugLogPopup popupManager;
  213. [SerializeField]
  214. private ScrollRect logItemsScrollRect;
  215. private RectTransform logItemsScrollRectTR;
  216. private Vector2 logItemsScrollRectOriginalSize;
  217. // Recycled list view to handle the log items efficiently
  218. [SerializeField]
  219. private DebugLogRecycledListView recycledListView;
  220. #pragma warning restore 0649
  221. private bool isLogWindowVisible = true;
  222. public bool IsLogWindowVisible { get { return isLogWindowVisible; } }
  223. public bool PopupEnabled
  224. {
  225. get { return popupManager.gameObject.activeSelf; }
  226. set { popupManager.gameObject.SetActive( value ); }
  227. }
  228. private bool screenDimensionsChanged = true;
  229. private float logWindowPreviousWidth;
  230. // Number of entries filtered by their types
  231. private int infoEntryCount = 0, warningEntryCount = 0, errorEntryCount = 0;
  232. // Number of new entries received this frame
  233. private int newInfoEntryCount = 0, newWarningEntryCount = 0, newErrorEntryCount = 0;
  234. // Filters to apply to the list of debug entries to show
  235. private bool isCollapseOn = false;
  236. private DebugLogFilter logFilter = DebugLogFilter.All;
  237. // Search filter
  238. private string searchTerm;
  239. private bool isInSearchMode;
  240. // If the last log item is completely visible (scrollbar is at the bottom),
  241. // scrollbar will remain at the bottom when new debug entries are received
  242. private bool snapToBottom = true;
  243. // List of unique debug entries (duplicates of entries are not kept)
  244. private List<DebugLogEntry> collapsedLogEntries;
  245. private List<DebugLogEntryTimestamp> collapsedLogEntriesTimestamps;
  246. // Dictionary to quickly find if a log already exists in collapsedLogEntries
  247. private Dictionary<DebugLogEntry, int> collapsedLogEntriesMap;
  248. // The order the collapsedLogEntries are received
  249. // (duplicate entries have the same index (value))
  250. private DebugLogIndexList<int> uncollapsedLogEntriesIndices;
  251. private DebugLogIndexList<DebugLogEntryTimestamp> uncollapsedLogEntriesTimestamps;
  252. // Filtered list of debug entries to show
  253. private DebugLogIndexList<int> indicesOfListEntriesToShow;
  254. private DebugLogIndexList<DebugLogEntryTimestamp> timestampsOfListEntriesToShow;
  255. // The log entry that must be focused this frame
  256. private int indexOfLogEntryToSelectAndFocus = -1;
  257. // Whether or not logs list view should be updated this frame
  258. private bool shouldUpdateRecycledListView = false;
  259. // Logs that should be registered in Update-loop
  260. private DynamicCircularBuffer<QueuedDebugLogEntry> queuedLogEntries;
  261. private object logEntriesLock;
  262. private int pendingLogToAutoExpand;
  263. // Command suggestions that match the currently entered command
  264. private List<Text> commandSuggestionInstances;
  265. private int visibleCommandSuggestionInstances = 0;
  266. private List<ConsoleMethodInfo> matchingCommandSuggestions;
  267. private List<int> commandCaretIndexIncrements;
  268. private string commandInputFieldPrevCommand;
  269. private string commandInputFieldPrevCommandName;
  270. private int commandInputFieldPrevParamCount = -1;
  271. private int commandInputFieldPrevCaretPos = -1;
  272. private int commandInputFieldPrevCaretArgumentIndex = -1;
  273. // Pools for memory efficiency
  274. private List<DebugLogEntry> pooledLogEntries;
  275. private List<DebugLogItem> pooledLogItems;
  276. // History of the previously entered commands
  277. private CircularBuffer<string> commandHistory;
  278. private int commandHistoryIndex = -1;
  279. private string unfinishedCommand;
  280. // StringBuilder used by various functions
  281. internal StringBuilder sharedStringBuilder;
  282. // Offset of DateTime.Now from DateTime.UtcNow
  283. private System.TimeSpan localTimeUtcOffset;
  284. // Required in ValidateScrollPosition() function
  285. private PointerEventData nullPointerEventData;
  286. // Callbacks for log window show/hide events
  287. public System.Action OnLogWindowShown, OnLogWindowHidden;
  288. #if UNITY_EDITOR
  289. private bool isQuittingApplication;
  290. #endif
  291. #if !UNITY_EDITOR && UNITY_ANDROID
  292. private DebugLogLogcatListener logcatListener;
  293. #endif
  294. private void Awake()
  295. {
  296. // Only one instance of debug console is allowed
  297. if( !Instance )
  298. {
  299. Instance = this;
  300. // If it is a singleton object, don't destroy it between scene changes
  301. if( singleton )
  302. DontDestroyOnLoad( gameObject );
  303. }
  304. else if( Instance != this )
  305. {
  306. Destroy( gameObject );
  307. return;
  308. }
  309. pooledLogEntries = new List<DebugLogEntry>( 16 );
  310. pooledLogItems = new List<DebugLogItem>( 16 );
  311. commandSuggestionInstances = new List<Text>( 8 );
  312. matchingCommandSuggestions = new List<ConsoleMethodInfo>( 8 );
  313. commandCaretIndexIncrements = new List<int>( 8 );
  314. queuedLogEntries = new DynamicCircularBuffer<QueuedDebugLogEntry>( 16 );
  315. commandHistory = new CircularBuffer<string>( commandHistorySize );
  316. logEntriesLock = new object();
  317. sharedStringBuilder = new StringBuilder( 1024 );
  318. canvasTR = (RectTransform) transform;
  319. logItemsScrollRectTR = (RectTransform) logItemsScrollRect.transform;
  320. logItemsScrollRectOriginalSize = logItemsScrollRectTR.sizeDelta;
  321. // Associate sprites with log types
  322. logSpriteRepresentations = new Dictionary<LogType, Sprite>()
  323. {
  324. { LogType.Log, infoLog },
  325. { LogType.Warning, warningLog },
  326. { LogType.Error, errorLog },
  327. { LogType.Exception, errorLog },
  328. { LogType.Assert, errorLog }
  329. };
  330. // Initially, all log types are visible
  331. filterInfoButton.color = filterButtonsSelectedColor;
  332. filterWarningButton.color = filterButtonsSelectedColor;
  333. filterErrorButton.color = filterButtonsSelectedColor;
  334. resizeButton.sprite = enableHorizontalResizing ? resizeIconAllDirections : resizeIconVerticalOnly;
  335. collapsedLogEntries = new List<DebugLogEntry>( 128 );
  336. collapsedLogEntriesMap = new Dictionary<DebugLogEntry, int>( 128 );
  337. uncollapsedLogEntriesIndices = new DebugLogIndexList<int>();
  338. indicesOfListEntriesToShow = new DebugLogIndexList<int>();
  339. if( captureLogTimestamps )
  340. {
  341. collapsedLogEntriesTimestamps = new List<DebugLogEntryTimestamp>( 128 );
  342. uncollapsedLogEntriesTimestamps = new DebugLogIndexList<DebugLogEntryTimestamp>();
  343. timestampsOfListEntriesToShow = new DebugLogIndexList<DebugLogEntryTimestamp>();
  344. }
  345. recycledListView.Initialize( this, collapsedLogEntries, indicesOfListEntriesToShow, timestampsOfListEntriesToShow, logItemPrefab.Transform.sizeDelta.y );
  346. recycledListView.UpdateItemsInTheList( true );
  347. if( minimumWidth < 100f )
  348. minimumWidth = 100f;
  349. if( minimumHeight < 200f )
  350. minimumHeight = 200f;
  351. if( !resizeFromRight )
  352. {
  353. RectTransform resizeButtonTR = (RectTransform) resizeButton.GetComponentInParent<DebugLogResizeListener>().transform;
  354. resizeButtonTR.anchorMin = new Vector2( 0f, resizeButtonTR.anchorMin.y );
  355. resizeButtonTR.anchorMax = new Vector2( 0f, resizeButtonTR.anchorMax.y );
  356. resizeButtonTR.pivot = new Vector2( 0f, resizeButtonTR.pivot.y );
  357. ( (RectTransform) commandInputField.transform ).anchoredPosition += new Vector2( resizeButtonTR.sizeDelta.x, 0f );
  358. }
  359. if( enableSearchbar )
  360. searchbar.GetComponent<InputField>().onValueChanged.AddListener( SearchTermChanged );
  361. else
  362. {
  363. searchbar = null;
  364. searchbarSlotTop.gameObject.SetActive( false );
  365. searchbarSlotBottom.gameObject.SetActive( false );
  366. }
  367. if( commandSuggestionsContainer.gameObject.activeSelf )
  368. commandSuggestionsContainer.gameObject.SetActive( false );
  369. // Register to UI events
  370. commandInputField.onValidateInput += OnValidateCommand;
  371. commandInputField.onValueChanged.AddListener( RefreshCommandSuggestions );
  372. commandInputField.onEndEdit.AddListener( OnEndEditCommand );
  373. hideButton.onClick.AddListener( HideLogWindow );
  374. clearButton.onClick.AddListener( ClearLogs );
  375. collapseButton.GetComponent<Button>().onClick.AddListener( CollapseButtonPressed );
  376. filterInfoButton.GetComponent<Button>().onClick.AddListener( FilterLogButtonPressed );
  377. filterWarningButton.GetComponent<Button>().onClick.AddListener( FilterWarningButtonPressed );
  378. filterErrorButton.GetComponent<Button>().onClick.AddListener( FilterErrorButtonPressed );
  379. snapToBottomButton.GetComponent<Button>().onClick.AddListener( () => SetSnapToBottom( true ) );
  380. localTimeUtcOffset = System.DateTime.Now - System.DateTime.UtcNow;
  381. nullPointerEventData = new PointerEventData( null );
  382. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  383. toggleBinding.performed += ( context ) =>
  384. {
  385. if( toggleWithKey )
  386. {
  387. if( isLogWindowVisible )
  388. HideLogWindow();
  389. else
  390. ShowLogWindow();
  391. }
  392. };
  393. // On new Input System, scroll sensitivity is much higher than legacy Input system
  394. logItemsScrollRect.scrollSensitivity *= 0.25f;
  395. #endif
  396. }
  397. private void OnEnable()
  398. {
  399. if( Instance != this )
  400. return;
  401. // Intercept debug entries
  402. Application.logMessageReceivedThreaded -= ReceivedLog;
  403. Application.logMessageReceivedThreaded += ReceivedLog;
  404. if( receiveLogcatLogsInAndroid )
  405. {
  406. #if !UNITY_EDITOR && UNITY_ANDROID
  407. if( logcatListener == null )
  408. logcatListener = new DebugLogLogcatListener();
  409. logcatListener.Start( logcatArguments );
  410. #endif
  411. }
  412. DebugLogConsole.AddCommand( "logs.save", "Saves logs to persistentDataPath", SaveLogsToFile );
  413. DebugLogConsole.AddCommand<string>( "logs.save", "Saves logs to the specified file", SaveLogsToFile );
  414. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  415. if( toggleWithKey )
  416. toggleBinding.Enable();
  417. #endif
  418. //Debug.LogAssertion( "assert" );
  419. //Debug.LogError( "error" );
  420. //Debug.LogException( new System.IO.EndOfStreamException() );
  421. //Debug.LogWarning( "warning" );
  422. //Debug.Log( "log" );
  423. }
  424. private void OnDisable()
  425. {
  426. if( Instance != this )
  427. return;
  428. // Stop receiving debug entries
  429. Application.logMessageReceivedThreaded -= ReceivedLog;
  430. #if !UNITY_EDITOR && UNITY_ANDROID
  431. if( logcatListener != null )
  432. logcatListener.Stop();
  433. #endif
  434. DebugLogConsole.RemoveCommand( "logs.save" );
  435. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  436. if( toggleBinding.enabled )
  437. toggleBinding.Disable();
  438. #endif
  439. }
  440. private void Start()
  441. {
  442. if( ( enablePopup && startInPopupMode ) || ( !enablePopup && startMinimized ) )
  443. HideLogWindow();
  444. else
  445. ShowLogWindow();
  446. PopupEnabled = enablePopup;
  447. }
  448. #if UNITY_EDITOR
  449. private void OnValidate()
  450. {
  451. if( UnityEditor.EditorApplication.isPlaying )
  452. resizeButton.sprite = enableHorizontalResizing ? resizeIconAllDirections : resizeIconVerticalOnly;
  453. }
  454. private void OnApplicationQuit()
  455. {
  456. isQuittingApplication = true;
  457. }
  458. #endif
  459. // Window is resized, update the list
  460. private void OnRectTransformDimensionsChange()
  461. {
  462. screenDimensionsChanged = true;
  463. }
  464. #if !ENABLE_INPUT_SYSTEM || ENABLE_LEGACY_INPUT_MANAGER
  465. private void Update()
  466. {
  467. // Toggling the console with toggleKey is handled in Update instead of LateUpdate because
  468. // when we hide the console, we don't want the commandInputField to capture the toggleKey.
  469. // InputField captures input in LateUpdate so deactivating it in Update ensures that
  470. // no further input is captured
  471. if( toggleWithKey )
  472. {
  473. if( Input.GetKeyDown( toggleKey ) )
  474. {
  475. if( isLogWindowVisible )
  476. HideLogWindow();
  477. else
  478. ShowLogWindow();
  479. }
  480. }
  481. }
  482. #endif
  483. private void LateUpdate()
  484. {
  485. #if UNITY_EDITOR
  486. if( isQuittingApplication )
  487. return;
  488. #endif
  489. int queuedLogCount = queuedLogEntries.Count;
  490. if( queuedLogCount > 0 )
  491. {
  492. for( int i = 0; i < queuedLogCount; i++ )
  493. {
  494. QueuedDebugLogEntry logEntry;
  495. lock( logEntriesLock )
  496. {
  497. logEntry = queuedLogEntries.RemoveFirst();
  498. }
  499. ProcessLog( logEntry );
  500. }
  501. }
  502. // Update entry count texts in a single batch
  503. if( newInfoEntryCount > 0 || newWarningEntryCount > 0 || newErrorEntryCount > 0 )
  504. {
  505. if( newInfoEntryCount > 0 )
  506. {
  507. infoEntryCount += newInfoEntryCount;
  508. infoEntryCountText.text = infoEntryCount.ToString();
  509. }
  510. if( newWarningEntryCount > 0 )
  511. {
  512. warningEntryCount += newWarningEntryCount;
  513. warningEntryCountText.text = warningEntryCount.ToString();
  514. }
  515. if( newErrorEntryCount > 0 )
  516. {
  517. errorEntryCount += newErrorEntryCount;
  518. errorEntryCountText.text = errorEntryCount.ToString();
  519. }
  520. // If debug popup is visible, notify it of the new debug entries
  521. if( !isLogWindowVisible )
  522. popupManager.NewLogsArrived( newInfoEntryCount, newWarningEntryCount, newErrorEntryCount );
  523. newInfoEntryCount = 0;
  524. newWarningEntryCount = 0;
  525. newErrorEntryCount = 0;
  526. }
  527. // Update visible logs if necessary
  528. if( isLogWindowVisible && shouldUpdateRecycledListView )
  529. {
  530. recycledListView.OnLogEntriesUpdated( false );
  531. shouldUpdateRecycledListView = false;
  532. }
  533. // Automatically expand the target log (if any)
  534. if( indexOfLogEntryToSelectAndFocus >= 0 )
  535. {
  536. if( indexOfLogEntryToSelectAndFocus < indicesOfListEntriesToShow.Count )
  537. recycledListView.SelectAndFocusOnLogItemAtIndex( indexOfLogEntryToSelectAndFocus );
  538. indexOfLogEntryToSelectAndFocus = -1;
  539. }
  540. if( showCommandSuggestions && commandInputField.isFocused && commandInputField.caretPosition != commandInputFieldPrevCaretPos )
  541. RefreshCommandSuggestions( commandInputField.text );
  542. if( screenDimensionsChanged )
  543. {
  544. // Update the recycled list view
  545. if( isLogWindowVisible )
  546. recycledListView.OnViewportHeightChanged();
  547. else
  548. popupManager.UpdatePosition( true );
  549. #if UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS
  550. CheckScreenCutout();
  551. #endif
  552. screenDimensionsChanged = false;
  553. }
  554. float logWindowWidth = logWindowTR.rect.width;
  555. if( !Mathf.Approximately( logWindowWidth, logWindowPreviousWidth ) )
  556. {
  557. logWindowPreviousWidth = logWindowWidth;
  558. if( searchbar )
  559. {
  560. if( logWindowWidth >= topSearchbarMinWidth )
  561. {
  562. if( searchbar.parent == searchbarSlotBottom )
  563. {
  564. searchbarSlotTop.gameObject.SetActive( true );
  565. searchbar.SetParent( searchbarSlotTop, false );
  566. searchbarSlotBottom.gameObject.SetActive( false );
  567. logItemsScrollRectTR.anchoredPosition = Vector2.zero;
  568. logItemsScrollRectTR.sizeDelta = logItemsScrollRectOriginalSize;
  569. }
  570. }
  571. else
  572. {
  573. if( searchbar.parent == searchbarSlotTop )
  574. {
  575. searchbarSlotBottom.gameObject.SetActive( true );
  576. searchbar.SetParent( searchbarSlotBottom, false );
  577. searchbarSlotTop.gameObject.SetActive( false );
  578. float searchbarHeight = searchbarSlotBottom.sizeDelta.y;
  579. logItemsScrollRectTR.anchoredPosition = new Vector2( 0f, searchbarHeight * -0.5f );
  580. logItemsScrollRectTR.sizeDelta = logItemsScrollRectOriginalSize - new Vector2( 0f, searchbarHeight );
  581. }
  582. }
  583. }
  584. if( isLogWindowVisible )
  585. recycledListView.OnViewportWidthChanged();
  586. }
  587. // If snapToBottom is enabled, force the scrollbar to the bottom
  588. if( snapToBottom )
  589. {
  590. logItemsScrollRect.verticalNormalizedPosition = 0f;
  591. if( snapToBottomButton.activeSelf )
  592. snapToBottomButton.SetActive( false );
  593. }
  594. else
  595. {
  596. float scrollPos = logItemsScrollRect.verticalNormalizedPosition;
  597. if( snapToBottomButton.activeSelf != ( scrollPos > 1E-6f && scrollPos < 0.9999f ) )
  598. snapToBottomButton.SetActive( !snapToBottomButton.activeSelf );
  599. }
  600. if( isLogWindowVisible && commandInputField.isFocused && commandHistory.Count > 0 )
  601. {
  602. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  603. if( Keyboard.current != null )
  604. #endif
  605. {
  606. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  607. if( Keyboard.current[Key.UpArrow].wasPressedThisFrame )
  608. #else
  609. if( Input.GetKeyDown( KeyCode.UpArrow ) )
  610. #endif
  611. {
  612. if( commandHistoryIndex == -1 )
  613. {
  614. commandHistoryIndex = commandHistory.Count - 1;
  615. unfinishedCommand = commandInputField.text;
  616. }
  617. else if( --commandHistoryIndex < 0 )
  618. commandHistoryIndex = 0;
  619. commandInputField.text = commandHistory[commandHistoryIndex];
  620. commandInputField.caretPosition = commandInputField.text.Length;
  621. }
  622. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  623. else if( Keyboard.current[Key.DownArrow].wasPressedThisFrame && commandHistoryIndex != -1 )
  624. #else
  625. else if( Input.GetKeyDown( KeyCode.DownArrow ) && commandHistoryIndex != -1 )
  626. #endif
  627. {
  628. if( ++commandHistoryIndex < commandHistory.Count )
  629. commandInputField.text = commandHistory[commandHistoryIndex];
  630. else
  631. {
  632. commandHistoryIndex = -1;
  633. commandInputField.text = unfinishedCommand ?? string.Empty;
  634. }
  635. }
  636. }
  637. }
  638. #if !UNITY_EDITOR && UNITY_ANDROID
  639. if( logcatListener != null )
  640. {
  641. string log;
  642. while( ( log = logcatListener.GetLog() ) != null )
  643. ReceivedLog( "LOGCAT: " + log, string.Empty, LogType.Log );
  644. }
  645. #endif
  646. }
  647. public void ShowLogWindow()
  648. {
  649. // Show the log window
  650. logWindowCanvasGroup.interactable = true;
  651. logWindowCanvasGroup.blocksRaycasts = true;
  652. logWindowCanvasGroup.alpha = 1f;
  653. popupManager.Hide();
  654. // Update the recycled list view
  655. // (in case new entries were intercepted while log window was hidden)
  656. recycledListView.OnLogEntriesUpdated( true );
  657. #if UNITY_EDITOR || UNITY_STANDALONE
  658. // Focus on the command input field on standalone platforms when the console is opened
  659. if( autoFocusOnCommandInputField )
  660. StartCoroutine( ActivateCommandInputFieldCoroutine() );
  661. #endif
  662. isLogWindowVisible = true;
  663. if( OnLogWindowShown != null )
  664. OnLogWindowShown();
  665. }
  666. public void HideLogWindow()
  667. {
  668. // Hide the log window
  669. logWindowCanvasGroup.interactable = false;
  670. logWindowCanvasGroup.blocksRaycasts = false;
  671. logWindowCanvasGroup.alpha = 0f;
  672. if( commandInputField.isFocused )
  673. commandInputField.DeactivateInputField();
  674. popupManager.Show();
  675. isLogWindowVisible = false;
  676. if( OnLogWindowHidden != null )
  677. OnLogWindowHidden();
  678. }
  679. // Command field input is changed, check if command is submitted
  680. private char OnValidateCommand( string text, int charIndex, char addedChar )
  681. {
  682. if( addedChar == '\t' ) // Autocomplete attempt
  683. {
  684. if( !string.IsNullOrEmpty( text ) )
  685. {
  686. string autoCompletedCommand = DebugLogConsole.GetAutoCompleteCommand( text );
  687. if( !string.IsNullOrEmpty( autoCompletedCommand ) )
  688. commandInputField.text = autoCompletedCommand;
  689. }
  690. return '\0';
  691. }
  692. else if( addedChar == '\n' ) // Command is submitted
  693. {
  694. // Clear the command field
  695. if( clearCommandAfterExecution )
  696. commandInputField.text = string.Empty;
  697. if( text.Length > 0 )
  698. {
  699. if( commandHistory.Count == 0 || commandHistory[commandHistory.Count - 1] != text )
  700. commandHistory.Add( text );
  701. commandHistoryIndex = -1;
  702. unfinishedCommand = null;
  703. // Execute the command
  704. DebugLogConsole.ExecuteCommand( text );
  705. // Snap to bottom and select the latest entry
  706. SetSnapToBottom( true );
  707. }
  708. return '\0';
  709. }
  710. return addedChar;
  711. }
  712. // A debug entry is received
  713. public void ReceivedLog( string logString, string stackTrace, LogType logType )
  714. {
  715. #if UNITY_EDITOR
  716. if( isQuittingApplication )
  717. return;
  718. #endif
  719. // Truncate the log if it is longer than maxLogLength
  720. int logLength = logString.Length;
  721. if( stackTrace == null )
  722. {
  723. if( logLength > maxLogLength )
  724. logString = logString.Substring( 0, maxLogLength - 11 ) + "<truncated>";
  725. }
  726. else
  727. {
  728. logLength += stackTrace.Length;
  729. if( logLength > maxLogLength )
  730. {
  731. // Decide which log component(s) to truncate
  732. int halfMaxLogLength = maxLogLength / 2;
  733. if( logString.Length >= halfMaxLogLength )
  734. {
  735. if( stackTrace.Length >= halfMaxLogLength )
  736. {
  737. // Truncate both logString and stackTrace
  738. logString = logString.Substring( 0, halfMaxLogLength - 11 ) + "<truncated>";
  739. // If stackTrace doesn't end with a blank line, its last line won't be visible in the console for some reason
  740. stackTrace = stackTrace.Substring( 0, halfMaxLogLength - 12 ) + "<truncated>\n";
  741. }
  742. else
  743. {
  744. // Truncate logString
  745. logString = logString.Substring( 0, maxLogLength - stackTrace.Length - 11 ) + "<truncated>";
  746. }
  747. }
  748. else
  749. {
  750. // Truncate stackTrace
  751. stackTrace = stackTrace.Substring( 0, maxLogLength - logString.Length - 12 ) + "<truncated>\n";
  752. }
  753. }
  754. }
  755. QueuedDebugLogEntry queuedLogEntry = new QueuedDebugLogEntry( logString, stackTrace, logType );
  756. lock( logEntriesLock )
  757. {
  758. queuedLogEntries.Add( queuedLogEntry );
  759. }
  760. }
  761. // Present the log entry in the console
  762. private void ProcessLog( QueuedDebugLogEntry queuedLogEntry )
  763. {
  764. LogType logType = queuedLogEntry.logType;
  765. DebugLogEntry logEntry;
  766. if( pooledLogEntries.Count > 0 )
  767. {
  768. logEntry = pooledLogEntries[pooledLogEntries.Count - 1];
  769. pooledLogEntries.RemoveAt( pooledLogEntries.Count - 1 );
  770. }
  771. else
  772. logEntry = new DebugLogEntry();
  773. logEntry.Initialize( queuedLogEntry.logString, queuedLogEntry.stackTrace );
  774. // Check if this entry is a duplicate (i.e. has been received before)
  775. int logEntryIndex;
  776. bool isEntryInCollapsedEntryList = collapsedLogEntriesMap.TryGetValue( logEntry, out logEntryIndex );
  777. if( !isEntryInCollapsedEntryList )
  778. {
  779. // It is not a duplicate,
  780. // add it to the list of unique debug entries
  781. logEntry.logTypeSpriteRepresentation = logSpriteRepresentations[logType];
  782. logEntryIndex = collapsedLogEntries.Count;
  783. collapsedLogEntries.Add( logEntry );
  784. collapsedLogEntriesMap[logEntry] = logEntryIndex;
  785. if( collapsedLogEntriesTimestamps != null )
  786. collapsedLogEntriesTimestamps.Add( new DebugLogEntryTimestamp( localTimeUtcOffset ) );
  787. }
  788. else
  789. {
  790. // It is a duplicate, pool the duplicate log entry and
  791. // increment the original debug item's collapsed count
  792. pooledLogEntries.Add( logEntry );
  793. logEntry = collapsedLogEntries[logEntryIndex];
  794. logEntry.count++;
  795. if( collapsedLogEntriesTimestamps != null )
  796. collapsedLogEntriesTimestamps[logEntryIndex] = new DebugLogEntryTimestamp( localTimeUtcOffset );
  797. }
  798. // Add the index of the unique debug entry to the list
  799. // that stores the order the debug entries are received
  800. uncollapsedLogEntriesIndices.Add( logEntryIndex );
  801. // Record log's timestamp if desired
  802. if( uncollapsedLogEntriesTimestamps != null )
  803. uncollapsedLogEntriesTimestamps.Add( collapsedLogEntriesTimestamps[logEntryIndex] );
  804. // If this debug entry matches the current filters,
  805. // add it to the list of debug entries to show
  806. int logEntryIndexInEntriesToShow = -1;
  807. Sprite logTypeSpriteRepresentation = logEntry.logTypeSpriteRepresentation;
  808. if( isCollapseOn && isEntryInCollapsedEntryList )
  809. {
  810. if( isLogWindowVisible )
  811. {
  812. if( !isInSearchMode && logFilter == DebugLogFilter.All )
  813. logEntryIndexInEntriesToShow = logEntryIndex;
  814. else
  815. logEntryIndexInEntriesToShow = indicesOfListEntriesToShow.IndexOf( logEntryIndex );
  816. if( timestampsOfListEntriesToShow != null )
  817. timestampsOfListEntriesToShow[logEntryIndexInEntriesToShow] = collapsedLogEntriesTimestamps[logEntryIndex];
  818. recycledListView.OnCollapsedLogEntryAtIndexUpdated( logEntryIndexInEntriesToShow );
  819. }
  820. }
  821. else if( ( !isInSearchMode || queuedLogEntry.MatchesSearchTerm( searchTerm ) ) && ( logFilter == DebugLogFilter.All ||
  822. ( logTypeSpriteRepresentation == infoLog && ( ( logFilter & DebugLogFilter.Info ) == DebugLogFilter.Info ) ) ||
  823. ( logTypeSpriteRepresentation == warningLog && ( ( logFilter & DebugLogFilter.Warning ) == DebugLogFilter.Warning ) ) ||
  824. ( logTypeSpriteRepresentation == errorLog && ( ( logFilter & DebugLogFilter.Error ) == DebugLogFilter.Error ) ) ) )
  825. {
  826. indicesOfListEntriesToShow.Add( logEntryIndex );
  827. logEntryIndexInEntriesToShow = indicesOfListEntriesToShow.Count - 1;
  828. if( timestampsOfListEntriesToShow != null )
  829. timestampsOfListEntriesToShow.Add( collapsedLogEntriesTimestamps[logEntryIndex] );
  830. if( isLogWindowVisible )
  831. shouldUpdateRecycledListView = true;
  832. }
  833. if( logType == LogType.Log )
  834. newInfoEntryCount++;
  835. else if( logType == LogType.Warning )
  836. newWarningEntryCount++;
  837. else
  838. newErrorEntryCount++;
  839. // Automatically expand this log if necessary
  840. if( pendingLogToAutoExpand > 0 && --pendingLogToAutoExpand <= 0 && isLogWindowVisible && logEntryIndexInEntriesToShow >= 0 )
  841. indexOfLogEntryToSelectAndFocus = logEntryIndexInEntriesToShow;
  842. }
  843. // Value of snapToBottom is changed (user scrolled the list manually)
  844. public void SetSnapToBottom( bool snapToBottom )
  845. {
  846. this.snapToBottom = snapToBottom;
  847. }
  848. // Make sure the scroll bar of the scroll rect is adjusted properly
  849. internal void ValidateScrollPosition()
  850. {
  851. logItemsScrollRect.OnScroll( nullPointerEventData );
  852. }
  853. // Automatically expand the latest log in queuedLogEntries
  854. public void ExpandLatestPendingLog()
  855. {
  856. pendingLogToAutoExpand = queuedLogEntries.Count;
  857. }
  858. // Omits the latest log's stack trace
  859. public void StripStackTraceFromLatestPendingLog()
  860. {
  861. QueuedDebugLogEntry log = queuedLogEntries[queuedLogEntries.Count - 1];
  862. queuedLogEntries[queuedLogEntries.Count - 1] = new QueuedDebugLogEntry( log.logString, string.Empty, log.logType );
  863. }
  864. // Clear all the logs
  865. public void ClearLogs()
  866. {
  867. snapToBottom = true;
  868. infoEntryCount = 0;
  869. warningEntryCount = 0;
  870. errorEntryCount = 0;
  871. infoEntryCountText.text = "0";
  872. warningEntryCountText.text = "0";
  873. errorEntryCountText.text = "0";
  874. collapsedLogEntries.Clear();
  875. collapsedLogEntriesMap.Clear();
  876. uncollapsedLogEntriesIndices.Clear();
  877. indicesOfListEntriesToShow.Clear();
  878. if( collapsedLogEntriesTimestamps != null )
  879. {
  880. collapsedLogEntriesTimestamps.Clear();
  881. uncollapsedLogEntriesTimestamps.Clear();
  882. timestampsOfListEntriesToShow.Clear();
  883. }
  884. recycledListView.DeselectSelectedLogItem();
  885. recycledListView.OnLogEntriesUpdated( true );
  886. }
  887. // Collapse button is clicked
  888. private void CollapseButtonPressed()
  889. {
  890. // Swap the value of collapse mode
  891. isCollapseOn = !isCollapseOn;
  892. snapToBottom = true;
  893. collapseButton.color = isCollapseOn ? collapseButtonSelectedColor : collapseButtonNormalColor;
  894. recycledListView.SetCollapseMode( isCollapseOn );
  895. // Determine the new list of debug entries to show
  896. FilterLogs();
  897. }
  898. // Filtering mode of info logs has changed
  899. private void FilterLogButtonPressed()
  900. {
  901. logFilter = logFilter ^ DebugLogFilter.Info;
  902. if( ( logFilter & DebugLogFilter.Info ) == DebugLogFilter.Info )
  903. filterInfoButton.color = filterButtonsSelectedColor;
  904. else
  905. filterInfoButton.color = filterButtonsNormalColor;
  906. FilterLogs();
  907. }
  908. // Filtering mode of warning logs has changed
  909. private void FilterWarningButtonPressed()
  910. {
  911. logFilter = logFilter ^ DebugLogFilter.Warning;
  912. if( ( logFilter & DebugLogFilter.Warning ) == DebugLogFilter.Warning )
  913. filterWarningButton.color = filterButtonsSelectedColor;
  914. else
  915. filterWarningButton.color = filterButtonsNormalColor;
  916. FilterLogs();
  917. }
  918. // Filtering mode of error logs has changed
  919. private void FilterErrorButtonPressed()
  920. {
  921. logFilter = logFilter ^ DebugLogFilter.Error;
  922. if( ( logFilter & DebugLogFilter.Error ) == DebugLogFilter.Error )
  923. filterErrorButton.color = filterButtonsSelectedColor;
  924. else
  925. filterErrorButton.color = filterButtonsNormalColor;
  926. FilterLogs();
  927. }
  928. // Search term has changed
  929. private void SearchTermChanged( string searchTerm )
  930. {
  931. if( searchTerm != null )
  932. searchTerm = searchTerm.Trim();
  933. this.searchTerm = searchTerm;
  934. bool isInSearchMode = !string.IsNullOrEmpty( searchTerm );
  935. if( isInSearchMode || this.isInSearchMode )
  936. {
  937. this.isInSearchMode = isInSearchMode;
  938. FilterLogs();
  939. }
  940. }
  941. // Show suggestions for the currently entered command
  942. private void RefreshCommandSuggestions( string command )
  943. {
  944. if( !showCommandSuggestions )
  945. return;
  946. commandInputFieldPrevCaretPos = commandInputField.caretPosition;
  947. // Don't recalculate the command suggestions if the input command hasn't changed (i.e. only caret's position has changed)
  948. bool commandChanged = command != commandInputFieldPrevCommand;
  949. bool commandNameOrParametersChanged = false;
  950. if( commandChanged )
  951. {
  952. commandInputFieldPrevCommand = command;
  953. matchingCommandSuggestions.Clear();
  954. commandCaretIndexIncrements.Clear();
  955. string prevCommandName = commandInputFieldPrevCommandName;
  956. int numberOfParameters;
  957. DebugLogConsole.GetCommandSuggestions( command, matchingCommandSuggestions, commandCaretIndexIncrements, ref commandInputFieldPrevCommandName, out numberOfParameters );
  958. if( prevCommandName != commandInputFieldPrevCommandName || numberOfParameters != commandInputFieldPrevParamCount )
  959. {
  960. commandInputFieldPrevParamCount = numberOfParameters;
  961. commandNameOrParametersChanged = true;
  962. }
  963. }
  964. int caretArgumentIndex = 0;
  965. int caretPos = commandInputField.caretPosition;
  966. for( int i = 0; i < commandCaretIndexIncrements.Count && caretPos > commandCaretIndexIncrements[i]; i++ )
  967. caretArgumentIndex++;
  968. if( caretArgumentIndex != commandInputFieldPrevCaretArgumentIndex )
  969. commandInputFieldPrevCaretArgumentIndex = caretArgumentIndex;
  970. else if( !commandChanged || !commandNameOrParametersChanged )
  971. {
  972. // Command suggestions don't need to be updated if:
  973. // a) neither the entered command nor the argument that the caret is hovering has changed
  974. // b) entered command has changed but command's name hasn't changed, parameter count hasn't changed and the argument
  975. // that the caret is hovering hasn't changed (i.e. user has continued typing a parameter's value)
  976. return;
  977. }
  978. if( matchingCommandSuggestions.Count == 0 )
  979. OnEndEditCommand( command );
  980. else
  981. {
  982. if( !commandSuggestionsContainer.gameObject.activeSelf )
  983. commandSuggestionsContainer.gameObject.SetActive( true );
  984. int suggestionInstancesCount = commandSuggestionInstances.Count;
  985. int suggestionsCount = matchingCommandSuggestions.Count;
  986. for( int i = 0; i < suggestionsCount; i++ )
  987. {
  988. if( i >= visibleCommandSuggestionInstances )
  989. {
  990. if( i >= suggestionInstancesCount )
  991. commandSuggestionInstances.Add( (Text) Instantiate( commandSuggestionPrefab, commandSuggestionsContainer, false ) );
  992. else
  993. commandSuggestionInstances[i].gameObject.SetActive( true );
  994. visibleCommandSuggestionInstances++;
  995. }
  996. ConsoleMethodInfo suggestedCommand = matchingCommandSuggestions[i];
  997. sharedStringBuilder.Length = 0;
  998. if( caretArgumentIndex > 0 )
  999. sharedStringBuilder.Append( suggestedCommand.command );
  1000. else
  1001. sharedStringBuilder.Append( commandSuggestionHighlightStart ).Append( matchingCommandSuggestions[i].command ).Append( commandSuggestionHighlightEnd );
  1002. if( suggestedCommand.parameters.Length > 0 )
  1003. {
  1004. sharedStringBuilder.Append( " " );
  1005. // If the command name wasn't highlighted, a parameter must always be highlighted
  1006. int caretParameterIndex = caretArgumentIndex - 1;
  1007. if( caretParameterIndex >= suggestedCommand.parameters.Length )
  1008. caretParameterIndex = suggestedCommand.parameters.Length - 1;
  1009. for( int j = 0; j < suggestedCommand.parameters.Length; j++ )
  1010. {
  1011. if( caretParameterIndex != j )
  1012. sharedStringBuilder.Append( suggestedCommand.parameters[j] );
  1013. else
  1014. sharedStringBuilder.Append( commandSuggestionHighlightStart ).Append( suggestedCommand.parameters[j] ).Append( commandSuggestionHighlightEnd );
  1015. }
  1016. }
  1017. commandSuggestionInstances[i].text = sharedStringBuilder.ToString();
  1018. }
  1019. for( int i = visibleCommandSuggestionInstances - 1; i >= suggestionsCount; i-- )
  1020. commandSuggestionInstances[i].gameObject.SetActive( false );
  1021. visibleCommandSuggestionInstances = suggestionsCount;
  1022. }
  1023. }
  1024. // Command input field has lost focus
  1025. private void OnEndEditCommand( string command )
  1026. {
  1027. if( commandSuggestionsContainer.gameObject.activeSelf )
  1028. commandSuggestionsContainer.gameObject.SetActive( false );
  1029. }
  1030. // Debug window is being resized,
  1031. // Set the sizeDelta property of the window accordingly while
  1032. // preventing window dimensions from going below the minimum dimensions
  1033. internal void Resize( PointerEventData eventData )
  1034. {
  1035. Vector2 localPoint;
  1036. if( !RectTransformUtility.ScreenPointToLocalPointInRectangle( canvasTR, eventData.position, eventData.pressEventCamera, out localPoint ) )
  1037. return;
  1038. // To be able to maximize the log window easily:
  1039. // - When enableHorizontalResizing is true and resizing horizontally, resize button will be grabbed from its left edge (if resizeFromRight is true) or its right edge
  1040. // - While resizing vertically, resize button will be grabbed from its top edge
  1041. const float resizeButtonWidth = 64f;
  1042. const float resizeButtonHeight = 36f;
  1043. Vector2 canvasPivot = canvasTR.pivot;
  1044. Vector2 canvasSize = canvasTR.rect.size;
  1045. Vector2 anchorMin = logWindowTR.anchorMin;
  1046. // Horizontal resizing
  1047. if( enableHorizontalResizing )
  1048. {
  1049. if( resizeFromRight )
  1050. {
  1051. localPoint.x += canvasPivot.x * canvasSize.x + resizeButtonWidth;
  1052. if( localPoint.x < minimumWidth )
  1053. localPoint.x = minimumWidth;
  1054. Vector2 anchorMax = logWindowTR.anchorMax;
  1055. anchorMax.x = Mathf.Clamp01( localPoint.x / canvasSize.x );
  1056. logWindowTR.anchorMax = anchorMax;
  1057. }
  1058. else
  1059. {
  1060. localPoint.x += canvasPivot.x * canvasSize.x - resizeButtonWidth;
  1061. if( localPoint.x > canvasSize.x - minimumWidth )
  1062. localPoint.x = canvasSize.x - minimumWidth;
  1063. anchorMin.x = Mathf.Clamp01( localPoint.x / canvasSize.x );
  1064. }
  1065. }
  1066. // Vertical resizing
  1067. float notchHeight = -logWindowTR.sizeDelta.y; // Size of notch screen cutouts at the top of the screen
  1068. localPoint.y += canvasPivot.y * canvasSize.y - resizeButtonHeight;
  1069. if( localPoint.y > canvasSize.y - minimumHeight - notchHeight )
  1070. localPoint.y = canvasSize.y - minimumHeight - notchHeight;
  1071. anchorMin.y = Mathf.Clamp01( localPoint.y / canvasSize.y );
  1072. logWindowTR.anchorMin = anchorMin;
  1073. // Update the recycled list view
  1074. recycledListView.OnViewportHeightChanged();
  1075. }
  1076. // Determine the filtered list of debug entries to show on screen
  1077. private void FilterLogs()
  1078. {
  1079. indicesOfListEntriesToShow.Clear();
  1080. if( timestampsOfListEntriesToShow != null )
  1081. timestampsOfListEntriesToShow.Clear();
  1082. if( logFilter != DebugLogFilter.None )
  1083. {
  1084. if( logFilter == DebugLogFilter.All )
  1085. {
  1086. if( isCollapseOn )
  1087. {
  1088. if( !isInSearchMode )
  1089. {
  1090. // All the unique debug entries will be listed just once.
  1091. // So, list of debug entries to show is the same as the
  1092. // order these unique debug entries are added to collapsedLogEntries
  1093. for( int i = 0, count = collapsedLogEntries.Count; i < count; i++ )
  1094. {
  1095. indicesOfListEntriesToShow.Add( i );
  1096. if( timestampsOfListEntriesToShow != null )
  1097. timestampsOfListEntriesToShow.Add( collapsedLogEntriesTimestamps[i] );
  1098. }
  1099. }
  1100. else
  1101. {
  1102. for( int i = 0, count = collapsedLogEntries.Count; i < count; i++ )
  1103. {
  1104. if( collapsedLogEntries[i].MatchesSearchTerm( searchTerm ) )
  1105. {
  1106. indicesOfListEntriesToShow.Add( i );
  1107. if( timestampsOfListEntriesToShow != null )
  1108. timestampsOfListEntriesToShow.Add( collapsedLogEntriesTimestamps[i] );
  1109. }
  1110. }
  1111. }
  1112. }
  1113. else
  1114. {
  1115. if( !isInSearchMode )
  1116. {
  1117. for( int i = 0, count = uncollapsedLogEntriesIndices.Count; i < count; i++ )
  1118. {
  1119. indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
  1120. if( timestampsOfListEntriesToShow != null )
  1121. timestampsOfListEntriesToShow.Add( uncollapsedLogEntriesTimestamps[i] );
  1122. }
  1123. }
  1124. else
  1125. {
  1126. for( int i = 0, count = uncollapsedLogEntriesIndices.Count; i < count; i++ )
  1127. {
  1128. if( collapsedLogEntries[uncollapsedLogEntriesIndices[i]].MatchesSearchTerm( searchTerm ) )
  1129. {
  1130. indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
  1131. if( timestampsOfListEntriesToShow != null )
  1132. timestampsOfListEntriesToShow.Add( uncollapsedLogEntriesTimestamps[i] );
  1133. }
  1134. }
  1135. }
  1136. }
  1137. }
  1138. else
  1139. {
  1140. // Show only the debug entries that match the current filter
  1141. bool isInfoEnabled = ( logFilter & DebugLogFilter.Info ) == DebugLogFilter.Info;
  1142. bool isWarningEnabled = ( logFilter & DebugLogFilter.Warning ) == DebugLogFilter.Warning;
  1143. bool isErrorEnabled = ( logFilter & DebugLogFilter.Error ) == DebugLogFilter.Error;
  1144. if( isCollapseOn )
  1145. {
  1146. for( int i = 0, count = collapsedLogEntries.Count; i < count; i++ )
  1147. {
  1148. DebugLogEntry logEntry = collapsedLogEntries[i];
  1149. if( isInSearchMode && !logEntry.MatchesSearchTerm( searchTerm ) )
  1150. continue;
  1151. bool shouldShowLog = false;
  1152. if( logEntry.logTypeSpriteRepresentation == infoLog )
  1153. {
  1154. if( isInfoEnabled )
  1155. shouldShowLog = true;
  1156. }
  1157. else if( logEntry.logTypeSpriteRepresentation == warningLog )
  1158. {
  1159. if( isWarningEnabled )
  1160. shouldShowLog = true;
  1161. }
  1162. else if( isErrorEnabled )
  1163. shouldShowLog = true;
  1164. if( shouldShowLog )
  1165. {
  1166. indicesOfListEntriesToShow.Add( i );
  1167. if( timestampsOfListEntriesToShow != null )
  1168. timestampsOfListEntriesToShow.Add( collapsedLogEntriesTimestamps[i] );
  1169. }
  1170. }
  1171. }
  1172. else
  1173. {
  1174. for( int i = 0, count = uncollapsedLogEntriesIndices.Count; i < count; i++ )
  1175. {
  1176. DebugLogEntry logEntry = collapsedLogEntries[uncollapsedLogEntriesIndices[i]];
  1177. if( isInSearchMode && !logEntry.MatchesSearchTerm( searchTerm ) )
  1178. continue;
  1179. bool shouldShowLog = false;
  1180. if( logEntry.logTypeSpriteRepresentation == infoLog )
  1181. {
  1182. if( isInfoEnabled )
  1183. shouldShowLog = true;
  1184. }
  1185. else if( logEntry.logTypeSpriteRepresentation == warningLog )
  1186. {
  1187. if( isWarningEnabled )
  1188. shouldShowLog = true;
  1189. }
  1190. else if( isErrorEnabled )
  1191. shouldShowLog = true;
  1192. if( shouldShowLog )
  1193. {
  1194. indicesOfListEntriesToShow.Add( uncollapsedLogEntriesIndices[i] );
  1195. if( timestampsOfListEntriesToShow != null )
  1196. timestampsOfListEntriesToShow.Add( uncollapsedLogEntriesTimestamps[i] );
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. // Update the recycled list view
  1203. recycledListView.DeselectSelectedLogItem();
  1204. recycledListView.OnLogEntriesUpdated( true );
  1205. ValidateScrollPosition();
  1206. }
  1207. public string GetAllLogs()
  1208. {
  1209. int count = uncollapsedLogEntriesIndices.Count;
  1210. int length = 0;
  1211. int newLineLength = System.Environment.NewLine.Length;
  1212. for( int i = 0; i < count; i++ )
  1213. {
  1214. DebugLogEntry entry = collapsedLogEntries[uncollapsedLogEntriesIndices[i]];
  1215. length += entry.logString.Length + entry.stackTrace.Length + newLineLength * 3;
  1216. }
  1217. if( uncollapsedLogEntriesTimestamps != null )
  1218. length += count * 12; // Timestamp: "[HH:mm:ss]: "
  1219. length += 100; // Just in case...
  1220. StringBuilder sb = new StringBuilder( length );
  1221. for( int i = 0; i < count; i++ )
  1222. {
  1223. DebugLogEntry entry = collapsedLogEntries[uncollapsedLogEntriesIndices[i]];
  1224. if( uncollapsedLogEntriesTimestamps != null )
  1225. {
  1226. uncollapsedLogEntriesTimestamps[i].AppendTime( sb );
  1227. sb.Append( ": " );
  1228. }
  1229. sb.AppendLine( entry.logString ).AppendLine( entry.stackTrace ).AppendLine();
  1230. }
  1231. return sb.ToString();
  1232. }
  1233. private void SaveLogsToFile()
  1234. {
  1235. SaveLogsToFile( Path.Combine( Application.persistentDataPath, System.DateTime.Now.ToString( "dd-MM-yyyy--HH-mm-ss" ) + ".txt" ) );
  1236. }
  1237. private void SaveLogsToFile( string filePath )
  1238. {
  1239. File.WriteAllText( filePath, GetAllLogs() );
  1240. Debug.Log( "Logs saved to: " + filePath );
  1241. }
  1242. // If a cutout is intersecting with debug window on notch screens, shift the window downwards
  1243. private void CheckScreenCutout()
  1244. {
  1245. if( !avoidScreenCutout )
  1246. return;
  1247. #if UNITY_2017_2_OR_NEWER && ( UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS )
  1248. // Check if there is a cutout at the top of the screen
  1249. int screenHeight = Screen.height;
  1250. float safeYMax = Screen.safeArea.yMax;
  1251. if( safeYMax < screenHeight - 1 ) // 1: a small threshold
  1252. {
  1253. // There is a cutout, shift the log window downwards
  1254. float cutoutPercentage = ( screenHeight - safeYMax ) / Screen.height;
  1255. float cutoutLocalSize = cutoutPercentage * canvasTR.rect.height;
  1256. logWindowTR.anchoredPosition = new Vector2( 0f, -cutoutLocalSize );
  1257. logWindowTR.sizeDelta = new Vector2( 0f, -cutoutLocalSize );
  1258. }
  1259. else
  1260. {
  1261. logWindowTR.anchoredPosition = Vector2.zero;
  1262. logWindowTR.sizeDelta = Vector2.zero;
  1263. }
  1264. #endif
  1265. }
  1266. #if UNITY_EDITOR || UNITY_STANDALONE
  1267. private IEnumerator ActivateCommandInputFieldCoroutine()
  1268. {
  1269. // Waiting 1 frame before activating commandInputField ensures that the toggleKey isn't captured by it
  1270. yield return null;
  1271. commandInputField.ActivateInputField();
  1272. yield return null;
  1273. commandInputField.MoveTextEnd( false );
  1274. }
  1275. #endif
  1276. // Pool an unused log item
  1277. internal void PoolLogItem( DebugLogItem logItem )
  1278. {
  1279. logItem.CanvasGroup.alpha = 0f;
  1280. logItem.CanvasGroup.blocksRaycasts = false;
  1281. pooledLogItems.Add( logItem );
  1282. }
  1283. // Fetch a log item from the pool
  1284. internal DebugLogItem PopLogItem()
  1285. {
  1286. DebugLogItem newLogItem;
  1287. // If pool is not empty, fetch a log item from the pool,
  1288. // create a new log item otherwise
  1289. if( pooledLogItems.Count > 0 )
  1290. {
  1291. newLogItem = pooledLogItems[pooledLogItems.Count - 1];
  1292. pooledLogItems.RemoveAt( pooledLogItems.Count - 1 );
  1293. newLogItem.CanvasGroup.alpha = 1f;
  1294. newLogItem.CanvasGroup.blocksRaycasts = true;
  1295. }
  1296. else
  1297. {
  1298. newLogItem = (DebugLogItem) Instantiate( logItemPrefab, logItemsContainer, false );
  1299. newLogItem.Initialize( recycledListView );
  1300. }
  1301. return newLogItem;
  1302. }
  1303. }
  1304. }