示例#1
0
        public void RecomputeBounds()
        {
            if (m_WaitingRecompute)
            {
                return;
            }
            //title width should be at least as wide as a context to be valid.
            float titleWidth        = m_Title.layout.width;
            bool  invalidTitleWidth = float.IsNaN(titleWidth) || titleWidth < 50;
            bool  titleEmpty        = string.IsNullOrEmpty(m_Title.text) || invalidTitleWidth;

            if (titleEmpty)
            {
                m_Title.AddToClassList("empty");
            }
            else
            {
                m_Title.RemoveFromClassList("empty");
            }

            Rect rect = Rect.zero;

            if (m_Contexts != null)
            {
                foreach (var context in m_Contexts)
                {
                    if (context != null)
                    {
                        if (rect == Rect.zero)
                        {
                            rect = context.localBound;
                        }
                        else
                        {
                            rect = RectUtils.Encompass(rect, context.GetPosition());
                        }
                    }
                }
            }

            if (float.IsNaN(rect.xMin) || float.IsNaN(rect.yMin) || float.IsNaN(rect.width) || float.IsNaN(rect.height))
            {
                rect = Rect.zero;
            }

            rect = RectUtils.Inflate(rect, 20, titleEmpty ? 20 : m_Title.layout.height, 20, 20);

            if (invalidTitleWidth)
            {
                SetPosition(rect);
                if (!m_WaitingRecompute)
                {
                    m_WaitingRecompute = true;
                    schedule.Execute(() => { m_WaitingRecompute = false; RecomputeBounds(); }).ExecuteLater(0); // title height might have changed if width have changed
                }
            }
            else
            {
                SetPosition(rect);
            }
        }
        void UpdateEventCallbacks(EventDebuggerEventRecord eventBase)
        {
            ClearEventCallbacks();

            if (eventBase == null)
            {
                return;
            }

            var callbacks = m_Debugger.GetCalls(panel, eventBase);

            if (callbacks != null)
            {
                foreach (EventDebuggerCallTrace callback in callbacks)
                {
                    VisualElement container = new VisualElement {
                        name = "line-container"
                    };

                    Label timeStamp = new Label {
                        name = "timestamp"
                    };
                    Label handler = new Label {
                        name = "handler"
                    };
                    Label phaseDurationContainer = new Label {
                        name = "phaseDurationContainer"
                    };
                    Label phase = new Label {
                        name = "phase"
                    };
                    Label duration = new Label {
                        name = "duration"
                    };

                    timeStamp.AddToClassList("log-line-item");
                    handler.AddToClassList("log-line-item");
                    phaseDurationContainer.AddToClassList("log-line-item");

                    timeStamp.text = "[" + eventBase.TimestampString() + "]";
                    handler.text   = callback.callbackName;
                    if (callback.immediatePropagationHasStopped)
                    {
                        handler.text += " Immediately Stopped Propagation";
                    }
                    else if (callback.propagationHasStopped)
                    {
                        handler.text += " Stopped Propagation";
                    }
                    if (callback.defaultHasBeenPrevented)
                    {
                        handler.text += " (Default Prevented)";
                    }

                    phase.text    = callback.eventBase.propagationPhase.ToString();
                    duration.text = "Duration: " + callback.duration / 1000f + "ms";

                    container.Add(timeStamp);
                    container.Add(handler);
                    phaseDurationContainer.Add(phase);
                    phaseDurationContainer.Add(duration);
                    container.Add(phaseDurationContainer);

                    m_EventCallbacksScrollView.Add(container);

                    var hash = callback.callbackHashCode;
                    HighlightCodeline(hash);
                }
            }

            var defaultActions = m_Debugger.GetDefaultActions(panel, eventBase);

            if (defaultActions == null)
            {
                return;
            }

            foreach (EventDebuggerDefaultActionTrace defaultAction in defaultActions)
            {
                VisualElement container = new VisualElement {
                    name = "line-container"
                };

                Label timeStamp = new Label {
                    name = "timestamp"
                };
                Label handler = new Label {
                    name = "handler"
                };
                Label phaseDurationContainer = new Label {
                    name = "phaseDurationContainer"
                };
                Label phase = new Label {
                    name = "phase"
                };
                Label duration = new Label {
                    name = "duration"
                };

                timeStamp.AddToClassList("log-line-item");
                handler.AddToClassList("log-line-item");
                phaseDurationContainer.AddToClassList("log-line-item");

                timeStamp.text = "[" + eventBase.TimestampString() + "]";
                handler.text   = defaultAction.targetName + "." +
                                 (defaultAction.phase == PropagationPhase.AtTarget
                        ? "ExecuteDefaultActionAtTarget"
                        : "ExecuteDefaultAction");

                duration.text = "Duration: " + defaultAction.duration / 1000f + "ms";

                container.Add(timeStamp);
                container.Add(handler);
                phaseDurationContainer.Add(phase);
                phaseDurationContainer.Add(duration);
                container.Add(phaseDurationContainer);

                m_EventCallbacksScrollView.Add(container);
            }
        }
示例#3
0
        public MinMaxGradientField(MinMaxGradientPropertyDrawer.PropertyData propertyData, string label) : base(label, null)
        {
            if (propertyData != null)
            {
                m_ColorMin = new PropertyField(propertyData.colorMin, "");
                m_ColorMin.AddToClassList(colorFieldUssClass);
                m_ColorMax = new PropertyField(propertyData.colorMax, "");
                m_ColorMax.AddToClassList(colorFieldUssClass);
                m_GradientMin  = new PropertyField(propertyData.gradientMin, "");
                m_GradientMax  = new PropertyField(propertyData.gradientMax, "");
                m_ModeDropdown = new DropdownField
                {
                    choices = stringModes.ToList()
                };
                m_ModeDropdown.createMenuCallback = () =>
                {
                    var osMenu = new GenericOSMenu();

                    for (int i = 0; i < stringModes.Length; i++)
                    {
                        var option          = stringModes[i];
                        var isValueSelected = propertyData.mode.intValue == i;

                        osMenu.AddItem(option, isValueSelected, () =>
                        {
                            m_ModeDropdown.value = option;
                        });
                    }

                    return(osMenu);
                };
                m_ModeDropdown.formatSelectedValueCallback = (value) =>
                {
                    // Don't show label for this dropdown
                    return("");
                };

                m_ModeDropdown.index = propertyData.mode.intValue;
                m_ModeDropdown.AddToClassList(dropdownFieldUssClass);
                m_MixedValueTypeLabel = new Label("\u2014");
                m_MixedValueTypeLabel.AddToClassList(multipleValuesLabelUssClass);

                var dropdownInput = m_ModeDropdown.Q <VisualElement>(null, "unity-popup-field__input");
                dropdownInput.AddToClassList(dropdownInputUssClass);

                m_GradientsContainer = new VisualElement();
                m_GradientsContainer.AddToClassList(gradientContainerUssClass);
                m_GradientsContainer.Add(m_GradientMin);
                m_GradientsContainer.Add(m_GradientMax);

                visualInput.AddToClassList(visualInputUssClass);
                visualInput.Add(m_ColorMin);
                visualInput.Add(m_ColorMax);
                visualInput.Add(m_GradientsContainer);
                visualInput.Add(m_MixedValueTypeLabel);
                visualInput.Add(m_ModeDropdown);

                m_ModeDropdown.RegisterCallback <ChangeEvent <string> >(e =>
                {
                    var index = Array.IndexOf(stringModes, e.newValue);
                    var mode  = (MinMaxGradientState)index;

                    propertyData.mode.intValue = index;
                    propertyData.mode.serializedObject.ApplyModifiedProperties();
                    UpdateFieldsDisplay(propertyData.mode);
                });

                UpdateFieldsDisplay(propertyData.mode);
            }
        }
        public MaskedInputField()
        {
            if (monoFont == null)
            {
                monoFont = AssetFileExtensions.GetFont("SourceCodePro-Medium");
            }
            if (monoFont == null)
            {
                Debug.Log($"Font not found");
            }

            AddToClassList(UssClassName);
            editorType = GetType();
            styleSheets.Add(StylesheetSetup());
            style.unityFont = monoFont;

            var textInputBase = this.Q("unity-text-input");

            VisualElementExtension.NameAsUSS(textInputBase, nameof(textInputBase));
            textInputBase.style.display = DisplayStyle.Flex;
            textInputBase.style.color   = new StyleColor(StyleKeyword.Initial);
            VisualElementExtension.SetBorderWidth(textInputBase, 2);

            maskedText = new TextField
            {
                style       = { display = DisplayStyle.Flex, position = Position.Absolute, unityFont = monoFont },
                value       = "",
                pickingMode = PickingMode.Ignore,
            };
            maskedInput             = maskedText.Q("unity-text-input");
            maskedInput.pickingMode = PickingMode.Ignore;
            VisualElementExtension.NameAsUSS(maskedInput, nameof(maskedInput));


            VisualElementExtension.NameAsUSS(maskedText, nameof(maskedText));
            maskedText.AddToClassList(UssClassName);
            Add(maskedText);

            this.RegisterCallback <MouseUpEvent>(evt =>
            {
                VisualElementExtension.SelectRangeDelayed(this, maskedText.text.Length, maskedText.text.Length);
                evt.StopPropagation();
            });

            // Add and configure placeholder
            m_PlaceholderLabel = new Label {
                pickingMode = PickingMode.Ignore
            };
            m_PlaceholderLabel.AddToClassList(PlaceholderUssClassName);
            maskedText.Add(m_PlaceholderLabel);

            RegisterCallback <FocusInEvent>(e => HidePlaceholder());
            RegisterCallback <FocusOutEvent>(e =>
            {
                if (string.IsNullOrEmpty(text))
                {
                    ShowPlaceholder();
                }
            });

            this.RegisterCallback <GeometryChangedEvent>(DeferredExecution);
            this.RegisterValueChangedCallback(e => OnValueChangedHandler?.Invoke(e.newValue));
        }
示例#5
0
        public ArrayElementBuilder(SerializedProperty arrayProperty, FieldData fieldType,
                                   Func <string, int, bool, VisualElement> makeItem = null, Action <string, int, bool> on_add_item = null)
        {
            m_ArrayProperty = arrayProperty;
            this.fieldType  = fieldType;
            m_ArrayProperty.serializedObject.Update();
            addNewArraySize = m_ArrayProperty.arraySize;
            AddToClassList("arrayElementBuilder");

            // -------------------------------------------- arrayFoldout
            var arrayFoldout = new Foldout {
                text = arrayProperty.displayName, name = "arrayFoldout"
            };

            arrayFoldout.AddToClassList("arrayFoldout");
            arrayFoldout.value = false;

            // -------------------------------------------- baseContainer
            baseContainer = new VisualElement {
                name = "arrayBaseContainer"
            };
            baseContainer.AddToClassList("arrayBaseContainer");

            arrayFoldout.Add(baseContainer);
            hierarchy.Add(arrayFoldout);

            // -------------------------------------------- addButton
            addButton = new Button(AddNewItem)
            {
                text = "+", name = "arrayAddButton"
            };
            addButton.AddToClassList("arrayAddButton");

            arrayPath     = arrayProperty.propertyPath;
            boundObject   = arrayProperty.serializedObject;
            this.makeItem = makeItem;
            var property    = arrayProperty.Copy();
            var endProperty = property.GetEndProperty();

            // -------------------------------------------- iterator
            property.NextVisible(true);
            do
            {
                if (SerializedProperty.EqualContents(property, endProperty))
                {
                    break;
                }
                if (property.propertyType != SerializedPropertyType.ArraySize)
                {
                    continue;
                }
                arraySize   = property.intValue;
                bindingPath = property.propertyPath;
                break;
            } while (property.NextVisible(false));

            arrayProperty.serializedObject.SetIsDifferentCacheDirty();
            UpdateCreatedItems();

            // -------------------------------------------- arrayFooter
            var arrayFooter = new VisualElement {
                name = "ArrayFooter"
            };

            arrayFooter.AddToClassList("arrayFooter");
            arrayFooterLabel = new Label($"Total: {childCount.ToString()}");
            arrayFooterLabel.AddToClassList("arrayFooterLabel");
            arrayFooter.Add(arrayFooterLabel);

            onAddItem = on_add_item;

            arrayFooter.Add(addButton);
            arrayFoldout.Add(arrayFooter);
            m_ArrayProperty.serializedObject.ApplyModifiedProperties();
        }
示例#6
0
        void OnEnable()
        {
            minSize = new Vector2(560.0f, 200.0f);

#if UNITY_2019_1_OR_NEWER
            var root = rootVisualElement;
            root.styleSheets.Add(Resources.Load <StyleSheet>(s_StylesFolder + "recorder"));
            root.styleSheets.Add(Resources.Load <StyleSheet>(s_StylesFolder + (EditorGUIUtility.isProSkin ? "recorder_darkSkin" : "recorder_lightSkin")));
#else
            var root = this.GetRootVisualContainer();
            root.AddStyleSheetPath(s_StylesFolder + "recorder");
            root.AddStyleSheetPath(s_StylesFolder + (EditorGUIUtility.isProSkin ? "recorder_darkSkin" : "recorder_lightSkin"));
#endif

            root.style.flexDirection = FlexDirection.Column;
            UIElementHelper.SetFocusable(root);

            var mainControls = new VisualElement
            {
                style =
                {
                    flexDirection = FlexDirection.Row,
                    minHeight     = 110.0f
                }
            };
            root.Add(mainControls);

            var controlLeftPane = new VisualElement
            {
                style =
                {
#if UNITY_2018_1
                    minWidth      =            350.0f,
#else
                    minWidth      =            180.0f,
#endif
                    maxWidth      =            450.0f,
                    flexDirection = FlexDirection.Row,
                }
            };

            UIElementHelper.SetFlex(controlLeftPane, 0.5f);

            var controlRightPane = new VisualElement
            {
                style =
                {
                    flexDirection = FlexDirection.Column,
                }
            };

            UIElementHelper.SetFlex(controlRightPane, 0.5f);

            mainControls.Add(controlLeftPane);
            mainControls.Add(controlRightPane);

            controlLeftPane.AddToClassList("StandardPanel");
            controlRightPane.AddToClassList("StandardPanel");

            m_RecordButtonIcon = new Button(OnRecordButtonClick)
            {
                name  = "recorderIcon",
                style =
                {
                    backgroundImage = Resources.Load <Texture2D>("recorder_icon"),
                }
            };

            controlLeftPane.Add(m_RecordButtonIcon);


            var leftButtonsStack = new VisualElement
            {
                style =
                {
                    flexDirection = FlexDirection.Column,
                }
            };

            UIElementHelper.SetFlex(leftButtonsStack, 1.0f);

            m_RecordButton = new Button(OnRecordButtonClick)
            {
                name = "recordButton"
            };

            UpdateRecordButtonText();

            leftButtonsStack.Add(m_RecordButton);

            m_RecordOptionsPanel = new IMGUIContainer(() =>
            {
                PrepareGUIState(m_RecordOptionsPanel.layout.width);
                Options.exitPlayMode = EditorGUILayout.Toggle(Styles.ExitPlayModeLabel, Options.exitPlayMode);
            })
            {
                name = "recordOptions"
            };

            UIElementHelper.SetFlex(m_RecordOptionsPanel, 1.0f);

            leftButtonsStack.Add(m_RecordOptionsPanel);

            m_RecordModeOptionsPanel = new IMGUIContainer(() =>
            {
                PrepareGUIState(m_RecordModeOptionsPanel.layout.width);
                if (m_RecorderSettingsPrefsEditor.RecordModeGUI())
                {
                    OnGlobalSettingsChanged();
                }
            });

            UIElementHelper.SetFlex(m_RecordModeOptionsPanel, 1.0f);

            leftButtonsStack.Add(m_RecordModeOptionsPanel);

            controlLeftPane.Add(leftButtonsStack);

            m_FrameRateOptionsPanel = new IMGUIContainer(() =>
            {
                PrepareGUIState(m_FrameRateOptionsPanel.layout.width);
                if (m_RecorderSettingsPrefsEditor.FrameRateGUI())
                {
                    OnGlobalSettingsChanged();
                }
            });

            UIElementHelper.SetFlex(m_FrameRateOptionsPanel, 1.0f);

            controlRightPane.Add(m_FrameRateOptionsPanel);

            m_SettingsPanel = new ScrollView();

            UIElementHelper.SetFlex(m_SettingsPanel, 1.0f);

            UIElementHelper.ResetStylePosition(m_SettingsPanel.contentContainer.style);

            var recordersAndParameters = new VisualElement
            {
                style =
                {
                    alignSelf     = Align.Stretch,
                    flexDirection = FlexDirection.Row,
                }
            };

            UIElementHelper.SetFlex(recordersAndParameters, 1.0f);

            m_RecordersPanel = new VisualElement
            {
                name  = "recordersPanel",
                style =
                {
                    width    = 200.0f,
                    minWidth = 150.0f,
                    maxWidth = 500.0f
                }
            };

            m_RecordersPanel.AddToClassList("StandardPanel");

            m_PanelSplitter = new PanelSplitter(m_RecordersPanel);

            recordersAndParameters.Add(m_RecordersPanel);
            recordersAndParameters.Add(m_PanelSplitter);
            recordersAndParameters.Add(m_SettingsPanel);

            m_SettingsPanel.AddToClassList("StandardPanel");

            root.Add(recordersAndParameters);

            var addRecordButton = new Label("+ Add New Recorders");
            UIElementHelper.SetFlex(addRecordButton, 1.0f);

            var recorderListPresetButton = new VisualElement
            {
                name = "recorderListPreset"
            };

            recorderListPresetButton.RegisterCallback <MouseUpEvent>(evt => ShowRecorderListMenu());

            recorderListPresetButton.Add(new Image
            {
                image = (Texture2D)EditorGUIUtility.Load("Builtin Skins/" + (EditorGUIUtility.isProSkin ? "DarkSkin" : "LightSkin") + "/Images/pane options.png"),
                style =
                {
                    width  = 16.0f,
                    height = 11.0f
                }
            });

            addRecordButton.AddToClassList("RecorderListHeader");
            recorderListPresetButton.AddToClassList("RecorderListHeader");

            addRecordButton.RegisterCallback <MouseUpEvent>(evt => ShowNewRecorderMenu());

            m_AddNewRecordPanel = new VisualElement
            {
                name  = "addRecordersButton",
                style = { flexDirection = FlexDirection.Row }
            };


            m_AddNewRecordPanel.Add(addRecordButton);
            m_AddNewRecordPanel.Add(recorderListPresetButton);

            m_RecordingListItem = new RecorderItemList
            {
                name = "recorderList"
            };

            UIElementHelper.SetFlex(m_RecordingListItem, 1.0f);
            UIElementHelper.SetFocusable(m_RecordingListItem);

            m_RecordingListItem.OnItemContextMenu  += OnRecordContextMenu;
            m_RecordingListItem.OnSelectionChanged += OnRecordSelectionChanged;
            m_RecordingListItem.OnItemRename       += item => item.StartRenaming();
            m_RecordingListItem.OnContextMenu      += ShowNewRecorderMenu;

            m_RecordersPanel.Add(m_AddNewRecordPanel);
            m_RecordersPanel.Add(m_RecordingListItem);

            m_ParametersControl = new VisualElement
            {
                style =
                {
                    minWidth = 300.0f,
                }
            };

            UIElementHelper.SetFlex(m_ParametersControl, 1.0f);

            m_ParametersControl.Add(new Button(OnRecorderSettingPresetClicked)
            {
                name  = "presetButton",
                style =
                {
                    alignSelf       = Align.FlexEnd,
                    backgroundImage = PresetHelper.presetIcon,
                    paddingTop      =                    0.0f,
                    paddingLeft     =                    0.0f,
                    paddingBottom   =                    0.0f,
                    paddingRight    =                    0.0f,
#if UNITY_2019_1_OR_NEWER
                    unityBackgroundScaleMode = ScaleMode.ScaleToFit,
#elif UNITY_2018_3_OR_NEWER
                    backgroundScaleMode      = ScaleMode.ScaleToFit,
#else
                    backgroundSize           = ScaleMode.ScaleToFit,
#endif
#if UNITY_2019_1_OR_NEWER
                    unitySliceTop    =                       0,
                    unitySliceBottom =                       0,
                    unitySliceLeft   =                       0,
                    unitySliceRight  =                       0,
#else
                    sliceTop    =                       0,
                    sliceBottom =                       0,
                    sliceLeft   =                       0,
                    sliceRight  =                       0,
#endif
                }
            });

            m_RecorderSettingPanel = new IMGUIContainer(OnRecorderSettingsGUI)
            {
                name = "recorderSettings"
            };

            UIElementHelper.SetFlex(m_RecorderSettingPanel, 1.0f);

            var statusBar = new VisualElement
            {
                name = "statusBar"
            };

            statusBar.Add(new IMGUIContainer(UpdateRecordingProgressGUI));

            root.Add(statusBar);

            m_ParametersControl.Add(m_RecorderSettingPanel);

            m_SettingsPanel.Add(m_ParametersControl);

            m_ControllerSettings = RecorderControllerSettings.LoadOrCreate(Application.dataPath + s_PrefsFileName);
            m_RecorderController = new RecorderController(m_ControllerSettings);

            m_RecorderSettingsPrefsEditor = (RecorderSettingsPrefsEditor)Editor.CreateEditor(m_ControllerSettings);


#if UNITY_2018_2_OR_NEWER
            m_RecordingListItem.RegisterCallback <ValidateCommandEvent>(OnRecorderListValidateCommand);
            m_RecordingListItem.RegisterCallback <ExecuteCommandEvent>(OnRecorderListExecuteCommand);
#else
            m_RecordingListItem.RegisterCallback <IMGUIEvent>(OnRecorderListIMGUI);
#endif

            m_RecordingListItem.RegisterCallback <KeyUpEvent>(OnRecorderListKeyUp);

            ReloadRecordings();

            Undo.undoRedoPerformed += SaveAndRepaint;

            EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
        }
示例#7
0
        public NullElement(string name)
        {
            styleSheets.Add(AssetDatabase.LoadAssetAtPath <StyleSheet>("Packages/com.unity.properties/Editor Default Resources/uss/null-element.uss"));
            AddToClassList("unity-properties-null");

            var label = new Label(name);

            label.AddToClassList("unity-properties-null--label");
            Add(label);

            var constructibleTypes = TypeConstruction.GetAllConstructibleTypes <TType>();

            if (constructibleTypes.Count > 0)
            {
                var button = new Button()
                {
                    text        = "New Instance",
                    bindingPath = name
                };

                // Multiple choices are available
                if (constructibleTypes.Count > 1)
                {
                    button.clickable.clicked += () =>
                    {
                        var menu = new GenericMenu();
                        foreach (var type in TypeConstruction.GetAllConstructibleTypes <TType>())
                        {
                            var t = type;
                            menu.AddItem(new GUIContent(t.Name), false, () =>
                            {
                                var newValue = TypeConstruction.Construct <TType>(type);
                                var binding  = GetFirstAncestorOfType <PropertyElement>();
                                binding.SetValue(button, newValue);
                                binding.Refresh(true);
                            });
                        }

                        menu.DropDown(button.worldBound);
                    };
                }
                else
                {
                    button.clickable.clicked += () =>
                    {
                        var type     = constructibleTypes[0];
                        var newValue = type == typeof(TType)
                            ? TypeConstruction.Construct <TType>()
                            : TypeConstruction.Construct <TType>(type);

                        var binding = GetFirstAncestorOfType <PropertyElement>();
                        binding.SetValue(button, newValue);
                        binding.Refresh(true);
                    };
                }

                button.AddToClassList("unity-properties-null--button");
                Add(button);
            }
            else
            {
                var value = new Label("Cannot create new Instance");
                value.AddToClassList("unity-properties-null--value");
                Add(value);
            }
        }
        static void BuildHighlightLabels(VisualElement container, string formattedHighlightText)
        {
            if (string.IsNullOrEmpty(formattedHighlightText))
            {
                return;
            }

            var substring    = string.Empty;
            var highlighting = false;
            var skipCount    = 0;

            foreach (var character in formattedHighlightText.ToCharArray())
            {
                switch (character)
                {
                // Skip embedded separators
                // Ex:
                // Query: middle e
                // Text: Middle Eastern
                // Formatted Text: {Middl{e}} {E}ast{e}rn
                //                      ^ ^
                case k_StartHighlightSeparator when highlighting:
                    skipCount++;
                    continue;

                case k_StartHighlightSeparator: {
                    highlighting = true;
                    if (!string.IsNullOrEmpty(substring))
                    {
                        container.Add(new Label(substring));
                        substring = string.Empty;
                    }

                    continue;
                }

                case k_EndHighlightSeparator when skipCount > 0:
                    skipCount--;
                    continue;

                case k_EndHighlightSeparator: {
                    var label = new Label(substring);
                    label.AddToClassList(k_HighlightedStyleClassName);
                    container.Add(label);

                    highlighting = false;
                    substring    = string.Empty;

                    continue;
                }

                default:
                    substring += character;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(substring))
            {
                var label = new Label(substring);
                if (highlighting)
                {
                    label.AddToClassList(k_HighlightedStyleClassName);
                }
                container.Add(label);
            }
        }
示例#9
0
        public override void Enable(bool fromInspector)
        {
            var stylesheet = Resources.Load <StyleSheet>(stylesheetName);

            if (!styleSheets.Contains(stylesheet))
            {
                styleSheets.Add(stylesheet);
            }

            nodeTarget.onProcessed += UpdateTexturePreview;

            // Fix the size of the node
            style.width = nodeTarget.nodeWidth;

            controlsContainer.AddToClassList("ControlsContainer");

            if (!String.IsNullOrEmpty(header))
            {
                var title = new Label(header);
                title.AddToClassList("PropertyEditorTitle");
                controlsContainer.Add(title);
            }

            // No preview in the inspector, we display it in the preview
            if (!fromInspector)
            {
                pinIcon = new Image {
                    image = MixtureEditorUtils.pinIcon, scaleMode = ScaleMode.ScaleToFit
                };
                var pinButton = new Button(() => {
                    if (nodeTarget.isPinned)
                    {
                        UnpinView();
                    }
                    else
                    {
                        PinView();
                    }
                });
                pinButton.Add(pinIcon);
                if (nodeTarget.isPinned)
                {
                    PinView();
                }

                pinButton.AddToClassList("PinButton");
                rightTitleContainer.Add(pinButton);

                previewContainer = new VisualElement();
                previewContainer.AddToClassList("Preview");
                controlsContainer.Add(previewContainer);
                UpdateTexturePreview();
            }

            InitProcessingTimeLabel();

            if (nodeTarget.showDefaultInspector)
            {
                DrawDefaultInspector(fromInspector);
            }
        }
示例#10
0
        public override VisualElement CreateInspectorGUI()
        {
            var container = new VisualElement();

            container.styleSheets.Add(EditorUtilities.Load <StyleSheet>("Editor/Core/DataConfigs/styles.uss", isRequired: true));
            this.rootElement = container;

            var target = this.target as ME.ECS.Debug.EntityDebugComponent;

            if (target.world != null && target.world.isActive == true)
            {
                this.debug                 = new ME.ECS.Debug.EntityProxyDebugger(target.entity, target.world);
                this.temp.components       = this.debug.GetComponentsList();
                this.temp.sharedComponents = this.debug.GetSharedComponentsList();
                container.schedule.Execute(this.Update).Every((long)(target.world.GetTickTime() * 1000f));

                var searchField = new ToolbarSearchField();
                searchField.AddToClassList("search-field");
                searchField.RegisterValueChangedCallback((evt) => {
                    var search = evt.newValue.ToLower();
                    DataConfigEditor.Search(search, this.componentsContainer);
                    DataConfigEditor.Search(search, this.sharedComponentsContainer);
                });
                container.Add(searchField);

                {
                    var entityElement = new VisualElement();
                    this.entityContainer = entityElement;
                    entityElement.name   = "EntityContainer";
                    entityElement.AddToClassList("entity-container");
                    var id = new Label("ID:");
                    id.AddToClassList("entity-container-item");
                    id.AddToClassList("entity-container-item-label");
                    entityElement.Add(id);
                    var idValue = new Label();
                    idValue.AddToClassList("entity-container-item");
                    idValue.AddToClassList("entity-container-item-value");
                    idValue.name  = "EntityId";
                    this.entityId = idValue;
                    entityElement.Add(idValue);
                    var gen = new Label("Generation:");
                    gen.AddToClassList("entity-container-item");
                    gen.AddToClassList("entity-container-item-label");
                    entityElement.Add(gen);
                    var genValue = new Label();
                    genValue.AddToClassList("entity-container-item");
                    genValue.AddToClassList("entity-container-item-value");
                    genValue.name  = "EntityGen";
                    this.entityGen = genValue;
                    entityElement.Add(genValue);
                    var version = new Label("Version:");
                    version.AddToClassList("entity-container-item");
                    version.AddToClassList("entity-container-item-label");
                    entityElement.Add(version);
                    var versionValue = new Label();
                    versionValue.AddToClassList("entity-container-item");
                    versionValue.AddToClassList("entity-container-item-value");
                    versionValue.name  = "EntityVersion";
                    this.entityVersion = versionValue;
                    entityElement.Add(versionValue);

                    container.Add(entityElement);

                    var changedWarning = new Label("Selected entity is no longer available: generation has been changed.");
                    this.entityContainerWarning = changedWarning;
                    changedWarning.name         = "EntityChanged";
                    changedWarning.AddToClassList("entity-changed-warning");
                    changedWarning.AddToClassList("hidden");
                    container.Add(changedWarning);
                }

                this.content      = new VisualElement();
                this.content.name = "Content";
                container.Add(this.content);

                if (target.entity.IsAlive() == true)
                {
                    this.BuildLists(this.content);
                }
            }
            else
            {
                var element = new Label("No active world found");
                element.AddToClassList("world-not-found");
                this.rootElement.Add(element);
            }

            return(this.rootElement);
        }
示例#11
0
        public override VisualElement CreateInspectorGUI()
        {
            (StyleSheet styleSheet, VisualTreeAsset uxml) = StyleExtensions.GetStyleSheetAndUXML("PackageUpdater");
            packageItemUXML = StyleExtensions.GetUXML("PackageItem");

            root = new VisualElement();
            root.styleSheets.Add(styleSheet);
            root.styleSheets.Add(StyleExtensions.GetStyleSheet("VertxShared"));
            uxml.CloneTree(root);

            packageRoot  = root.Q("Packages Root");
            addRoot      = root.Q("Add Root");
            addContainer = addRoot.Q("Add Container");
            search       = addContainer.Q <ToolbarSearchField>("Search");
            search.RegisterCallback <ChangeEvent <string> >(Search);

            if (updatingPackages.arraySize == 0)
            {
                AddHelpBox();
            }
            else
            {
                for (int i = 0; i < updatingPackages.arraySize; i++)
                {
                    AddTrackedPackage(i);
                }
            }

            //-----------------------------------------------------
            addButton = addRoot.Q <Button>("Add Button");
            addButton.SetEnabled(false);
            addButton.clickable.clicked += PopulateAdd;
            listView = addRoot.Q <ListView>("Add Contents");
            // List view configuration
            listView.makeItem = () =>
            {
                Label button = new Label();
                button.AddToClassList("addPackageItemButton");
                return(button);
            };
            listView.bindItem = (element, i) =>
            {
                string packageName = (string)listView.itemsSource[i];
                ((Label)element).text = packageName;
            };
                        #if UNITY_2020_1_OR_NEWER
            listView.onItemsChosen += objects =>
            {
                int c = untrackedPackages.Count;
                foreach (var o in objects)
                {
                    //Add package so it can be tracked by the Package Updater.
                    string packageName = (string)o;
                    int    index       = updatingPackages.arraySize++;
                    updatingPackages.GetArrayElementAtIndex(index).FindPropertyRelative(ignoreProp).stringValue = null;
                    AddTrackedPackage(index, packageName);
                    serializedObject.ApplyModifiedProperties();
                    listView.Clear();
                    addContainer.AddToClassList(hiddenStyle);
                    c--;
                }

                //Disable the add button if there will be no more packages.
                if (c <= 0)
                {
                    DisableAddButton();
                }
                else
                {
                    EnableAddButton();
                }
            };
                        #else
            listView.onItemChosen += o =>
            {
                //Disable the add button if there will be no more packages.
                if (untrackedPackages.Count <= 1)
                {
                    DisableAddButton();
                }
                else
                {
                    EnableAddButton();
                }

                //Add package so it can be tracked by the Package Updater.
                string packageName = (string)o;
                int    index       = updatingPackages.arraySize++;
                AddTrackedPackage(index, packageName);
                serializedObject.ApplyModifiedProperties();
                listView.Clear();
                addContainer.AddToClassList(hiddenStyle);
            };
                        #endif
            addContainer.AddToClassList(hiddenStyle);
            //-----------------------------------------------------

            updateButton = root.Q <Button>("Update Button");
            updateButton.SetEnabled(false);
            updateButton.clickable.clicked += DoUpdate;

            var helpBox = root.Q <HelpBox>("Auto Update Help Box");
            helpBox.Q <Label>(className: HelpBox.uSSLabelClassName).text
                = NUtilitiesPreferences.AutoUpdatePackages ? "Auto-Update is enabled." : "Auto-Update is disabled.";
            helpBox.RegisterCallback <MouseUpEvent>(evt => SettingsService.OpenUserPreferences(NUtilitiesPreferences.PreferencesPath));

            ValidateAddButton();
            ValidatePackages();

            return(root);
        }
示例#12
0
        protected override void SelfChange()
        {
            base.SelfChange();

            Profiler.BeginSample("VFXContextUI.CreateBlockProvider");
            if (m_BlockProvider == null)
            {
                m_BlockProvider = new VFXBlockProvider(controller, (d, mPos) =>
                {
                    AddBlock(mPos, d);
                });
            }
            Profiler.EndSample();

            if (inputContainer.childCount == 0 && !hasSettings)
            {
                mainContainer.AddToClassList("empty");
            }
            else
            {
                mainContainer.RemoveFromClassList("empty");
            }

            m_Divider.visible = hasSettings;

            m_HeaderIcon.image   = GetIconForVFXType(controller.model.inputType);
            m_HeaderIcon.visible = m_HeaderIcon.image != null;


            Profiler.BeginSample("VFXContextUI.SetAllStyleClasses");

            VFXContextType contextType = controller.model.contextType;

            foreach (VFXContextType value in System.Enum.GetValues(typeof(VFXContextType)))
            {
                if (value != contextType)
                {
                    RemoveFromClassList(ContextEnumToClassName(value.ToString()));
                }
            }
            AddToClassList(ContextEnumToClassName(contextType.ToString()));

            var inputType = controller.model.inputType;

            if (inputType == VFXDataType.kNone)
            {
                inputType = controller.model.ownedType;
            }
            foreach (VFXDataType value in System.Enum.GetValues(typeof(VFXDataType)))
            {
                if (inputType != value)
                {
                    RemoveFromClassList("inputType" + ContextEnumToClassName(value.ToString()));
                }
            }
            AddToClassList("inputType" + ContextEnumToClassName(inputType.ToString()));

            var outputType = controller.model.outputType;

            foreach (VFXDataType value in System.Enum.GetValues(typeof(VFXDataType)))
            {
                if (value != outputType)
                {
                    RemoveFromClassList("outputType" + ContextEnumToClassName(value.ToString()));
                }
            }
            AddToClassList("outputType" + ContextEnumToClassName(outputType.ToString()));

            var type = controller.model.ownedType;

            foreach (VFXDataType value in System.Enum.GetValues(typeof(VFXDataType)))
            {
                if (value != type)
                {
                    RemoveFromClassList("type" + ContextEnumToClassName(value.ToString()));
                }
            }
            AddToClassList("type" + ContextEnumToClassName(type.ToString()));

            var space = controller.model.space;

            foreach (VFXCoordinateSpace val in System.Enum.GetValues(typeof(VFXCoordinateSpace)))
            {
                if (val != space || !controller.model.spaceable)
                {
                    m_HeaderSpace.RemoveFromClassList("space" + val.ToString());
                }
            }
            if (controller.model.spaceable)
            {
                m_HeaderSpace.AddToClassList("space" + (controller.model.space).ToString());
            }

            Profiler.EndSample();
            if (controller.model.outputType == VFXDataType.kNone)
            {
                if (m_Footer.parent != null)
                {
                    m_Footer.RemoveFromHierarchy();
                }
            }
            else
            {
                if (m_Footer.parent == null)
                {
                    mainContainer.Add(m_Footer);
                }
                m_FooterTitle.text   = controller.model.outputType.ToString().Substring(1);
                m_FooterIcon.image   = GetIconForVFXType(controller.model.outputType);
                m_FooterIcon.visible = m_FooterIcon.image != null;
            }

            Profiler.BeginSample("VFXContextUI.CreateInputFlow");
            HashSet <VisualElement> newInAnchors = new HashSet <VisualElement>();

            foreach (var inanchorcontroller in controller.flowInputAnchors)
            {
                var existing = m_FlowInputConnectorContainer.Children().Select(t => t as VFXFlowAnchor).FirstOrDefault(t => t.controller == inanchorcontroller);
                if (existing == null)
                {
                    var anchor = VFXFlowAnchor.Create(inanchorcontroller);
                    m_FlowInputConnectorContainer.Add(anchor);
                    newInAnchors.Add(anchor);
                }
                else
                {
                    newInAnchors.Add(existing);
                }
            }

            foreach (var nonLongerExistingAnchor in m_FlowInputConnectorContainer.Children().Where(t => !newInAnchors.Contains(t)).ToList()) // ToList to make a copy because the enumerable will change when we delete
            {
                m_FlowInputConnectorContainer.Remove(nonLongerExistingAnchor);
            }
            Profiler.EndSample();

            Profiler.BeginSample("VFXContextUI.CreateInputFlow");
            HashSet <VisualElement> newOutAnchors = new HashSet <VisualElement>();

            foreach (var outanchorcontroller in controller.flowOutputAnchors)
            {
                var existing = m_FlowOutputConnectorContainer.Children().Select(t => t as VFXFlowAnchor).FirstOrDefault(t => t.controller == outanchorcontroller);
                if (existing == null)
                {
                    var anchor = VFXFlowAnchor.Create(outanchorcontroller);
                    m_FlowOutputConnectorContainer.Add(anchor);
                    newOutAnchors.Add(anchor);
                }
                else
                {
                    newOutAnchors.Add(existing);
                }
            }

            foreach (var nonLongerExistingAnchor in m_FlowOutputConnectorContainer.Children().Where(t => !newOutAnchors.Contains(t)).ToList()) // ToList to make a copy because the enumerable will change when we delete
            {
                m_FlowOutputConnectorContainer.Remove(nonLongerExistingAnchor);
            }
            Profiler.EndSample();

            m_Label.text = controller.model.label;
            if (string.IsNullOrEmpty(m_Label.text))
            {
                m_Label.AddToClassList("empty");
            }
            else
            {
                m_Label.RemoveFromClassList("empty");
            }

            RefreshContext();
        }
示例#13
0
        void CreateView()
        {
            minSize = new Vector2(560.0f, 200.0f);

            var  pathPrefix1   = $"Styles/recorder.uss";
            var  lightOrDark   = EditorGUIUtility.isProSkin ? "recorder_darkSkin" : "recorder_lightSkin";
            var  pathPrefix2   = $"Styles/{lightOrDark}.uss";
            var  root          = rootVisualElement;
            var  sheet1        = UnityHelpers.LoadLocalPackageAsset <StyleSheet>(pathPrefix1, false);
            var  sheet2        = UnityHelpers.LoadLocalPackageAsset <StyleSheet>(pathPrefix2, false);
            bool sheetNotFound = sheet1 == null || sheet2 == null;

            if (sheetNotFound)
            {
                s_NeedToResetView = true;
                return;
            }
            root.styleSheets.Add(sheet1);
            root.styleSheets.Add(sheet2);

            root.style.flexDirection = FlexDirection.Column;
            UIElementHelper.SetFocusable(root);

            var mainControls = new VisualElement
            {
                style =
                {
                    flexDirection = FlexDirection.Row,
                    minHeight     = 120.0f
                }
            };

            root.Add(mainControls);

            var controlLeftPane = new VisualElement
            {
                style =
                {
                    minWidth      =            180.0f,
                    maxWidth      =            450.0f,
                    flexDirection = FlexDirection.Row,
                }
            };

            UIElementHelper.SetFlex(controlLeftPane, 0.5f);

            var controlRightPane = new VisualElement
            {
                style =
                {
                    flexDirection = FlexDirection.Column,
                }
            };

            UIElementHelper.SetFlex(controlRightPane, 0.5f);

            mainControls.Add(controlLeftPane);
            mainControls.Add(controlRightPane);

            controlLeftPane.AddToClassList("StandardPanel");
            controlRightPane.AddToClassList("StandardPanel");

            m_RecordButtonIcon = new Button(OnRecordButtonClick)
            {
                name  = "recorderIcon",
                style =
                {
                    backgroundImage = UnityHelpers.LoadLocalPackageAsset <Texture2D>("recorder_icon.png", true),
                },
                tooltip = "Start the recording for all active recorders of the list\n\n This automatically activates the Play mode first (if not activated yet)."
            };

            controlLeftPane.Add(m_RecordButtonIcon);


            var leftButtonsStack = new VisualElement
            {
                style =
                {
                    flexDirection = FlexDirection.Column,
                }
            };

            UIElementHelper.SetFlex(leftButtonsStack, 1.0f);

            m_RecordButton = new Button(OnRecordButtonClick)
            {
                name    = "recordButton",
                tooltip = "Start/Stop the recording for all active recorders of the list\n\nStarting the recording automatically activates the Play mode first (if not activated yet)."
            };

            UpdateRecordButtonText();

            leftButtonsStack.Add(m_RecordButton);

            m_RecordOptionsPanel = new IMGUIContainer(() =>
            {
                PrepareGUIState(m_RecordOptionsPanel.layout.width);
                RecorderOptions.exitPlayMode = EditorGUILayout.Toggle(Styles.ExitPlayModeLabel, RecorderOptions.exitPlayMode);
            })
            {
                name = "recordOptions"
            };

            UIElementHelper.SetFlex(m_RecordOptionsPanel, 1.0f);

            leftButtonsStack.Add(m_RecordOptionsPanel);

            m_RecordModeOptionsPanel = new IMGUIContainer(() =>
            {
                PrepareGUIState(m_RecordModeOptionsPanel.layout.width);
                if (m_RecorderSettingsPrefsEditor.RecordModeGUI())
                {
                    OnGlobalSettingsChanged();
                }
            });

            UIElementHelper.SetFlex(m_RecordModeOptionsPanel, 1.0f);

            leftButtonsStack.Add(m_RecordModeOptionsPanel);

            controlLeftPane.Add(leftButtonsStack);

            m_FrameRateOptionsPanel = new IMGUIContainer(() =>
            {
                PrepareGUIState(m_FrameRateOptionsPanel.layout.width);
                if (m_RecorderSettingsPrefsEditor.FrameRateGUI())
                {
                    OnGlobalSettingsChanged();
                }
            });

            UIElementHelper.SetFlex(m_FrameRateOptionsPanel, 1.0f);

            controlRightPane.Add(m_FrameRateOptionsPanel);

            m_SettingsPanel      = new ScrollView();
            m_SettingsPanel.name = "SettingPanelScrollView";

            UIElementHelper.SetFlex(m_SettingsPanel, 1.0f);

            UIElementHelper.ResetStylePosition(m_SettingsPanel.contentContainer.style);

            var recordersAndParameters = new VisualElement
            {
                style =
                {
                    alignSelf     = Align.Stretch,
                    flexDirection = FlexDirection.Row,
                }
            };

            UIElementHelper.SetFlex(recordersAndParameters, 1.0f);

            m_RecordersPanel = new VisualElement
            {
                name  = "recordersPanel",
                style =
                {
                    width    = 200.0f,
                    minWidth = 150.0f,
                    maxWidth = 500.0f
                }
            };

            m_RecordersPanel.AddToClassList("StandardPanel");

            m_PanelSplitter = new PanelSplitter(m_RecordersPanel);

            recordersAndParameters.Add(m_RecordersPanel);
            recordersAndParameters.Add(m_PanelSplitter);
            recordersAndParameters.Add(m_SettingsPanel);

            m_SettingsPanel.AddToClassList("StandardPanel");

            root.Add(recordersAndParameters);

            var addRecordButton = new Label("+ Add Recorder");

            UIElementHelper.SetFlex(addRecordButton, 1.0f);

            var recorderListPresetButton = new VisualElement
            {
                name    = "recorderListPreset",
                tooltip = "Manage the recorder list"
            };

            recorderListPresetButton.RegisterCallback <MouseUpEvent>(evt => ShowRecorderListMenu());

            recorderListPresetButton.Add(new Image
            {
                image = (Texture2D)EditorGUIUtility.Load("Builtin Skins/" + (EditorGUIUtility.isProSkin ? "DarkSkin" : "LightSkin") + "/Images/pane options.png"),
                style =
                {
                    width  = 16.0f,
                    height = 16.0f
                }
            });

            addRecordButton.AddToClassList("RecorderListHeader");
            recorderListPresetButton.AddToClassList("RecorderListHeader");

            addRecordButton.RegisterCallback <MouseUpEvent>(evt => ShowNewRecorderMenu());

            m_AddNewRecordPanel = new VisualElement
            {
                name    = "addRecordersButton",
                style   = { flexDirection = FlexDirection.Row },
                tooltip = "Add a new recorder item to the list"
            };


            m_AddNewRecordPanel.Add(addRecordButton);
            m_AddNewRecordPanel.Add(recorderListPresetButton);

            m_RecordingListItem = new RecorderItemList
            {
                name = "recorderList"
            };

            UIElementHelper.SetFlex(m_RecordingListItem, 1.0f);
            UIElementHelper.SetFocusable(m_RecordingListItem);

            m_RecordingListItem.OnItemContextMenu  += OnRecordContextMenu;
            m_RecordingListItem.OnSelectionChanged += OnRecordSelectionChanged;
            m_RecordingListItem.OnItemRename       += item => item.StartRenaming();
            m_RecordingListItem.OnContextMenu      += ShowNewRecorderMenu;

            m_RecordersPanel.Add(m_AddNewRecordPanel);
            m_RecordersPanel.Add(m_RecordingListItem);

            m_ParametersControl = new VisualElement
            {
                style =
                {
                    minWidth = 300.0f,
                }
            };

            UIElementHelper.SetFlex(m_ParametersControl, 1.0f);

            m_RecorderSettingPanel = new IMGUIContainer(OnRecorderSettingsGUI)
            {
                name = "recorderSettings"
            };

            UIElementHelper.SetFlex(m_RecorderSettingPanel, 1.0f);

            var statusBar = new VisualElement
            {
                name = "statusBar"
            };

            statusBar.Add(new IMGUIContainer(UpdateRecordingProgressGUI));

            root.Add(statusBar);

            m_ParametersControl.Add(m_RecorderSettingPanel);

            m_SettingsPanel.Add(m_ParametersControl);

            m_RecordingListItem.RegisterCallback <ValidateCommandEvent>(OnRecorderListValidateCommand);
            m_RecordingListItem.RegisterCallback <ExecuteCommandEvent>(OnRecorderListExecuteCommand);
            m_RecordingListItem.RegisterCallback <KeyUpEvent>(OnRecorderListKeyUp);

            SetRecorderControllerSettings(RecorderControllerSettings.GetGlobalSettings());
        }
示例#14
0
        private VisualElement MakeItem()
        {
            var row = new VisualElement();

            row.style.flexDirection = FlexDirection.Row;
            row.AddToClassList("perf-row");

            var pinIcon = new VisualElement();

            pinIcon.AddToClassList("perf-pin");
            row.Add(pinIcon);

            var trackerName = new TextField {
                isReadOnly = true
            };
            VisualElement column = trackerName;

            column.AddToClassList("perf-tracker-name");
            row.Add(column);

            if (IsColumnVisible(ColumnId.SampleCount))
            {
                column = new Button();
                column.RegisterCallback <MouseUpEvent>(evt =>
                {
                    var tracker = GetTrackerInRowAtEvt(evt);
                    EditorPerformanceTracker.Reset(tracker.name);
                    RefreshTrackers();
                    SendAnalytics(Analytics.WindowUsageType.ResetSampleCount, tracker.name);
                });

                column.AddToClassList("perf-sample-count");
                row.Add(column);
            }

            if (IsColumnVisible(ColumnId.Age))
            {
                column = new Label();
                column.AddToClassList("perf-age");
                row.Add(column);
            }

            if (IsColumnVisible(ColumnId.AvgTime))
            {
                column = new Label();
                column.AddToClassList("perf-avg-time");
                row.Add(column);
            }

            if (IsColumnVisible(ColumnId.PeakTime))
            {
                column = new Label();
                column.AddToClassList("perf-peak-time");
                row.Add(column);
            }

            if (IsColumnVisible(ColumnId.LastTime))
            {
                column = new Label();
                column.AddToClassList("perf-last-time");
                row.Add(column);
            }

            if (IsColumnVisible(ColumnId.TotalTime))
            {
                column = new Label();
                column.AddToClassList("perf-total-time");
                row.Add(column);
            }

            var actionBtn = new Button {
                text = "..."
            };

            actionBtn.RegisterCallback <MouseUpEvent>(evt =>
            {
                var btn     = evt.target as Button;
                var tracker = GetTrackerInRowAtEvt(evt);
                if (tracker.name == m_CurrentProfileTag)
                {
                    EndTrackerProfiling(evt.target as Button, tracker.name);
                }
                else
                {
                    GenericMenu menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Set as search filter"), false, () => {
                        m_SearchField.value = tracker.name;
                        SendAnalytics(Analytics.WindowUsageType.SetSearchFieldAction, tracker.name);
                    });
                    menu.AddItem(new GUIContent("Add performance notification"), false, () => PerformanceTrackerActions.AddNewPerformanceNotification(tracker.name, (float)tracker.avgTime, Analytics.ActionSource.PerformanceTrackerWindow));
                    menu.AddItem(new GUIContent("LogCallstack"), false, () => PerformanceTrackerActions.LogCallstack(tracker.name, Analytics.ActionSource.PerformanceTrackerWindow));
                    if (String.IsNullOrEmpty(m_CurrentProfileTag))
                    {
                        menu.AddSeparator("");
                        menu.AddItem(new GUIContent("Editmode Profile..."), false, () => StartTrackerProfiling(btn, tracker.name, false, true));
                        menu.AddItem(new GUIContent("Editmode Deep profile..."), false, () => StartTrackerProfiling(btn, tracker.name, true, true));
                        menu.AddSeparator("");
                        menu.AddItem(new GUIContent("Playmode Profile..."), false, () => StartTrackerProfiling(btn, tracker.name, false, false));
                        menu.AddItem(new GUIContent("Playmode Deep profile..."), false, () => StartTrackerProfiling(btn, tracker.name, true, false));
                    }
                    menu.ShowAsContext();
                }
            });
            actionBtn.AddToClassList("perf-actions");
            row.Add(actionBtn);

            return(row);
        }
        void PerformSearch(ChangeEvent <string> evt)
        {
            m_FoundItems.Clear();
            m_SelectedIndex = 0;

            m_CountLabel.text = string.Empty;
            m_CountLabel.AddToClassList("unity-treeview-searchbar-hidden");

            m_ParentTreeView.ClearSearchResults();

            m_FieldHelpLabel.AddToClassList("unity-treeview-searchbar-hidden");

            var query = evt.newValue;

            if (string.IsNullOrEmpty(query))
            {
                m_FieldHelpLabel.RemoveFromClassList("unity-treeview-searchbar-hidden");
                return;
            }

            var items = m_ParentTreeView.treeItems;

            if (items == null)
            {
                return;
            }

            m_CurrentFilter = ElementHierarchySearchBarFilter.All;

            if (query.StartsWith(BuilderConstants.UssSelectorNameSymbol))
            {
                m_CurrentFilter = ElementHierarchySearchBarFilter.Name;
            }
            else if (query.StartsWith(BuilderConstants.UssSelectorClassNameSymbol))
            {
                m_CurrentFilter = ElementHierarchySearchBarFilter.Class;
            }

            if ((m_CurrentFilter & ElementHierarchySearchBarFilter.All) != ElementHierarchySearchBarFilter.All)
            {
                query = query.Remove(0, 1);
            }

            m_CurrentQuery = query;
            foreach (var item in items)
            {
                var treeItem = item as TreeViewItem <VisualElement>;
                var element  = treeItem.data;

                if (m_CurrentFilter == ElementHierarchySearchBarFilter.All &&
                    element.typeName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    m_FoundItems.Add(new SearchResultItem()
                    {
                        item = treeItem, highlight = SearchHighlight.Type
                    });
                }

                if ((m_CurrentFilter & ElementHierarchySearchBarFilter.Name) != 0 &&
                    element.name.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    m_FoundItems.Add(new SearchResultItem()
                    {
                        item = treeItem, highlight = SearchHighlight.Name
                    });
                }

                if ((m_CurrentFilter & ElementHierarchySearchBarFilter.Class) != 0)
                {
                    foreach (var styleClass in element.GetClasses())
                    {
                        if (styleClass.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            m_FoundItems.Add(new SearchResultItem()
                            {
                                item = treeItem, highlight = SearchHighlight.Class
                            });
                            break;
                        }
                    }
                }
            }

            if (m_FoundItems.Count == 0)
            {
                return;
            }

            m_CountLabel.RemoveFromClassList("unity-treeview-searchbar-hidden");
            m_CountLabel.text =
                string.Format("{0} of {1}", m_SelectedIndex + 1, m_FoundItems.Count);

            var firstItem = m_FoundItems.First();

            m_ParentTreeView.SelectElement(firstItem.item.data, query, firstItem.highlight);
        }
示例#16
0
 void OnDragLeave(DragLeaveEvent evt)
 {
     m_DropLabel.AddToClassList(k_HideClass);
 }
        public ElementHierarchySearchBar(ElementHierarchyView parent)
        {
            m_ParentTreeView = parent;
            m_FoundItems     = new List <SearchResultItem>();

            this.AddToClassList("unity-treeview-searchbar");

            m_FieldHelpLabel             = new Label("Search by type, name, or class");
            m_FieldHelpLabel.pickingMode = PickingMode.Ignore;
            m_FieldHelpLabel.AddToClassList("unity-treeview-searchbar-label");
            m_FieldHelpLabel.AddToClassList("unity-treeview-searchbar-label-help");
            Add(m_FieldHelpLabel);

            var field = new TextField();

            field.AddToClassList("unity-treeview-searchbar-field");
            field.RegisterValueChangedCallback(PerformSearch);
            field.RegisterCallback <KeyDownEvent>((e) =>
            {
                var targetField = field;
                if (e.keyCode == KeyCode.F3 || e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter)
                {
                    if (e.modifiers == EventModifiers.Shift)
                    {
                        SelectPrev();
                    }
                    else
                    {
                        SelectNext();
                    }
                }
                else if (e.keyCode == KeyCode.Escape)
                {
                    targetField.value = string.Empty;
                    targetField.visualInput.Blur();
                    m_ParentTreeView.ClearSearchResults();
                    m_ParentTreeView.Focus();
                }
            }, TrickleDown.TrickleDown);
            Add(field);

            m_CountLabel = new Label();
            m_CountLabel.AddToClassList("unity-treeview-searchbar-label");
            m_CountLabel.AddToClassList("unity-treeview-searchbar-hidden");
            Add(m_CountLabel);

            var prevButton = new Button(SelectPrev)
            {
                text = "<"
            };

            prevButton.AddToClassList("unity-treeview-searchbar-button");
            prevButton.AddToClassList("unity-treeview-searchbar-button-prev");
            Add(prevButton);

            var nextButton = new Button(SelectNext)
            {
                text = ">"
            };

            nextButton.AddToClassList("unity-treeview-searchbar-button");
            nextButton.AddToClassList("unity-treeview-searchbar-button-next");
            Add(nextButton);
        }
示例#18
0
        private static VisualElement CreateSnippetCode(string title, string path)
        {
            var container = new VisualElement();

            container.AddToClassList(s_CodeContainerClassName);

            var titleLabel = new Label(title);

            titleLabel.AddToClassList(s_CodeTitleClassName);
            container.Add(titleLabel);

            var asset = EditorGUIUtility.Load(path) as UIElementsSnippetAsset;

            if (asset == null)
            {
                return(null);
            }

            var text = asset.text;

            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            if (path.EndsWith("_cs.asset")) // C#
            {
                text = ProcessCSharp(text);
            }

            var    lineCount       = text.Count(x => x == '\n') + 1;
            string lineNumbersText = "";

            for (int i = 1; i <= lineCount; ++i)
            {
                if (!string.IsNullOrEmpty(lineNumbersText))
                {
                    lineNumbersText += "\n";
                }

                lineNumbersText += i.ToString();
            }

            var lineNumbers = new Label(lineNumbersText);

            lineNumbers.RemoveFromClassList(TextField.ussClassName);
            lineNumbers.AddToClassList(s_CodeClassName);
            lineNumbers.AddToClassList(s_CodeLineNumbersClassName);
            lineNumbers.AddToClassList(s_CodeInputClassName);

            var code = new TextField(TextField.kMaxLengthNone, true, false, char.MinValue)
            {
                value = text
            };

            code.isReadOnly = true;
            code.RemoveFromClassList(TextField.ussClassName);
            code.AddToClassList(s_CodeClassName);
            code.AddToClassList(s_CodeTextClassName);

            var codeInput = code.Q(className: TextField.inputUssClassName);

            codeInput.AddToClassList(s_CodeInputClassName);

            var codeOuterContainer = new VisualElement();

            codeOuterContainer.AddToClassList(s_CodeCodeOuterContainerClassName);
            container.Add(codeOuterContainer);

            var codeContainer = new VisualElement();

            codeContainer.AddToClassList(s_CodeCodeContainerClassName);
            codeOuterContainer.Add(codeContainer);

            codeContainer.Add(lineNumbers);
            codeContainer.Add(code);

            return(container);
        }
            public QualitySettingsPanelVisualElement(string searchContext)
            {
                // Get the assigned HDRP assets
                m_HDRPAssets = new List <HDRPAssetLocations>();
                if (GraphicsSettings.renderPipelineAsset is HDRenderPipelineAsset hdrp)
                {
                    m_HDRPAssets.Add(new HDRPAssetLocations(true, hdrp));
                }

                var qualityLevelCount = QualitySettings.names.Length;

                for (var i = 0; i < qualityLevelCount; ++i)
                {
                    if (!(QualitySettings.GetRenderPipelineAssetAt(i) is HDRenderPipelineAsset hdrp2))
                    {
                        continue;
                    }

                    var index = m_HDRPAssets.FindIndex(a => a.asset == hdrp2);
                    if (index >= 0)
                    {
                        m_HDRPAssets[index].indices.Add(i);
                    }
                    else
                    {
                        var loc = new HDRPAssetLocations(false, hdrp2);
                        loc.indices.Add(i);
                        m_HDRPAssets.Add(loc);
                    }
                }

                m_HDRPAssets.Sort((l, r) => string.CompareOrdinal(l.asset.name, r.asset.name));

                // title
                var title = new Label()
                {
                    text = "Quality"
                };

                title.AddToClassList("h1");

                // Header
                var headerBox = new VisualElement();

                headerBox.style.height = 200;

                m_HDRPAssetList = new ListView()
                {
                    bindItem      = (el, i) => ((HDRPAssetHeaderEntry)el).Bind(i, m_HDRPAssets[i]),
                    itemHeight    = (int)EditorGUIUtility.singleLineHeight + 3,
                    selectionType = SelectionType.Single,
                    itemsSource   = m_HDRPAssets,
                    makeItem      = () => new HDRPAssetHeaderEntry(),
                };
                m_HDRPAssetList.AddToClassList("unity-quality-header-list");
#if UNITY_2020_1_OR_NEWER
                m_HDRPAssetList.onSelectionChange += OnSelectionChange;
#else
                m_HDRPAssetList.onSelectionChanged += OnSelectionChanged;
#endif

                headerBox.Add(m_HDRPAssetList);

                m_InspectorTitle      = new Label();
                m_InspectorTitle.text = "No asset selected";
                m_InspectorTitle.AddToClassList("h1");

                // Inspector
                var inspector = new IMGUIContainer(DrawInspector);
                inspector.style.flexGrow      = 1;
                inspector.style.flexDirection = FlexDirection.Row;

                var inspectorBox = new ScrollView();
                inspectorBox.style.flexGrow      = 1;
                inspectorBox.style.flexDirection = FlexDirection.Row;
                inspectorBox.contentContainer.Add(inspector);

                Add(title);
                Add(headerBox);
                Add(m_InspectorTitle);
                Add(inspectorBox);
            }
示例#20
0
        private VisualElement MakeThumbnailField(SerializedProperty thumbnailProperty, string label)
        {
            var propertyElement      = new VisualElement();
            var thumbnailObjectField = new PropertyField(thumbnailProperty, label);

            propertyElement.Add(thumbnailObjectField);

            m_PreviewArea = new SceneTemplatePreviewArea(k_ThumbnailAreaName, thumbnailProperty.objectReferenceValue as Texture2D, "No preview available");
            var previewAreaElement = m_PreviewArea.Element;

            previewAreaElement.AddToClassList(StyleSheetLoader.Styles.classUnityBaseField);
            propertyElement.Add(previewAreaElement);

            thumbnailObjectField.RegisterCallback <ChangeEvent <Object> >(e =>
            {
                m_PreviewArea.UpdatePreview(e.newValue as Texture2D);
                TriggerSceneTemplateModified();
            });

            // Snapshot header row
            var snapshotHeaderRowElement = new VisualElement();

            snapshotHeaderRowElement.AddToClassList(StyleSheetLoader.Styles.classUnityBaseField);
            propertyElement.Add(snapshotHeaderRowElement);
            var snapshotHeaderLabel = new Label("Snapshot");

            snapshotHeaderLabel.AddToClassList(StyleSheetLoader.Styles.classUnityLabel);
            snapshotHeaderRowElement.Add(snapshotHeaderLabel);

            // Snapshot button with dropdown
            var cameraNames = Camera.allCameras.Select(c => new SnapshotTargetInfo {
                Name = c.name, OnSnapshotAction = TakeSnapshotFromCamera
            }).ToList();

            cameraNames.Add(new SnapshotTargetInfo()); // Separator
            cameraNames.Add(new SnapshotTargetInfo {
                Name = "Game View", OnSnapshotAction = (info, property) => TakeSnapshotFromGameView(property)
            });
            var snapshotTargetPopup = new PopupField <SnapshotTargetInfo>("View", cameraNames, Camera.allCameras.Length == 0 ? 1 : 0);

            snapshotTargetPopup.formatListItemCallback      = info => info.Name;
            snapshotTargetPopup.formatSelectedValueCallback = info => info.Name;
            propertyElement.Add(snapshotTargetPopup);

            var snapshotSecondRowElement = new VisualElement()
            {
                name = k_SnapshotRowName
            };

            snapshotSecondRowElement.AddToClassList(StyleSheetLoader.Styles.classUnityBaseField);
            propertyElement.Add(snapshotSecondRowElement);
            var emptyLabel = new VisualElement();

            emptyLabel.AddToClassList(StyleSheetLoader.Styles.classUnityBaseFieldLabel);
            snapshotSecondRowElement.Add(emptyLabel);
            var snapshotButton = new Button(() =>
            {
                var targetInfo = snapshotTargetPopup.value;
                if (targetInfo.OnSnapshotAction == null)
                {
                    return;
                }
                targetInfo.OnSnapshotAction(targetInfo, thumbnailProperty);
            });

            snapshotButton.tooltip = k_SnapshotTooltip;
            snapshotButton.text    = k_SnapshotButtonLabel;
            snapshotButton.AddToClassList(StyleSheetLoader.Styles.classUnityBaseFieldInput);
            snapshotSecondRowElement.Add(snapshotButton);

            return(propertyElement);
        }
 void HidePlaceholder()
 {
     m_PlaceholderLabel?.AddToClassList("hidden");
 }
示例#22
0
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            VisualElement root = new VisualElement();

            Foldout foldout = new Foldout {
                text = property.displayName, value = property.isExpanded
            };

            foldout.RegisterValueChangedCallback((evt) => { property.isExpanded = foldout.value; });

            elements = new VisualElement();
            foldout.contentContainer.Add(elements);

            enabled     = new PropertyField(property.FindPropertyRelative("enabled"));
            randomPitch = new PropertyField(property.FindPropertyRelative("randomPitch"));
            pitch       = new PropertyField(property.FindPropertyRelative("pitch"));

            randomPitchElements = new VisualElement();
            randomPitchElements.AddToClassList("unity-property-field");

            VisualElement basePitchFields = new VisualElement();

            basePitchFields.AddToClassList("unity-base-field");
            basePitchFields.AddToClassList("unity-base-text-field");
            basePitchFields.AddToClassList("unity-float-field");

            Label pitchLabel = new Label("Pitch");

            pitchLabel.AddToClassList("unity-text-element");
            pitchLabel.AddToClassList("unity-label");
            pitchLabel.AddToClassList("unity-base-field__label");
            pitchLabel.AddToClassList("unity-base-text-field__label");
            pitchLabel.AddToClassList("unity-float-field__label");
            pitchLabel.AddToClassList("unity-property-field__label");

            FloatField minPitchField = new FloatField
            {
                bindingPath = property.FindPropertyRelative("minPitch").propertyPath,
            };

            minPitchField.style.flexGrow = 1;
            minPitchField.AddToClassList("unity-property-field__input");

            FloatField maxPitchField = new FloatField
            {
                bindingPath = property.FindPropertyRelative("maxPitch").propertyPath,
            };

            maxPitchField.style.flexGrow = 1;
            maxPitchField.AddToClassList("unity-property-field__input");

            VisualElement pitchFields = new VisualElement()
            {
                name = "pitch-fields"
            };

            pitchFields.style.flexDirection = FlexDirection.Row;
            pitchFields.style.flexGrow      = 1;

            Label minLabel = new Label("Min");

            minLabel.AddToClassList("unity-text-element");
            minLabel.AddToClassList("unity-label");
            minLabel.style.unityTextAlign = TextAnchor.MiddleLeft;

            pitchFields.Add(minLabel);
            pitchFields.Add(minPitchField);

            Label maxLabel = new Label("Max");

            maxLabel.AddToClassList("unity-text-element");
            maxLabel.AddToClassList("unity-label");
            maxLabel.style.unityTextAlign = TextAnchor.MiddleLeft;

            pitchFields.Add(maxLabel);
            pitchFields.Add(maxPitchField);

            basePitchFields.Add(pitchLabel);
            basePitchFields.Add(pitchFields);

            randomPitchElements.Add(basePitchFields);

            changeVolume = new PropertyField(property.FindPropertyRelative("changeVolume"));
            volume       = new PropertyField(property.FindPropertyRelative("volume"));
            audioClips   = new PropertyField(property.FindPropertyRelative("audioClips"));

            elements.Add(enabled);
            elements.Add(randomPitch);
            elements.Add(pitch);
            elements.Add(randomPitchElements);
            elements.Add(changeVolume);
            elements.Add(volume);
            elements.Add(audioClips);

            enabled.RegisterCallback <ChangeEvent <bool> >(x => ToggleEnabled(x.newValue));
            randomPitch.RegisterCallback <ChangeEvent <bool> >(x => ToggleRandomPitch(x.newValue));
            changeVolume.RegisterCallback <ChangeEvent <bool> >(x => ToggleVolume(x.newValue));

            ToggleEnabled(property.FindPropertyRelative("enabled").boolValue);
            ToggleRandomPitch(property.FindPropertyRelative("randomPitch").boolValue);
            ToggleVolume(property.FindPropertyRelative("changeVolume").boolValue);

            root.Add(foldout);

            return(root);
        }
        private void CreateListView()
        {
            var      assets   = FindAssets();
            ListView listView = rootVisualElement.Q <ListView>(className: "table-list");

            listView.makeItem = null;
            listView.bindItem = null;

            listView.itemsSource = assets;
            listView.itemHeight  = 16;
            string labelClass = $"label-{(EditorGUIUtility.isProSkin ? "pro" : "personal")}";

            listView.makeItem = () =>
            {
                var label = new Label();
                label.AddToClassList(labelClass);
                return(label);
            };
            listView.bindItem      = (element, i) => ((Label)element).text = assets[i].name;
            listView.selectionType = SelectionType.Single;

            listView.onSelectionChanged += enumerable =>
            {
                IMGUIContainer editor = rootVisualElement.Q <IMGUIContainer>(className: "table-editor");
                editor.onGUIHandler = null;

                if (enumerable.Count == 0)
                {
                    return;
                }

                var table = (TransitionTableSO)enumerable[0];
                if (table == null)
                {
                    return;
                }

                if (_transitionTableEditor == null)
                {
                    _transitionTableEditor = UnityEditor.Editor.CreateEditor(table, typeof(TransitionTableEditor));
                }
                else
                {
                    UnityEditor.Editor.CreateCachedEditor(table, typeof(TransitionTableEditor), ref _transitionTableEditor);
                }

                editor.onGUIHandler = () =>
                {
                    if (!_transitionTableEditor.target)
                    {
                        editor.onGUIHandler = null;
                        return;
                    }

                    if ((Object)listView.selectedItem != _transitionTableEditor.target)
                    {
                        var i = listView.itemsSource.IndexOf(_transitionTableEditor.target);
                        listView.selectedIndex = i;
                        if (i < 0)
                        {
                            editor.onGUIHandler = null;
                            return;
                        }
                    }

                    _transitionTableEditor.OnInspectorGUI();
                };
            };
        }
示例#24
0
 void CreateButton()
 {
     m_DropDownButton = new Label();
     m_DropDownButton.AddToClassList("PopupButton");
     m_DropDownButton.AddManipulator(new DownClickable(OnClick));
 }
示例#25
0
        void FillItem(VisualElement element, ITreeViewItem item)
        {
            var explorerItem = element as BuilderExplorerItem;

            explorerItem.Clear();

            // Pre-emptive cleanup.
            var row = explorerItem.parent.parent;

            row.RemoveFromClassList(BuilderConstants.ExplorerHeaderRowClassName);
            row.RemoveFromClassList(BuilderConstants.ExplorerItemHiddenClassName);

            // Get target element (in the document).
            var documentElement = (item as TreeViewItem <VisualElement>).data;

            documentElement.SetProperty(BuilderConstants.ElementLinkedExplorerItemVEPropertyName, explorerItem);
            explorerItem.SetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName, documentElement);
            row.userData = documentElement;

            // If we have a FillItem callback (override), we call it and stop creating the rest of the item.
            var fillItemCallback =
                documentElement.GetProperty(BuilderConstants.ExplorerItemFillItemCallbackVEPropertyName) as Action <VisualElement, ITreeViewItem, BuilderSelection>;

            if (fillItemCallback != null)
            {
                fillItemCallback(explorerItem, item, m_Selection);
                return;
            }

            // Create main label container.
            var labelCont = new VisualElement();

            labelCont.AddToClassList(BuilderConstants.ExplorerItemLabelContClassName);
            explorerItem.Add(labelCont);

            if (BuilderSharedStyles.IsSelectorsContainerElement(documentElement))
            {
                var styleSheetAsset     = documentElement.GetStyleSheet();
                var styleSheetFileName  = AssetDatabase.GetAssetPath(styleSheetAsset);
                var styleSheetAssetName = BuilderAssetUtilities.GetStyleSheetAssetName(styleSheetAsset);
                var ssLabel             = new Label(styleSheetAssetName);
                ssLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                ssLabel.AddToClassList("unity-debugger-tree-item-type");
                row.AddToClassList(BuilderConstants.ExplorerHeaderRowClassName);
                labelCont.Add(ssLabel);
                return;
            }
            else if (BuilderSharedStyles.IsSelectorElement(documentElement))
            {
                var selectorParts = BuilderSharedStyles.GetSelectorParts(documentElement);

                foreach (var partStr in selectorParts)
                {
                    if (partStr.StartsWith(BuilderConstants.UssSelectorClassNameSymbol))
                    {
                        m_ClassPillTemplate.CloneTree(labelCont);
                        var pill      = labelCont.contentContainer.ElementAt(labelCont.childCount - 1);
                        var pillLabel = pill.Q <Label>("class-name-label");
                        pill.AddToClassList("unity-debugger-tree-item-pill");
                        pill.SetProperty(BuilderConstants.ExplorerStyleClassPillClassNameVEPropertyName, partStr);
                        pill.userData = documentElement;

                        // Add ellipsis if the class name is too long.
                        var partStrShortened = BuilderNameUtilities.CapStringLengthAndAddEllipsis(partStr, BuilderConstants.ClassNameInPillMaxLength);
                        pillLabel.text = partStrShortened;

                        m_ClassDragger.RegisterCallbacksOnTarget(pill);
                    }
                    else if (partStr.StartsWith(BuilderConstants.UssSelectorNameSymbol))
                    {
                        var selectorPartLabel = new Label(partStr);
                        selectorPartLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                        selectorPartLabel.AddToClassList(BuilderConstants.ElementNameClassName);
                        labelCont.Add(selectorPartLabel);
                    }
                    else if (partStr.StartsWith(BuilderConstants.UssSelectorPseudoStateSymbol))
                    {
                        var selectorPartLabel = new Label(partStr);
                        selectorPartLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                        selectorPartLabel.AddToClassList(BuilderConstants.ElementPseudoStateClassName);
                        labelCont.Add(selectorPartLabel);
                    }
                    else if (partStr == BuilderConstants.SingleSpace)
                    {
                        var selectorPartLabel = new Label(BuilderConstants.TripleSpace);
                        selectorPartLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                        selectorPartLabel.AddToClassList(BuilderConstants.ElementTypeClassName);
                        labelCont.Add(selectorPartLabel);
                    }
                    else
                    {
                        var selectorPartLabel = new Label(partStr);
                        selectorPartLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                        selectorPartLabel.AddToClassList(BuilderConstants.ElementTypeClassName);
                        labelCont.Add(selectorPartLabel);
                    }
                }

                // Register right-click events for context menu actions.
                m_ContextMenuManipulator.RegisterCallbacksOnTarget(explorerItem);

                return;
            }

            if (BuilderSharedStyles.IsDocumentElement(documentElement))
            {
                var uxmlAsset = documentElement.GetVisualTreeAsset();
                var ssLabel   = new Label(BuilderAssetUtilities.GetVisualTreeAssetAssetName(uxmlAsset));
                ssLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                ssLabel.AddToClassList("unity-debugger-tree-item-type");
                row.AddToClassList(BuilderConstants.ExplorerHeaderRowClassName);
                labelCont.Add(ssLabel);
                return;
            }

            // Check if element is inside current document.
            if (!documentElement.IsPartOfCurrentDocument())
            {
                row.AddToClassList(BuilderConstants.ExplorerItemHiddenClassName);
            }

            // Register drag-and-drop events for reparenting.
            m_HierarchyDragger.RegisterCallbacksOnTarget(explorerItem);

            // Allow reparenting.
            explorerItem.SetProperty(BuilderConstants.ExplorerItemElementLinkVEPropertyName, documentElement);

            // Element type label.
            if (string.IsNullOrEmpty(documentElement.name) ||
                elementInfoVisibilityState.HasFlag(BuilderExplorer.BuilderElementInfoVisibilityState.TypeName))
            {
                var typeLabel = new Label(documentElement.typeName);
                typeLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                typeLabel.AddToClassList(BuilderConstants.ElementTypeClassName);
                labelCont.Add(typeLabel);
            }

            // Element name label.
            var nameLabel = new Label();

            nameLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
            nameLabel.AddToClassList("unity-debugger-tree-item-name-label");
            nameLabel.AddToClassList(BuilderConstants.ExplorerItemNameLabelClassName);
            nameLabel.AddToClassList(BuilderConstants.ElementNameClassName);
            if (!string.IsNullOrEmpty(documentElement.name))
            {
                nameLabel.text = "#" + documentElement.name;
            }
            labelCont.Add(nameLabel);

            // Textfield to rename element in hierarchy.
            var renameTextfield = explorerItem.CreateRenamingTextField(documentElement, nameLabel, m_Selection);

            labelCont.Add(renameTextfield);

            // Add class list.
            if (documentElement.classList.Count > 0 && elementInfoVisibilityState.HasFlag(BuilderExplorer.BuilderElementInfoVisibilityState.ClassList))
            {
                foreach (var ussClass in documentElement.GetClasses())
                {
                    var classLabelCont = new VisualElement();
                    classLabelCont.AddToClassList(BuilderConstants.ExplorerItemLabelContClassName);
                    explorerItem.Add(classLabelCont);

                    var classLabel = new Label("." + ussClass);
                    classLabel.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                    classLabel.AddToClassList(BuilderConstants.ElementClassNameClassName);
                    classLabel.AddToClassList("unity-debugger-tree-item-classlist-label");

                    classLabelCont.Add(classLabel);
                }
            }

            // Show name of uxml file if this element is a TemplateContainer.
            var path = documentElement.GetProperty(BuilderConstants.LibraryItemLinkedTemplateContainerPathVEPropertyName) as string;

            if (documentElement is TemplateContainer && !string.IsNullOrEmpty(path))
            {
                var pathStr = Path.GetFileName(path);
                var label   = new Label(pathStr);
                label.AddToClassList(BuilderConstants.ExplorerItemLabelClassName);
                label.AddToClassList(BuilderConstants.ElementTypeClassName);
                label.AddToClassList("unity-builder-explorer-tree-item-template-path"); // Just make it look a bit shaded.
                labelCont.Add(label);
            }

            // Register right-click events for context menu actions.
            m_ContextMenuManipulator.RegisterCallbacksOnTarget(explorerItem);
        }
示例#26
0
        private void Initialize(AttachToPanelEvent evt)
        {
            // switch event to do some UI updates instead of initialization from here on out
            UnregisterCallback <AttachToPanelEvent>(Initialize);
            //    this.RegisterCallback<AttachToPanelEvent>(OnAttach);

            // Add Header
            Add(new TextElement()
            {
                name = "intro",
                text = "Udon Graph",
            });

            Add(new TextElement()
            {
                name = "header-message",
                text =
                    "The Udon Graph is your gateway to creating amazing things in VRChat.\nCheck out the Readme and UdonExampleScene in the VRChat Examples folder to get started."
            });

            var mainContainer = new VisualElement()
            {
                name = "main",
            };

            Add(mainContainer);

            var template = EditorGUIUtility.Load("Assets/Udon/Editor/Resources/UdonChangelog.uxml") as VisualTreeAsset;

            #if UNITY_2019_3_OR_NEWER
            var changelog = template.CloneTree((string)null);
            #else
            var changelog = template.CloneTree(null);
            #endif
            changelog.name = "changelog";
            mainContainer.Add(changelog);

            var column2 = new VisualElement()
            {
                name = "column-2"
            };
            mainContainer.Add(column2);

            // Add Button for Last Graph
            if (!string.IsNullOrEmpty(Settings.LastGraphGuid))
            {
                _openLastGraphButton = new Button(() =>
                {
                    var assetPath = AssetDatabase.GUIDToAssetPath(Settings.LastGraphGuid);
                    var graphName = assetPath.Substring(assetPath.LastIndexOf("/") + 1).Replace(".asset", "");

                    // Find actual asset from guid
                    var asset = AssetDatabase.LoadAssetAtPath <UdonGraphProgramAsset>(assetPath);
                    if (asset != null)
                    {
                        var w = EditorWindow.GetWindow <UdonGraphWindow>("Udon Graph", true, typeof(SceneView));
                        // get reference to saved UdonBehaviour if possible
                        UdonBehaviour udonBehaviour = null;
                        string gPath = Settings.LastUdonBehaviourPath;
                        string sPath = Settings.LastUdonBehaviourScenePath;
                        if (!string.IsNullOrEmpty(gPath) && !string.IsNullOrEmpty(sPath))
                        {
                            var targetScene = EditorSceneManager.GetSceneByPath(sPath);
                            if (targetScene != null && targetScene.isLoaded && targetScene.IsValid())
                            {
                                var targetObject = GameObject.Find(gPath);
                                if (targetObject != null)
                                {
                                    udonBehaviour = targetObject.GetComponent <UdonBehaviour>();
                                }
                            }
                        }

                        // Initialize graph with restored udonBehaviour or null if not found / not saved
                        w.InitializeGraph(asset, udonBehaviour);
                    }
                });

                UpdateLastGraphButtonLabel();
                column2.Add(_openLastGraphButton);
            }

            var settingsTemplate =
                EditorGUIUtility.Load("Assets/Udon/Editor/Resources/UdonSettings.uxml") as VisualTreeAsset;
            #if UNITY_2019_3_OR_NEWER
            var settings = settingsTemplate.CloneTree((string)null);
            #else
            var settings = settingsTemplate.CloneTree(null);
            #endif
            settings.name = "settings";
            column2.Add(settings);

            // get reference to first settings section
            var section = settings.Q("section");

            // Add Grid Snap setting
            var gridSnapContainer = new VisualElement();
            gridSnapContainer.AddToClassList("settings-item-container");
            var gridSnapField = new IntegerField(3)
            {
                value = Settings.GridSnapSize
            };
#if UNITY_2019_3_OR_NEWER
            gridSnapField.RegisterValueChangedCallback(
#else
            gridSnapField.OnValueChanged(
#endif
                e => { Settings.GridSnapSize = e.newValue; });
            gridSnapContainer.Add(new Label("Grid Snap Size"));
            gridSnapContainer.Add(gridSnapField);
            section.Add(gridSnapContainer);
            var gridSnapLabel = new Label("Snap elements to a grid as you move them. 0 for No Snapping.");
            gridSnapLabel.AddToClassList("settings-label");
            section.Add(gridSnapLabel);

            // Add Search On Selected Node settings
            var searchOnSelectedNode = (new Toggle()
            {
                text = "Focus Search On Selected Node",
                value = Settings.SearchOnSelectedNodeRegistry,
            });
#if UNITY_2019_3_OR_NEWER
                                        searchOnSelectedNode.RegisterValueChangedCallback(
#else
                                        searchOnSelectedNode.OnValueChanged(
#endif
                                            (toggleEvent) => { Settings.SearchOnSelectedNodeRegistry = toggleEvent.newValue; });
                                        section.Add(searchOnSelectedNode);
                                        var searchOnLabel =
                                            new Label(
                                                "Highlight a node and press Spacebar to open a Search Window focused on nodes for that type. ");
                                        searchOnLabel.AddToClassList("settings-label");
                                        section.Add(searchOnLabel);

                                        // Add Search On Noodle Drop settings
                                        var searchOnNoodleDrop = (new Toggle()
            {
                text = "Search On Noodle Drop",
                value = Settings.SearchOnNoodleDrop,
            });
#if UNITY_2019_3_OR_NEWER
                                                                  searchOnNoodleDrop.RegisterValueChangedCallback(
#else
                                                                  searchOnNoodleDrop.OnValueChanged(
#endif
                                                                      (toggleEvent) => { Settings.SearchOnNoodleDrop = toggleEvent.newValue; });
                                                                  section.Add(searchOnNoodleDrop);
                                                                  var searchOnDropLabel =
                                                                      new Label("Drop a noodle into empty space to search for anything that can be connected.");
                                                                  searchOnDropLabel.AddToClassList("settings-label");
                                                                  section.Add(searchOnDropLabel);

                                                                  // Add UseNeonStyle setting
                                                                  var useNeonStyle = (new Toggle()
            {
                text = "Use Neon Style",
                value = Settings.UseNeonStyle,
            });
#if UNITY_2019_3_OR_NEWER
                                                                                      useNeonStyle.RegisterValueChangedCallback(
#else
                                                                                      useNeonStyle.OnValueChanged(
#endif
                                                                                          (toggleEvent) => { Settings.UseNeonStyle = toggleEvent.newValue; });
                                                                                      section.Add(useNeonStyle);
                                                                                      var useNeonStyleLabel =
                                                                                          new Label("Try out an experimental Neon Style. We will support User Styles in an upcoming version.");
                                                                                      useNeonStyleLabel.AddToClassList("settings-label");
                                                                                      section.Add(useNeonStyleLabel);
        }
 public CounterItem()
 {
     titleLabel = new Label();
     titleLabel.AddToClassList(k_UssClass_Label);
     Add(titleLabel);
 }
示例#28
0
            public BoxModelElement(BoxType boxType, VisualElement content,
                                   VisualElement topTextFieldContainer, VisualElement bottomTextFieldContainer)
            {
                string title = "";

                switch (boxType)
                {
                case BoxType.Margin:
                    title = "margin";
                    break;

                case BoxType.Border:
                    title = "border";
                    break;

                case BoxType.Padding:
                    title = "padding";
                    break;
                }

                this.boxType = boxType;

                m_Title = new Label(title);
                m_Title.AddToClassList("box-model-title");

                m_CenterContent = content;
                m_CenterContent.AddToClassList("box-model-center-content");

                m_LeftTextField = new IntegerField();
                m_LeftTextField.AddToClassList("box-model-textfield");
                m_LeftTextField.RegisterValueChangedCallback(e => OnTextFieldValueChanged(e, SideChanged.Left));

                m_RightTextField = new IntegerField();
                m_RightTextField.AddToClassList("box-model-textfield");
                m_RightTextField.RegisterValueChangedCallback(e => OnTextFieldValueChanged(e, SideChanged.Right));

                m_TopTextField = new IntegerField();
                m_TopTextField.AddToClassList("box-model-textfield");
                m_TopTextField.RegisterValueChangedCallback(e => OnTextFieldValueChanged(e, SideChanged.Top));

                m_FakeTopTextField = new IntegerField();
                m_FakeTopTextField.AddToClassList("box-model-textfield");
                m_FakeTopTextField.visible = false;

                m_BottomTextField = new IntegerField();
                m_BottomTextField.AddToClassList("box-model-textfield");
                m_BottomTextField.RegisterValueChangedCallback(e => OnTextFieldValueChanged(e, SideChanged.Bottom));

                m_FakeBottomTextField = new IntegerField();
                m_FakeBottomTextField.AddToClassList("box-model-textfield");
                m_FakeBottomTextField.visible = false;

                m_Left = new VisualElement();
                m_Left.AddToClassList("box-model-side");
                m_Left.Add(m_LeftTextField);

                m_Right = new VisualElement();
                m_Right.AddToClassList("box-model-side");
                m_Right.Add(m_RightTextField);

                m_Center = new VisualElement();
                m_Center.AddToClassList("box-model-center");

                m_CenterTop = new VisualElement();
                m_CenterTop.AddToClassList("box-model-center-top");
                m_CenterTop.Add(m_FakeTopTextField);
                topTextFieldContainer.Add(m_TopTextField);

                m_CenterBottom = new VisualElement();
                m_CenterBottom.AddToClassList("box-model-center-bottom");
                m_CenterBottom.Add(m_FakeBottomTextField);
                bottomTextFieldContainer.Add(m_BottomTextField);

                m_Center.Add(m_CenterTop);
                m_Center.Add(m_CenterContent);
                m_Center.Add(m_CenterBottom);

                Add(m_Title);
                Add(m_Left);
                Add(m_Center);
                Add(m_Right);

                // Sync styles values
                schedule.Execute(SyncValues).Every(100);
            }
示例#29
0
        public void OnEnable()
        {
            var root = rootVisualElement;

            var styleSheet = EditorGUIUtility.Load(s_StyleSheetPath) as StyleSheet;

            root.styleSheets.Add(styleSheet);

            var themedStyleSheet = EditorGUIUtility.isProSkin
                ? EditorGUIUtility.Load(s_DarkStyleSheetPath) as StyleSheet
                : EditorGUIUtility.Load(s_LightStyleSheetPath) as StyleSheet;

            root.styleSheets.Add(themedStyleSheet);

            SampleTreeItem.ResetNextId();
            var items = new List <ITreeViewItem>()
            {
                new SampleTreeItem("Styles", StylesExplorer.Create),
                new SampleTreeItem("Button", ButtonSnippet.Create),
                new SampleTreeItem("Scroller", ScrollerSnippet.Create),
                new SampleTreeItem("Toggle", ToggleSnippet.Create),
                new SampleTreeItem("Label", LabelSnippet.Create),
                new SampleTreeItem("Text Field", TextFieldSnippet.Create),
                new SampleTreeItem("HelpBox", HelpBoxSnippet.Create),
                new SampleTreeItem("Object Field", ObjectFieldSnippet.Create),
                new SampleTreeItem("List View", ListViewSnippet.Create),
                new SampleTreeItem("Numeric Fields", MakeNumericFieldsPanel, new List <TreeViewItem <string> >()
                {
                    new SampleTreeItem("Integer", IntegerFieldSnippet.Create),
                    new SampleTreeItem("Float", FloatFieldSnippet.Create),
                    new SampleTreeItem("Long", LongFieldSnippet.Create),
                    new SampleTreeItem("MinMaxSlider", MinMaxSliderSnippet.Create),
                    new SampleTreeItem("Slider", SliderSnippet.Create),
                    new SampleTreeItem("Vector2", Vector2FieldSnippet.Create),
                    new SampleTreeItem("Vector3", Vector3FieldSnippet.Create),
                    new SampleTreeItem("Vector4", Vector4FieldSnippet.Create),
                    new SampleTreeItem("Rect", RectFieldSnippet.Create),
                    new SampleTreeItem("Bounds", BoundsFieldSnippet.Create),
                    new SampleTreeItem("SliderInt", SliderIntSnippet.Create),
                    new SampleTreeItem("Vector2Int", Vector2IntFieldSnippet.Create),
                    new SampleTreeItem("Vector3Int", Vector3IntFieldSnippet.Create),
                    new SampleTreeItem("RectInt", RectIntFieldSnippet.Create),
                    new SampleTreeItem("BoundsInt", BoundsIntFieldSnippet.Create)
                }),
                new SampleTreeItem("Value Fields", MakeValueFieldsPanel, new List <TreeViewItem <string> >()
                {
                    new SampleTreeItem("Color", ColorFieldSnippet.Create),
                    new SampleTreeItem("Curve", CurveFieldSnippet.Create),
                    new SampleTreeItem("Gradient", GradientFieldSnippet.Create)
                }),
                new SampleTreeItem("Choice Fields", MakeChoiceFieldsPanel, new List <TreeViewItem <string> >()
                {
                    new SampleTreeItem("Enum", EnumFieldSnippet.Create),
                    new SampleTreeItem("EnumFlags", EnumFlagsFieldSnippet.Create),
                    new SampleTreeItem("Popup", PopupFieldSnippet.Create),
                    new SampleTreeItem("Tag", TagFieldSnippet.Create),
                    new SampleTreeItem("Mask", MaskFieldSnippet.Create),
                    new SampleTreeItem("Layer", LayerFieldSnippet.Create),
                    new SampleTreeItem("LayerMask", LayerMaskFieldSnippet.Create)
                }),
            };

            Func <VisualElement> makeItem = () =>
            {
                var box = new VisualElement();
                box.AddToClassList(k_TreeItemClassName);

                var label = new Label();
                label.AddToClassList(k_TreeItemLabelClassName);

                box.Add(label);
                return(box);
            };

            Action <VisualElement, ITreeViewItem> bindItem = (element, item) =>
            {
                (element.ElementAt(0) as Label).text = (item as SampleTreeItem).data;
                element.userData = item;
            };

            Action <IEnumerable <ITreeViewItem> > onSelectionChanged = selectedItems =>
            {
                var item = (SampleTreeItem)selectedItems.FirstOrDefault();
                if (item == null)
                {
                    return;
                }

                m_ContentPanel.Clear();
                m_ContentPanel.Add(item.makeItem(item));
            };

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

            treeView.AddToClassList(k_TreeViewClassName);
            m_ContentPanel = new VisualElement()
            {
                name = k_ContentPanelName
            };
            m_ContentPanel.AddToClassList(k_ContentPanelClassName);

            var splitter = new DebuggerSplitter();

            splitter.AddToClassList(k_SplitterClassName);
            splitter.leftPane.style.width = k_SplitterLeftPaneStartingWidth;
            root.Add(splitter);

            splitter.leftPane.Add(treeView);
            splitter.rightPane.Add(m_ContentPanel);

            treeView.viewDataKey        = "samples-tree";
            treeView.itemHeight         = 20;
            treeView.rootItems          = items;
            treeView.makeItem           = makeItem;
            treeView.bindItem           = bindItem;
            treeView.onSelectionChange += onSelectionChanged;
            treeView.Refresh();

            // Force TreeView to call onSelectionChanged when it restores its own selection from view data.
            treeView.schedule.Execute(() =>
            {
                onSelectionChanged(treeView.selectedItems);
            }).StartingIn(k_TreeViewSelectionRestoreDelay);

            // Force TreeView to select something if nothing is selected.
            treeView.schedule.Execute(() =>
            {
                if (treeView.selectedItems.Count() > 0)
                {
                    return;
                }

                treeView.SetSelection(0);

                // Auto-expand all items on load.
                foreach (var item in treeView.rootItems)
                {
                    treeView.ExpandItem(item.id);
                }
            }).StartingIn(k_TreeViewInitialSelectionDelay);
        }
示例#30
0
        internal TagEditor(TagAnnotation tag, TaggedAnimationClip clip)
        {
            m_Tag  = tag;
            m_Clip = clip;

            UIElementsUtils.CloneTemplateInto("Inspectors/TagEditor.uxml", this);
            UIElementsUtils.ApplyStyleSheet(AnnotationsEditor.k_AnnotationsEditorStyle, this);
            AddToClassList(AnnotationsEditor.k_AnnotationsContainer);
            AddToClassList("drawerElement");

            var deleteButton = this.Q <Button>("deleteButton");

            deleteButton.clickable.clicked += () => { RemoveTag(m_Tag); };

            if (!tag.payload.ValidPayloadType)
            {
                Clear();
                var unknownLabel = new Label {
                    text = TagAttribute.k_UnknownTagType
                };
                unknownLabel.AddToClassList(AnnotationsEditor.k_UnknownAnnotationType);
                Add(unknownLabel);
                return;
            }

            TextField tagType = this.Q <TextField>("tagType");

            tagType.value = TagAttribute.GetDescription(m_Tag.Type);
            tagType.SetEnabled(false);

            Asset asset = m_Clip.Asset;

            TextField tagName = this.Q <TextField>("name");

            tagName.value = m_Tag.name;
            tagName.RegisterValueChangedCallback(evt =>
            {
                if (!evt.newValue.Equals(m_Tag.name, StringComparison.Ordinal))
                {
                    Undo.RecordObject(asset, "Change tag name");
                    m_Tag.name = evt.newValue;
                    m_Tag.NotifyChanged();
                    asset.MarkDirty();
                }
            });

            TextField metricLabel = this.Q <TextField>("metricLabel");
            var       metric      = asset.GetMetricForTagType(m_Tag.Type);

            if (metric != null)
            {
                metricLabel.value = metric.name;
                metricLabel.SetEnabled(false);
            }
            else
            {
                metricLabel.style.display = DisplayStyle.None;
            }

            TimeField stf = this.Q <TimeField>("startTime");

            stf.Init(m_Clip, m_Tag.startTime);
            stf.TimeChanged += (newTime) =>
            {
                if (!EqualityComparer <float> .Default.Equals(m_Tag.startTime, newTime))
                {
                    Undo.RecordObject(asset, "Change tag start time");
                    m_Tag.startTime = newTime;
                    m_Tag.NotifyChanged();
                    asset.MarkDirty();
                }
            };


            TimeField dtf = this.Q <TimeField>("durationTime");

            dtf.Init(m_Clip, m_Tag.duration);
            dtf.TimeChanged += (newTime) =>
            {
                if (!EqualityComparer <float> .Default.Equals(m_Tag.duration, newTime))
                {
                    Undo.RecordObject(asset, "Change tag duration");
                    m_Tag.duration = newTime;
                    m_Tag.NotifyChanged();
                    asset.MarkDirty();
                }
            };

            var so = m_Tag.payload.ScriptableObject;

            if (so != null)
            {
                m_PayloadInspector = UnityEditor.Editor.CreateEditor(so) as GenericStructInspector;
                m_PayloadInspector.StructModified += () =>
                {
                    m_Tag.payload.Serialize();
                    m_Tag.NotifyChanged();
                    m_Clip.Asset.MarkDirty();
                };

                VisualElement inspectorElement   = m_PayloadInspector.CreateInspectorGUI() ?? new IMGUIContainer(m_PayloadInspector.OnInspectorGUI);
                var           inspectorContainer = this.Q <VisualElement>("payloadInspector");
                inspectorContainer.Add(inspectorElement);
            }

            RegisterCallback <DetachFromPanelEvent>(OnDetachFromPanel);

            m_Tag.Changed += Refresh;
            asset.AssetWasDeserialized += Refresh;
        }