diff --git a/Editor/CustomEditors/Base/ExtendedEditor.cs b/Editor/CustomEditors/Base/ExtendedEditor.cs index e710329..1653143 100644 --- a/Editor/CustomEditors/Base/ExtendedEditor.cs +++ b/Editor/CustomEditors/Base/ExtendedEditor.cs @@ -1,6 +1,5 @@ using UnityEditor; using UnityEngine; -using UnityEngine.UIElements; namespace Better.Commons.EditorAddons.CustomEditors.Base { @@ -23,21 +22,20 @@ protected ExtendedEditor(Object target, SerializedObject serializedObject) /// This method called just right after instance created /// public abstract void OnEnable(); - + /// /// Use to draw your inspector /// - public abstract VisualElement CreateInspectorGUI(); - + public abstract void OnInspectorGUI(); + /// /// This method called than editor disables /// public abstract void OnDisable(); - + /// /// Called when object data in editor is changed /// - /// - public abstract void OnChanged(SerializedObject serializedObject); + public abstract void OnChanged(); } } \ No newline at end of file diff --git a/Editor/CustomEditors/MultiEditor.cs b/Editor/CustomEditors/MultiEditor.cs index 8630b87..a9d8b15 100644 --- a/Editor/CustomEditors/MultiEditor.cs +++ b/Editor/CustomEditors/MultiEditor.cs @@ -7,8 +7,6 @@ using Better.Commons.EditorAddons.Extensions; using Better.Commons.Runtime.Extensions; using UnityEditor; -using UnityEditor.UIElements; -using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace Better.Commons.EditorAddons.CustomEditors @@ -92,47 +90,35 @@ private void Iterate(IReadOnlyList<(Type type, MultiEditorAttribute)> extensions } } - public override VisualElement CreateInspectorGUI() + public override void OnInspectorGUI() { - var container = new VisualElement(); - - for (var i = 0; i < _preEditors.Count; i++) + using (var change = new EditorGUI.ChangeCheckScope()) { - var element = _preEditors[i].CreateInspectorGUI(); - if (element != null) + for (var i = 0; i < _preEditors.Count; i++) { - container.Add(element); + _preEditors[i].OnInspectorGUI(); } - } - - if (!_overrideDefault) - { - InspectorElement.FillDefaultInspector(container, serializedObject, this); - } - for (var i = 0; i < _postEditors.Count; i++) - { - var element = _postEditors[i].CreateInspectorGUI(); - if (element != null) + if (!_overrideDefault) { - container.Add(element); + base.OnInspectorGUI(); } - } - container.TrackSerializedObjectValue(serializedObject, OnSerializedObjectTrack); - return container; - } + for (var i = 0; i < _postEditors.Count; i++) + { + _postEditors[i].OnInspectorGUI(); + } - private void OnSerializedObjectTrack(SerializedObject serializedObject) - { - for (var i = 0; i < _preEditors.Count; i++) - { - _preEditors[i].OnChanged(serializedObject); - } + if (!change.changed) return; + for (var i = 0; i < _preEditors.Count; i++) + { + _preEditors[i].OnChanged(); + } - for (var i = 0; i < _postEditors.Count; i++) - { - _postEditors[i].OnChanged(serializedObject); + for (var i = 0; i < _postEditors.Count; i++) + { + _postEditors[i].OnChanged(); + } } } diff --git a/Editor/Drawers/Base/FieldDrawer.cs b/Editor/Drawers/Base/FieldDrawer.cs index 87f72a8..a8b68ed 100644 --- a/Editor/Drawers/Base/FieldDrawer.cs +++ b/Editor/Drawers/Base/FieldDrawer.cs @@ -10,19 +10,92 @@ public abstract class FieldDrawer { protected readonly FieldInfo _fieldInfo; protected readonly MultiPropertyAttribute _attribute; + protected FieldDrawer _nextDrawer; protected FieldDrawer(FieldInfo fieldInfo, MultiPropertyAttribute attribute) { + Selection.selectionChanged += OnSelectionChanged; _fieldInfo = fieldInfo; _attribute = attribute; } - public virtual void Initialize() + ~FieldDrawer() { + EditorApplication.update += DeconstructOnMainThread; } - protected internal abstract void Deconstruct(); + public virtual void Initialize(FieldDrawer drawer) + { + _nextDrawer = drawer; + } + + private void DeconstructOnMainThread() + { + EditorApplication.update -= DeconstructOnMainThread; + Selection.selectionChanged -= OnSelectionChanged; + Deconstruct(); + } + + private void OnSelectionChanged() + { + Selection.selectionChanged -= OnSelectionChanged; + Deconstruct(); + } + + protected abstract void Deconstruct(); + + protected virtual void DrawField(Rect position, SerializedProperty property, GUIContent label) + { + var buffer = PreparePropertyRect(position); + EditorGUI.PropertyField(buffer, property, label, true); + } + + internal void DrawFieldInternal(Rect position, SerializedProperty property, GUIContent label) + { + if (_nextDrawer != null) + { + _nextDrawer.DrawFieldInternal(position, property, label); + return; + } + + DrawField(position, property, label); + } + + internal bool PreDrawInternal(ref Rect position, SerializedProperty property, GUIContent label) + { + if (_nextDrawer != null) + { + return PreDraw(ref position, property, label) && _nextDrawer.PreDrawInternal(ref position, property, label); + } + + return PreDraw(ref position, property, label); + } + + internal void PostDrawInternal(Rect position, SerializedProperty property, GUIContent label) + { + _nextDrawer?.PostDrawInternal(position, property, label); + PostDraw(position, property, label); + } - protected internal abstract void PopulateContainer(ElementsContainer container); + internal HeightCacheValue GetPropertyHeightInternal(SerializedProperty property, GUIContent label) + { + var propertyHeight = GetPropertyHeight(property, label); + if (_nextDrawer != null) + { + var heightInternal = _nextDrawer.GetPropertyHeightInternal(property, label); + return propertyHeight + heightInternal; + } + + return propertyHeight; + } + + protected abstract bool PreDraw(ref Rect position, SerializedProperty property, GUIContent label); + protected abstract Rect PreparePropertyRect(Rect original); + protected abstract void PostDraw(Rect position, SerializedProperty property, GUIContent label); + + protected virtual HeightCacheValue GetPropertyHeight(SerializedProperty property, GUIContent label) + { + return HeightCacheValue.GetFull(EditorGUI.GetPropertyHeight(property, label, true)); + } } } \ No newline at end of file diff --git a/Editor/Drawers/Base/MultiFieldDrawer.cs b/Editor/Drawers/Base/MultiFieldDrawer.cs index d160a40..46fa4ed 100644 --- a/Editor/Drawers/Base/MultiFieldDrawer.cs +++ b/Editor/Drawers/Base/MultiFieldDrawer.cs @@ -9,13 +9,13 @@ namespace Better.Commons.EditorAddons.Drawers.Base { - public abstract class MultiFieldDrawer : FieldDrawer where T : SerializedPropertyHandler + public abstract class MultiFieldDrawer : FieldDrawer where T : UtilityWrapper { private static readonly CacheValue CacheValueField = new CacheValue(); - protected HandlerCollection _handlers; + protected WrapperCollection _wrappers; - protected class CacheValue : CacheValue> + protected class CacheValue : CacheValue> { } @@ -24,20 +24,20 @@ protected MultiFieldDrawer(FieldInfo fieldInfo, MultiPropertyAttribute attribute } /// - /// Method generates explicit typed collection inherited from + /// Method generates explicit typed collection inherited from /// /// - protected abstract HandlerCollection GenerateCollection(); + protected abstract WrapperCollection GenerateCollection(); - public override void Initialize() + public override void Initialize(FieldDrawer drawer) { - base.Initialize(); - _handlers = GenerateCollection(); + base.Initialize(drawer); + _wrappers = GenerateCollection(); } - protected internal override void Deconstruct() + protected override void Deconstruct() { - _handlers?.Deconstruct(); + _wrappers.Deconstruct(); } protected virtual Type GetFieldOrElementType() @@ -50,16 +50,16 @@ protected virtual Type GetFieldOrElementType() } /// - /// Validates if contains property by + /// Validates if contains property by /// - /// SerializedProperty what will be stored into - /// used to validate current stored wrappers and gets instance for recently added property + /// SerializedProperty what will be stored into + /// used to validate current stored wrappers and gets instance for recently added property /// - /// Returns true if wrapper for was already stored into - protected CacheValue ValidateCachedProperties(SerializedProperty property, HandlerMap handler) - where THandler : HandlerMap, new() + /// Returns true if wrapper for was already stored into + protected CacheValue ValidateCachedProperties(SerializedProperty property, BaseUtility handler) + where THandler : new() { - ValidateCachedPropertiesUtility.Validate(_handlers, CacheValueField, property, GetFieldOrElementType(), _attribute.GetType(), handler); + ValidateCachedPropertiesUtility.Validate(_wrappers, CacheValueField, property, GetFieldOrElementType(), _attribute.GetType(), handler); return CacheValueField; } } diff --git a/Editor/Drawers/Base/HandlerCollection.cs b/Editor/Drawers/Base/WrapperCollection.cs similarity index 72% rename from Editor/Drawers/Base/HandlerCollection.cs rename to Editor/Drawers/Base/WrapperCollection.cs index 452bcbc..bc4a76f 100644 --- a/Editor/Drawers/Base/HandlerCollection.cs +++ b/Editor/Drawers/Base/WrapperCollection.cs @@ -5,10 +5,10 @@ namespace Better.Commons.EditorAddons.Drawers.Base { - public class HandlerCollection : Dictionary> - where T : SerializedPropertyHandler + public class WrapperCollection : Dictionary> + where T : UtilityWrapper { - public HandlerCollection() : base(SerializedPropertyComparer.Instance) + public WrapperCollection() : base(SerializedPropertyComparer.Instance) { } diff --git a/Editor/Drawers/Base/HandlerCollection.cs.meta b/Editor/Drawers/Base/WrapperCollection.cs.meta similarity index 100% rename from Editor/Drawers/Base/HandlerCollection.cs.meta rename to Editor/Drawers/Base/WrapperCollection.cs.meta diff --git a/Editor/Drawers/Base/CollectionValue.cs b/Editor/Drawers/Base/WrapperCollectionValue.cs similarity index 68% rename from Editor/Drawers/Base/CollectionValue.cs rename to Editor/Drawers/Base/WrapperCollectionValue.cs index 8857390..94f35d3 100644 --- a/Editor/Drawers/Base/CollectionValue.cs +++ b/Editor/Drawers/Base/WrapperCollectionValue.cs @@ -3,9 +3,9 @@ namespace Better.Commons.EditorAddons.Drawers.Base { - public class CollectionValue where T : SerializedPropertyHandler + public class WrapperCollectionValue where T : UtilityWrapper { - public CollectionValue(T wrapper, Type type) + public WrapperCollectionValue(T wrapper, Type type) { Wrapper = wrapper; Type = type; diff --git a/Editor/Drawers/Base/CollectionValue.cs.meta b/Editor/Drawers/Base/WrapperCollectionValue.cs.meta similarity index 100% rename from Editor/Drawers/Base/CollectionValue.cs.meta rename to Editor/Drawers/Base/WrapperCollectionValue.cs.meta diff --git a/Editor/Drawers/BasePropertyDrawer.cs b/Editor/Drawers/BasePropertyDrawer.cs deleted file mode 100644 index 2dcd808..0000000 --- a/Editor/Drawers/BasePropertyDrawer.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Reflection; -using Better.Commons.EditorAddons.Drawers.Base; -using Better.Commons.EditorAddons.Drawers.Caching; -using Better.Commons.EditorAddons.Drawers.Utility; -using Better.Commons.Runtime.Drawers.Attributes; -using Better.Commons.Runtime.Extensions; -using UnityEditor; -using UnityEditor.UIElements; -using UnityEngine.UIElements; - -namespace Better.Commons.EditorAddons.Drawers -{ - public abstract class BasePropertyDrawer : PropertyDrawer where T : SerializedPropertyHandler - { - protected FieldInfo _fieldInfo => fieldInfo; - protected MultiPropertyAttribute _attribute => (MultiPropertyAttribute)attribute; - private static readonly CacheValue CacheValueField = new CacheValue(); - - protected HandlerCollection _handlers; - - protected class CacheValue : CacheValue> - { - } - - protected BasePropertyDrawer() - { - Selection.selectionChanged += OnSelectionChanged; - } - - ~BasePropertyDrawer() - { - EditorApplication.update += DeconstructOnMainThread; - } - - public override VisualElement CreatePropertyGUI(SerializedProperty property) - { - var container = new ElementsContainer(property); - var propertyField = new PropertyField(property); - propertyField.style.FlexGrow(new StyleFloat(1)); - var defaultElement = container.CreateElementFrom(propertyField); - defaultElement.AddTag(typeof(PropertyDrawer)); - defaultElement.AddTag(property); - - _handlers = GenerateCollection(); - PopulateContainer(container); - - return container.Generate(); - } - - /// - /// Method generates explicit typed collection inherited from - /// - /// - protected abstract HandlerCollection GenerateCollection(); - - protected abstract void PopulateContainer(ElementsContainer container); - - private void DeconstructOnMainThread() - { - EditorApplication.update -= DeconstructOnMainThread; - Selection.selectionChanged -= OnSelectionChanged; - Deconstruct(); - } - - private void OnSelectionChanged() - { - Selection.selectionChanged -= OnSelectionChanged; - Deconstruct(); - } - - protected virtual Type GetFieldOrElementType() - { - var fieldType = _fieldInfo.FieldType; - if (fieldType.IsArrayOrList()) - return fieldType.GetCollectionElementType(); - - return fieldType; - } - - /// - /// Validates if contains property by - /// - /// SerializedProperty what will be stored into - /// used to validate current stored wrappers and gets instance for recently added property - /// - /// Returns true if wrapper for was already stored into - protected CacheValue ValidateCachedProperties(SerializedProperty property, HandlerMap handler) - where THandler : HandlerMap, new() - { - ValidateCachedPropertiesUtility.Validate(_handlers, CacheValueField, property, GetFieldOrElementType(), _attribute.GetType(), handler); - return CacheValueField; - } - - protected virtual void Deconstruct() - { - _handlers?.Deconstruct(); - } - } -} \ No newline at end of file diff --git a/Editor/Drawers/BasePropertyDrawer.cs.meta b/Editor/Drawers/BasePropertyDrawer.cs.meta deleted file mode 100644 index ecea6f7..0000000 --- a/Editor/Drawers/BasePropertyDrawer.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: bbb270479ba84bb8bcfca7d8ae9f13d6 -timeCreated: 1716417021 \ No newline at end of file diff --git a/Editor/Drawers/Caching/ValidateCachedPropertiesUtility.cs b/Editor/Drawers/Caching/ValidateCachedPropertiesUtility.cs index af3a5e1..9230867 100644 --- a/Editor/Drawers/Caching/ValidateCachedPropertiesUtility.cs +++ b/Editor/Drawers/Caching/ValidateCachedPropertiesUtility.cs @@ -8,10 +8,10 @@ namespace Better.Commons.EditorAddons.Drawers.Caching { public static class ValidateCachedPropertiesUtility { - public static void Validate(HandlerCollection handlers, TCache cache, SerializedProperty property, Type fieldType, - Type attributeType, HandlerMap handler) where TCache : CacheValue> - where TWrapper : SerializedPropertyHandler - where THandler :HandlerMap, new() + public static void Validate(WrapperCollection wrappers, TCache cache, SerializedProperty property, Type fieldType, + Type attributeType, BaseUtility handler) where TCache : CacheValue> + where TWrapper : UtilityWrapper + where THandler : new() { if (cache == null) { @@ -19,9 +19,9 @@ public static void Validate(HandlerCollection(nameof(handlers)); + DebugUtility.LogException(nameof(wrappers)); cache.Set(false, null); return; } @@ -54,22 +54,22 @@ public static void Validate(HandlerCollection(fieldType, attributeType); + var wrapper = handler.GetUtilityWrapper(fieldType, attributeType); if (wrapper == null) { cache.Set(false, null); return; } - var collectionValue = new CollectionValue(wrapper, fieldType); - handlers.Add(property, collectionValue); + var collectionValue = new WrapperCollectionValue(wrapper, fieldType); + wrappers.Add(property, collectionValue); cache.Set(false, collectionValue); } } diff --git a/Editor/Drawers/ElementsContainer.cs b/Editor/Drawers/ElementsContainer.cs deleted file mode 100644 index efdb56b..0000000 --- a/Editor/Drawers/ElementsContainer.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Better.Commons.EditorAddons.Utility; -using Better.Commons.Runtime.Utility; -using UnityEditor; -using UnityEditor.UIElements; -using UnityEngine.UIElements; - -namespace Better.Commons.EditorAddons.Drawers -{ - public class ElementsContainer - { - public SerializedProperty Property { get; } - public SerializedObject Object => Property.serializedObject; - private List _elements; - private VisualElement _container; - - public IStyle ContainerStyle => _container.style; - public event Action OnSerializedObjectChanged; - - public ElementsContainer(SerializedProperty property) - { - Property = property; - _elements = new List(); - _container = new VisualElement(); - var classStyle = StyleDefinition.AddSubState(StyleDefinition.BetterPropertyClass, nameof(ElementsContainer)); - _container.AddToClassList(classStyle); - _container.TrackSerializedObjectValue(Object, Callback); - } - - public FieldVisualElement CreateElementFrom(VisualElement element) - { - var item = new FieldVisualElement(element); - _elements.Add(item); - return item; - } - - public void SetEnabled(bool value) - { - _container.SetEnabled(value); - } - - public FieldVisualElement CreateElement() - { - var item = new FieldVisualElement(); - _elements.Add(item); - return item; - } - - public FieldVisualElement GetByTag(object tag) - { - if (TryGetByTag(tag, out var fieldVisualElement)) - { - return fieldVisualElement; - } - - throw new KeyNotFoundException($"Element with tag: {tag} not found"); - } - - public IEnumerable GetByTags(IEnumerable tag) - { - return _elements.Where(x => x.ContainsAnyTags(tag)); - } - - public bool TryGetByTag(object tag, out FieldVisualElement element) - { - element = _elements.FirstOrDefault(x => x.ContainsTag(tag)); - return element != null; - } - - public IEnumerable GetAll() - { - return _elements; - } - - public void ClearElements() - { - _elements.Clear(); - } - - public VisualElement Generate() - { - foreach (var value in _elements) - { - var visualElement = value.Generate(); - _container.Add(visualElement); - } - - return _container; - } - - private void Callback(SerializedObject obj) - { - OnSerializedObjectChanged?.Invoke(this); - } - } -} \ No newline at end of file diff --git a/Editor/Drawers/ElementsContainer.cs.meta b/Editor/Drawers/ElementsContainer.cs.meta deleted file mode 100644 index 61d5064..0000000 --- a/Editor/Drawers/ElementsContainer.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: dde73507efb44fd6ad7d0c96e7bb95c6 -timeCreated: 1714928738 \ No newline at end of file diff --git a/Editor/Drawers/FieldVisualElement.cs b/Editor/Drawers/FieldVisualElement.cs deleted file mode 100644 index 9d22276..0000000 --- a/Editor/Drawers/FieldVisualElement.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Collections.Generic; -using Better.Commons.EditorAddons.Utility; -using Better.Commons.Runtime.Utility; -using UnityEngine.UIElements; - -namespace Better.Commons.EditorAddons.Drawers -{ - public class FieldVisualElement : IComparable - { - private readonly VisualElement _root; - - private readonly HashSet _tags; - - public List Elements { get; private set; } - public int Order { get; set; } - public IStyle RootStyle => _root.style; - - public FieldVisualElement() - { - Elements = new List(); - _root = new VisualElement(); - var classStyle = StyleDefinition.AddSubState(StyleDefinition.BetterPropertyClass, nameof(FieldVisualElement)); - _root.AddToClassList(classStyle); - _tags = new HashSet(); - } - - public FieldVisualElement(VisualElement element) : this() - { - Elements.Add(element); - } - - public bool ContainsTag(object value) - { - return _tags != null && _tags.Contains(value); - } - - public bool ContainsAllTags(IEnumerable values) - { - if (values == null) - { - var message = $"{nameof(values)} cannot be null"; - DebugUtility.LogException(message); - return false; - } - - foreach (var value in values) - { - if (!ContainsTag(value)) - { - return false; - } - } - - return true; - } - - public bool ContainsAnyTags(IEnumerable values) - { - if (values == null) - { - var message = $"{nameof(values)} cannot be null"; - DebugUtility.LogException(message); - return false; - } - - foreach (var value in values) - { - if (ContainsTag(value)) - { - return true; - } - } - - return false; - } - - public void AddTag(object value) - { - if (value == null) - { - var message = $"{nameof(value)} cannot be null"; - DebugUtility.LogException(message); - return; - } - - if (!ContainsTag(value)) - { - _tags.Add(value); - } - } - - public void AddTags(IEnumerable values) - { - if (values == null) - { - var message = $"{nameof(values)} cannot be null"; - DebugUtility.LogException(message); - return; - } - - foreach (var value in values) - { - AddTag(value); - } - } - - public void RemoveTag(object value) - { - _tags?.Remove(value); - } - - public void RemoveTags(IEnumerable values) - { - if (values == null) - { - var message = $"{nameof(values)} cannot be null"; - DebugUtility.LogException(message); - return; - } - - foreach (var value in values) - { - RemoveTag(value); - } - } - - public int CompareTo(FieldVisualElement other) - { - if (ReferenceEquals(this, other)) return 0; - if (ReferenceEquals(null, other)) return 1; - return Order.CompareTo(other.Order); - } - - public VisualElement Generate() - { - foreach (var visualElement in Elements) - { - _root.Add(visualElement); - } - - return _root; - } - } -} \ No newline at end of file diff --git a/Editor/Drawers/FieldVisualElement.cs.meta b/Editor/Drawers/FieldVisualElement.cs.meta deleted file mode 100644 index b39ac32..0000000 --- a/Editor/Drawers/FieldVisualElement.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: aca97b632872405abec912b9e8120ef2 -timeCreated: 1715681772 \ No newline at end of file diff --git a/Editor/Drawers/MultiPropertyDrawer.cs b/Editor/Drawers/MultiPropertyDrawer.cs index 92d88eb..8843c21 100644 --- a/Editor/Drawers/MultiPropertyDrawer.cs +++ b/Editor/Drawers/MultiPropertyDrawer.cs @@ -10,32 +10,21 @@ using Better.Internal.Core.Runtime; using UnityEditor; using UnityEditor.Callbacks; -using UnityEditor.UIElements; -using UnityEngine.UIElements; +using UnityEngine; namespace Better.Commons.EditorAddons.Drawers { - // [CustomPropertyDrawer(typeof(MultiPropertyAttribute), true)] + [CustomPropertyDrawer(typeof(MultiPropertyAttribute), true)] public sealed class MultiPropertyDrawer : PropertyDrawer { private static Dictionary _fieldDrawers = new Dictionary(AssignableFromComparer.Instance); - - private static Dictionary _propertyDrawers = - new Dictionary(); - private bool _initialized; - private List _drawers; - - public MultiPropertyDrawer() - { - _drawers = new List(); - } + private FieldDrawer _rootDrawer; [InitializeOnLoadMethod] [DidReloadScripts] private static void OnInitialize() { - _propertyDrawers.Clear(); var types = typeof(FieldDrawer).GetAllInheritedTypesWithoutUnityObject(); foreach (var type in types) { @@ -43,75 +32,51 @@ private static void OnInitialize() foreach (var att in atts) { if (att == null) continue; - if (!_fieldDrawers.TryAdd(att.ForAttribute, type)) + if (!_fieldDrawers.ContainsKey(att.ForAttribute)) { - if (att.Override) - { - _fieldDrawers[att.ForAttribute] = type; - } + _fieldDrawers.Add(att.ForAttribute, type); + } + else if (att.Override) + { + _fieldDrawers[att.ForAttribute] = type; } } } } - ~MultiPropertyDrawer() + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { - EditorApplication.update += DeconstructOnMainThread; - } - - - private void DeconstructOnMainThread() - { - EditorApplication.update -= DeconstructOnMainThread; - Selection.selectionChanged -= OnSelectionChanged; - Deconstruct(); - } + TryInitialize(); - private void OnSelectionChanged() - { - Selection.selectionChanged -= OnSelectionChanged; - Deconstruct(); - } + if (_rootDrawer == null) + { + EditorGUI.PropertyField(position, property, label, true); + return; + } - private void Deconstruct() - { - _propertyDrawers.Remove(this); - foreach (var fieldDrawer in _drawers) + if (_rootDrawer.PreDrawInternal(ref position, property, label)) { - fieldDrawer.Deconstruct(); + _rootDrawer.DrawFieldInternal(position, property, label); } + + _rootDrawer.PostDrawInternal(position, property, label); } - public override VisualElement CreatePropertyGUI(SerializedProperty property) + public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { - Selection.selectionChanged += OnSelectionChanged; - if (_propertyDrawers.ContainsValue(property.propertyPath)) + TryInitialize(); + if (_rootDrawer == null) { - var visualElement = new VisualElement(); - visualElement.visible = false; - return visualElement; + return EditorGUI.GetPropertyHeight(property, label, true); } - TryInitialize(); - _propertyDrawers.Add(this, property.propertyPath); - VisualElement propertyField = new PropertyField(property); - if (_drawers.Count > 0) + var height = _rootDrawer.GetPropertyHeightInternal(property, label); + if (height.IsValid) { - var container = new ElementsContainer(property); - var defaultElement = container.CreateElementFrom(propertyField); - propertyField.style.FlexGrow(new StyleFloat(1)); - defaultElement.AddTag(typeof(PropertyDrawer)); - defaultElement.AddTag(property); - - foreach (var fieldDrawer in _drawers) - { - fieldDrawer.PopulateContainer(container); - } - - propertyField = container.Generate(); + return height.Value + EditorGUI.GetPropertyHeight(property, label, true); } - return propertyField; + return height.Value; } private IOrderedEnumerable GetAttributes(FieldInfo field) @@ -125,6 +90,7 @@ private void TryInitialize() _initialized = true; var attributes = GetAttributes(fieldInfo); + var drawers = new List(); var param = new object[] { fieldInfo, null }; foreach (var propertyAttribute in attributes) { @@ -132,8 +98,24 @@ private void TryInitialize() param[1] = propertyAttribute; var drawer = (FieldDrawer)Activator.CreateInstance(drawerType, Defines.ConstructorFlags, null, param, null); - drawer.Initialize(); - _drawers.Add(drawer); + drawers.Add(drawer); + } + + if (drawers.Count <= 0) return; + + _rootDrawer = drawers[0]; + if (drawers.Count < 2) + { + drawers[0].Initialize(null); + } + else + { + for (var index = 0; index < drawers.Count - 1; index++) + { + drawers[index].Initialize(drawers[index + 1]); + } + + drawers[drawers.Count - 1].Initialize(null); } } } diff --git a/Editor/Drawers/Utility/HandlerMap.cs b/Editor/Drawers/Utility/BaseUtility.cs similarity index 83% rename from Editor/Drawers/Utility/HandlerMap.cs rename to Editor/Drawers/Utility/BaseUtility.cs index 1027b7b..aafa795 100644 --- a/Editor/Drawers/Utility/HandlerMap.cs +++ b/Editor/Drawers/Utility/BaseUtility.cs @@ -7,28 +7,27 @@ namespace Better.Commons.EditorAddons.Drawers.Utility { - //TODO: Maybe make Locator> - public abstract class HandlerMap where TMap : HandlerMap, new() + public abstract class BaseUtility where THandler : new() { - private static TMap _instance; + private static THandler _instance; protected HashSet _availableTypes; protected BaseWrappersTypeCollection _wrappersCollection; - public static TMap Instance + public static THandler Instance { get { if (_instance == null) { - _instance = new TMap(); + _instance = new THandler(); } return _instance; } } - protected HandlerMap() + protected BaseUtility() { Construct(); } @@ -41,7 +40,7 @@ private void Construct() /// - /// Type collection for . + /// Type collection for . /// Example: /// /// return new WrappersTypeCollection() @@ -84,7 +83,7 @@ private void Construct() /// /// /// - public T GetHandler(Type fieldType, Type attributeType) where T : SerializedPropertyHandler + public T GetUtilityWrapper(Type fieldType, Type attributeType) where T : UtilityWrapper { if (fieldType == null) { @@ -129,15 +128,16 @@ public virtual bool IsSupported(Type type) } /// - /// Validates stored properties if their supported + /// Validates stored properties if their supported /// /// + /// /// - /// - public void ValidateCachedProperties(HandlerCollection handler) where T : SerializedPropertyHandler + /// + public void ValidateCachedProperties(WrapperCollection gizmoWrappers) where T : UtilityWrapper { List keysToRemove = null; - foreach (var value in handler) + foreach (var value in gizmoWrappers) { if (IsSupported(value.Value.Type)) continue; if (keysToRemove == null) @@ -151,7 +151,7 @@ public void ValidateCachedProperties(HandlerCollection handler) where T : { foreach (var serializedProperty in keysToRemove) { - handler.Remove(serializedProperty); + gizmoWrappers.Remove(serializedProperty); } } } diff --git a/Editor/Drawers/Utility/HandlerMap.cs.meta b/Editor/Drawers/Utility/BaseUtility.cs.meta similarity index 100% rename from Editor/Drawers/Utility/HandlerMap.cs.meta rename to Editor/Drawers/Utility/BaseUtility.cs.meta diff --git a/Editor/Drawers/Utility/SerializedPropertyHandler.cs b/Editor/Drawers/Utility/UtilityWrapper.cs similarity index 69% rename from Editor/Drawers/Utility/SerializedPropertyHandler.cs rename to Editor/Drawers/Utility/UtilityWrapper.cs index f87d450..e2703c4 100644 --- a/Editor/Drawers/Utility/SerializedPropertyHandler.cs +++ b/Editor/Drawers/Utility/UtilityWrapper.cs @@ -1,6 +1,6 @@ namespace Better.Commons.EditorAddons.Drawers.Utility { - public abstract class SerializedPropertyHandler + public abstract class UtilityWrapper { public abstract void Deconstruct(); } diff --git a/Editor/Drawers/Utility/SerializedPropertyHandler.cs.meta b/Editor/Drawers/Utility/UtilityWrapper.cs.meta similarity index 100% rename from Editor/Drawers/Utility/SerializedPropertyHandler.cs.meta rename to Editor/Drawers/Utility/UtilityWrapper.cs.meta diff --git a/Editor/DropDown/DropdownWindow.cs b/Editor/DropDown/DropdownWindow.cs index a4c60a3..1d9d790 100644 --- a/Editor/DropDown/DropdownWindow.cs +++ b/Editor/DropDown/DropdownWindow.cs @@ -203,7 +203,7 @@ private bool CaseEscape() private void ResolveSize(Vector2 size) { var width = Mathf.Max(position.width, size.x + 50f); - var height = UnityEditor.EditorGUIUtility.singleLineHeight * _maxLines + VisualElementUtility.SpaceHeight; + var height = UnityEditor.EditorGUIUtility.singleLineHeight * _maxLines + ExtendedGUIUtility.SpaceHeight; var copy = position; copy.position = _display; copy.width = width; diff --git a/Editor/EditorPopups/EditorPopup.cs b/Editor/EditorPopups/EditorPopup.cs index c947508..4ab505b 100644 --- a/Editor/EditorPopups/EditorPopup.cs +++ b/Editor/EditorPopups/EditorPopup.cs @@ -9,60 +9,43 @@ public class EditorPopup : EditorWindow private Texture _texture; private bool _needUpdate = true; private bool _destroyTexture; - private Action _updateAction; public event Action Closed; public event Action FocusLost; public event Action Destroyed; - public static EditorPopup Initialize(Texture texture, Rect position, bool destroyTexture = false) + public static EditorPopup Initialize(Texture texture, Rect position, bool needUpdate, bool destroyTexture = false) { var window = HasOpenInstances() ? GetWindow() : CreateInstance(); - return Initialize(texture, position, destroyTexture, window); - } - - private static EditorPopup Initialize(Texture texture, Rect position, bool destroyTexture, EditorPopup window) - { window.position = position; window._texture = texture; - window._needUpdate = false; + window._needUpdate = needUpdate; window._destroyTexture = destroyTexture; window.ShowPopup(); return window; } - public static EditorPopup InitializeAsWindow(Texture texture, Rect position, bool destroyTexture = false) + public static EditorPopup InitializeAsWindow(Texture texture, Rect position, bool needUpdate, + bool destroyTexture = false) { var window = HasOpenInstances() ? GetWindow() : CreateInstance(); window.position = position; - window.SetTexture(texture); - window._needUpdate = false; + window._texture = texture; + window._needUpdate = needUpdate; window._destroyTexture = destroyTexture; window.ShowUtility(); return window; } - public EditorPopup SetUpdateAction(Action action) - { - _updateAction = action; - _needUpdate = true; - return this; - } - private void Update() { if (_needUpdate) - { - _updateAction?.Invoke(); Repaint(); - } } private void OnGUI() { if (_texture != null) - { GUI.DrawTexture(new Rect(0, 0, position.width, position.height), _texture, ScaleMode.ScaleToFit, true); - } } private void OnLostFocus() @@ -79,7 +62,13 @@ public static void CloseInstance() { if (!HasOpenInstances()) return; var window = GetWindow(); - window.ClosePopup(); + window.Closed?.Invoke(); + if (window._destroyTexture && window._texture) + { + DestroyImmediate(window._texture); + } + + window.Close(); } public void UpdatePosition(Vector2 newPosition) @@ -88,25 +77,5 @@ public void UpdatePosition(Vector2 newPosition) rect.position = newPosition; position = rect; } - - public void SetTexture(Texture texture) - { - _texture = texture; - } - - public void ClosePopup() - { - OnClosePopup(); - Close(); - } - - private void OnClosePopup() - { - Closed?.Invoke(); - if (_destroyTexture && _texture) - { - DestroyImmediate(_texture); - } - } } } \ No newline at end of file diff --git a/Editor/Extensions/ElementsContainerExtensions.cs b/Editor/Extensions/ElementsContainerExtensions.cs deleted file mode 100644 index a136c6e..0000000 --- a/Editor/Extensions/ElementsContainerExtensions.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using Better.Commons.EditorAddons.Drawers; -using Better.Commons.EditorAddons.Enums; -using Better.Commons.EditorAddons.Extensions; -using Better.Commons.Runtime.Extensions; -using UnityEditor; -using UnityEditor.UIElements; -using UnityEngine.UIElements; - -namespace Better.Commons.EditorAddons.Utility -{ - public static class ElementsContainerExtensions - { - //TODO: Add validation - public static void AddClickableIcon(this ElementsContainer self, IconType iconType, SerializedProperty property, - EventCallback action) - { - var image = self.AddIcon(iconType); - image.RegisterCallback(action, (property, image)); - } - - public static Image AddIcon(this ElementsContainer self, IconType iconType) - { - var icon = iconType.GetIcon(); - var image = VisualElementUtility.CreateLabelIcon(iconType); - - var element = self.GetByTag(self.Property); - element.RootStyle.FlexDirection(new StyleEnum(FlexDirection.Row)); - element.Elements.Insert(0, image); - return image; - } - - public static bool TryGetPropertyField(this ElementsContainer self, out PropertyField propertyField) - { - if (!self.TryGetByTag(self.Property, out var propertyElement)) - { - propertyField = null; - return false; - } - - if (!propertyElement.Elements.TryFind(out propertyField)) - { - propertyField = null; - return false; - } - - return true; - } - - public static void AddNotSupportedBox(this ElementsContainer self, Type fieldType, Type attributeType) - { - var helpBox = VisualElementUtility.NotSupportedBox(self.Property, fieldType, attributeType); - if (self.TryGetByTag(VisualElementUtility.NotSupportedTag, out var element)) - { - element.Elements.Add(helpBox); - } - else - { - element = self.CreateElementFrom(helpBox); - element.AddTag(VisualElementUtility.NotSupportedTag); - } - } - - public static FieldVisualElement GetOrAddHelpBox(this ElementsContainer self, string message, object tag, HelpBoxMessageType messageType) - { - if (!self.TryGetByTag(tag, out var element)) - { - var helpBox = VisualElementUtility.HelpBox(message, messageType); - element = self.CreateElementFrom(helpBox); - element.AddTag(tag); - } - - return element; - } - } -} \ No newline at end of file diff --git a/Editor/Extensions/ElementsContainerExtensions.cs.meta b/Editor/Extensions/ElementsContainerExtensions.cs.meta deleted file mode 100644 index 971ee1a..0000000 --- a/Editor/Extensions/ElementsContainerExtensions.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: f1fcfecf040e4fbda9e2aee0fc54e902 -timeCreated: 1715908373 \ No newline at end of file diff --git a/Editor/Extensions/VisualElementExtension.cs b/Editor/Extensions/VisualElementExtension.cs deleted file mode 100644 index 08173e0..0000000 --- a/Editor/Extensions/VisualElementExtension.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Better.Commons.EditorAddons.Enums; -using Better.Commons.EditorAddons.Utility; -using Better.Commons.Runtime.Extensions; -using UnityEditor; -using UnityEngine.UIElements; - -namespace Better.Commons.EditorAddons.Extensions -{ - public static class VisualElementExtension - { - public static void AddClickedEvent(this VisualElement self, SerializedProperty property, EventCallback action) - { - self.RegisterCallback(action, property); - } - - public static void AddIconClickedEvent(this VisualElement self, SerializedProperty property, EventCallback action) - { - var image = self.Q(); - AddClickedEvent(image, property, action); - } - - public static void AddClickableIcon(this VisualElement self, IconType iconType, SerializedProperty property, - EventCallback action) - { - var image = AddIcon(self, iconType); - image.RegisterCallback(action, (property, image)); - } - - public static Image AddIcon(this VisualElement self, IconType iconType) - { - var image = VisualElementUtility.CreateLabelIcon(iconType); - self.Insert(0, image); - return image; - } - } -} \ No newline at end of file diff --git a/Editor/Extensions/VisualElementExtension.cs.meta b/Editor/Extensions/VisualElementExtension.cs.meta deleted file mode 100644 index 5fae4ba..0000000 --- a/Editor/Extensions/VisualElementExtension.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: ca3dfc0e43684f4b87fd9741cb9842c4 -timeCreated: 1716168717 \ No newline at end of file diff --git a/Editor/Utility/ExtendedGUIUtility.cs b/Editor/Utility/ExtendedGUIUtility.cs new file mode 100644 index 0000000..b9f7b77 --- /dev/null +++ b/Editor/Utility/ExtendedGUIUtility.cs @@ -0,0 +1,348 @@ +using System; +using Better.Commons.EditorAddons.Enums; +using Better.Commons.EditorAddons.Extensions; +using Better.Commons.Runtime.Utility; +using UnityEditor; +using UnityEngine; + +namespace Better.Commons.EditorAddons.Utility +{ + public static class ExtendedGUIUtility + { + private static float _spaceHeight = 6f; + private static GUIStyle _helpBoxStyle; + public static float SpaceHeight => _spaceHeight; + + public const int MouseButtonLeft = 0; + public const int MouseButtonRight = 1; + public const int MouseButtonMiddle = 2; + + /// + /// Override for default Inspector HelpBox with RTF text + /// + /// + /// + /// + public static void HelpBox(string message, IconType type, bool useSpace = true) + { + var style = new GUIStyle(EditorStyles.helpBox) { richText = true, fontSize = 11 }; + HelpBox(message, type, style, useSpace); + } + + /// + /// Override for default Inspector HelpBox with Rich text + /// + /// + /// + /// + public static void HelpBox(Rect position, string message, IconType type) + { + HelpBox(message, position, type, CreateOrReturnHelpBoxStyle()); + } + + public static string NotSupportedMessage(string fieldName, Type fieldType, Type attributeType) + { + return + $"Field {FormatBold(fieldName)} of type {FormatBold(fieldType.Name)} not supported for {FormatBold(attributeType.Name)}"; + } + + /// + /// Not supported Inspector HelpBox with RTF text + /// + /// + /// + /// + /// + /// + /// + public static void NotSupportedAttribute(Rect position, SerializedProperty property, GUIContent label, Type fieldType, Type attributeType, float offset) + { + if (property == null) + { + DebugUtility.LogException(nameof(property)); + return; + } + + if (label == null) + { + DebugUtility.LogException(nameof(label)); + return; + } + + if (fieldType == null) + { + DebugUtility.LogException(nameof(fieldType)); + return; + } + + if (attributeType == null) + { + DebugUtility.LogException(nameof(attributeType)); + return; + } + + HelpBoxFromRect(position, property, label, NotSupportedMessage(property.name, fieldType, attributeType), IconType.ErrorMessage, offset); + } + + /// + /// Not supported Inspector HelpBox with RTF text + /// + /// + /// + /// + /// + /// + public static void NotSupportedAttribute(Rect position, SerializedProperty property, GUIContent label, Type fieldType, Type attributeType) + { + var offset = EditorGUI.GetPropertyHeight(property, label, true) + SpaceHeight; + NotSupportedAttribute(position, property, label, fieldType, attributeType, offset); + } + + public static void HelpBoxFromRect(Rect position, SerializedProperty property, GUIContent label, string message, IconType messageType, float offset = 0) + { + if (property == null) + { + DebugUtility.LogException(nameof(property)); + return; + } + + if (label == null) + { + DebugUtility.LogException(nameof(label)); + return; + } + + var buffer = new Rect(position); + + var lab = new GUIContent(label); + + buffer.y += offset; + + label.image = lab.image; + label.text = lab.text; + label.tooltip = lab.tooltip; + + HelpBox(buffer, message, messageType); + } + + public static string FormatBold(string text) + { + return $"{text}"; + } + + public static string FormatItalic(string text) + { + return $"{text}"; + } + + public static string FormatBoldItalic(string text) + { + return $"{text}"; + } + + public static string BeautifyFormat(string text) + { + return $"\"{text}\""; + } + + /// + /// Override for default Inspector HelpBox with style + /// + /// + /// + /// + /// + private static void HelpBox(string message, IconType type, GUIStyle style, bool useSpace) + { + if (style == null) + { + DebugUtility.LogException(nameof(style)); + return; + } + + var icon = type.GetIconName(); + if (useSpace) + { + EditorGUILayout.Space(_spaceHeight); + } + + EditorGUILayout.LabelField(GUIContent.none, EditorGUIUtility.TrTextContentWithIcon(message, icon), style); + } + + /// + /// Override for default Inspector HelpBox with style + /// + /// + /// + /// + /// + private static void HelpBox(string message, Rect position, IconType type, GUIStyle style) + { + var icon = type.GetIconName(); + var rect = new Rect(position); + var withIcon = EditorGUIUtility.TrTextContentWithIcon(message, icon); + rect.height = style.CalcHeight(withIcon, rect.width); + EditorGUI.LabelField(rect, GUIContent.none, withIcon, style); + } + + /// + /// Override for default Inspector HelpBox with style + /// + /// + /// + /// + private static void HelpBox(Rect position, GUIContent message, GUIStyle style) + { + EditorGUI.LabelField(position, GUIContent.none, message, style); + } + + /// + /// Override for default Inspector HelpBox with style + /// + /// + /// + public static void HelpBox(Rect position, GUIContent message) + { + if (message == null) + { + DebugUtility.LogException(nameof(message)); + return; + } + + HelpBox(position, message, CreateOrReturnHelpBoxStyle()); + } + + public static float GetHelpBoxHeight(float width, string message, IconType type) + { + var icon = type.GetIconName(); + var withIcon = EditorGUIUtility.TrTextContentWithIcon(message, icon); + return CreateOrReturnHelpBoxStyle().CalcHeight(withIcon, width); + } + + public static float GetHelpBoxHeight(string message, IconType type) + { + var icon = type.GetIconName(); + var withIcon = EditorGUIUtility.TrTextContentWithIcon(message, icon); + return CreateOrReturnHelpBoxStyle().CalcHeight(withIcon, EditorGUIUtility.currentViewWidth); + } + + public static float GetHelpBoxHeight(GUIContent message) + { + if (message == null) + { + DebugUtility.LogException(nameof(message)); + return 0; + } + + return CreateOrReturnHelpBoxStyle().CalcHeight(message, EditorGUIUtility.currentViewWidth); + } + + public static float GetHelpBoxHeight(string message) + { + return GetHelpBoxHeight(new GUIContent(message)); + } + + private static GUIStyle CreateOrReturnHelpBoxStyle() + { + if (_helpBoxStyle == null) + _helpBoxStyle = new GUIStyle(EditorStyles.helpBox) { richText = true, fontSize = 11, wordWrap = true }; + return _helpBoxStyle; + } + + public static int SelectionGrid(int selected, string[] texts, int xCount, GUIStyle style, + params GUILayoutOption[] options) + { + var bufferSelected = selected; + GUILayout.BeginVertical(); + var count = 0; + var isHorizontal = false; + + for (var index = 0; index < texts.Length; index++) + { + var text = texts[index]; + + if (count == 0) + { + GUILayout.BeginHorizontal(); + isHorizontal = true; + } + + count++; + if (GUILayout.Toggle(bufferSelected == index, text, new GUIStyle(style), options)) + bufferSelected = index; + + if (count == xCount) + { + GUILayout.EndHorizontal(); + count = 0; + isHorizontal = false; + } + } + + if (isHorizontal) GUILayout.EndHorizontal(); + GUILayout.EndVertical(); + return bufferSelected; + } + + public static bool IsLeftButtonDown() + { + return IsMouseButton(EventType.MouseDown, MouseButtonLeft); + } + + public static bool IsRightButtonDown() + { + return IsMouseButton(EventType.MouseDown, MouseButtonRight); + } + + public static bool IsMiddleButtonDown() + { + return IsMouseButton(EventType.MouseDown, MouseButtonMiddle); + } + + public static bool IsLeftButtonUp() + { + return IsMouseButton(EventType.MouseUp, MouseButtonLeft); + } + + public static bool IsRightButtonUp() + { + return IsMouseButton(EventType.MouseUp, MouseButtonRight); + } + + public static bool IsMiddleButtonUp() + { + return IsMouseButton(EventType.MouseUp, MouseButtonMiddle); + } + + public static bool IsMouseButton(EventType eventType, int mouseButton) + { + var current = Event.current; + return current.type == eventType && current.button == mouseButton && current.isMouse; + } + + public static Rect GetClickRect(Rect position, GUIContent label) + { + if (label == null) + { + DebugUtility.LogException(nameof(label)); + return Rect.zero; + } + + var copy = position; + copy.size = GUIStyle.none.CalcSize(label); + return copy; + } + + public static bool IsClickedAt(Rect position) + { + var current = Event.current; + var contains = position.Contains(current.mousePosition); + if (contains && IsLeftButtonDown()) + { + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/Editor/Utility/VisualElementUtility.cs.meta b/Editor/Utility/ExtendedGUIUtility.cs.meta similarity index 100% rename from Editor/Utility/VisualElementUtility.cs.meta rename to Editor/Utility/ExtendedGUIUtility.cs.meta diff --git a/Editor/Utility/HideGroup.cs b/Editor/Utility/HideGroup.cs new file mode 100644 index 0000000..4f989ec --- /dev/null +++ b/Editor/Utility/HideGroup.cs @@ -0,0 +1,25 @@ +using UnityEditor; +using UnityEngine; + +namespace Better.Commons.EditorAddons.Utility +{ + public class HideGroup : EditorGUI.DisabledGroupScope + { + private readonly Color _color; + + public HideGroup(bool satisfied) : base(satisfied) + { + _color = GUI.color; + if (satisfied) + { + GUI.color = Color.clear; + } + } + + protected override void CloseScope() + { + base.CloseScope(); + GUI.color = _color; + } + } +} \ No newline at end of file diff --git a/Editor/Utility/HideGroup.cs.meta b/Editor/Utility/HideGroup.cs.meta new file mode 100644 index 0000000..1647169 --- /dev/null +++ b/Editor/Utility/HideGroup.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d1c8683282344a0aad1768ee65e5d96d +timeCreated: 1688635730 \ No newline at end of file diff --git a/Editor/Utility/StyleDefinition.cs b/Editor/Utility/StyleDefinition.cs deleted file mode 100644 index b21b30b..0000000 --- a/Editor/Utility/StyleDefinition.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Text.RegularExpressions; -using UnityEngine.UIElements; - -namespace Better.Commons.EditorAddons.Utility -{ - public static class StyleDefinition - { - public const string BetterPropertyClass = "better-property-field"; - public static readonly StyleLength SingleLineHeight = new StyleLength(new Length(18, LengthUnit.Pixel)); - public static readonly StyleLength IndentLevelPadding = new StyleLength(new Length(15, LengthUnit.Pixel)); - public const string PropertyFieldClass = "unity-property-field"; - - public static string AddSubState(string style, string state) - { - var kebabStyle = ConvertToKebabCase(style); - var kebabState = ConvertToKebabCase(state); - return $"{kebabStyle}__{kebabState}"; - } - - public static string ConvertToKebabCase(string input) - { - if (string.IsNullOrEmpty(input)) - return input; - - // Check if the string is already in kebab case - if (Regex.IsMatch(input, "^[a-z]+(-[a-z]+)*$")) - return input; - - // Insert hyphen before each uppercase letter (except the first one) - string kebabCase = Regex.Replace(input, "(? _spaceHeight; - - public const int MouseButtonLeft = 0; - public const int MouseButtonRight = 1; - public const int MouseButtonMiddle = 2; - - private static readonly HelpBox EmptyHelpBox = new HelpBox(); - - public const string NotSupportedTag = nameof(NotSupportedTag); - - public static string NotSupportedMessage(string fieldName, Type fieldType, Type attributeType) - { - return - $"Field {FormatBold(fieldName)} of type {FormatBold(fieldType.Name)} not supported for {FormatBold(attributeType.Name)}"; - } - - /// - /// Not supported Inspector HelpBox with RTF text - /// - /// - /// - /// - public static HelpBox NotSupportedBox(SerializedProperty property, Type fieldType, Type attributeType) - { - if (property == null) - { - DebugUtility.LogException(nameof(property)); - return EmptyHelpBox; - } - - if (fieldType == null) - { - DebugUtility.LogException(nameof(fieldType)); - return EmptyHelpBox; - } - - if (attributeType == null) - { - DebugUtility.LogException(nameof(attributeType)); - return EmptyHelpBox; - } - - var message = NotSupportedMessage(property.name, fieldType, attributeType); - return HelpBox(message, HelpBoxMessageType.Error); - } - - public static string FormatBold(string text) - { - return $"{text}"; - } - - public static string FormatItalic(string text) - { - return $"{text}"; - } - - public static string FormatBoldItalic(string text) - { - return $"{text}"; - } - - public static string BeautifyFormat(string text) - { - return $"\"{text}\""; - } - - /// - /// Override for default Inspector HelpBox with style - /// - /// - /// - public static HelpBox HelpBox(string message, HelpBoxMessageType type) - { - if (message == null) - { - DebugUtility.LogException(nameof(message)); - return EmptyHelpBox; - } - - return new HelpBox(message, type); - } - - /// - /// Override for default Inspector HelpBox with style - /// - /// - public static HelpBox HelpBox(string message) - { - if (message == null) - { - DebugUtility.LogException(nameof(message)); - return EmptyHelpBox; - } - - return HelpBox(message, HelpBoxMessageType.None); - } - - public static int SelectionGrid(int selected, string[] texts, int xCount, GUIStyle style, - params GUILayoutOption[] options) - { - var bufferSelected = selected; - GUILayout.BeginVertical(); - var count = 0; - var isHorizontal = false; - - for (var index = 0; index < texts.Length; index++) - { - var text = texts[index]; - - if (count == 0) - { - GUILayout.BeginHorizontal(); - isHorizontal = true; - } - - count++; - if (GUILayout.Toggle(bufferSelected == index, text, new GUIStyle(style), options)) - bufferSelected = index; - - if (count == xCount) - { - GUILayout.EndHorizontal(); - count = 0; - isHorizontal = false; - } - } - - if (isHorizontal) GUILayout.EndHorizontal(); - GUILayout.EndVertical(); - return bufferSelected; - } - - public static bool IsLeftButton(ClickEvent clickEvent) - { - return IsMouseButton(clickEvent, MouseButtonLeft); - } - - public static bool IsRightButton(ClickEvent clickEvent) - { - return IsMouseButton(clickEvent, MouseButtonRight); - } - - public static bool IsMiddleButton(ClickEvent clickEvent) - { - return IsMouseButton(clickEvent, MouseButtonMiddle); - } - - public static bool IsMouseButton(ClickEvent clickEvent, int mouseButton) - { - return clickEvent.button == mouseButton; - } - - public static VisualElement CreateHorizontalGroup() - { - var element = new VisualElement(); - element.style.flexDirection = new StyleEnum(FlexDirection.Row); - return element; - } - - public static VisualElement CreateVerticalGroup() - { - var element = new VisualElement(); - element.style.flexDirection = new StyleEnum(FlexDirection.Column); - return element; - } - - public static Image CreateLabelIcon(IconType iconType) - { - var icon = iconType.GetIcon(); - var image = new Image - { - image = icon - }; - - image.style.Height(StyleDefinition.SingleLineHeight).Width(StyleDefinition.SingleLineHeight).AlignSelf(new StyleEnum(Align.Center)); - - return image; - } - } -} \ No newline at end of file diff --git a/Runtime/Extensions/IEnumerableExtensions.cs b/Runtime/Extensions/EnumerableExtensions.cs similarity index 83% rename from Runtime/Extensions/IEnumerableExtensions.cs rename to Runtime/Extensions/EnumerableExtensions.cs index a67b0b6..21e6a50 100644 --- a/Runtime/Extensions/IEnumerableExtensions.cs +++ b/Runtime/Extensions/EnumerableExtensions.cs @@ -7,7 +7,7 @@ namespace Better.Commons.Runtime.Extensions { - public static class IEnumerableExtensions + public static class EnumerableExtensions { public static IEnumerable Shuffle(this IEnumerable self) { @@ -20,44 +20,6 @@ public static IEnumerable Shuffle(this IEnumerable self) return self.OrderBy(e => Guid.NewGuid()); } - public static T Find(this IEnumerable self) where T : TBase - { - if (!self.TryFind(out T item)) - { - DebugUtility.LogException(); - } - - return item; - } - - public static T FindOrDefault(this IEnumerable self) where T : TBase - { - self.TryFind(out T item); - return item; - } - - public static bool TryFind(this IEnumerable self, out T item) where T : TBase - { - if (self == null) - { - DebugUtility.LogException(nameof(self)); - item = default; - return false; - } - - foreach (var x in self) - { - if (x is T element) - { - item = element; - return true; - } - } - - item = default; - return false; - } - public static IEnumerable DistinctBy(this IEnumerable self, Func keySelector) { if (self == null) @@ -189,7 +151,7 @@ private static T GetRandomWithWeights(this IEnumerable> self) var totalWeight = valuesArray.Sum(v => v.Item2); if (totalWeight <= 0) { - var message = $"[${nameof(IEnumerableExtensions)}] {nameof(GetRandomWithWeights)}: Total weight is {totalWeight}, returned first item"; + var message = $"[${nameof(EnumerableExtensions)}] {nameof(GetRandomWithWeights)}: Total weight is {totalWeight}, returned first item"; Debug.LogWarning(message); return valuesArray[0].Item1; } diff --git a/Runtime/Extensions/IEnumerableExtensions.cs.meta b/Runtime/Extensions/EnumerableExtensions.cs.meta similarity index 100% rename from Runtime/Extensions/IEnumerableExtensions.cs.meta rename to Runtime/Extensions/EnumerableExtensions.cs.meta diff --git a/Runtime/Extensions/StyleExtensions.cs b/Runtime/Extensions/StyleExtensions.cs deleted file mode 100644 index 77dfc20..0000000 --- a/Runtime/Extensions/StyleExtensions.cs +++ /dev/null @@ -1,477 +0,0 @@ -using UnityEngine; -using UnityEngine.UIElements; - -namespace Better.Commons.Runtime.Extensions -{ - public static class StyleExtensions - { - public static IStyle SetVisible(this IStyle self, bool visible) - { - var visibility = visible ? UnityEngine.UIElements.Visibility.Visible : UnityEngine.UIElements.Visibility.Hidden; - var displayStyle = visible ? StyleKeyword.Auto : StyleKeyword.None; - return self.Visibility(visibility).Display(displayStyle); - } - - public static IStyle AlignContent(this IStyle self, StyleEnum alignContent) - { - self.alignContent = alignContent; - return self; - } - - public static IStyle AlignItems(this IStyle self, StyleEnum alignItems) - { - self.alignItems = alignItems; - return self; - } - - public static IStyle AlignSelf(this IStyle self, StyleEnum alignSelf) - { - self.alignSelf = alignSelf; - return self; - } - - public static IStyle BackgroundColor(this IStyle self, StyleColor backgroundColor) - { - self.backgroundColor = backgroundColor; - return self; - } - - public static IStyle BackgroundImage(this IStyle self, StyleBackground backgroundImage) - { - self.backgroundImage = backgroundImage; - return self; - } - - public static IStyle BorderBottomColor(this IStyle self, StyleColor borderBottomColor) - { - self.borderBottomColor = borderBottomColor; - return self; - } - - public static IStyle BorderBottomLeftRadius(this IStyle self, StyleLength borderBottomLeftRadius) - { - self.borderBottomLeftRadius = borderBottomLeftRadius; - return self; - } - - public static IStyle BorderBottomRightRadius(this IStyle self, StyleLength borderBottomRightRadius) - { - self.borderBottomRightRadius = borderBottomRightRadius; - return self; - } - - public static IStyle BorderBottomWidth(this IStyle self, StyleFloat borderBottomWidth) - { - self.borderBottomWidth = borderBottomWidth; - return self; - } - - public static IStyle BorderLeftColor(this IStyle self, StyleColor borderLeftColor) - { - self.borderLeftColor = borderLeftColor; - return self; - } - - public static IStyle BorderLeftWidth(this IStyle self, StyleFloat borderLeftWidth) - { - self.borderLeftWidth = borderLeftWidth; - return self; - } - - public static IStyle BorderRightColor(this IStyle self, StyleColor borderRightColor) - { - self.borderRightColor = borderRightColor; - return self; - } - - public static IStyle BorderRightWidth(this IStyle self, StyleFloat borderRightWidth) - { - self.borderRightWidth = borderRightWidth; - return self; - } - - public static IStyle BorderTopColor(this IStyle self, StyleColor borderTopColor) - { - self.borderTopColor = borderTopColor; - return self; - } - - public static IStyle BorderTopLeftRadius(this IStyle self, StyleLength borderTopLeftRadius) - { - self.borderTopLeftRadius = borderTopLeftRadius; - return self; - } - - public static IStyle BorderTopRightRadius(this IStyle self, StyleLength borderTopRightRadius) - { - self.borderTopRightRadius = borderTopRightRadius; - return self; - } - - public static IStyle BorderTopWidth(this IStyle self, StyleFloat borderTopWidth) - { - self.borderTopWidth = borderTopWidth; - return self; - } - - public static IStyle Bottom(this IStyle self, StyleLength bottom) - { - self.bottom = bottom; - return self; - } - - public static IStyle Color(this IStyle self, StyleColor color) - { - self.color = color; - return self; - } - - public static IStyle Cursor(this IStyle self, StyleCursor cursor) - { - self.cursor = cursor; - return self; - } - - public static IStyle Display(this IStyle self, StyleEnum display) - { - self.display = display; - return self; - } - - public static IStyle FlexBasis(this IStyle self, StyleLength flexBasis) - { - self.flexBasis = flexBasis; - return self; - } - - public static IStyle FlexDirection(this IStyle self, StyleEnum flexDirection) - { - self.flexDirection = flexDirection; - return self; - } - - public static IStyle FlexGrow(this IStyle self, StyleFloat flexGrow) - { - self.flexGrow = flexGrow; - return self; - } - - public static IStyle FlexShrink(this IStyle self, StyleFloat flexShrink) - { - self.flexShrink = flexShrink; - return self; - } - - public static IStyle FlexWrap(this IStyle self, StyleEnum flexWrap) - { - self.flexWrap = flexWrap; - return self; - } - - public static IStyle FontSize(this IStyle self, StyleLength fontSize) - { - self.fontSize = fontSize; - return self; - } - - public static IStyle Height(this IStyle self, StyleLength height) - { - self.height = height; - return self; - } - - public static IStyle Width(this IStyle self, StyleLength height) - { - self.width = height; - return self; - } - - public static IStyle JustifyContent(this IStyle self, StyleEnum justifyContent) - { - self.justifyContent = justifyContent; - return self; - } - - public static IStyle Left(this IStyle self, StyleLength left) - { - self.left = left; - return self; - } - - public static IStyle LetterSpacing(this IStyle self, StyleLength letterSpacing) - { - self.letterSpacing = letterSpacing; - return self; - } - - public static IStyle MarginBottom(this IStyle self, StyleLength marginBottom) - { - self.marginBottom = marginBottom; - return self; - } - - public static IStyle MarginLeft(this IStyle self, StyleLength marginLeft) - { - self.marginLeft = marginLeft; - return self; - } - - public static IStyle MarginRight(this IStyle self, StyleLength marginRight) - { - self.marginRight = marginRight; - return self; - } - - public static IStyle MarginTop(this IStyle self, StyleLength marginTop) - { - self.marginTop = marginTop; - return self; - } - - public static IStyle MaxHeight(this IStyle self, StyleLength maxHeight) - { - self.maxHeight = maxHeight; - return self; - } - - public static IStyle MaxWidth(this IStyle self, StyleLength maxWidth) - { - self.maxWidth = maxWidth; - return self; - } - - public static IStyle MinHeight(this IStyle self, StyleLength minHeight) - { - self.minHeight = minHeight; - return self; - } - - public static IStyle MinWidth(this IStyle self, StyleLength minWidth) - { - self.minWidth = minWidth; - return self; - } - - public static IStyle Opacity(this IStyle self, StyleFloat opacity) - { - self.opacity = opacity; - return self; - } - - public static IStyle Overflow(this IStyle self, StyleEnum overflow) - { - self.overflow = overflow; - return self; - } - - public static IStyle PaddingBottom(this IStyle self, StyleLength paddingBottom) - { - self.paddingBottom = paddingBottom; - return self; - } - - public static IStyle PaddingLeft(this IStyle self, StyleLength paddingLeft) - { - self.paddingLeft = paddingLeft; - return self; - } - - public static IStyle PaddingRight(this IStyle self, StyleLength paddingRight) - { - self.paddingRight = paddingRight; - return self; - } - - public static IStyle PaddingTop(this IStyle self, StyleLength paddingTop) - { - self.paddingTop = paddingTop; - return self; - } - - public static IStyle Position(this IStyle self, StyleEnum position) - { - self.position = position; - return self; - } - - public static IStyle Right(this IStyle self, StyleLength right) - { - self.right = right; - return self; - } - - public static IStyle Rotate(this IStyle self, StyleRotate rotate) - { - self.rotate = rotate; - return self; - } - - public static IStyle Scale(this IStyle self, StyleScale scale) - { - self.scale = scale; - return self; - } - - public static IStyle TextOverflow(this IStyle self, StyleEnum textOverflow) - { - self.textOverflow = textOverflow; - return self; - } - - public static IStyle TextShadow(this IStyle self, StyleTextShadow textShadow) - { - self.textShadow = textShadow; - return self; - } - - public static IStyle Top(this IStyle self, StyleLength top) - { - self.top = top; - return self; - } - - public static IStyle TransformOrigin(this IStyle self, StyleTransformOrigin transformOrigin) - { - self.transformOrigin = transformOrigin; - return self; - } - - public static IStyle TransitionDelay(this IStyle self, StyleList transitionDelay) - { - self.transitionDelay = transitionDelay; - return self; - } - - public static IStyle TransitionDuration(this IStyle self, StyleList transitionDuration) - { - self.transitionDuration = transitionDuration; - return self; - } - - public static IStyle TransitionProperty(this IStyle self, StyleList transitionProperty) - { - self.transitionProperty = transitionProperty; - return self; - } - - public static IStyle TransitionTimingFunction(this IStyle self, StyleList transitionTimingFunction) - { - self.transitionTimingFunction = transitionTimingFunction; - return self; - } - - public static IStyle Translate(this IStyle self, StyleTranslate translate) - { - self.translate = translate; - return self; - } - - public static IStyle UnityBackgroundImageTintColor(this IStyle self, StyleColor unityBackgroundImageTintColor) - { - self.unityBackgroundImageTintColor = unityBackgroundImageTintColor; - return self; - } - - public static IStyle UnityBackgroundScaleMode(this IStyle self, StyleEnum unityBackgroundScaleMode) - { - self.unityBackgroundScaleMode = unityBackgroundScaleMode; - return self; - } - - public static IStyle UnityFont(this IStyle self, StyleFont unityFont) - { - self.unityFont = unityFont; - return self; - } - - public static IStyle UnityFontDefinition(this IStyle self, StyleFontDefinition unityFontDefinition) - { - self.unityFontDefinition = unityFontDefinition; - return self; - } - - public static IStyle UnityFontStyleAndWeight(this IStyle self, StyleEnum unityFontStyleAndWeight) - { - self.unityFontStyleAndWeight = unityFontStyleAndWeight; - return self; - } - - public static IStyle UnityOverflowClipBox(this IStyle self, StyleEnum unityOverflowClipBox) - { - self.unityOverflowClipBox = unityOverflowClipBox; - return self; - } - - public static IStyle UnityParagraphSpacing(this IStyle self, StyleLength unityParagraphSpacing) - { - self.unityParagraphSpacing = unityParagraphSpacing; - return self; - } - - public static IStyle UnitySliceBottom(this IStyle self, StyleInt unitySliceBottom) - { - self.unitySliceBottom = unitySliceBottom; - return self; - } - - public static IStyle UnitySliceLeft(this IStyle self, StyleInt unitySliceLeft) - { - self.unitySliceLeft = unitySliceLeft; - return self; - } - - public static IStyle UnitySliceRight(this IStyle self, StyleInt unitySliceRight) - { - self.unitySliceRight = unitySliceRight; - return self; - } - - public static IStyle UnitySliceTop(this IStyle self, StyleInt unitySliceTop) - { - self.unitySliceTop = unitySliceTop; - return self; - } - - public static IStyle UnityTextAlign(this IStyle self, StyleEnum unityTextAlign) - { - self.unityTextAlign = unityTextAlign; - return self; - } - - public static IStyle UnityTextOutlineColor(this IStyle self, StyleColor unityTextOutlineColor) - { - self.unityTextOutlineColor = unityTextOutlineColor; - return self; - } - - public static IStyle UnityTextOutlineWidth(this IStyle self, StyleFloat unityTextOutlineWidth) - { - self.unityTextOutlineWidth = unityTextOutlineWidth; - return self; - } - - public static IStyle UnityTextOverflowPosition(this IStyle self, StyleEnum unityTextOverflowPosition) - { - self.unityTextOverflowPosition = unityTextOverflowPosition; - return self; - } - - public static IStyle Visibility(this IStyle self, StyleEnum visibility) - { - self.visibility = visibility; - return self; - } - - public static IStyle WhiteSpace(this IStyle self, StyleEnum whiteSpace) - { - self.whiteSpace = whiteSpace; - return self; - } - - public static IStyle WordSpacing(this IStyle self, StyleLength wordSpacing) - { - self.wordSpacing = wordSpacing; - return self; - } - } -} \ No newline at end of file diff --git a/Runtime/Extensions/StyleExtensions.cs.meta b/Runtime/Extensions/StyleExtensions.cs.meta deleted file mode 100644 index 30eca1f..0000000 --- a/Runtime/Extensions/StyleExtensions.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: de2c29a04d4f4437a7c30def672e3089 -timeCreated: 1715114336 \ No newline at end of file diff --git a/Runtime/Utility/EnumUtility.cs b/Runtime/Utility/EnumUtility.cs index 5cbc8cf..675a319 100644 --- a/Runtime/Utility/EnumUtility.cs +++ b/Runtime/Utility/EnumUtility.cs @@ -27,7 +27,7 @@ public static IEnumerable GetAllValues(Type enumType) var values = Enum.GetValues(enumType); return values.ToEnumerable(); } - + public static IEnumerable GetAllValues() where TEnum : Enum { @@ -75,17 +75,12 @@ public static Enum Add(Enum a, Enum b) { if (a == null) { - throw new ArgumentNullException(nameof(a)); + DebugUtility.LogException(nameof(a)); } if (b == null) { - throw new ArgumentNullException(nameof(b)); - } - - if (a.GetType() != b.GetType()) - { - throw new Exception($"Type of {a.ToString()} and {b.ToString()} is different"); + DebugUtility.LogException(nameof(b)); } return (Enum)Enum.ToObject(a.GetType(), a.ToFlagInt() | b.ToFlagInt()); @@ -95,35 +90,15 @@ public static Enum Remove(Enum a, Enum b) { if (a == null) { - throw new ArgumentNullException(nameof(a)); + DebugUtility.LogException(nameof(a)); } if (b == null) { - throw new ArgumentNullException(nameof(b)); - } - - if (a.GetType() != b.GetType()) - { - throw new Exception($"Type of {a.ToString()} and {b.ToString()} is different"); + DebugUtility.LogException(nameof(b)); } return (Enum)Enum.ToObject(a.GetType(), a.ToFlagInt() & ~b.ToFlagInt()); } - - public static Enum ToEnum(Type enumType, int value) - { - return (Enum)Enum.ToObject(enumType, value); - } - - public static bool HasValue(Enum currentValue, Enum value, bool isFlag) - { - if (isFlag) - { - return currentValue.HasFlag(value); - } - - return Equals(currentValue, value); - } } } \ No newline at end of file diff --git a/package.json b/package.json index e45892c..875eae2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "com.tdw.better.commons", "displayName": "Better Commons", - "version": "0.0.8", + "version": "0.0.9", "unity": "2021.3", "description": " ", "dependencies": {