Exemplo n.º 1
0
        private EditorMember GetElement <T>(List <EditorMember> elements, List <T> source, int index, int id)
        {
            if (index >= elements.Count)
            {
                var element = EditorMember.WrapIListElement(
                    @elementName: string.Empty,
                    @elementType: typeof(T),
                    @elementId: RuntimeHelper.CombineHashCodes(id, index),
                    @attributes: attributes
                    );
                element.InitializeIList(source, index, rawTarget, unityTarget);
                elements.Add(element);
                return(element);
            }

            try
            {
                var e = elements[index];
                e.InitializeIList(source, index, rawTarget, unityTarget);
                return(e);
            }
            catch (ArgumentOutOfRangeException)
            {
                Log("DictionaryDrawer: Accessing element out of range. Index: {0} Count {1}. This shouldn't really happen. Please report it with information on how to replicate it".FormatWith(index, elements.Count));
                return(null);
            }
        }
Exemplo n.º 2
0
        protected override void OnSingleInitialization()
        {
            var seqOptions = attributes.GetAttribute <SeqAttribute>();

            options          = new SequenceOptions(seqOptions != null ? seqOptions.options : SeqOpt.None);
            options.Readonly = options.Readonly || attributes.AnyIs <ReadonlyAttribute>();

            // Sequence name
            {
                var formatMember = attributes.GetAttribute <FormatMemberAttribute>();
                if (formatMember != null)
                {
                    sequenceName = formatMember.Format(niceName, memberType.GetNiceName());
                }
                else
                {
                    sequenceName = niceName + " (" + memberType.GetNiceName() + ")";
                }

                if (options.Readonly)
                {
                    sequenceName += " (Readonly)";
                }
            }

            advancedKey          = RuntimeHelper.CombineHashCodes(id, sequenceName, "advanced");
            perItemDrawing       = attributes.AnyIs <PerItemAttribute>();
            shouldDrawAddingArea = !options.Readonly && elementType.IsA <UnityObject>();
        }
Exemplo n.º 3
0
        protected override void Initialize()
        {
            var iden = RuntimeHelper.CombineHashCodes(id, attribute.GetType());

            kSource = RuntimeHelper.CombineHashCodes(iden, "src");
            kTarget = RuntimeHelper.CombineHashCodes(iden, "target");
            kMember = RuntimeHelper.CombineHashCodes(iden, "member");

            string srcName = prefs[kSource];

            if (!string.IsNullOrEmpty(srcName))
            {
                source = GameObject.Find(srcName);
                if (source != null)
                {
                    string targetTypeName = prefs[kTarget];
                    if (!string.IsNullOrEmpty(targetTypeName))
                    {
                        target = source.GetComponent(targetTypeName);
                        if (target != null)
                        {
                            string memberName = prefs[kMember];
                            if (!string.IsNullOrEmpty(memberName))
                            {
                                var targetType = target.GetType();
                                targetMember = targetType.GetMember(memberName, Flags.InstancePublic).FirstOrDefault();

                                targetIdx = source.GetAllComponents().IndexOf(target);
                                memberIdx = getMembers(targetType).IndexOf(targetMember);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 4
0
        private EditorMember(MemberInfo memberInfo, Type memberType, string memberName,
                             object rawTarget, UnityObject unityTarget, int targetId, Attribute[] attributes)
        {
            if (attributes == null)
            {
                attributes = Empty;
            }
            else
            {
                ResolveUsing(ref attributes);
            }

            Info         = memberInfo;
            Type         = memberType;
            RawTarget    = rawTarget;
            TypeNiceName = memberType.GetNiceName();
            Name         = memberName;
            NiceName     = Formatters[@"\$nicename"].Invoke(this);
            UnityTarget  = unityTarget;
            Attributes   = attributes;

            string displayFormat = null;

            var displayAttr = attributes.GetAttribute <DisplayAttribute>();

            if (displayAttr != null && MemberDrawersHandler.IsApplicableAttribute(memberType, displayAttr, attributes))
            {
                displayFormat = displayAttr.FormatLabel;
            }

            if (displayFormat == null)
            {
                if (Type.IsImplementerOfRawGeneric(typeof(IDictionary <,>)))
                {
                    displayFormat = VFWSettings.DefaultDictionaryFormat;
                }
                else if (Type.IsImplementerOfRawGeneric(typeof(IList <>)))
                {
                    displayFormat = VFWSettings.DefaultSequenceFormat;
                }
                else
                {
                    displayFormat = VFWSettings.DefaultMemberFormat;
                }
            }

            var iter = Formatters.GetEnumerator();

            while (iter.MoveNext())
            {
                var pair    = iter.Current;
                var pattern = pair.Key;
                var result  = pair.Value(this);
                displayFormat = Regex.Replace(displayFormat, pattern, result, RegexOptions.IgnoreCase);
            }

            DisplayText = displayFormat;

            Id = RuntimeHelper.CombineHashCodes(targetId, TypeNiceName, DisplayText);
        }
Exemplo n.º 5
0
        private void AddNewPair()
        {
            var key = _options.TempKey ? _tempKey : GetNewKey(_kvpList);

            try
            {
                var value = default(TV);
                if (_options.AddToLast)
                {
                    _kvpList.Add(key, value);
                }
                else
                {
                    _kvpList.Insert(0, key, value);
                }

                memberValue.Add(key, value);

                var eKey = RuntimeHelper.CombineHashCodes(id, (_kvpList.Count - 1), "entry");
                foldouts[eKey] = true;
                foldout        = true;

                if (_options.TempKey)
                {
                    _tempKey = GetNewKey(_kvpList);
                }
            }
            catch (ArgumentException)
            {
                Log("Key already exists: " + key);
            }
        }
Exemplo n.º 6
0
        public void Initialize(MethodInfo method, object rawTarget, UnityObject unityTarget, int id, BaseGUI gui)
        {
            this.gui       = gui;
            this.rawTarget = rawTarget;
            this.id        = id;

            if (initialized)
            {
                return;
            }
            initialized = true;

            var commentAttr = method.GetCustomAttribute <CommentAttribute>();

            if (commentAttr != null)
            {
                comment = commentAttr.comment;
            }

            niceName = method.GetNiceName();

            if (niceName.IsPrefix("dbg") || niceName.IsPrefix("Dbg"))
            {
                niceName = niceName.Remove(0, 3);
            }

            invoke = method.DelegateForCall();
            var argInfos = method.GetParameters();
            int len      = argInfos.Length;

            argValues  = new object[len];
            argKeys    = new int[len];
            argMembers = new EditorMember[len];

            for (int iLoop = 0; iLoop < len; iLoop++)
            {
                int i       = iLoop;
                var argInfo = argInfos[i];

                argKeys[i] = RuntimeHelper.CombineHashCodes(id, argInfo.ParameterType.Name + argInfo.Name);

                argValues[i] = TryLoad(argInfos[i].ParameterType, argKeys[i]);

                argMembers[i] = EditorMember.WrapGetSet(
                    @get: () => argValues[i],
                    @set: x => argValues[i] = x,
                    @rawTarget: rawTarget,
                    @unityTarget: unityTarget,
                    @attributes: argInfo.GetCustomAttributes(true) as Attribute[],
                    @name: argInfo.Name,
                    @id: argKeys[i],
                    @dataType: argInfo.ParameterType
                    );
            }

#if DBG
            Log("Method drawer init");
#endif
        }
Exemplo n.º 7
0
        public void SetV2(int key, Vector2 value)
        {
            int keyX = RuntimeHelper.CombineHashCodes(key, "x");
            int keyY = RuntimeHelper.CombineHashCodes(key, "y");

            this[keyX] = value.x;
            this[keyY] = value.y;
        }
Exemplo n.º 8
0
 void StoreValidRect()
 {
     if (!_storedValidRect && _validRect.HasValue)
     {
         var key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
         _prefs.Vector3s[key] = new Vector3(_validRect.Value.x, _validRect.Value.y);
         _storedValidRect     = true;
     }
 }
Exemplo n.º 9
0
        public TextFilter(string[] values, int id, bool initialToggle, EditorRecord prefs, Action <string> setValue)
        {
            _prefs    = prefs;
            _values   = values;
            _setValue = setValue;
            _id       = RuntimeHelper.CombineHashCodes(id, "Filter");

            _toggle  = _prefs.ValueOrDefault(this._id, initialToggle);
            _pattern = _prefs.ValueOrDefault(this._id, "");
        }
Exemplo n.º 10
0
        public void SetV3(int key, Vector3 value)
        {
            int keyX = RuntimeHelper.CombineHashCodes(key, "x");
            int keyY = RuntimeHelper.CombineHashCodes(key, "y");
            int keyZ = RuntimeHelper.CombineHashCodes(key, "z");

            this[keyX] = value.x;
            this[keyY] = value.y;
            this[keyZ] = value.z;
        }
Exemplo n.º 11
0
        public MembersCategory(string fullPath, float displayOrder, int id)
        {
            this.DisplayOrder = displayOrder;
            this.FullPath     = fullPath;
            this.Name         = FullPath.Substring(FullPath.LastIndexOf('/') + 1);
            this._id          = RuntimeHelper.CombineHashCodes(id, fullPath.GetHashCode());
            Indent            = true;

            NestedCategories = new List <MembersCategory>();
            Members          = new List <MemberInfo>();
        }
Exemplo n.º 12
0
 void StoreValidRect()
 {
     if (!_storedValidRect && _validRect.HasValue)
     {
         int key  = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
         int keyX = RuntimeHelper.CombineHashCodes(key, "x");
         int keyY = RuntimeHelper.CombineHashCodes(key, "y");
         prefs[keyX]      = _validRect.Value.x;
         prefs[keyY]      = _validRect.Value.y;
         _storedValidRect = true;
     }
 }
Exemplo n.º 13
0
 private EditorMember(MemberInfo memberInfo, Type memberType, string memberName, object rawTarget, UnityObject unityTarget, int targetId, Attribute[] attributes)
 {
     Info         = memberInfo;
     Type         = memberType;
     RawTarget    = rawTarget;
     Name         = memberName;
     NiceName     = Name.Replace("_", "").SplitPascalCase();
     TypeNiceName = memberType.GetNiceName();
     UnityTarget  = unityTarget;
     Id           = RuntimeHelper.CombineHashCodes(targetId, TypeNiceName, NiceName);
     Attributes   = attributes;
 }
Exemplo n.º 14
0
        private void AddNewPair()
        {
            TK defKey;

            if (typeof(TK) == typeof(string))
            {
                var x = "New Key ";
                var n = 0;
                while (_kvpList.Keys.Contains((TK)(object)(x + n)))
                {
                    n++;
                }
                defKey = (TK)(object)(x + n);
            }
            else if (typeof(TK) == typeof(int))
            {
                var n = 0;
                while (_kvpList.Keys.Contains((TK)(object)(n)))
                {
                    n++;
                }
                defKey = (TK)(object)n;
            }
            else if (typeof(TK).IsEnum)
            {
                var values = Enum.GetValues(typeof(TK)) as TK[];
                var result = values.Except(_kvpList.Keys).ToList();
                if (result.Count == 0)
                {
                    return;
                }
                defKey = (TK)result[0];
            }
            else
            {
                defKey = default(TK);
            }

            try
            {
                var defValue = default(TV);
                _kvpList.Insert(0, defKey, defValue);
                memberValue.Add(defKey, defValue);

                var eKey = RuntimeHelper.CombineHashCodes(id, (_kvpList.Count - 1), "entry");
                foldouts[eKey] = true;
            }
            catch (ArgumentException)
            {
                Log("Key already exists: " + defKey);
            }
        }
Exemplo n.º 15
0
        private EditorMember(MemberInfo memberInfo, Type memberType, string memberName,
                             object rawTarget, UnityObject unityTarget, int targetId, Attribute[] attributes)
        {
            Info         = memberInfo;
            Type         = memberType;
            RawTarget    = rawTarget;
            Name         = memberName;
            TypeNiceName = memberType.GetNiceName();
            UnityTarget  = unityTarget;
            Attributes   = attributes ?? Empty;

            string displayFormat = null;

            var formatAttr = Attributes.GetAttribute <DisplayAttribute>();

            if (formatAttr != null && !string.IsNullOrEmpty(formatAttr.FormatLabel))
            {
                displayFormat = formatAttr.FormatLabel;
            }

            var settings = VFWSettings.GetInstance();

            if (displayFormat == null)
            {
                if (Type.IsImplementerOfRawGeneric(typeof(IDictionary <,>)))
                {
                    displayFormat = settings.DefaultDictionaryFormat;
                }
                else if (Type.IsImplementerOfRawGeneric(typeof(IList <>)))
                {
                    displayFormat = settings.DefaultSequenceFormat;
                }
                else
                {
                    displayFormat = settings.DefaultMemberFormat;
                }
            }

            var iter = Formatters.GetEnumerator();

            while (iter.MoveNext())
            {
                var pair    = iter.Current;
                var pattern = pair.Key;
                var result  = pair.Value(this);
                displayFormat = Regex.Replace(displayFormat, pattern, result, RegexOptions.IgnoreCase);
            }

            DisplayText = displayFormat;

            Id = RuntimeHelper.CombineHashCodes(targetId, TypeNiceName, DisplayText);
        }
Exemplo n.º 16
0
        public TextFilter(string[] values, int id, bool initialToggle, Action <string> setValue)
        {
            _values   = values;
            _setValue = setValue;
            _id       = RuntimeHelper.CombineHashCodes(id, "Filter");

            if (_prefs == null)
            {
                _prefs = BetterPrefs.GetEditorInstance();
            }

            _toggle  = _prefs.Bools.ValueOrDefault(this._id, initialToggle);
            _pattern = _prefs.Strings.ValueOrDefault(this._id, "");
        }
Exemplo n.º 17
0
        protected override void Initialize()
        {
            var displayAttr = attributes.GetAttribute <DisplayAttribute>();

            _options = new SequenceOptions(displayAttr != null ? displayAttr.SeqOpt : Seq.None);

            if (_options.Readonly)
            {
                displayText += " (Readonly)";
            }

            _advancedKey          = RuntimeHelper.CombineHashCodes(id, "advanced");
            _perItemDrawing       = attributes.AnyIs <PerItemAttribute>();
            _shouldDrawAddingArea = !_options.Readonly && _elementType.IsA <UnityObject>();
        }
Exemplo n.º 18
0
        private void AddNewPair()
        {
            try
            {
                var key   = getNewKey();
                var value = default(TV);
                kvpList.Insert(0, key, value, false);

                var pkey = RuntimeHelper.CombineHashCodes(id, (kvpList.Count - 1), "entry");
                foldouts[pkey] = true;
            }
            catch (ArgumentException e)
            {
                Log(e.Message);
            }
        }
Exemplo n.º 19
0
        public override void OnGUI(Action guiCode, Vector4 padding, int targetId)
        {
            _widthCorrection = padding.y;
            _id = targetId;

            if (!_validRect.HasValue)
            {
                int         key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
                int         keyX = RuntimeHelper.CombineHashCodes(key, "x");
                int         keyY = RuntimeHelper.CombineHashCodes(key, "y");
                RecordValue prevX, prevY;
                if (prefs.TryGetValue(keyX, out prevX))
                {
                    //Log("Seems we changed play modes and rabbit doesn't have a coord. but we have in store a prev coord from a previous editor session that should work");
                    prevY = prefs[keyY];
                    var tmp = new Rect();
                    tmp.x      = prevX;
                    tmp.y      = prevY;
                    _validRect = tmp;
                }
            }

            var unityRect = GUILayoutUtility.GetRect(0f, 0f);

            if (Event.current.type == EventType.Repaint)
            {
                if (!_validRect.HasValue || _validRect.Value.y != unityRect.y)
                {
                    _validRect     = unityRect;
                    _pendingLayout = true;
                }
            }

            if (_validRect.HasValue)
            {
                var start = new Rect(_validRect.Value.x + padding.x, _validRect.Value.y + padding.z,
                                     EditorGUIUtility.currentViewWidth - padding.y, _validRect.Value.height);

                using (Begin(start))
                    guiCode();
            }

            GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth - 35f, Height - padding.w);

            OnFinishedLayoutReserve.SafeInvoke();
        }
Exemplo n.º 20
0
        void OnPlaymodeChanged()
        {
            //Debug.Log("Playmode changed");
            if (_validRect.HasValue)
            {
                var key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
                _prefs.Vector3s[key] = new Vector3(_validRect.Value.x, _validRect.Value.y);
            }

            //if (_prevRect.HasValue)
            //{
            //var prevKey = RTHelper.CombineHashCodes(_id, "prevRect");
            //var x = _prevRect.Value.x;
            //var y = _prevRect.Value.y;
            //_prefs.Vector3s[prevKey] = new Vector3(x, y);
            //Debug.Log("Saved: " + x + " " + y);
            //}
        }
Exemplo n.º 21
0
        protected override void OnSingleInitialization()
        {
            adding     = new AddingData();
            kAdvanced  = RuntimeHelper.CombineHashCodes(id, "advanced");
            kAdd       = RuntimeHelper.CombineHashCodes(id, "add");
            kInvoke    = RuntimeHelper.CombineHashCodes(id, "invoke");
            kHeaderStr = string.Format("{0} ({1})", niceName, memberTypeName);

            if (memberValue == null)
            {
                memberValue = memberType.Instance <IBaseDelegate>();
            }

            int len = memberValue.ParamTypes.Length;

            argValues  = new object[len];
            argMembers = new EditorMember[len];

            for (int iLoop = 0; iLoop < len; iLoop++)
            {
                int i         = iLoop;
                var paramType = memberValue.ParamTypes[i];

                argValues[i] = paramType.GetDefaultValueEmptyIfString();

                var argMember = EditorMember.WrapGetSet(
                    @get: () => argValues[i],
                    @set: x => argValues[i] = x,
                    @rawTarget: argValues,
                    @unityTarget: unityTarget,
                    @name: string.Format("({0})", paramType.GetNiceName()),
                    @attributes: null,
                    @id: RuntimeHelper.CombineHashCodes(id, i),
                    @dataType: paramType
                    );

                argMember.RawTarget = rawTarget;
                argMembers[i]       = argMember;
            }

#if DBG
            Log("Delegate drawer init. " + niceName);
#endif
        }
Exemplo n.º 22
0
        protected override void Initialize()
        {
            var displayAttr = attributes.GetAttribute <DisplayAttribute>();

            _options = new SequenceOptions(displayAttr != null ? displayAttr.SeqOpt : Seq.None);

            if (_options.Readonly)
            {
                displayText += " (Readonly)";
            }

            _advancedKey          = RuntimeHelper.CombineHashCodes(id, "advanced");
            _shouldDrawAddingArea = !_options.Readonly && _elementType.IsA <UnityObject>();

            var perItem = attributes.GetAttribute <PerItemAttribute>();

            if (perItem != null)
            {
                if (perItem.ExplicitAttributes == null)
                {
                    _perItemAttributes = attributes.Where(x => !(x is PerItemAttribute)).ToArray();
                }
                else
                {
                    _perItemAttributes = attributes.Where(x => perItem.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray();
                }
            }

            if (_options.Filter)
            {
                _filter = new TextFilter(null, id, true, null);
            }

            _originalDisplay = displayText;

            if (memberValue == null)
            {
                memberValue = GetNew();
            }

            member.CollectionCount = memberValue.Count;
        }
Exemplo n.º 23
0
        public Vector2 GetV2(int key, Vector2 defaultValue = new Vector2())
        {
            int keyX = RuntimeHelper.CombineHashCodes(key, "x");

            Vector2 result;

            RecordValue x;

            if (!TryGetValue(keyX, out x))
            {
                result = defaultValue;
            }
            else
            {
                int keyY = RuntimeHelper.CombineHashCodes(key, "y");
                result = new Vector2(x, this[keyY]);
            }

            return(result);
        }
Exemplo n.º 24
0
        private EditorMember GetElement(int index)
        {
            if (index >= _elements.Count)
            {
                var element = EditorMember.WrapIListElement(
                    @attributes: _perItemAttributes,
                    @elementName: string.Empty,
                    @elementType: typeof(TElement),
                    @elementId: RuntimeHelper.CombineHashCodes(id, index)
                    );

                element.InitializeIList(memberValue, index, rawTarget, unityTarget);
                _elements.Add(element);
                return(element);
            }

            var e = _elements[index];

            e.InitializeIList(memberValue, index, rawTarget, unityTarget);
            return(e);
        }
Exemplo n.º 25
0
        public override void OnGUI(Action guiCode, Vector2 padding, int targetId)
        {
            _id = targetId;

            if (!_validRect.HasValue)
            {
                var     key = RuntimeHelper.CombineHashCodes(_id, "rabbit_coords");
                Vector3 prevCoords;
                if (_prefs.Vector3s.TryGetValue(key, out prevCoords))
                {
                    //Log("Seems we changed play modes and rabbit doesn't have a coord. but we have in store a prev coord from a previous editor session that should work");
                    var tmp = new Rect();
                    tmp.x      = prevCoords.x;
                    tmp.y      = prevCoords.y;
                    _validRect = tmp;
                }
            }

            var unityRect = GUILayoutUtility.GetRect(0f, 0f);

            if (Event.current.type == EventType.Repaint)
            {
                if (!_validRect.HasValue || _validRect.Value.y != unityRect.y)
                {
                    _validRect     = unityRect;
                    _pendingLayout = true;
                }
            }

            if (_validRect.HasValue)
            {
                var start = new Rect(_validRect.Value.x + padding.x, _validRect.Value.y,
                                     EditorGUIUtility.currentViewWidth - padding.y, _validRect.Value.height);

                using (Begin(start))
                    guiCode();
            }

            GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth - 35f, Height);
        }
Exemplo n.º 26
0
        protected override void OnSingleInitialization()
        {
            adding = new AddingData();

            kAdvanced  = RuntimeHelper.CombineHashCodes(id, "advanced");
            kAdd       = RuntimeHelper.CombineHashCodes(id, "add");
            kHeaderStr = string.Format("{0} ({1})", niceName, memberTypeName);

            if (memberValue == null)
            {
                memberValue = new uDelegate();
            }

            if (argValuesList == null)
            {
                argValuesList = new List <object[]>();
            }

            argMembersList = new List <EditorMember[]>();
#if DBG
            Log("Delegate drawer init. " + niceName);
#endif
        }
Exemplo n.º 27
0
        /// <summary>
        /// Fetches visible members in the inspected target object and assigns them to their corresponding categories
        /// </summary>
        private void Initialize()
        {
            OnBeforeInitialized();

            // fetch visible members
            _visibleMembers = VisibilityLogic.CachedGetVisibleMembers(targetType);

            var drawnByUnity = _visibleMembers
                               .Where(x => x.IsDefined <DrawByUnityAttribute>() || DrawnByUnityTypes.Any(x.GetDataType().IsA));

            _visibleMembers = _visibleMembers.Except(drawnByUnity).ToList();

            _membersDrawnByUnityLayout = drawnByUnity.Select(x => x.Name).ToArray();

            // allocate categories
            _categories = new List <MembersCategory>();

            var multiple    = targetType.GetCustomAttribute <DefineCategoriesAttribute>(true);
            var definitions = targetType.GetCustomAttributes <DefineCategoryAttribute>(true);

            if (multiple != null)
            {
                definitions = definitions.Concat(multiple.names.Select(n => new DefineCategoryAttribute(n, 1000)));
            }

            Func <string, string[]> ParseCategoryPath = fullPath =>
            {
                int      nPaths = fullPath.Split('/').Length;
                string[] result = new string[nPaths];
                for (int i = 0, index = -1; i < nPaths - 1; i++)
                {
                    index     = fullPath.IndexOf('/', index + 1);
                    result[i] = fullPath.Substring(0, index);
                }
                result[nPaths - 1] = fullPath;
                return(result);
            };

            // Order by exclusivity
            var defs = from d in definitions
                       let paths = ParseCategoryPath(d.FullPath)
                                   orderby !d.Exclusive
                                   select new { def = d, paths };

            // Parse paths and resolve definitions
            var resolver = new CategoryDefinitionResolver();
            var lookup   = new Dictionary <string, MembersCategory>();

            foreach (var x in defs)
            {
                var paths = x.paths;
                var d     = x.def;

                MembersCategory parent = null;

                for (int i = 0; i < paths.Length; i++)
                {
                    var path = paths[i];

                    var current = (parent == null ? _categories :
                                   parent.NestedCategories).FirstOrDefault(c => c.FullPath == path);

                    if (current == null)
                    {
                        current = new MembersCategory(path, d.Order, id, prefs);
                        if (i == 0)
                        {
                            _categories.Add(current);
                        }
                        if (parent != null)
                        {
                            parent.NestedCategories.Add(current);
                        }
                    }
                    lookup[path] = current;
                    parent       = current;
                }

                var last = lookup[paths.Last()];
                last.ForceExpand      = d.ForceExpand;
                last.AlwaysHideHeader = d.AlwaysHideHeader;
                resolver.Resolve(_visibleMembers, d).Foreach(last.Members.Add);

                lookup.Clear();
                parent.Members = parent.Members.OrderBy <MemberInfo, float>(VisibilityLogic.GetMemberDisplayOrder).ToList();
            }

            // filter out empty categories
            _categories = _categories.Where(x => x.NestedCategories.Count > 0 || x.Members.Count > 0)
                          .OrderBy(x => x.DisplayOrder)
                          .ToList();

            for (int i = 0; i < _categories.Count; i++)
            {
                var c = _categories[i];
                c.RemoveEmptyNestedCategories();
            }

            var getDisplayOptions = targetType.GetMethod("GetDisplayOptions");

            Assert.IsNotNull(getDisplayOptions);

            // otherwise whatever value is in our settings asset
            // TODO CHANGED: A common interface is now used for both cases.
            var defaultDisplay = typeof(IVFWObject).IsAssignableFrom(getDisplayOptions.DeclaringType) ?
                                 VFWSettings.DefaultDisplay : (CategoryDisplay)getDisplayOptions.Invoke(target);

            //var defaultDisplay = (getDisplayOptions.DeclaringType == typeof(BaseBehaviour) ||
            //                      getDisplayOptions.DeclaringType == typeof(BaseScriptableObject)) ?
            //                      VFWSettings.DefaultDisplay : (CategoryDisplay)getDisplayOptions.Invoke(target);

            int displayKey   = RuntimeHelper.CombineHashCodes(id, "display");
            int displayValue = prefs.ValueOrDefault(displayKey, (int)defaultDisplay);

            _display          = displayValue == -1 ? VFWSettings.DefaultDisplay : (CategoryDisplay)displayValue;
            prefs[displayKey] = (int)_display;

            var spacingKey = RuntimeHelper.CombineHashCodes(id, "spacing");

            _spacing          = prefs.ValueOrDefault(spacingKey, VFWSettings.DefaultSpacing);
            prefs[spacingKey] = _spacing;

            FieldInfo field;

            field = targetType.GetField("dbg", Flags.InstanceAnyVisibility);
            if (field == null)
            {
                ErrorHelper.MemberNotFound(targetType, "dbg");
            }

            _debug = EditorMember.WrapMember(field, target, target, id);

            OnAfterInitialized();
        }
Exemplo n.º 28
0
 public override int GetHashCode()
 {
     return(RuntimeHelper.CombineHashCodes(Item1, Item2));
 }
Exemplo n.º 29
0
        public override void OnGUI()
        {
            foldout = gui.Foldout(kHeaderStr, foldout, Layout.sExpandWidth());
            if (!foldout)
            {
                return;
            }

            if (memberValue == null)
            {
                memberValue = new uDelegate();
            }

            // read
            var handlers = memberValue.handlers;

            using (gui.Vertical(GUI.skin.box))
            {
                if (handlers.Count == 0)
                {
                    gui.HelpBox("There are no handlers for this delegate");
                    goto FOOTER;
                }

                // header
                {
                    gui.Space(1.5f);
                    using (gui.Horizontal())
                    {
                        gui.BoldLabel("Target :: Handler");
                        using (gui.State(foldout))
                        {
                            foldouts[kAdvanced] = gui.CheckButton(foldouts[kAdvanced], "advanced mode", MiniButtonStyle.Right);
                        }
                    }
                }

                gui.Splitter();

                // body
                {
                    // target : handler
                    for (int iLoop = 0; iLoop < handlers.Count;)
                    {
                        var i       = iLoop;
                        var handler = handlers[i];
                        var target  = handler.target;
                        var removed = false;
                        var key     = RuntimeHelper.CombineHashCodes(id, "udel", i);

                        using (gui.Horizontal())
                        {
                            var obj = target as UnityObject;
                            if (obj != null)
                            {
                                gui.Object(obj);
                            }
                            else
                            {
                                string str;
                                if (target == null)
                                {
                                    str = "null";
                                }
                                else
                                {
                                    str = target.ToString();
                                }
                                gui.Text(str);
                            }

                            gui.Text(handler.method.Name);

                            gui.Space(10f);
                            foldouts[key] = gui.Foldout(foldouts[key]);
                            gui.Space(-5f);

                            if (foldouts[kAdvanced])
                            {
                                if (gui.MoveDownButton())
                                {
                                    handlers.MoveElementDown(i);
                                }
                                if (gui.MoveUpButton())
                                {
                                    handlers.MoveElementUp(i);
                                }
                                if (gui.RemoveButton("handler", MiniButtonStyle.ModRight))
                                {
                                    handlers.RemoveAt(i);
                                    argMembersList.RemoveAt(i);
                                    argValuesList.RemoveAt(i);
                                    removed = true;
                                }
                            }
                        }

                        if (foldouts[key] && !removed)
                        {
                            var    method     = handler.method;
                            Type[] paramTypes = method.GetParameters().Select(x => x.ParameterType).ToArray();

                            SetupMembers(i, paramTypes);

                            using (gui.Indent())
                            {
                                gui.Label("Invocation args");
                                using (gui.Indent())
                                {
                                    var argMembers = argMembersList[i];
                                    for (int j = 0; j < argMembers.Length; j++)
                                    {
                                        gui.Member(argMembers[j], true);
                                    }
                                }
                            }
                        }

                        if (!removed)
                        {
                            iLoop++;
                        }
                    }
                }

FOOTER:
                gui.Space(3f);
                gui.Splitter();
                {
                    // add> source :: invoke>
                    using (gui.Horizontal())
                    {
                        using (gui.State(foldouts[kAdd] && adding.source != null && adding.target != null && adding.method != null))
                        {
                            if (gui.Button("Add", "Add new handler", EditorStyles.miniButton, Layout.sWidth(40f)))
                            {
                                handlers.Add(new IBaseDelegate.Handler
                                {
                                    target = adding.target,
                                    method = adding.method
                                });

                                var method     = adding.method;
                                var paramTypes = method.GetParameters().Select(x => x.ParameterType).ToArray();
                                int len        = paramTypes.Length;
                                var argValues  = new object[len];
                                argValuesList.Add(argValues);
                                for (int x = 0; x < argValues.Length; x++)
                                {
                                    argValues[x] = paramTypes[x].GetDefaultValueEmptyIfString();
                                }
                            }
                        }

                        gui.Space(10f);

                        // add foldout
                        if (adding.source != null)
                        {
                            foldouts[kAdd] = gui.Foldout(foldouts[kAdd]);
                        }

                        // source
                        var obj = gui.Object(adding.source);
                        {
                            if (adding.source != obj)
                            {
                                adding.source  = obj;
                                foldouts[kAdd] = true;
                            }
                        }

                        using (gui.State(handlers.Count > 0))
                        {
                            if (gui.Button("Invoke", EditorStyles.miniButtonRight, Layout.sWidth(50f)))
                            {
                                memberValue.Invoke();
                            }
                        }
                    }

                    // adding area: target -- method
                    if (foldouts[kAdd] && adding.source != null)
                    {
                        gui.Space(5f);
                        gui.Label("Add handler:");
                        using (gui.Indent(GUI.skin.textArea))
                        {
                            // target
                            var gameObject = adding.gameObject;
                            if (gameObject == null)
                            {
                                gui.Popup("Target", 0, new string[] { adding.source.GetType().Name });
                                {
                                    adding.target = adding.source;
                                }
                            }
                            else
                            {
                                if (adding.source is Component)
                                {
                                    adding.target = adding.source;
                                }

                                var components      = gameObject.GetAllComponents();
                                int cIndex          = components.IndexOfZeroIfNotFound(adding.target);
                                var uniqueNames     = components.Select(c => c.GetType().Name).ToList().Uniqify();
                                var targetSelection = gui.Popup("Target", cIndex, uniqueNames.ToArray());
                                {
                                    if (cIndex != targetSelection || adding.target != components[targetSelection])
                                    {
                                        adding.target = components[targetSelection];
                                    }
                                }
                            }

                            // method
                            if (adding.target != null)
                            {
                                var methods = adding.target.GetType()
                                              .GetMethods(memberValue.ReturnType, memberValue.ParamTypes, Flags.InstancePublic, false)
                                              .Where(m => !m.IsDefined <HideAttribute>())
                                              .Where(m => !DelegateSettings.IgnoredMethods.Contains(m.Name))
                                              .ToList();
                                int mIndex          = methods.IndexOfZeroIfNotFound(adding.method);
                                int methodSelection = gui.Popup("Handler", mIndex, methods.Select(m => m.GetFullName()).ToArray());
                                {
                                    if (!methods.IsEmpty() && (mIndex != methodSelection || adding.method != methods[methodSelection]))
                                    {
                                        adding.method = methods[methodSelection];
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // write
            memberValue.handlers = handlers;
        }
Exemplo n.º 30
0
        protected virtual void OnGUI()
        {
            if (ShowScriptHeader)
            {
                var scriptKey = RuntimeHelper.CombineHashCodes(id, "script");
                gui.Space(3f);
                using (gui.Horizontal(EditorStyles.toolbarButton))
                {
                    gui.Space(10f);
                    prefs[scriptKey] = gui.Foldout(prefs.ValueOrDefault(scriptKey, false));
                    gui.Space(-12f);

                    if (ScriptField()) // script changed? exit!
                    {
                        return;
                    }
                }

                if (prefs[scriptKey])
                {
                    gui.Space(2f);

                    using (gui.Indent(GUI.skin.textField))
                    {
                        gui.Space(3f);

                        gui.Member(_debug);

                        var mask = gui.BunnyMask("Display", _display);
                        {
                            var newValue = (CategoryDisplay)mask;
                            if (_display != newValue)
                            {
                                _display = newValue;
                                var displayKey = RuntimeHelper.CombineHashCodes(id, "display");
                                prefs[displayKey] = mask;
                            }
                        }

                        var spacing = Mathf.Clamp(gui.Int("Spacing", _spacing), -13, (int)EditorGUIUtility.currentViewWidth / 4);
                        if (_spacing != spacing)
                        {
                            _spacing = spacing;
                            int spacingKey = RuntimeHelper.CombineHashCodes(id, "spacing");
                            prefs[spacingKey] = _spacing;
                            gui.RequestResetIfRabbit();
                        }
                    }
                }
            }

            gui.BeginCheck();

            for (int i = 0; i < _categories.Count; i++)
            {
                var cat = _categories[i];
                cat.Display    = _display;
                cat.Spacing    = _spacing;
                cat.gui        = gui;
                cat.HideHeader = (_display & CategoryDisplay.Headers) == 0;
                if ((_display & CategoryDisplay.CategorySplitter) != 0)
                {
                    gui.Splitter();
                }
                cat.Draw(target);
            }

            if (gui.HasChanged())
            {
#if DBG
                Log("Target changed: " + target);
#endif
                if (target != null)
                {
                    EditorUtility.SetDirty(target);
                }
            }
        }