Ejemplo n.º 1
0
 public void CanBeConstructedFromGenericMethod_WithNonConstructableType_ReturnsFalse()
 {
     Assert.That(TypeConstruction.CanBeConstructed <IConstructInterface>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <AbstractConstructibleBaseType>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <NonConstructibleDerivedType>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False);
 }
        internal static void ValidateBuildArtifactTypeAndThrow(Type buildArtifactType)
        {
            if (buildArtifactType == null)
            {
                throw new ArgumentNullException(nameof(buildArtifactType));
            }

            if (buildArtifactType == typeof(object))
            {
                throw new InvalidOperationException("Build artifact type cannot be object.");
            }

            if (!buildArtifactType.IsClass)
            {
                throw new InvalidOperationException($"Build artifact type {buildArtifactType.FullName} is not a class.");
            }

            if (!typeof(IBuildArtifact).IsAssignableFrom(buildArtifactType))
            {
                throw new InvalidOperationException($"Build artifact type {buildArtifactType.FullName} does not derive from {typeof(IBuildArtifact).FullName}.");
            }

            if (!TypeConstruction.CanBeConstructed(buildArtifactType))
            {
                throw new InvalidOperationException($"Build artifact type {buildArtifactType.FullName} cannot be constructed because it does not have a default, implicit or registered constructor.");
            }
        }
Ejemplo n.º 3
0
 public void CanBeConstructedFromGenericMethod_WithConstructableType_ReturnsTrue()
 {
     Assert.That(TypeConstruction.CanBeConstructed <ConstructibleBaseType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <ConstructibleDerivedType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <NoConstructorType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <ParameterLessConstructorType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <ScriptableObjectType>(), Is.True);
 }
Ejemplo n.º 4
0
        public VisitStatus Visit <TContainer, TValue>(Property <TContainer, TValue> property, ref TContainer container,
                                                      ref TValue value)
        {
            if (!RuntimeTypeInfoCache <TValue> .CanBeNull || null != value)
            {
                return(VisitStatus.Unhandled);
            }

            if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(TValue)))
            {
                return(VisitStatus.Unhandled);
            }

            if (!property.IsReadOnly && property.HasAttribute <CreateInstanceOnInspectionAttribute>() && !(property is ICollectionElementProperty))
            {
                var attribute = property.GetAttribute <CreateInstanceOnInspectionAttribute>();
                if (null == attribute.Type)
                {
                    if (TypeConstruction.CanBeConstructed <TValue>())
                    {
                        value = TypeConstruction.Construct <TValue>();
                        property.SetValue(ref container, value);
                        return(VisitStatus.Unhandled);
                    }

                    Debug.LogWarning(PropertyChecks.GetNotConstructableWarningMessage(typeof(TValue)));
                }
                else
                {
                    var isAssignable    = typeof(TValue).IsAssignableFrom(attribute.Type);
                    var isConstructable = TypeConstruction.GetAllConstructableTypes(typeof(TValue))
                                          .Contains(attribute.Type);
                    if (isAssignable && isConstructable)
                    {
                        value = TypeConstruction.Construct <TValue>(attribute.Type);
                        property.SetValue(ref container, value);
                        return(VisitStatus.Unhandled);
                    }

                    Debug.LogWarning(isAssignable
                        ? PropertyChecks.GetNotConstructableWarningMessage(attribute.Type)
                        : PropertyChecks.GetNotAssignableWarningMessage(attribute.Type, typeof(TValue)));
                }
            }

            Visitor.AddToPath(property);
            try
            {
                var path    = Visitor.GetCurrentPath();
                var element = new NullElement <TValue>(VisitorContext.Root, property, path);
                VisitorContext.Parent.contentContainer.Add(element);
            }
            finally
            {
                Visitor.RemoveFromPath(property);
            }
            return(VisitStatus.Stop);
        }
Ejemplo n.º 5
0
        internal static SearcherDatabase Populate <T>(Func <Type, bool> filter = null, Func <Type, string> nameResolver = null, Func <Type, string> categoryResolver = null)
        {
            var list = new List <SearcherItem>();
            var dict = new Dictionary <string, SearcherItem>();

            var types = TypeCache.GetTypesDerivedFrom <T>();

            foreach (var type in types)
            {
                if (type.IsGenericType || type.IsAbstract || type.ContainsGenericParameters || type.IsInterface)
                {
                    continue;
                }

                if (!TypeConstruction.CanBeConstructed(type))
                {
                    continue;
                }

                if (filter != null && !filter(type))
                {
                    continue;
                }

                try
                {
                    var typeItem = new TypeSearcherItem(type, nameResolver != null ? nameResolver(type) : string.Empty);
                    var category = categoryResolver != null?categoryResolver(type) : type.Namespace ?? "Global";

                    if (!string.IsNullOrEmpty(category))
                    {
                        if (!dict.TryGetValue(category, out var item))
                        {
                            dict[category] = item = new SearcherItem(category);
                            list.Add(item);
                        }
                        item.AddChild(typeItem);
                    }
                    else
                    {
                        list.Add(typeItem);
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            foreach (var kvp in dict)
            {
                kvp.Value.Children.Sort(CompareByName);
            }

            list.Sort(CompareByName);

            return(new SearcherDatabase(list));
        }
Ejemplo n.º 6
0
        internal static TComponent Construct(Type componentType)
        {
            if (!TypeConstruction.CanBeConstructed(componentType))
            {
                throw new InvalidOperationException($"Component type {componentType.FullName} cannot be constructed because it does not have a default, implicit or registered constructor.");
            }

            return(TypeConstruction.Construct <TComponent>(componentType));
        }
Ejemplo n.º 7
0
 public void CanBeConstructedTests()
 {
     Assert.That(TypeConstruction.CanBeConstructed <IConstructInterface>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <AbstractConstructibleBaseType>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <ConstructibleBaseType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <ConstructibleDerivedType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <NonConstructibleDerivedType>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <NoConstructorType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <ParameterLessConstructorType>(), Is.True);
     Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False);
     Assert.That(TypeConstruction.CanBeConstructed <ScriptableObjectType>(), Is.True);
 }
Ejemplo n.º 8
0
        public void CanSetExplicitConstruction()
        {
            Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False);
            TypeConstruction.SetExplicitConstructionMethod(ExplicitConstruction);
            Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.True);
            {
                var instance = TypeConstruction.Construct <ParameterConstructorType>();
                Assert.That(instance, Is.Not.Null);
                Assert.That(instance.Value, Is.EqualTo(10.0f));
            }

            TypeConstruction.UnsetExplicitConstructionMethod(ExplicitConstruction);
            Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False);
        }
Ejemplo n.º 9
0
        public void SettingAndUnSettingAnExplicitConstructionMethod_ToCreateAnInstance_BehavesProperly()
        {
            Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False);
            Assert.That(TypeConstruction.CanBeConstructed(typeof(ParameterConstructorType)), Is.False);
            TypeConstruction.SetExplicitConstructionMethod(ExplicitConstruction);
            Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.True);
            Assert.That(TypeConstruction.CanBeConstructed(typeof(ParameterConstructorType)), Is.True);
            {
                var instance = TypeConstruction.Construct <ParameterConstructorType>();
                Assert.That(instance, Is.Not.Null);
                Assert.That(instance.Value, Is.EqualTo(10.0f));
            }

            TypeConstruction.UnsetExplicitConstructionMethod(ExplicitConstruction);
            Assert.That(TypeConstruction.CanBeConstructed <ParameterConstructorType>(), Is.False);
            Assert.That(TypeConstruction.CanBeConstructed(typeof(ParameterConstructorType)), Is.False);
        }
Ejemplo n.º 10
0
        static bool ShouldStayNull <TContainer, TValue>(
            Property <TContainer, TValue> property,
            ref TContainer container,
            ref TValue value)
        {
            if (property.IsReadOnly || !property.HasAttribute <CreateInstanceOnInspectionAttribute>() ||
                property is ICollectionElementProperty)
            {
                return(true);
            }

            var attribute = property.GetAttribute <CreateInstanceOnInspectionAttribute>();

            if (null == attribute.Type)
            {
                if (TypeConstruction.CanBeConstructed <TValue>())
                {
                    value = TypeConstruction.Construct <TValue>();
                    property.SetValue(ref container, value);
                    return(false);
                }

                Debug.LogWarning(PropertyChecks.GetNotConstructableWarningMessage(typeof(TValue)));
            }
            else
            {
                var isAssignable    = typeof(TValue).IsAssignableFrom(attribute.Type);
                var isConstructable = TypeUtility.GetAllConstructableTypes(typeof(TValue))
                                      .Contains(attribute.Type);
                if (isAssignable && isConstructable)
                {
                    value = TypeConstruction.Construct <TValue>(attribute.Type);
                    property.SetValue(ref container, value);
                    return(false);
                }

                Debug.LogWarning(isAssignable
                    ? PropertyChecks.GetNotConstructableWarningMessage(attribute.Type)
                    : PropertyChecks.GetNotAssignableWarningMessage(attribute.Type, typeof(TValue)));
            }

            return(true);
        }
Ejemplo n.º 11
0
 public void CanBeConstructedFromType_WithNonConstructableType_ReturnsFalse(Type type)
 {
     Assert.That(TypeConstruction.CanBeConstructed(type), Is.False);
 }
Ejemplo n.º 12
0
 public void CanBeConstructedFromType_WithConstructableType_ReturnsTrue(Type type)
 {
     Assert.That(TypeConstruction.CanBeConstructed(type), Is.True);
 }
Ejemplo n.º 13
0
        public override VisualElement Build()
        {
            var root = Resources.TypeInspector.Clone();

            var label = root.Q <Label>("label");

            label.text = DisplayName;

            var input = root.Q <VisualElement>("input");

            input.RegisterCallback <MouseDownEvent>(e =>
            {
                var items = new List <SearchView.Item>();
                var types = TypeCache.GetTypesDerivedFrom <T>();
                foreach (var type in types)
                {
                    if (type.IsAbstract || type.IsInterface ||
                        type.HasAttribute <HideInInspector>() ||
                        type.HasAttribute <ObsoleteAttribute>())
                    {
                        continue;
                    }

                    if (!TypeConstruction.CanBeConstructed(type))
                    {
                        continue;
                    }

                    if (TypeFilter != null && !TypeFilter(type))
                    {
                        continue;
                    }

                    var name     = GetName(type);
                    var category = GetCategory(type);
                    items.Add(new SearchView.Item
                    {
                        Path = !string.IsNullOrEmpty(category) ? $"{category}/{name}" : name,
                        Icon = GetIcon(type),
                        Data = type
                    });
                }
                items = items.OrderBy(item => item.Path).ToList();

                SearchWindow searchWindow = SearchWindow.Create();
                searchWindow.Title        = Title;
                searchWindow.Items        = items;
                searchWindow.OnSelection += item =>
                {
                    var type = (Type)item.Data;
                    if (TypeConstruction.TryConstruct <T>(type, out var instance))
                    {
                        Target             = instance;
                        m_TextElement.text = GetName(type);
                    }
                };

                var rect              = EditorWindow.focusedWindow.position;
                var button            = input.worldBound;
                searchWindow.position = new Rect(rect.x + button.x, rect.y + button.y + button.height, 230, 315);
                searchWindow.ShowPopup();

                e.StopPropagation();
            });

            m_TextElement      = input.Q <TextElement>("text");
            m_TextElement.text = GetName(Target?.GetType());

            return(root);
        }
        public PropertyBagDebugInfo(Type type, IPropertyBag propertyBag)
        {
            Type          = type;
            Namespace     = type.Namespace;
            Assembly      = type.Assembly.GetName().Name;
            Name          = TypeUtility.GetTypeDisplayName(type);
            FullName      = $"{Namespace}.{Name}";
            m_PropertyBag = propertyBag;

            var bagType = m_PropertyBag.GetType();

            if (null != bagType.GetCustomAttribute <System.Runtime.CompilerServices.CompilerGeneratedAttribute>())
            {
                PropertyBagType = PropertyBagType.CodeGen;
            }
            else if (null != bagType.GetCustomAttribute <ReflectedPropertyBagAttribute>())
            {
                PropertyBagType = PropertyBagType.Reflection;
            }
            else
            {
                PropertyBagType = PropertyBagType.Manual;
            }

            TypeTraits = type.IsValueType
                ? TypeTraits.Struct
                : TypeTraits.Class;
            if (UnsafeUtility.IsUnmanaged(type))
            {
                TypeTraits |= TypeTraits.Unmanaged;
            }
            if (UnsafeUtility.IsBlittable(type))
            {
                TypeTraits |= TypeTraits.Blittable;
            }

            if (type.IsGenericType)
            {
                TypeTraits |= TypeTraits.Generic;
            }

            TypeInfo      = CacheTypeInfo();
            Properties    = CacheProperties();
            PropertyNames = new List <string>();
            PropertyTypes = new List <string>();
            foreach (var property in Properties)
            {
                if (!(property is PropertyTypeDescriptor typed))
                {
                    continue;
                }
                PropertyNames.Add(typed.Descriptor.Name);
                PropertyTypes.Add(TypeUtility.GetTypeDisplayName(typed.Value));
            }
            Serialization    = CacheSerializationInfo();
            UI               = CacheInspectorInfo();
            CanBeConstructed = TypeConstruction.CanBeConstructed(type);

            if (Properties.Count > 0)
            {
                Extensions |= ExtensionType.Properties;
            }

            if (Serialization.Count > 0)
            {
                Extensions |= ExtensionType.Serialization;
            }

            if (UI.Count > 0)
            {
                Extensions |= ExtensionType.UI;
            }
        }