BuildOutputView.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. using Godot;
  2. using System;
  3. using Godot.Collections;
  4. using GodotTools.Internals;
  5. using JetBrains.Annotations;
  6. using File = GodotTools.Utils.File;
  7. using Path = System.IO.Path;
  8. namespace GodotTools.Build
  9. {
  10. public class BuildOutputView : VBoxContainer, ISerializationListener
  11. {
  12. [Serializable]
  13. private class BuildIssue : Reference // TODO Remove Reference once we have proper serialization
  14. {
  15. public bool Warning { get; set; }
  16. public string File { get; set; }
  17. public int Line { get; set; }
  18. public int Column { get; set; }
  19. public string Code { get; set; }
  20. public string Message { get; set; }
  21. public string ProjectFile { get; set; }
  22. }
  23. private readonly Array<BuildIssue> issues = new Array<BuildIssue>(); // TODO Use List once we have proper serialization
  24. private ItemList issuesList;
  25. private TextEdit buildLog;
  26. private PopupMenu issuesListContextMenu;
  27. private readonly object pendingBuildLogTextLock = new object();
  28. [NotNull] private string pendingBuildLogText = string.Empty;
  29. [Signal] public event Action BuildStateChanged;
  30. public bool HasBuildExited { get; private set; } = false;
  31. public BuildResult? BuildResult { get; private set; } = null;
  32. public int ErrorCount { get; private set; } = 0;
  33. public int WarningCount { get; private set; } = 0;
  34. public bool ErrorsVisible { get; set; } = true;
  35. public bool WarningsVisible { get; set; } = true;
  36. public Texture2D BuildStateIcon
  37. {
  38. get
  39. {
  40. if (!HasBuildExited)
  41. return GetThemeIcon("Stop", "EditorIcons");
  42. if (BuildResult == Build.BuildResult.Error)
  43. return GetThemeIcon("Error", "EditorIcons");
  44. if (WarningCount > 1)
  45. return GetThemeIcon("Warning", "EditorIcons");
  46. return null;
  47. }
  48. }
  49. private BuildInfo BuildInfo { get; set; }
  50. public bool LogVisible
  51. {
  52. set => buildLog.Visible = value;
  53. }
  54. private void LoadIssuesFromFile(string csvFile)
  55. {
  56. using (var file = new Godot.File())
  57. {
  58. try
  59. {
  60. Error openError = file.Open(csvFile, Godot.File.ModeFlags.Read);
  61. if (openError != Error.Ok)
  62. return;
  63. while (!file.EofReached())
  64. {
  65. string[] csvColumns = file.GetCsvLine();
  66. if (csvColumns.Length == 1 && string.IsNullOrEmpty(csvColumns[0]))
  67. return;
  68. if (csvColumns.Length != 7)
  69. {
  70. GD.PushError($"Expected 7 columns, got {csvColumns.Length}");
  71. continue;
  72. }
  73. var issue = new BuildIssue
  74. {
  75. Warning = csvColumns[0] == "warning",
  76. File = csvColumns[1],
  77. Line = int.Parse(csvColumns[2]),
  78. Column = int.Parse(csvColumns[3]),
  79. Code = csvColumns[4],
  80. Message = csvColumns[5],
  81. ProjectFile = csvColumns[6]
  82. };
  83. if (issue.Warning)
  84. WarningCount += 1;
  85. else
  86. ErrorCount += 1;
  87. issues.Add(issue);
  88. }
  89. }
  90. finally
  91. {
  92. file.Close(); // Disposing it is not enough. We need to call Close()
  93. }
  94. }
  95. }
  96. private void IssueActivated(int idx)
  97. {
  98. if (idx < 0 || idx >= issuesList.GetItemCount())
  99. throw new IndexOutOfRangeException("Item list index out of range");
  100. // Get correct issue idx from issue list
  101. int issueIndex = (int)(long)issuesList.GetItemMetadata(idx);
  102. if (issueIndex < 0 || issueIndex >= issues.Count)
  103. throw new IndexOutOfRangeException("Issue index out of range");
  104. BuildIssue issue = issues[issueIndex];
  105. if (string.IsNullOrEmpty(issue.ProjectFile) && string.IsNullOrEmpty(issue.File))
  106. return;
  107. string projectDir = issue.ProjectFile.Length > 0 ? issue.ProjectFile.GetBaseDir() : BuildInfo.Solution.GetBaseDir();
  108. string file = Path.Combine(projectDir.SimplifyGodotPath(), issue.File.SimplifyGodotPath());
  109. if (!File.Exists(file))
  110. return;
  111. file = ProjectSettings.LocalizePath(file);
  112. if (file.StartsWith("res://"))
  113. {
  114. var script = (Script)ResourceLoader.Load(file, typeHint: Internal.CSharpLanguageType);
  115. if (script != null && Internal.ScriptEditorEdit(script, issue.Line, issue.Column))
  116. Internal.EditorNodeShowScriptScreen();
  117. }
  118. }
  119. public void UpdateIssuesList()
  120. {
  121. issuesList.Clear();
  122. using (var warningIcon = GetThemeIcon("Warning", "EditorIcons"))
  123. using (var errorIcon = GetThemeIcon("Error", "EditorIcons"))
  124. {
  125. for (int i = 0; i < issues.Count; i++)
  126. {
  127. BuildIssue issue = issues[i];
  128. if (!(issue.Warning ? WarningsVisible : ErrorsVisible))
  129. continue;
  130. string tooltip = string.Empty;
  131. tooltip += $"Message: {issue.Message}";
  132. if (!string.IsNullOrEmpty(issue.Code))
  133. tooltip += $"\nCode: {issue.Code}";
  134. tooltip += $"\nType: {(issue.Warning ? "warning" : "error")}";
  135. string text = string.Empty;
  136. if (!string.IsNullOrEmpty(issue.File))
  137. {
  138. text += $"{issue.File}({issue.Line},{issue.Column}): ";
  139. tooltip += $"\nFile: {issue.File}";
  140. tooltip += $"\nLine: {issue.Line}";
  141. tooltip += $"\nColumn: {issue.Column}";
  142. }
  143. if (!string.IsNullOrEmpty(issue.ProjectFile))
  144. tooltip += $"\nProject: {issue.ProjectFile}";
  145. text += issue.Message;
  146. int lineBreakIdx = text.IndexOf("\n", StringComparison.Ordinal);
  147. string itemText = lineBreakIdx == -1 ? text : text.Substring(0, lineBreakIdx);
  148. issuesList.AddItem(itemText, issue.Warning ? warningIcon : errorIcon);
  149. int index = issuesList.GetItemCount() - 1;
  150. issuesList.SetItemTooltip(index, tooltip);
  151. issuesList.SetItemMetadata(index, i);
  152. }
  153. }
  154. }
  155. private void BuildLaunchFailed(BuildInfo buildInfo, string cause)
  156. {
  157. HasBuildExited = true;
  158. BuildResult = Build.BuildResult.Error;
  159. issuesList.Clear();
  160. var issue = new BuildIssue {Message = cause, Warning = false};
  161. ErrorCount += 1;
  162. issues.Add(issue);
  163. UpdateIssuesList();
  164. EmitSignal(nameof(BuildStateChanged));
  165. }
  166. private void BuildStarted(BuildInfo buildInfo)
  167. {
  168. BuildInfo = buildInfo;
  169. HasBuildExited = false;
  170. issues.Clear();
  171. WarningCount = 0;
  172. ErrorCount = 0;
  173. buildLog.Text = string.Empty;
  174. UpdateIssuesList();
  175. EmitSignal(nameof(BuildStateChanged));
  176. }
  177. private void BuildFinished(BuildResult result)
  178. {
  179. HasBuildExited = true;
  180. BuildResult = result;
  181. LoadIssuesFromFile(Path.Combine(BuildInfo.LogsDirPath, BuildManager.MsBuildIssuesFileName));
  182. UpdateIssuesList();
  183. EmitSignal(nameof(BuildStateChanged));
  184. }
  185. private void UpdateBuildLogText()
  186. {
  187. lock (pendingBuildLogTextLock)
  188. {
  189. buildLog.Text += pendingBuildLogText;
  190. pendingBuildLogText = string.Empty;
  191. ScrollToLastNonEmptyLogLine();
  192. }
  193. }
  194. private void StdOutputReceived(string text)
  195. {
  196. lock (pendingBuildLogTextLock)
  197. {
  198. if (pendingBuildLogText.Length == 0)
  199. CallDeferred(nameof(UpdateBuildLogText));
  200. pendingBuildLogText += text + "\n";
  201. }
  202. }
  203. private void StdErrorReceived(string text)
  204. {
  205. lock (pendingBuildLogTextLock)
  206. {
  207. if (pendingBuildLogText.Length == 0)
  208. CallDeferred(nameof(UpdateBuildLogText));
  209. pendingBuildLogText += text + "\n";
  210. }
  211. }
  212. private void ScrollToLastNonEmptyLogLine()
  213. {
  214. int line;
  215. for (line = buildLog.GetLineCount(); line > 0; line--)
  216. {
  217. string lineText = buildLog.GetLine(line);
  218. if (!string.IsNullOrEmpty(lineText) || !string.IsNullOrEmpty(lineText?.Trim()))
  219. break;
  220. }
  221. buildLog.CursorSetLine(line);
  222. }
  223. public void RestartBuild()
  224. {
  225. if (!HasBuildExited)
  226. throw new InvalidOperationException("Build already started");
  227. BuildManager.RestartBuild(this);
  228. }
  229. public void StopBuild()
  230. {
  231. if (!HasBuildExited)
  232. throw new InvalidOperationException("Build is not in progress");
  233. BuildManager.StopBuild(this);
  234. }
  235. private enum IssuesContextMenuOption
  236. {
  237. Copy
  238. }
  239. private void IssuesListContextOptionPressed(int id)
  240. {
  241. switch ((IssuesContextMenuOption)id)
  242. {
  243. case IssuesContextMenuOption.Copy:
  244. {
  245. // We don't allow multi-selection but just in case that changes later...
  246. string text = null;
  247. foreach (int issueIndex in issuesList.GetSelectedItems())
  248. {
  249. if (text != null)
  250. text += "\n";
  251. text += issuesList.GetItemText(issueIndex);
  252. }
  253. if (text != null)
  254. DisplayServer.ClipboardSet(text);
  255. break;
  256. }
  257. default:
  258. throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid issue context menu option");
  259. }
  260. }
  261. private void IssuesListRmbSelected(int index, Vector2 atPosition)
  262. {
  263. _ = index; // Unused
  264. issuesListContextMenu.Clear();
  265. issuesListContextMenu.Size = new Vector2i(1, 1);
  266. if (issuesList.IsAnythingSelected())
  267. {
  268. // Add menu entries for the selected item
  269. issuesListContextMenu.AddIconItem(GetThemeIcon("ActionCopy", "EditorIcons"),
  270. label: "Copy Error".TTR(), (int)IssuesContextMenuOption.Copy);
  271. }
  272. if (issuesListContextMenu.GetItemCount() > 0)
  273. {
  274. issuesListContextMenu.Position = (Vector2i)(issuesList.RectGlobalPosition + atPosition);
  275. issuesListContextMenu.Popup();
  276. }
  277. }
  278. public override void _Ready()
  279. {
  280. base._Ready();
  281. SizeFlagsVertical = (int)SizeFlags.ExpandFill;
  282. var hsc = new HSplitContainer
  283. {
  284. SizeFlagsHorizontal = (int)SizeFlags.ExpandFill,
  285. SizeFlagsVertical = (int)SizeFlags.ExpandFill
  286. };
  287. AddChild(hsc);
  288. issuesList = new ItemList
  289. {
  290. SizeFlagsVertical = (int)SizeFlags.ExpandFill,
  291. SizeFlagsHorizontal = (int)SizeFlags.ExpandFill // Avoid being squashed by the build log
  292. };
  293. issuesList.ItemActivated += IssueActivated;
  294. issuesList.AllowRmbSelect = true;
  295. issuesList.ItemRmbSelected += IssuesListRmbSelected;
  296. hsc.AddChild(issuesList);
  297. issuesListContextMenu = new PopupMenu();
  298. issuesListContextMenu.IdPressed += IssuesListContextOptionPressed;
  299. issuesList.AddChild(issuesListContextMenu);
  300. buildLog = new TextEdit
  301. {
  302. Readonly = true,
  303. SizeFlagsVertical = (int)SizeFlags.ExpandFill,
  304. SizeFlagsHorizontal = (int)SizeFlags.ExpandFill // Avoid being squashed by the issues list
  305. };
  306. hsc.AddChild(buildLog);
  307. AddBuildEventListeners();
  308. }
  309. private void AddBuildEventListeners()
  310. {
  311. BuildManager.BuildLaunchFailed += BuildLaunchFailed;
  312. BuildManager.BuildStarted += BuildStarted;
  313. BuildManager.BuildFinished += BuildFinished;
  314. // StdOutput/Error can be received from different threads, so we need to use CallDeferred
  315. BuildManager.StdOutputReceived += StdOutputReceived;
  316. BuildManager.StdErrorReceived += StdErrorReceived;
  317. }
  318. public void OnBeforeSerialize()
  319. {
  320. // In case it didn't update yet. We don't want to have to serialize any pending output.
  321. UpdateBuildLogText();
  322. }
  323. public void OnAfterDeserialize()
  324. {
  325. AddBuildEventListeners(); // Re-add them
  326. }
  327. }
  328. }