Beispiel #1
0
        public static string ToUssString(StyleSheet sheet, UssExportOptions options = null)
        {
            if (options == null)
            {
                options = new UssExportOptions();
            }

            var sb = new StringBuilder();

            if (sheet.complexSelectors != null)
            {
                for (var complexSelectorIndex = 0; complexSelectorIndex < sheet.complexSelectors.Length; ++complexSelectorIndex)
                {
                    var complexSelector = sheet.complexSelectors[complexSelectorIndex];

                    // Omit special selection rule.
                    if (complexSelector.selectors.Length > 0 &&
                        complexSelector.selectors[0].parts.Length > 0 &&
                        (complexSelector.selectors[0].parts[0].value == BuilderConstants.SelectedStyleSheetSelectorName ||
                         complexSelector.selectors[0].parts[0].value.StartsWith(BuilderConstants.StyleSelectorElementName)
                        ))
                    {
                        continue;
                    }

                    ToUssString(sheet, options, complexSelector, sb);
                    if (complexSelectorIndex != sheet.complexSelectors.Length - 1)
                    {
                        sb.Append(BuilderConstants.NewlineCharFromEditorSettings);
                    }
                }
            }

            return(sb.ToString());
        }
        VisualElement GeneratedMatchingSelectors()
        {
            m_MatchingSelectors.GetElementMatchers();
            if (m_MatchingSelectors.matchedRulesExtractor.selectedElementRules == null ||
                m_MatchingSelectors.matchedRulesExtractor.selectedElementRules.Count <= 0)
            {
                return(null);
            }

            var container = new VisualElement();

            int ruleIndex = 0;
            var options   = new UssExportOptions();
            var sb        = new StringBuilder();

            foreach (var rule in m_MatchingSelectors.matchedRulesExtractor.selectedElementRules)
            {
                var selectorStr = StyleSheetToUss.ToUssSelector(rule.matchRecord.complexSelector);

                StyleProperty[] props       = rule.matchRecord.complexSelector.rule.properties;
                var             ruleFoldout = new PersistedFoldout()
                {
                    value       = false,
                    text        = selectorStr,
                    viewDataKey = "builder-inspector-rule-foldout__" + ruleIndex
                };
                ruleIndex++;
                container.Add(ruleFoldout);

                if (props.Length == 0)
                {
                    var label = new Label("None");
                    label.AddToClassList(BuilderConstants.InspectorEmptyFoldoutLabelClassName);
                    ruleFoldout.Add(label);
                    continue;
                }

                for (int j = 0; j < props.Length; j++)
                {
                    sb.Clear();
                    StyleSheetToUss.ToUssString(rule.matchRecord.sheet, options, props[j], sb);
                    string s = sb.ToString();

                    s = s?.ToLower();
                    var textField = new TextField(props[j].name)
                    {
                        value = s
                    };
                    textField.isReadOnly = true;
                    ruleFoldout.Add(textField);
                }
            }

            return(container);
        }
Beispiel #3
0
        public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleComplexSelector complexSelector, StringBuilder sb)
        {
            foreach (var selector in complexSelector.selectors)
            {
                ToUssString(selector.previousRelationship, selector.parts, sb);
            }

            sb.Append(" {\n");

            ToUssString(sheet, options, complexSelector.rule, sb);

            sb.Append("}");
            sb.Append("\n");
        }
        public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleComplexSelector complexSelector, StringBuilder sb)
        {
            foreach (var selector in complexSelector.selectors)
            {
                ToUssString(selector.previousRelationship, selector.parts, sb);
            }

            sb.Append(" {");
            sb.Append(BuilderConstants.newlineCharFromEditorSettings);

            ToUssString(sheet, options, complexSelector.rule, sb);

            sb.Append("}");
            sb.Append(BuilderConstants.newlineCharFromEditorSettings);
        }
 public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleProperty property, StringBuilder sb)
 {
     if (property.name == "cursor" && property.values.Length > 1 && !property.IsVariable())
     {
         for (var i = 0; i < property.values.Length; i++)
         {
             var propertyValueStr = ValueHandleToUssString(sheet, options, property.name, property.values[i]);
             sb.Append(" ");
             sb.Append(propertyValueStr);
         }
     }
     else
     {
         var valueIndex = 0;
         sb.Append(" ");
         ValueHandlesToUssString(sb, sheet, options, property.name, property.values, ref valueIndex);
     }
 }
        public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleRule rule, StringBuilder sb)
        {
            foreach (var property in rule.properties)
            {
                if (property.name == BuilderConstants.SelectedStyleRulePropertyName)
                {
                    continue;
                }

                sb.Append(options.propertyIndent);
                sb.Append(property.name);
                sb.Append(":");

                ToUssString(sheet, options, property, sb);
                sb.Append(";");
                sb.Append(BuilderConstants.newlineCharFromEditorSettings);
            }
        }
Beispiel #7
0
 public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleProperty property, StringBuilder sb)
 {
     if (property.name == "cursor" && property.values.Length > 1)
     {
         int    i;
         string propertyValueStr;
         for (i = 0; i < property.values.Length - 1; i++)
         {
             propertyValueStr = ValueHandleToUssString(sheet, options, property.name, property.values[i]);
             sb.Append(" ");
             sb.Append(propertyValueStr);
         }
         sb.Append(", ");
         propertyValueStr = ValueHandleToUssString(sheet, options, property.name, property.values[i]);
         sb.Append(propertyValueStr);
     }
     else
     {
         var valueIndex = 0;
         sb.Append(" ");
         ValueHandlesToUssString(sb, sheet, options, property.name, property.values, ref valueIndex);
     }
 }
Beispiel #8
0
        public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleRule rule, StringBuilder sb)
        {
            foreach (var property in rule.properties)
            {
                if (property.name == BuilderConstants.SelectedStyleRulePropertyName)
                {
                    continue;
                }

                sb.Append(options.propertyIndent);
                sb.Append(property.name);
                sb.Append(":");
                if (property.name == "cursor" && property.values.Length > 1)
                {
                    int    i;
                    string propertyValueStr;
                    for (i = 0; i < property.values.Length - 1; i++)
                    {
                        propertyValueStr = ValueHandleToUssString(sheet, options, property.name, property.values[i]);
                        sb.Append(" ");
                        sb.Append(propertyValueStr);
                    }
                    sb.Append(", ");
                    propertyValueStr = ValueHandleToUssString(sheet, options, property.name, property.values[i]);
                    sb.Append(propertyValueStr);
                }
                else
                {
                    var valueIndex = 0;
                    sb.Append(" ");
                    ValueHandlesToUssString(sb, sheet, options, property.name, property.values, ref valueIndex);
                }

                sb.Append(";\n");
            }
        }
        public static string ValueHandleToUssString(StyleSheet sheet, UssExportOptions options, string propertyName, StyleValueHandle handle)
        {
            string str = "";

            switch (handle.valueType)
            {
            case StyleValueType.Keyword:
                str = sheet.ReadKeyword(handle).ToString().ToLower();
                break;

            case StyleValueType.Float:
            {
                var num = sheet.ReadFloat(handle);
                if (num == 0)
                {
                    str = "0";
                }
                else
                {
                    str = num.ToString(CultureInfo.InvariantCulture.NumberFormat);
                    if (IsLength(propertyName))
                    {
                        str += "px";
                    }
                }
            }
            break;

            case StyleValueType.Dimension:
                var dim = sheet.ReadDimension(handle);
                if (dim.value == 0 && !dim.unit.IsTimeUnit())
                {
                    str = "0";
                }
                else
                {
                    str = dim.ToString();
                }
                break;

            case StyleValueType.Color:
                UnityEngine.Color color = sheet.ReadColor(handle);
                str = ToUssString(color, options.useColorCode);
                break;

            case StyleValueType.ResourcePath:
                str = $"resource('{sheet.ReadResourcePath(handle)}')";
                break;

            case StyleValueType.Enum:
                str = sheet.ReadEnum(handle);
                break;

            case StyleValueType.String:
                str = $"\"{sheet.ReadString(handle)}\"";
                break;

            case StyleValueType.MissingAssetReference:
                str = $"url('{sheet.ReadMissingAssetReferenceUrl(handle)}')";
                break;

            case StyleValueType.AssetReference:
                var assetRef = sheet.ReadAssetReference(handle);
                str = GetPathValueFromAssetRef(assetRef);
                break;

            case StyleValueType.Variable:
                str = sheet.ReadVariable(handle);
                break;

            case StyleValueType.ScalableImage:
                var image       = sheet.ReadScalableImage(handle);
                var normalImage = image.normalImage;
                str = GetPathValueFromAssetRef(normalImage);
                break;

            default:
                throw new ArgumentException("Unhandled type " + handle.valueType);
            }
            return(str);
        }
 public static void WriteStyleSheet(StyleSheet sheet, string path, UssExportOptions options = null)
 {
     File.WriteAllText(path, ToUssString(sheet, options));
 }
 public UssExportOptions(UssExportOptions opts)
     : base()
 {
     propertyIndent      = opts.propertyIndent;
     exportDefaultValues = opts.exportDefaultValues;
 }
        public static void ValueHandlesToUssString(StringBuilder sb, StyleSheet sheet, UssExportOptions options, string propertyName, StyleValueHandle[] values, ref int valueIndex, int valueCount = -1)
        {
            for (; valueIndex < values.Length && valueCount != 0; --valueCount)
            {
                var propertyValue = values[valueIndex++];
                switch (propertyValue.valueType)
                {
                case StyleValueType.Function:
                    // First param: function name
                    sb.Append(sheet.ReadFunctionName(propertyValue));
                    sb.Append("(");

                    // Second param: number of arguments
                    var nbParams = (int)sheet.ReadFloat(values[valueIndex++]);
                    ValueHandlesToUssString(sb, sheet, options, propertyName, values, ref valueIndex, nbParams);
                    sb.Append(")");

                    break;

                case StyleValueType.CommaSeparator:
                    sb.Append(",");
                    break;

                default:
                {
                    var propertyValueStr = ValueHandleToUssString(sheet, options, propertyName, propertyValue);
                    sb.Append(propertyValueStr);
                    break;
                }
                }

                if (valueIndex < values.Length && values[valueIndex].valueType != StyleValueType.CommaSeparator && valueCount != 1)
                {
                    sb.Append(" ");
                }
            }
        }
        void CloneTree()
        {
            m_Container.Clear();
            m_StyleSheetContents.Clear();
            m_VisualTreeAssetContents.Clear();

            m_Container.styleSheets.Clear();

            if (m_VisualTreeAsset != null)
            {
                m_VisualTreeAsset.LinkedCloneTree(m_Container);

                var canvas      = m_Container.Q("sample-canvas");
                var canvasAsset = canvas.GetVisualElementAsset();

                var newButton = m_VisualTreeAsset.AddElement(canvasAsset, "UnityEngine.UIElements.Button");
                newButton.AddProperty("name", "new-guy");
                newButton.AddProperty("text", "Canvas Button 2!");
                newButton.AddStyleClass("new-guy-type");
                newButton.AddStyleClass("some-button");
                newButton.RemoveStyleClass("some-button");
                newButton.AddStyleClass("some-fancy-button");
                { // Add max-width to newButton.
                    var rule = m_VisualTreeAsset.GetOrCreateInlineStyleRule(newButton);
                    var prop = m_VisualTreeAsset.inlineSheet.AddProperty(rule, "max-width");
                    var val  = m_VisualTreeAsset.inlineSheet.AddValue(prop, 200);
                }

                { // Add max-width to canvas.
                    var rule = m_VisualTreeAsset.GetOrCreateInlineStyleRule(canvasAsset);
                    var prop = m_VisualTreeAsset.inlineSheet.AddProperty(rule, "max-width");
                    var val  = m_VisualTreeAsset.inlineSheet.AddValue(prop, 500);
                }
                { // Change border of canvas.
                    var rule = m_VisualTreeAsset.GetOrCreateInlineStyleRule(canvasAsset);
                    var prop = m_VisualTreeAsset.inlineSheet.FindLastProperty(rule, "border-width");
                    m_VisualTreeAsset.inlineSheet.SetValue(prop.values[0], 10);
                }
                { // Remove max-width
                    var rule = m_VisualTreeAsset.GetOrCreateInlineStyleRule(canvasAsset);
                    var prop = m_VisualTreeAsset.inlineSheet.FindLastProperty(rule, "max-width");
                    m_VisualTreeAsset.inlineSheet.RemoveProperty(rule, prop);
                }

                var newButton2 = m_VisualTreeAsset.AddElement(canvasAsset, "UnityEngine.UIElements.Button");
                m_VisualTreeAsset.RemoveElement(newButton2);

                var newInstance = m_VisualTreeAsset.AddTemplateInstance(canvasAsset, "SampleSection");
                newInstance.SetAttributeOverride("section-text-field", "label", "label programmatically written!");
                newInstance.SetAttributeOverride("section-text-field", "text", "text programmatically written!");
                newInstance.RemoveAttributeOverride("section-text-field", "text");
                newInstance.AddStyleSheetPath(s_CanvasInstanceUSSPath);

                var overriddenSection = m_VisualTreeAsset.FindElementByName("overridden-section");
                if (overriddenSection != null)
                {
                    overriddenSection.RemoveStyleSheetPath(s_CanvasInstanceUSSPath);
                }

                // Add UXML string.
                var uxmlString = m_VisualTreeAsset.GenerateUXML(null);
                m_VisualTreeAssetContents.Add(new Label(uxmlString));

                // Add inline stylesheet.
                var inlineBuilder = new StringBuilder();
                foreach (var rule in m_VisualTreeAsset.inlineSheet.rules)
                {
                    inlineBuilder.Append("{\n");

                    var exportOptions = new UssExportOptions();
                    StyleSheetToUss.ToUssString(m_VisualTreeAsset.inlineSheet, exportOptions, rule, inlineBuilder);

                    inlineBuilder.Append("}\n");
                }
                var inlineStyleSheetString = inlineBuilder.ToString();
                m_VisualTreeAssetContents.Add(new Label(inlineStyleSheetString));

                m_Container.Clear();
                m_VisualTreeAsset.LinkedCloneTree(m_Container);
            }

            if (m_StyleSheet != null)
            {
                // Add width
                //var firstSelector = m_StyleSheet.complexSelectors.First();
                //var firstSelector = m_StyleSheet.FindSelector(".blue#red > .green .pink");
                var firstSelector = m_StyleSheet.FindSelector(".unity-button");
                if (firstSelector != null)
                {
                    var widthProperty = m_StyleSheet.AddProperty(firstSelector, "width");
                    var widthValue    = m_StyleSheet.AddValue(widthProperty, 62);
                    m_StyleSheet.SetValue(widthValue, 82);
                    m_StyleSheet.RemoveProperty(firstSelector, widthProperty);

                    var borderWidthProperty = m_StyleSheet.AddProperty(firstSelector, "border-width");
                    m_StyleSheet.AddValue(borderWidthProperty, 1);
                    m_StyleSheet.AddValue(borderWidthProperty, 2);
                    m_StyleSheet.AddValue(borderWidthProperty, 5);
                    var leftBorderWidthValue = m_StyleSheet.AddValue(borderWidthProperty, 8);
                    m_StyleSheet.RemoveValue(borderWidthProperty, leftBorderWidthValue);

                    var borderColorProperty = m_StyleSheet.AddProperty(firstSelector, "border-color");
                    var borderColorValue    = m_StyleSheet.AddValue(borderColorProperty, Color.red);
                    m_StyleSheet.SetValue(borderColorValue, Color.green);
                }

                var newSelector = m_StyleSheet.AddSelector(".unity-button Label");
                {
                    var widthProperty = m_StyleSheet.AddProperty(newSelector, "width");
                    var widthValue    = m_StyleSheet.AddValue(widthProperty, 62);
                    m_StyleSheet.SetValue(widthValue, 82);
                }

                //

                // Add USS contents.
                //var selectorStrings = m_StyleSheet.GetSelectorStrings();
                //foreach (var selectorString in selectorStrings)
                //m_StyleSheetContents.Add(new Label(selectorString));

                // Add USS string.
                var ussString = m_StyleSheet.GenerateUSS();
                m_StyleSheetContents.Add(new Label(ussString));

                //m_Container.styleSheets.Add(m_StyleSheet);
            }
        }
Beispiel #14
0
        public static string ValueHandleToUssString(StyleSheet sheet, UssExportOptions options, string propertyName, StyleValueHandle handle)
        {
            string str = "";

            switch (handle.valueType)
            {
            case StyleValueType.Keyword:
                str = sheet.ReadKeyword(handle).ToString().ToLower();
                break;

            case StyleValueType.Float:
            {
                var num = sheet.ReadFloat(handle);
                if (num == 0)
                {
                    str = "0";
                }
                else
                {
                    str = num.ToString(CultureInfo.InvariantCulture.NumberFormat);
                    if (IsLength(propertyName))
                    {
                        str += "px";
                    }
                }
            }
            break;

            case StyleValueType.Dimension:
                var dim = sheet.ReadDimension(handle);
                if (dim.value == 0)
                {
                    str = "0";
                }
                else
                {
                    str = dim.ToString();
                }
                break;

            case StyleValueType.Color:
                UnityEngine.Color color = sheet.ReadColor(handle);
                str = ToUssString(color, options.useColorCode);
                break;

            case StyleValueType.ResourcePath:
                str = $"resource('{sheet.ReadResourcePath(handle)}')";
                break;

            case StyleValueType.Enum:
                str = sheet.ReadEnum(handle);
                break;

            case StyleValueType.String:
                str = $"\"{sheet.ReadString(handle)}\"";
                break;

#if UNITY_2020_2_OR_NEWER
            case StyleValueType.MissingAssetReference:
                str = $"url('{sheet.ReadMissingAssetReferenceUrl(handle)}')";
                break;
#endif
            case StyleValueType.AssetReference:
                var assetRef  = sheet.ReadAssetReference(handle);
                var assetPath = AssetDatabase.GetAssetPath(assetRef);
                if (assetPath.StartsWith("Assets") || assetPath.StartsWith("Packages"))
                {
                    assetPath = "/" + assetPath;
                }
                str = assetRef == null ? "none" : $"url('{assetPath}')";
                break;

            case StyleValueType.Variable:
                str = sheet.ReadVariable(handle);
                break;

            default:
                throw new ArgumentException("Unhandled type " + handle.valueType);
            }
            return(str);
        }
        static void GenerateUXMLRecursive(
            VisualTreeAsset vta, string vtaPath, VisualElementAsset root,
            Dictionary <int, List <VisualElementAsset> > idToChildren,
            StringBuilder stringBuilder, int depth, bool writingToFile)
        {
            Indent(stringBuilder, depth);

            stringBuilder.Append("<");
            AppendElementTypeName(root, stringBuilder);

            // Add all non-style attributes.
            AppendElementNonStyleAttributes(root, stringBuilder, writingToFile);

            // Add style classes to class attribute.
            if (root.classes != null && root.classes.Length > 0)
            {
                stringBuilder.Append(" class=\"");
                for (int i = 0; i < root.classes.Length; i++)
                {
                    if (i > 0)
                    {
                        stringBuilder.Append(" ");
                    }

                    stringBuilder.Append(root.classes[i]);
                }
                stringBuilder.Append("\"");
            }

            // Add inline StyleSheet attribute.
            if (root.ruleIndex != -1)
            {
                if (vta.inlineSheet == null)
                {
                    Debug.LogWarning("VisualElementAsset has a RuleIndex but no inlineStyleSheet");
                }
                else
                {
                    StyleRule r = vta.inlineSheet.rules[root.ruleIndex];

                    if (r.properties != null && r.properties.Length > 0)
                    {
                        var ruleBuilder   = new StringBuilder();
                        var exportOptions = new UssExportOptions();
                        exportOptions.propertyIndent = string.Empty;
                        StyleSheetToUss.ToUssString(vta.inlineSheet, exportOptions, r, ruleBuilder);
                        var ruleStr = ruleBuilder.ToString();

                        // Need to remove newlines here before we give it to
                        // AppendElementAttribute() so we don't add "&#10;" everywhere.
                        ruleStr = ruleStr.Replace("\n", " ");
                        ruleStr = ruleStr.Replace("\r", "");
                        ruleStr = ruleStr.Trim();

                        AppendElementAttribute("style", ruleStr, stringBuilder);
                    }
                }
            }

            // If we have no children, avoid adding the full end tag and just end the open tag.
            bool hasChildTags = false;

            // Add special children.
            // TODO: What's the difference between these two ifdef options?
#if false
            var styleSheets = root.stylesheets;
            if (styleSheets != null && styleSheets.Count > 0)
            {
                bool newLineAdded = false;

                foreach (var styleSheet in styleSheets)
                {
                    var path = AssetDatabase.GetAssetPath(styleSheet);
                    ProcessStyleSheetPath(
                        vtaPath,
                        path, stringBuilder, depth,
                        ref newLineAdded, ref hasChildTags);
                }
            }
#else
            var styleSheetPaths = root.GetStyleSheetPaths();
            if (styleSheetPaths != null && styleSheetPaths.Count > 0)
            {
                bool newLineAdded = false;

                foreach (var path in styleSheetPaths)
                {
                    ProcessStyleSheetPath(
                        vtaPath,
                        path, stringBuilder, depth,
                        ref newLineAdded, ref hasChildTags);
                }
            }
#endif

            var templateAsset = root as TemplateAsset;
            if (templateAsset != null && templateAsset.attributeOverrides != null && templateAsset.attributeOverrides.Count > 0)
            {
                if (!hasChildTags)
                {
                    stringBuilder.Append(">");
                    stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
                }

                var overridesMap = new Dictionary <string, List <TemplateAsset.AttributeOverride> >();
                foreach (var attributeOverride in templateAsset.attributeOverrides)
                {
                    if (!overridesMap.ContainsKey(attributeOverride.m_ElementName))
                    {
                        overridesMap.Add(attributeOverride.m_ElementName, new List <TemplateAsset.AttributeOverride>());
                    }

                    overridesMap[attributeOverride.m_ElementName].Add(attributeOverride);
                }
                foreach (var attributeOverridePair in overridesMap)
                {
                    var elementName = attributeOverridePair.Key;
                    var overrides   = attributeOverridePair.Value;

                    Indent(stringBuilder, depth + 1);
                    stringBuilder.Append("<AttributeOverrides");
                    AppendElementAttribute("element-name", elementName, stringBuilder);

                    foreach (var attributeOverride in overrides)
                    {
                        AppendElementAttribute(attributeOverride.m_AttributeName, attributeOverride.m_Value, stringBuilder);
                    }

                    stringBuilder.Append(" />");
                    stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
                }

                hasChildTags = true;
            }

            // Iterate through child elements.
            List <VisualElementAsset> children;
            if (idToChildren != null && idToChildren.TryGetValue(root.id, out children) && children.Count > 0)
            {
                if (!hasChildTags)
                {
                    stringBuilder.Append(">");
                    stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
                }

                children.Sort(VisualTreeAssetUtilities.CompareForOrder);

                foreach (VisualElementAsset childVea in children)
                {
                    GenerateUXMLRecursive(
                        vta, vtaPath, childVea, idToChildren, stringBuilder,
                        depth + 1, writingToFile);
                }

                hasChildTags = true;
            }

            if (hasChildTags)
            {
                Indent(stringBuilder, depth);
                stringBuilder.Append("</");
                AppendElementTypeName(root, stringBuilder);
                stringBuilder.Append(">");
                stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
            }
            else
            {
                stringBuilder.Append(" />");
                stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
            }
        }