static void FindElementsRecursive(VisualElement parent, Func <VisualElement, bool> predicate, List <VisualElement> selected)
        {
            if (predicate(parent))
            {
                selected.Add(parent);
            }

            foreach (var child in parent.Children())
            {
                FindElementsRecursive(child, predicate, selected);
            }
        }
        public static VisualElement GetMinSizeSpecialElement(this VisualElement element)
        {
            foreach (var child in element.Children())
            {
                if (child.name == BuilderConstants.SpecialVisualElementInitialMinSizeName)
                {
                    return(child);
                }
            }

            return(null);
        }
Example #3
0
        void OnGUI()
        {
            if (m_BaseUpdatable == null)
            {
                return;
            }

            foreach (VisualElementUpdatable updatable in m_BaseUpdatable.Children().Where(c => c is VisualElementUpdatable))
            {
                updatable.CheckUpdate();
            }
        }
        static void FindSelectedElementsRecursive(VisualElement parent, List <VisualElement> selected)
        {
            if (parent.IsSelected())
            {
                selected.Add(parent);
            }

            foreach (var child in parent.Children())
            {
                FindSelectedElementsRecursive(child, selected);
            }
        }
Example #5
0
        private void OnTogglePopup()
        {
            // If the user click on the arrow button while the popup is opened
            // the popup is then closed (because clicked outside) and immediately reopened
            // To prevent this behavior we allow the popup to reopen only after a very short period of time after being closed
            var deltaTime = DateTime.UtcNow - m_PopupClosedTimestamp;

            if (m_CurrentPopup == null && deltaTime.TotalMilliseconds > 500)
            {
                m_CurrentPopup           = ScriptableObject.CreateInstance <NotifyEditorWindow>();
                m_CurrentPopup.hideFlags = HideFlags.HideAndDontSave;
                if (m_PopupContent.parent != null)
                {
                    m_PopupContent.parent.Remove(m_PopupContent);
                }

                m_CurrentPopup.Destroyed += OnPopupClosed;
                m_CurrentPopup.rootVisualElement.AddStyleSheetPath("VFXToolbar");
                m_CurrentPopup.rootVisualElement.Add(m_PopupContent);
                m_CurrentPopup.rootVisualElement.AddToClassList("popup");
                m_CurrentPopup.rootVisualElement.RegisterCallback <KeyUpEvent>(OnKeyUp);

                OnOpenPopup();
                var bounds = new Rect(GetPopupPosition(), localBound.size);
                // Offset the bounds to align the popup with the real dropdown left edge
                if (m_HasLeftSeparator)
                {
                    bounds.xMin += 6;
                }

                m_CurrentPopup.ShowAsDropDown(bounds, GetPopupSize(), new[] { PopupLocation.BelowAlignLeft, PopupLocation.AboveAlignLeft });
                m_CurrentPopup.minSize = GetPopupSize();
                m_CurrentPopup.maxSize = m_CurrentPopup.minSize;
                GetNextFocusable(null, m_PopupContent.Children(), false)?.Focus();
            }
            else if (m_CurrentPopup != null)
            {
                ClosePopup();
            }
        }
Example #6
0
 void UpdatePortInputs()
 {
     foreach (var port in inputContainer.Children().OfType <LogicPort>())
     {
         if (!_portInputContainer.Children().OfType <PortInputView>().Any(a => Equals(a.Description, port.Slot)))
         {
             var portInputView = new PortInputView(port.Slot)
             {
                 style = { position = Position.Absolute }
             };
             _portInputContainer.Add(portInputView);
             if (float.IsNaN(port.layout.width))
             {
                 port.RegisterCallback <GeometryChangedEvent>(UpdatePortInput);
             }
             else
             {
                 SetPortInputPosition(port, portInputView);
             }
         }
     }
 }
Example #7
0
        void ClearButtons()
        {
            List <VisualElement> buttons = new List <VisualElement>();

            foreach (var child in buttonsParent.Children())
            {
                buttons.Add(child);
            }
            foreach (var child in buttons)
            {
                buttonsParent.Remove(child);
            }
        }
Example #8
0
        /// <summary>
        /// Refreshes the names of the children and the relations' child references
        /// </summary>
        internal override void Refresh()
        {
            base.Refresh();
            foreach (var child in m_ChildrenSection.Children())
            {
                (child as PotentialChildUI)?.UpdateName();
            }

            foreach (var relation in m_PotentialRelations)
            {
                (relation.createdComponent as Relation)?.ResetChildrenReferences();
            }
        }
 public void DeleteAsset(KeyDownEvent evt, VisualElement asset)
 {
     if (evt.keyCode == KeyCode.Delete)
     {
         if (asset != null)
         {
             foreach (VisualElement ve in asset.Children())
             {
                 if (ve.GetFirstOfType <Label>() != null)
                 {
                     for (int i = allGameAssets.gameTextures.Count - 1; i >= 0; i--)
                     {
                         if (ve.GetFirstOfType <Label>().text == allGameAssets.gameTextures[i].name)
                         {
                             //Debug.LogError("REMOVING");
                             allGameAssets.gameTextures.RemoveAt(i);
                             asset.parent.Remove(asset);
                             EditorUtility.SetDirty(allGameAssets);
                             break;
                         }
                     }
                     for (int i = allGameAssets.gameAudioClips.Count - 1; i >= 0; i--)
                     {
                         if (ve.GetFirstOfType <Label>().text == allGameAssets.gameAudioClips[i].name)
                         {
                             //Debug.LogError("REMOVING");
                             allGameAssets.gameAudioClips.RemoveAt(i);
                             asset.parent.Remove(asset);
                             EditorUtility.SetDirty(allGameAssets);
                             break;
                         }
                     }
                     for (int i = allGameAssets.gameFonts.Count - 1; i >= 0; i--)
                     {
                         if (ve.GetFirstOfType <Label>().text == allGameAssets.gameFonts[i].name)
                         {
                             //Debug.LogError("REMOVING");
                             allGameAssets.gameFonts.RemoveAt(i);
                             asset.parent.Remove(asset);
                             EditorUtility.SetDirty(allGameAssets);
                             break;
                         }
                     }
                 }
             }
             EditorUtility.SetDirty(allGameAssets);
             AssetDatabase.SaveAssets();
             AssetDatabase.Refresh();
         }
     }
 }
        public void InitializeGraph(BaseGraph graph)
        {
            if (this.graph != null && graph != this.graph)
            {
                // Save the graph to the disk
                EditorUtility.SetDirty(this.graph);
                AssetDatabase.SaveAssets();
                // Unload the graph
                graphUnloaded?.Invoke(this.graph);

                if (!this.graph.IsLinkedToScene())
                {
                    Resources.UnloadAsset(this.graph);
                }
            }

            graphLoaded?.Invoke(graph);
            this.graph = graph;

            if (graphView != null)
            {
                rootView.Remove(graphView);
            }

            //Initialize will provide the BaseGraphView
            InitializeWindow(graph);

            graphView = rootView.Children().FirstOrDefault(e => e is BaseGraphView) as BaseGraphView;

            if (graphView == null)
            {
                Debug.LogError("GraphView has not been added to the BaseGraph root view !");
                return;
            }

            graphView.Initialize(graph);

            InitializeGraphView(graphView);

            // TOOD: onSceneLinked...

            if (graph.IsLinkedToScene())
            {
                LinkGraphWindowToScene(graph.GetLinkedScene());
            }
            else
            {
                graph.onSceneLinked += LinkGraphWindowToScene;
            }
        }
        void ReloadStyleSheetsToCanvas(VisualElement documentRootElement)
        {
            m_CurrentDocumentRootElement = documentRootElement;

#if UNITY_2019
            // TODO: For now, don't allow stylesheets in root elements.
            foreach (var rootElement in documentRootElement.Children())
            {
                rootElement.styleSheets.Clear();
            }
#endif

            // Refresh styles.
            RefreshStyle(documentRootElement);
        }
Example #12
0
 public static void ForceDarkToolbarStyleSheet(VisualElement ele)
 {
     if (!EditorGUIUtility.isProSkin)
     {
         if (ele.styleSheets.Contains(s_ToolbarLightStyleSheet))
         {
             ele.styleSheets.Remove(s_ToolbarLightStyleSheet);
             ele.styleSheets.Add(s_ToolbarDarkStyleSheet);
         }
         foreach (var e in ele.Children())
         {
             ForceDarkToolbarStyleSheet(e);
         }
     }
 }
Example #13
0
        public static IEnumerable <T> ChildrenOfType <T>(this VisualElement element)
        {
            foreach (var child in element.Children())
            {
                if (child is T t)
                {
                    yield return(t);
                }

                foreach (var e in child.ChildrenOfType <T>())
                {
                    yield return(e);
                }
            }
        }
        private void UpdateChildren(VisualElement element, List <IState> dirtyState)
        {
            foreach (var child in element.Children().ToList())
            {
                var stateBoundComponent = child as StateBoundComponent;
                if (stateBoundComponent != null)
                {
                    if (stateBoundComponent.BoundStates.Any(dirtyState.Contains))
                    {
                        stateBoundComponent.Update();
                    }
                }

                UpdateChildren(child, dirtyState);
            }
        }
        /// <summary>
        /// 只有两种情况会调用到这个函数
        /// 1.打开GraphEditorWindow(初次打开或者在已经打开的基础上更换GraphAsset)
        /// 2.编译/进入PlayMode而导致的GraphEditorWindow重载
        /// </summary>
        /// <param name="graph"></param>
        public void InitializeGraph(BaseGraph graph)
        {
            if (this.graph != null && graph != this.graph)
            {
                // Save the graph to the disk
                GraphCreateAndSaveHelper.SaveGraphToDisk(this.graph);
                // Unload the graph
                graphUnloaded?.Invoke(this.graph);
            }

            graphLoaded?.Invoke(graph);
            this.graph = graph;

            if (graphView != null)
            {
                rootView.Remove(graphView);
            }

            InitializeWindow(graph);
            rootView.Add(graphView);

            graphView = rootView.Children().FirstOrDefault(e => e is BaseGraphView) as BaseGraphView;

            if (graphView == null)
            {
                Debug.LogError("GraphView has not been added to the BaseGraph root view !");
                return;
            }

            graphView.Initialize(graph);

            InitializeGraphView(graphView);

            // TOOD: onSceneLinked...

            if (graph.IsLinkedToScene())
            {
                LinkGraphWindowToScene(graph.GetLinkedScene());
            }
            else
            {
                graph.onSceneLinked += LinkGraphWindowToScene;
            }
            //防止在外部调用InitializeGraph时重复执行InitializeGraph
            reloadWorkaround = false;
        }
        static void PopulateBindings(this VisualElement element, List <IBinding> list)
        {
            if (element is IBindable bindable && null != bindable.binding)
            {
                list.Add(bindable.binding);
            }

            if (element is IBinding binding)
            {
                list.Add(binding);
            }

            foreach (var child in element.Children())
            {
                PopulateBindings(child, list);
            }
        }
Example #17
0
 public static void RecursiveFromStyle(VisualElement element, ref Dictionary <string, VisualElement> fields)
 {
     if (element.customStyle.TryGetValue(new CustomStyleProperty <string>("--csName"), out string name))
     {
         if (fields.ContainsKey(name))
         {
             Debug.LogError($"UXML has multiple elements with \"{name}\" --csName, only first one will be referenced");
         }
         else
         {
             fields.Add(name, element);
         }
     }
     foreach (var item in element.Children())
     {
         RecursiveFromStyle(item, ref fields);
     }
 }
        public static VisualElement GetRootRecursively(this VisualElement el)
        {
            if (el.parent == null)
            {
                return(el);

                foreach (var child in el.Children())
                {
                    if (child.style.display != DisplayStyle.None && child.ClassListContains(documentRootUssClassName))
                    {
                        return(child);
                    }
                }
                return(null);// el.Q(null, "unity-ui-document__root");
            }

            return(el.parent.GetRootRecursively());
        }
Example #19
0
        private void DrawValueField()
        {
            // Clear previous field
            if (fieldContainer.Children().Any())
            {
                fieldContainer.Clear();
            }

            // Create a type-specific field for each different variable type, set the right value (mainly null handling),
            // and register the type-specific callback
            VisualElement field;

            switch (worldVars.GetType(guid))
            {
            case VariableType.String:
                field = new TextField();
                field.RegisterCallback <ChangeEvent <string> >(UpdateWorldvarValue);
                break;

            case VariableType.Bool:
                field = new Toggle();
                field.RegisterCallback <ChangeEvent <bool> >(UpdateWorldvarValue);
                break;

            case VariableType.Long:
                field = new LongField();
                field.RegisterCallback <ChangeEvent <long> >(UpdateWorldvarValue);
                break;

            case VariableType.Double:
                field = new DoubleField();
                field.RegisterCallback <ChangeEvent <double> >(UpdateWorldvarValue);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            field.name = fieldName;
            fieldContainer.Add(field);

            SetFieldValue(worldVars.GetValue(guid));
        }
        void RegisterBindings(VisualElement content)
        {
            if (content is CustomInspectorElement && content != this)
            {
                return;
            }

            var popRelativePartCount = 0;

            if (content is BindableElement b && !string.IsNullOrEmpty(b.bindingPath))
            {
                if (b.bindingPath != ".")
                {
                    var previousCount = m_RelativePath.PartsCount;
                    m_RelativePath.AppendPath(b.bindingPath);
                    m_AbsolutePath.AppendPath(b.bindingPath);
                    popRelativePartCount = m_RelativePath.PartsCount - previousCount;
                }

                if (Inspector.IsPathValid(m_RelativePath))
                {
                    RegisterBindings(Inspector, m_RelativePath, content, m_Root);
                }
                else if (Inspector.IsPathValid(m_AbsolutePath))
                {
                    RegisterBindings(Inspector, m_AbsolutePath, content, m_Root);
                }
                m_AbsolutePath.Clear();
            }

            if (!(content is PropertyElement) && !(content is DefaultInspectorElement))
            {
                foreach (var child in content.Children())
                {
                    RegisterBindings(child);
                }
            }

            for (var i = 0; i < popRelativePartCount; ++i)
            {
                m_RelativePath.Pop();
            }
        }
        public void UpdateEventList()
        {
            if (m_AttachedComponent == null)
            {
                if (m_EventsContainer != null)
                {
                    m_EventsContainer.Clear();
                }
                m_Events.Clear();
            }
            else
            {
                var eventNames = GetEventNames().ToArray();

                foreach (var removed in m_Events.Keys.Except(eventNames).ToArray())
                {
                    var ui = m_Events[removed];
                    m_EventsContainer.Remove(ui);
                    m_Events.Remove(removed);
                }

                foreach (var added in eventNames.Except(m_Events.Keys).ToArray())
                {
                    var tpl = VFXView.LoadUXML("VFXComponentBoard-event");

                    tpl.CloneTree(m_EventsContainer);

                    VFXComponentBoardEventUI newUI = m_EventsContainer.Children().Last() as VFXComponentBoardEventUI;
                    if (newUI != null)
                    {
                        newUI.Setup();
                        newUI.name = added;
                        m_Events.Add(added, newUI);
                    }
                }

                if (!m_Events.Values.Any(t => t.nameHasFocus))
                {
                    SortEventList();
                }
            }
        }
Example #22
0
        static void AlignInspectorLabelWidth(VisualElement element, float topLevelLabelWidth, int indentLevel)
        {
            if (element.ClassListContains(UssClasses.Unity.Label))
            {
                element.style.width    = Mathf.Max(topLevelLabelWidth - indentLevel * k_Indent, 0.0f);
                element.style.minWidth = 0;
#if UNITY_2020_1_OR_NEWER
                element.style.textOverflow = TextOverflow.Ellipsis;
#endif
                element.style.flexWrap   = Wrap.NoWrap;
                element.style.overflow   = Overflow.Hidden;
                element.style.whiteSpace = WhiteSpace.NoWrap;
            }

            if (element is Foldout)
            {
                var label = element.Q <Toggle>().Q(className: UssClasses.ListElement.ToggleInput);
                if (null != label)
                {
                    label.style.width    = Mathf.Max(topLevelLabelWidth - indentLevel * k_Indent + 16.0f, 0.0f);
                    label.style.minWidth = 0;
#if UNITY_2020_1_OR_NEWER
                    label.style.textOverflow = TextOverflow.Ellipsis;
#endif
                    label.style.flexWrap   = Wrap.NoWrap;
                    label.style.overflow   = Overflow.Hidden;
                    label.style.whiteSpace = WhiteSpace.NoWrap;
                }

                ++indentLevel;
            }

            if (element is IReloadableElement && element.ClassListContains(UssClasses.ListElement.Item))
            {
                --indentLevel;
            }

            foreach (var child in element.Children())
            {
                AlignInspectorLabelWidth(child, topLevelLabelWidth, indentLevel);
            }
        }
Example #23
0
        public void UpdateEventList()
        {
            if (m_AttachedComponent == null)
            {
                if (m_EventsContainer != null)
                {
                    m_EventsContainer.Clear();
                }
                m_Events.Clear();
            }
            else
            {
                var eventNames = controller.contexts.Select(t => t.model).OfType <VFXBasicEvent>().Select(t => t.eventName).Except(staticEventNames).Distinct().OrderBy(t => t).ToArray();

                foreach (var removed in m_Events.Keys.Except(eventNames).ToArray())
                {
                    var ui = m_Events[removed];
                    m_EventsContainer.Remove(ui);
                    m_Events.Remove(removed);
                }

                foreach (var added in eventNames.Except(m_Events.Keys).ToArray())
                {
                    var tpl = Resources.Load <VisualTreeAsset>("uxml/VFXComponentBoard-event");

                    tpl.CloneTree(m_EventsContainer, new Dictionary <string, VisualElement>());

                    VFXComponentBoardEventUI newUI = m_EventsContainer.Children().Last() as VFXComponentBoardEventUI;
                    if (newUI != null)
                    {
                        newUI.Setup();
                        newUI.name = added;
                        m_Events.Add(added, newUI);
                    }
                }

                if (!m_Events.Values.Any(t => t.nameHasFocus))
                {
                    SortEventList();
                }
            }
        }
Example #24
0
        void RegisterSearchHandlers(VisualElement content)
        {
            if (content is CustomInspectorElement && content != this)
            {
                return;
            }

            if (content is SearchElement search)
            {
                search.ResolveSearchHandlerBindings(m_Root);
            }

            if (!(content is BindingContextElement) && !(content is DefaultInspectorElement))
            {
                foreach (var child in content.Children())
                {
                    RegisterSearchHandlers(child);
                }
            }
        }
        public static void SortElementsByTheirVisualElementInAsset(VisualElement parentVE)
        {
            var parentVEA = parentVE.GetVisualElementAsset();

            if (parentVEA == null)
            {
                return;
            }

            if (parentVE.childCount <= 1)
            {
                return;
            }

            var correctOrderForElementAssets = new List <VisualElementAsset>();
            var correctOrdersInDocument      = new List <int>();

            foreach (var ve in parentVE.Children())
            {
                var vea = ve.GetVisualElementAsset();
                if (vea == null)
                {
                    continue;
                }

                correctOrderForElementAssets.Add(vea);
                correctOrdersInDocument.Add(vea.orderInDocument);
            }

            if (correctOrderForElementAssets.Count <= 1)
            {
                return;
            }

            correctOrdersInDocument.Sort();

            for (int i = 0; i < correctOrderForElementAssets.Count; ++i)
            {
                correctOrderForElementAssets[i].orderInDocument = correctOrdersInDocument[i];
            }
        }
Example #26
0
        private void RefreshView()
        {
            // Calculate slice of list to be rendered.
            var firstIndex = currentPage * elementsPerPage;
            var length     = Math.Min(elementsPerPage, data.Count - firstIndex);

            // If the child count is the same, don't adjust it.
            // If the child count is less, add the requisite number.
            // If the child count is more, pop elements off the end.

            var diff = container.childCount - length;

            if (diff > 0)
            {
                for (var i = 0; i < diff; i++)
                {
                    var element = container.ElementAt(container.childCount - 1);
                    container.RemoveAt(container.childCount - 1);
                    elementPool.Return((TElement)element);
                }
            }
            else if (diff < 0)
            {
                for (var i = diff; i < 0; i++)
                {
                    container.Add(elementPool.GetOrCreate());
                }
            }

            // At this point, container.Children() has the same length as the slice.
            var elementIndex = firstIndex;

            foreach (var child in container.Children())
            {
                bindElement(elementIndex, data[elementIndex], (TElement)child);
                elementIndex++;
            }

            backButton.SetEnabled(currentPage != 0);
            forwardButton.SetEnabled(currentPage != numPages - 1);
        }
Example #27
0
        //switch between content
        private void ShowTab(string screen)
        {
            VisualElement rightColumn = rootVisualElement.Q <VisualElement>("RightColumnBox");

            foreach (VisualElement tab in rightColumn.Children())
            {
                if (tab.name == screen)
                {
                    if (tab.name == "ChangeLog" && ShowChangeLog)
                    {
                        tab.Q <Label>("Header").text = "Change Log (updated)";
                    }

                    tab.style.display = DisplayStyle.Flex;
                }
                else
                {
                    tab.style.display = DisplayStyle.None;
                }
            }
        }
        public void OnEnable()
        {
            missionList = new List <TableMissionItem>();


            //


            VisualElement root = rootVisualElement;

            var           visualTree    = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>($"{path}/Editor/EditorWindow/TableParseEditorWindow.uxml");
            VisualElement labelFromUXML = visualTree.CloneTree();

            root.Add(labelFromUXML);

            var styleSheet = AssetDatabase.LoadAssetAtPath <StyleSheet>($"{path}/Editor/EditorWindow/TableParseEditorWindow.uss");

            root.Children().First().style.flexGrow = 1F;

            root.Q <Button>("SelectFile").clickable.clicked    += SelectFile;
            root.Q <Button>("BreakProgress").clickable.clicked += BreakProgress;
            root.Q <Button>("ResetMission").clickable.clicked  += ResetMission;


            root.Q <Toggle>("ToggleHideLog").RegisterValueChangedCallback(b =>
            {
                hideLogs = b.newValue;
            });

            btnExecute = root.Q <Button>("Execute");
            btnExecute.clickable.clicked += Execute;

            btnBreakProgress = root.Q <Button>("BreakProgress");
            bar = root.Q <ProgressBar>("progress");

            btnExecute.style.display       = new StyleEnum <DisplayStyle>(DisplayStyle.Flex);
            btnBreakProgress.style.display = new StyleEnum <DisplayStyle>(DisplayStyle.None);

            FreshMissionList();
        }
        public static void ReorderStyleSheetsInAsset(
            BuilderDocument document, VisualElement styleSheetsContainerElement)
        {
            Undo.RegisterCompleteObjectUndo(
                document.visualTreeAsset, "Reorder StyleSheets in UXML");

            var reorderedUSSList = new List <StyleSheet>();

            foreach (var ussElement in styleSheetsContainerElement.Children())
            {
                reorderedUSSList.Add(ussElement.GetStyleSheet());
            }

            var openUXMLFile = document.activeOpenUXMLFile;

            openUXMLFile.openUSSFiles.Sort((left, right) =>
            {
                var leftOrder  = reorderedUSSList.IndexOf(left.styleSheet);
                var rightOrder = reorderedUSSList.IndexOf(right.styleSheet);
                return(leftOrder.CompareTo(rightOrder));
            });
        }
        public void InitializeGraph(BaseGraph graph)
        {
            this.graph = graph;

            if (graphView != null)
            {
                rootView.Remove(graphView);
            }

            //Initialize will provide the BaseGraphView
            Initialize(graph);

            graphView = rootView.Children().FirstOrDefault(e => e is BaseGraphView) as BaseGraphView;

            if (graphView == null)
            {
                Debug.LogError("GraphView has not been added to the BaseGraph root view !");
                return;
            }

            graphView.Initialize(graph);
        }