public static void CloneTree(
            VisualTreeAsset vta, VisualElement target,
            Dictionary <string, VisualElement> slotInsertionPoints,
            List <TemplateAsset.AttributeOverride> attributeOverrides)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if ((vta.visualElementAssets == null || vta.visualElementAssets.Count <= 0) &&
                (vta.templateAssets == null || vta.templateAssets.Count <= 0))
            {
                return;
            }

            var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta);

            List <VisualElementAsset> rootAssets;

            // Tree root has parentId == 0
            idToChildren.TryGetValue(0, out rootAssets);
            if (rootAssets == null || rootAssets.Count == 0)
            {
                return;
            }

#if !UNITY_2019_4
            var uxmlRootAsset = rootAssets[0];

            vta.AssignClassListFromAssetToElement(uxmlRootAsset, target);
            vta.AssignStyleSheetFromAssetToElement(uxmlRootAsset, target);

            // Get the first-level elements. These will be instantiated and added to target.
            idToChildren.TryGetValue(uxmlRootAsset.id, out rootAssets);
            if (rootAssets == null || rootAssets.Count == 0)
            {
                return;
            }
#endif

            rootAssets.Sort(VisualTreeAssetUtilities.CompareForOrder);
            foreach (VisualElementAsset rootElement in rootAssets)
            {
                Assert.IsNotNull(rootElement);

                // Don't try to instatiate the special selection tracking element.
                if (rootElement.fullTypeName == BuilderConstants.SelectedVisualTreeAssetSpecialElementTypeName)
                {
                    continue;
                }

                VisualElement rootVe = CloneSetupRecursively(vta, rootElement, idToChildren,
                                                             new CreationContext(slotInsertionPoints, attributeOverrides, vta, target));

                // if contentContainer == this, the shadow and the logical hierarchy are identical
                // otherwise, if there is a CC, we want to insert in the shadow
                target.hierarchy.Add(rootVe);
            }
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        public static string GenerateUXML(VisualTreeAsset vta, string vtaPath, List <VisualElementAsset> veas)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append(BuilderConstants.UxmlHeader);
            stringBuilder.Append(">");
            stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);

            var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta);

            foreach (var vea in veas)
            {
                // Templates
                var usedTemplates = new HashSet <string>();
                GatherUsedTemplates(vta, vea, idToChildren, usedTemplates);
                AppendTemplateRegistrations(vta, vtaPath, stringBuilder, usedTemplates);

                GenerateUXMLRecursive(vta, vtaPath, vea, idToChildren, stringBuilder, 1, true);
            }

            stringBuilder.Append(BuilderConstants.UxmlFooter);
            stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);

            return(stringBuilder.ToString());
        }
Exemplo n.º 4
0
        public static string GenerateUXML(VisualTreeAsset vta, string vtaPath, bool writingToFile = false)
        {
            var stringBuilder = new StringBuilder();

            if ((vta.visualElementAssets == null || vta.visualElementAssets.Count <= 0) &&
                (vta.templateAssets == null || vta.templateAssets.Count <= 0))
            {
                stringBuilder.Append(BuilderConstants.UxmlHeader);
                stringBuilder.Append(">");
                stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
                stringBuilder.Append(BuilderConstants.UxmlFooter);
                stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);
                return(stringBuilder.ToString());
            }

            var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta);

            stringBuilder.Append(BuilderConstants.UxmlHeader);
#if UNITY_2020_1_OR_NEWER
            AppendHeaderAttributes(vta, stringBuilder, writingToFile);
#endif
            stringBuilder.Append(">");
            stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);

            // Templates
            AppendTemplateRegistrations(vta, vtaPath, stringBuilder);

            GenerateUXMLFromRootElements(vta, idToChildren, stringBuilder, vtaPath, writingToFile);

            stringBuilder.Append(BuilderConstants.UxmlFooter);
            stringBuilder.Append(BuilderConstants.NewlineCharFromEditorSettings);

            return(stringBuilder.ToString());
        }
Exemplo n.º 5
0
 internal static VisualElementAsset AddElement(
     this VisualTreeAsset vta, VisualElementAsset parent, string fullTypeName, int index = -1)
 {
     var vea = new VisualElementAsset(fullTypeName);
     VisualTreeAssetUtilities.InitializeElement(vea);
     return VisualTreeAssetUtilities.AddElementToDocument(vta, vea, parent);
 }
        public static string GenerateUXML(VisualTreeAsset vta, string vtaPath, bool writingToFile = false)
        {
            var stringBuilder = new StringBuilder();

            if ((vta.visualElementAssets == null || vta.visualElementAssets.Count <= 0) &&
                (vta.templateAssets == null || vta.templateAssets.Count <= 0))
            {
                stringBuilder.Append(BuilderConstants.UxmlHeader);
                stringBuilder.Append(BuilderConstants.UxmlFooter);
                return(stringBuilder.ToString());
            }

            var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta);

            stringBuilder.Append(BuilderConstants.UxmlHeader);

            // Templates
            AppendTemplateRegistrations(vta, vtaPath, stringBuilder);

            GenerateUXMLFromRootElements(vta, idToChildren, stringBuilder, vtaPath, writingToFile);

            stringBuilder.Append(BuilderConstants.UxmlFooter);

            return(stringBuilder.ToString());
        }
Exemplo n.º 7
0
        static void ReinitElementWithNewParentAsset(
            VisualTreeAsset vta, VisualElementAsset parent, VisualTreeAsset other,
            Dictionary <int, List <VisualElementAsset> > otherIdToChildren,
            VisualElementAsset vea, ref int nextOrderInDocument)
        {
            SwallowStyleRule(vta, other, vea);

            // Set new parent id on root elements.
            if (other.IsRootElement(vea) && parent != null)
            {
                vea.parentId = parent.id;
            }

            // Set order in document.
            vea.orderInDocument  = nextOrderInDocument;
            nextOrderInDocument += BuilderConstants.VisualTreeAssetOrderIncrement;

            // Create new id and update parentId in children.
            var oldId = vea.id;

            vea.id = VisualTreeAssetUtilities.GenerateNewId(vta, vea);
            List <VisualElementAsset> children;

            if (otherIdToChildren.TryGetValue(oldId, out children) && children != null)
            {
                foreach (var child in children)
                {
                    child.parentId = vea.id;
                }
            }
        }
Exemplo n.º 8
0
 public static void ReparentElement(
     this VisualTreeAsset vta,
     VisualElementAsset elementToReparent,
     VisualElementAsset newParent,
     int index = -1)
 {
     VisualTreeAssetUtilities.ReparentElementInDocument(vta, elementToReparent, newParent, index);
 }
Exemplo n.º 9
0
        public static VisualTreeAsset DeepCopy(this VisualTreeAsset vta)
        {
            var newTreeAsset = VisualTreeAssetUtilities.CreateInstance();

            vta.DeepOverwrite(newTreeAsset);

            return(newTreeAsset);
        }
Exemplo n.º 10
0
        public static void Swallow(this VisualTreeAsset vta, VisualElementAsset parent, VisualTreeAsset other)
        {
            var otherIdToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(other);

            if (parent == null)
            {
                parent = vta.GetRootUXMLElement();
            }

            var nextOrderInDocument = (vta.visualElementAssets.Count + vta.templateAssets.Count) * BuilderConstants.VisualTreeAssetOrderIncrement;
            var assetsList          = new List <VisualElementAsset>();

            assetsList.AddRange(other.visualElementAssets);
            assetsList.AddRange(other.templateAssets);
            assetsList = assetsList.OrderBy(x => x.orderInDocument).ToList();

            foreach (var asset in assetsList)
            {
                if (other.IsRootUXMLElement(asset))
                {
                    continue;
                }

                ReinitElementWithNewParentAsset(
                    vta, parent, other, otherIdToChildren, asset, ref nextOrderInDocument);
            }

            foreach (var vea in other.visualElementAssets)
            {
                if (other.IsRootUXMLElement(vea))
                {
                    continue;
                }

                vta.visualElementAssets.Add(vea);
            }

            foreach (var vea in other.templateAssets)
            {
                if (!vta.TemplateExists(vea.templateAlias))
                {
                    vta.RegisterTemplate(vea.templateAlias, other.ResolveTemplate(vea.templateAlias));
                }

                vta.templateAssets.Add(vea);
            }

            VisualTreeAssetUtilities.ReOrderDocument(vta);
        }
Exemplo n.º 11
0
        internal static VisualElementAsset AddElement(
            this VisualTreeAsset vta, VisualElementAsset parent, VisualElement visualElement, int index = -1)
        {
            var fullTypeName = visualElement.GetType().ToString();
            var vea = new VisualElementAsset(fullTypeName);
            VisualTreeAssetUtilities.InitializeElement(vea);

            visualElement.SetProperty(BuilderConstants.ElementLinkedVisualElementAssetVEPropertyName, vea);
            visualElement.SetProperty(BuilderConstants.ElementLinkedBelongingVisualTreeAssetVEPropertyName, vta);

            var overriddenAttributes = visualElement.GetOverriddenAttributes();
            foreach (var attribute in overriddenAttributes)
                vea.AddProperty(attribute.Key, attribute.Value);

            return VisualTreeAssetUtilities.AddElementToDocument(vta, vea, parent);
        }
Exemplo n.º 12
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;
        }
Exemplo n.º 13
0
        public static string GenerateUXML(VisualTreeAsset vta, string vtaPath, VisualElementAsset vea)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append(BuilderConstants.UxmlHeader);

            var idToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(vta);

            // Templates
            var usedTemplates = new HashSet<string>();
            GatherUsedTemplates(vta, vea, idToChildren, usedTemplates);
            AppendTemplateRegistrations(vta, vtaPath, stringBuilder, usedTemplates);

            GenerateUXMLRecursive(vta, vtaPath, vea, idToChildren, stringBuilder, 1, true, true);

            stringBuilder.Append(BuilderConstants.UxmlFooter);

            return stringBuilder.ToString();
        }
Exemplo n.º 14
0
        public static void Swallow(this VisualTreeAsset vta, VisualElementAsset parent, VisualTreeAsset other)
        {
            var otherIdToChildren = VisualTreeAssetUtilities.GenerateIdToChildren(other);

            if (parent == null)
            {
                parent = vta.GetRootUXMLElement();
            }

            var nextOrderInDocument = (vta.visualElementAssets.Count + vta.templateAssets.Count) * BuilderConstants.VisualTreeAssetOrderIncrement;

            foreach (var vea in other.visualElementAssets)
            {
                if (other.IsRootUXMLElement(vea))
                {
                    continue;
                }

                ReinitElementWithNewParentAsset(
                    vta, parent, other, otherIdToChildren, vea, ref nextOrderInDocument);

                vta.visualElementAssets.Add(vea);
            }

            foreach (var vea in other.templateAssets)
            {
                ReinitElementWithNewParentAsset(
                    vta, parent, other, otherIdToChildren, vea, ref nextOrderInDocument);

                if (!vta.TemplateExists(vea.templateAlias))
                {
                    var path = other.GetPathFromTemplateName(vea.templateAlias);
                    vta.RegisterTemplate(vea.templateAlias, path);
                }

                vta.templateAssets.Add(vea);
            }

            VisualTreeAssetUtilities.ReOrderDocument(vta);
        }
        static List <ITreeViewItem> GenerateControlsItemsTree()
        {
            var controlsTree   = new List <ITreeViewItem>();
            var containersItem = new BuilderLibraryTreeItem(BuilderConstants.LibraryContainersSectionHeaderName, null, null, null)
            {
                IsHeader = true
            };
            IList <ITreeViewItem> containersItemList = new List <ITreeViewItem>
            {
                new BuilderLibraryTreeItem("VisualElement", "VisualElement", typeof(VisualElement), () =>
                {
                    var ve              = new VisualElement();
                    var veMinSizeChild  = new VisualElement();
                    veMinSizeChild.name = BuilderConstants.SpecialVisualElementInitialMinSizeName;
                    veMinSizeChild.AddToClassList(BuilderConstants.SpecialVisualElementInitialMinSizeClassName);
                    ve.Add(veMinSizeChild);
                    return(ve);
                },
                                           (inVta, inParent, ve) =>
                {
                    var vea = new VisualElementAsset(typeof(VisualElement).ToString());
                    VisualTreeAssetUtilities.InitializeElement(vea);
                    inVta.AddElement(inParent, vea);
                    return(vea);
                }),
                new BuilderLibraryTreeItem("ScrollView", "ScrollView", typeof(ScrollView), () => new ScrollView()),
                new BuilderLibraryTreeItem("ListView", "ListView", typeof(ListView), () => new ListView()),
                new BuilderLibraryTreeItem("IMGUI Container", "VisualElement", typeof(IMGUIContainer), () => new IMGUIContainer()),
            };

            containersItem.AddChildren(containersItemList);
            controlsTree.Add(containersItem);

            var controlsItem = new BuilderLibraryTreeItem(BuilderConstants.LibraryControlsSectionHeaderName, null, null, null, null, new List <TreeViewItem <string> >
            {
                new BuilderLibraryTreeItem("Label", nameof(Label), typeof(Label), () => new Label("Label")),
                new BuilderLibraryTreeItem("Button", nameof(Button), typeof(Button), () => new Button {
                    text = "Button"
                }),
                new BuilderLibraryTreeItem("Toggle", nameof(Toggle), typeof(Toggle), () => new Toggle("Toggle")),
                new BuilderLibraryTreeItem("Scroller", nameof(Scroller), typeof(Scroller), () => new Scroller(0, 100, (v) => { }, SliderDirection.Horizontal)
                {
                    value = 42
                }),
                new BuilderLibraryTreeItem("Text Field", nameof(TextField), typeof(TextField), () => new TextField("Text Field")
                {
                    value = "filler text"
                }),
                new BuilderLibraryTreeItem("Foldout", nameof(Foldout), typeof(Foldout), () => new Foldout {
                    text = "Foldout"
                }),
                new BuilderLibraryTreeItem("Slider", nameof(Slider), typeof(Slider), () => new Slider("Slider", 0, 100)
                {
                    value = 42
                }),
                new BuilderLibraryTreeItem("Min-Max Slider", nameof(MinMaxSlider), typeof(MinMaxSlider), () => new MinMaxSlider("Min/Max Slider", 0, 20, -10, 40)
                {
                    value = new Vector2(10, 12)
                }),
            })
            {
                IsHeader = true
            };

            var numericFields = new BuilderLibraryTreeItem("Numeric Fields", null, null, null, null, new List <TreeViewItem <string> >
            {
                new BuilderLibraryTreeItem("Integer", nameof(IntegerField), typeof(IntegerField), () => new IntegerField("Int Field")
                {
                    value = 42
                }),
                new BuilderLibraryTreeItem("Float", nameof(FloatField), typeof(FloatField), () => new FloatField("Float Field")
                {
                    value = 42.2f
                }),
                new BuilderLibraryTreeItem("Long", nameof(LongField), typeof(LongField), () => new LongField("Long Field")
                {
                    value = 42
                }),
                new BuilderLibraryTreeItem("Min-Max Slider", nameof(MinMaxSlider), typeof(MinMaxSlider), () => new MinMaxSlider("Min/Max Slider", 0, 20, -10, 40)
                {
                    value = new Vector2(10, 12)
                }),
                new BuilderLibraryTreeItem("Slider", nameof(Slider), typeof(Slider), () => new Slider("Slider", 0, 100)
                {
                    value = 42
                }),
                new BuilderLibraryTreeItem("Progress Bar", nameof(ProgressBar), typeof(ProgressBar), () => new ProgressBar()
                {
                    title = "my-progress", value = 22
                }),
                new BuilderLibraryTreeItem("Vector2", nameof(Vector2Field), typeof(Vector2Field), () => new Vector2Field("Vec2 Field")),
                new BuilderLibraryTreeItem("Vector3", nameof(Vector3Field), typeof(Vector3Field), () => new Vector3Field("Vec3 Field")),
                new BuilderLibraryTreeItem("Vector4", nameof(Vector4Field), typeof(Vector4Field), () => new Vector4Field("Vec4 Field")),
                new BuilderLibraryTreeItem("Rect", nameof(RectField), typeof(RectField), () => new RectField("Rect")),
                new BuilderLibraryTreeItem("Bounds", nameof(BoundsField), typeof(BoundsField), () => new BoundsField("Bounds")),
                new BuilderLibraryTreeItem("Slider (Int)", nameof(SliderInt), typeof(SliderInt), () => new SliderInt("SliderInt", 0, 100)
                {
                    value = 42
                }),
                new BuilderLibraryTreeItem("Vector2 (Int)", nameof(Vector2IntField), typeof(Vector2IntField), () => new Vector2IntField("Vector2Int")),
                new BuilderLibraryTreeItem("Vector3 (Int)", nameof(Vector3IntField), typeof(Vector3IntField), () => new Vector3IntField("Vector3Int")),
                new BuilderLibraryTreeItem("Rect (Int)", nameof(RectIntField), typeof(RectIntField), () => new RectIntField("RectInt")),
                new BuilderLibraryTreeItem("Bounds (Int)", nameof(BoundsIntField), typeof(BoundsIntField), () => new BoundsIntField("BoundsInt")),
                new BuilderLibraryTreeItem("Object Field", nameof(ObjectField), typeof(ObjectField), () => new ObjectField("Object Field")
                {
                    value = new Texture2D(10, 10)
                    {
                        name = "new_texture"
                    }
                }),
            })
            {
                IsEditorOnly = true, IsHeader = true
            };

            var valueFields = new BuilderLibraryTreeItem("Value Fields", null, null, null, null, new List <TreeViewItem <string> >
            {
                new BuilderLibraryTreeItem("Color", nameof(ColorField), typeof(ColorField), () => new ColorField("Color")
                {
                    value = Color.cyan
                }),
                new BuilderLibraryTreeItem("Curve", nameof(CurveField), typeof(CurveField), () => new CurveField("Curve")
                {
                    value = new AnimationCurve(new Keyframe(0, 0), new Keyframe(5, 8), new Keyframe(10, 4))
                }),
                new BuilderLibraryTreeItem("Gradient", nameof(GradientField), typeof(GradientField), () => new GradientField("Gradient")
                {
                    value = new Gradient()
                    {
                        colorKeys = new[]
                        {
                            new GradientColorKey(Color.red, 0),
                            new GradientColorKey(Color.blue, 10),
                            new GradientColorKey(Color.green, 20)
                        }
                    }
                })
            })
            {
                IsEditorOnly = true, IsHeader = true
            };

            var choiceFields = new BuilderLibraryTreeItem("Choice Fields", null, null, null, null, new List <TreeViewItem <string> >
            {
                new BuilderLibraryTreeItem("Enum", nameof(EnumField), typeof(EnumField), () => new EnumField("Enum", TextAlignment.Center)),

                // No UXML support for PopupField.
                //new LibraryTreeItem("Popup", () => new PopupField<string>("Normal Field", choices, 0)),

                new BuilderLibraryTreeItem("Tag", nameof(TagField), typeof(TagField), () => new TagField("Tag", "Player")),
                new BuilderLibraryTreeItem("Mask", nameof(MaskField), typeof(MaskField), () => new MaskField("Mask")),
                new BuilderLibraryTreeItem("Layer", nameof(LayerField), typeof(LayerField), () => new LayerField("Layer")),
                new BuilderLibraryTreeItem("LayerMask", nameof(LayerMaskField), typeof(LayerMaskField), () => new LayerMaskField("LayerMask"))
            })
            {
                IsEditorOnly = true, IsHeader = true
            };

            var toolbar = new BuilderLibraryTreeItem("Toolbar", null, null, null, null, new List <TreeViewItem <string> >
            {
                new BuilderLibraryTreeItem("Toolbar", "ToolbarElement", typeof(Toolbar), () => new Toolbar()),
                new BuilderLibraryTreeItem("Toolbar Menu", "ToolbarElement", typeof(ToolbarMenu), () => new ToolbarMenu()),
                new BuilderLibraryTreeItem("Toolbar Button", "ToolbarElement", typeof(ToolbarButton), () => new ToolbarButton {
                    text = "Button"
                }),
                new BuilderLibraryTreeItem("Toolbar Spacer", "ToolbarElement", typeof(ToolbarSpacer), () => new ToolbarSpacer()),
                new BuilderLibraryTreeItem("Toolbar Toggle", "ToolbarElement", typeof(ToolbarToggle), () => new ToolbarToggle {
                    label = "Toggle"
                }),
#if UNITY_2019_3_OR_NEWER
                new BuilderLibraryTreeItem("Toolbar Breadcrumbs", "ToolbarElement", typeof(ToolbarBreadcrumbs), () => new ToolbarBreadcrumbs()),
#endif
                new BuilderLibraryTreeItem("Toolbar Search Field", "ToolbarElement", typeof(ToolbarSearchField), () => new ToolbarSearchField()),
                new BuilderLibraryTreeItem("Toolbar Popup Search Field", "ToolbarElement", typeof(ToolbarPopupSearchField), () => new ToolbarPopupSearchField()),
            })
            {
                IsEditorOnly = true, IsHeader = true
            };

            var inspectors = new BuilderLibraryTreeItem("Inspectors", null, null, null, null, new List <TreeViewItem <string> >
            {
                new BuilderLibraryTreeItem("PropertyField", nameof(PropertyField), typeof(PropertyField), () => new PropertyField())
            })
            {
                IsEditorOnly = true, IsHeader = true
            };

            controlsTree.Add(controlsItem);
            controlsTree.Add(numericFields);
            controlsTree.Add(valueFields);
            controlsTree.Add(choiceFields);
            controlsTree.Add(toolbar);
            controlsTree.Add(inspectors);

            return(controlsTree);
        }
Exemplo n.º 16
0
 internal static VisualElementAsset AddElement(
     this VisualTreeAsset vta, VisualElementAsset parent, VisualElementAsset vea)
 {
     return(VisualTreeAssetUtilities.AddElementToDocument(vta, vea, parent));
 }
Exemplo n.º 17
0
        public bool SaveNewDocument(
            VisualElement documentRootElement, bool isSaveAs,
            out bool needsFullRefresh,
            string manualUxmlPath = null)
        {
            needsFullRefresh = false;

            ClearUndo();

            // Re-use or ask the user for the UXML path.
            var newUxmlPath = uxmlPath;

            if (string.IsNullOrEmpty(newUxmlPath) || isSaveAs)
            {
                if (!string.IsNullOrEmpty(manualUxmlPath))
                {
                    newUxmlPath = manualUxmlPath;
                }
                else
                {
                    newUxmlPath = BuilderDialogsUtility.DisplaySaveFileDialog("Save UXML", null, null, "uxml");
                    if (newUxmlPath == null) // User cancelled the save dialog.
                    {
                        return(false);
                    }
                }
            }

            List <BuilderDocumentOpenUSS> savedUSSFiles = new List <BuilderDocumentOpenUSS>();

            // Save USS files.
            foreach (var openUSSFile in m_OpenUSSFiles)
            {
                if (openUSSFile.SaveToDisk(visualTreeAsset))
                {
                    savedUSSFiles.Add(openUSSFile);
                }
            }

            var oldUxmlTest = m_VisualTreeAssetBackup?.GenerateUXML(m_OpenendVisualTreeAssetOldPath, true);

            // Save UXML files
            // Saving all open UXML files to ensure references correct upon changes in child documents.
            foreach (var openUXMLFile in openUXMLFiles)
            {
                openUXMLFile.PreSaveSyncBackup();
            }

            bool shouldSave = m_OpenendVisualTreeAssetOldPath != newUxmlPath;
            var  uxmlText   = visualTreeAsset.GenerateUXML(newUxmlPath, true);

            if (uxmlText != null)
            {
                if (!shouldSave && m_VisualTreeAssetBackup)
                {
                    shouldSave = oldUxmlTest != uxmlText;
                }

                if (shouldSave)
                {
                    WriteUXMLToFile(newUxmlPath, uxmlText);
                }
            }

            // Once we wrote all the files to disk, we refresh the DB and reload
            // the files from the AssetDatabase.
            m_DocumentBeingSavedExplicitly = true;
            try
            {
                AssetDatabase.Refresh();
            }
            finally
            {
                m_DocumentBeingSavedExplicitly = false;
            }

            // Reorder document after reimporting
            VisualTreeAssetUtilities.ReOrderDocument(m_VisualTreeAsset);

            // Check if any USS assets have changed reload them.
            foreach (var openUSSFile in savedUSSFiles)
            {
                needsFullRefresh |= openUSSFile.PostSaveToDiskChecksAndFixes();
            }

            // Check if any UXML assets have changed and reload them.
            // Saving all open UXML files to ensure references correct upon changes in child subdocuments.
            foreach (var openUXMLFile in openUXMLFiles)
            {
                needsFullRefresh |= openUXMLFile.PostSaveToDiskChecksAndFixes(this == openUXMLFile ? newUxmlPath : null, needsFullRefresh);
            }

            if (needsFullRefresh)
            {
                // Copy previous document settings.
                if (m_Settings != null)
                {
                    m_Settings.UxmlGuid = AssetDatabase.AssetPathToGUID(newUxmlPath);
                    m_Settings.UxmlPath = newUxmlPath;
                    m_Settings.SaveSettingsToDisk();
                }

                // Reset asset name.
                m_VisualTreeAsset.name          = Path.GetFileNameWithoutExtension(newUxmlPath);
                m_OpenendVisualTreeAssetOldPath = newUxmlPath;
            }

            if (documentRootElement != null)
            {
                ReloadDocumentToCanvas(documentRootElement);
            }

            hasUnsavedChanges = false;

            return(true);
        }
Exemplo n.º 18
0
        void RefreshTreeView()
        {
            Clear();
            LibraryTreeItem.ResetNextId();
            var items = new List <ITreeViewItem>();

            var unityItem = new LibraryTreeItem("Unity", () => null);

            unityItem.isHeader = true;
            IList <ITreeViewItem> unityItemList = new List <ITreeViewItem>()
            {
                new LibraryTreeItem("VisualElement",
                                    () =>
                {
                    var ve              = new VisualElement();
                    var veMinSizeChild  = new VisualElement();
                    veMinSizeChild.name = BuilderConstants.SpecialVisualElementInitialMinSizeName;
                    veMinSizeChild.AddToClassList(BuilderConstants.SpecialVisualElementInitialMinSizeClassName);
                    ve.Add(veMinSizeChild);
                    return(ve);
                },
                                    (inVta, inParent) =>
                {
                    var vea = new VisualElementAsset(typeof(VisualElement).ToString());
                    VisualTreeAssetUtilities.InitializeElement(vea);
                    inVta.AddElement(inParent, vea);
                    return(vea);
                }),
                new LibraryTreeItem("Button", () => new Button()
                {
                    text = "Button"
                }),
                new LibraryTreeItem("Scroller", () => new Scroller(0, 100, (v) => { }, SliderDirection.Horizontal)
                {
                    value = 42
                }),
                new LibraryTreeItem("Toggle", () => new Toggle("Toggle")),
                new LibraryTreeItem("Label", () => new Label("Label")),
                new LibraryTreeItem("Text Field", () => new TextField("Text Field")
                {
                    value = "filler text"
                }),
                new LibraryTreeItem("Object Field", () => new ObjectField("Object Field")
                {
                    value = new Texture2D(10, 10)
                    {
                        name = "new_texture"
                    }
                }),
                new LibraryTreeItem("Foldout", () => new Foldout()
                {
                    text = "Foldout"
                }),
                new LibraryTreeItem("Numeric Fields", () => null, null, new List <TreeViewItem <string> >()
                {
                    new LibraryTreeItem("Integer", () => new IntegerField("Int Field")
                    {
                        value = 42
                    }),
                    new LibraryTreeItem("Float", () => new FloatField("Float Field")
                    {
                        value = 42.2f
                    }),
                    new LibraryTreeItem("Long", () => new LongField("Long Field")
                    {
                        value = 42
                    }),
                    new LibraryTreeItem("Min-Max Slider", () => new MinMaxSlider("Min/Max Slider", 0, 20, -10, 40)
                    {
                        value = new Vector2(10, 12)
                    }),
                    new LibraryTreeItem("Slider", () => new Slider("Slider", 0, 100)
                    {
                        value = 42
                    }),
                    new LibraryTreeItem("Progress Bar", () => new ProgressBar()
                    {
                        title = "my-progress", value = 22
                    }),
                    new LibraryTreeItem("Vector2", () => new Vector2Field("Vec2 Field")),
                    new LibraryTreeItem("Vector3", () => new Vector3Field("Vec3 Field")),
                    new LibraryTreeItem("Vector4", () => new Vector4Field("Vec4 Field")),
                    new LibraryTreeItem("Rect", () => new RectField("Rect")),
                    new LibraryTreeItem("Bounds", () => new BoundsField("Bounds")),
                    new LibraryTreeItem("Slider (Int)", () => new SliderInt("SliderInt", 0, 100)
                    {
                        value = 42
                    }),
                    new LibraryTreeItem("Vector2 (Int)", () => new Vector2IntField("Vector2Int")),
                    new LibraryTreeItem("Vector3 (Int)", () => new Vector3IntField("Vector3Int")),
                    new LibraryTreeItem("Rect (Int)", () => new RectIntField("RectInt")),
                    new LibraryTreeItem("Bounds (Int)", () => new BoundsIntField("BoundsInt"))
                }),
                new LibraryTreeItem("Value Fields", () => null, null, new List <TreeViewItem <string> >()
                {
                    new LibraryTreeItem("Color", () => new ColorField("Color")
                    {
                        value = Color.cyan
                    }),
                    new LibraryTreeItem("Curve", () => new CurveField("Curve")
                    {
                        value = new AnimationCurve(new Keyframe[] { new Keyframe(0, 0), new Keyframe(5, 8), new Keyframe(10, 4) })
                    }),
                    new LibraryTreeItem("Gradient", () => new GradientField("Gradient")
                    {
                        value = new Gradient()
                        {
                            colorKeys = new GradientColorKey[]
                            {
                                new GradientColorKey(Color.red, 0),
                                new GradientColorKey(Color.blue, 10),
                                new GradientColorKey(Color.green, 20)
                            }
                        }
                    })
                }),
                new LibraryTreeItem("Choice Fields", () => null, null, new List <TreeViewItem <string> >()
                {
                    new LibraryTreeItem("Enum", () => new EnumField("Enum", TextAlignment.Center)),

                    // No UXML support for PopupField.
                    //new LibraryTreeItem("Popup", () => new PopupField<string>("Normal Field", choices, 0)),

                    new LibraryTreeItem("Tag", () => new TagField("Tag", "Player")),
                    new LibraryTreeItem("Mask", () => new MaskField("Mask")),
                    new LibraryTreeItem("Layer", () => new LayerField("Layer")),
                    new LibraryTreeItem("LayerMask", () => new LayerMaskField("LayerMask"))
                }),
                new LibraryTreeItem("Containers", () => null, null, new List <TreeViewItem <string> >()
                {
                    new LibraryTreeItem("ScrollView", () => new ScrollView()),
                    new LibraryTreeItem("ListView", () => new ListView()),
                    new LibraryTreeItem("IMGUIContainer", () => new IMGUIContainer()),
                }),
                new LibraryTreeItem("Toolbar", () => null, null, new List <TreeViewItem <string> >()
                {
                    new LibraryTreeItem("Toolbar", () => new Toolbar()),
                    new LibraryTreeItem("Toolbar Menu", () => new ToolbarMenu()),
                    new LibraryTreeItem("Toolbar Button", () => new ToolbarButton {
                        text = "Button"
                    }),
                    new LibraryTreeItem("Toolbar Spacer", () => new ToolbarSpacer()),
                    new LibraryTreeItem("Toolbar Toggle", () => new ToolbarToggle {
                        label = "Toggle"
                    }),
#if UNITY_2019_3_OR_NEWER
                    new LibraryTreeItem("Toolbar Breadcrumbs", () => new ToolbarBreadcrumbs()),
#endif
                    new LibraryTreeItem("Toolbar Search Field", () => new ToolbarSearchField()),
                    new LibraryTreeItem("Toolbar Popup Search Field", () => new ToolbarPopupSearchField()),
                }),
                new LibraryTreeItem("Inspectors", () => null, null, new List <TreeViewItem <string> >()
                {
                    new LibraryTreeItem("PropertyField", () => new PropertyField())
                }),
            };

            unityItem.AddChildren(unityItemList);
            items.Add(unityItem);

            // From Project
            var fromProjectCategory = new LibraryTreeItem("Project", () => null);

            fromProjectCategory.isHeader = true;
            items.Add(fromProjectCategory);
            ImportUxmlFromProject(fromProjectCategory);
            ImportFactoriesFromSource(fromProjectCategory);

            var treeView = new TreeView()
            {
                name = k_TreeViewName
            };

            treeView.AddToClassList(k_TreeViewClassName);
            Add(treeView);

            treeView.viewDataKey = "samples-tree";
            treeView.itemHeight  = 20;
            treeView.rootItems   = items;
            treeView.makeItem    = () => MakeItem(); // This is apparently more optimal than "= MakeItem;".
            treeView.bindItem    = (e, i) => BindItem(e, i);
#if UNITY_2020_1_OR_NEWER
            treeView.onItemsChosen += (s) => OnItemsChosen(s);
#else
            treeView.onItemChosen += (s) => OnItemChosen(s);
#endif
            treeView.Refresh();

            // Make sure the Hierarchy View gets focus when the pane gets focused.
            primaryFocusable = treeView.Q <ListView>();

            // Auto-expand all items on load.
            foreach (var item in treeView.rootItems)
            {
                treeView.ExpandItem(item.id);
            }
        }