ComponentWhitelistController.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. using AssetBank.Settings;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using UnityEditor;
  8. using UnityEngine;
  9. using Newtonsoft.Json.Linq;
  10. namespace AssetBank.Editor.Tools
  11. {
  12. /// <summary>
  13. /// Handles the core logic for scanning the project and managing the component whitelist.
  14. /// </summary>
  15. public class ComponentWhitelistController
  16. {
  17. private static readonly string ProjectRoot = Path.GetDirectoryName(Application.dataPath);
  18. public enum ScanSource
  19. {
  20. Scenes,
  21. Prefabs,
  22. Both
  23. }
  24. /// <summary>
  25. /// Scans the project for components based on the selected source.
  26. /// </summary>
  27. /// <param name="scanSource">The type of assets to scan.</param>
  28. /// <returns>A HashSet of unique component type names found.</returns>
  29. public HashSet<string> ScanProject(ScanSource scanSource)
  30. {
  31. var settings = ProjectExporterSettings.GetOrCreateSettings();
  32. var ignoredFolders = settings.FoldersToIgnore;
  33. var assetsToScan = new List<string>();
  34. if (scanSource == ScanSource.Scenes || scanSource == ScanSource.Both)
  35. {
  36. assetsToScan.AddRange(AssetDatabase.FindAssets("t:Scene", new[] { "Assets" }));
  37. }
  38. if (scanSource == ScanSource.Prefabs || scanSource == ScanSource.Both)
  39. {
  40. assetsToScan.AddRange(AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" }));
  41. }
  42. var assetPaths = assetsToScan.Distinct().Select(AssetDatabase.GUIDToAssetPath).ToList();
  43. var filteredPaths = assetPaths.Where(path => !ignoredFolders.Any(folder => path.StartsWith(folder, StringComparison.OrdinalIgnoreCase))).ToList();
  44. var tempDir = Path.Combine("Library", "ComponentScanTemp");
  45. if (Directory.Exists(tempDir))
  46. {
  47. Directory.Delete(tempDir, true);
  48. }
  49. Directory.CreateDirectory(tempDir);
  50. var uniqueComponents = new HashSet<string>();
  51. try
  52. {
  53. EditorUtility.DisplayProgressBar("Scanning Components", "Preparing to scan...", 0f);
  54. for (int i = 0; i < filteredPaths.Count; i++)
  55. {
  56. var assetPath = filteredPaths[i];
  57. var progress = (float)i / filteredPaths.Count;
  58. EditorUtility.DisplayProgressBar("Scanning Components", $"Processing: {Path.GetFileName(assetPath)}", progress);
  59. var jsonPath = Path.Combine(tempDir, $"{Path.GetFileNameWithoutExtension(assetPath)}_{i}.json");
  60. if (ExecutePythonConversion(assetPath, jsonPath))
  61. {
  62. var components = ParseComponentsFromJson(jsonPath);
  63. uniqueComponents.UnionWith(components);
  64. }
  65. }
  66. }
  67. finally
  68. {
  69. if (Directory.Exists(tempDir))
  70. {
  71. Directory.Delete(tempDir, true);
  72. }
  73. EditorUtility.ClearProgressBar();
  74. }
  75. return uniqueComponents;
  76. }
  77. private string FindPythonExecutable()
  78. {
  79. var venvPath = Path.Combine(ProjectRoot, "venv", "bin", "python3");
  80. if (File.Exists(venvPath))
  81. {
  82. return venvPath;
  83. }
  84. venvPath = Path.Combine(ProjectRoot, "venv", "bin", "python");
  85. if (File.Exists(venvPath))
  86. {
  87. return venvPath;
  88. }
  89. return "python3";
  90. }
  91. /// <summary>
  92. /// Executes the Python conversion script for a given asset.
  93. /// </summary>
  94. private bool ExecutePythonConversion(string assetPath, string jsonOutputPath)
  95. {
  96. var pythonExecutable = FindPythonExecutable();
  97. var scriptGuid = AssetDatabase.FindAssets("convert_scene").FirstOrDefault();
  98. if (string.IsNullOrEmpty(scriptGuid))
  99. {
  100. UnityEngine.Debug.LogError("Conversion script 'convert_scene.py' not found.");
  101. return false;
  102. }
  103. var scriptPath = Path.Combine(ProjectRoot, AssetDatabase.GUIDToAssetPath(scriptGuid));
  104. var absoluteAssetPath = Path.Combine(ProjectRoot, assetPath);
  105. var process = new Process
  106. {
  107. StartInfo = new ProcessStartInfo
  108. {
  109. FileName = pythonExecutable,
  110. Arguments = $"\"{scriptPath}\" \"{absoluteAssetPath}\" \"{jsonOutputPath}\"",
  111. RedirectStandardOutput = true,
  112. RedirectStandardError = true,
  113. UseShellExecute = false,
  114. CreateNoWindow = true
  115. }
  116. };
  117. process.Start();
  118. string error = process.StandardError.ReadToEnd();
  119. process.WaitForExit();
  120. if (process.ExitCode == 0) return true;
  121. UnityEngine.Debug.LogError($"Failed to convert {assetPath}. Error: {error}");
  122. return false;
  123. }
  124. /// <summary>
  125. /// Parses a temporary JSON file to extract unique component names.
  126. /// </summary>
  127. private IEnumerable<string> ParseComponentsFromJson(string jsonPath)
  128. {
  129. var components = new HashSet<string>();
  130. try
  131. {
  132. var jsonContent = File.ReadAllText(jsonPath);
  133. var jsonArray = JArray.Parse(jsonContent);
  134. foreach (var item in jsonArray)
  135. {
  136. var data = item["data"];
  137. if (data is JObject dataObject)
  138. {
  139. var componentName = dataObject.Properties().FirstOrDefault()?.Name;
  140. if (!string.IsNullOrEmpty(componentName))
  141. {
  142. components.Add(componentName);
  143. }
  144. }
  145. }
  146. }
  147. catch (Exception e)
  148. {
  149. UnityEngine.Debug.LogError($"Failed to parse JSON file {jsonPath}. Error: {e.Message}");
  150. }
  151. return components;
  152. }
  153. /// <summary>
  154. /// Saves the selected components to the ComponentWhitelistSettings asset.
  155. /// </summary>
  156. public void SaveWhitelist(Dictionary<string, bool> selection)
  157. {
  158. var settings = ComponentWhitelistSettings.GetOrCreateSettings();
  159. settings.WhitelistedComponents.Clear();
  160. settings.WhitelistedComponents.AddRange(selection.Where(kvp => kvp.Value).Select(kvp => kvp.Key));
  161. EditorUtility.SetDirty(settings);
  162. AssetDatabase.SaveAssets();
  163. EditorUtility.DisplayDialog("Success", $"Whitelist saved with {settings.WhitelistedComponents.Count} components.", "OK");
  164. }
  165. }
  166. }