diff --git a/.github/Images/SearchResults1Dark.png b/.github/Images/SearchResults1Dark.png new file mode 100644 index 0000000..f83cb82 Binary files /dev/null and b/.github/Images/SearchResults1Dark.png differ diff --git a/.github/Images/SearchResults1Light.png b/.github/Images/SearchResults1Light.png new file mode 100644 index 0000000..38dce15 Binary files /dev/null and b/.github/Images/SearchResults1Light.png differ diff --git a/.github/Images/SearchResults2Dark.png b/.github/Images/SearchResults2Dark.png new file mode 100644 index 0000000..54210b2 Binary files /dev/null and b/.github/Images/SearchResults2Dark.png differ diff --git a/.github/Images/SearchResults2Light.png b/.github/Images/SearchResults2Light.png new file mode 100644 index 0000000..2001ea3 Binary files /dev/null and b/.github/Images/SearchResults2Light.png differ diff --git a/.github/Images/Settings.png b/.github/Images/Settings.png new file mode 100644 index 0000000..4a52b3f Binary files /dev/null and b/.github/Images/Settings.png differ diff --git a/.github/README.md b/.github/README.md index 3c1d592..9f76e60 100644 --- a/.github/README.md +++ b/.github/README.md @@ -1,6 +1,6 @@ # Asset Usage Detector for Unity 3D -![screenshot1](screenshots/img1.png) +![Settings](Images/Settings.png) **Available on Asset Store:** https://assetstore.unity.com/packages/tools/utilities/asset-usage-detector-112837 @@ -12,7 +12,7 @@ ## ABOUT -This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode! +This tool helps you find usages of the selected asset(s) and/or scene object(s), i.e. lists the objects that refer to them. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode! ## INSTALLATION @@ -30,20 +30,17 @@ There are 5 ways to install this plugin: - Open **Window - Asset Usage Detector** window, configure the settings and hit **GO!** - or, right click an object and select **Search For References** -- In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the references are formed. If a node's label contains text inside square brackets (e.g. *\[Child object\]*), then that text describes how that node is connected to the node to its left +- To learn how to interpret the search results and for more instructions, please see the included [README.txt](Plugins/AssetUsageDetector/README.txt) file +- You can tweak most settings/colors via *Project Settings/yasirkula/Asset Usage Detector* page (on older versions, this menu is located at *Preferences* window) -## FEATURES +![SearchResults1](Images/SearchResults1Dark.png) -- You can search for references of any object that extends *UnityEngine.Object* -- Extensive search algorithm that uses *SerializedObject* and *reflection* to find references -- Can search in multiple scenes at once -- Can show complete paths to the references or only the most relevant parts of the paths (see the demonstration below) - -![screenshot2](screenshots/img2.gif) +![SearchResults2](Images/SearchResults2Dark.png) ## KNOWN LIMITATIONS - *Addressables* aren't supported - *static* variables aren't searched +- *Resources.Load* usages can't be found - *GUIText* materials aren't searched - Textures in *Lens Flares* can't be searched diff --git a/.github/screenshots/img1.png b/.github/screenshots/img1.png deleted file mode 100644 index c830e91..0000000 Binary files a/.github/screenshots/img1.png and /dev/null differ diff --git a/.github/screenshots/img2.gif b/.github/screenshots/img2.gif deleted file mode 100644 index 450feff..0000000 Binary files a/.github/screenshots/img2.gif and /dev/null differ diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs index c13590b..f9d2f5c 100644 --- a/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetector.cs @@ -19,7 +19,6 @@ namespace AssetUsageDetectorNamespace { [Flags] public enum SceneSearchMode { None = 0, OpenScenes = 1, ScenesInBuildSettingsAll = 2, ScenesInBuildSettingsTickedOnly = 4, AllScenes = 8 }; - public enum PathDrawingMode { Full = 0, ShortRelevantParts = 1, Shortest = 2 }; public partial class AssetUsageDetector { @@ -43,7 +42,12 @@ namespace AssetUsageDetectorNamespace public BindingFlags propertyModifiers = BindingFlags.Public | BindingFlags.NonPublic; public bool searchNonSerializableVariables = true; + public bool searchUnusedMaterialProperties = true; + public bool lazySceneSearch = true; + public bool calculateUnusedObjects = false; + public bool hideDuplicateRows = true; + public bool hideReduntantPrefabVariantLinks = true; public bool noAssetDatabaseChanges = false; public bool showDetailedProgressBar = true; } @@ -68,7 +72,8 @@ namespace AssetUsageDetectorNamespace private SearchResultGroup currentSearchResultGroup; // An optimization to search an object only once (key is a hash of the searched object) - private readonly Dictionary searchedObjects = new Dictionary( 32768 ); + private readonly Dictionary searchedObjects = new Dictionary( 4096 ); + private readonly Dictionary searchedUnityObjects = new Dictionary( 32768 ); // Unity objects use their instanceIDs as key which is more performant // Stack of SearchObject function parameters to avoid infinite loops (which happens when same object is passed as parameter to function) private readonly List callStack = new List( 64 ); @@ -78,6 +83,8 @@ namespace AssetUsageDetectorNamespace private Object currentSearchedObject; private int currentDepth; + private bool searchUnusedMaterialProperties; + private bool dontSearchInSourceAssets; private bool searchingSourceAssets; private bool isInPlayMode; @@ -101,13 +108,13 @@ namespace AssetUsageDetectorNamespace if( searchParameters == null ) { Debug.LogError( "'searchParameters' mustn't be null!" ); - return new SearchResult( false, null, null, this, searchParameters ); + return new SearchResult( false, null, null, null, this, searchParameters ); } if( searchParameters.objectsToSearch == null ) { - Debug.LogError( "'objectsToSearch' list (\"Find references of:\") is empty!" ); - return new SearchResult( false, null, null, this, searchParameters ); + Debug.LogError( "'objectsToSearch' list (\"SEARCHED OBJECTS\") is empty!" ); + return new SearchResult( false, null, null, null, this, searchParameters ); } #if UNITY_2018_3_OR_NEWER @@ -124,7 +131,7 @@ namespace AssetUsageDetectorNamespace { // Don't start the search if a prefab stage is currently open and dirty (not saved) Debug.LogError( "Save open prefab first!" ); - return new SearchResult( false, null, null, this, searchParameters ); + return new SearchResult( false, null, null, null, this, searchParameters ); } #if UNITY_2020_1_OR_NEWER @@ -148,7 +155,7 @@ namespace AssetUsageDetectorNamespace if( !isInPlayMode && !Utilities.AreScenesSaved() && !EditorUtility.DisplayDialog( "Asset Usage Detector", "Some scene(s) aren't saved. This may result in incorrect search results in those scene(s). Proceed?", "Yes", "Cancel" ) ) { Debug.LogError( "Save open scene(s) first!" ); - return new SearchResult( false, null, null, this, searchParameters ); + return new SearchResult( false, null, null, null, this, searchParameters ); } // Get the scenes that are open right now @@ -169,8 +176,10 @@ namespace AssetUsageDetectorNamespace searchDepthLimit = searchParameters.searchDepthLimit; dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; + searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties; searchedObjects.Clear(); + searchedUnityObjects.Clear(); animationClipUniqueBindings.Clear(); callStack.Clear(); objectsToSearchSet.Clear(); @@ -329,7 +338,7 @@ namespace AssetUsageDetectorNamespace // Initialize the nodes of searched asset(s) foreach( Object obj in objectsToSearchSet ) - searchedObjects.Add( obj.Hash(), PopReferenceNode( obj ) ); + searchedUnityObjects.Add( obj.GetHashCode(), PopReferenceNode( obj ) ); // Progressbar values int searchProgress = 0; @@ -537,17 +546,26 @@ namespace AssetUsageDetectorNamespace searchingSourceAssets = false; } + EditorUtility.DisplayProgressBar( "Please wait...", "Post-processing search results", 1f ); + InitializeSearchResultNodes( searchResult ); + HashSet usedObjects = null; + if( searchResult.Count > 0 && searchParameters.calculateUnusedObjects ) + CalculateUnusedObjects( searchResult, out usedObjects ); + // Log some c00l stuff to console Debug.Log( "Searched " + searchedObjectsCount + " objects in " + ( EditorApplication.timeSinceStartup - searchStartTime ).ToString( "F2" ) + " seconds" ); - return new SearchResult( true, searchResult, initialSceneSetup, this, searchParameters ); + return new SearchResult( true, searchResult, usedObjects, initialSceneSetup, this, searchParameters ); } catch( Exception e ) { - StringBuilder sb = new StringBuilder( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 ); - sb.AppendLine( "AssetUsageDetector Error: The following Exception is thrown during the search. Details:" ).AppendLine(); + StringBuilder sb = Utilities.stringBuilder; + sb.Length = 0; + sb.EnsureCapacity( objectsToSearchSet.Count * 50 + callStack.Count * 50 + 500 ); + + sb.AppendLine( "AssetUsageDetector Error: The following Exception is thrown during the search. Details:" ); Object latestUnityObjectInCallStack = AppendCallStackToStringBuilder( sb ); @@ -568,7 +586,7 @@ namespace AssetUsageDetectorNamespace catch { } - return new SearchResult( false, searchResult, initialSceneSetup, this, searchParameters ); + return new SearchResult( false, searchResult, null, initialSceneSetup, this, searchParameters ); } finally { @@ -611,13 +629,168 @@ namespace AssetUsageDetectorNamespace private void InitializeSearchResultNodes( List searchResult ) { for( int i = 0; i < searchResult.Count; i++ ) - searchResult[i].InitializeNodes( GetReferenceNode, objectsToSearchSet ); - - // If there are any empty groups after node initialization, remove those groups - for( int i = searchResult.Count - 1; i >= 0; i-- ) { + searchResult[i].InitializeNodes( objectsToSearchSet ); + + // Remove empty search result groups if( !searchResult[i].PendingSearch && searchResult[i].NumberOfReferences == 0 ) - searchResult.RemoveAtFast( i ); + searchResult.RemoveAt( i-- ); + } + } + + private void CalculateUnusedObjects( List searchResult, out HashSet usedObjectsSet ) + { + currentSearchResultGroup = new SearchResultGroup( "Unused Objects", SearchResultGroup.GroupType.UnusedObjects, false, false ); + + usedObjectsSet = new HashSet(); + HashSet usedObjectPathsSet = new HashSet(); // For assets: stores the filepaths, For scene objects: stores the topmost GameObject's instanceID + foreach( SearchResultGroup searchResultGroup in searchResult ) + { + for( int j = 0; j < searchResultGroup.NumberOfReferences; j++ ) + { + Object obj = searchResultGroup[j].UnityObject; + if( obj is Component ) + obj = ( (Component) obj ).gameObject; + + if( usedObjectsSet.Add( obj ) ) + { + string assetPath = AssetDatabase.GetAssetPath( obj ); + if( !string.IsNullOrEmpty( assetPath ) ) + usedObjectPathsSet.Add( assetPath ); + else + { + for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent ) + usedObjectPathsSet.Add( parent.gameObject.GetHashCode().ToString() ); + } + } + } + } + + Dictionary unusedMainObjectNodes = new Dictionary( objectsToSearchSet.Count - usedObjectsSet.Count ); + Dictionary> unusedSubObjectNodes = new Dictionary>( objectsToSearchSet.Count - usedObjectsSet.Count ); + foreach( Object obj in objectsToSearchSet ) + { + // Omit components, their GameObjects are already included in search + if( obj is Component ) + continue; + + // Omit assets that are invisible in Hierarchy/Inspector + if( ( obj.hideFlags & ( HideFlags.HideInInspector | HideFlags.HideInHierarchy ) ) != HideFlags.None ) + continue; + + if( usedObjectsSet.Contains( obj ) ) + continue; + + string assetPath = AssetDatabase.GetAssetPath( obj ); + GameObject searchedTopmostGameObject = null; + if( obj is GameObject ) + { + if( string.IsNullOrEmpty( assetPath ) ) + { + for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent ) + { + if( objectsToSearchSet.Contains( parent ) && !usedObjectsSet.Contains( parent.gameObject ) ) + searchedTopmostGameObject = parent.gameObject; + } + } + else + { + for( Transform parent = ( (GameObject) obj ).transform.parent; parent != null; parent = parent.parent ) + { + if( objectsToSearchSet.Contains( parent ) ) + { + searchedTopmostGameObject = parent.gameObject; + break; + } + } + } + + if( searchedTopmostGameObject && !string.IsNullOrEmpty( assetPath ) ) // Omit GameObject assets if their parent objects are already included in search + continue; + } + + // Omit meshes of an imported model asset + if( obj is Mesh && !string.IsNullOrEmpty( assetPath ) && AssetDatabase.GetMainAssetTypeAtPath( assetPath ) == typeof( GameObject ) && objectsToSearchSet.Contains( AssetDatabase.LoadMainAssetAtPath( assetPath ) ) ) + continue; + + // Omit MonoScripts whose types can't be determined + if( obj is MonoScript && ( (MonoScript) obj ).GetClass() == null ) + continue; + + // Use new ReferenceNodes in UnusedObjects search result group because we don't want these nodes to be linked to the actual ReferenceNodes in any way + // (i.e. we don't use actual ReferenceNodes of these objects (GetReferenceNode) because these may have links to other nodes in unknown circumstances) + ReferenceNode node = PopReferenceNode( obj ); + node.usedState = ReferenceNode.UsedState.Unused; + + if( string.IsNullOrEmpty( assetPath ) ) + { + if( !searchedTopmostGameObject ) + { + if( obj is GameObject ) + unusedMainObjectNodes[obj.GetHashCode().ToString()] = node; + else + currentSearchResultGroup.AddReference( node ); + } + else // List child GameObject scene objects under their parent GameObject + { + string dictionaryKey = searchedTopmostGameObject.GetHashCode().ToString(); + List unusedSubObjectNodesAtPath; + if( !unusedSubObjectNodes.TryGetValue( dictionaryKey, out unusedSubObjectNodesAtPath ) ) + unusedSubObjectNodes[dictionaryKey] = unusedSubObjectNodesAtPath = new List( 2 ); + + unusedSubObjectNodesAtPath.Add( node ); + } + } + else + { + if( AssetDatabase.IsMainAsset( obj ) ) + unusedMainObjectNodes[assetPath] = node; + else + { + List unusedSubObjectNodesAtPath; + if( !unusedSubObjectNodes.TryGetValue( assetPath, out unusedSubObjectNodesAtPath ) ) + unusedSubObjectNodes[assetPath] = unusedSubObjectNodesAtPath = new List( 2 ); + + unusedSubObjectNodesAtPath.Add( node ); + } + } + } + + foreach( KeyValuePair kvPair in unusedMainObjectNodes ) + { + List unusedSubAssetNodesAtPath; + if( unusedSubObjectNodes.TryGetValue( kvPair.Key, out unusedSubAssetNodesAtPath ) ) + { + currentSearchResultGroup.AddReference( kvPair.Value ); + for( int i = 0; i < unusedSubAssetNodesAtPath.Count; i++ ) + kvPair.Value.AddLinkTo( unusedSubAssetNodesAtPath[i] ); + + if( usedObjectPathsSet.Contains( kvPair.Key ) ) + kvPair.Value.usedState = ReferenceNode.UsedState.MixedCollapsed; + + unusedSubObjectNodes.Remove( kvPair.Key ); + } + else if( !usedObjectPathsSet.Contains( kvPair.Key ) ) // If a main asset has sub-assets and all of them are used, consider the main asset as used, as well (especially useful for Sprite assets) + currentSearchResultGroup.AddReference( kvPair.Value ); + else if( !AssetDatabase.Contains( (Object) kvPair.Value.nodeObject ) ) + { + currentSearchResultGroup.AddReference( kvPair.Value ); + kvPair.Value.usedState = ReferenceNode.UsedState.MixedCollapsed; + } + } + + foreach( KeyValuePair> kvPair in unusedSubObjectNodes ) // These aren't linked to any unusedMainObjectNodes, add them as root nodes to the search result group + { + foreach( ReferenceNode node in kvPair.Value ) + currentSearchResultGroup.AddReference( node ); + } + + if( currentSearchResultGroup.NumberOfReferences > 0 ) + { + for( int i = 0; i < currentSearchResultGroup.NumberOfReferences; i++ ) + currentSearchResultGroup[i].InitializeRecursively(); + + searchResult.Insert( 0, currentSearchResultGroup ); } } @@ -807,18 +980,12 @@ namespace AssetUsageDetectorNamespace bool searchingSourceAsset = searchingSourceAssets && ReferenceEquals( currentSearchedObject, obj ); // Hashing does not work well with structs all the time, don't cache search results for structs - string objHash = null; - if( !( obj is ValueType ) ) + if( !( obj is ValueType ) && !searchingSourceAsset ) { - objHash = obj.Hash(); - - if( !searchingSourceAsset ) - { - // If object was searched before, return the cached result - ReferenceNode cachedResult; - if( searchedObjects.TryGetValue( objHash, out cachedResult ) ) - return cachedResult; - } + // If object was searched before, return the cached result + ReferenceNode cachedResult; + if( TryGetReferenceNode( obj, out cachedResult ) ) + return cachedResult; } searchedObjectsCount++; @@ -833,14 +1000,14 @@ namespace AssetUsageDetectorNamespace { if( assetsToSearchSet.Count == 0 ) { - searchedObjects.Add( objHash, null ); + searchedUnityObjects.Add( unityObject.GetHashCode(), null ); return null; } assetPath = AssetDatabase.GetAssetPath( unityObject ); - if( !AssetHasAnyReference( assetPath ) ) + if( excludedAssetsPathsSet.Contains( assetPath ) || !AssetHasAnyReference( assetPath ) ) { - searchedObjects.Add( objHash, null ); + searchedUnityObjects.Add( unityObject.GetHashCode(), null ); return null; } } @@ -874,7 +1041,7 @@ namespace AssetUsageDetectorNamespace for( int i = 0; i < prefabChildren.Length; i++ ) { if( prefabChildren[i].gameObject != prefabGameObject ) - result.AddLinkTo( SearchObject( prefabChildren[i].gameObject ) ); + result.AddLinkTo( SearchObject( prefabChildren[i].gameObject ), isWeakLink: true ); } } @@ -905,13 +1072,18 @@ namespace AssetUsageDetectorNamespace // Cache the search result if we are skimming through a class (not a struct; i.e. objHash != null) // and if the object is a UnityEngine.Object (if not, cache the result only if we have actually found something // or we are at the root of the search; i.e. currentDepth == 0) - if( objHash != null && ( result != null || unityObject != null || currentDepth == 0 ) ) + if( !( obj is ValueType ) && ( result != null || unityObject != null || currentDepth == 0 ) ) { if( !searchingSourceAsset ) - searchedObjects.Add( objHash, result ); + { + if( obj is Object ) + searchedUnityObjects.Add( unityObject.GetHashCode(), result ); + else + searchedObjects.Add( GetNodeObjectHash( obj ), result ); + } else if( result != null ) { - result.CopyReferencesTo( searchedObjects[objHash] ); + result.CopyReferencesTo( searchedUnityObjects[unityObject.GetHashCode()] ); PoolReferenceNode( result ); } } @@ -963,7 +1135,10 @@ namespace AssetUsageDetectorNamespace // if that happens, log useful information to help reproduce the issue if( lastRefreshedCacheEntry == cacheEntry ) { - StringBuilder sb = new StringBuilder( 1000 ); + StringBuilder sb = Utilities.stringBuilder; + sb.Length = 0; + sb.EnsureCapacity( 1000 ); + sb.AppendLine( "Infinite loop while refreshing a cache entry, please report it to the author." ).AppendLine(); sb.Append( "Asset path: " ).AppendLine( assetPath ); @@ -1032,15 +1207,42 @@ namespace AssetUsageDetectorNamespace return false; } + // If object was already searched, return its ReferenceNode + private bool TryGetReferenceNode( object nodeObject, out ReferenceNode referenceNode ) + { + if( nodeObject is Object ) + { + if( searchedUnityObjects.TryGetValue( nodeObject.GetHashCode(), out referenceNode ) ) + return true; + } + else if( searchedObjects.TryGetValue( GetNodeObjectHash( nodeObject ), out referenceNode ) ) + return true; + + referenceNode = null; + return false; + } + // Get reference node for object private ReferenceNode GetReferenceNode( object nodeObject ) { ReferenceNode result; - string hash = nodeObject.Hash(); - if( !searchedObjects.TryGetValue( hash, out result ) || result == null ) + if( nodeObject is Object ) { - result = PopReferenceNode( nodeObject ); - searchedObjects[hash] = result; + int hash = nodeObject.GetHashCode(); + if( !searchedUnityObjects.TryGetValue( hash, out result ) || result == null ) + { + result = PopReferenceNode( nodeObject ); + searchedUnityObjects[hash] = result; + } + } + else + { + string hash = GetNodeObjectHash( nodeObject ); + if( !searchedObjects.TryGetValue( hash, out result ) || result == null ) + { + result = PopReferenceNode( nodeObject ); + searchedObjects[hash] = result; + } } return result; @@ -1070,6 +1272,12 @@ namespace AssetUsageDetectorNamespace nodesPool.Add( node ); } + // Get a unique-ish string hash code for a plain C# object (i.e. non-UnityEngine.Object object) + private string GetNodeObjectHash( object nodeObject ) + { + return nodeObject.GetHashCode() + nodeObject.GetType().Name; + } + // Retrieve the game objects listed under the DontDestroyOnLoad scene private GameObject[] GetDontDestroyOnLoadObjects() { diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs index 588f1b8..b4b98bd 100644 --- a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSearchFunctions.cs @@ -166,6 +166,10 @@ namespace AssetUsageDetectorNamespace private readonly Dictionary typeToVariables = new Dictionary( 4096 ); private readonly List validVariables = new List( 32 ); + // All MonoScripts in objectsToSearchSet + private readonly List monoScriptsToSearch = new List(); + private readonly List monoScriptsToSearchTypes = new List(); + // Path(s) of .cginc, .cg, .hlsl and .glslinc assets in assetsToSearchSet private readonly HashSet shaderIncludesToSearchSet = new HashSet(); @@ -179,8 +183,6 @@ namespace AssetUsageDetectorNamespace private bool searchPrefabConnections; private bool searchMonoBehavioursForScript; - private bool searchRenderers; - private bool searchMaterialsForShader; private bool searchTextureReferences; #if UNITY_2018_1_OR_NEWER private bool searchShaderGraphsForSubGraphs; @@ -255,8 +257,6 @@ namespace AssetUsageDetectorNamespace searchPrefabConnections = false; searchMonoBehavioursForScript = false; - searchRenderers = false; - searchMaterialsForShader = false; searchTextureReferences = false; #if UNITY_2018_1_OR_NEWER searchShaderGraphsForSubGraphs = false; @@ -264,19 +264,18 @@ namespace AssetUsageDetectorNamespace foreach( Object obj in objectsToSearchSet ) { - if( obj is Texture ) - { - searchRenderers = true; + if( obj is Texture || obj is Sprite ) searchTextureReferences = true; - } - else if( obj is Material ) - searchRenderers = true; else if( obj is MonoScript ) - searchMonoBehavioursForScript = true; - else if( obj is Shader ) { - searchRenderers = true; - searchMaterialsForShader = true; + searchMonoBehavioursForScript = true; + + Type monoScriptType = ( (MonoScript) obj ).GetClass(); + if( monoScriptType != null && !monoScriptType.IsSealed ) + { + monoScriptsToSearch.Add( (MonoScript) obj ); + monoScriptsToSearchTypes.Add( monoScriptType ); + } } else if( obj is GameObject ) searchPrefabConnections = true; @@ -286,6 +285,13 @@ namespace AssetUsageDetectorNamespace #endif } + // We need to search for class/interface inheritance references manually because AssetDatabase.GetDependencies doesn't take that into account + if( monoScriptsToSearch.Count > 0 ) + { + alwaysSearchedExtensionsSet.Add( "cs" ); + alwaysSearchedExtensionsSet.Add( "dll" ); + } + foreach( string path in assetsToSearchPathsSet ) { string extension = Utilities.GetFileExtension( path ); @@ -365,7 +371,7 @@ namespace AssetUsageDetectorNamespace // Search through all the components of the object Component[] components = go.GetComponents(); for( int i = 0; i < components.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( components[i] ) ); + referenceNode.AddLinkTo( SearchObject( components[i] ), isWeakLink: true ); return referenceNode; } @@ -383,19 +389,13 @@ namespace AssetUsageDetectorNamespace if( searchMonoBehavioursForScript && component is MonoBehaviour ) { // If a searched asset is script, check if this component is an instance of it + // Although SearchVariablesWithSerializedObject can detect these references with SerializedObject, it isn't possible when reflection is used in Play mode MonoScript script = MonoScript.FromMonoBehaviour( (MonoBehaviour) component ); if( objectsToSearchSet.Contains( script ) ) referenceNode.AddLinkTo( GetReferenceNode( script ) ); } - else if( searchRenderers && component is Renderer ) - { - // If an asset is a shader, texture or material, and this component is a Renderer, - // search it for references - Material[] materials = ( (Renderer) component ).sharedMaterials; - for( int i = 0; i < materials.Length; i++ ) - referenceNode.AddLinkTo( SearchObject( materials[i] ) ); - } - else if( component is Animation ) + + if( component is Animation ) { // Search animation clips for references foreach( AnimationState anim in (Animation) component ) @@ -445,28 +445,55 @@ namespace AssetUsageDetectorNamespace private ReferenceNode SearchMaterial( Object unityObject ) { + const string TEXTURE_PROPERTY_PREFIX = "m_SavedProperties.m_TexEnvs["; + Material material = (Material) unityObject; ReferenceNode referenceNode = PopReferenceNode( material ); - if( searchMaterialsForShader && objectsToSearchSet.Contains( material.shader ) ) - referenceNode.AddLinkTo( GetReferenceNode( material.shader ), "Shader" ); + // We used to search only the shader and the Texture properties in this function but it has changed for 2 major reasons: + // 1) Materials can store more than these references now. For example, HDRP materials can have references to other HDRP materials + // 2) It wasn't possible to search Texture properties that were no longer used by the shader + // Thus, we are searching every property of the material using SerializedObject + SearchVariablesWithSerializedObject( referenceNode ); - if( searchTextureReferences ) + // Post-process the found results and convert links that start with TEXTURE_PROPERTY_PREFIX to their readable names + SerializedObject materialSO = null; + for( int i = referenceNode.NumberOfOutgoingLinks - 1; i >= 0; i-- ) { - // Search through all the textures attached to this material - // Credit: http://answers.unity3d.com/answers/1116025/view.html - Shader shader = material.shader; - int shaderPropertyCount = ShaderUtil.GetPropertyCount( shader ); - for( int i = 0; i < shaderPropertyCount; i++ ) + List linkDescriptions = referenceNode[i].descriptions; + for( int j = linkDescriptions.Count - 1; j >= 0; j-- ) { - if( ShaderUtil.GetPropertyType( shader, i ) == ShaderUtil.ShaderPropertyType.TexEnv ) + int texturePropertyPrefixIndex = linkDescriptions[j].IndexOf( TEXTURE_PROPERTY_PREFIX ); + if( texturePropertyPrefixIndex >= 0 ) { - string propertyName = ShaderUtil.GetPropertyName( shader, i ); - Texture assignedTexture = material.GetTexture( propertyName ); - if( objectsToSearchSet.Contains( assignedTexture ) ) - referenceNode.AddLinkTo( GetReferenceNode( assignedTexture ), "Shader property: " + propertyName ); + texturePropertyPrefixIndex += TEXTURE_PROPERTY_PREFIX.Length; + int texturePropertyEndIndex = linkDescriptions[j].IndexOf( ']', texturePropertyPrefixIndex ); + if( texturePropertyEndIndex > texturePropertyPrefixIndex ) + { + int texturePropertyIndex; + if( int.TryParse( linkDescriptions[j].Substring( texturePropertyPrefixIndex, texturePropertyEndIndex - texturePropertyPrefixIndex ), out texturePropertyIndex ) ) + { + if( materialSO == null ) + materialSO = new SerializedObject( material ); + + string propertyName = materialSO.FindProperty( "m_SavedProperties.m_TexEnvs.Array.data[" + texturePropertyIndex + "].first" ).stringValue; + if( material.HasProperty( propertyName ) ) + linkDescriptions[j] = "[Property: " + propertyName + "]"; + else if( searchUnusedMaterialProperties ) + { + // Move unused references to the end of the list so that used references come first + linkDescriptions.Add( "[Property (UNUSED): " + propertyName + "]" ); + linkDescriptions.RemoveAt( j ); + } + else + linkDescriptions.RemoveAt( j ); + } + } } } + + if( linkDescriptions.Count == 0 ) // All shader properties were unused and we weren't searching for unused material properties + referenceNode.RemoveLink( i ); } return referenceNode; @@ -520,7 +547,7 @@ namespace AssetUsageDetectorNamespace return referenceNode; } - // Searches default UnityEngine.Object values assigned to script variables + // Searches class/interface inheritances and default UnityEngine.Object values assigned to script variables private ReferenceNode SearchMonoScript( Object unityObject ) { MonoScript script = (MonoScript) unityObject; @@ -528,20 +555,27 @@ namespace AssetUsageDetectorNamespace if( scriptType == null || ( !scriptType.IsSubclassOf( typeof( MonoBehaviour ) ) && !scriptType.IsSubclassOf( typeof( ScriptableObject ) ) ) ) return null; - MonoImporter scriptImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( unityObject ) ) as MonoImporter; - if( scriptImporter == null ) - return null; - ReferenceNode referenceNode = PopReferenceNode( script ); - VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType ); - for( int i = 0; i < variables.Length; i++ ) + // Check for class/interface inheritance references + for( int i = monoScriptsToSearch.Count - 1; i >= 0; i-- ) { - if( variables[i].isSerializable && !variables[i].isProperty ) + if( monoScriptsToSearchTypes[i] != scriptType && monoScriptsToSearchTypes[i].IsAssignableFrom( scriptType ) ) + referenceNode.AddLinkTo( GetReferenceNode( monoScriptsToSearch[i] ), monoScriptsToSearchTypes[i].IsInterface ? "Implements interface" : "Extends class" ); + } + + MonoImporter scriptImporter = AssetImporter.GetAtPath( AssetDatabase.GetAssetPath( unityObject ) ) as MonoImporter; + if( scriptImporter != null ) + { + VariableGetterHolder[] variables = GetFilteredVariablesForType( scriptType ); + for( int i = 0; i < variables.Length; i++ ) { - Object defaultValue = scriptImporter.GetDefaultReference( variables[i].name ); - if( objectsToSearchSet.Contains( defaultValue ) ) - referenceNode.AddLinkTo( GetReferenceNode( defaultValue ), "Default variable value: " + variables[i].name ); + if( variables[i].isSerializable && !variables[i].isProperty ) + { + Object defaultValue = scriptImporter.GetDefaultReference( variables[i].name ); + if( objectsToSearchSet.Contains( defaultValue ) ) + referenceNode.AddLinkTo( GetReferenceNode( defaultValue ), "Default variable value: " + variables[i].name ); + } } } @@ -712,7 +746,7 @@ namespace AssetUsageDetectorNamespace if( packedAsset is Texture ) { - // Search the Texture's sprites if the Texture asset isn't included in the "Find references of:" list (i.e. user has + // Search the Texture's sprites if the Texture asset isn't included in the "SEARCHED OBJECTS" list (i.e. user has // added only a Sprite sub-asset of the Texture to the list, not the Texture asset itself). Otherwise, references to // both the Texture and its sprites will be found which can be considered as duplicate references if( AssetDatabase.IsMainAsset( packedAsset ) && !assetsToSearchSet.Contains( packedAsset ) ) @@ -1155,7 +1189,10 @@ namespace AssetUsageDetectorNamespace catch( Exception e ) { // Unknown exceptions usually occur when variableValue is an IEnumerable and its enumerator throws an unhandled exception in MoveNext or Current - StringBuilder sb = new StringBuilder( callStack.Count * 50 + 1000 ); + StringBuilder sb = Utilities.stringBuilder; + sb.Length = 0; + sb.EnsureCapacity( callStack.Count * 50 + 1000 ); + sb.Append( "Skipped searching " ).Append( referenceNode.nodeObject.GetType().FullName ).Append( "." ).Append( variables[i].name ).AppendLine( " because it threw exception:" ).Append( e ).AppendLine(); Object latestUnityObjectInCallStack = AppendCallStackToStringBuilder( sb ); @@ -1270,10 +1307,6 @@ namespace AssetUsageDetectorNamespace #endif typeof( Collider2D ).IsAssignableFrom( currType ) ) ) continue; - // "sharedMaterials" are searched via SearchComponent, no need to search it with reflection, as well - else if( typeof( Renderer ).IsAssignableFrom( currType ) && - ( propertyName == "sharedMaterial" || propertyName == "sharedMaterials" ) ) - continue; // Ignore "parameters" property of Animator since it doesn't contain any useful data and logs a warning to the console when Animator is inactive else if( typeof( Animator ).IsAssignableFrom( currType ) && propertyName == "parameters" ) continue; diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSettings.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSettings.cs new file mode 100644 index 0000000..f4d2184 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSettings.cs @@ -0,0 +1,275 @@ +using UnityEditor; +using UnityEngine; + +namespace AssetUsageDetectorNamespace +{ + public static class AssetUsageDetectorSettings + { + private static readonly GUILayoutOption GL_WIDTH_60 = GUILayout.Width( 60f ); + + #region Colors + private static Color? m_settingsHeaderColor = null; + public static Color SettingsHeaderColor + { + get { if( m_settingsHeaderColor == null ) m_settingsHeaderColor = GetColor( "AUD_SettingsHeaderTint", Color.cyan ); return m_settingsHeaderColor.Value; } + set { if( m_settingsHeaderColor == value ) return; m_settingsHeaderColor = value; SetColor( "AUD_SettingsHeaderTint", value ); } + } + + private static Color? m_searchResultGroupHeaderColor = null; + public static Color SearchResultGroupHeaderColor + { + get { if( m_searchResultGroupHeaderColor == null ) m_searchResultGroupHeaderColor = GetColor( "AUD_ResultGroupHeaderTint", Color.cyan ); return m_searchResultGroupHeaderColor.Value; } + set { if( m_searchResultGroupHeaderColor == value ) return; m_searchResultGroupHeaderColor = value; SetColor( "AUD_ResultGroupHeaderTint", value ); } + } + + private static Color? m_rootRowsBackgroundColor = null; + public static Color RootRowsBackgroundColor + { + get { if( m_rootRowsBackgroundColor == null ) m_rootRowsBackgroundColor = GetColor( "AUD_RootRowsTint", EditorGUIUtility.isProSkin ? new Color( 0f, 1f, 1f, 0.15f ) : new Color( 0f, 1f, 1f, 0.25f ) ); return m_rootRowsBackgroundColor.Value; } + set { if( m_rootRowsBackgroundColor == value ) return; m_rootRowsBackgroundColor = value; SetColor( "AUD_RootRowsTint", value ); } + } + + private static Color? m_rootRowsBorderColor = null; + public static Color RootRowsBorderColor + { + get { if( m_rootRowsBorderColor == null ) m_rootRowsBorderColor = GetColor( "AUD_RootRowsBorderColor", EditorGUIUtility.isProSkin ? new Color( 0.15f, 0.15f, 0.15f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) ); return m_rootRowsBorderColor.Value; } + set { if( m_rootRowsBorderColor == value ) return; m_rootRowsBorderColor = value; SetColor( "AUD_RootRowsBorderColor", value ); } + } + + private static Color? m_mainReferencesBackgroundColor = null; + public static Color MainReferencesBackgroundColor + { + get { if( m_mainReferencesBackgroundColor == null ) m_mainReferencesBackgroundColor = GetColor( "AUD_MainRefRowsTint", EditorGUIUtility.isProSkin ? new Color( 0f, 0.35f, 0f, 1f ) : new Color( 0.25f, 0.75f, 0.25f, 1f ) ); return m_mainReferencesBackgroundColor.Value; } + set { if( m_mainReferencesBackgroundColor == value ) return; m_mainReferencesBackgroundColor = value; SetColor( "AUD_MainRefRowsTint", value ); } + } + + private static Color? m_selectedRowsParentTint = null; + public static Color SelectedRowParentsTint + { + get { if( m_selectedRowsParentTint == null ) m_selectedRowsParentTint = GetColor( "AUD_SelectedRowParentsTint", EditorGUIUtility.isProSkin ? new Color( 0.36f, 0.36f, 0.18f, 1f ) : new Color( 0.825f, 0.825f, 0.55f, 1f ) ); return m_selectedRowsParentTint.Value; } + set { if( m_selectedRowsParentTint == value ) return; m_selectedRowsParentTint = value; SetColor( "AUD_SelectedRowParentsTint", value ); } + } + + private static Color? m_selectedRowOccurrencesColor = null; + public static Color SelectedRowOccurrencesColor + { + get { if( m_selectedRowOccurrencesColor == null ) m_selectedRowOccurrencesColor = GetColor( "AUD_SelectedRowOccurrencesTint", EditorGUIUtility.isProSkin ? new Color( 0f, 0.3f, 0.75f, 1f ) : new Color( 0.25f, 0.75f, 1f, 1f ) ); return m_selectedRowOccurrencesColor.Value; } + set { if( m_selectedRowOccurrencesColor == value ) return; m_selectedRowOccurrencesColor = value; SetColor( "AUD_SelectedRowOccurrencesTint", value ); } + } + + private static Color? m_treeLinesColor = null; + public static Color TreeLinesColor + { + get { if( m_treeLinesColor == null ) m_treeLinesColor = GetColor( "AUD_TreeLinesColor", EditorGUIUtility.isProSkin ? new Color( 0.65f, 0.65f, 0.65f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) ); return m_treeLinesColor.Value; } + set { if( m_treeLinesColor == value ) return; m_treeLinesColor = value; SetColor( "AUD_TreeLinesColor", value ); } + } + + private static Color? m_highlightedTreeLinesColor = null; + public static Color HighlightedTreeLinesColor + { + get { if( m_highlightedTreeLinesColor == null ) m_highlightedTreeLinesColor = GetColor( "AUD_HighlightTreeLinesColor", Color.cyan ); return m_highlightedTreeLinesColor.Value; } + set { if( m_highlightedTreeLinesColor == value ) return; m_highlightedTreeLinesColor = value; SetColor( "AUD_HighlightTreeLinesColor", value ); } + } + + private static Color? m_searchMatchingTextColor = null; + public static Color SearchMatchingTextColor + { + get { if( m_searchMatchingTextColor == null ) m_searchMatchingTextColor = GetColor( "AUD_SearchTextColor", Color.red ); return m_searchMatchingTextColor.Value; } + set { if( m_searchMatchingTextColor == value ) return; m_searchMatchingTextColor = value; SetColor( "AUD_SearchTextColor", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged( highlightedSearchTextColorChanged: true ) ); } + } + + private static Color? m_tooltipDescriptionTextColor = null; + public static Color TooltipDescriptionTextColor + { + get { if( m_tooltipDescriptionTextColor == null ) m_tooltipDescriptionTextColor = GetColor( "AUD_TooltipUsageTextColor", EditorGUIUtility.isProSkin ? new Color( 0f, 0.9f, 0.9f, 1f ) : new Color( 0.9f, 0f, 0f, 1f ) ); return m_tooltipDescriptionTextColor.Value; } + set { if( m_tooltipDescriptionTextColor == value ) return; m_tooltipDescriptionTextColor = value; SetColor( "AUD_TooltipUsageTextColor", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged( tooltipDescriptionsColorChanged: true ) ); } + } + #endregion + + #region Size Adjustments + private static float? m_extraRowHeight = null; + public static float ExtraRowHeight + { + get { if( m_extraRowHeight == null ) m_extraRowHeight = EditorPrefs.GetFloat( "AUD_ExtraRowHeight", 0f ); return m_extraRowHeight.Value; } + set { if( m_extraRowHeight == value ) return; m_extraRowHeight = value; EditorPrefs.SetFloat( "AUD_ExtraRowHeight", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged() ); } + } + #endregion + + #region Other Settings + private static bool? m_pingClickedObjects = null; + public static bool PingClickedObjects + { + get { if( m_pingClickedObjects == null ) m_pingClickedObjects = EditorPrefs.GetBool( "AUD_PingClickedObj", true ); return m_pingClickedObjects.Value; } + set { if( m_pingClickedObjects == value ) return; m_pingClickedObjects = value; EditorPrefs.SetBool( "AUD_PingClickedObj", value ); } + } + + private static bool? m_selectClickedObjects = null; + public static bool SelectClickedObjects + { + get { if( m_selectClickedObjects == null ) m_selectClickedObjects = EditorPrefs.GetBool( "AUD_SelectClickedObj", false ); return m_selectClickedObjects.Value; } + set { if( m_selectClickedObjects == value ) return; m_selectClickedObjects = value; EditorPrefs.SetBool( "AUD_SelectClickedObj", value ); } + } + + private static bool? m_selectDoubleClickedObjects = null; + public static bool SelectDoubleClickedObjects + { + get { if( m_selectDoubleClickedObjects == null ) m_selectDoubleClickedObjects = EditorPrefs.GetBool( "AUD_SelectDoubleClickedObj", true ); return m_selectDoubleClickedObjects.Value; } + set { if( m_selectDoubleClickedObjects == value ) return; m_selectDoubleClickedObjects = value; EditorPrefs.SetBool( "AUD_SelectDoubleClickedObj", value ); } + } + + private static bool? m_showUnityTooltip = null; + public static bool ShowUnityTooltip + { + get { if( m_showUnityTooltip == null ) m_showUnityTooltip = EditorPrefs.GetBool( "AUD_ShowUnityTooltip", false ); return m_showUnityTooltip.Value; } + set { if( m_showUnityTooltip == value ) return; m_showUnityTooltip = value; EditorPrefs.SetBool( "AUD_ShowUnityTooltip", value ); } + } + + private static bool? m_showCustomTooltip = null; + public static bool ShowCustomTooltip + { + get { if( m_showCustomTooltip == null ) m_showCustomTooltip = EditorPrefs.GetBool( "AUD_ShowCustomTooltip", true ); return m_showCustomTooltip.Value; } + set { if( m_showCustomTooltip == value ) return; m_showCustomTooltip = value; EditorPrefs.SetBool( "AUD_ShowCustomTooltip", value ); ForEachAssetUsageDetectorWindow( ( window ) => window.OnSettingsChanged() ); } + } + + private static float? m_customTooltipDelay = null; + public static float CustomTooltipDelay + { + get { if( m_customTooltipDelay == null ) m_customTooltipDelay = EditorPrefs.GetFloat( "AUD_CustomTooltipDelay", 0.7f ); return m_customTooltipDelay.Value; } + set { if( m_customTooltipDelay == value ) return; m_customTooltipDelay = value; EditorPrefs.SetFloat( "AUD_CustomTooltipDelay", value ); } + } + + private static bool? m_showTreeLines = null; + public static bool ShowTreeLines + { + get { if( m_showTreeLines == null ) m_showTreeLines = EditorPrefs.GetBool( "AUD_ShowTreeLines", true ); return m_showTreeLines.Value; } + set { if( m_showTreeLines == value ) return; m_showTreeLines = value; EditorPrefs.SetBool( "AUD_ShowTreeLines", value ); } + } + + private static bool? m_applySelectedRowParentsTintToRootRows = null; + public static bool ApplySelectedRowParentsTintToRootRows + { + get { if( m_applySelectedRowParentsTintToRootRows == null ) m_applySelectedRowParentsTintToRootRows = EditorPrefs.GetBool( "AUD_SelectedRowParentsTintAtRoot", true ); return m_applySelectedRowParentsTintToRootRows.Value; } + set { if( m_applySelectedRowParentsTintToRootRows == value ) return; m_applySelectedRowParentsTintToRootRows = value; EditorPrefs.SetBool( "AUD_SelectedRowParentsTintAtRoot", value ); } + } + #endregion + +#if UNITY_2018_3_OR_NEWER + [SettingsProvider] + public static SettingsProvider CreatePreferencesGUI() + { + return new SettingsProvider( "Project/yasirkula/Asset Usage Detector", SettingsScope.Project ) + { + guiHandler = ( searchContext ) => PreferencesGUI(), + keywords = new System.Collections.Generic.HashSet() { "Asset", "Usage", "Detector" } + }; + } +#endif + +#if !UNITY_2018_3_OR_NEWER + [PreferenceItem( "Asset Usage Detector" )] +#endif + public static void PreferencesGUI() + { + float labelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth += 60f; + + EditorGUI.BeginChangeCheck(); + + SettingsHeaderColor = ColorField( "Settings Header Color", SettingsHeaderColor, Color.cyan ); + + EditorGUILayout.Space(); + + PingClickedObjects = EditorGUILayout.Toggle( "Ping Clicked Objects", PingClickedObjects ); + SelectClickedObjects = EditorGUILayout.Toggle( "Select Clicked Objects", SelectClickedObjects ); + SelectDoubleClickedObjects = EditorGUILayout.Toggle( "Select Double Clicked Objects", SelectDoubleClickedObjects ); + + EditorGUILayout.Space(); + + ShowUnityTooltip = EditorGUILayout.Toggle( "Show Unity Tooltip", ShowUnityTooltip ); + ShowCustomTooltip = EditorGUILayout.Toggle( "Show Custom Tooltip", ShowCustomTooltip ); + EditorGUI.indentLevel++; + CustomTooltipDelay = FloatField( "Delay", CustomTooltipDelay, 0.7f ); + EditorGUI.indentLevel--; + TooltipDescriptionTextColor = ColorField( "Tooltip Descriptions Text Color", TooltipDescriptionTextColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.9f, 0.9f, 1f ) : new Color( 0.9f, 0f, 0f, 1f ) ); + + EditorGUILayout.Space(); + + ExtraRowHeight = Mathf.Max( 0f, FloatField( "Extra Row Height", ExtraRowHeight, 0f ) ); + + EditorGUILayout.Space(); + + SearchResultGroupHeaderColor = ColorField( "Group Header Color", SearchResultGroupHeaderColor, Color.cyan ); + RootRowsBackgroundColor = ColorField( "Root Rows Background Color", RootRowsBackgroundColor, EditorGUIUtility.isProSkin ? new Color( 0f, 1f, 1f, 0.15f ) : new Color( 0f, 1f, 1f, 0.25f ) ); + RootRowsBorderColor = ColorField( "Root Rows Border Color", RootRowsBorderColor, EditorGUIUtility.isProSkin ? new Color( 0.15f, 0.15f, 0.15f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) ); + MainReferencesBackgroundColor = ColorField( "Main References Background Color", MainReferencesBackgroundColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.35f, 0f, 1f ) : new Color( 0.25f, 0.75f, 0.25f, 1f ) ); + SelectedRowParentsTint = ColorField( "Selected Row Parents Tint", SelectedRowParentsTint, EditorGUIUtility.isProSkin ? new Color( 0.36f, 0.36f, 0.18f, 1f ) : new Color( 0.825f, 0.825f, 0.55f, 1f ) ); + EditorGUI.indentLevel++; + ApplySelectedRowParentsTintToRootRows = !EditorGUILayout.Toggle( "Ignore Root Rows", !ApplySelectedRowParentsTintToRootRows ); + EditorGUI.indentLevel--; + SelectedRowOccurrencesColor = ColorField( "Selected Row All Occurrences Tint", SelectedRowOccurrencesColor, EditorGUIUtility.isProSkin ? new Color( 0f, 0.3f, 0.75f, 1f ) : new Color( 0.25f, 0.75f, 1f, 1f ) ); + SearchMatchingTextColor = ColorField( "Matching Search Text Color", SearchMatchingTextColor, Color.red ); + + ShowTreeLines = EditorGUILayout.Toggle( "Show Tree Lines", ShowTreeLines ); + EditorGUI.indentLevel++; + TreeLinesColor = ColorField( "Normal Color", TreeLinesColor, EditorGUIUtility.isProSkin ? new Color( 0.65f, 0.65f, 0.65f, 1f ) : new Color( 0.375f, 0.375f, 0.375f, 1f ) ); + HighlightedTreeLinesColor = ColorField( "Highlighted Color", HighlightedTreeLinesColor, Color.cyan ); + EditorGUI.indentLevel--; + + EditorGUIUtility.labelWidth = labelWidth; + + if( EditorGUI.EndChangeCheck() ) + ForEachAssetUsageDetectorWindow( ( window ) => window.Repaint() ); + } + + private static Color ColorField( string label, Color value, Color defaultValue ) + { + GUILayout.BeginHorizontal(); + Color result = EditorGUILayout.ColorField( label, value ); + if( GUILayout.Button( "Reset", GL_WIDTH_60 ) ) + result = defaultValue; + GUILayout.EndHorizontal(); + + return result; + } + + private static float FloatField( string label, float value, float defaultValue ) + { + GUILayout.BeginHorizontal(); + float result = EditorGUILayout.FloatField( label, value ); + if( GUILayout.Button( "Reset", GL_WIDTH_60 ) ) + result = defaultValue; + GUILayout.EndHorizontal(); + + return result; + } + + private static Color GetColor( string pref, Color defaultColor ) + { + if( EditorGUIUtility.isProSkin ) + pref += "_Pro"; + + if( !EditorPrefs.HasKey( pref ) ) + return defaultColor; + + string[] parts = EditorPrefs.GetString( pref ).Split( ';' ); + return new Color32( byte.Parse( parts[0] ), byte.Parse( parts[1] ), byte.Parse( parts[2] ), byte.Parse( parts[3] ) ); + } + + private static void SetColor( string pref, Color32 value ) + { + if( EditorGUIUtility.isProSkin ) + pref += "_Pro"; + + EditorPrefs.SetString( pref, string.Concat( value.r.ToString(), ";", value.g.ToString(), ";", value.b.ToString(), ";", value.a.ToString() ) ); + } + + private static void ForEachAssetUsageDetectorWindow( System.Action action ) + { + foreach( AssetUsageDetectorWindow window in Resources.FindObjectsOfTypeAll() ) + { + if( window ) + action( window ); + } + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSettings.cs.meta b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSettings.cs.meta new file mode 100644 index 0000000..feedefc --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorSettings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 13295073724765e45aa3b77486e515f4 +timeCreated: 1639982865 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs index 03ff6bb..c53a7e2 100644 --- a/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs +++ b/Plugins/AssetUsageDetector/Editor/AssetUsageDetectorWindow.cs @@ -16,7 +16,7 @@ namespace AssetUsageDetectorNamespace public class AssetUsageDetectorWindow : EditorWindow, IHasCustomMenu { - private const float PLAY_MODE_REFRESH_INTERVAL = 1f; // Interval to refresh the editor window in play mode + private enum WindowFilter { AlwaysReturnActive, ReturnActiveIfNotLocked, AlwaysReturnNew }; private const string PREFS_SEARCH_SCENES = "AUD_SceneSearch"; private const string PREFS_SEARCH_ASSETS = "AUD_AssetsSearch"; @@ -26,19 +26,40 @@ namespace AssetUsageDetectorNamespace private const string PREFS_SEARCH_FIELDS = "AUD_Fields"; private const string PREFS_SEARCH_PROPERTIES = "AUD_Properties"; private const string PREFS_SEARCH_NON_SERIALIZABLES = "AUD_NonSerializables"; + private const string PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES = "AUD_SearchUnusedMaterialProps"; private const string PREFS_LAZY_SCENE_SEARCH = "AUD_LazySceneSearch"; - private const string PREFS_PATH_DRAWING_MODE = "AUD_PathDrawing"; + private const string PREFS_CALCULATE_UNUSED_OBJECTS = "AUD_FindUnusedObjs"; + private const string PREFS_HIDE_DUPLICATE_ROWS = "AUD_HideDuplicates"; + private const string PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS = "AUD_HideRedundantPVariantLinks"; private const string PREFS_SHOW_PROGRESS = "AUD_Progress"; - private const string PREFS_SHOW_TOOLTIPS = "AUD_Tooltips"; private static readonly GUIContent windowTitle = new GUIContent( "Asset Usage Detector" ); private static readonly Vector2 windowMinSize = new Vector2( 325f, 220f ); - private AssetUsageDetector core = new AssetUsageDetector(); + private readonly GUILayoutOption GL_WIDTH_12 = GUILayout.Width( 12f ); + + private GUIStyle lockButtonStyle; + + private readonly AssetUsageDetector core = new AssetUsageDetector(); private SearchResult searchResult; // Overall search results + // This isn't readonly so that it can be serialized private List objectsToSearch = new List() { new ObjectToSearch( null ) }; + private bool m_isLocked; + private bool IsLocked + { + get { return m_isLocked; } + set + { + if( m_isLocked != value ) + { + m_isLocked = value; + titleContent = value ? new GUIContent( "[L] " + windowTitle.text, EditorGUIUtility.IconContent( "InspectorLock" ).image ) : windowTitle; + } + } + } + private Phase currentPhase = Phase.Setup; private bool searchInOpenScenes = true; // Scenes currently open in Hierarchy view @@ -57,70 +78,129 @@ namespace AssetUsageDetectorNamespace private bool lazySceneSearch = true; private bool searchNonSerializableVariables = true; + private bool searchUnusedMaterialProperties = true; + private bool calculateUnusedObjects = false; + private bool hideDuplicateRows = true; + private bool hideReduntantPrefabVariantLinks = true; private bool noAssetDatabaseChanges = false; private bool showDetailedProgressBar = true; private BindingFlags fieldModifiers, propertyModifiers; - private SearchResultDrawParameters searchResultDrawParameters = new SearchResultDrawParameters( PathDrawingMode.ShortRelevantParts, false, false ); - - private double nextPlayModeRefreshTime = 0f; - private readonly ObjectToSearchListDrawer objectsToSearchDrawer = new ObjectToSearchListDrawer(); private readonly ObjectListDrawer searchInAssetsSubsetDrawer = new ObjectListDrawer( "Search following asset(s) only:", false ); private readonly ObjectListDrawer excludedAssetsDrawer = new ObjectListDrawer( "Don't search following asset(s):", false ); private readonly ObjectListDrawer excludedScenesDrawer = new ObjectListDrawer( "Don't search in following scene(s):", false ); - private readonly GUIContent showTooltipsLabel = new GUIContent( "Show tooltips", "Display nodes' contents in a tooltip when cursor hovers over them" ); + private bool drawObjectsToSearchSection = true; private Vector2 scrollPosition = Vector2.zero; private bool shouldRepositionSelf; private Rect windowTargetPosition; - private static AssetUsageDetectorWindow mainWindow = null; - - void IHasCustomMenu.AddItemsToMenu( GenericMenu menu ) + void IHasCustomMenu.AddItemsToMenu( GenericMenu contextMenu ) { - if( currentPhase == Phase.Complete ) - menu.AddItem( new GUIContent( "Select Clicked Objects" ), SearchResult.SelectClickedObjects, () => SearchResult.SelectClickedObjects = !SearchResult.SelectClickedObjects ); + contextMenu.AddItem( new GUIContent( "Lock" ), IsLocked, () => IsLocked = !IsLocked ); + contextMenu.AddSeparator( "" ); + +#if UNITY_2018_3_OR_NEWER + contextMenu.AddItem( new GUIContent( "Settings" ), false, () => SettingsService.OpenProjectSettings( "Project/yasirkula/Asset Usage Detector" ) ); +#else + contextMenu.AddItem( new GUIContent( "Settings" ), false, () => + { + System.Type preferencesWindowType = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.PreferencesWindow" ); + preferencesWindowType.GetMethod( "ShowPreferencesWindow", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).Invoke( null, null ); + + EditorWindow preferencesWindow = GetWindow( preferencesWindowType ); + if( (bool) preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow ) ) + { + preferencesWindowType.GetMethod( "AddCustomSections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( preferencesWindow, null ); + preferencesWindowType.GetField( "m_RefreshCustomPreferences", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, false ); + } + + int targetSectionIndex = -1; + System.Collections.IList sections = (System.Collections.IList) preferencesWindowType.GetField( "m_Sections", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( preferencesWindow ); + for( int i = 0; i < sections.Count; i++ ) + { + if( ( (GUIContent) sections[i].GetType().GetField( "content", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( sections[i] ) ).text == "Asset Usage Detector" ) + { + targetSectionIndex = i; + break; + } + } + + if( targetSectionIndex >= 0 ) + preferencesWindowType.GetProperty( "selectedSectionIndex", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).SetValue( preferencesWindow, targetSectionIndex, null ); + } ); +#endif + + if( currentPhase == Phase.Setup ) + { + contextMenu.AddSeparator( "" ); + contextMenu.AddItem( new GUIContent( "Refresh Sub-Assets of Searched Objects" ), false, () => + { + for( int i = objectsToSearch.Count - 1; i >= 0; i-- ) + objectsToSearch[i].RefreshSubAssets(); + } ); + } + } + + // Shows lock button at the top-right corner + // Credit: http://leahayes.co.uk/2013/04/30/adding-the-little-padlock-button-to-your-editorwindow.html + private void ShowButton( Rect position ) + { + if( lockButtonStyle == null ) + lockButtonStyle = "IN LockButton"; + + IsLocked = GUI.Toggle( position, IsLocked, GUIContent.none, lockButtonStyle ); + } + + private static AssetUsageDetectorWindow GetWindow( WindowFilter filter ) + { + AssetUsageDetectorWindow[] windows = Resources.FindObjectsOfTypeAll(); + AssetUsageDetectorWindow window = System.Array.Find( windows, ( w ) => w && !w.IsLocked ); + if( !window ) + window = System.Array.Find( windows, ( w ) => w ); + + if( window && ( filter == WindowFilter.AlwaysReturnActive || ( !window.IsLocked && filter == WindowFilter.ReturnActiveIfNotLocked ) ) ) + { + window.Show(); + return window; + } + + Rect? windowTargetPosition = null; + if( window ) + { + Rect position = window.position; + position.position += new Vector2( 50f, 50f ); + windowTargetPosition = position; + } + + window = CreateInstance(); + window.titleContent = windowTitle; + window.minSize = windowMinSize; + + if( windowTargetPosition.HasValue ) + { + window.shouldRepositionSelf = true; + window.windowTargetPosition = windowTargetPosition.Value; + } + + window.Show( true ); + return window; } [MenuItem( "Window/Asset Usage Detector/Active Window" )] private static void OpenActiveWindow() { - if( !mainWindow ) - { - mainWindow = GetWindow(); - mainWindow.titleContent = windowTitle; - mainWindow.minSize = windowMinSize; - } - - mainWindow.Show(); + GetWindow( WindowFilter.AlwaysReturnActive ); } [MenuItem( "Window/Asset Usage Detector/New Window" )] private static void OpenNewWindow() { - Rect? windowTargetPosition = null; - if( mainWindow ) - { - Rect position = mainWindow.position; - position.position += new Vector2( 50f, 50f ); - windowTargetPosition = position; - } - - mainWindow = CreateInstance(); - mainWindow.titleContent = windowTitle; - mainWindow.minSize = windowMinSize; - - if( windowTargetPosition.HasValue ) - { - mainWindow.shouldRepositionSelf = true; - mainWindow.windowTargetPosition = windowTargetPosition.Value; - } - - mainWindow.Show( true ); + GetWindow( WindowFilter.AlwaysReturnNew ); } // Quickly initiate search for the selected assets @@ -164,7 +244,7 @@ namespace AssetUsageDetectorNamespace // Quickly show the AssetUsageDetector window and initiate a search public static void ShowAndSearch( IEnumerable searchObjects, bool? shouldSearchChildren = null ) { - ShowAndSearchInternal( searchObjects, null, shouldSearchChildren ); + GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchObjects, null, shouldSearchChildren ); } // Quickly show the AssetUsageDetector window and initiate a search @@ -176,7 +256,7 @@ namespace AssetUsageDetectorNamespace return; } - ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters, shouldSearchChildren ); + GetWindow( WindowFilter.ReturnActiveIfNotLocked ).ShowAndSearchInternal( searchParameters.objectsToSearch, searchParameters, shouldSearchChildren ); } private static void CallSearchSelectedAssetReferencesOnce() @@ -191,61 +271,63 @@ namespace AssetUsageDetectorNamespace SearchSelectedAssetReferencesWithChildren( new MenuCommand( null ) ); } - private static void ShowAndSearchInternal( IEnumerable searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren ) + private void ShowAndSearchInternal( IEnumerable searchObjects, AssetUsageDetector.Parameters searchParameters, bool? shouldSearchChildren ) { - if( mainWindow && !mainWindow.ReturnToSetupPhase() ) + if( !ReturnToSetupPhase() ) { Debug.LogError( "Need to reset the previous search first!" ); return; } - OpenActiveWindow(); - - mainWindow.objectsToSearch.Clear(); + objectsToSearch.Clear(); if( searchObjects != null ) { foreach( Object obj in searchObjects ) - mainWindow.objectsToSearch.Add( new ObjectToSearch( obj, shouldSearchChildren ) ); + objectsToSearch.Add( new ObjectToSearch( obj, shouldSearchChildren ) ); } if( searchParameters != null ) { - mainWindow.ParseSceneSearchMode( searchParameters.searchInScenes ); - mainWindow.searchInAssetsFolder = searchParameters.searchInAssetsFolder; - mainWindow.dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; - mainWindow.searchInProjectSettings = searchParameters.searchInProjectSettings; - mainWindow.searchDepthLimit = searchParameters.searchDepthLimit; - mainWindow.fieldModifiers = searchParameters.fieldModifiers; - mainWindow.propertyModifiers = searchParameters.propertyModifiers; - mainWindow.searchNonSerializableVariables = searchParameters.searchNonSerializableVariables; - mainWindow.lazySceneSearch = searchParameters.lazySceneSearch; - mainWindow.noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges; - mainWindow.showDetailedProgressBar = searchParameters.showDetailedProgressBar; + ParseSceneSearchMode( searchParameters.searchInScenes ); + searchInAssetsFolder = searchParameters.searchInAssetsFolder; + dontSearchInSourceAssets = searchParameters.dontSearchInSourceAssets; + searchInProjectSettings = searchParameters.searchInProjectSettings; + searchDepthLimit = searchParameters.searchDepthLimit; + fieldModifiers = searchParameters.fieldModifiers; + propertyModifiers = searchParameters.propertyModifiers; + searchNonSerializableVariables = searchParameters.searchNonSerializableVariables; + searchUnusedMaterialProperties = searchParameters.searchUnusedMaterialProperties; + lazySceneSearch = searchParameters.lazySceneSearch; + calculateUnusedObjects = searchParameters.calculateUnusedObjects; + hideDuplicateRows = searchParameters.hideDuplicateRows; + hideReduntantPrefabVariantLinks = searchParameters.hideReduntantPrefabVariantLinks; + noAssetDatabaseChanges = searchParameters.noAssetDatabaseChanges; + showDetailedProgressBar = searchParameters.showDetailedProgressBar; - mainWindow.searchInAssetsSubset.Clear(); + searchInAssetsSubset.Clear(); if( searchParameters.searchInAssetsSubset != null ) { foreach( Object obj in searchParameters.searchInAssetsSubset ) - mainWindow.searchInAssetsSubset.Add( obj ); + searchInAssetsSubset.Add( obj ); } - mainWindow.excludedAssets.Clear(); + excludedAssets.Clear(); if( searchParameters.excludedAssetsFromSearch != null ) { foreach( Object obj in searchParameters.excludedAssetsFromSearch ) - mainWindow.excludedAssets.Add( obj ); + excludedAssets.Add( obj ); } - mainWindow.excludedScenes.Clear(); + excludedScenes.Clear(); if( searchParameters.excludedScenesFromSearch != null ) { foreach( Object obj in searchParameters.excludedScenesFromSearch ) - mainWindow.excludedScenes.Add( obj ); + excludedScenes.Add( obj ); } } - mainWindow.InitiateSearch(); - mainWindow.Repaint(); + InitiateSearch(); + Repaint(); } private void Awake() @@ -255,7 +337,8 @@ namespace AssetUsageDetectorNamespace private void OnEnable() { - mainWindow = this; + if( currentPhase == Phase.Complete && AssetUsageDetectorSettings.ShowCustomTooltip ) + wantsMouseMove = wantsMouseEnterLeaveWindow = true; // These values aren't preserved during domain reload on Unity 2020.3.0f1 #if UNITY_2018_3_OR_NEWER PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets; @@ -268,9 +351,7 @@ namespace AssetUsageDetectorNamespace #if UNITY_2018_3_OR_NEWER PrefabStage.prefabStageClosing -= ReplacePrefabStageObjectsWithAssets; #endif - - if( mainWindow == this ) - mainWindow = null; + SearchResultTooltip.Hide(); } private void OnDestroy() @@ -284,11 +365,6 @@ namespace AssetUsageDetectorNamespace searchResult.RestoreInitialSceneSetup(); } - private void OnFocus() - { - mainWindow = this; - } - private void SavePrefs() { EditorPrefs.SetInt( PREFS_SEARCH_SCENES, (int) GetSceneSearchMode( false ) ); @@ -298,10 +374,12 @@ namespace AssetUsageDetectorNamespace EditorPrefs.SetInt( PREFS_SEARCH_DEPTH_LIMIT, searchDepthLimit ); EditorPrefs.SetInt( PREFS_SEARCH_FIELDS, (int) fieldModifiers ); EditorPrefs.SetInt( PREFS_SEARCH_PROPERTIES, (int) propertyModifiers ); - EditorPrefs.SetInt( PREFS_PATH_DRAWING_MODE, (int) searchResultDrawParameters.pathDrawingMode ); EditorPrefs.SetBool( PREFS_SEARCH_NON_SERIALIZABLES, searchNonSerializableVariables ); + EditorPrefs.SetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, searchUnusedMaterialProperties ); EditorPrefs.SetBool( PREFS_LAZY_SCENE_SEARCH, lazySceneSearch ); - EditorPrefs.SetBool( PREFS_SHOW_TOOLTIPS, searchResultDrawParameters.showTooltips ); + EditorPrefs.SetBool( PREFS_CALCULATE_UNUSED_OBJECTS, calculateUnusedObjects ); + EditorPrefs.SetBool( PREFS_HIDE_DUPLICATE_ROWS, hideDuplicateRows ); + EditorPrefs.SetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, hideReduntantPrefabVariantLinks ); EditorPrefs.SetBool( PREFS_SHOW_PROGRESS, showDetailedProgressBar ); } @@ -313,23 +391,14 @@ namespace AssetUsageDetectorNamespace dontSearchInSourceAssets = EditorPrefs.GetBool( PREFS_DONT_SEARCH_SOURCE_ASSETS, true ); searchInProjectSettings = EditorPrefs.GetBool( PREFS_SEARCH_PROJECT_SETTINGS, true ); searchDepthLimit = EditorPrefs.GetInt( PREFS_SEARCH_DEPTH_LIMIT, 4 ); - - // Fetch public, protected and private non-static fields and properties from objects by default fieldModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_FIELDS, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) ); propertyModifiers = (BindingFlags) EditorPrefs.GetInt( PREFS_SEARCH_PROPERTIES, (int) ( BindingFlags.Public | BindingFlags.NonPublic ) ); - - try - { - searchResultDrawParameters.pathDrawingMode = (PathDrawingMode) EditorPrefs.GetInt( PREFS_PATH_DRAWING_MODE, (int) PathDrawingMode.ShortRelevantParts ); - } - catch - { - searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts; - } - searchNonSerializableVariables = EditorPrefs.GetBool( PREFS_SEARCH_NON_SERIALIZABLES, true ); + searchUnusedMaterialProperties = EditorPrefs.GetBool( PREFS_SEARCH_UNUSED_MATERIAL_PROPERTIES, true ); lazySceneSearch = EditorPrefs.GetBool( PREFS_LAZY_SCENE_SEARCH, true ); - searchResultDrawParameters.showTooltips = EditorPrefs.GetBool( PREFS_SHOW_TOOLTIPS, false ); + calculateUnusedObjects = EditorPrefs.GetBool( PREFS_CALCULATE_UNUSED_OBJECTS, false ); + hideDuplicateRows = EditorPrefs.GetBool( PREFS_HIDE_DUPLICATE_ROWS, true ); + hideReduntantPrefabVariantLinks = EditorPrefs.GetBool( PREFS_HIDE_REDUNDANT_PREFAB_VARIANT_LINKS, true ); showDetailedProgressBar = EditorPrefs.GetBool( PREFS_SHOW_PROGRESS, true ); } @@ -359,13 +428,6 @@ namespace AssetUsageDetectorNamespace private void Update() { - // Refresh the window at a regular interval in play mode to update the tooltip - if( EditorApplication.isPlaying && currentPhase == Phase.Complete && searchResultDrawParameters.showTooltips && EditorApplication.timeSinceStartup >= nextPlayModeRefreshTime ) - { - nextPlayModeRefreshTime = EditorApplication.timeSinceStartup + PLAY_MODE_REFRESH_INTERVAL; ; - Repaint(); - } - if( shouldRepositionSelf ) { shouldRepositionSelf = false; @@ -390,47 +452,50 @@ namespace AssetUsageDetectorNamespace } else if( currentPhase == Phase.Setup ) { - objectsToSearchDrawer.Draw( objectsToSearch ); + DrawObjectsToSearchSection(); - GUILayout.Space( 10 ); + GUILayout.Space( 10f ); Color c = GUI.backgroundColor; - GUI.backgroundColor = Color.cyan; - GUILayout.Box( "SEARCH IN", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); + GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor; + GUILayout.Box( "SEARCH IN", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); GUI.backgroundColor = c; - searchInAssetsFolder = EditorGUILayout.ToggleLeft( "Project window (Assets folder)", searchInAssetsFolder ); + searchInAssetsFolder = WordWrappingToggleLeft( "Project window (Assets folder)", searchInAssetsFolder ); if( searchInAssetsFolder ) { GUILayout.BeginHorizontal(); - GUILayout.Space( 35 ); + GUILayout.Space( 35f ); GUILayout.BeginVertical(); searchInAssetsSubsetDrawer.Draw( searchInAssetsSubset ); excludedAssetsDrawer.Draw( excludedAssets ); - dontSearchInSourceAssets = EditorGUILayout.ToggleLeft( "Don't search \"Find references of\" themselves for references", dontSearchInSourceAssets ); - GUILayout.EndVertical(); GUILayout.EndHorizontal(); } + GUILayout.Space( 5f ); + + dontSearchInSourceAssets = WordWrappingToggleLeft( "Don't search \"SEARCHED OBJECTS\" themselves for references", dontSearchInSourceAssets ); + searchUnusedMaterialProperties = WordWrappingToggleLeft( "Search unused material properties (e.g. normal map of a material that no longer uses normal mapping)", searchUnusedMaterialProperties ); + Utilities.DrawSeparatorLine(); if( searchInAllScenes && !EditorApplication.isPlaying ) GUI.enabled = false; - searchInOpenScenes = EditorGUILayout.ToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes ); + searchInOpenScenes = WordWrappingToggleLeft( "Currently open (loaded) scene(s)", searchInOpenScenes ); if( !EditorApplication.isPlaying ) { - searchInScenesInBuild = EditorGUILayout.ToggleLeft( "Scenes in Build Settings", searchInScenesInBuild ); + searchInScenesInBuild = WordWrappingToggleLeft( "Scenes in Build Settings", searchInScenesInBuild ); if( searchInScenesInBuild ) { GUILayout.BeginHorizontal(); - GUILayout.Space( 35 ); + GUILayout.Space( 35f ); searchInScenesInBuildTickedOnly = EditorGUILayout.ToggleLeft( "Ticked only", searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); searchInScenesInBuildTickedOnly = !EditorGUILayout.ToggleLeft( "All", !searchInScenesInBuildTickedOnly, Utilities.GL_WIDTH_100 ); @@ -440,11 +505,11 @@ namespace AssetUsageDetectorNamespace GUI.enabled = true; - searchInAllScenes = EditorGUILayout.ToggleLeft( "All scenes in the project", searchInAllScenes ); + searchInAllScenes = WordWrappingToggleLeft( "All scenes in the project", searchInAllScenes ); } GUILayout.BeginHorizontal(); - GUILayout.Space( 35 ); + GUILayout.Space( 35f ); GUILayout.BeginVertical(); excludedScenesDrawer.Draw( excludedScenes ); @@ -454,71 +519,24 @@ namespace AssetUsageDetectorNamespace Utilities.DrawSeparatorLine(); - searchInProjectSettings = EditorGUILayout.ToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings ); + searchInProjectSettings = WordWrappingToggleLeft( "Project Settings (Player Settings, Graphics Settings etc.)", searchInProjectSettings ); - GUILayout.Space( 10 ); + GUILayout.Space( 10f ); - //GUILayout.Box( "SEARCH SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); - - //GUILayout.BeginHorizontal(); - - //GUILayout.Label( new GUIContent( "> Search depth: " + searchDepthLimit, "Depth limit for recursively searching variables of objects" ), Utilities.GL_WIDTH_250 ); - - //searchDepthLimit = (int) GUILayout.HorizontalSlider( searchDepthLimit, 0, 4 ); - - //GUILayout.EndHorizontal(); - - //GUILayout.Label( "> Search variables:" ); - - //GUILayout.BeginHorizontal(); - - //GUILayout.Space( 35 ); - - //if( EditorGUILayout.ToggleLeft( "Public", ( fieldModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) ) - // fieldModifiers |= BindingFlags.Public; - //else - // fieldModifiers &= ~BindingFlags.Public; - - //if( EditorGUILayout.ToggleLeft( "Non-public", ( fieldModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) ) - // fieldModifiers |= BindingFlags.NonPublic; - //else - // fieldModifiers &= ~BindingFlags.NonPublic; - - //GUILayout.EndHorizontal(); - - //GUILayout.Label( "> Search properties:" ); - - //GUILayout.BeginHorizontal(); - - //GUILayout.Space( 35 ); - - //if( EditorGUILayout.ToggleLeft( "Public", ( propertyModifiers & BindingFlags.Public ) == BindingFlags.Public, Utilities.GL_WIDTH_100 ) ) - // propertyModifiers |= BindingFlags.Public; - //else - // propertyModifiers &= ~BindingFlags.Public; - - //if( EditorGUILayout.ToggleLeft( "Non-public", ( propertyModifiers & BindingFlags.NonPublic ) == BindingFlags.NonPublic, Utilities.GL_WIDTH_100 ) ) - // propertyModifiers |= BindingFlags.NonPublic; - //else - // propertyModifiers &= ~BindingFlags.NonPublic; - - //GUILayout.EndHorizontal(); - - //GUILayout.Space( 10 ); - - //searchNonSerializableVariables = EditorGUILayout.ToggleLeft( "Search non-serializable fields and properties", searchNonSerializableVariables ); - - //GUILayout.Space( 10 ); - - GUI.backgroundColor = Color.cyan; - GUILayout.Box( "SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); + GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor; + GUILayout.Box( "SETTINGS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); GUI.backgroundColor = c; - lazySceneSearch = EditorGUILayout.ToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch ); - noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges ); - showDetailedProgressBar = EditorGUILayout.ToggleLeft( "Update search progress bar more often (slower search)", showDetailedProgressBar ); + lazySceneSearch = WordWrappingToggleLeft( "Lazy scene search: scenes are searched in detail only when they are manually refreshed (faster search)", lazySceneSearch ); + calculateUnusedObjects = WordWrappingToggleLeft( "Calculate unused objects", calculateUnusedObjects ); + hideDuplicateRows = WordWrappingToggleLeft( "Hide duplicate rows in search results", hideDuplicateRows ); +#if UNITY_2018_3_OR_NEWER + hideReduntantPrefabVariantLinks = WordWrappingToggleLeft( "Hide redundant prefab variant links (when the same value is assigned to the same Component of a prefab and its variant(s))", hideReduntantPrefabVariantLinks ); +#endif + noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster search)", noAssetDatabaseChanges ); + showDetailedProgressBar = WordWrappingToggleLeft( "Update search progress bar more often (cancelable search) (slower search)", showDetailedProgressBar ); - GUILayout.Space( 10 ); + GUILayout.Space( 10f ); // Don't let the user press the GO button without any valid search location if( !searchInAllScenes && !searchInOpenScenes && !searchInScenesInBuild && !searchInAssetsFolder && !searchInProjectSettings ) @@ -529,15 +547,19 @@ namespace AssetUsageDetectorNamespace InitiateSearch(); GUIUtility.ExitGUI(); } + + GUILayout.Space( 5f ); } else if( currentPhase == Phase.Complete ) { // Draw the results of the search GUI.enabled = false; - objectsToSearchDrawer.Draw( objectsToSearch ); + DrawObjectsToSearchSection(); + + if( drawObjectsToSearchSection ) + GUILayout.Space( 10f ); - GUILayout.Space( 10 ); GUI.enabled = true; if( GUILayout.Button( "Reset Search", Utilities.GL_HEIGHT_30 ) ) @@ -551,87 +573,66 @@ namespace AssetUsageDetectorNamespace else if( !searchResult.SearchCompletedSuccessfully ) EditorGUILayout.HelpBox( "ERROR: search was interrupted, check the logs for more info", MessageType.Error ); - Color c = GUI.backgroundColor; - GUI.backgroundColor = Color.green; - GUILayout.Box( "Don't forget to save scene(s) if you made any changes!", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); - GUI.backgroundColor = c; - if( searchResult.NumberOfGroups == 0 ) { - GUILayout.Space( 10 ); + GUILayout.Space( 10f ); GUILayout.Box( "No references found...", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); } else { - //GUILayout.Space( 10 ); - //GUILayout.BeginHorizontal(); + noAssetDatabaseChanges = WordWrappingToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges ); - //// Select all the references after filtering them (select only the GameObject's) - //if( GUILayout.Button( "Select All\n(GameObject-wise)", Utilities.GL_HEIGHT_35 ) ) - //{ - // GameObject[] objects = searchResult.SelectAllAsGameObjects(); - // if( objects != null && objects.Length > 0 ) - // Selection.objects = objects; - //} + EditorGUILayout.Space(); - //// Select all the references without filtering them - //if( GUILayout.Button( "Select All\n(Object-wise)", Utilities.GL_HEIGHT_35 ) ) - //{ - // Object[] objects = searchResult.SelectAllAsObjects(); - // if( objects != null && objects.Length > 0 ) - // Selection.objects = objects; - //} - - //GUILayout.EndHorizontal(); - - //GUILayout.Space( 10 ); - - searchResultDrawParameters.showTooltips = EditorGUILayout.ToggleLeft( showTooltipsLabel, searchResultDrawParameters.showTooltips ); - noAssetDatabaseChanges = EditorGUILayout.ToggleLeft( "I haven't modified any assets/scenes since the last search (faster Refresh)", noAssetDatabaseChanges ); - searchResultDrawParameters.noAssetDatabaseChanges = noAssetDatabaseChanges; - - Utilities.DrawSeparatorLine(); - - GUILayout.Label( "Path drawing mode:" ); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Full: Draw the complete paths to the references", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Full ) ) - searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Full; - - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Shorter: Draw only the most relevant parts (that start with a UnityEngine.Object) of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) ) - searchResultDrawParameters.pathDrawingMode = PathDrawingMode.ShortRelevantParts; - - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - - GUILayout.Space( 35 ); - - if( EditorGUILayout.ToggleLeft( "Shortest: Draw only the last two nodes of the complete paths", searchResultDrawParameters.pathDrawingMode == PathDrawingMode.Shortest ) ) - searchResultDrawParameters.pathDrawingMode = PathDrawingMode.Shortest; - - GUILayout.EndHorizontal(); - - searchResult.DrawOnGUI( searchResultDrawParameters ); + scrollPosition.y = searchResult.DrawOnGUI( this, scrollPosition.y, noAssetDatabaseChanges ); } } - GUILayout.Space( 10 ); + if( Event.current.type == EventType.MouseLeaveWindow ) + { + SearchResultTooltip.Hide(); + + if( searchResult != null ) + searchResult.CancelDelayedTreeViewTooltip(); + } GUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } + private void DrawObjectsToSearchSection() + { + Color c = GUI.backgroundColor; + GUI.backgroundColor = AssetUsageDetectorSettings.SettingsHeaderColor; + GUILayout.Box( "SEARCHED OBJECTS", Utilities.BoxGUIStyle, Utilities.GL_EXPAND_WIDTH ); + GUI.backgroundColor = c; + + Rect searchedObjectsHeaderRect = GUILayoutUtility.GetLastRect(); + searchedObjectsHeaderRect.x += 5f; + searchedObjectsHeaderRect.yMin += ( searchedObjectsHeaderRect.height - EditorGUIUtility.singleLineHeight ) * 0.5f; + searchedObjectsHeaderRect.height = EditorGUIUtility.singleLineHeight; + + drawObjectsToSearchSection = EditorGUI.Foldout( searchedObjectsHeaderRect, drawObjectsToSearchSection, GUIContent.none, true ); + + if( drawObjectsToSearchSection ) + objectsToSearchDrawer.Draw( objectsToSearch ); + } + + private bool WordWrappingToggleLeft( string label, bool value ) + { + GUILayout.BeginHorizontal(); + bool result = EditorGUILayout.ToggleLeft( GUIContent.none, value, GL_WIDTH_12 ); + if( GUILayout.Button( label, EditorStyles.wordWrappedLabel ) ) + { + GUI.FocusControl( null ); + result = !value; + } + GUILayout.EndHorizontal(); + + return result; + } + private void InitiateSearch() { currentPhase = Phase.Processing; @@ -657,12 +658,19 @@ namespace AssetUsageDetectorNamespace //propertyModifiers = propertyModifiers, //searchDepthLimit = searchDepthLimit, //searchNonSerializableVariables = searchNonSerializableVariables, + searchUnusedMaterialProperties = searchUnusedMaterialProperties, lazySceneSearch = lazySceneSearch, + calculateUnusedObjects = calculateUnusedObjects, + hideDuplicateRows = hideDuplicateRows, + hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks, noAssetDatabaseChanges = noAssetDatabaseChanges, showDetailedProgressBar = showDetailedProgressBar } ); currentPhase = Phase.Complete; + + if( AssetUsageDetectorSettings.ShowCustomTooltip ) + wantsMouseMove = wantsMouseEnterLeaveWindow = true; } #if UNITY_2018_3_OR_NEWER @@ -712,8 +720,28 @@ namespace AssetUsageDetectorNamespace searchResult = null; currentPhase = Phase.Setup; + wantsMouseMove = wantsMouseEnterLeaveWindow = false; + + SearchResultTooltip.Hide(); return true; } + + internal void OnSettingsChanged( bool highlightedSearchTextColorChanged = false, bool tooltipDescriptionsColorChanged = false ) + { + if( searchResult == null ) + return; + + wantsMouseMove = wantsMouseEnterLeaveWindow = AssetUsageDetectorSettings.ShowCustomTooltip; + + for( int i = searchResult.NumberOfGroups - 1; i >= 0; i-- ) + { + if( searchResult[i].treeView != null ) + { + searchResult[i].treeView.rowHeight = EditorGUIUtility.singleLineHeight + AssetUsageDetectorSettings.ExtraRowHeight; + searchResult[i].treeView.OnSettingsChanged( highlightedSearchTextColorChanged, tooltipDescriptionsColorChanged ); + } + } + } } } \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/ListDrawer.cs b/Plugins/AssetUsageDetector/Editor/ListDrawer.cs index 57683c2..d7d50dd 100644 --- a/Plugins/AssetUsageDetector/Editor/ListDrawer.cs +++ b/Plugins/AssetUsageDetector/Editor/ListDrawer.cs @@ -103,12 +103,6 @@ namespace AssetUsageDetectorNamespace SetObjectOfElement( list, i, newObject ); } - if( guiEnabled && newObject && ev.type == EventType.ContextClick && GUILayoutUtility.GetLastRect().Contains( ev.mousePosition ) ) - { - OnElementRightClicked( list, i, newObject ); - ev.Use(); - } - if( guiEnabled ) { if( GUILayout.Button( "+", Utilities.GL_WIDTH_25 ) ) @@ -138,7 +132,6 @@ namespace AssetUsageDetectorNamespace protected abstract T CreateElement( Object source ); protected abstract Object GetObjectFromElement( T element ); protected abstract void SetObjectOfElement( List list, int index, Object value ); - protected abstract void OnElementRightClicked( List list, int index, Object value ); protected abstract bool IsElementNull( T element ); protected abstract void PostElementDrawer( T element ); } @@ -164,10 +157,6 @@ namespace AssetUsageDetectorNamespace list[index] = value; } - protected override void OnElementRightClicked( List list, int index, Object value ) - { - } - protected override bool IsElementNull( Object element ) { return element == null || element.Equals( null ); @@ -200,13 +189,6 @@ namespace AssetUsageDetectorNamespace list[index].RefreshSubAssets(); } - protected override void OnElementRightClicked( List list, int index, Object value ) - { - GenericMenu contextMenu = new GenericMenu(); - contextMenu.AddItem( new GUIContent( "Refresh" ), false, () => SetObjectOfElement( list, index, value ) ); - contextMenu.ShowAsContext(); - } - protected override bool IsElementNull( ObjectToSearch element ) { return element == null || element.obj == null || element.obj.Equals( null ); diff --git a/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs b/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs index 62f1160..24ad8ac 100644 --- a/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs +++ b/Plugins/AssetUsageDetector/Editor/ObjectToSearch.cs @@ -26,7 +26,6 @@ namespace AssetUsageDetectorNamespace public List subAssets; public bool showSubAssetsFoldout; - private static MonoScript[] monoScriptsInProject; private static HashSet currentSubAssets; public ObjectToSearch( Object obj, bool? shouldSearchChildren = null ) @@ -81,11 +80,8 @@ namespace AssetUsageDetectorNamespace if( includeTarget ) { - if( !currentSubAssets.Contains( target ) ) - { + if( currentSubAssets.Add( target ) ) subAssets.Add( new SubAsset( target, shouldSearchChildren ?? true ) ); - currentSubAssets.Add( target ); - } } else { @@ -104,49 +100,19 @@ namespace AssetUsageDetectorNamespace for( int i = 0; i < assets.Length; i++ ) { Object asset = assets[i]; - if( asset == null || asset.Equals( null ) || asset is Component ) + if( asset == null || asset.Equals( null ) || asset is Component || asset == target ) continue; - if( currentSubAssets.Contains( asset ) ) +#if UNITY_2018_3_OR_NEWER + // Nested prefabs in prefab assets add an additional native object of type 'UnityEngine.PrefabInstance' to the prefab. Managed type of that native type + // is UnityEngine.Object (i.e. GetType() returns UnityEngine.Object, not UnityEngine.PrefabInstance). There are no possible references to these native + // objects so skip them (we're checking for UnityEngine.Prefab because it includes other native types like UnityEngine.PrefabCreation, as well) + if( target is GameObject && asset.GetType() == typeof( Object ) && asset.ToString().Contains( "(UnityEngine.Prefab" ) ) continue; +#endif - if( asset != target ) - { + if( currentSubAssets.Add( asset ) ) subAssets.Add( new SubAsset( asset, shouldSearchChildren ?? true ) ); - currentSubAssets.Add( asset ); - } - - // MonoScripts are a special case such that other MonoScript objects - // that extend this MonoScript are also considered a sub-asset - if( asset is MonoScript ) - { - Type monoScriptType = ( (MonoScript) asset ).GetClass(); - if( monoScriptType == null || ( !monoScriptType.IsInterface && !typeof( Component ).IsAssignableFrom( monoScriptType ) ) ) - continue; - - // Find all MonoScript objects in the project - if( monoScriptsInProject == null ) - { - string[] monoScriptGuids = AssetDatabase.FindAssets( "t:MonoScript" ); - monoScriptsInProject = new MonoScript[monoScriptGuids.Length]; - for( int k = 0; k < monoScriptGuids.Length; k++ ) - monoScriptsInProject[k] = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath( monoScriptGuids[k] ) ); - } - - // Add any MonoScript objects that extend this MonoScript as a sub-asset - for( int j = 0; j < monoScriptsInProject.Length; j++ ) - { - Type otherMonoScriptType = monoScriptsInProject[j].GetClass(); - if( otherMonoScriptType == null || monoScriptType == otherMonoScriptType || !monoScriptType.IsAssignableFrom( otherMonoScriptType ) ) - continue; - - if( !currentSubAssets.Contains( monoScriptsInProject[j] ) ) - { - subAssets.Add( new SubAsset( monoScriptsInProject[j], shouldSearchChildren ?? true ) ); - currentSubAssets.Add( monoScriptsInProject[j] ); - } - } - } } } } diff --git a/Plugins/AssetUsageDetector/Editor/SearchResult.cs b/Plugins/AssetUsageDetector/Editor/SearchResult.cs index b45a495..ad74a4e 100644 --- a/Plugins/AssetUsageDetector/Editor/SearchResult.cs +++ b/Plugins/AssetUsageDetector/Editor/SearchResult.cs @@ -1,7 +1,9 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Text; using UnityEditor; +using UnityEditor.IMGUI.Controls; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; @@ -9,57 +11,116 @@ using Object = UnityEngine.Object; namespace AssetUsageDetectorNamespace { - [Serializable] - public class SearchResultDrawParameters - { - public SearchResult searchResult; - public PathDrawingMode pathDrawingMode; - public bool showTooltips; - public bool noAssetDatabaseChanges; - public Rect guiRect; - public bool shouldRefreshEditorWindow; - public string tooltip; - - public SearchResultDrawParameters( PathDrawingMode pathDrawingMode, bool showTooltips, bool noAssetDatabaseChanges ) - { - this.pathDrawingMode = pathDrawingMode; - this.showTooltips = showTooltips; - this.noAssetDatabaseChanges = noAssetDatabaseChanges; - } - } - // Custom class to hold search results [Serializable] - public class SearchResult : ISerializationCallbackReceiver + public class SearchResult : IEnumerable, ISerializationCallbackReceiver { - // Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html [Serializable] - public class SerializableResultGroup + internal class SerializableResultGroup { public string title; public SearchResultGroup.GroupType type; public bool isExpanded; public bool pendingSearch; + public SearchResultTreeViewState treeViewState; public List initialSerializedNodes; } [Serializable] - public class SerializableNode + internal class SerializableNode { + [Serializable] + public class SerializableLinkDescriptions + { + public List value; + } + + public string label; public int instanceId; - public bool isUnityObject; - public string description; + public bool isUnityObject, isMainReference; + public ReferenceNode.UsedState usedState; public List links; - public List linkDescriptions; + public List linkDescriptions; + public List linkWeakStates; } -#pragma warning disable 1692 -#pragma warning disable IDE0044 - private bool success; // This is not readonly so that it can be serialized -#pragma warning restore IDE0044 -#pragma warning restore 1692 + internal class SortedEntry : IComparable + { + public readonly string assetPath, subAssetName; + public readonly bool isMainAsset; + public readonly Transform transform; + public readonly object entry; + + public SortedEntry( ReferenceNode node ) : this( node.nodeObject as Object ) + { + entry = node; + } + + public SortedEntry( ReferenceNode.Link link ) : this( link.targetNode.nodeObject as Object ) + { + entry = link; + } + + private SortedEntry( Object obj ) + { + if( obj ) + { + assetPath = AssetDatabase.GetAssetPath( obj ); + if( string.IsNullOrEmpty( assetPath ) ) + { + assetPath = null; + + if( obj is Component ) + transform = ( (Component) obj ).transform; + else if( obj is GameObject ) + transform = ( (GameObject) obj ).transform; + } + else + { + isMainAsset = AssetDatabase.IsMainAsset( ( obj is Component ) ? ( (Component) obj ).gameObject : obj ); + if( !isMainAsset ) + subAssetName = obj.name; + } + } + } + + // Sorting order: + // 1) Scene objects come first and are sorted by their absolute sibling indices in Hierarchy + // 2) Assets come later and are sorted by their asset paths (for assets sharing the same path, main assets come first and sub-assets are then sorted by their names) + // 3) Regular C# objects come last + int IComparable.CompareTo( SortedEntry other ) + { + if( this == other ) + return 0; + else if( assetPath == null ) + { + if( !transform ) + return 1; + else if( other.assetPath == null ) + return other.transform ? Utilities.CompareHierarchySiblingIndices( transform, other.transform ) : -1; + else + return -1; + } + else if( other.assetPath == null ) + return other.transform ? 1 : -1; + else + { + int assetPathComparison = EditorUtility.NaturalCompare( assetPath, other.assetPath ); + if( assetPathComparison != 0 ) + return assetPathComparison; + else if( isMainAsset ) + return -1; + else if( other.isMainAsset ) + return 1; + else + return subAssetName.CompareTo( other.subAssetName ); + } + } + } + + private bool success; // This isn't readonly so that it can be serialized private List result; private SceneSetup[] initialSceneSetup; @@ -67,36 +128,41 @@ namespace AssetUsageDetectorNamespace private AssetUsageDetector searchHandler; private AssetUsageDetector.Parameters m_searchParameters; - private float guiHeight; // Prevents scroll view's position from getting reset at domain reload + // Each TreeView in the drawn search results must use unique ids for their TreeViewItems. Otherwise, strange things happen: https://forum.unity.com/threads/multiple-editor-treeviews-selection-issue.601471/ + internal int nextTreeViewId = 1; private List serializedNodes; private List serializedGroups; + private Object[] serializedUsedObjects; public int NumberOfGroups { get { return result.Count; } } public SearchResultGroup this[int index] { get { return result[index]; } } + public HashSet UsedObjects { get; private set; } + public bool SearchCompletedSuccessfully { get { return success; } } public bool InitialSceneSetupConfigured { get { return initialSceneSetup != null && initialSceneSetup.Length > 0; } } + public bool HasPendingLazySceneSearchResults { get { return result.Find( ( group ) => group.PendingSearch ) != null; } } public AssetUsageDetector.Parameters SearchParameters { get { return m_searchParameters; } } - public static bool SelectClickedObjects - { - get { return EditorPrefs.GetBool( "AUD_SelectClickedObj", true ); } - set { EditorPrefs.SetBool( "AUD_SelectClickedObj", value ); } - } - - public SearchResult( bool success, List result, SceneSetup[] initialSceneSetup, AssetUsageDetector searchHandler, AssetUsageDetector.Parameters searchParameters ) + public SearchResult( bool success, List result, HashSet usedObjects, SceneSetup[] initialSceneSetup, AssetUsageDetector searchHandler, AssetUsageDetector.Parameters searchParameters ) { if( result == null ) result = new List( 0 ); this.success = success; this.result = result; + this.UsedObjects = usedObjects ?? new HashSet(); this.initialSceneSetup = initialSceneSetup; this.searchHandler = searchHandler; this.m_searchParameters = searchParameters; } + public void RemoveSearchResultGroup( SearchResultGroup searchResultGroup ) + { + result.Remove( searchResultGroup ); + } + public void RefreshSearchResultGroup( SearchResultGroup searchResultGroup, bool noAssetDatabaseChanges ) { if( searchResultGroup == null ) @@ -105,23 +171,14 @@ namespace AssetUsageDetectorNamespace return; } - int searchResultGroupIndex = -1; - for( int i = 0; i < result.Count; i++ ) - { - if( result[i] == searchResultGroup ) - { - searchResultGroupIndex = i; - break; - } - } - + int searchResultGroupIndex = result.IndexOf( searchResultGroup ); if( searchResultGroupIndex < 0 ) { Debug.LogError( "SearchResultGroup is not a part of SearchResult!" ); return; } - if( searchResultGroup.Type == SearchResultGroup.GroupType.Scene && EditorApplication.isPlaying && !EditorSceneManager.GetSceneByPath( searchResultGroup.Title ).isLoaded ) + if( searchResultGroup.Type == SearchResultGroup.GroupType.Scene && EditorApplication.isPlaying && !EditorSceneManager.GetSceneByPath( searchResultGroup.ScenePath ).isLoaded ) { Debug.LogError( "Can't search unloaded scene while in Play Mode!" ); return; @@ -135,6 +192,9 @@ namespace AssetUsageDetectorNamespace bool searchInAssetsFolder = m_searchParameters.searchInAssetsFolder; Object[] searchInAssetsSubset = m_searchParameters.searchInAssetsSubset; bool searchInProjectSettings = m_searchParameters.searchInProjectSettings; + bool lazySceneSearch = m_searchParameters.lazySceneSearch; + bool calculateUnusedObjects = m_searchParameters.calculateUnusedObjects; + bool _noAssetDatabaseChanges = m_searchParameters.noAssetDatabaseChanges; try { @@ -155,12 +215,12 @@ namespace AssetUsageDetectorNamespace else if( searchResultGroup.Type == SearchResultGroup.GroupType.Scene ) { m_searchParameters.searchInScenes = SceneSearchMode.None; - m_searchParameters.searchInScenesSubset = new Object[1] { AssetDatabase.LoadAssetAtPath( searchResultGroup.Title ) }; + m_searchParameters.searchInScenesSubset = new Object[1] { AssetDatabase.LoadAssetAtPath( searchResultGroup.ScenePath ) }; m_searchParameters.searchInAssetsFolder = false; m_searchParameters.searchInAssetsSubset = null; m_searchParameters.searchInProjectSettings = false; } - else + else if( searchResultGroup.Type == SearchResultGroup.GroupType.DontDestroyOnLoad ) { m_searchParameters.searchInScenes = (SceneSearchMode) 1024; // A unique value to search only the DontDestroyOnLoad scene m_searchParameters.searchInScenesSubset = null; @@ -168,8 +228,14 @@ namespace AssetUsageDetectorNamespace m_searchParameters.searchInAssetsSubset = null; m_searchParameters.searchInProjectSettings = false; } + else + { + Debug.LogError( "Can't refresh group: " + searchResultGroup.Type ); + return; + } m_searchParameters.lazySceneSearch = false; + m_searchParameters.calculateUnusedObjects = result.Find( ( group ) => group.Type == SearchResultGroup.GroupType.UnusedObjects ) != null; m_searchParameters.noAssetDatabaseChanges = noAssetDatabaseChanges; // Make sure the AssetDatabase is up-to-date @@ -182,23 +248,101 @@ namespace AssetUsageDetectorNamespace return; } - List searchResultGroups = searchResult.result; - if( searchResultGroups != null ) + if( searchResult.result != null ) { - int newSearchResultGroupIndex = -1; - for( int i = 0; i < searchResultGroups.Count; i++ ) - { - if( searchResultGroup.Title == searchResultGroups[i].Title ) - { - newSearchResultGroupIndex = i; - break; - } - } - - if( newSearchResultGroupIndex >= 0 ) - result[searchResultGroupIndex] = searchResultGroups[newSearchResultGroupIndex]; + SearchResultGroup newSearchResultGroup = searchResult.result.Find( ( group ) => group.Title == searchResultGroup.Title ); + if( newSearchResultGroup != null ) + result[searchResultGroupIndex] = newSearchResultGroup; else searchResultGroup.Clear(); + + UsedObjects.UnionWith( searchResult.UsedObjects ); + + SearchResultGroup unusedObjectsSearchResultGroup = result.Find( ( group ) => group.Type == SearchResultGroup.GroupType.UnusedObjects ); + if( unusedObjectsSearchResultGroup != null ) + { + SearchResultGroup newUnusedObjectsSearchResultGroup = searchResult.result.Find( ( group ) => group.Type == SearchResultGroup.GroupType.UnusedObjects ); + if( newUnusedObjectsSearchResultGroup == null ) + { + // UnusedObjects search result group doesn't exist in 2 cases: + // - When there are no search results found (NumberOfGroups == 0) + // - When all searched objects are referenced (NumberOfGroups > 0) + if( searchResult.result.Count > 0 ) + unusedObjectsSearchResultGroup.Clear(); + } + else + { + // NOTE: We can process UnusedObjects graphs iteratively (instead of recursively) because for the time being, these graphs have a maximum depth of 1 + bool unusedObjectsGraphChanged = false; + HashSet newUnusedObjectsSet = new HashSet(); + for( int i = newUnusedObjectsSearchResultGroup.NumberOfReferences - 1; i >= 0; i-- ) + { + ReferenceNode node = newUnusedObjectsSearchResultGroup[i]; + newUnusedObjectsSet.Add( node.UnityObject ); + + for( int j = node.NumberOfOutgoingLinks - 1; j >= 0; j-- ) + newUnusedObjectsSet.Add( node[j].targetNode.UnityObject ); + } + + for( int i = unusedObjectsSearchResultGroup.NumberOfReferences - 1; i >= 0; i-- ) + { + ReferenceNode node = unusedObjectsSearchResultGroup[i]; + bool parentNodeRemoved = false; + Object obj = node.UnityObject; + if( !obj || !newUnusedObjectsSet.Contains( obj ) ) + { + unusedObjectsSearchResultGroup.RemoveReference( i ); + unusedObjectsGraphChanged = parentNodeRemoved = true; + } + + bool hasUnusedSubObjects = false, hasUsedSubObjects = false; + bool hadSubObjects = node.NumberOfOutgoingLinks > 0; + for( int j = 0; j < node.NumberOfOutgoingLinks; j++ ) + { + if( node[j].targetNode.usedState == ReferenceNode.UsedState.Used ) // User has explicitly displayed this used child object/sub-asset in the TreeView + continue; + + Object _obj = node[j].targetNode.UnityObject; + if( newUnusedObjectsSet.Contains( _obj ) ) + { + hasUnusedSubObjects = true; + + if( parentNodeRemoved ) + unusedObjectsSearchResultGroup.AddReference( node[j].targetNode ); + } + else if( !parentNodeRemoved ) + { + node.RemoveLink( j-- ); + unusedObjectsGraphChanged = hasUsedSubObjects = true; + } + } + + if( !parentNodeRemoved ) + { + // When all sub-assets of a main asset are used, consider the main asset as used, as well + if( !hasUnusedSubObjects && hadSubObjects && AssetDatabase.IsMainAsset( obj ) ) + { + unusedObjectsSearchResultGroup.RemoveReference( i ); + unusedObjectsGraphChanged = true; + } + + if( hasUsedSubObjects && node.usedState == ReferenceNode.UsedState.Unused ) + node.usedState = ReferenceNode.UsedState.MixedCollapsed; + } + } + + if( unusedObjectsGraphChanged && unusedObjectsSearchResultGroup.treeView != null ) + { + unusedObjectsSearchResultGroup.treeView.SetSelection( new int[0], TreeViewSelectionOptions.FireSelectionChanged ); + unusedObjectsSearchResultGroup.treeViewState.preSearchExpandedIds = null; + unusedObjectsSearchResultGroup.treeView.Reload(); + unusedObjectsSearchResultGroup.treeView.ExpandAll(); + } + } + + if( unusedObjectsSearchResultGroup.NumberOfReferences == 0 ) + result.Remove( unusedObjectsSearchResultGroup ); + } } } finally @@ -208,97 +352,37 @@ namespace AssetUsageDetectorNamespace m_searchParameters.searchInAssetsFolder = searchInAssetsFolder; m_searchParameters.searchInAssetsSubset = searchInAssetsSubset; m_searchParameters.searchInProjectSettings = searchInProjectSettings; + m_searchParameters.lazySceneSearch = lazySceneSearch; + m_searchParameters.calculateUnusedObjects = calculateUnusedObjects; + m_searchParameters.noAssetDatabaseChanges = _noAssetDatabaseChanges; } } - public void DrawOnGUI( SearchResultDrawParameters parameters ) + public float DrawOnGUI( EditorWindow window, float scrollPosition, bool noAssetDatabaseChanges ) { - parameters.searchResult = this; - parameters.tooltip = null; - parameters.guiRect = EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, Utilities.GL_HEIGHT_0 ); - - float guiInitialY = parameters.guiRect.y; - for( int i = 0; i < result.Count; i++ ) { - result[i].DrawOnGUI( parameters ); + scrollPosition = result[i].DrawOnGUI( this, window, scrollPosition, noAssetDatabaseChanges ); if( i < result.Count - 1 ) - { - Rect rect = parameters.guiRect; - rect.y += 10f; - parameters.guiRect = rect; - } + GUILayout.Space( 10f ); } - if( Event.current.type == EventType.Repaint ) - guiHeight = parameters.guiRect.y - guiInitialY; - - // To work nicely with GUILayout and scroll view - EditorGUILayout.GetControlRect( Utilities.GL_EXPAND_WIDTH, GUILayout.Height( guiHeight ) ); - - if( !string.IsNullOrEmpty( parameters.tooltip ) ) - { - // Show tooltip at mouse position - Vector2 mousePos = Event.current.mousePosition; - Vector2 size = Utilities.TooltipGUIStyle.CalcSize( new GUIContent( parameters.tooltip ) ); - size.x += 10f; - - Rect tooltipRect = new Rect( new Vector2( mousePos.x - size.x * 0.5f, mousePos.y - size.y ), size ); - if( tooltipRect.xMin < 0f ) - tooltipRect.x -= tooltipRect.xMin; - else if( tooltipRect.xMax > parameters.guiRect.width ) - tooltipRect.x -= tooltipRect.xMax - parameters.guiRect.width; - - GUI.Box( tooltipRect, parameters.tooltip, Utilities.TooltipGUIStyle ); - } - - if( parameters.shouldRefreshEditorWindow ) - { - parameters.shouldRefreshEditorWindow = false; - - EditorWindow focusedWindow = EditorWindow.focusedWindow; - if( focusedWindow != null ) - focusedWindow.Repaint(); - - EditorWindow mouseOverWindow = EditorWindow.mouseOverWindow; - if( mouseOverWindow != null && mouseOverWindow != focusedWindow ) - mouseOverWindow.Repaint(); - } + return scrollPosition; } - public Object[] SelectAllAsObjects() + public int IndexOf( SearchResultGroup searchResult ) { - HashSet uniqueObjects = new HashSet(); - for( int i = 0; i < result.Count; i++ ) - result[i].AddObjectsTo( uniqueObjects ); - - if( uniqueObjects.Count > 0 ) - { - Object[] objects = new Object[uniqueObjects.Count]; - uniqueObjects.CopyTo( objects ); - - return objects; - } - - return null; + return result.IndexOf( searchResult ); } - public GameObject[] SelectAllAsGameObjects() + public void CancelDelayedTreeViewTooltip() { - HashSet uniqueGameObjects = new HashSet(); for( int i = 0; i < result.Count; i++ ) - result[i].AddGameObjectsTo( uniqueGameObjects ); - - if( uniqueGameObjects.Count > 0 ) { - GameObject[] objects = new GameObject[uniqueGameObjects.Count]; - uniqueGameObjects.CopyTo( objects ); - - return objects; + if( result[i].treeView != null ) + result[i].treeView.CancelDelayedTooltip(); } - - return null; } // Returns if RestoreInitialSceneSetup will have any effect on the current scene setup @@ -346,7 +430,9 @@ namespace AssetUsageDetectorNamespace if( !IsSceneSetupDifferentThanCurrentSetup() ) return true; - StringBuilder sb = new StringBuilder( 300 ); + StringBuilder sb = Utilities.stringBuilder; + sb.Length = 0; + sb.AppendLine( "Restore initial scene setup?" ); for( int i = 0; i < initialSceneSetup.Length; i++ ) sb.AppendLine().Append( "- " ).Append( initialSceneSetup[i].path ); @@ -398,6 +484,7 @@ namespace AssetUsageDetectorNamespace } // Assembly reloading; serialize nodes in a way that Unity can serialize + // Credit: https://docs.unity3d.com/Manual/script-Serialization-Custom.html void ISerializationCallbackReceiver.OnBeforeSerialize() { if( result == null ) @@ -416,12 +503,17 @@ namespace AssetUsageDetectorNamespace Dictionary nodeToIndex = new Dictionary( result.Count * 16 ); for( int i = 0; i < result.Count; i++ ) serializedGroups.Add( result[i].Serialize( nodeToIndex, serializedNodes ) ); + + if( serializedUsedObjects == null || serializedUsedObjects.Length != UsedObjects.Count ) + serializedUsedObjects = new Object[UsedObjects.Count]; + + UsedObjects.CopyTo( serializedUsedObjects ); } // Assembly reloaded; deserialize nodes to construct the original graph void ISerializationCallbackReceiver.OnAfterDeserialize() { - if( serializedGroups == null || serializedNodes == null ) + if( serializedGroups == null || serializedNodes == null || serializedUsedObjects == null ) return; if( result == null ) @@ -442,450 +534,498 @@ namespace AssetUsageDetectorNamespace result[i].Deserialize( serializedGroups[i], allNodes ); } + if( UsedObjects == null ) + UsedObjects = new HashSet( serializedUsedObjects ); + else + UsedObjects.UnionWith( serializedUsedObjects ); + serializedNodes.Clear(); serializedGroups.Clear(); + serializedUsedObjects = null; } + + IEnumerator IEnumerable.GetEnumerator() { return ( (IEnumerable) result ).GetEnumerator(); } + IEnumerator IEnumerable.GetEnumerator() { return ( (IEnumerable) result ).GetEnumerator(); } } // Custom class to hold the results for a single scene or Assets folder - public class SearchResultGroup + public class SearchResultGroup : IEnumerable { - public enum GroupType { Assets = 0, Scene = 1, DontDestroyOnLoad = 2, ProjectSettings = 3 }; + public enum GroupType { Assets = 0, Scene = 1, DontDestroyOnLoad = 2, ProjectSettings = 3, UnusedObjects = 4 }; - // Custom struct to hold a single path to a reference - public struct ReferencePath - { - public readonly ReferenceNode startNode; - public readonly int[] pathLinksToFollow; + private readonly List references = new List(); - public ReferencePath( ReferenceNode startNode, int[] pathIndices ) - { - this.startNode = startNode; - pathLinksToFollow = pathIndices; - } - } - - private const float HEADER_HEIGHT = 40f; + internal SearchResultTreeView treeView; + internal SearchResultTreeViewState treeViewState; + private Rect lastTreeViewRect; + private SearchField treeViewSearchField; public string Title { get; private set; } public GroupType Type { get; private set; } + public string ScenePath { get; private set; } public bool IsExpanded { get; private set; } public bool PendingSearch { get; private set; } - private readonly List references; - private List referencePathsShortUnique; - private List referencePathsShortest; - - private float calculatedGUIWidth; - private float calculatedGUIHeight; - private PathDrawingMode calculatedGUIMode; - private ReferenceNodeGUI[] guiNodes; - public int NumberOfReferences { get { return references.Count; } } public ReferenceNode this[int index] { get { return references[index]; } } public SearchResultGroup( string title, GroupType type, bool isExpanded = true, bool pendingSearch = false ) { - Title = title; + Title = title.StartsWith( "" ) ? title : string.Concat( "", title, "" ); + ScenePath = type != GroupType.Scene ? null : ( title.StartsWith( "" ) ? title.Substring( 3, title.Length - 7 ) : title ); Type = type; IsExpanded = isExpanded; PendingSearch = pendingSearch; - - references = new List(); - referencePathsShortUnique = null; - referencePathsShortest = null; - - calculatedGUIWidth = 0f; - guiNodes = null; } - // Add a reference to the list public void AddReference( ReferenceNode node ) { references.Add( node ); } + public void RemoveReference( int index ) + { + references.RemoveAt( index ); + } + // Removes all nodes public void Clear() { + PendingSearch = false; + references.Clear(); - if( referencePathsShortUnique != null ) - referencePathsShortUnique.Clear(); - if( referencePathsShortest != null ) - referencePathsShortest.Clear(); - - PendingSearch = false; - calculatedGUIWidth = 0f; - guiNodes = null; + treeView = null; + treeViewState = null; + treeViewSearchField = null; } // Initializes commonly used variables of the nodes - public void InitializeNodes( Func nodeGetter, HashSet objectsToSearchSet ) + public void InitializeNodes( HashSet objectsToSearchSet ) { - // Remove root nodes that don't have any outgoing links or have null node objects (somehow) + List _references = new List( references ); + references.Clear(); + + // Reverse the links of the search results graph so that the root ReferenceNodes are the searched objects + Dictionary reverseGraphNodes = new Dictionary( references.Count * 16 ); + for( int i = 0; i < _references.Count; i++ ) + _references[i].CreateReverseGraphRecursively( this, references, reverseGraphNodes, objectsToSearchSet ); + + // Remove weak links if they aren't ultimately connected to a non-weak link + HashSet visitedNodes = new HashSet(); + for( int i = references.Count - 1; i >= 0; i-- ) + references[i].RemoveRedundantLinksRecursively( visitedNodes ); + + // When a GameObject is a root node, then any components of that GameObject that are also root nodes should omit their links to the + // GameObject's node because otherwise, search results are filled with redundant 'GameObject->Its Component' references + HashSet rootGameObjectNodes = new HashSet(); for( int i = references.Count - 1; i >= 0; i-- ) { - if( references[i].NumberOfOutgoingLinks == 0 ) - references.RemoveAtFast( i ); - else + if( references[i].nodeObject as GameObject ) + rootGameObjectNodes.Add( references[i] ); + } + + for( int i = references.Count - 1; i >= 0; i-- ) + { + ReferenceNode node = references[i]; + Component component = node.nodeObject as Component; + if( component ) { - object nodeObject = references[i].nodeObject; - if( nodeObject == null || nodeObject.Equals( null ) ) - references.RemoveAtFast( i ); + for( int j = node.NumberOfOutgoingLinks - 1; j >= 0; j-- ) + { + if( ReferenceEquals( node[j].targetNode.nodeObject, component.gameObject ) && rootGameObjectNodes.Contains( node[j].targetNode ) ) + { + node.RemoveLink( j ); + break; + } + } } } + // Remove root nodes that don't have any outgoing links for( int i = references.Count - 1; i >= 0; i-- ) { - references[i].VerifyLinksRecursively(); - - // Some links might be removed during verification if( references[i].NumberOfOutgoingLinks == 0 ) - references.RemoveAtFast( i ); + references.RemoveAt( i ); } - if( references.Count == 0 ) - return; - - List callStack = new List( 8 ); - - // If this SearchResultGroup belongs to a scene, simplify the root nodes so that they go directly to either the searched objects or to an asset in a single link - if( Type == GroupType.Scene || Type == GroupType.DontDestroyOnLoad ) + // Sort root nodes + if( references.Count > 1 ) { - Scene scene = references[0].nodeObject is GameObject ? ( (GameObject) references[0].nodeObject ).scene : ( (Component) references[0].nodeObject ).gameObject.scene; - HashSet leafNodes = new HashSet(); + SearchResult.SortedEntry[] sortedEntries = new SearchResult.SortedEntry[references.Count]; for( int i = references.Count - 1; i >= 0; i-- ) - { - references[i].GetLeafSceneNodesRecursive( scene, leafNodes, references[i], objectsToSearchSet, callStack ); + sortedEntries[i] = new SearchResult.SortedEntry( references[i] ); - if( leafNodes.Count > 0 ) - { - references.RemoveAt( i ); - foreach( ReferenceNode leafNode in leafNodes ) - references.Add( leafNode ); + Array.Sort( sortedEntries ); - leafNodes.Clear(); - } - } + for( int i = 0; i < sortedEntries.Length; i++ ) + references[i] = (ReferenceNode) sortedEntries[i].entry; } - // For simplicity's sake, get rid of root nodes that are already part of another node's hierarchy for( int i = references.Count - 1; i >= 0; i-- ) { - if( IsRootNodePartOfAnotherRootNode( i, callStack ) ) - references.RemoveAtFast( i ); - } - - // For clarity, a reference path shouldn't start with a sub-asset but instead with its corresponding main asset - for( int i = references.Count - 1; i >= 0; i-- ) - { - object nodeObject = references[i].nodeObject; - if( nodeObject.IsAsset() && !AssetDatabase.IsMainAsset( (Object) nodeObject ) ) - { - string assetPath = AssetDatabase.GetAssetPath( (Object) nodeObject ); - if( string.IsNullOrEmpty( assetPath ) ) - continue; - - Object mainAsset = AssetDatabase.LoadMainAssetAtPath( assetPath ); - if( mainAsset == null || mainAsset.Equals( null ) ) - continue; - - // We're already calling AssetDatabase.IsMainAsset but just in case... - if( ReferenceEquals( nodeObject, mainAsset ) ) - continue; - - if( nodeObject is Component && ( (Component) nodeObject ).gameObject == mainAsset ) - continue; - - // Get a ReferenceNode for the main asset, add a link to the sub-asset's node and change the root node - ReferenceNode newRootNode = nodeGetter( mainAsset ); - newRootNode.AddLinkTo( references[i], ( nodeObject is Component || nodeObject is GameObject ) ? "Child object" : "Sub-asset" ); - references[i] = newRootNode; - - // Make sure that the new root node isn't already a part of another node's hierarchy - if( IsRootNodePartOfAnotherRootNode( i, callStack ) ) - references.RemoveAtFast( i ); - } - } - - for( int i = 0; i < references.Count; i++ ) + references[i].SortLinks(); // Sort immediate links of the root nodes references[i].InitializeRecursively(); - } - - // Check if node exists in this results set - public bool Contains( ReferenceNode node ) - { - for( int i = 0; i < references.Count; i++ ) - { - if( references[i] == node ) - return true; - } - - return false; - } - - private bool IsRootNodePartOfAnotherRootNode( int index, List callStack ) - { - ReferenceNode node = references[index]; - for( int i = references.Count - 1; i >= 0; i-- ) - { - if( index == i ) - continue; - - if( references[i].nodeObject == node.nodeObject || references[i].NodeExistsInChildrenRecursive( node, callStack ) ) - return true; - } - - return false; - } - - // Add all the Object's in this container to the set - public void AddObjectsTo( HashSet objectsSet ) - { - if( PendingSearch ) - return; - - CalculateShortestPathsToReferences(); - - for( int i = 0; i < referencePathsShortUnique.Count; i++ ) - { - Object obj = referencePathsShortUnique[i].startNode.UnityObject; - if( obj != null && !obj.Equals( null ) ) - objectsSet.Add( obj ); - } - } - - // Add all the GameObject's in this container to the set - public void AddGameObjectsTo( HashSet gameObjectsSet ) - { - if( PendingSearch ) - return; - - CalculateShortestPathsToReferences(); - - for( int i = 0; i < referencePathsShortUnique.Count; i++ ) - { - Object obj = referencePathsShortUnique[i].startNode.UnityObject; - if( obj != null && !obj.Equals( null ) ) - { - if( obj is GameObject ) - gameObjectsSet.Add( (GameObject) obj ); - else if( obj is Component ) - gameObjectsSet.Add( ( (Component) obj ).gameObject ); - } - } - } - - // Calculate short unique paths to the references - private void CalculateShortestPathsToReferences() - { - if( referencePathsShortUnique != null ) - return; - - referencePathsShortUnique = new List( 32 ); - for( int i = 0; i < references.Count; i++ ) - references[i].CalculateShortUniquePaths( referencePathsShortUnique, Type == GroupType.Scene || Type == GroupType.DontDestroyOnLoad ); - - referencePathsShortest = new List( referencePathsShortUnique.Count ); - for( int i = 0; i < referencePathsShortUnique.Count; i++ ) - { - int[] linksToFollow = referencePathsShortUnique[i].pathLinksToFollow; - - // Find the last two nodes in this path - ReferenceNode nodeBeforeLast = referencePathsShortUnique[i].startNode; - for( int j = 0; j < linksToFollow.Length - 1; j++ ) - nodeBeforeLast = nodeBeforeLast[linksToFollow[j]].targetNode; - - // Check if these two nodes are unique - bool isUnique = true; - for( int j = 0; j < referencePathsShortest.Count; j++ ) - { - ReferencePath path = referencePathsShortest[j]; - if( path.startNode == nodeBeforeLast && path.pathLinksToFollow[0] == linksToFollow[linksToFollow.Length - 1] ) - { - isUnique = false; - break; - } - } - - if( isUnique ) - referencePathsShortest.Add( new ReferencePath( nodeBeforeLast, new int[1] { linksToFollow[linksToFollow.Length - 1] } ) ); } } // Draw the results found for this container - public void DrawOnGUI( SearchResultDrawParameters parameters ) + public float DrawOnGUI( SearchResult searchResult, EditorWindow window, float scrollPosition, bool noAssetDatabaseChanges ) { - if( Event.current.type == EventType.Repaint && ( guiNodes == null || parameters.pathDrawingMode != calculatedGUIMode || parameters.guiRect.width != calculatedGUIWidth ) ) - { - GenerateGUINodes( parameters ); - parameters.shouldRefreshEditorWindow = true; // A repaint is needed to work nicely with GUILayout - } - + Event ev = Event.current; Color c = GUI.backgroundColor; - GUI.backgroundColor = Color.cyan; - Rect rect = parameters.guiRect; - float width = rect.width; - rect.width = 40f; - rect.height = HEADER_HEIGHT; - if( GUI.Button( rect, IsExpanded ? "v" : ">" ) ) + float headerHeight = EditorGUIUtility.singleLineHeight * 2f; + float refreshButtonWidth = 100f; + + GUI.backgroundColor = AssetUsageDetectorSettings.SearchResultGroupHeaderColor; + + Rect headerRect = EditorGUILayout.GetControlRect( false, headerHeight ); + float width = headerRect.width; + headerRect.width = headerHeight; + if( GUI.Button( headerRect, IsExpanded ? "v" : ">" ) ) { IsExpanded = !IsExpanded; + if( ev.alt && treeView != null ) + { + if( !IsExpanded ) + treeView.CollapseAll(); + else + treeView.ExpandAll(); + } - parameters.shouldRefreshEditorWindow = true; + window.Repaint(); GUIUtility.ExitGUI(); } - rect.x += 40f; - rect.width = width - ( parameters.searchResult != null ? 140f : 40f ); - if( GUI.Button( rect, Title, Utilities.BoxGUIStyle ) && Type == GroupType.Scene ) + headerRect.x += headerHeight; + headerRect.width = width - ( searchResult != null ? ( refreshButtonWidth + headerHeight ) : headerHeight ); + + if( GUI.Button( headerRect, Title, Utilities.BoxGUIStyle ) ) { - if( Event.current.button != 1 ) + if( ev.button != 1 ) { - // If the container (scene, usually) is left clicked, highlight it on Project view - if( SearchResult.SelectClickedObjects ) - AssetDatabase.LoadAssetAtPath( Title ).SelectInEditor(); - else - AssetDatabase.LoadAssetAtPath( Title ).PingInEditor(); - } - else if( !EditorApplication.isPlaying && EditorSceneManager.loadedSceneCount > 1 ) - { - // Show context menu when SearchResultGroup's header is right clicked - Scene scene = EditorSceneManager.GetSceneByPath( Title ); - if( scene.isLoaded ) + if( Type == GroupType.Scene ) { - GenericMenu contextMenu = new GenericMenu(); - contextMenu.AddItem( new GUIContent( "Close Scene" ), false, () => + // If the container (scene, usually) is left clicked, highlight it on Project view + SceneAsset sceneAsset = AssetDatabase.LoadAssetAtPath( ScenePath ); + if( sceneAsset ) { - if( !scene.isDirty || EditorSceneManager.SaveModifiedScenesIfUserWantsTo( new Scene[1] { scene } ) ) - EditorSceneManager.CloseScene( scene, true ); - } ); - contextMenu.ShowAsContext(); + if( AssetUsageDetectorSettings.PingClickedObjects ) + EditorGUIUtility.PingObject( sceneAsset ); + if( AssetUsageDetectorSettings.SelectClickedObjects ) + Selection.activeObject = sceneAsset; + } } } - } - - if( parameters.searchResult != null ) - { - rect.x += width - 140f; - rect.width = 100f; - if( GUI.Button( rect, "Refresh" ) ) - { - parameters.searchResult.RefreshSearchResultGroup( this, parameters.noAssetDatabaseChanges ); - GUIUtility.ExitGUI(); - } - } - - rect = parameters.guiRect; - rect.y += HEADER_HEIGHT + 5f; - - if( IsExpanded ) - { - // On light skin, yellow background looks better than light grey background - GUI.backgroundColor = EditorGUIUtility.isProSkin ? c : Color.yellow; - - if( PendingSearch ) - { - rect.height = 25f; - GUI.Box( rect, "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle ); - } - else if( references.Count == 0 ) - { - rect.height = 25f; - GUI.Box( rect, "No references found...", Utilities.BoxGUIStyle ); - } - else if( guiNodes != null ) - { - rect.height = calculatedGUIHeight; - parameters.guiRect = rect; - - for( int i = 0; i < guiNodes.Length; i++ ) - guiNodes[i].DrawOnGUI( parameters ); - } - - rect.y += rect.height; - } - - parameters.guiRect = rect; - GUI.backgroundColor = c; - } - - private void GenerateGUINodes( SearchResultDrawParameters parameters ) - { - float guiRectWidth = parameters.guiRect.width; - - if( guiNodes == null || parameters.pathDrawingMode != calculatedGUIMode ) - { - if( parameters.pathDrawingMode == PathDrawingMode.Full ) - { - List stack = new List( 8 ); - guiNodes = new ReferenceNodeGUI[references.Count]; - - for( int i = 0; i < guiNodes.Length; i++ ) - guiNodes[i] = references[i].GenerateGUINodeRecursive( stack, null ); - } else { - if( referencePathsShortUnique == null ) - CalculateShortestPathsToReferences(); + GenericMenu contextMenu = new GenericMenu(); - List pathsToDraw; - if( parameters.pathDrawingMode == PathDrawingMode.ShortRelevantParts ) - pathsToDraw = referencePathsShortUnique; - else - pathsToDraw = referencePathsShortest; + if( searchResult != null ) + contextMenu.AddItem( new GUIContent( "Hide" ), false, () => searchResult.RemoveSearchResultGroup( this ) ); - guiNodes = new ReferenceNodeGUI[pathsToDraw.Count]; - - for( int i = 0; i < guiNodes.Length; i++ ) + if( references.Count > 0 ) { - ReferencePath path = pathsToDraw[i]; - ReferenceNode currentNode = path.startNode; + if( contextMenu.GetItemCount() > 0 ) + contextMenu.AddSeparator( "" ); - ReferenceNodeGUI currentNodeGUI = currentNode.GenerateGUINode( null ); - guiNodes[i] = currentNodeGUI; - - for( int j = 0; j < path.pathLinksToFollow.Length; j++ ) + if( Type != GroupType.UnusedObjects ) { - ReferenceNode.Link link = currentNode[path.pathLinksToFollow[j]]; - currentNodeGUI.links = new ReferenceNodeGUI[1] { link.targetNode.GenerateGUINode( link.description ) }; + contextMenu.AddItem( new GUIContent( "Expand Direct References Only" ), false, () => + { + treeView.ExpandDirectReferences(); + IsExpanded = true; + } ); - currentNode = link.targetNode; - currentNodeGUI = currentNodeGUI.links[0]; + contextMenu.AddItem( new GUIContent( "Expand Main References Only" ), false, () => + { + treeView.ExpandMainReferences(); + IsExpanded = true; + } ); } - currentNodeGUI.links = new ReferenceNodeGUI[0]; + if( !string.IsNullOrEmpty( treeViewState.searchTerm ) && treeViewState.searchMode == SearchResultTreeView.SearchMode.ReferencesOnly ) + { + contextMenu.AddItem( new GUIContent( "Expand Matching Search Results Only" ), false, () => + { + treeView.ExpandMatchingSearchResults(); + IsExpanded = true; + } ); + } + + contextMenu.AddItem( new GUIContent( "Expand All" ), false, () => + { + treeView.ExpandAll(); + IsExpanded = true; + } ); + + contextMenu.AddItem( new GUIContent( "Collapse All" ), false, () => + { + treeView.CollapseAll(); + IsExpanded = true; + } ); + + if( searchResult != null && searchResult.NumberOfGroups > 1 && !string.IsNullOrEmpty( treeViewState.searchTerm ) ) + { + if( contextMenu.GetItemCount() > 0 ) + contextMenu.AddSeparator( "" ); + + contextMenu.AddItem( new GUIContent( "Apply Search to All Results" ), false, () => + { + for( int i = 0; i < searchResult.NumberOfGroups; i++ ) + { + if( searchResult[i].treeView == null ) + continue; + + string previousSearchTerm = searchResult[i].treeViewState.searchTerm ?? ""; + SearchResultTreeView.SearchMode previousSearchMode = searchResult[i].treeViewState.searchMode; + + searchResult[i].treeViewState.searchTerm = treeViewState.searchTerm ?? ""; + searchResult[i].treeViewState.searchMode = treeViewState.searchMode; + + if( treeViewState.searchTerm != previousSearchTerm || treeViewState.searchMode != previousSearchMode ) + searchResult[i].treeView.RefreshSearch( previousSearchTerm ); + } + } ); + } } + + if( Type == GroupType.Scene && !EditorApplication.isPlaying && EditorSceneManager.loadedSceneCount > 1 ) + { + // Show context menu when SearchResultGroup's header is right clicked + Scene scene = EditorSceneManager.GetSceneByPath( ScenePath ); + if( scene.isLoaded ) + { + if( contextMenu.GetItemCount() > 0 ) + contextMenu.AddSeparator( "" ); + + contextMenu.AddItem( new GUIContent( "Close Scene" ), false, () => + { + if( !scene.isDirty || EditorSceneManager.SaveModifiedScenesIfUserWantsTo( new Scene[1] { scene } ) ) + EditorSceneManager.CloseScene( scene, true ); + } ); + } + } + + contextMenu.ShowAsContext(); + } + } + + if( searchResult != null ) + { + bool guiEnabled = GUI.enabled; + GUI.enabled = Type != GroupType.UnusedObjects; + + headerRect.x += width - ( refreshButtonWidth + headerHeight ); + headerRect.width = refreshButtonWidth; + if( GUI.Button( headerRect, "Refresh" ) ) + { + searchResult.RefreshSearchResultGroup( this, noAssetDatabaseChanges ); + GUIUtility.ExitGUI(); } - for( int i = 0; i < guiNodes.Length; i++ ) - guiNodes[i].CalculateDepth(); + GUI.enabled = guiEnabled; } - calculatedGUIMode = parameters.pathDrawingMode; - calculatedGUIWidth = guiRectWidth; + GUI.backgroundColor = c; - calculatedGUIHeight = -5f; // will start from -5f + 5f = 0f - for( int i = 0; i < guiNodes.Length; i++ ) + if( IsExpanded ) { - calculatedGUIHeight += 5f; - guiNodes[i].CalculateHeight( guiRectWidth ); - guiNodes[i].CalculateOffset( new Vector2( 0f, calculatedGUIHeight ) ); - calculatedGUIHeight += guiNodes[i].size.y; + if( PendingSearch ) + GUILayout.Box( "Lazy Search: this scene potentially has some references, hit Refresh to find them", Utilities.BoxGUIStyle ); + else if( references.Count == 0 ) + GUILayout.Box( ( Type == GroupType.UnusedObjects ) ? "No unused objects left..." : "No references found...", Utilities.BoxGUIStyle ); + else + { + if( Type == GroupType.UnusedObjects ) + { + if( searchResult != null && searchResult.HasPendingLazySceneSearchResults ) + EditorGUILayout.HelpBox( "Some scene(s) aren't searched yet (lazy scene search). Refreshing those scene(s) will automatically update this list.", MessageType.Warning ); + + if( searchResult != null && searchResult.SearchParameters.dontSearchInSourceAssets && searchResult.SearchParameters.objectsToSearch.Length > 1 ) + EditorGUILayout.HelpBox( "'Don't search \"SEARCHED OBJECTS\" themselves for references' is enabled, some of these objects might be used by \"SEARCHED OBJECTS\".", MessageType.Warning ); + + EditorGUILayout.HelpBox( "Although no references to these objects are found, they might still be used somewhere (e.g. via Resources.Load). If you intend to delete these objects, consider creating a backup of your project first.", MessageType.Info ); + } + + if( treeView == null ) + { + bool isFirstInitialization = ( treeViewState == null ); + if( isFirstInitialization ) + treeViewState = new SearchResultTreeViewState(); + + // This isn't inside isFirstInitialization because SearchResultTreeViewState might have been initialized by + // Unity's serialization system after a domain reload + bool shouldUpdateInitialTreeViewNodeId = ( treeViewState.initialNodeId == 0 && searchResult != null ); + if( shouldUpdateInitialTreeViewNodeId ) + treeViewState.initialNodeId = searchResult.nextTreeViewId; + + treeView = new SearchResultTreeView( treeViewState, references, ( Type == GroupType.UnusedObjects ) ? SearchResultTreeView.TreeType.UnusedObjects : SearchResultTreeView.TreeType.Normal, searchResult != null ? searchResult.UsedObjects : null, searchResult != null && searchResult.SearchParameters.hideDuplicateRows, searchResult != null && searchResult.SearchParameters.hideReduntantPrefabVariantLinks, true ); + + if( isFirstInitialization ) + { + if( Type != GroupType.UnusedObjects ) + treeView.ExpandMainReferences(); + else + treeView.ExpandAll(); + } + + if( shouldUpdateInitialTreeViewNodeId ) + searchResult.nextTreeViewId = treeViewState.finalNodeId; + } + + if( treeViewSearchField == null ) + { + treeViewSearchField = new SearchField() { autoSetFocusOnFindCommand = false }; + treeViewSearchField.downOrUpArrowKeyPressed += () => treeView.SetFocusAndEnsureSelectedItem(); // Not assigning SetFocusAndEnsureSelectedItem directly in case treeView's value changes + } + + Rect searchFieldRect = EditorGUILayout.GetControlRect( false, EditorGUIUtility.singleLineHeight ); + string previousSearchTerm = treeViewState.searchTerm ?? ""; + SearchResultTreeView.SearchMode previousSearchMode = treeViewState.searchMode; + treeViewState.searchTerm = treeViewSearchField.OnToolbarGUI( new Rect( searchFieldRect.x, searchFieldRect.y, searchFieldRect.width - 100f, searchFieldRect.height ), treeViewState.searchTerm ) ?? ""; + treeViewState.searchMode = (SearchResultTreeView.SearchMode) EditorGUI.EnumPopup( new Rect( searchFieldRect.xMax - 100f, searchFieldRect.y, 100f, searchFieldRect.height ), treeViewState.searchMode ); + if( treeViewState.searchTerm != previousSearchTerm || treeViewState.searchMode != previousSearchMode ) + treeView.RefreshSearch( previousSearchTerm ); + + KeyCode pressedKeyboardNavigationKey = KeyCode.None; + bool treeViewKeyboardNavigation = false; + if( ev.type == EventType.KeyDown ) + { + pressedKeyboardNavigationKey = ev.keyCode; + switch( pressedKeyboardNavigationKey ) + { + case KeyCode.UpArrow: + case KeyCode.DownArrow: + case KeyCode.LeftArrow: + case KeyCode.RightArrow: + case KeyCode.PageUp: + case KeyCode.PageDown: + case KeyCode.Home: + case KeyCode.End: + case KeyCode.F: treeViewKeyboardNavigation = true; break; + } + + SearchResultTooltip.Hide(); + } + else if( ( ev.type == EventType.ValidateCommand || ev.type == EventType.ExecuteCommand ) && ev.commandName == "Find" && treeView.HasFocus() ) + { + if( ev.type == EventType.ExecuteCommand ) + { + treeViewSearchField.SetFocus(); + + // Framed rect padding: Top = 2, Bottom = 2 + the first element in the TreeView + scrollPosition = FrameRectInScrollView( scrollPosition, new Vector2( searchFieldRect.y - 2f, searchFieldRect.yMax + EditorGUIUtility.singleLineHeight + 2f ), window.position.height ); + window.Repaint(); + + SearchResultTooltip.Hide(); + } + + ev.Use(); + } + else if( ev.type == EventType.ScrollWheel ) + SearchResultTooltip.Hide(); + + bool isFirstRowSelected = false, isLastRowSelected = false, isSelectedRowExpanded = false, canExpandSelectedRow = false; + if( treeViewKeyboardNavigation && treeView.HasFocus() && treeView.HasSelection() ) + treeView.GetRowStateWithId( treeViewState.lastClickedID, out isFirstRowSelected, out isLastRowSelected, out isSelectedRowExpanded, out canExpandSelectedRow ); + + Rect treeViewRect = EditorGUILayout.GetControlRect( false, treeView.totalHeight ); + if( ev.type == EventType.Repaint ) + { + lastTreeViewRect = treeViewRect; + +#if !UNITY_2018_2_OR_NEWER + // TreeView calls RowGUI for all rows instead of only the visible rows on early Unity versions which leads to performance issues. Do manual row culling on those versions + // Credit: https://github.com/Unity-Technologies/UnityCsReference/blob/a048de916b23331bf6dfe92c4a6c205989b83b4f/Editor/Mono/GUI/TreeView/TreeViewGUI.cs#L273-L276 + float topPixel = scrollPosition - treeViewRect.y; + float heightInPixels = window.position.height; + treeView.visibleRowTop = (int) Mathf.Floor( topPixel / treeView.rowHeight ); + treeView.visibleRowBottom = treeView.visibleRowTop + (int) Mathf.Ceil( heightInPixels / treeView.rowHeight ); +#endif + } + + treeView.OnGUI( treeViewRect ); + + if( treeViewKeyboardNavigation && treeView.HasFocus() && treeView.HasSelection() ) + { + Rect targetTreeViewRowRect; + if( treeView.GetRowRectWithId( treeViewState.lastClickedID, out targetTreeViewRowRect ) ) + { + // Allow keyboard navigation between different SearchResultGroups' TreeViews + Rect targetTreeViewRect = lastTreeViewRect; + if( !ev.control && !ev.command && !ev.shift ) + { + if( isFirstRowSelected && ( pressedKeyboardNavigationKey == KeyCode.UpArrow || pressedKeyboardNavigationKey == KeyCode.PageUp || pressedKeyboardNavigationKey == KeyCode.Home || ( pressedKeyboardNavigationKey == KeyCode.LeftArrow && !isSelectedRowExpanded ) ) ) + { + int searchResultGroupIndex = searchResult.IndexOf( this ); + for( int i = searchResultGroupIndex - 1; i >= 0; i-- ) + { + if( !searchResult[i].PendingSearch && searchResult[i].IsExpanded && searchResult[i].references.Count > 0 ) + { + searchResult[i].treeView.SetFocus(); + + targetTreeViewRect = searchResult[i].lastTreeViewRect; + targetTreeViewRowRect = searchResult[i].treeView.SelectLastRowAndReturnRect(); + + break; + } + } + } + else if( isLastRowSelected && ( pressedKeyboardNavigationKey == KeyCode.DownArrow || pressedKeyboardNavigationKey == KeyCode.PageDown || pressedKeyboardNavigationKey == KeyCode.End || ( pressedKeyboardNavigationKey == KeyCode.RightArrow && !canExpandSelectedRow ) ) ) + { + int searchResultGroupIndex = searchResult.IndexOf( this ); + for( int i = searchResultGroupIndex + 1; i < searchResult.NumberOfGroups; i++ ) + { + if( !searchResult[i].PendingSearch && searchResult[i].IsExpanded && searchResult[i].references.Count > 0 ) + { + searchResult[i].treeView.SetFocus(); + + targetTreeViewRect = searchResult[i].lastTreeViewRect; + targetTreeViewRowRect = searchResult[i].treeView.SelectFirstRowAndReturnRect(); + + break; + } + } + } + } + + // When key event isn't automatically used by the focused TreeView (happens when its search results are empty), if we navigate to + // a new TreeView, key event will be consumed by that TreeView and hence, keyboard navigation will occur twice + if( ev.type != EventType.Used ) + ev.Use(); + + float scrollTop = targetTreeViewRect.y + targetTreeViewRowRect.y; + float scrollBottom = targetTreeViewRect.y + targetTreeViewRowRect.yMax; + + scrollPosition = FrameRectInScrollView( scrollPosition, new Vector2( scrollTop, scrollBottom ), window.position.height ); + window.Repaint(); + } + } + } } + + return scrollPosition; + } + + // Frame selection (it isn't handled automatically when using an external scroll view) + // Credit: https://github.com/Unity-Technologies/UnityCsReference/blob/d0fe81a19ce788fd1d94f826cf797aafc37db8ea/Editor/Mono/GUI/TreeView/TreeViewController.cs#L1329-L1351 + private float FrameRectInScrollView( float scrollPosition, Vector2 rectBounds, float windowHeight ) + { + return Mathf.Clamp( scrollPosition, rectBounds.y - windowHeight, rectBounds.x ); } // Serialize this result group - public SearchResult.SerializableResultGroup Serialize( Dictionary nodeToIndex, List serializedNodes ) + internal SearchResult.SerializableResultGroup Serialize( Dictionary nodeToIndex, List serializedNodes ) { SearchResult.SerializableResultGroup serializedResultGroup = new SearchResult.SerializableResultGroup() { title = Title, type = Type, isExpanded = IsExpanded, - pendingSearch = PendingSearch + pendingSearch = PendingSearch, + treeViewState = treeViewState }; if( references != null ) @@ -900,31 +1040,44 @@ namespace AssetUsageDetectorNamespace } // Deserialize this result group from the serialized data - public void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List allNodes ) + internal void Deserialize( SearchResult.SerializableResultGroup serializedResultGroup, List allNodes ) { + treeViewState = serializedResultGroup.treeViewState; + if( serializedResultGroup.initialSerializedNodes != null ) { for( int i = 0; i < serializedResultGroup.initialSerializedNodes.Count; i++ ) references.Add( allNodes[serializedResultGroup.initialSerializedNodes[i]] ); } - - referencePathsShortUnique = null; - referencePathsShortest = null; } + + IEnumerator IEnumerable.GetEnumerator() { return ( (IEnumerable) references ).GetEnumerator(); } + IEnumerator IEnumerable.GetEnumerator() { return ( (IEnumerable) references ).GetEnumerator(); } } // Custom class to hold an object in the path to a reference as a node public class ReferenceNode { - public struct Link + internal enum UsedState { Unused, MixedCollapsed, MixedExpanded, Used }; + + public class Link { public readonly ReferenceNode targetNode; - public readonly string description; + public readonly List descriptions; + public bool isWeakLink; // Weak links can be omitted from search results if this ReferenceNode isn't referenced by any other node - public Link( ReferenceNode targetNode, string description ) + public Link( ReferenceNode targetNode, string description, bool isWeakLink ) { this.targetNode = targetNode; - this.description = description; + this.descriptions = string.IsNullOrEmpty( description ) ? new List() : new List( 1 ) { description }; + this.isWeakLink = isWeakLink; + } + + public Link( ReferenceNode targetNode, List descriptions, bool isWeakLink ) + { + this.targetNode = targetNode; + this.descriptions = descriptions; + this.isWeakLink = isWeakLink; } } @@ -932,25 +1085,27 @@ namespace AssetUsageDetectorNamespace private static int uid_last = 0; private readonly int uid; + public string Label { get; private set; } + public bool IsMainReference { get; private set; } // True: if belongs to a scene search result group, then it's an object in that scene. If belongs to the assets search result group, then it's an asset + internal object nodeObject; private int? instanceId; // instanceId of the nodeObject if it is a Unity object, null otherwise - private string description; // String to print on this node - - private readonly List links; - public Object UnityObject { get { return instanceId.HasValue ? EditorUtility.InstanceIDToObject( instanceId.Value ) : null; } } + private readonly List links = new List( 2 ); public int NumberOfOutgoingLinks { get { return links.Count; } } public Link this[int index] { get { return links[index]; } } + internal UsedState usedState; + public ReferenceNode() { - links = new List( 2 ); uid = uid_last++; + usedState = UsedState.Used; } // Add a one-way connection to another node - public void AddLinkTo( ReferenceNode nextNode, string description = null ) + public void AddLinkTo( ReferenceNode nextNode, string description = null, bool isWeakLink = false ) { if( nextNode != null && nextNode != this ) { @@ -962,163 +1117,82 @@ namespace AssetUsageDetectorNamespace { if( links[i].targetNode == nextNode ) { - if( !string.IsNullOrEmpty( description ) ) - { - if( !string.IsNullOrEmpty( links[i].description ) ) - { - // Avoid duplicate descriptions - if( !links[i].description.Contains( description ) ) - links[i] = new Link( links[i].targetNode, string.Concat( links[i].description, Environment.NewLine, description ) ); - } - else - links[i] = new Link( links[i].targetNode, description ); - } + if( !string.IsNullOrEmpty( description ) && !links[i].descriptions.Contains( description ) ) + links[i].descriptions.Add( description ); + links[i].isWeakLink &= isWeakLink; return; } } - links.Add( new Link( nextNode, description ) ); + links.Add( new Link( nextNode, description, isWeakLink ) ); } } + public void RemoveLink( int index ) + { + links.RemoveAt( index ); + } + + public bool RemoveLink( ReferenceNode nextNode ) + { + for( int i = links.Count - 1; i >= 0; i-- ) + { + if( links[i].targetNode == nextNode ) + { + links.RemoveAt( i ); + return true; + } + } + + return false; + } + + public void SortLinks() + { + if( links.Count > 1 ) + { + SearchResult.SortedEntry[] sortedEntries = new SearchResult.SortedEntry[links.Count]; + for( int i = links.Count - 1; i >= 0; i-- ) + sortedEntries[i] = new SearchResult.SortedEntry( links[i] ); + + Array.Sort( sortedEntries ); + + for( int i = 0; i < sortedEntries.Length; i++ ) + links[i] = (Link) sortedEntries[i].entry; + } + } + + internal bool HasLinkToObjectWithDescriptions( int instanceId, List descriptions ) + { + for( int i = links.Count - 1; i >= 0; i-- ) + { + Link link = links[i]; + if( link.targetNode.instanceId == instanceId ) + { + List _descriptions = link.descriptions; + if( _descriptions.Count != descriptions.Count ) + return false; + + for( int j = _descriptions.Count - 1; j >= 0; j-- ) + { + if( _descriptions[j] != descriptions[j] ) + return false; + } + + return true; + } + } + + return false; + } + public void CopyReferencesTo( ReferenceNode other ) { other.links.Clear(); other.links.AddRange( links ); } - // Remove any redundant connections that this node has - public void VerifyLinksRecursively() - { - // Make sure that this functions isn't called multiple times per node (avoids StackOverflowException) - if( description != null ) - return; - - description = ""; - - for( int i = links.Count - 1; i >= 0; i-- ) - { - // Links from a GameObject to its components should be omitted if the component has no references (these are redundant links) - if( links[i].targetNode.links.Count == 0 && nodeObject is GameObject ) - { - Component component = links[i].targetNode.nodeObject as Component; - if( component != null && !component.Equals( null ) && component.gameObject == (GameObject) nodeObject ) - { - links.RemoveAtFast( i ); - continue; - } - } - - links[i].targetNode.VerifyLinksRecursively(); - } - - description = null; - } - - // Initialize node's commonly used variables - public void InitializeRecursively() - { - if( description != null ) // Already initialized - return; - - Object unityObject = nodeObject as Object; - if( unityObject != null ) - { - instanceId = unityObject.GetInstanceID(); - description = unityObject.name + " (" + unityObject.GetType() + ")"; - } - else if( nodeObject != null ) - { - instanceId = null; - description = nodeObject.GetType() + " object"; - } - else - { - instanceId = null; - description = "<>"; - } - - nodeObject = null; // Don't hold Object reference, allow Unity to GC used memory - - for( int i = 0; i < links.Count; i++ ) - links[i].targetNode.InitializeRecursively(); - } - - // Finds all leaf nodes that originate from this node and have GameObject/Component node objects in the specified scene - public void GetLeafSceneNodesRecursive( Scene scene, HashSet leafNodes, ReferenceNode latestSceneObjectNode, HashSet objectsToSearchSet, List callStack ) - { - if( links.Count == 0 || callStack.ContainsFast( this ) || ( nodeObject is Object && objectsToSearchSet.Contains( (Object) nodeObject ) ) ) // This is a searched object's node - { - leafNodes.Add( latestSceneObjectNode ); - return; - } - - Object unityObject = nodeObject as Object; - if( unityObject != null ) - { - if( AssetDatabase.Contains( unityObject ) ) - { - leafNodes.Add( latestSceneObjectNode ); - return; - } - else if( unityObject is Component ) - { - if( ( (Component) unityObject ).gameObject.scene == scene ) - latestSceneObjectNode = this; - else - { - leafNodes.Add( latestSceneObjectNode ); - return; - } - } - else if( unityObject is GameObject ) - { - if( ( (GameObject) unityObject ).scene == scene ) - latestSceneObjectNode = this; - else - { - leafNodes.Add( latestSceneObjectNode ); - return; - } - } - } - - callStack.Add( this ); - - for( int i = 0; i < links.Count; i++ ) - links[i].targetNode.GetLeafSceneNodesRecursive( scene, leafNodes, latestSceneObjectNode, objectsToSearchSet, callStack ); - - callStack.RemoveAt( callStack.Count - 1 ); - } - - // Returns whether or not specified node is part of this node's siblings - public bool NodeExistsInChildrenRecursive( ReferenceNode node, List callStack ) - { - if( callStack.ContainsFast( this ) ) - return false; - - for( int i = 0; i < links.Count; i++ ) - { - if( links[i].targetNode == node ) - return true; - } - - callStack.Add( this ); - - for( int i = 0; i < links.Count; i++ ) - { - if( links[i].targetNode.NodeExistsInChildrenRecursive( node, callStack ) ) - { - callStack.RemoveAt( callStack.Count - 1 ); - return true; - } - } - - callStack.RemoveAt( callStack.Count - 1 ); - return false; - } - // Clear this node so that it can be reused later public void Clear() { @@ -1126,105 +1200,136 @@ namespace AssetUsageDetectorNamespace links.Clear(); } - // Calculate short unique paths that start with this node - public void CalculateShortUniquePaths( List currentPaths, bool startPathsWithSceneObjects ) + public void InitializeRecursively() { - CalculateShortUniquePaths( currentPaths, startPathsWithSceneObjects, new List( 8 ), new List( 8 ) { -1 }, 0, new List( 8 ) ); + if( Label != null ) // Already initialized + return; + + Object unityObject = nodeObject as Object; + if( unityObject != null ) + { + instanceId = unityObject.GetInstanceID(); + Label = unityObject.name + " (" + unityObject.GetType().Name + ")"; + } + else if( nodeObject != null ) + { + instanceId = null; + Label = nodeObject.GetType() + " object"; + } + else + { + instanceId = null; + Label = "<>"; + } + + nodeObject = null; // Don't hold Object reference, allow Unity to GC used memory + + for( int i = 0; i < links.Count; i++ ) + links[i].targetNode.InitializeRecursively(); } - // Just some boring calculations to find the short unique paths recursively - private void CalculateShortUniquePaths( List shortestPaths, bool startPathsWithSceneObjects, List currentPath, List currentPathIndices, int latestObjectIndexInPath, List stack ) + public ReferenceNode CreateReverseGraphRecursively( SearchResultGroup searchResultGroup, List reverseGraphRoots, Dictionary reverseGraphNodes, HashSet objectsToSearchSet ) { - int currentIndex = currentPath.Count; - currentPath.Add( this ); - - if( links.Count == 0 || stack.ContainsFast( this ) ) + ReferenceNode result; + if( !reverseGraphNodes.TryGetValue( this, out result ) ) { - // Check if the path to the reference is unique (not discovered so far) - bool isUnique = true; - for( int i = 0; i < shortestPaths.Count; i++ ) - { - if( shortestPaths[i].startNode == currentPath[latestObjectIndexInPath] && shortestPaths[i].pathLinksToFollow.Length == currentPathIndices.Count - latestObjectIndexInPath - 1 ) - { - int j = latestObjectIndexInPath + 1; - for( int k = 0; j < currentPathIndices.Count; j++, k++ ) - { - if( shortestPaths[i].pathLinksToFollow[k] != currentPathIndices[j] ) - break; - } + reverseGraphNodes[this] = result = new ReferenceNode() { nodeObject = nodeObject }; - if( j == currentPathIndices.Count ) + Object obj = nodeObject as Object; + if( obj && objectsToSearchSet.Contains( obj ) ) + reverseGraphRoots.Add( result ); + //else // When 'else' is uncommented, 'Don't search "Find referenced of" themselves for references" option simply does nothing. I am not entirely sure if commenting it out will have any side effects, so fingers crossed? + { + for( int i = 0; i < links.Count; i++ ) + { + ReferenceNode linkedNode = links[i].targetNode.CreateReverseGraphRecursively( searchResultGroup, reverseGraphRoots, reverseGraphNodes, objectsToSearchSet ); + linkedNode.links.Add( new Link( result, links[i].descriptions, links[i].isWeakLink ) ); + } + } + + if( obj ) + { + if( obj is Component ) + obj = ( (Component) obj ).gameObject; + + switch( searchResultGroup.Type ) + { + case SearchResultGroup.GroupType.Assets: result.IsMainReference = obj.IsAsset() && ( obj is GameObject || ( obj.hideFlags & ( HideFlags.HideInInspector | HideFlags.HideInHierarchy ) ) == HideFlags.None ); break; + case SearchResultGroup.GroupType.ProjectSettings: result.IsMainReference = obj.IsAsset() && AssetDatabase.GetAssetPath( obj ).StartsWith( "ProjectSettings/" ); break; + case SearchResultGroup.GroupType.Scene: + case SearchResultGroup.GroupType.DontDestroyOnLoad: { - isUnique = false; + if( obj is GameObject ) + { + Scene scene = ( (GameObject) obj ).scene; + if( scene.IsValid() ) + result.IsMainReference = ( searchResultGroup.Type == SearchResultGroup.GroupType.Scene ) ? scene.path == searchResultGroup.ScenePath : scene.name == "DontDestroyOnLoad"; + } + break; } } } - - // Don't allow duplicate short paths - if( isUnique ) - { - int[] pathIndices = new int[currentPathIndices.Count - latestObjectIndexInPath - 1]; - for( int i = latestObjectIndexInPath + 1, j = 0; i < currentPathIndices.Count; i++, j++ ) - pathIndices[j] = currentPathIndices[i]; - - shortestPaths.Add( new SearchResultGroup.ReferencePath( currentPath[latestObjectIndexInPath], pathIndices ) ); - } - } - else - { - if( instanceId.HasValue ) // nodeObject is Unity object - { - if( !startPathsWithSceneObjects || !AssetDatabase.Contains( instanceId.Value ) ) - latestObjectIndexInPath = currentIndex; - } - - for( int i = 0; i < links.Count; i++ ) - { - currentPathIndices.Add( i ); - stack.Add( this ); - - links[i].targetNode.CalculateShortUniquePaths( shortestPaths, startPathsWithSceneObjects, currentPath, currentPathIndices, latestObjectIndexInPath, stack ); - - stack.RemoveAt( stack.Count - 1 ); - currentPathIndices.RemoveAt( currentIndex + 1 ); - } } - currentPath.RemoveAt( currentIndex ); + return result; } - public ReferenceNodeGUI GenerateGUINode( string linkToPrevNodeDescription ) + public void RemoveRedundantLinksRecursively( HashSet visitedNodes ) { - return new ReferenceNodeGUI() + if( !visitedNodes.Add( this ) ) + return; + + List stack = null; + for( int i = links.Count - 1; i >= 0; i-- ) { - label = new GUIContent( string.IsNullOrEmpty( linkToPrevNodeDescription ) ? description : ( linkToPrevNodeDescription + "\n" + description ) ), - instanceId = instanceId - }; - } + if( !links[i].isWeakLink ) + continue; - public ReferenceNodeGUI GenerateGUINodeRecursive( List stack, string linkToPrevNodeDescription ) - { - ReferenceNodeGUI guiNode = GenerateGUINode( linkToPrevNodeDescription ); + if( links[i].targetNode.links.Count == 0 ) + links.RemoveAt( i ); + else + { + if( stack == null ) + stack = new List( 2 ); + else + stack.Clear(); - if( stack.ContainsFast( this ) ) - guiNode.links = new ReferenceNodeGUI[0]; - else - { - stack.Add( this ); - - guiNode.links = new ReferenceNodeGUI[links.Count]; - for( int i = 0; i < links.Count; i++ ) - guiNode.links[i] = links[i].targetNode.GenerateGUINodeRecursive( stack, links[i].description ); - - stack.RemoveAt( stack.Count - 1 ); + if( !links[i].targetNode.CheckForNonWeakLinksRecursively( stack ) ) + links.RemoveAt( i ); + } } - return guiNode; + for( int i = links.Count - 1; i >= 0; i-- ) + links[i].targetNode.RemoveRedundantLinksRecursively( visitedNodes ); + } + + private bool CheckForNonWeakLinksRecursively( List stack ) + { + if( stack.Contains( this ) || links.Count == 0 ) + return false; + + for( int i = links.Count - 1; i >= 0; i-- ) + { + if( !links[i].isWeakLink ) + return true; + } + + stack.Add( this ); + + for( int i = links.Count - 1; i >= 0; i-- ) + { + if( links[i].targetNode.CheckForNonWeakLinksRecursively( stack ) ) + return true; + } + + stack.RemoveAt( stack.Count - 1 ); + + return false; } // Serialize this node and its connected nodes recursively - public int SerializeRecursively( Dictionary nodeToIndex, List serializedNodes ) + internal int SerializeRecursively( Dictionary nodeToIndex, List serializedNodes ) { int index; if( nodeToIndex.TryGetValue( this, out index ) ) @@ -1232,9 +1337,11 @@ namespace AssetUsageDetectorNamespace SearchResult.SerializableNode serializedNode = new SearchResult.SerializableNode() { + label = Label, + isMainReference = IsMainReference, instanceId = instanceId ?? 0, isUnityObject = instanceId.HasValue, - description = description + usedState = usedState }; index = serializedNodes.Count; @@ -1244,12 +1351,14 @@ namespace AssetUsageDetectorNamespace if( links.Count > 0 ) { serializedNode.links = new List( links.Count ); - serializedNode.linkDescriptions = new List( links.Count ); + serializedNode.linkDescriptions = new List( links.Count ); + serializedNode.linkWeakStates = new List( links.Count ); for( int i = 0; i < links.Count; i++ ) { serializedNode.links.Add( links[i].targetNode.SerializeRecursively( nodeToIndex, serializedNodes ) ); - serializedNode.linkDescriptions.Add( links[i].description ); + serializedNode.linkDescriptions.Add( new SearchResult.SerializableNode.SerializableLinkDescriptions() { value = links[i].descriptions } ); + serializedNode.linkWeakStates.Add( links[i].isWeakLink ); } } @@ -1257,19 +1366,21 @@ namespace AssetUsageDetectorNamespace } // Deserialize this node and its links from the serialized data - public void Deserialize( SearchResult.SerializableNode serializedNode, List allNodes ) + internal void Deserialize( SearchResult.SerializableNode serializedNode, List allNodes ) { if( serializedNode.isUnityObject ) instanceId = serializedNode.instanceId; else instanceId = null; - description = serializedNode.description; + Label = serializedNode.label; + IsMainReference = serializedNode.isMainReference; + usedState = serializedNode.usedState; if( serializedNode.links != null ) { for( int i = 0; i < serializedNode.links.Count; i++ ) - links.Add( new Link( allNodes[serializedNode.links[i]], serializedNode.linkDescriptions[i] ) ); + links.Add( new Link( allNodes[serializedNode.links[i]], serializedNode.linkDescriptions[i].value, serializedNode.linkWeakStates[i] ) ); } } @@ -1278,98 +1389,4 @@ namespace AssetUsageDetectorNamespace return uid; } } - - public class ReferenceNodeGUI - { - public GUIContent label; - public ReferenceNodeGUI[] links; - public int? instanceId; - - private int depth; - - private Vector2 offset; - public Vector2 size; - - public void CalculateDepth() - { - depth = 0; - - for( int i = 0; i < links.Length; i++ ) - { - links[i].CalculateDepth(); - if( links[i].depth > depth ) - depth = links[i].depth; - } - - depth++; - } - - public void CalculateHeight( float totalWidth ) - { - size.x = totalWidth / depth; - totalWidth -= size.x; - size.y = Utilities.BoxGUIStyle.CalcHeight( label, size.x ); - float connectedNodesHeight = 0f; - for( int i = 0; i < links.Length; i++ ) - { - links[i].CalculateHeight( totalWidth ); - connectedNodesHeight += links[i].size.y; - } - - if( size.y < connectedNodesHeight ) - size.y = connectedNodesHeight; - else if( size.y > connectedNodesHeight ) - ExpandHeightLeftToRight(); - } - - private void ExpandHeightLeftToRight() - { - float connectedNodesHeight = 0f; - for( int i = 0; i < links.Length; i++ ) - connectedNodesHeight += links[i].size.y; - - if( size.y > connectedNodesHeight ) - { - for( int i = 0; i < links.Length; i++ ) - { - links[i].size.y = size.y * links[i].size.y / connectedNodesHeight; - links[i].ExpandHeightLeftToRight(); - } - } - } - - public void CalculateOffset( Vector2 baseOffset ) - { - offset = baseOffset; - baseOffset.x += size.x; - - for( int i = 0; i < links.Length; i++ ) - { - links[i].CalculateOffset( baseOffset ); - baseOffset.y += links[i].size.y; - } - } - - public void DrawOnGUI( SearchResultDrawParameters parameters ) - { - Rect rect = parameters.guiRect; - rect.position += offset; - rect.size = size; - - if( GUI.Button( rect, label, Utilities.BoxGUIStyle ) && instanceId.HasValue ) - { - // If a reference is clicked, highlight it (either on Hierarchy view or Project view) - if( SearchResult.SelectClickedObjects ) - EditorUtility.InstanceIDToObject( instanceId.Value ).SelectInEditor(); - else - EditorUtility.InstanceIDToObject( instanceId.Value ).PingInEditor(); - } - - for( int i = 0; i < links.Length; i++ ) - links[i].DrawOnGUI( parameters ); - - if( parameters.showTooltips && Event.current.type == EventType.Repaint && rect.Contains( Event.current.mousePosition ) ) - parameters.tooltip = label.text; - } - } } \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/SearchResultTooltip.cs b/Plugins/AssetUsageDetector/Editor/SearchResultTooltip.cs new file mode 100644 index 0000000..9785717 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/SearchResultTooltip.cs @@ -0,0 +1,91 @@ +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace AssetUsageDetectorNamespace +{ + public class SearchResultTooltip : EditorWindow + { + private static SearchResultTooltip mainWindow; + private static string tooltip; + + private static GUIStyle m_style; + internal static GUIStyle Style + { + get + { + if( m_style == null ) + { + m_style = (GUIStyle) typeof( EditorStyles ).GetProperty( "tooltip", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ).GetValue( null, null ); + m_style.richText = true; + } + + return m_style; + } + } + + public static void Show( Rect sourcePosition, string tooltip ) + { + Vector2 preferredSize = Style.CalcSize( new GUIContent( tooltip ) ) + Style.contentOffset + new Vector2( Style.padding.horizontal + Style.margin.horizontal, Style.padding.vertical + Style.margin.vertical ); + Rect preferredPosition; + + Rect positionLeft = new Rect( sourcePosition.position - new Vector2( preferredSize.x, 0f ), preferredSize ); + Rect screenFittedPositionLeft = Utilities.GetScreenFittedRect( positionLeft ); + + Vector2 positionOffset = positionLeft.position - screenFittedPositionLeft.position; + Vector2 sizeOffset = positionLeft.size - screenFittedPositionLeft.size; + if( positionOffset.sqrMagnitude <= 400f && sizeOffset.sqrMagnitude <= 400f ) + preferredPosition = screenFittedPositionLeft; + else + { + Rect positionRight = new Rect( sourcePosition.position + new Vector2( sourcePosition.width, 0f ), preferredSize ); + Rect screenFittedPositionRight = Utilities.GetScreenFittedRect( positionRight ); + + Vector2 positionOffset2 = positionRight.position - screenFittedPositionRight.position; + Vector2 sizeOffset2 = positionRight.size - screenFittedPositionRight.size; + if( positionOffset2.magnitude + sizeOffset2.magnitude < positionOffset.magnitude + sizeOffset.magnitude ) + preferredPosition = screenFittedPositionRight; + else + preferredPosition = screenFittedPositionLeft; + } + + // Don't lose focus to the previous window + EditorWindow prevFocusedWindow = focusedWindow; + + if( !mainWindow ) + { + mainWindow = CreateInstance(); + mainWindow.ShowPopup(); + } + + SearchResultTooltip.tooltip = tooltip; + mainWindow.minSize = preferredPosition.size; + mainWindow.position = preferredPosition; + mainWindow.Repaint(); + + if( prevFocusedWindow ) + prevFocusedWindow.Focus(); + } + + public static void Hide() + { + if( mainWindow ) + { + mainWindow.Close(); + mainWindow = null; + } + } + + private void OnGUI() + { + // If somehow the tooltip isn't automatically closed, allow closing it by clicking on it + if( Event.current.type == EventType.MouseDown ) + { + Hide(); + GUIUtility.ExitGUI(); + } + + GUI.Label( new Rect( Vector2.zero, position.size ), tooltip, Style ); + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/SearchResultTooltip.cs.meta b/Plugins/AssetUsageDetector/Editor/SearchResultTooltip.cs.meta new file mode 100644 index 0000000..8f0008c --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/SearchResultTooltip.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c8bd4351b5024324ca5974ebcad1dde3 +timeCreated: 1639247551 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/SearchResultTreeView.cs b/Plugins/AssetUsageDetector/Editor/SearchResultTreeView.cs new file mode 100644 index 0000000..6f6c364 --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/SearchResultTreeView.cs @@ -0,0 +1,1367 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Reflection; +using System.Text; +using UnityEditor; +using UnityEditor.IMGUI.Controls; +using UnityEngine; +#if UNITY_2018_3_OR_NEWER +using PrefabStage = UnityEditor.Experimental.SceneManagement.PrefabStage; +using PrefabStageUtility = UnityEditor.Experimental.SceneManagement.PrefabStageUtility; +#endif + +namespace AssetUsageDetectorNamespace +{ + [System.Serializable] + public class SearchResultTreeViewState : TreeViewState + { + // - initialNodeId is serialized because we want to preserve the expanded states of the TreeViewItems after domain reload and + // it's only possible if TreeView is reconstructed with the same ids + // - finalNodeId is serialized because if the same id used for multiple TreeViewItems across multiple TreeViews, strange issues occur. + // Thus, each new TreeView will set its initialNodeId to the previous TreeView's finalNodeId + // - Each TreeViewItem's id is different even if two TreeViewItems point to the exact same ReferenceNode. That's because TreeView + // doesn't work well when some TreeViewItems share the same id (e.g. while navigating the tree with arrow keys) + public int initialNodeId, finalNodeId; + + // Not using the built-in searchString and hasSearch properties of TreeView because: + // - This search algorithm is a bit more complicated than usual, we don't flatten the tree during the search + // - If code is recompiled while searchString wasn't empty, the tree isn't rebuilt and remains empty (at least on Unity 5.6) + public string searchTerm; + public SearchResultTreeView.SearchMode searchMode = SearchResultTreeView.SearchMode.All; + public bool selectionChangedDuringSearch; + + public List preSearchExpandedIds; + } + + public class SearchResultTreeView : TreeView + { + public enum TreeType { Normal, UnusedObjects, IsolatedView }; + public enum SearchMode { SearchedObjectsOnly, ReferencesOnly, All }; + + private class ReferenceNodeData + { + public readonly TreeViewItem item; + public readonly ReferenceNode node; + public readonly ReferenceNodeData parent; + public readonly int linkIndex; + public bool isLastLink; + public bool isDuplicate; + public bool shouldExpandAfterSearch; + + private string m_tooltipText; + public string tooltipText + { + get + { + if( m_tooltipText != null ) + return m_tooltipText; + + return GetTooltipText( Utilities.stringBuilder ); + } + } + + public ReferenceNodeData( TreeViewItem item, ReferenceNode node, ReferenceNodeData parent, int linkIndex ) + { + this.item = item; + this.node = node; + this.parent = parent; + this.linkIndex = linkIndex; + } + + private string GetTooltipText( StringBuilder sb ) + { + sb.Length = 0; + sb.Append( "- " ).Append( node.Label ); + + if( parent != null ) + { + sb.Append( "\n" ); + + if( parent.node[linkIndex].descriptions.Count > 0 ) + { + List linkDescriptions = parent.node[linkIndex].descriptions; + for( int i = 0; i < linkDescriptions.Count; i++ ) + sb.Append( " " ).Append( linkDescriptions[i] ).Append( "\n" ); + } + + if( parent.m_tooltipText != null ) + sb.Append( parent.m_tooltipText ); + else // Cache parents' tooltips along the way because they'll likely be reused frequently. We need to use new StringBuilder instances for them + sb.Append( parent.GetTooltipText( new StringBuilder( 256 ) ) ); + } + + m_tooltipText = sb.ToString(); + return m_tooltipText; + } + + public void ResetTooltip() + { + m_tooltipText = null; + } + } + + private const float SEARCHED_OBJECTS_BORDER_THICKNESS = 1f; +#if UNITY_2019_3_OR_NEWER + private const float TREE_VIEW_LINES_THICKNESS = 1.5f; // There are inexplicable spaces between the vertical and horizontal lines if we don't change thickness by 0.5f on 2019.3+ +#else + private const float TREE_VIEW_LINES_THICKNESS = 2f; +#endif + private const float HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS = TREE_VIEW_LINES_THICKNESS * 2f; + + private readonly new SearchResultTreeViewState state; + + private readonly List references; + private readonly List idToNodeDataLookup = new List( 128 ); + + private readonly HashSet selectedReferenceNodes = new HashSet(); + private readonly HashSet selectedReferenceNodesHierarchyIds = new HashSet(); + private readonly HashSet selectedReferenceNodesHierarchyIndirectIds = new HashSet(); + + private readonly HashSet usedObjectsSet; + + private readonly TreeType treeType; + private readonly bool hideDuplicateRows; + private readonly bool hideReduntantPrefabVariantLinks; + + private bool isSearching; + +#if !UNITY_2018_2_OR_NEWER + public int visibleRowTop = 0, visibleRowBottom = int.MaxValue; +#endif + + private readonly CompareInfo textComparer = new CultureInfo( "en-US" ).CompareInfo; + private readonly CompareOptions textCompareOptions = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace; + + private readonly GUIContent sharedGUIContent = new GUIContent(); + private GUIStyle foldoutLabelStyle; + private Texture2D whiteGradientTexture; + private string highlightedSearchTextColor; + + private ReferenceNodeData prevHoveredData, hoveredData; + private Rect hoveredDataRect; + + private bool isTreeViewEmpty; + private bool isLMBDown; + + private double customTooltipShowTime; + + public new float rowHeight + { + get { return base.rowHeight; } + set + { + base.rowHeight = value; +#if !UNITY_2019_3_OR_NEWER + customFoldoutYOffset = ( value - EditorGUIUtility.singleLineHeight ) * 0.5f; +#endif + } + } + + // Avoid using these properties of TreeView by mistake + [System.Obsolete] private new string searchString { get; } + [System.Obsolete] private new bool hasSearch { get; } + + public SearchResultTreeView( SearchResultTreeViewState state, List references, TreeType treeType, HashSet usedObjectsSet, bool hideDuplicateRows, bool hideReduntantPrefabVariantLinks, bool usesExternalScrollView ) : base( state ) + { + this.state = state; + this.references = references; + this.treeType = treeType; + this.hideDuplicateRows = hideDuplicateRows; + this.hideReduntantPrefabVariantLinks = hideReduntantPrefabVariantLinks; + + highlightedSearchTextColor = ""; + + rowHeight = EditorGUIUtility.singleLineHeight + AssetUsageDetectorSettings.ExtraRowHeight; + + if( treeType == TreeType.UnusedObjects ) + { + showBorder = true; + this.usedObjectsSet = usedObjectsSet; + } + + if( treeType != TreeType.IsolatedView ) + { + // Draw only the visible rows. This requires setting useScrollView to false because we are using an external scroll view: https://docs.unity3d.com/ScriptReference/IMGUI.Controls.TreeView-useScrollView.html +#if UNITY_2018_2_OR_NEWER + useScrollView = false; +#else + // In my tests, SetUseScrollView seems to have no effect unfortunately but let's keep this line in case it fixes some other issues with the external scroll view + object treeViewController = typeof( TreeView ).GetField( "m_TreeView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( this ); + treeViewController.GetType().GetMethod( "SetUseScrollView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ).Invoke( treeViewController, new object[1] { false } ); +#endif + } + + isSearching = !string.IsNullOrEmpty( state.searchTerm ); + + Reload(); + + if( HasSelection() ) + RefreshSelectedNodes( GetSelection() ); + } + + public void RefreshSearch( string prevSearchTerm ) + { + bool wasSearchTermEmpty = string.IsNullOrEmpty( prevSearchTerm ); + bool isSearchTermEmpty = string.IsNullOrEmpty( state.searchTerm ); + + isSearching = !isSearchTermEmpty; + + if( !wasSearchTermEmpty || !isSearchTermEmpty ) + { + Reload(); + + if( !isSearchTermEmpty ) + { + if( wasSearchTermEmpty ) + { + state.preSearchExpandedIds = new List( GetExpanded() ?? new int[0] ); + state.selectionChangedDuringSearch = false; + } + + ExpandMatchingSearchResults(); + } + else if( !wasSearchTermEmpty && state.preSearchExpandedIds != null && state.preSearchExpandedIds.Count > 0 ) + { + List expandedIds = state.preSearchExpandedIds; + HashSet expandedIdsSet = new HashSet( expandedIds ); + if( state.selectionChangedDuringSearch ) + { + IList selection = GetSelection(); + for( int i = 0; i < selection.Count; i++ ) + { + for( TreeViewItem item = GetDataFromId( selection[i] ).item; item != null; item = item.parent ) + { + if( expandedIdsSet.Add( item.id ) ) + expandedIds.Add( item.id ); + else + break; + } + } + } + + SetExpanded( state.preSearchExpandedIds ); + expandedIds.Clear(); + } + + if( HasSelection() ) + RefreshSelectedNodes( GetSelection() ); + } + } + + protected override TreeViewItem BuildRoot() + { + TreeViewItem root = new TreeViewItem { id = state.initialNodeId, depth = -1, displayName = "Root" }; + int id = state.initialNodeId + 1; + + idToNodeDataLookup.Clear(); + + List stack = new List( 8 ); + HashSet processedNodes = null; + if( hideDuplicateRows ) + { + processedNodes = new HashSet(); + for( int i = references.Count - 1; i >= 0; i-- ) + { + // Don't mark root nodes as duplicates unless we're in ReferencesOnly search mode (in which case, it's just technically unfeasible to know which root nodes will be displayed in advance) + if( !isSearching || ( state.searchMode != SearchMode.ReferencesOnly && textComparer.IndexOf( references[i].Label, state.searchTerm, textCompareOptions ) >= 0 ) ) + processedNodes.Add( references[i] ); + } + } + + for( int i = 0; i < references.Count; i++ ) + GenerateRowsRecursive( root, references[i], null, i, 0, null, stack, processedNodes, ref id ); + + isTreeViewEmpty = !root.hasChildren; + if( isTreeViewEmpty ) // May happen if all items are hidden inside HideItems function or there are no matching search results. If we don't create a dummy child, Unity throws an exception + root.AddChild( new TreeViewItem( state.initialNodeId + 1 ) ); // If we don't give it a valid id, some functions throw exceptions when there are no matching search results + else + GetDataFromId( root.children[root.children.Count - 1].id ).isLastLink = true; + + state.finalNodeId = id + 1; + + return root; + } + + private bool GenerateRowsRecursive( TreeViewItem parent, ReferenceNode referenceNode, ReferenceNodeData parentData, int siblingIndex, int depth, bool? itemForcedVisibility, List stack, HashSet processedNodes, ref int id ) + { +#if UNITY_2018_3_OR_NEWER + // If the same reference is found in both a prefab variant and its base prefab, omit the prefab variant to reduce the number of + // redundant links (changing the value in base prefab will automatically change the value in its variants, after all) + if( hideReduntantPrefabVariantLinks && depth > 0 ) + { + Object unityObject = referenceNode.UnityObject; + if( unityObject && ( unityObject is Component || unityObject is GameObject ) && unityObject.IsAsset() ) + { + List linkDescriptions = parentData.node[siblingIndex].descriptions; + if( linkDescriptions.Count > 0 ) + { + Object prefabObject = PrefabUtility.GetCorrespondingObjectFromSource( unityObject ); + if( prefabObject && parentData.node.HasLinkToObjectWithDescriptions( prefabObject.GetHashCode(), linkDescriptions ) ) + return false; + } + } + } +#endif + + TreeViewItem item = new TreeViewItem( id++, depth, "" ); + ReferenceNodeData data = new ReferenceNodeData( item, referenceNode, parentData, siblingIndex ); + + bool shouldShowItem; + if( itemForcedVisibility.HasValue ) + shouldShowItem = itemForcedVisibility.Value; + else + { + if( !isSearching ) + shouldShowItem = true; + else if( state.searchMode == SearchMode.All || ( ( depth == 0 ) == ( state.searchMode == SearchMode.SearchedObjectsOnly ) ) ) + { + shouldShowItem = textComparer.IndexOf( referenceNode.Label, state.searchTerm, textCompareOptions ) >= 0; + if( !shouldShowItem && depth > 0 ) + { + List descriptions = parentData.node[siblingIndex].descriptions; + for( int i = descriptions.Count - 1; i >= 0; i-- ) + { + if( textComparer.IndexOf( descriptions[i], state.searchTerm, textCompareOptions ) >= 0 ) + { + shouldShowItem = true; + break; + } + } + } + + data.shouldExpandAfterSearch = shouldShowItem; + + if( state.searchMode == SearchMode.SearchedObjectsOnly || ( state.searchMode == SearchMode.All && shouldShowItem ) ) + itemForcedVisibility = shouldShowItem; + } + else + shouldShowItem = false; + } + + idToNodeDataLookup.Add( data ); + + // Disallow recursion (stack) because it would crash Unity + if( referenceNode.NumberOfOutgoingLinks > 0 && !stack.ContainsFast( referenceNode ) ) + { + // Add children only if hideDuplicateRows is false (processedNodes == null) or this node hasn't been seen before + if( processedNodes != null && !processedNodes.Add( referenceNode ) && depth > 0 ) // "depth > 0": Root nodes are either added to processedNodes prior to generating rows (so that they're never marked as duplicate), or they just shouldn't be trimmed + data.isDuplicate = true; + else + { + stack.Add( referenceNode ); + + // Generate child items even if they will be forced invisible so that each visible row's id is deterministic and doesn't change when some rows become invisible + for( int i = 0; i < referenceNode.NumberOfOutgoingLinks; i++ ) + shouldShowItem |= GenerateRowsRecursive( item, referenceNode[i].targetNode, data, i, depth + 1, itemForcedVisibility, stack, processedNodes, ref id ); + + stack.RemoveAt( stack.Count - 1 ); + } + } + + if( shouldShowItem ) + { + if( item.hasChildren ) + GetDataFromId( item.children[item.children.Count - 1].id ).isLastLink = true; + + parent.AddChild( item ); + return true; + } + + return false; + } + + private ReferenceNodeData GetDataFromId( int id ) + { + return idToNodeDataLookup[id - state.initialNodeId - 1]; + } + + public override void OnGUI( Rect rect ) + { + // Disallow clicking on "No matching results" text when in search mode + bool guiEnabled = GUI.enabled; + if( isTreeViewEmpty ) + GUI.enabled = false; + + // Mouse and special keyboard events are already in Used state in CommandEventHandling, so we need to process them here + Event ev = Event.current; + if( ev.type == EventType.MouseDown ) + { + if( ev.button == 0 ) + isLMBDown = true; + } + else if( ev.type == EventType.MouseUp ) + { + if( ev.button == 0 ) + isLMBDown = false; + } + else if( ev.type == EventType.MouseMove ) + hoveredData = null; + else if( ev.type == EventType.KeyDown ) + { + if( ( ev.keyCode == KeyCode.Return || ev.keyCode == KeyCode.KeypadEnter ) && HasSelection() && HasFocus() ) + { + DoubleClickedItem( state.lastClickedID ); + ev.Use(); + } + } + + base.OnGUI( rect ); + + if( prevHoveredData != hoveredData ) + { + if( AssetUsageDetectorSettings.CustomTooltipDelay > 0f ) + EditorApplication.update -= ShowTooltipDelayed; + + prevHoveredData = hoveredData; + if( hoveredData != null ) + { + if( AssetUsageDetectorSettings.CustomTooltipDelay <= 0f ) + SearchResultTooltip.Show( hoveredDataRect, hoveredData.tooltipText ); + else + { + customTooltipShowTime = EditorApplication.timeSinceStartup + AssetUsageDetectorSettings.CustomTooltipDelay; + EditorApplication.update += ShowTooltipDelayed; + } + } + else + SearchResultTooltip.Hide(); + + Repaint(); + } + + GUI.enabled = guiEnabled; + } + + protected override void RowGUI( RowGUIArgs args ) + { +#if !UNITY_2018_2_OR_NEWER + // Do manual row culling on early Unity versions + if( args.row < visibleRowTop || args.row > visibleRowBottom ) + return; +#endif + + if( isTreeViewEmpty ) + { + EditorGUI.LabelField( args.rowRect, "No matching results..." ); + return; + } + + Event ev = Event.current; + ReferenceNodeData data = GetDataFromId( args.item.id ); + Rect rect = args.rowRect; + + if( string.IsNullOrEmpty( args.item.displayName ) ) + { + Object unityObject = data.node.UnityObject; + if( unityObject ) + args.item.icon = AssetPreview.GetMiniThumbnail( unityObject ); + + StringBuilder sb = Utilities.stringBuilder; + sb.Length = 0; + + if( data.isDuplicate ) + sb.Append( "[D] " ); + + if( data.parent == null ) + { + if( treeType != TreeType.UnusedObjects ) + sb.Append( "" ); + else if( data.node.usedState == ReferenceNode.UsedState.MixedCollapsed ) + sb.Append( "[!] " ); + else if( data.node.usedState == ReferenceNode.UsedState.MixedExpanded ) + sb.Append( "[!] " ); + + if( !isSearching || state.searchMode == SearchMode.ReferencesOnly ) + sb.Append( data.node.Label ); + else + HighlightSearchTermInString( sb, data.node.Label ); + + if( treeType != TreeType.UnusedObjects ) + sb.Append( "" ); + } + else + { + List linkDescriptions = data.parent.node[data.linkIndex].descriptions; + if( linkDescriptions.Count > 0 ) + { + if( !isSearching || state.searchMode == SearchMode.SearchedObjectsOnly ) + sb.Append( data.node.Label ).Append( " " ).Append( linkDescriptions[0] ); + else + { + HighlightSearchTermInString( sb, data.node.Label ); + sb.Append( " " ); + HighlightSearchTermInString( sb, linkDescriptions[0] ); + } + + if( linkDescriptions.Count > 1 ) + { + bool shouldHighlightRemainingLinkDescriptions = false; + if( isSearching && state.searchMode != SearchMode.SearchedObjectsOnly ) + { + for( int i = linkDescriptions.Count - 1; i > 0; i-- ) + { + if( textComparer.IndexOf( linkDescriptions[i], state.searchTerm, textCompareOptions ) >= 0 ) + { + shouldHighlightRemainingLinkDescriptions = true; + sb.Append( highlightedSearchTextColor ); + + break; + } + } + } + + sb.Append( " and " ).Append( linkDescriptions.Count - 1 ).Append( " more" ); + + if( shouldHighlightRemainingLinkDescriptions ) + sb.Append( "" ); + } + + sb.Append( "" ); + } + else if( isSearching && state.searchMode != SearchMode.SearchedObjectsOnly ) + HighlightSearchTermInString( sb, data.node.Label ); + else + sb.Append( data.node.Label ); + } + + args.item.displayName = sb.ToString(); + } + + sharedGUIContent.text = args.item.displayName; + sharedGUIContent.tooltip = AssetUsageDetectorSettings.ShowUnityTooltip ? data.tooltipText : null; + sharedGUIContent.image = args.item.icon; + + if( ev.type == EventType.Repaint ) + { + if( treeType != TreeType.UnusedObjects ) + { + if( args.item.depth == 0 ) + { + Color guiColor = GUI.color; + + // Draw background + if( !args.selected ) + { + GUI.color = guiColor * ( ( AssetUsageDetectorSettings.ApplySelectedRowParentsTintToRootRows && selectedReferenceNodesHierarchyIds.Contains( args.item.id ) ) ? AssetUsageDetectorSettings.SelectedRowParentsTint : AssetUsageDetectorSettings.RootRowsBackgroundColor ); + GUI.DrawTexture( rect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + } + + // Draw border: https://github.com/Unity-Technologies/UnityCsReference/blob/33cbfe062d795667c39e16777230e790fcd4b28b/Editor/Mono/GUI/InternalEditorGUI.cs#L262-L275 + if( AssetUsageDetectorSettings.RootRowsBorderColor.a > 0f ) + { + GUI.color = guiColor * AssetUsageDetectorSettings.RootRowsBorderColor; + GUI.DrawTexture( new Rect( rect.x, rect.y, rect.width, SEARCHED_OBJECTS_BORDER_THICKNESS ), EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + + // Draw bottom border only if there isn't another searched object immediately below this one (otherwise, this bottom border and the following top border are drawn at the same space, resulting in darker shade for that edge) + if( data.isLastLink || ( args.item.hasChildren && IsExpanded( args.item.id ) ) ) + { + GUI.DrawTexture( new Rect( rect.x, rect.yMax - SEARCHED_OBJECTS_BORDER_THICKNESS, rect.width, SEARCHED_OBJECTS_BORDER_THICKNESS ), EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + GUI.DrawTexture( new Rect( rect.x, rect.y + 1, SEARCHED_OBJECTS_BORDER_THICKNESS, rect.height - 2f * SEARCHED_OBJECTS_BORDER_THICKNESS ), EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + GUI.DrawTexture( new Rect( rect.xMax - SEARCHED_OBJECTS_BORDER_THICKNESS, rect.y + 1, SEARCHED_OBJECTS_BORDER_THICKNESS, rect.height - 2f * SEARCHED_OBJECTS_BORDER_THICKNESS ), EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + } + else + { + GUI.DrawTexture( new Rect( rect.x, rect.y + 1, SEARCHED_OBJECTS_BORDER_THICKNESS, rect.height ), EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + GUI.DrawTexture( new Rect( rect.xMax - SEARCHED_OBJECTS_BORDER_THICKNESS, rect.y + 1, SEARCHED_OBJECTS_BORDER_THICKNESS, rect.height ), EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + } + } + + GUI.color = guiColor; + } + else + { + if( !args.selected ) + { + if( selectedReferenceNodesHierarchyIds.Contains( args.item.id ) ) + EditorGUI.DrawRect( rect, AssetUsageDetectorSettings.SelectedRowParentsTint ); + + if( data.node.IsMainReference ) + EditorGUI.DrawRect( new Rect( rect.x, rect.y, GetContentIndent( args.item ) - 1f, rect.height ), AssetUsageDetectorSettings.MainReferencesBackgroundColor ); + } + } + } + else + { + if( !args.selected && data.node.usedState == ReferenceNode.UsedState.Used ) + EditorGUI.DrawRect( new Rect( rect.x, rect.y, GetContentIndent( args.item ) - 1f, rect.height ), AssetUsageDetectorSettings.MainReferencesBackgroundColor ); + } + + if( !isLMBDown && treeType != TreeType.UnusedObjects && !args.selected && selectedReferenceNodes.Contains( data.node ) ) + { + if( !whiteGradientTexture ) + { + whiteGradientTexture = new Texture2D( 2, 1, TextureFormat.RGBA32, false ) + { + hideFlags = HideFlags.HideAndDontSave, + alphaIsTransparency = true, + filterMode = FilterMode.Bilinear, + wrapMode = TextureWrapMode.Clamp + }; + + whiteGradientTexture.SetPixels32( new Color32[2] { Color.white, new Color32( 255, 255, 255, 0 ) } ); + whiteGradientTexture.Apply( false, true ); + } + + Color guiColor = GUI.color; + GUI.color = guiColor * AssetUsageDetectorSettings.SelectedRowOccurrencesColor; + GUI.DrawTexture( new Rect( GetContentIndent( args.item ), rect.y, 125f, rect.height ), whiteGradientTexture, ScaleMode.StretchToFill, true, 0f ); + GUI.color = guiColor; + } + + if( hoveredData == data ) + EditorGUI.DrawRect( rect, new Color( 0.5f, 0.5f, 0.5f, 0.25f ) ); + + if( AssetUsageDetectorSettings.ShowTreeLines && args.item.depth > 0 ) + { + // I was using EditorGUI.DrawRect here but looking at its source code, it's more performant to call GUI.DrawTexture directly: https://github.com/Unity-Technologies/UnityCsReference/blob/e740821767d2290238ea7954457333f06e952bad/Editor/Mono/GUI/InternalEditorGUI.cs#L246-L255 + Color guiColor = GUI.color; + bool shouldHighlightTreeLine; + + Rect verticalLineRect = new Rect( rect.x + GetContentIndent( args.item.parent ) - ( foldoutWidth + TREE_VIEW_LINES_THICKNESS ) * 0.5f - 2f, rect.y, TREE_VIEW_LINES_THICKNESS, rect.height ); + Rect horizontalLineRect = new Rect( verticalLineRect.x, verticalLineRect.y + ( verticalLineRect.height - TREE_VIEW_LINES_THICKNESS ) * 0.5f, foldoutWidth + TREE_VIEW_LINES_THICKNESS - 4f, TREE_VIEW_LINES_THICKNESS ); + + for( ReferenceNodeData parentData = data.parent; parentData.parent != null; parentData = parentData.parent ) + { + if( !parentData.isLastLink ) + { + shouldHighlightTreeLine = selectedReferenceNodesHierarchyIndirectIds.Contains( parentData.item.id ); + Rect _verticalLineRect = new Rect( verticalLineRect.x - depthIndentWidth * ( args.item.depth - parentData.item.depth ), verticalLineRect.y, verticalLineRect.width, verticalLineRect.height ); + if( shouldHighlightTreeLine ) + { + _verticalLineRect.x -= ( HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS - TREE_VIEW_LINES_THICKNESS ) * 0.5f; + _verticalLineRect.width = HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS; + } + + GUI.color = guiColor * ( shouldHighlightTreeLine ? AssetUsageDetectorSettings.HighlightedTreeLinesColor : AssetUsageDetectorSettings.TreeLinesColor ); + GUI.DrawTexture( _verticalLineRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + } + } + + bool isInSelectedReferenceNodesHierarchy = selectedReferenceNodesHierarchyIds.Contains( args.item.id ); + if( isInSelectedReferenceNodesHierarchy ) + { + horizontalLineRect.y -= ( HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS - TREE_VIEW_LINES_THICKNESS ) * 0.5f; + horizontalLineRect.height = HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS; + } + + GUI.color = guiColor * ( isInSelectedReferenceNodesHierarchy ? AssetUsageDetectorSettings.HighlightedTreeLinesColor : AssetUsageDetectorSettings.TreeLinesColor ); + GUI.DrawTexture( horizontalLineRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + + if( data.isLastLink ) + verticalLineRect.height = ( verticalLineRect.height + TREE_VIEW_LINES_THICKNESS ) * 0.5f; + + GUI.color = guiColor * AssetUsageDetectorSettings.TreeLinesColor; + GUI.DrawTexture( verticalLineRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + + bool isInSelectedReferenceNodesIndirectHierarchy = selectedReferenceNodesHierarchyIndirectIds.Contains( args.item.id ); + if( isInSelectedReferenceNodesHierarchy || isInSelectedReferenceNodesIndirectHierarchy ) + { + GUI.color = guiColor * AssetUsageDetectorSettings.HighlightedTreeLinesColor; + + if( isInSelectedReferenceNodesHierarchy && !isInSelectedReferenceNodesIndirectHierarchy ) + { + if( !data.isLastLink ) + verticalLineRect.height = ( verticalLineRect.height + HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS ) * 0.5f; + else + verticalLineRect.height += ( HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS - TREE_VIEW_LINES_THICKNESS ) * 0.5f; + } + + verticalLineRect.x -= ( HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS - TREE_VIEW_LINES_THICKNESS ) * 0.5f; + verticalLineRect.width = HIGHLIGHTED_TREE_VIEW_LINES_THICKNESS; + + GUI.DrawTexture( verticalLineRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill, true, 0f ); + } + + GUI.color = guiColor; + } + + rect.xMin += GetContentIndent( args.item ); + rect.y += AssetUsageDetectorSettings.ExtraRowHeight * 0.5f; +#if !UNITY_2019_3_OR_NEWER + rect.y -= 2f; +#endif + rect.height += 4f; // Incrementing height fixes cropped icon issue on Unity 2019.2 or earlier + + if( foldoutLabelStyle == null ) + foldoutLabelStyle = new GUIStyle( DefaultStyles.foldoutLabel ) { richText = true }; + + foldoutLabelStyle.Draw( rect, sharedGUIContent, false, false, args.selected && args.focused, args.selected ); + + // The only way to support Unity's tooltips seems to be by drawing an invisible GUI.Label over our own label + if( sharedGUIContent.tooltip != null ) + { + sharedGUIContent.text = ""; + sharedGUIContent.image = null; + GUI.Label( rect, sharedGUIContent, foldoutLabelStyle ); + } + } + else if( ev.type == EventType.MouseDown ) + { + if( ev.button == 2 && rect.Contains( ev.mousePosition ) ) + { + HideItems( new int[1] { args.item.id } ); + GUIUtility.ExitGUI(); + } + } + else if( ev.type == EventType.MouseMove ) + { + if( hoveredData != data && AssetUsageDetectorSettings.ShowCustomTooltip && rect.Contains( ev.mousePosition ) ) + { + hoveredData = data; + hoveredDataRect = new Rect( GUIUtility.GUIToScreenPoint( rect.position ), new Vector2( EditorGUIUtility.currentViewWidth, 0f ) ); + } + } + } + + protected override void SelectionChanged( IList selectedIds ) + { + if( isTreeViewEmpty ) + return; + + RefreshSelectedNodes( selectedIds ); + + if( selectedIds.Count == 0 ) + return; + + if( isSearching ) + state.selectionChangedDuringSearch = true; + + Object selection, pingTarget = null; + List selectedUnityObjects = new List( selectedIds.Count ); + for( int i = 0; i < selectedIds.Count; i++ ) + { + Object obj = GetDataFromId( selectedIds[i] ).node.UnityObject; + if( obj ) + { + obj.GetObjectsToSelectAndPing( out selection, out pingTarget ); + if( selection && !selectedUnityObjects.Contains( selection ) ) + selectedUnityObjects.Add( selection ); + } + } + + if( selectedUnityObjects.Count > 0 ) + { + if( AssetUsageDetectorSettings.PingClickedObjects && pingTarget ) + EditorGUIUtility.PingObject( pingTarget ); + if( AssetUsageDetectorSettings.SelectClickedObjects || ( AssetUsageDetectorSettings.SelectDoubleClickedObjects && selectedUnityObjects.Count > 1 ) ) + Selection.objects = selectedUnityObjects.ToArray(); + } + } + + protected override void DoubleClickedItem( int id ) + { + if( isTreeViewEmpty ) + return; + + isLMBDown = false; + + Object clickedObject = GetDataFromId( id ).node.UnityObject; +#if UNITY_2018_3_OR_NEWER + if( clickedObject && clickedObject.IsAsset() ) + { + GameObject clickedPrefabRoot = null; + if( clickedObject is Component ) + clickedPrefabRoot = ( (Component) clickedObject ).transform.root.gameObject; + else if( clickedObject is GameObject ) + clickedPrefabRoot = ( (GameObject) clickedObject ).transform.root.gameObject; + + if( clickedPrefabRoot ) + { + PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( clickedPrefabRoot ); + if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant ) + { + // Try to open the prefab stage of this prefab + string assetPath = AssetDatabase.GetAssetPath( clickedPrefabRoot ); + PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); +#if UNITY_2020_1_OR_NEWER + if( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.assetPath ) +#else + if( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.prefabAssetPath ) +#endif + AssetDatabase.OpenAsset( clickedPrefabRoot ); + } + } + } +#endif + + // Ping the clicked GameObject in the open prefab stage + Object selection, pingTarget; + clickedObject.GetObjectsToSelectAndPing( out selection, out pingTarget ); + + if( AssetUsageDetectorSettings.PingClickedObjects && pingTarget ) + EditorGUIUtility.PingObject( pingTarget ); + if( AssetUsageDetectorSettings.SelectDoubleClickedObjects ) + Selection.activeObject = selection; + } + + protected override void ContextClickedItem( int id ) + { + ContextClicked(); + } + + protected override void ContextClicked() + { + if( !isTreeViewEmpty && HasSelection() && HasFocus() ) + { + IList selection = SortItemIDsInRowOrder( GetSelection() ); + + bool hasAnyDuplicateRows = false, hasAnyRowWithOutgoingLinks = false, hasAnyUnusedMixedCollapsedNode = false; + for( int i = 0; i < selection.Count; i++ ) + { + ReferenceNodeData data = GetDataFromId( selection[i] ); + if( !hasAnyDuplicateRows && data.isDuplicate ) + hasAnyDuplicateRows = true; + if( !hasAnyRowWithOutgoingLinks && data.node.NumberOfOutgoingLinks > 0 ) + hasAnyRowWithOutgoingLinks = true; + if( !hasAnyUnusedMixedCollapsedNode && data.node.usedState == ReferenceNode.UsedState.MixedCollapsed ) + hasAnyUnusedMixedCollapsedNode = true; + } + + GenericMenu contextMenu = new GenericMenu(); + + if( treeType != TreeType.IsolatedView ) + contextMenu.AddItem( new GUIContent( "Hide" ), false, () => HideItems( selection ) ); + + if( treeType == TreeType.UnusedObjects ) + { + if( hasAnyUnusedMixedCollapsedNode ) + { + if( contextMenu.GetItemCount() > 0 ) + contextMenu.AddSeparator( "" ); + + contextMenu.AddItem( new GUIContent( "Show Used Children" ), false, ShowChildrenOfSelectedUnusedObjects ); + } + } + else + { + if( contextMenu.GetItemCount() > 0 ) + contextMenu.AddSeparator( "" ); + + if( hasAnyDuplicateRows ) + contextMenu.AddItem( new GUIContent( "Select First Occurrence" ), false, SelectFirstOccurrencesOfDuplicateSelection ); + + contextMenu.AddItem( new GUIContent( "Expand All Occurrences" ), false, ExpandAllSelectionOccurrences ); + } + + if( hasAnyRowWithOutgoingLinks ) + { + if( contextMenu.GetItemCount() > 0 ) + contextMenu.AddSeparator( "" ); + + contextMenu.AddItem( new GUIContent( "Show Children In New Window" ), false, ShowChildrenOfSelectionInNewWindow ); + } + + contextMenu.ShowAsContext(); + + if( Event.current != null && Event.current.type == EventType.ContextClick ) + Event.current.Use(); // It's safer to eat the event and if we don't, the context menu is sometimes displayed with a delay + } + } + + protected override void CommandEventHandling() + { + if( !isTreeViewEmpty && HasFocus() ) // There may be multiple SearchResultTreeViews. Execute the event only for the currently focused one + { + Event ev = Event.current; + if( ev.type == EventType.ValidateCommand || ev.type == EventType.ExecuteCommand ) + { + if( ev.commandName == "Delete" || ev.commandName == "SoftDelete" ) + { + if( ev.type == EventType.ExecuteCommand ) + HideItems( GetSelection() ); + + ev.Use(); + return; + } + } + } + + base.CommandEventHandling(); + } + + protected override bool CanStartDrag( CanStartDragArgs args ) + { + return true; + } + + protected override void SetupDragAndDrop( SetupDragAndDropArgs args ) + { + IList draggedItemIds = args.draggedItemIDs; + if( draggedItemIds.Count == 0 ) + return; + + List draggedUnityObjects = new List( draggedItemIds.Count ); + for( int i = 0; i < draggedItemIds.Count; i++ ) + { + Object obj = GetDataFromId( draggedItemIds[i] ).node.UnityObject; + if( obj ) + draggedUnityObjects.Add( obj ); + } + + if( draggedUnityObjects.Count > 0 ) + { + DragAndDrop.objectReferences = draggedUnityObjects.ToArray(); + DragAndDrop.StartDrag( draggedUnityObjects.Count > 1 ? "" : draggedUnityObjects[0].name ); + } + } + + public void ExpandDirectReferences() + { + List expandedIds = new List( rootItem.children.Count ); + for( int i = 0; i < rootItem.children.Count; i++ ) + expandedIds.Add( rootItem.children[i].id ); + + SetExpanded( expandedIds ); + } + + public void ExpandMainReferences() + { + List expandedIds = new List( references.Count * 12 ); + for( int i = 0; i < rootItem.children.Count; i++ ) + GetMainReferenceIdsRecursive( rootItem.children[i], expandedIds ); + + SetExpanded( expandedIds ); + } + + public void ExpandMatchingSearchResults() + { + if( state.searchMode != SearchMode.ReferencesOnly ) + return; + + List expandedIds = new List( references.Count * 12 ); + for( int i = 0; i < rootItem.children.Count; i++ ) + GetMatchingSearchResultIdsRecursive( rootItem.children[i], expandedIds ); + + SetExpanded( expandedIds ); + } + + private void ExpandAllSelectionOccurrences() + { + IList selection = GetSelection(); + if( selection.Count == 0 ) + return; + + HashSet selectedNodes = new HashSet(); + for( int i = selection.Count - 1; i >= 0; i-- ) + selectedNodes.Add( GetDataFromId( selection[i] ).node ); + + List expandedIds = new List( GetExpanded() ); + for( int i = 0; i < rootItem.children.Count; i++ ) + GetReferenceNodeOccurrenceIdsRecursive( rootItem.children[i], selectedNodes, expandedIds ); + + SetExpanded( expandedIds ); + } + + private bool GetMainReferenceIdsRecursive( TreeViewItem item, List ids ) + { + if( item.depth > 0 && GetDataFromId( item.id ).node.IsMainReference ) + return true; + + bool shouldExpand = false; + if( item.hasChildren ) + { + for( int i = 0; i < item.children.Count; i++ ) + shouldExpand |= GetMainReferenceIdsRecursive( item.children[i], ids ); + } + + if( shouldExpand ) + ids.Add( item.id ); + + return shouldExpand; + } + + private bool GetMatchingSearchResultIdsRecursive( TreeViewItem item, List ids ) + { + bool shouldExpand = false; + if( item.hasChildren ) + { + for( int i = 0; i < item.children.Count; i++ ) + shouldExpand |= GetMatchingSearchResultIdsRecursive( item.children[i], ids ); + } + + if( shouldExpand ) + ids.Add( item.id ); + else + shouldExpand = GetDataFromId( item.id ).shouldExpandAfterSearch; + + return shouldExpand; + } + + private bool GetReferenceNodeOccurrenceIdsRecursive( TreeViewItem item, HashSet referenceNodes, List ids ) + { + bool shouldExpand = false; + if( item.hasChildren ) + { + for( int i = 0; i < item.children.Count; i++ ) + shouldExpand |= GetReferenceNodeOccurrenceIdsRecursive( item.children[i], referenceNodes, ids ); + } + + if( shouldExpand ) + { + if( !ids.Contains( item.id ) ) + ids.Add( item.id ); + + return true; + } + else + return referenceNodes.Contains( GetDataFromId( item.id ).node ); + } + + private void HideItems( IList ids ) + { + if( ids.Count > 0 ) + { + List hiddenNodes = new List( ids.Count ); + List hiddenLinks = new List( ids.Count ); + List newExpandedItemIDs = new List( 32 ); + List newSelectedItemIDs = new List( 16 ); + + for( int i = 0; i < ids.Count; i++ ) + { + ReferenceNodeData data = GetDataFromId( ids[i] ); + if( data.item.depth > 0 ) + hiddenLinks.Add( data.parent.node[data.linkIndex] ); + else + hiddenNodes.Add( data.node ); + } + + int id = state.initialNodeId + 1; + for( int i = 0; i < rootItem.children.Count; i++ ) + CalculateNewItemIdsAfterHideRecursive( rootItem.children[i], hiddenNodes, hiddenLinks, newExpandedItemIDs, newSelectedItemIDs, ref id ); + + for( int i = 0; i < ids.Count; i++ ) + { + ReferenceNodeData data = GetDataFromId( ids[i] ); + if( data.item.depth > 0 ) + { + // Can't remove by index here because if multiple sibling nodes are removed at once, the latter sibling nodes' linkIndex + // will be different than their actual sibling indices until this TreeView is refreshed + data.parent.node.RemoveLink( data.node ); + } + else + references.Remove( data.node ); + } + + SetSelection( newSelectedItemIDs ); + SetExpanded( newExpandedItemIDs ); + Reload(); + } + } + + private void CalculateNewItemIdsAfterHideRecursive( TreeViewItem item, List hiddenNodes, List hiddenLinks, List newExpandedItemIDs, List newSelectedItemIDs, ref int id ) + { + ReferenceNodeData data = GetDataFromId( item.id ); + if( hiddenNodes.Contains( data.node ) || ( data.parent != null && hiddenLinks.Contains( data.parent.node[data.linkIndex] ) ) ) + return; + + if( IsExpanded( item.id ) ) + newExpandedItemIDs.Add( id ); + if( IsSelected( item.id ) ) + newSelectedItemIDs.Add( id ); + + id++; + + if( item.hasChildren ) + { + for( int i = 0; i < item.children.Count; i++ ) + CalculateNewItemIdsAfterHideRecursive( item.children[i], hiddenNodes, hiddenLinks, newExpandedItemIDs, newSelectedItemIDs, ref id ); + } + } + + private void SelectFirstOccurrencesOfDuplicateSelection() + { + IList selection = GetSelection(); + if( selection.Count == 0 ) + return; + + HashSet selectedNodes = new HashSet(); + for( int i = selection.Count - 1; i >= 0; i-- ) + { + ReferenceNodeData data = GetDataFromId( selection[i] ); + if( data.isDuplicate ) + selectedNodes.Add( data.node ); + } + + List newSelection = new List( selection.Count ); + for( int i = 0; i < rootItem.children.Count; i++ ) + FindFirstOccurrencesOfSelectionRecursive( rootItem.children[i], selectedNodes, newSelection ); + + if( newSelection.Count > 0 ) + { + SetSelection( newSelection, TreeViewSelectionOptions.FireSelectionChanged | TreeViewSelectionOptions.RevealAndFrame ); + + if( treeType != TreeType.IsolatedView ) + EditorWindow.focusedWindow.SendEvent( new Event() { type = EventType.KeyDown, keyCode = KeyCode.F } ); // To actually frame the row when external scroll view is used + } + } + + private void FindFirstOccurrencesOfSelectionRecursive( TreeViewItem item, HashSet selectedNodes, List result ) + { + ReferenceNodeData data = GetDataFromId( item.id ); + if( !data.isDuplicate && selectedNodes.Remove( data.node ) ) + result.Add( item.id ); + + if( item.hasChildren ) + { + for( int i = 0; i < item.children.Count; i++ ) + FindFirstOccurrencesOfSelectionRecursive( item.children[i], selectedNodes, result ); + } + } + + private void ShowChildrenOfSelectedUnusedObjects() + { + IList selection = GetSelection(); + if( selection.Count == 0 ) + return; + + for( int i = selection.Count - 1; i >= 0; i-- ) + { + ReferenceNodeData data = GetDataFromId( selection[i] ); + if( data.node.usedState != ReferenceNode.UsedState.MixedCollapsed ) + continue; + + data.node.usedState = ReferenceNode.UsedState.MixedExpanded; + + Object unityObject = data.node.UnityObject; + if( !unityObject ) + continue; + + string assetPath = AssetDatabase.GetAssetPath( unityObject ); + if( string.IsNullOrEmpty( assetPath ) ) + { + foreach( Object obj in usedObjectsSet ) + { + if( obj && obj is GameObject && obj != unityObject && ( (GameObject) obj ).transform.IsChildOf( ( (GameObject) unityObject ).transform ) ) + { + ReferenceNode childNode = new ReferenceNode() { nodeObject = obj }; + childNode.InitializeRecursively(); + data.node.AddLinkTo( childNode, "USED" ); + } + } + } + else + { + foreach( Object obj in usedObjectsSet ) + { + if( obj && AssetDatabase.GetAssetPath( obj ) == assetPath ) + { + ReferenceNode childNode = new ReferenceNode() { nodeObject = obj }; + childNode.InitializeRecursively(); + data.node.AddLinkTo( childNode, "USED" ); + } + } + } + } + + Reload(); + } + + private void ShowChildrenOfSelectionInNewWindow() + { + IList selection = SortItemIDsInRowOrder( GetSelection() ); + if( selection.Count == 0 ) + return; + + List selectedNodes = new List( selection.Count ); + for( int i = 0; i < selection.Count; i++ ) + { + ReferenceNodeData data = GetDataFromId( selection[i] ); + if( data.node.NumberOfOutgoingLinks > 0 && !selectedNodes.Contains( data.node ) ) + selectedNodes.Add( data.node ); + } + + if( selectedNodes.Count > 0 ) + { + SearchResultTreeView isolatedTreeView = new SearchResultTreeView( new SearchResultTreeViewState(), selectedNodes, TreeType.IsolatedView, null, hideDuplicateRows, hideReduntantPrefabVariantLinks, false ); + isolatedTreeView.ExpandMainReferences(); + + SearchResultTreeViewIsolatedView.Show( new Vector2( EditorWindow.focusedWindow.position.width, isolatedTreeView.totalHeight + 1f ), isolatedTreeView, new GUIContent( selectedNodes[0].Label + ( selectedNodes.Count <= 1 ? "" : ( " (and " + ( selectedNodes.Count - 1 ) + " more)" ) ) ) ); + } + } + + private void RefreshSelectedNodes( IList selectedIds ) + { + selectedReferenceNodes.Clear(); + selectedReferenceNodesHierarchyIds.Clear(); + selectedReferenceNodesHierarchyIndirectIds.Clear(); + + for( int i = 0; i < selectedIds.Count; i++ ) + { + ReferenceNodeData data = GetDataFromId( selectedIds[i] ); + + selectedReferenceNodes.Add( data.node ); + selectedReferenceNodesHierarchyIds.Add( selectedIds[i] ); + + if( data.item.parent == null ) + continue; + + TreeViewItem linkItem = data.item; + for( TreeViewItem parentItem = linkItem.parent; parentItem.depth >= 0; parentItem = parentItem.parent ) + { + selectedReferenceNodesHierarchyIds.Add( parentItem.id ); + + List parentItemChildren = parentItem.children; + for( int j = 0; parentItemChildren[j] != linkItem; j++ ) + selectedReferenceNodesHierarchyIndirectIds.Add( parentItemChildren[j].id ); + + linkItem = parentItem; + } + } + } + + private void ShowTooltipDelayed() + { + if( EditorApplication.timeSinceStartup >= customTooltipShowTime ) + { + EditorApplication.update -= ShowTooltipDelayed; + + if( GetRows().Contains( hoveredData.item ) ) // Make sure that the hovered item is still a part of the tree (e.g. it might have been removed with middle mouse button) + SearchResultTooltip.Show( hoveredDataRect, hoveredData.tooltipText ); + } + } + + public void CancelDelayedTooltip() + { + EditorApplication.update -= ShowTooltipDelayed; + } + + public void GetRowStateWithId( int id, out bool isFirstRow, out bool isLastRow, out bool isExpanded, out bool canExpand ) + { + if( isTreeViewEmpty ) + { + isFirstRow = isLastRow = true; + isExpanded = canExpand = false; + + return; + } + + IList rows = GetRows(); + for( int i = 0; i < rows.Count; i++ ) + { + if( rows[i].id == id ) + { + isFirstRow = ( i <= 0 ); + isLastRow = ( i >= rows.Count - 1 ); + isExpanded = rows[i].hasChildren && IsExpanded( id ); + canExpand = rows[i].hasChildren && !IsExpanded( id ); + + return; + } + } + + isFirstRow = isLastRow = isExpanded = canExpand = false; + } + + public bool GetRowRectWithId( int id, out Rect rect ) + { + IList rows = GetRows(); + for( int i = 0; i < rows.Count; i++ ) + { + if( rows[i].id == id ) + { + rect = GetRowRect( i ); + return true; + } + } + + rect = new Rect(); + return false; + } + + public Rect SelectFirstRowAndReturnRect() + { + SetSelection( new int[1] { GetRows()[0].id }, TreeViewSelectionOptions.FireSelectionChanged ); + return GetRowRect( 0 ); + } + + public Rect SelectLastRowAndReturnRect() + { + IList rows = GetRows(); + SetSelection( new int[1] { rows[rows.Count - 1].id }, TreeViewSelectionOptions.FireSelectionChanged ); + return GetRowRect( rows.Count - 1 ); + } + + private void HighlightSearchTermInString( StringBuilder sb, string str ) + { + int prevSearchOccurrenceIndex = 0, searchOccurrenceIndex = 0; + while( ( searchOccurrenceIndex = textComparer.IndexOf( str, state.searchTerm, searchOccurrenceIndex, textCompareOptions ) ) >= 0 ) + { + sb.Append( str, prevSearchOccurrenceIndex, searchOccurrenceIndex - prevSearchOccurrenceIndex ); + sb.Append( highlightedSearchTextColor ).Append( "" ); + sb.Append( str, searchOccurrenceIndex, state.searchTerm.Length ); + sb.Append( "" ).Append( "" ); + + searchOccurrenceIndex += state.searchTerm.Length; + prevSearchOccurrenceIndex = searchOccurrenceIndex; + } + + if( prevSearchOccurrenceIndex < str.Length ) + sb.Append( str, prevSearchOccurrenceIndex, str.Length - prevSearchOccurrenceIndex ); + } + + public void OnSettingsChanged( bool resetHighlightedSearchTextColor, bool resetTooltipDescriptionsTextColor ) + { + hoveredData = null; + + if( !resetHighlightedSearchTextColor && !resetTooltipDescriptionsTextColor ) + return; + + if( resetHighlightedSearchTextColor ) + highlightedSearchTextColor = ""; + + for( int i = idToNodeDataLookup.Count - 1; i >= 0; i-- ) + { + if( isSearching && resetHighlightedSearchTextColor ) + idToNodeDataLookup[i].item.displayName = ""; + if( resetTooltipDescriptionsTextColor ) + idToNodeDataLookup[i].ResetTooltip(); + } + } + } + + public class SearchResultTreeViewIsolatedView : EditorWindow + { + private SearchResultTreeView treeView; + private bool shouldRepositionSelf = true; + + public static void Show( Vector2 preferredSize, SearchResultTreeView treeView, GUIContent title ) + { + SearchResultTreeViewIsolatedView window = CreateInstance(); + window.treeView = treeView; + window.titleContent = title; + window.ShowAuxWindow(); + + window.minSize = new Vector2( 150f, Mathf.Min( preferredSize.y, EditorGUIUtility.singleLineHeight * 2f ) ); + window.position = new Rect( new Vector2( -9999f, -9999f ), preferredSize ); + window.Repaint(); + } + + private void OnEnable() + { + wantsMouseMove = wantsMouseEnterLeaveWindow = true; + } + + private void OnGUI() + { + if( treeView == null ) // After domain reload + Close(); + else + { + treeView.OnGUI( GUILayoutUtility.GetRect( 0f, 100000f, 0f, 100000f ) ); + + if( shouldRepositionSelf ) + { + float preferredHeight = GUILayoutUtility.GetLastRect().height; + if( preferredHeight > 10f ) + { + Vector2 size = position.size; + position = Utilities.GetScreenFittedRect( new Rect( GUIUtility.GUIToScreenPoint( Event.current.mousePosition ) + new Vector2( size.x * -0.5f, 10f ), size ) ); + + shouldRepositionSelf = false; + GUIUtility.ExitGUI(); + } + } + } + } + } +} \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/Editor/SearchResultTreeView.cs.meta b/Plugins/AssetUsageDetector/Editor/SearchResultTreeView.cs.meta new file mode 100644 index 0000000..684fdce --- /dev/null +++ b/Plugins/AssetUsageDetector/Editor/SearchResultTreeView.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b3903f1d3149e9b4990e49206f8255c8 +timeCreated: 1638690728 +licenseType: Free +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Plugins/AssetUsageDetector/Editor/Utilities.cs b/Plugins/AssetUsageDetector/Editor/Utilities.cs index 0660e9f..8e44899 100644 --- a/Plugins/AssetUsageDetector/Editor/Utilities.cs +++ b/Plugins/AssetUsageDetector/Editor/Utilities.cs @@ -49,14 +49,11 @@ namespace AssetUsageDetectorNamespace private static readonly string nativeCollectionsNamespace = typeof( NativeArray ).Namespace; #endif + private static MethodInfo screenFittedRectGetter; + private static readonly HashSet folderContentsSet = new HashSet(); - private static readonly StringBuilder stringBuilder = new StringBuilder( 10 ); - -#if UNITY_2018_3_OR_NEWER - private static int previousPingedPrefabInstanceId; - private static double previousPingedPrefabPingTime; -#endif + internal static readonly StringBuilder stringBuilder = new StringBuilder( 400 ); public static readonly GUILayoutOption GL_EXPAND_WIDTH = GUILayout.ExpandWidth( true ); public static readonly GUILayoutOption GL_EXPAND_HEIGHT = GUILayout.ExpandHeight( true ); @@ -79,7 +76,8 @@ namespace AssetUsageDetectorNamespace m_boxGUIStyle = new GUIStyle( EditorStyles.helpBox ) { alignment = TextAnchor.MiddleCenter, - font = EditorStyles.label.font + font = EditorStyles.label.font, + richText = true }; Color textColor = GUI.skin.button.normal.textColor; @@ -99,58 +97,17 @@ namespace AssetUsageDetectorNamespace } } - private static GUIStyle m_tooltipGUIStyle; // GUIStyle used to draw the tooltip - public static GUIStyle TooltipGUIStyle - { - get - { - GUIStyleState normalState; - - if( m_tooltipGUIStyle != null ) - normalState = m_tooltipGUIStyle.normal; - else - { - m_tooltipGUIStyle = new GUIStyle( EditorStyles.helpBox ) - { - alignment = TextAnchor.MiddleCenter, - font = EditorStyles.label.font - }; - - normalState = m_tooltipGUIStyle.normal; - - normalState.background = null; - normalState.scaledBackgrounds = new Texture2D[0]; - normalState.textColor = Color.black; - } - - if( normalState.background == null || normalState.background.Equals( null ) ) - { - Texture2D backgroundTexture = new Texture2D( 1, 1 ) { hideFlags = HideFlags.HideAndDontSave }; - backgroundTexture.SetPixel( 0, 0, new Color( 0.88f, 0.88f, 0.88f, 0.85f ) ); - backgroundTexture.Apply(); - - normalState.background = backgroundTexture; - } - - return m_tooltipGUIStyle; - } - } - - // Get a unique-ish string hash code for an object - public static string Hash( this object obj ) - { - if( obj is Object ) - return obj.GetHashCode().ToString(); - - return obj.GetHashCode() + obj.GetType().Name; - } - // Check if object is an asset or a Scene object public static bool IsAsset( this object obj ) { return obj is Object && AssetDatabase.Contains( (Object) obj ); } + public static bool IsAsset( this Object obj ) + { + return AssetDatabase.Contains( obj ); + } + // Check if object is a folder asset public static bool IsFolder( this Object obj ) { @@ -175,128 +132,65 @@ namespace AssetUsageDetectorNamespace return folderContentsSet; } - // Select an object in the editor - public static void SelectInEditor( this Object obj ) + public static void GetObjectsToSelectAndPing( this Object obj, out Object selection, out Object pingTarget ) { - if( obj == null ) + if( obj == null || obj.Equals( null ) ) + { + selection = pingTarget = null; return; - - if( obj is Component ) - obj = ( (Component) obj ).gameObject; - - Event e = Event.current; - - // If CTRL or Shift keys are pressed, do a multi-select; - // otherwise select only the clicked object and ping it in editor - if( !e.control && !e.shift ) - Selection.activeObject = obj.PingInEditor(); - else - { - Object[] selection = Selection.objects; - Object[] newSelection; - - int selectionIndex = Array.IndexOf( selection, obj ); - if( selectionIndex == -1 ) - { - // Include object in selection - newSelection = new Object[selection.Length + 1]; - selection.CopyTo( newSelection, 0 ); - newSelection[selection.Length] = obj; - } - else - { - // Remove object from selection - newSelection = new Object[selection.Length - 1]; - int j = 0; - for( int i = 0; i < selectionIndex; i++, j++ ) - newSelection[j] = selection[i]; - for( int i = selectionIndex + 1; i < selection.Length; i++, j++ ) - newSelection[j] = selection[i]; - } - - Selection.objects = newSelection; } - } - // Ping an object in either Project view or Hierarchy view - public static Object PingInEditor( this Object obj ) - { if( obj is Component ) obj = ( (Component) obj ).gameObject; - Object selection = obj; + selection = pingTarget = obj; - // Pinging a prefab only works if the pinged object is the root of the prefab - // or a direct child of it. Pinging any grandchildren of the prefab - // does not work; in which case, traverse the parent hierarchy until - // a pingable parent is reached - if( obj.IsAsset() && obj is GameObject ) + if( obj.IsAsset() ) { + if( obj is GameObject ) + { + // Pinging a prefab only works if the pinged object is the root of the prefab or a direct child of it. Pinging any grandchildren + // of the prefab doesn't work; in which case, traverse the parent hierarchy until a pingable parent is reached #if UNITY_2018_3_OR_NEWER - Transform objTR = ( (GameObject) obj ).transform.root; + Transform objTR = ( (GameObject) obj ).transform.root; - PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject ); - if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant ) - { - string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject ); - PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); - - // Try to open the prefab stage of pinged prefabs if they are double clicked - bool previousPingedPrefabIsDoubleClicked = previousPingedPrefabInstanceId == objTR.GetInstanceID(); - if( previousPingedPrefabIsDoubleClicked && EditorApplication.timeSinceStartup - previousPingedPrefabPingTime <= 0.3f && -#if UNITY_2020_1_OR_NEWER - ( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.assetPath ) ) -#else - ( openPrefabStage == null || !openPrefabStage.stageHandle.IsValid() || assetPath != openPrefabStage.prefabAssetPath ) ) -#endif + PrefabAssetType prefabAssetType = PrefabUtility.GetPrefabAssetType( objTR.gameObject ); + if( prefabAssetType == PrefabAssetType.Regular || prefabAssetType == PrefabAssetType.Variant ) { - AssetDatabase.OpenAsset( objTR.gameObject ); - openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); - } - - previousPingedPrefabInstanceId = objTR.GetInstanceID(); - previousPingedPrefabPingTime = EditorApplication.timeSinceStartup; - + string assetPath = AssetDatabase.GetAssetPath( objTR.gameObject ); + PrefabStage openPrefabStage = PrefabStageUtility.GetCurrentPrefabStage(); #if UNITY_2020_1_OR_NEWER - if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath ) + if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.assetPath ) #else - if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.prefabAssetPath ) + if( openPrefabStage != null && openPrefabStage.stageHandle.IsValid() && assetPath == openPrefabStage.prefabAssetPath ) #endif - { - GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot ); - if( prefabStageGO != null ) { - objTR = prefabStageGO.transform; - selection = objTR.gameObject; + GameObject prefabStageGO = FollowSymmetricHierarchy( (GameObject) obj, ( (GameObject) obj ).transform.root.gameObject, openPrefabStage.prefabContentsRoot ); + if( prefabStageGO != null ) + { + objTR = prefabStageGO.transform; + selection = objTR.gameObject; + } } - } #if UNITY_2019_1_OR_NEWER - else if( obj != objTR.gameObject ) - { - if( !previousPingedPrefabIsDoubleClicked ) // Don't spam this log unnecessarily - Debug.Log( "Open " + assetPath + " in prefab mode to select and edit " + obj.name ); - - selection = objTR.gameObject; + else if( obj != objTR.gameObject ) + selection = objTR.gameObject; +#endif } #else - else - { - if( !previousPingedPrefabIsDoubleClicked ) // Don't spam this log unnecessarily - Debug.Log( "Open " + assetPath + " in prefab mode to select and edit " + obj.name ); - } + Transform objTR = ( (GameObject) obj ).transform; + while( objTR.parent != null && objTR.parent.parent != null ) + objTR = objTR.parent; #endif + + pingTarget = objTR.gameObject; + } + else if( ( obj.hideFlags & ( HideFlags.HideInInspector | HideFlags.HideInHierarchy ) ) != HideFlags.None ) + { + // Can't ping assets that are hidden from Project window (e.g. animator states of AnimatorController), ping the main asset at that path instead + pingTarget = AssetDatabase.LoadMainAssetAtPath( AssetDatabase.GetAssetPath( obj ) ); } -#else - Transform objTR = ( (GameObject) obj ).transform; - while( objTR.parent != null && objTR.parent.parent != null ) - objTR = objTR.parent; -#endif - - obj = objTR.gameObject; } - - EditorGUIUtility.PingObject( obj ); - return selection; } // We are passing "go"s root Transform to thisRoot parameter. If we use go.transform.root instead, when we are in prefab mode on @@ -333,6 +227,43 @@ namespace AssetUsageDetectorNamespace return root2.gameObject; } + // Returns -1 if t1 is above t2 in Hierarchy, 1 if t1 is below t2 in Hierarchy and 0 if they are the same object + public static int CompareHierarchySiblingIndices( Transform t1, Transform t2 ) + { + Transform parent1 = t1.parent; + Transform parent2 = t2.parent; + + if( parent1 == parent2 ) + return t1.GetSiblingIndex() - t2.GetSiblingIndex(); + + int deltaHierarchyDepth = 0; + for( ; parent1; parent1 = parent1.parent ) + deltaHierarchyDepth++; + for( ; parent2; parent2 = parent2.parent ) + deltaHierarchyDepth--; + + for( ; deltaHierarchyDepth > 0; deltaHierarchyDepth-- ) + { + t1 = t1.parent; + if( t1 == t2 ) + return 1; + } + for( ; deltaHierarchyDepth < 0; deltaHierarchyDepth++ ) + { + t2 = t2.parent; + if( t1 == t2 ) + return -1; + } + + while( t1.parent != t2.parent ) + { + t1 = t1.parent; + t2 = t2.parent; + } + + return t1.GetSiblingIndex() - t2.GetSiblingIndex(); + } + // Check if the field is serializable public static bool IsSerializable( this FieldInfo fieldInfo ) { @@ -507,9 +438,18 @@ namespace AssetUsageDetectorNamespace // Draw horizontal line inside OnGUI public static void DrawSeparatorLine() { - GUILayout.Space( 4 ); + GUILayout.Space( 4f ); GUILayout.Box( "", GL_HEIGHT_2, GL_EXPAND_WIDTH ); - GUILayout.Space( 4 ); + GUILayout.Space( 4f ); + } + + // Restricts the given Rect within the screen's bounds + public static Rect GetScreenFittedRect( Rect originalRect ) + { + if( screenFittedRectGetter == null ) + screenFittedRectGetter = typeof( EditorWindow ).Assembly.GetType( "UnityEditor.ContainerWindow" ).GetMethod( "FitRectToScreen", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static ); + + return (Rect) screenFittedRectGetter.Invoke( null, new object[3] { originalRect, true, true } ); } // Check if all the objects inside the list are null @@ -610,13 +550,5 @@ namespace AssetUsageDetectorNamespace return false; } - - public static void RemoveAtFast( this List list, int index ) - { - int lastElementIndex = list.Count - 1; - - list[index] = list[lastElementIndex]; - list.RemoveAt( lastElementIndex ); - } } } \ No newline at end of file diff --git a/Plugins/AssetUsageDetector/README.txt b/Plugins/AssetUsageDetector/README.txt index dfff56f..825a1ab 100644 --- a/Plugins/AssetUsageDetector/README.txt +++ b/Plugins/AssetUsageDetector/README.txt @@ -3,12 +3,43 @@ Online documentation available at: https://github.com/yasirkula/UnityAssetUsageDetector E-mail: yasirkula@gmail.com + ### ABOUT -This tool helps you find usages of the selected asset(s) and/or Object(s) in your Unity project, i.e. lists the objects that refer to them. +This tool helps you find usages of the selected asset(s) and/or scene object(s), i.e. lists the objects that refer to them. + ### HOW TO -Open "Window-Asset Usage Detector" window, configure the settings and hit GO! You can also right click an object and select "Search For References". +- Open "Window-Asset Usage Detector" window, configure the settings and hit "GO!". You can also right click an object and select "Search For References" -In the search results page, each row represents a reference to the searched Object(s). Rows can be traversed from left to right to see how the -references are formed. If a node's label contains text inside square brackets (e.g. [Child object]), then that text describes how that node is -connected to the node to its left. \ No newline at end of file +- Asset Usage Detector window can be locked via the "Lock" button in its context menu (or via the lock icon at the top-right corner). If all the + open windows are locked, "Search For References" opens a new window + +- Seach results are split into different groups (scenes, assets, Project Settings) and each group displays its search results in its own tree view. + Tree views support multi-selection and keyboard navigation. It's possible to hide groups or rows via their context menu (right click) + +- Each root row in a group's tree view represents a different searched object and is drawn with an outline. Usage(s) of a searched object are listed under it as + child rows (with indentation). If a child row's label contains bold text inside square brackets (e.g. "[Variable: m_Shader]"), then that text describes how + its parent row is connected to that row (i.e. the value assigned to the m_Shader variable of that row is its parent row). Child rows can have their own children + as some references involve multiple steps (e.g. when a Texture reference is found in a material which is used in a prefab which is referenced by a scene object) + +- Rows with green tint to their left are the main references. For example, main references in a scene are the GameObjects that belong to that scene + +- Rows with yellow tint are the parent rows of the selected row(s). To see a row's connection to the searched object, the yellow tinted rows can be traversed + from bottom to top (or, you can hover the cursor over a row and see its connection to the searched object in a tooltip) + +- Rows with gradient blue tint are the other occurrences of the selected row(s) (a row can appear multiple times in the tree view, right clicking the row and + selecting "Expand All Occurrences" will reveal them all) + +- When "Hide duplicate rows" option is enabled and a row's label starts with "[D]", then it means that the row has appeared in the tree view before and its children + were omitted to simplify the search results (because otherwise the same child rows would be displayed for each occurrence of that row). Only the first occurrence + of a row will display its children when "Hide duplicate rows" is enabled. To find a row's first occurrence, you can right click it and select "Select First Occurrence" + +- Inside "Unused Objects" group, if a row's label starts with "[!]", then it means that some of its children are used in the project and it isn't safe to delete + that object. Right clicking the row and selecting "Show Used Children" will reveal the used children + +- When a prefab's row is double clicked, that prefab is automatically opened in Prefab Mode + +- Selections in tree views are completely independent from each other, it isn't possible to multi-select objects in different tree views. Likewise, selected rows in + a tree view won't be highlighted in other tree views. "Hide duplicate rows" also works independently for each tree view + +- You can tweak most settings/colors via "Project Settings/yasirkula/Asset Usage Detector" page (on older versions, this menu is located at "Preferences" window) \ No newline at end of file diff --git a/package.json b/package.json index 33056e6..e854463 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,9 @@ { "name": "com.yasirkula.assetusagedetector", "displayName": "Asset Usage Detector", - "version": "2.0.0", + "version": "2.1.0", "documentationUrl": "https://github.com/yasirkula/UnityAssetUsageDetector", "changelogUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/releases", "licensesUrl": "https://github.com/yasirkula/UnityAssetUsageDetector/blob/master/LICENSE.txt", - "description": "This editor extension helps you figure out at which places an asset or GameObject is used, i.e. lists the objects that refer to the asset. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!" + "description": "This tool helps you find usages of the selected asset(s) and/or scene object(s), i.e. lists the objects that refer to them. It is possible to search for references in the Assets folder (Project view) and/or in the scene(s) of your project. You can also search for references while in Play mode!" }