Esempio n. 1
0
        public static TemplateAsset AddTemplateInstance(
            this VisualTreeAsset vta, VisualElementAsset parent, string path)
        {
            var templateName = vta.GetTemplateNameFromPath(path);

            if (!vta.TemplateExists(templateName))
            {
                var resolvedAsset = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>(path);
                if (resolvedAsset)
                {
                    vta.RegisterTemplate(templateName, resolvedAsset);
                }
                else
                {
                    vta.RegisterTemplate(templateName, path);
                }
            }

            var templateAsset = new TemplateAsset(templateName, BuilderConstants.UxmlInstanceTypeName);

            VisualTreeAssetUtilities.InitializeElement(templateAsset);

            templateAsset.AddProperty("template", templateName);

            return(VisualTreeAssetUtilities.AddElementToDocument(vta, templateAsset, parent) as TemplateAsset);
        }
        public static void SetAttributeOverride(
            this TemplateAsset ta, string elementName, string attributeName, string value)
        {
            if (ta.attributeOverrides == null)
            {
                ta.attributeOverrides = new List <TemplateAsset.AttributeOverride>();
            }

            // See if the override already exists.
            for (int i = 0; i < ta.attributeOverrides.Count; ++i)
            {
                var over = ta.attributeOverrides[i];
                if (over.m_ElementName == elementName &&
                    over.m_AttributeName == attributeName)
                {
                    over.m_ElementName   = elementName;
                    over.m_AttributeName = attributeName;
                    over.m_Value         = value;

                    ta.attributeOverrides[i] = over;

                    return;
                }
            }

            // If the override does not exist, add it.
            var attributeOverride = new TemplateAsset.AttributeOverride();

            attributeOverride.m_ElementName   = elementName;
            attributeOverride.m_AttributeName = attributeName;
            attributeOverride.m_Value         = value;
            ta.attributeOverrides.Add(attributeOverride);
        }
Esempio n. 3
0
        public static void LoadTemplateAsset(GameObject gameObject, Package.Asset asset)
        {
            if (gameObject.GetComponent <MarkingInfo>() is not MarkingInfo markingInfo)
            {
                return;
            }

            Mod.Logger.Debug($"Start load template asset \"{asset.fullName}\" from {asset.package.packagePath}");
            try
            {
                var templateConfig = XmlExtension.Parse(markingInfo.data);
                if (TemplateAsset.FromPackage(templateConfig, asset, out TemplateAsset templateAsset))
                {
                    templateAsset.Template.Manager.AddTemplate(templateAsset.Template);
                    Mod.Logger.Debug($"Template asset loaded: {templateAsset} ({templateAsset.Flags})");
                }
                else
                {
                    Mod.Logger.Error($"Could not load template asset");
                }
            }
            catch (Exception error)
            {
                Mod.Logger.Error($"Could not load template asset", error);
            }
        }
Esempio n. 4
0
        void LoadAttributeOverridesNode(TemplateAsset templateAsset, XElement attributeOverridesElt)
        {
            var elementNameAttr = attributeOverridesElt.Attribute(k_AttributeOverridesElementNameAttr);

            if (elementNameAttr == null || String.IsNullOrEmpty(elementNameAttr.Value))
            {
                logger.LogError(ImportErrorType.Semantic, ImportErrorCode.AttributeOverridesMissingElementNameAttr, null, Error.Level.Warning, attributeOverridesElt);
                return;
            }

            foreach (var attribute in attributeOverridesElt.Attributes())
            {
                if (attribute.Name.LocalName == k_AttributeOverridesElementNameAttr)
                {
                    continue;
                }

                var attributeOverride = new TemplateAsset.AttributeOverride()
                {
                    m_ElementName   = elementNameAttr.Value,
                    m_AttributeName = attribute.Name.LocalName,
                    m_Value         = attribute.Value
                };

                templateAsset.attributeOverrides.Add(attributeOverride);
            }
        }
Esempio n. 5
0
 public static void RaiseAssetCountChanged(TemplateAsset asset)
 {
     lock (LockChangedCountItems) {
         ChangedCountItems.Add(asset);
         Timer.Change(1000, Timeout.Infinite);
     }
 }
Esempio n. 6
0
        public static bool SaveTemplateAsset(TemplateAsset templateAsset)
        {
            SingletonMod <Mod> .Logger.Debug($"Start save template asset {templateAsset}");

            try
            {
                var meta = new CustomAssetMetaData()
                {
                    name      = $"{templateAsset.Template.Name}_{Guid.NewGuid().Unique()}",
                    timeStamp = DateTime.Now,
                    type      = CustomAssetMetaData.Type.Unknown,
                    dlcMask   = SteamHelper.DLC_BitMask.None,
                    steamTags = new string[] { "Marking" },
                    guid      = templateAsset.Template.Id.ToString(),
                };

                var package = new Package(templateAsset.IsWorkshop ? templateAsset.WorkshopId.ToString() : meta.name)
                {
                    packageMainAsset = meta.name,
                    packageAuthor    = $"steamid:{TemplateManager.UserId}",
                };

                var gameObject  = new GameObject(typeof(MarkingInfo).Name);
                var markingInfo = gameObject.AddComponent <MarkingInfo>();
                markingInfo.data = GetString(templateAsset.Template.ToXml());
                meta.assetRef    = package.AddAsset($"{meta.name}_Data", markingInfo.gameObject);

                if (templateAsset.Preview is Image image)
                {
                    meta.imageRef = package.AddAsset(templateAsset.MetaPreview, image, false, Image.BufferFileFormat.PNG, false, false);
                }

                if (templateAsset.SeparatePreview && templateAsset.SteamPreview is Image steamImage)
                {
                    meta.steamPreviewRef = package.AddAsset(templateAsset.MetaSteamPreview, steamImage, false, Image.BufferFileFormat.PNG, false, false);
                }
                else
                {
                    meta.steamPreviewRef = meta.imageRef;
                }

                package.AddAsset(meta.name, meta, UserAssetType.CustomAssetMetaData);

                var path = Path.Combine(DataLocation.assetsPath, PathUtils.AddExtension(PathEscaper.Escape(templateAsset.FileName), PackageManager.packageExtension));
                package.Save(path);

                SingletonMod <Mod> .Logger.Debug($"Template asset saved to {path}");

                return(true);
            }
            catch (Exception error)
            {
                SingletonMod <Mod> .Logger.Error($"Could not save template asset", error);

                return(false);
            }
        }
Esempio n. 7
0
 private static bool ResolveType(XElement elt, VisualTreeAsset visualTreeAsset, out VisualElementAsset vea)
 {
     if (visualTreeAsset.AliasExists(elt.Name.LocalName))
     {
         vea = new TemplateAsset(elt.Name.LocalName);
     }
     else
     {
         string text = (!string.IsNullOrEmpty(elt.Name.NamespaceName)) ? (elt.Name.NamespaceName + "." + elt.Name.LocalName) : elt.Name.LocalName;
         if (text == typeof(VisualElement).FullName)
         {
             text = typeof(VisualContainer).FullName;
         }
         vea = new VisualElementAsset(text);
     }
     return(true);
 }
Esempio n. 8
0
        public bool MakeAsset(TemplateType template)
        {
            if (template.IsAsset)
            {
                return(true);
            }

            var asset = new TemplateAsset(template);
            var saved = Loader.SaveTemplateAsset(asset);

            if (saved)
            {
                Save();
            }

            return(saved);
        }
Esempio n. 9
0
        void InstantiateTemplate()
        {
            TemplateAsset template = renderer.Templates.TryGetTemplateAsset(this.type);
            var           clone    = template.Instantiate();

            // Transfer binding path to top-level children & custom classes
            if (!string.IsNullOrWhiteSpace(bindingPath))
            {
                clone.Query <TemplateContainer>().Children <BindableElement>().ForEach(x =>
                {
                    x.bindingPath = bindingPath;
                    x.AddMultipleToClassList(this.GetClasses().Where(c => c != ussClassName));
                }
                                                                                       );
            }

            Add(clone);
        }
Esempio n. 10
0
        public static TemplateAsset AddTemplateInstance(
            this VisualTreeAsset vta, VisualElementAsset parent, string path)
        {
            var templateName = vta.GetTemplateNameFromPath(path);
            if (!vta.TemplateExists(templateName))
                vta.RegisterTemplate(templateName, path);

#if UNITY_2019_4
            var templateAsset = new TemplateAsset(templateName);
#else
            var templateAsset = new TemplateAsset(templateName, BuilderConstants.UxmlInstanceTypeName);
#endif
            VisualTreeAssetUtilities.InitializeElement(templateAsset);

            templateAsset.AddProperty("template", templateName);

            return VisualTreeAssetUtilities.AddElementToDocument(vta, templateAsset, parent) as TemplateAsset;
        }
        private static VisualElementAsset ResolveType(XElement elt, VisualTreeAsset visualTreeAsset)
        {
            VisualElementAsset vea = null;

            if (elt.Name.LocalName == k_TemplateInstanceNode && elt.Name.NamespaceName == "UnityEngine.Experimental.UIElements")
            {
                XAttribute sourceAttr = elt.Attribute(k_TemplateInstanceSourceAttr);
                if (sourceAttr == null || String.IsNullOrEmpty(sourceAttr.Value))
                {
                    logger.LogError(ImportErrorType.Semantic, ImportErrorCode.TemplateInstanceHasEmptySource, null, Error.Level.Fatal, elt);
                }
                else
                {
                    string templateName = sourceAttr.Value;
                    if (!visualTreeAsset.TemplateExists(templateName))
                    {
                        logger.LogError(ImportErrorType.Semantic, ImportErrorCode.UnknownTemplate, templateName, Error.Level.Fatal, elt);
                    }
                    else
                    {
                        vea = new TemplateAsset(templateName);
                    }
                }
            }
            else
            {
                string fullName = String.IsNullOrEmpty(elt.Name.NamespaceName)
                    ? elt.Name.LocalName
                    : elt.Name.NamespaceName + "." + elt.Name.LocalName;

                // HACK: wait for Theo's PR OR go with that
                if (fullName == "UnityEngine.Experimental.UIElements.VisualContainer")
                {
                    Debug.LogWarning("VisualContainer is obsolete, use VisualElement now");
                    fullName = typeof(VisualElement).FullName;
                }

                vea = new VisualElementAsset(fullName);
            }

            return(vea);
        }
Esempio n. 12
0
        VisualElementAsset ResolveType(XElement elt, VisualTreeAsset visualTreeAsset)
        {
            VisualElementAsset vea = null;

            string elementNamespaceName = elt.Name.NamespaceName;

            if (elementNamespaceName.StartsWith("UnityEditor.Experimental.UIElements") || elementNamespaceName.StartsWith("UnityEngine.Experimental.UIElements"))
            {
                elementNamespaceName = elementNamespaceName.Replace(".Experimental.UIElements", ".UIElements");
            }

            if (elt.Name.LocalName == k_TemplateInstanceNode && elementNamespaceName == "UnityEngine.UIElements")
            {
                XAttribute sourceAttr = elt.Attribute(k_TemplateInstanceSourceAttr);
                if (sourceAttr == null || String.IsNullOrEmpty(sourceAttr.Value))
                {
                    logger.LogError(ImportErrorType.Semantic, ImportErrorCode.TemplateInstanceHasEmptySource, null, Error.Level.Fatal, elt);
                }
                else
                {
                    string templateName = sourceAttr.Value;
                    if (!visualTreeAsset.TemplateExists(templateName))
                    {
                        logger.LogError(ImportErrorType.Semantic, ImportErrorCode.UnknownTemplate, templateName, Error.Level.Fatal, elt);
                    }
                    else
                    {
                        vea = new TemplateAsset(templateName);
                    }
                }
            }
            else
            {
                string fullName = String.IsNullOrEmpty(elementNamespaceName)
                    ? elt.Name.LocalName
                    : elementNamespaceName + "." + elt.Name.LocalName;
                vea = new VisualElementAsset(fullName);
            }

            return(vea);
        }
        public static void RemoveAttributeOverride(
            this TemplateAsset ta, string elementName, string attributeName)
        {
            if (ta.attributeOverrides == null)
            {
                return;
            }

            // See if the override already exists.
            for (int i = 0; i < ta.attributeOverrides.Count; ++i)
            {
                var over = ta.attributeOverrides[i];
                if (over.m_ElementName == elementName &&
                    over.m_AttributeName == attributeName)
                {
                    ta.attributeOverrides.RemoveAt(i);

                    return;
                }
            }
        }
Esempio n. 14
0
        private static IReferenceModifier BuildReferenceModifier(TemplateAsset ta, Dictionary <string, string> replaceGuidPairDictionary, Dictionary <string, string> replaceNamePairDictionary)
        {
            if (ta.IsDummyAsset || ta.IsFolder)
            {
                return(null);
            }
            IReferenceModifier modifier = null;

            if (AssetDatabase.GetMainAssetTypeAtPath(ta.templatePath) == typeof(AnimationClip))
            {
                modifier = new AnimationClipReferenceModifier(replaceNamePairDictionary);
            }
            else if (Path.GetExtension(ta.templatePath).Equals(".fbx", StringComparison.OrdinalIgnoreCase))
            {
                modifier = new FbxReferenceModifier(replaceGuidPairDictionary);
            }
            else
            {
                modifier = new GuidReferenceModifier(replaceGuidPairDictionary);
            }
            return(modifier);
        }
Esempio n. 15
0
        void LoadAttributeOverridesNode(TemplateAsset templateAsset, XElement attributeOverridesElt, VisualTreeAsset vta)
        {
            var elementNameAttr = attributeOverridesElt.Attribute(k_AttributeOverridesElementNameAttr);

            if (elementNameAttr == null || String.IsNullOrEmpty(elementNameAttr.Value))
            {
                LogWarning(vta, ImportErrorType.Semantic, ImportErrorCode.AttributeOverridesMissingElementNameAttr, null, attributeOverridesElt);
                return;
            }

            foreach (var attribute in attributeOverridesElt.Attributes())
            {
                string attributeName = attribute.Name.LocalName;
                if (attributeName == k_AttributeOverridesElementNameAttr)
                {
                    continue;
                }

                if (attributeName == k_ClassAttr ||
                    attributeName == k_StyleAttr ||
                    attributeName == nameof(VisualElement.name))
                {
                    LogWarning(vta, ImportErrorType.Semantic, ImportErrorCode.AttributeOverridesInvalidAttr, attributeName, attributeOverridesElt);
                    continue;
                }

                var attributeOverride = new TemplateAsset.AttributeOverride()
                {
                    m_ElementName   = elementNameAttr.Value,
                    m_AttributeName = attribute.Name.LocalName,
                    m_Value         = attribute.Value
                };

                templateAsset.attributeOverrides.Add(attributeOverride);
            }
        }
Esempio n. 16
0
        private static bool ResolveType(XElement elt, VisualTreeAsset visualTreeAsset, out VisualElementAsset vea)
        {
            string fullName;

            if (visualTreeAsset.AliasExists(elt.Name.LocalName))
            {
                vea = new TemplateAsset(elt.Name.LocalName);
            }
            else
            {
                fullName = String.IsNullOrEmpty(elt.Name.NamespaceName)
                    ? elt.Name.LocalName
                    : elt.Name.NamespaceName + "." + elt.Name.LocalName;

                // HACK: wait for Theo's PR OR go with that
                if (fullName == typeof(VisualElement).FullName)
                {
                    fullName = typeof(VisualContainer).FullName;
                }
                vea = new VisualElementAsset(fullName);
            }

            return(true);
        }
        public static bool OpenAsSubDocument(BuilderPaneWindow paneWindow, VisualTreeAsset vta, TemplateAsset vea = null)
        {
            bool didSaveChanges = paneWindow.document.CheckForUnsavedChanges();

            if (!didSaveChanges)
            {
                return(false);
            }

            // This is important because if the user chose to not save changes to the
            // parent document, we restore the VTA from backup. The problem with that
            // is that the backup VTA was made before we fixed any USS assignments on
            // root elements. This is fine when simply restoring the backup before a
            // File > New or switching documents (just prior to closing the current document),
            // but this is not ok here because we need the parent document to continue
            // staying open and usable in the UI Builder.
            paneWindow.document.activeOpenUXMLFile.PostLoadDocumentStyleSheetCleanup();

            paneWindow.document.AddSubDocument(vea);
            paneWindow.LoadDocument(vta, false);

            return(true);
        }
Esempio n. 18
0
        private static bool ParseAttributes(XElement elt, VisualElementAsset res, StyleSheetBuilder ssb, VisualTreeAsset vta, VisualElementAsset parent)
        {
            res.name = "_" + res.GetType().Name;
            bool result = false;

            foreach (XAttribute current in elt.Attributes())
            {
                string localName = current.Name.LocalName;
                switch (localName)
                {
                case "name":
                    res.name = current.Value;
                    continue;

                case "text":
                    res.text = current.Value;
                    continue;

                case "class":
                    res.classes = current.Value.Split(new char[]
                    {
                        ' '
                    });
                    continue;

                case "contentContainer":
                    if (vta.contentContainerId != 0)
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.DuplicateContentContainer, null, UIElementsViewImporter.Error.Level.Fatal, elt);
                        continue;
                    }
                    vta.contentContainerId = res.id;
                    continue;

                case "slot-name":
                    if (string.IsNullOrEmpty(current.Value))
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.SlotDefinitionHasEmptyName, null, UIElementsViewImporter.Error.Level.Fatal, elt);
                    }
                    else if (!vta.AddSlotDefinition(current.Value, res.id))
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.DuplicateSlotDefinition, current.Value, UIElementsViewImporter.Error.Level.Fatal, elt);
                    }
                    continue;

                case "slot":
                {
                    TemplateAsset templateAsset = parent as TemplateAsset;
                    if (templateAsset == null)
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.SlotUsageInNonTemplate, parent, UIElementsViewImporter.Error.Level.Fatal, elt);
                        continue;
                    }
                    if (string.IsNullOrEmpty(current.Value))
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.SlotUsageHasEmptyName, null, UIElementsViewImporter.Error.Level.Fatal, elt);
                        continue;
                    }
                    templateAsset.AddSlotUsage(current.Value, res.id);
                    continue;
                }

                case "style":
                {
                    StyleSheet styleSheet = new Parser().Parse("* { " + current.Value + " }");
                    if (styleSheet.Errors.Count != 0)
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.InvalidCssInStyleAttribute, styleSheet.Errors.Aggregate("", (string s, StylesheetParseError error) => s + error.ToString() + "\n"), UIElementsViewImporter.Error.Level.Warning, current);
                        continue;
                    }
                    if (styleSheet.StyleRules.Count != 1)
                    {
                        UIElementsViewImporter.logger.LogError(ImportErrorType.Semantic, ImportErrorCode.InvalidCssInStyleAttribute, "Expected one style rule, found " + styleSheet.StyleRules.Count, UIElementsViewImporter.Error.Level.Warning, current);
                        continue;
                    }
                    ssb.BeginRule(-1);
                    result = true;
                    StyleSheetImportErrors errors = new StyleSheetImportErrors();
                    foreach (Property current2 in styleSheet.StyleRules[0].Declarations)
                    {
                        ssb.BeginProperty(current2.Name);
                        StyleSheetImporterImpl.VisitValue(errors, ssb, current2.Term);
                        ssb.EndProperty();
                    }
                    continue;
                }

                case "pickingMode":
                    if (!Enum.IsDefined(typeof(PickingMode), current.Value))
                    {
                        Debug.LogErrorFormat("Could not parse value of '{0}', because it isn't defined in the PickingMode enum.", new object[]
                        {
                            current.Value
                        });
                        continue;
                    }
                    res.pickingMode = (PickingMode)Enum.Parse(typeof(PickingMode), current.Value);
                    continue;
                }
                res.AddProperty(current.Name.LocalName, current.Value);
            }
            return(result);
        }