Beispiel #1
0
 public override bool IsAssignableFrom(PLanguageType otherType)
 {
     // Copying semantics: both the other key and value types must be subtypes of this key/value type.
     return(otherType.Canonicalize() is MapType other &&
            KeyType.IsAssignableFrom(other.KeyType) &&
            ValueType.IsAssignableFrom(other.ValueType));
 }
Beispiel #2
0
        /// <summary>Set the value explicitly (i.e. not ignored if equal to the current value)</summary>
        public void SetValue(object value, bool notify = true)
        {
            // Adopt the type from the value if 'ValueType' is currently 'object'
            if (ValueType == typeof(object) && value != null)
            {
                ValueType = value.GetType();
            }

            // Null is equivalent to the default type for structs
            if (!ValueType.IsClass && value == null)
            {
                value = ValueType.DefaultInstance();
            }

            // Check the assigned value has the correct type
            if (value != null && !ValueType.IsAssignableFrom(value.GetType()))
            {
                throw new ArgumentException($"Cannot assign to 'Value', argument has the wrong type. Expected: {ValueType.Name}  Received: {value.GetType().Name} with value '{value}'");
            }

            // Save the assigned value
            m_value = value;


            // Set 'Text' to match the value
            ValueToTextIfNotFocused(value);

            // Notify value changed
            if (notify)
            {
                OnValueChanged(new ValueEventArgs(Value));
            }

            Trace($"SetValue to '{value}'");
        }
Beispiel #3
0
        public void Definition(INode node, IValuePortAttribute info)
        {
            Id        = new PortId(node.NodeId, info.Name);
            Node      = node;
            Name      = info.Name;
            Direction = info.Direction;
            Capacity  = info.Capacity;
            GraphPort = info.GraphPort;
            ValueType = typeof(T);
            if (info.CallbackInfo == null)
            {
                return;
            }
            var parameters = info.CallbackInfo.GetParameters();

            if (parameters.Length > 0)
            {
                Debug.LogWarning($"ValuePort Callback for '{node}.{info.CallbackInfo.Name}' has {parameters.Length} parameter(s).  Callback cannot accept any parameters");
                return;
            }
            if (VoidType.IsAssignableFrom(info.CallbackInfo.ReturnType))
            {
                _simpleCallback = (Action)info.CallbackInfo.CreateDelegate(SimpleCallbackType, node);
                _callbackType   = CallbackTypes.Simple;
            }
            if (ValueType.IsAssignableFrom(info.CallbackInfo.ReturnType))
            {
                _valueCallback = (Func <T>)info.CallbackInfo.CreateDelegate(ValueCallbackType, node);
                _callbackType  = CallbackTypes.Value;
            }
            if (_callbackType == CallbackTypes.None)
            {
                Debug.LogWarning($"ValuePort Callback for '{node}.{info.CallbackInfo.Name}' did not have one of the following method signatures [Action, Func<T>]");
            }
        }
Beispiel #4
0
 public void Add(object value)
 {
     if (!ValueType.IsAssignableFrom(value.GetType()))
     {
         value = TypeDescriptor.GetConverter(ValueType).ConvertFrom(value);
     }
     Dictionary.Add(value);
 }
        /// <summary>
        /// Returns true if the value is valid for this type of editor without any conversion.
        /// </summary>
        /// <param name="p_Value"></param>
        /// <returns></returns>
        public bool IsValidValue(object p_Value)
        {
            try
            {
                if (IsInStandardValues(p_Value))
                {
                    return(true);
                }

                if (p_Value == null)
                {
                    if (AllowNull)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }

                if (m_bStandardValuesExclusive)
                {
                    return(false);
                }

                if (m_MaximumValue != null)
                {
                    IComparable l_Max = (IComparable)m_MaximumValue;
                    if (l_Max.CompareTo(p_Value) < 0)
                    {
                        return(false);
                    }
                }

                if (m_MinimumValue != null)
                {
                    IComparable l_Min = (IComparable)m_MinimumValue;
                    if (l_Min.CompareTo(p_Value) > 0)
                    {
                        return(false);
                    }
                }

                if (ValueType != null)
                {
                    return(ValueType.IsAssignableFrom(p_Value.GetType()));
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Set the member on an object
        /// </summary>
        /// <param name="obj">The parameterized object</param>
        /// <param name="value">The parameter value</param>
        /// <param name="ckt">The circuit if applicable</param>
        public void Set(Parameterized obj, object value = null, Circuit ckt = null)
        {
            if (!Access.HasFlag(AccessFlags.Set))
            {
                throw new CircuitException($"Cannot set parameter");
            }
            if (ValueType == typeof(void) && value != null)
            {
                throw new ParameterTypeException(obj, typeof(void));
            }
            else if (value != null && !ValueType.IsAssignableFrom(value.GetType()))
            {
                throw new ParameterTypeException(obj, ValueType);
            }

            switch (MemberType)
            {
            case MemberTypes.Property:
                PropertyInfo pi = Info as PropertyInfo;
                if (IsParameter)
                {
                    ((IParameter)pi.GetValue(obj)).Set(value);
                }
                else
                {
                    pi.SetValue(obj, value);
                }
                break;

            case MemberTypes.Field:
                FieldInfo fi = Info as FieldInfo;
                if (IsParameter)
                {
                    ((IParameter)fi.GetValue(obj)).Set(value);
                }
                else
                {
                    fi.SetValue(obj, value);
                }
                break;

            case MemberTypes.Method:
                MethodInfo mi = Info as MethodInfo;
                switch (Parameters)
                {
                case 0: mi.Invoke(obj, null); break;

                case 1: mi.Invoke(obj, new object[] { value }); break;

                case 2: mi.Invoke(obj, new object[] { ckt, value }); break;
                }
                break;

            default:
                throw new CircuitException($"Invalid type for {Info.Name}");
            }
        }
Beispiel #7
0
        DataType FindDerivedType(string name, object mapData, out bool isFallbackType)
        {
            isFallbackType = false;
            if (subtypes != null)
            {
                foreach (ClassDataType stype in new List <ClassDataType> (subtypes))
                {
                    if (stype.Name == name)
                    {
                        return(stype);
                    }

                    bool     fb;
                    DataType cst = stype.FindDerivedType(name, null, out fb);
                    if (cst != null && !fb)
                    {
                        isFallbackType = false;
                        return(cst);
                    }
                }
            }

            // Try a direct type name query
            DataType dt = Context.GetConfigurationDataType(name);

            if (dt != null && ValueType.IsAssignableFrom(dt.ValueType))
            {
                return(dt);
            }

            // The type could not be found. Use the fallback type if available.

            // Properties can specify a specific fallback type. It is provided in the custom map data.
            if (mapData != null)
            {
                isFallbackType = true;
                return(Context.GetConfigurationDataType((Type)mapData));
            }

            // A type can have a default fallback type.
            if (fallbackType != null)
            {
                isFallbackType = true;
                return(Context.GetConfigurationDataType(fallbackType));
            }
            else
            {
                return(null);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Throws an exception if the value is incompatible with this option.
        /// </summary>
        /// <param name="value">The value to check.</param>
        public void CheckValue(object value)
        {
            if (value is null)
            {
                throw Exceptions.ArgumentNull(nameof(value));
            }

            if (!ValueType.IsAssignableFrom(value.GetType()))
            {
                throw Exceptions.Argument(nameof(value), "Value is incompatible with type {0}.", ValueType);
            }

            OnCheckValue(value);
        }
Beispiel #9
0
        protected override Func <object, int, int, T> BuildGetter()
        {
            EnsureInitialized();
            var p_obj = Expression.Parameter(typeof(object));
            var p_i1  = Expression.Parameter(typeof(int));
            var p_i2  = Expression.Parameter(typeof(int));

            Expression access = Expression.MakeMemberAccess(Expression.Convert(p_obj, ObjectType), MemberInfo);

            return(Expression.Lambda <Func <object, int, int, T> >(
                       ValueType.IsAssignableFrom(MemberType) ?
                       access : Expression.Convert(access, ValueType),
                       p_obj, p_i1, p_i2
                       ).Compile());
        }
Beispiel #10
0
        protected override Func <object, int, int, T> BuildGetter()
        {
            var p_obj       = Expression.Parameter(typeof(object));
            var p_i1        = Expression.Parameter(typeof(int));
            var p_i2        = Expression.Parameter(typeof(int));
            var elementType = MemberType.GetElementType();

            Expression arrayAccess = BuildArrayAccess(p_obj, p_i2);

            return(Expression.Lambda <Func <object, int, int, T> >(
                       ValueType.IsAssignableFrom(elementType) ?
                       arrayAccess : Expression.Convert(arrayAccess, ValueType),
                       p_obj, p_i1, p_i2
                       ).Compile());
        }
Beispiel #11
0
        protected override Func <object, int, int, T> BuildGetter()
        {
            var p_obj   = Expression.Parameter(typeof(object));
            var p_i1    = Expression.Parameter(typeof(int));
            var p_i2    = Expression.Parameter(typeof(int));
            var valType = GetValueType();

            Expression access = Expression.MakeMemberAccess(Expression.Convert(p_obj, ObjectType), MemberInfo);
            Expression getter = Expression.Call(access, MemberType.GetMethod("Get"), p_i1, p_i2);

            return(Expression.Lambda <Func <object, int, int, T> >(
                       ValueType.IsAssignableFrom(valType) ?
                       getter : Expression.Convert(getter, ValueType),
                       p_obj, p_i1, p_i2
                       ).Compile());
        }
Beispiel #12
0
        /// <summary>Set the value explicitly (i.e. not ignored if equal to the current value)</summary>
        public void SetValue(object value, bool notify = true)
        {
            if (m_in_set_value != 0)
            {
                return;
            }
            using (Scope.Create(() => ++ m_in_set_value, () => -- m_in_set_value))
            {
                // Adopt the type from 'value' if 'ValueType' is currently 'object'
                if (ValueType == typeof(object) && value != null)
                {
                    ValueType = value.GetType();
                }

                // Null is equivalent to the default type for structs
                if (ValueType.IsValueType && value == null)
                {
                    value = ValueType.DefaultInstance();
                }

                // Check the assigned value has the correct type
                if (value != null && !ValueType.IsAssignableFrom(value.GetType()))
                {
                    throw new ArgumentException($"Cannot assign to 'Value', argument has the wrong type. Expected: {ValueType.Name}  Received: {value.GetType().Name} with value '{value}'");
                }

                // Save the assigned value
                m_value = value;

                // Try assign the value to the SelectedItem property.
                // If 'value' is not a drop down item, this will be silently ignored
                SelectedItem = value;

                // Set 'Text' to match the value
                ValueToTextIfNotFocused(value);

                // Notify value changed
                if (notify)
                {
                    OnValueChanged(new ValueEventArgs(Value));
                }

                Trace($"SetValue to '{value}'");
            }
        }
        public override bool CanConnect(CPinViewModel pinToCheck, out string failReason)
        {
            if (IsLiteralOnly)
            {
                failReason = "This pin cannot be connected to another pin";
                return(false);
            }

            if (pinToCheck == null)
            {
                failReason = "Source not existing";
                return(false);
            }

            if (pinToCheck.NodeViewModel == NodeViewModel)
            {
                failReason = "Cannot connect to a pin on the same node";
                return(false);
            }

            if (pinToCheck is CInputPinViewModel)
            {
                failReason = "Input is not compatible with another input";
                return(false);
            }

            if (pinToCheck is CExecutionPinViewModel)
            {
                failReason = "Input is not compatible with execution";
                return(false);
            }

            if (pinToCheck is COutputPinViewModel outputPin)
            {
                if (!ValueType.IsAssignableFrom(outputPin.ValueType))
                {
                    failReason = "Output of type " + EditorKlaxScriptUtility.GetTypeName(outputPin.ValueType) + " is not compatible with input of type " + EditorKlaxScriptUtility.GetTypeName(ValueType);
                    return(false);
                }
            }

            failReason = "";
            return(true);
        }
Beispiel #14
0
 protected virtual bool CheckAllowedValueType(Type t) => ValueType.IsAssignableFrom(t);
Beispiel #15
0
        protected override void Initialize()
        {
            IDataItemAttribute atd = (IDataItemAttribute)Context.AttributeProvider.GetCustomAttribute(ValueType, typeof(IDataItemAttribute), false);

            if (atd != null)
            {
                if (!string.IsNullOrEmpty(atd.Name))
                {
                    Name = atd.Name;
                }
                if (atd.FallbackType != null)
                {
                    fallbackType = atd.FallbackType;
                    if (!typeof(IExtendedDataItem).IsAssignableFrom(fallbackType))
                    {
                        throw new InvalidOperationException("Fallback type '" + fallbackType + "' must implement IExtendedDataItem");
                    }
                    if (!ValueType.IsAssignableFrom(fallbackType))
                    {
                        throw new InvalidOperationException("Fallback type '" + fallbackType + "' must be a subclass of '" + ValueType + "'");
                    }
                }
            }

            object[] incs = Attribute.GetCustomAttributes(ValueType, typeof(DataIncludeAttribute), true);
            foreach (DataIncludeAttribute incat in incs)
            {
                Context.IncludeType(incat.Type);
            }

            if (ValueType.BaseType != null)
            {
                ClassDataType baseType = (ClassDataType)Context.GetConfigurationDataType(ValueType.BaseType);
                baseType.AddSubtype(this);
                int n = 0;
                foreach (ItemProperty prop in baseType.Properties)
                {
                    properties.Add(prop.Name, prop);
                    sortedPoperties.Insert(n++, prop);
                }

                // Inherit the fallback type
                if (fallbackType == null && baseType.fallbackType != null)
                {
                    fallbackType = baseType.fallbackType;
                }
            }

            foreach (Type interf in ValueType.GetInterfaces())
            {
                ClassDataType baseType = (ClassDataType)Context.GetConfigurationDataType(interf);
                baseType.AddSubtype(this);
            }

            MemberInfo[] members = ValueType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (MemberInfo member in members)
            {
                if ((member is FieldInfo || member is PropertyInfo) && member.DeclaringType == ValueType)
                {
                    Type memberType = member is FieldInfo ? ((FieldInfo)member).FieldType : ((PropertyInfo)member).PropertyType;
                    AddProperty(member, member.Name, memberType);
                }
            }

            foreach (ItemMember member in Context.AttributeProvider.GetItemMembers(ValueType))
            {
                AddProperty(member, member.Name, member.Type);
            }

            if (fallbackType != null)
            {
                Context.IncludeType(fallbackType);
            }
        }
Beispiel #16
0
        public void SetValue(object o)
        {
            if (ValueType.IsValueType && o == null)
            {
                throw new NullReferenceException($"Field type {ValueType} is value type, but argument is null");
            }

            if (o == null)
            {
                setMethod.Invoke(BindableValue, new object[1] {
                    null
                });
            }
            else
            {
                Type objectType = o?.GetType();

                if (!ValueType.IsAssignableFrom(objectType))
                {
                    if (typeof(Array).IsAssignableFrom(ValueType))
                    {
                        IList inputList = (IList)o;
                        Array array     = (Array)Activator.CreateInstance(ValueType, new object[1] {
                            inputList.Count
                        });

                        inputList.CopyTo(array, 0);
                        setMethod.Invoke(BindableValue, new object[1] {
                            array
                        });
                    }
                    else if (ValueType.GetInterface(nameof(IDictionary)) != null)
                    {
                        IList        inputList  = (IList)o;
                        var          dictionary = (IDictionary)Activator.CreateInstance(ValueType);
                        Type         kvpType    = typeof(KeyValuePair <,>).MakeGenericType(ValueType.GenericTypeArguments);
                        PropertyInfo kvpKey     = kvpType.GetProperty("Key");
                        PropertyInfo kvpValue   = kvpType.GetProperty("Value");
                        foreach (var kvp in inputList)
                        {
                            dictionary[kvpKey.GetValue(kvp)] = kvpValue.GetValue(kvp);
                        }
                        setMethod.Invoke(BindableValue, new object[1] {
                            dictionary
                        });
                    }
                    else if (ValueType.GetInterface(nameof(IList)) != null &&
                             o is IList)
                    {
                        var inputList = (IList)o;
                        var list      = (IList)Activator.CreateInstance(ValueType);
                        foreach (var element in inputList)
                        {
                            list.Add(element);
                        }
                        setMethod.Invoke(BindableValue, new object[1] {
                            list
                        });
                    }
                    else
                    {
                        throw new ArgumentException($"Field type {ValueType} is not assignable from argument type {o?.GetType()}");
                    }
                    return;
                }
                else
                {
                    setMethod.Invoke(BindableValue, new object[1] {
                        o
                    });
                }
            }
        }
 public bool IsMatch(IMemberMap memberMap)
 => ValueType.IsAssignableFrom(memberMap.SourceType) && memberMap.DestinationType.IsAssignableFrom(ValueType);