コード例 #1
0
    public void getAllContainedElements(UnityEngine.UIElements.VisualElement parentElement,
                                        ref List <UnityEngine.UIElements.VisualElement> allElements)
    {
        allElements.Add(parentElement);

        for (int i = 0; i < parentElement.childCount; i++)
        {
            getAllContainedElements(parentElement[i], ref allElements);
        }
    }
コード例 #2
0
    private void ReflectionVisualElement()
    {
        UnityEngine.UIElements.VisualElement a = new UnityEngine.UIElements.VisualElement();
        Class    visualElement = new Class(typeof(UnityEngine.UIElements.VisualElement));
        Property Array         = new Property(visualElement, "Item");

        visualElement.SetInstance(a);
        Debug.Log(Array.propertyInfo);
        Debug.Log(Array.propertyInfo.GetValue(a, new object [] { 0 }));

        //Class proerty = new Class(typeof(PropertyInfo));
        //proerty.SetInstance(Array.propertyInfo);
        //proerty.ShowMembersValue();
    }
コード例 #3
0
        public static VisualElement ParseEntry(string entry, VisualElement element)
        {
            if (element?.name is null)
            {
                Debug.Log($"Failed to parse entry, element was null");
                return(null);
            }

            var entrySplit = entry.Split(':');

            entrySplit[0] = entrySplit[0].Replace(" ", "");
            if (entrySplit[0] == "")
            {
                return(element);
            }

            var property = MapProperty(entrySplit[0]);

            if (property == null)
            {
                Debug.Log($"Failed to find property \"{MapCssName(entrySplit[0])}\"");
                // Debug.Log($"Type of style: \"{typeof(element.style).FullName}\"");
            }

            try
            {
                if (property is null)
                {
                    var value = ParseProperty(property, entrySplit[1]);
                    if (value == null)
                    {
                        Debug.Log($"Failed to parse entry {property.Name}\n\"{entry}\"");
                    }
                    else
                    {
                        property.SetValue(element.style, value);
                    }
                }
            }
            catch (Exception)
            {
                Debug.Log($"Failed to set property. Skipping {property?.Name}\n\"{entry}\"");
            }

            return(element);
        }
コード例 #4
0
        internal static TextCoreSettings TextCoreSettingsForElement(UnityEngine.UIElements.VisualElement ve)
        {
            var fontAsset = GetFontAsset(ve);

            if (fontAsset == null)
            {
                return(new TextCoreSettings());
            }

            var resolvedStyle = ve.resolvedStyle;
            var computedStyle = ve.computedStyle;

            // Convert the text settings pixel units to TextCore relative units
            float paddingPercent = 1.0f / fontAsset.atlasPadding;
            float pointSizeRatio = ((float)fontAsset.faceInfo.pointSize) / ve.computedStyle.fontSize.value;
            float factor         = paddingPercent * pointSizeRatio;

            float   outlineWidth     = Mathf.Max(0.0f, resolvedStyle.unityTextOutlineWidth * factor);
            float   underlaySoftness = Mathf.Max(0.0f, computedStyle.textShadow.blurRadius * factor);
            Vector2 underlayOffset   = computedStyle.textShadow.offset * factor;

            var outlineColor = resolvedStyle.unityTextOutlineColor;

            if (outlineWidth < Mathf.Epsilon)
            {
                outlineColor.a = 0.0f;
            }

            return(new TextCoreSettings()
            {
                outlineColor = outlineColor,
                outlineWidth = outlineWidth,
                underlayColor = computedStyle.textShadow.color,
                underlayOffset = underlayOffset,
                underlaySoftness = underlaySoftness
            });
        }
コード例 #5
0
 public static void BuildInspectorProperties(IEditorContainer editor, System.Collections.Generic.HashSet <System.Type> usedComponents, SerializedProperty obj,
                                             UnityEngine.UIElements.VisualElement container, bool noFields, System.Action <int, PropertyField> onBuild = null)
 {
     BuildInspectorPropertiesElement(string.Empty, editor, usedComponents, obj, container, noFields, onBuild);
 }
コード例 #6
0
 public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
 {
     base.Init(ve, bag, cc);
     ((BaseField <TValueType>)ve).label = m_Label.GetValueFromBag(bag, cc);
 }
コード例 #7
0
 public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
 {
     base.Init(ve, bag, cc);
     ((INotifyValueChanged <TValueType>)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc));
 }
コード例 #8
0
 protected BaseField(string label, VisualElement visualInput)
     : this(label)
 {
     this.visualInput = visualInput;
 }
コード例 #9
0
 public void ScrollTo(VisualElement visualElement)
 {
     m_ListView.ScrollTo(visualElement);
 }
コード例 #10
0
        int FocusRingAutoIndexSort(FocusRingRecord a, FocusRingRecord b)
        {
            switch (defaultFocusOrder)
            {
            case DefaultFocusOrder.ChildOrder:
            default:
                return(Comparer <int> .Default.Compare(a.m_AutoIndex, b.m_AutoIndex));

            case DefaultFocusOrder.PositionXY:
            {
                VisualElement ave = a.m_Focusable as VisualElement;
                VisualElement bve = b.m_Focusable as VisualElement;

                if (ave != null && bve != null)
                {
                    if (ave.layout.position.x < bve.layout.position.x)
                    {
                        return(-1);
                    }
                    else if (ave.layout.position.x > bve.layout.position.x)
                    {
                        return(1);
                    }
                    else
                    {
                        if (ave.layout.position.y < bve.layout.position.y)
                        {
                            return(-1);
                        }
                        else if (ave.layout.position.y > bve.layout.position.y)
                        {
                            return(1);
                        }
                    }
                }

                // a and b should be ordered using their order of appearance.
                return(Comparer <int> .Default.Compare(a.m_AutoIndex, b.m_AutoIndex));
            }

            case DefaultFocusOrder.PositionYX:
            {
                VisualElement ave = a.m_Focusable as VisualElement;
                VisualElement bve = b.m_Focusable as VisualElement;

                if (ave != null && bve != null)
                {
                    if (ave.layout.position.y < bve.layout.position.y)
                    {
                        return(-1);
                    }
                    else if (ave.layout.position.y > bve.layout.position.y)
                    {
                        return(1);
                    }
                    else
                    {
                        if (ave.layout.position.x < bve.layout.position.x)
                        {
                            return(-1);
                        }
                        else if (ave.layout.position.x > bve.layout.position.x)
                        {
                            return(1);
                        }
                    }
                }

                // a and b should be ordered using their order of appearance.
                return(Comparer <int> .Default.Compare(a.m_AutoIndex, b.m_AutoIndex));
            }
            }
        }
コード例 #11
0
 static void OnProcessMatchResult(VisualElement current, MatchResultInfo info)
 {
     current.triggerPseudoMask    |= info.triggerPseudoMask;
     current.dependencyPseudoMask |= info.dependencyPseudoMask;
 }
コード例 #12
0
        public override void TraverseRecursive(VisualElement element, int depth)
        {
            if (ShouldSkipElement(element))
            {
                return;
            }

            // If the element is fully dirty, we need to erase those flags since the full element and its subtree
            // will be re-styled.
            // If the element is not in the update list, it's a parent of something dirty and therefore it won't be restyled.
            bool updateElement = m_UpdateList.Contains(element);

            if (updateElement)
            {
                element.triggerPseudoMask    = 0;
                element.dependencyPseudoMask = 0;
            }

            int originalStyleSheetCount = m_StyleMatchingContext.styleSheetStack.Count;
            int originalVariableCount   = m_ProcessVarContext.count;

            if (element.styleSheetList != null)
            {
                for (var index = 0; index < element.styleSheetList.Count; index++)
                {
                    var styleSheetData = element.styleSheetList[index];
                    m_StyleMatchingContext.styleSheetStack.Add(styleSheetData);
                }
            }

            // Store the number of custom style before processing rules in case an element stop
            // to have matching custom styles the event still need to be sent and only looking
            // at the matched custom styles won't suffice.
            int originalCustomStyleCount = element.specifiedStyle.customPropertiesCount;
            var currentInheritStyle      = m_StyleMatchingContext.inheritedStyle;

            if (updateElement)
            {
                m_StyleMatchingContext.currentElement = element;

                StyleSelectorHelper.FindMatches(m_StyleMatchingContext, m_TempMatchResults);

                ProcessMatchedRules(element, m_TempMatchResults);

                ResolveInheritance(element);

                m_StyleMatchingContext.currentElement = null;
                m_TempMatchResults.Clear();
            }
            else
            {
                m_StyleMatchingContext.inheritedStyle  = element.propagatedStyle;
                m_StyleMatchingContext.variableContext = element.variableContext;
            }

            // Need to send the custom styles event after the inheritance is resolved because an element
            // may want to read standard styles too (TextInputFieldBase callback depends on it).
            if (updateElement && (originalCustomStyleCount > 0 || element.specifiedStyle.customPropertiesCount > 0))
            {
                using (var evt = CustomStyleResolvedEvent.GetPooled())
                {
                    evt.target = element;
                    element.SendEvent(evt);
                }
            }

            Recurse(element, depth);

            m_StyleMatchingContext.inheritedStyle = currentInheritStyle;

            if (m_StyleMatchingContext.styleSheetStack.Count > originalStyleSheetCount)
            {
                m_StyleMatchingContext.styleSheetStack.RemoveRange(originalStyleSheetCount, m_StyleMatchingContext.styleSheetStack.Count - originalStyleSheetCount);
            }

            if (m_ProcessVarContext.count > originalVariableCount)
            {
                m_ProcessVarContext.RemoveRange(originalVariableCount, m_ProcessVarContext.count - originalVariableCount);
            }
        }
コード例 #13
0
 internal VisualElementStyleSheetSet(VisualElement element)
 {
     m_Element = element;
 }
コード例 #14
0
 public override void Init(VisualElement item)
 {
     // Do nothing here, we are using the other Init.
 }
コード例 #15
0
        private void ResolveInheritance(VisualElement element)
        {
            var specifiedStyle = element.specifiedStyle;

            var currentInheritedStyle = m_StyleMatchingContext.inheritedStyle;

            element.inheritedStyle = currentInheritedStyle;

            m_ResolveInheritData.CopyFrom(currentInheritedStyle);

            if (specifiedStyle.color.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                m_ResolveInheritData.color = specifiedStyle.color;
            }

            if (specifiedStyle.unityFont.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                m_ResolveInheritData.font = specifiedStyle.unityFont;
            }

            if (specifiedStyle.fontSize.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                // Only calculated value can be inherited
                // Thus if it's a percentage the real value needs to be propagated
                // See: https://developer.mozilla.org/en-US/docs/Web/CSS/percentage
                m_ResolveInheritData.fontSize             = new StyleLength(ComputedStyle.CalculatePixelFontSize(element));
                m_ResolveInheritData.fontSize.specificity = specifiedStyle.fontSize.specificity;
            }

            if (specifiedStyle.unityFontStyleAndWeight.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                m_ResolveInheritData.unityFontStyle = specifiedStyle.unityFontStyleAndWeight;
            }

            if (specifiedStyle.unityTextAlign.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                m_ResolveInheritData.unityTextAlign = specifiedStyle.unityTextAlign;
            }

            if (specifiedStyle.visibility.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                m_ResolveInheritData.visibility = specifiedStyle.visibility;
            }

            if (specifiedStyle.whiteSpace.specificity != StyleValueExtensions.UndefinedSpecificity)
            {
                m_ResolveInheritData.whiteSpace = specifiedStyle.whiteSpace;
            }

            if (!m_ResolveInheritData.Equals(currentInheritedStyle))
            {
                InheritedStylesData inheritData = null;
                int hash = m_ResolveInheritData.GetHashCode();
                if (!StyleCache.TryGetValue(hash, out inheritData))
                {
                    inheritData = new InheritedStylesData(m_ResolveInheritData);
                    StyleCache.SetValue(hash, inheritData);
                }

                m_StyleMatchingContext.inheritedStyle = inheritData;
            }

            element.propagatedStyle = m_StyleMatchingContext.inheritedStyle;
        }
コード例 #16
0
        void ProcessMatchedRules(VisualElement element, List <SelectorMatchRecord> matchingSelectors)
        {
            matchingSelectors.Sort(SelectorMatchRecord.Compare);

            Int64 matchingRulesHash = element.fullTypeName.GetHashCode();

            // Let current DPI contribute to the hash so cache is invalidated when this changes
            matchingRulesHash = (matchingRulesHash * 397) ^ currentPixelsPerPoint.GetHashCode();

            int oldVariablesHash      = m_StyleMatchingContext.variableContext.GetVariableHash();
            int customPropertiesCount = 0;

            foreach (var record in matchingSelectors)
            {
                StyleRule rule        = record.complexSelector.rule;
                int       specificity = record.complexSelector.specificity;
                matchingRulesHash = (matchingRulesHash * 397) ^ rule.GetHashCode();
                matchingRulesHash = (matchingRulesHash * 397) ^ specificity;

                if (rule.customPropertiesCount > 0)
                {
                    customPropertiesCount += rule.customPropertiesCount;
                    ProcessMatchedVariables(record.sheet, rule);
                }
            }

            int variablesHash = customPropertiesCount > 0 ? m_ProcessVarContext.GetVariableHash() : oldVariablesHash;

            matchingRulesHash = (matchingRulesHash * 397) ^ variablesHash;

            if (oldVariablesHash != variablesHash)
            {
                StyleVariableContext ctx;
                if (!StyleCache.TryGetValue(variablesHash, out ctx))
                {
                    ctx = new StyleVariableContext(m_ProcessVarContext);
                    StyleCache.SetValue(variablesHash, ctx);
                }

                m_StyleMatchingContext.variableContext = ctx;
            }
            element.variableContext = m_StyleMatchingContext.variableContext;

            VisualElementStylesData resolvedStyles;

            if (StyleCache.TryGetValue(matchingRulesHash, out resolvedStyles))
            {
                element.SetSharedStyles(resolvedStyles);
            }
            else
            {
                resolvedStyles = new VisualElementStylesData(isShared: true);

                foreach (var record in matchingSelectors)
                {
                    m_StylePropertyReader.SetContext(record.sheet, record.complexSelector, m_StyleMatchingContext.variableContext);
                    resolvedStyles.ApplyProperties(m_StylePropertyReader, m_StyleMatchingContext.inheritedStyle);
                }

                resolvedStyles.ApplyLayoutValues();

                StyleCache.SetValue(matchingRulesHash, resolvedStyles);

                element.SetSharedStyles(resolvedStyles);
            }
        }
コード例 #17
0
 bool ShouldSkipElement(VisualElement element)
 {
     return(!m_ParentList.Contains(element) && !m_UpdateList.Contains(element));
 }
コード例 #18
0
        public static void BuildInspectorPropertiesElement(string elementPath, IEditorContainer editor, System.Collections.Generic.HashSet <System.Type> usedComponents, SerializedProperty obj, UnityEngine.UIElements.VisualElement container, bool noFields, System.Action <int, PropertyField> onBuild = null)
        {
            obj = obj.Copy();
            container.Clear();
            var source = obj.Copy();
            SerializedProperty iterator = obj;

            if (iterator.NextVisible(true) == false)
            {
                return;
            }
            if (iterator.NextVisible(true) == false)
            {
                return;
            }
            var depth        = iterator.depth;
            var i            = 0;
            var iteratorNext = iterator.Copy();

            do
            {
                if (string.IsNullOrEmpty(elementPath) == false)
                {
                    iterator = iteratorNext.FindPropertyRelative(elementPath);
                }
                else
                {
                    iterator = iteratorNext;
                }
                if (iterator.propertyType != SerializedPropertyType.ManagedReference)
                {
                    continue;
                }

                var element = new VisualElement();
                element.AddToClassList("element");

                var itCopy = iterator.Copy();
                GetTypeFromManagedReferenceFullTypeName(iterator.managedReferenceFullTypename, out var type);
                element.AddToClassList(i % 2 == 0 ? "even" : "odd");
                element.RegisterCallback <UnityEngine.UIElements.ContextClickEvent, int>((evt, idx) => {
                    var menu = new GenericMenu();
                    if (usedComponents != null)
                    {
                        menu.AddItem(new GUIContent("Delete"), false, () => {
                            RemoveComponent((DataConfigEditor)editor, usedComponents, source, type, noFields);
                            editor.Save();
                            BuildInspectorProperties(editor, usedComponents, source, container, noFields);
                        });

                        menu.AddItem(new GUIContent("Copy JSON"), false, () => {
                            var instance = itCopy.GetValue();
                            var json     = JsonUtility.ToJson(instance, true);
                            EditorGUIUtility.systemCopyBuffer = json;
                        });
                    }

                    editor.OnComponentMenu(menu, idx);
                    menu.ShowAsContext();
                }, i);

                if (type != null && usedComponents?.Contains(type) == false)
                {
                    usedComponents?.Add(type);
                }
                if (type == null)
                {
                    var label = new UnityEngine.UIElements.Label("MISSING: " + iterator.managedReferenceFullTypename);
                    element.name = "missing";
                    label.AddToClassList("inner-element");
                    label.AddToClassList("missing-label");
                    element.Add(label);
                }
                else if (iterator.hasVisibleChildren == false || noFields == true)
                {
                    var horizontal = new UnityEngine.UIElements.VisualElement();
                    horizontal.AddToClassList("inner-element");
                    horizontal.AddToClassList("no-fields-container");
                    element.name = type.Name;

                    var toggle = new UnityEngine.UIElements.Toggle();
                    toggle.AddToClassList("no-fields-toggle");
                    toggle.SetEnabled(false);
                    toggle.SetValueWithoutNotify(true);
                    horizontal.Add(toggle);

                    var label = new UnityEngine.UIElements.Label(GUILayoutExt.GetStringCamelCaseSpace(type.Name));
                    label.AddToClassList("no-fields-label");
                    horizontal.Add(label);

                    element.Add(horizontal);
                }
                else
                {
                    var label = GUILayoutExt.GetStringCamelCaseSpace(type.Name);
                    if (iterator.hasVisibleChildren == true)
                    {
                        var childs = iterator.Copy();
                        //var height = EditorUtilities.GetPropertyHeight(childs, true, new GUIContent(label));
                        var cnt = EditorUtilities.GetPropertyChildCount(childs);
                        if (cnt == 1 /*&& height <= 22f*/)
                        {
                            iterator.NextVisible(true);
                        }
                    }

                    var propertyField = new PropertyField(iterator.Copy(), label);
                    propertyField.BindProperty(iterator);
                    onBuild?.Invoke(i, propertyField);
                    propertyField.AddToClassList("property-field");
                    propertyField.AddToClassList("inner-element");
                    element.name = type.Name;
                    element.Add(propertyField);
                }

                if (type != null)
                {
                    var helps = type.GetCustomAttributes(typeof(ComponentHelpAttribute), false);
                    if (helps.Length > 0)
                    {
                        var label = new UnityEngine.UIElements.Label(((ComponentHelpAttribute)helps[0]).comment);
                        label.AddToClassList("comment");
                        element.Add(label);
                    }

                    if (typeof(IComponentStatic).IsAssignableFrom(type) == true)
                    {
                        var label = new UnityEngine.UIElements.Label("Static");
                        label.AddToClassList("static-component");
                        element.AddToClassList("has-static-component");
                        element.Add(label);
                    }

                    if (typeof(IComponentShared).IsAssignableFrom(type) == true)
                    {
                        var label = new UnityEngine.UIElements.Label("Shared");
                        label.AddToClassList("shared-component");
                        element.AddToClassList("has-shared-component");
                        element.Add(label);
                    }
                }

                container.Add(element);
                ++i;
            } while (iteratorNext.NextVisible(false) == true && depth <= iteratorNext.depth);
        }
コード例 #19
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="root">The root of the element tree for which we want to build a focus ring.</param>
 /// <param name="dfo">Default ordering of the elements in the ring.</param>
 public VisualElementFocusRing(VisualElement root, DefaultFocusOrder dfo = DefaultFocusOrder.ChildOrder)
 {
     defaultFocusOrder = dfo;
     this.root         = root;
     m_FocusRing       = new List <FocusRingRecord>();
 }
コード例 #20
0
        public static VisualElement CreateVisualElement(XmlNode node)
        {
            if (node == null)
            {
                throw new Exception("Node is null");
            }

            // Debug.Log($"Looking for type: {node.Name.Replace("ui:", "")}");
            Type elementType = Array.Find(typeof(VisualElement).Assembly.GetTypes(), x =>
                                          x.Name.Equals(node.Name.Replace("ui:", "")));

            if (elementType == null)
            {
                if (!node.Name.Replace("ui:", "").Equals("Style"))
                {
                    Debug.Log($"Couldn't find type \"{node.Name.Replace("ui:", "")}\"\nSkipping...");
                }

                return(null);
            }

            VisualElement element = (VisualElement)typeof(VisualElement).GetMethod("CreateUnityType")
                                    ?.MakeGenericMethod(elementType)
                                    .Invoke(null, new object[] { new object[] { } });

            // Debug.Log("Creating element..");

            if (node.Attributes != null)
            {
                foreach (XmlAttribute attr in node.Attributes)
                {
                    // Debug.Log("Parsing Attribute");

                    var property = elementType.GetProperty(MapCssName(attr.Name));

                    if (attr.Name.Equals("class"))
                    {
                        //Debug.Log("Class found with value: " + attr.Value);
                        element?.AddToClassList(attr.Value);
                    }

                    if (property == null)
                    {
                        if (!attr.Name.Equals("class"))
                        {
                            Debug.Log($"Skipping attribute \"{attr.Name}\"");
                        }

                        // throw new Exception($"No property found with name \"{attr.Name}\"");
                        continue;
                    }

                    if (property.PropertyType.IsEnum)
                    {
                        property.SetValue(element, Enum.Parse(property.PropertyType, attr.Value));
                        continue;
                    }

                    switch (property.PropertyType.Name)
                    {
                    case "Boolean":
                        // Debug.Log($"Parsing Boolean: {attr.Value}");
                        property.SetValue(element, bool.Parse(attr.Value));
                        break;

                    case "String":
                        // Debug.Log($"Parsing String: {attr.Value}");
                        property.SetValue(element, attr.Value);
                        break;

                    case "IStyle":
                        // Debug.Log("Parsing IStyle");
                        element = ParseStyle(attr.Value, element);
                        break;

                    default:
                        throw new Exception($"Found no matching type to {property.PropertyType.FullName}");
                    }
                }
            }


            VisualElement resultElement = element;

            foreach (XmlNode child in node.ChildNodes)
            {
                var parsedChild = CreateVisualElement(child);
            }

            return(resultElement);
        }
コード例 #21
0
 public void AddChangedElement(VisualElement ve)
 {
     m_UpdateList.Add(ve);
     PropagateToChildren(ve);
     PropagateToParents(ve);
 }