void FillView(IEnumerable <ITreeViewItem> items, VisualElement itemsParent = null)
        {
            foreach (var item in items)
            {
                if (item is BuilderLibraryTreeItem libraryTreeItem)
                {
                    if (libraryTreeItem.isHeader)
                    {
                        var categoryFoldout = new LibraryFoldout {
                            text = libraryTreeItem.data
                        };
                        if (libraryTreeItem.isEditorOnly)
                        {
                            categoryFoldout.tag = BuilderConstants.EditorOnlyTag;
                            categoryFoldout.Q(LibraryFoldout.TagLabelName).AddToClassList(BuilderConstants.TagPillClassName);
                        }
                        categoryFoldout.contentContainer.RegisterCallback <GeometryChangedEvent>(e => AdjustSpace(categoryFoldout));
                        categoryFoldout.AddToClassList(k_PlainViewFoldoutStyle);
                        Add(categoryFoldout);
                        FillView(libraryTreeItem.children, categoryFoldout);
                        continue;
                    }

                    var plainViewItem = new LibraryPlainViewItem(libraryTreeItem);
                    plainViewItem.AddManipulator(new ContextualMenuManipulator(OnContextualMenuPopulateEvent));
                    plainViewItem.RegisterCallback <MouseDownEvent, LibraryPlainViewItem>(OnPlainViewItemMouseDown, plainViewItem);

                    LinkToTreeViewItem(plainViewItem, libraryTreeItem);

                    // The element set up is not yet completed at this point.
                    // SetupView has to be called as well.
                    plainViewItem.RegisterCallback <AttachToPanelEvent>(e =>
                    {
                        RegisterControlContainer(plainViewItem);
                    });

                    plainViewItem.RegisterCallback <MouseDownEvent>(e =>
                    {
                        if (e.clickCount == 2)
                        {
                            AddItemToTheDocument(libraryTreeItem);
                        }
                    });
                    itemsParent?.Add(plainViewItem);
                    m_PlainViewItems.Add(plainViewItem);
                }
            }
        }
Example #2
0
    void Start()
    {
        var uiRoot = m_UiRoot.rootVisualElement;

        // CONTAINER
        m_Container                = new VisualElement();
        m_Container.name           = "build-menu-container";
        m_Container.style.display  = DisplayStyle.None;
        m_Container.style.position = Position.Absolute;
        m_Container.style.width    = 398;
        m_Container.style.height   = 398;

        // BACKGROUND
        var backgroundLarge = new VisualElement();

        backgroundLarge.style.visibility      = Visibility.Visible;
        backgroundLarge.style.position        = Position.Absolute;
        backgroundLarge.style.backgroundImage = new StyleBackground(spriteBackgroundLarge);
        backgroundLarge.style.width           = Length.Percent(100);
        backgroundLarge.style.height          = Length.Percent(100);
        backgroundLarge.style.left            = Length.Percent(-50);
        backgroundLarge.style.top             = Length.Percent(-50);

        m_Container.Add(backgroundLarge);

        // ICON
        {
            m_IconWrapper = new VisualElement();

            // CALLBACK HANDLERS
            m_IconWrapper.RegisterCallback <PointerEnterEvent>(e =>
            {
                m_Logger.Log($"PointerEnterEvent ({e.localPosition})");
                SetIconState(IconState.Selected);
            });
            m_IconWrapper.RegisterCallback <PointerMoveEvent>(e =>
            {
                m_Logger.Log($"PointerMoveEvent ({e.localPosition})");
            });
            m_IconWrapper.RegisterCallback <PointerLeaveEvent>(e =>
            {
                m_Logger.Log($"PointerLeaveEvent ({e.localPosition})");
                SetIconState(IconState.Active);
            });



            // Set icon position
            var centerX = 100;
            var centerY = 0;
            m_IconWrapper.style.left = (-65 / 2) + centerX;
            m_IconWrapper.style.top  = (-77 / 2) + centerY;

            m_IconSelected = new VisualElement();
            m_IconSelected.style.visibility      = Visibility.Hidden;
            m_IconSelected.style.position        = Position.Absolute;
            m_IconSelected.style.backgroundImage = new StyleBackground(spriteIcon2);
            m_IconSelected.style.width           = 65;
            m_IconSelected.style.height          = 77;
            m_IconWrapper.Add(m_IconSelected);

            m_IconActive = new VisualElement();
            m_IconActive.style.visibility      = Visibility.Hidden;
            m_IconActive.style.position        = Position.Absolute;
            m_IconActive.style.backgroundImage = new StyleBackground(spriteIcon1);
            m_IconActive.style.width           = 65;
            m_IconActive.style.height          = 77;

            m_IconWrapper.Add(m_IconActive);

            m_IconDisabled = new VisualElement();
            m_IconDisabled.style.visibility      = Visibility.Hidden;
            m_IconDisabled.style.position        = Position.Absolute;
            m_IconDisabled.style.backgroundImage = new StyleBackground(spriteIcon0);
            m_IconDisabled.style.width           = 65;
            m_IconDisabled.style.height          = 77;
            m_IconWrapper.Add(m_IconDisabled);

            m_Container.Add(m_IconWrapper);
        }

        // Add container to root
        uiRoot.Add(m_Container);

        SetIconState(IconState.Active);
    }
        public VisualElement Create()
        {
            var root = new ScrollView();

            m_parent.OnStats += (peer, report) =>
            {
                if (peer != m_peerConnection || report.Stats.Keys.Count == m_lastUpdateKeys?.Count)
                {
                    return;
                }

                m_lastUpdateKeys = report.Stats.Keys;
                root.Clear();

                var container = new VisualElement();

                var popup = new PopupField <string>(m_lastUpdateKeys.ToList(), 0, id => $"{id}", id => $"{id}");

                root.Add(popup);
                root.Add(container);

                popup.RegisterValueChangedCallback(e =>
                {
                    container.Clear();
                    var id   = e.newValue;
                    var type = report.Get(id).Type;
                    switch (type)
                    {
                    case RTCStatsType.Codec:
                        container.Add(CreateCodecView(id));
                        break;

                    case RTCStatsType.InboundRtp:
                        container.Add(CreateInboundRtpView(id));
                        break;

                    case RTCStatsType.OutboundRtp:
                        container.Add(CreateOutboundRtpView(id));
                        break;

                    case RTCStatsType.RemoteInboundRtp:
                        container.Add(CreateRemoteInboundRtpView(id));
                        break;

                    case RTCStatsType.RemoteOutboundRtp:
                        container.Add(CreateRemoteOutboundRtpView(id));
                        break;

                    case RTCStatsType.MediaSource:
                        container.Add(CreateMediaSourceView(id));
                        break;

                    case RTCStatsType.Csrc:
                        container.Add(CreateCsrcView(id));
                        break;

                    case RTCStatsType.PeerConnection:
                        container.Add(CreatePeerConnectionView(id));
                        break;

                    case RTCStatsType.DataChannel:
                        container.Add(CreateDataChannelView(id));
                        break;

                    case RTCStatsType.Stream:
                        container.Add(CreateStreamView(id));
                        break;

                    case RTCStatsType.Track:
                        container.Add(CreateTrackView(id));
                        break;

                    case RTCStatsType.Transceiver:
                        container.Add(CreateTransceiverView(id));
                        break;

                    case RTCStatsType.Sender:
                        container.Add(CreateSenderView(id));
                        break;

                    case RTCStatsType.Receiver:
                        container.Add(CreateReceiverView(id));
                        break;

                    case RTCStatsType.Transport:
                        container.Add(CreateTransportView(id));
                        break;

                    case RTCStatsType.SctpTransport:
                        container.Add(CreateSctpTransportView(id));
                        break;

                    case RTCStatsType.CandidatePair:
                        container.Add(CreateCandidatePairView(id));
                        break;

                    case RTCStatsType.LocalCandidate:
                        container.Add(CreateLocalCandidateView(id));
                        break;

                    case RTCStatsType.RemoteCandidate:
                        container.Add(CreateRemoteCandidateView(id));
                        break;

                    case RTCStatsType.Certificate:
                        container.Add(CreateCertificateView(id));
                        break;

                    case RTCStatsType.IceServer:
                        container.Add(CreateIceServerView(id));
                        break;

                    default:
                        throw new ArgumentOutOfRangeException($"this type is not supported : {type}");
                    }
                });
            };

            return(root);
        }
        public void Initialize(AbstractMaterialNode inNode, PreviewManager previewManager, IEdgeConnectorListener connectorListener, GraphView graphView)
        {
            styleSheets.Add(Resources.Load <StyleSheet>("Styles/MaterialNodeView"));
            styleSheets.Add(Resources.Load <StyleSheet>($"Styles/ColorMode"));
            AddToClassList("MaterialNode");

            if (inNode == null)
            {
                return;
            }

            var contents = this.Q("contents");

            m_GraphView = graphView;

            m_ConnectorListener = connectorListener;
            node        = inNode;
            viewDataKey = node.guid.ToString();
            UpdateTitle();

            // Add controls container
            var controlsContainer = new VisualElement {
                name = "controls"
            };

            {
                m_ControlsDivider = new VisualElement {
                    name = "divider"
                };
                m_ControlsDivider.AddToClassList("horizontal");
                controlsContainer.Add(m_ControlsDivider);
                m_ControlItems = new VisualElement {
                    name = "items"
                };
                controlsContainer.Add(m_ControlItems);

                // Instantiate control views from node
                foreach (var propertyInfo in node.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
                {
                    foreach (IControlAttribute attribute in propertyInfo.GetCustomAttributes(typeof(IControlAttribute), false))
                    {
                        m_ControlItems.Add(attribute.InstantiateControl(node, propertyInfo));
                    }
                }
            }
            if (m_ControlItems.childCount > 0)
            {
                contents.Add(controlsContainer);
            }

            if (node.hasPreview)
            {
                // Add actual preview which floats on top of the node
                m_PreviewContainer = new VisualElement
                {
                    name          = "previewContainer",
                    cacheAsBitmap = true,
                    style         = { overflow = Overflow.Hidden },
                    pickingMode   = PickingMode.Ignore
                };
                m_PreviewImage = new Image
                {
                    name        = "preview",
                    pickingMode = PickingMode.Ignore,
                    image       = Texture2D.whiteTexture,
                };
                {
                    // Add preview collapse button on top of preview
                    var collapsePreviewButton = new VisualElement {
                        name = "collapse"
                    };
                    collapsePreviewButton.Add(new VisualElement {
                        name = "icon"
                    });
                    collapsePreviewButton.AddManipulator(new Clickable(() =>
                    {
                        node.owner.owner.RegisterCompleteObjectUndo("Collapse Preview");
                        UpdatePreviewExpandedState(false);
                    }));
                    m_PreviewImage.Add(collapsePreviewButton);
                }
                m_PreviewContainer.Add(m_PreviewImage);

                // Hook up preview image to preview manager
                m_PreviewRenderData = previewManager.GetPreview(inNode);
                m_PreviewRenderData.onPreviewChanged += UpdatePreviewTexture;
                UpdatePreviewTexture();

                // Add fake preview which pads out the node to provide space for the floating preview
                m_PreviewFiller = new VisualElement {
                    name = "previewFiller"
                };
                m_PreviewFiller.AddToClassList("expanded");
                {
                    var previewDivider = new VisualElement {
                        name = "divider"
                    };
                    previewDivider.AddToClassList("horizontal");
                    m_PreviewFiller.Add(previewDivider);

                    var expandPreviewButton = new VisualElement {
                        name = "expand"
                    };
                    expandPreviewButton.Add(new VisualElement {
                        name = "icon"
                    });
                    expandPreviewButton.AddManipulator(new Clickable(() =>
                    {
                        node.owner.owner.RegisterCompleteObjectUndo("Expand Preview");
                        UpdatePreviewExpandedState(true);
                    }));
                    m_PreviewFiller.Add(expandPreviewButton);
                }
                contents.Add(m_PreviewFiller);

                UpdatePreviewExpandedState(node.previewExpanded);
            }

            // Add port input container, which acts as a pixel cache for all port inputs
            m_PortInputContainer = new VisualElement
            {
                name          = "portInputContainer",
                cacheAsBitmap = true,
                style         = { overflow = Overflow.Hidden },
                pickingMode   = PickingMode.Ignore
            };
            Add(m_PortInputContainer);

            AddSlots(node.GetSlots <MaterialSlot>());
            UpdatePortInputs();
            base.expanded = node.drawState.expanded;
            RefreshExpandedState(); //This should not be needed. GraphView needs to improve the extension api here
            UpdatePortInputVisibilities();

            SetPosition(new Rect(node.drawState.position.x, node.drawState.position.y, 0, 0));

            if (node is SubGraphNode)
            {
                RegisterCallback <MouseDownEvent>(OnSubGraphDoubleClick);
            }

            m_PortInputContainer.SendToBack();

            m_TitleContainer = this.Q("title");

            var masterNode = node as IMasterNode;

            if (masterNode != null)
            {
                AddToClassList("master");

                if (!masterNode.IsPipelineCompatible(GraphicsSettings.renderPipelineAsset))
                {
                    AttachMessage("The current render pipeline is not compatible with this master node.", ShaderCompilerMessageSeverity.Error);
                }
            }

            m_NodeSettingsView         = new NodeSettingsView();
            m_NodeSettingsView.visible = false;
            Add(m_NodeSettingsView);

            m_SettingsButton = new VisualElement {
                name = "settings-button"
            };
            m_SettingsButton.Add(new VisualElement {
                name = "icon"
            });

            m_Settings = new VisualElement();
            AddDefaultSettings();

            // Add Node type specific settings
            var nodeTypeSettings = node as IHasSettings;

            if (nodeTypeSettings != null)
            {
                m_Settings.Add(nodeTypeSettings.CreateSettingsElement());
            }

            // Add manipulators
            m_SettingsButton.AddManipulator(new Clickable(() =>
            {
                UpdateSettingsExpandedState();
            }));

            if (m_Settings.childCount > 0)
            {
                m_ButtonContainer = new VisualElement {
                    name = "button-container"
                };
                m_ButtonContainer.style.flexDirection = FlexDirection.Row;
                m_ButtonContainer.Add(m_SettingsButton);
                m_ButtonContainer.Add(m_CollapseButton);
                m_TitleContainer.Add(m_ButtonContainer);
            }
        }
Example #5
0
 void InitializeDebug()
 {
     ComputeOrderUpdatedCallback();
     debugContainer.Add(computeOrderLabel);
 }
        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;
        }
Example #7
0
    private Node CreateNode(AssetGroup assetGroup, Object obj, string assetPath, bool isMainNode, int dependencyAmount)
    {
        Node   resultNode;
        string assetGUID = AssetDatabase.AssetPathToGUID(assetPath);

        if (m_GUIDNodeLookup.TryGetValue(assetGUID, out resultNode))
        {
            //----not sure what this is, the more dependencies the further removed on the chart?
            //int currentDepth = (int)resultNode.userData;
            //resultNode.userData = currentDepth + 1;
            return(resultNode);
        }

        if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(obj, out var assetGuid, out long _))
        {
            var objNode = new Node {
                title = obj.name,
                style =
                {
                    width = kNodeWidth
                }
            };

            objNode.extensionContainer.style.backgroundColor = new Color(0.24f, 0.24f, 0.24f, 0.8f);

            #region Select button
            objNode.titleContainer.Add(new Button(() => {
                Selection.activeObject = obj;
                EditorGUIUtility.PingObject(obj);
            })
            {
                style =
                {
                    height     =        16.0f,
                    alignSelf  = Align.Center,
                    alignItems = Align.Center
                },
                text = "Select"
            });
            #endregion

            #region Padding
            var infoContainer = new VisualElement {
                style =
                {
                    paddingBottom = 4.0f,
                    paddingTop    = 4.0f,
                    paddingLeft   = 4.0f,
                    paddingRight  = 4.0f
                }
            };
            #endregion

            #region Asset Path, removed to improve visibility with large amount of assets
            //            infoContainer.Add(new Label {
            //                text = assetPath,
            //#if UNITY_2019_1_OR_NEWER
            //                style = { whiteSpace = WhiteSpace.Normal }
            //#else
            //                style = { wordWrap = true }
            //#endif
            //            });
            #endregion

            #region Asset type
            var typeName = obj.GetType().Name;
            if (isMainNode)
            {
                var prefabType = PrefabUtility.GetPrefabAssetType(obj);
                if (prefabType != PrefabAssetType.NotAPrefab)
                {
                    typeName = $"{prefabType} Prefab";
                }
            }

            var typeLabel = new Label {
                text = $"Type: {typeName}",
            };
            infoContainer.Add(typeLabel);

            objNode.extensionContainer.Add(infoContainer);
            #endregion

            var typeContainer = new VisualElement {
                style =
                {
                    paddingBottom   = 4.0f,
                    paddingTop      = 4.0f,
                    paddingLeft     = 4.0f,
                    paddingRight    = 4.0f,
                    backgroundColor = GetColorByAssetType(obj)
                }
            };

            objNode.extensionContainer.Add(typeContainer);

            #region Node Icon, replaced with color
            //Texture assetTexture = AssetPreview.GetAssetPreview(obj);
            //if (!assetTexture)
            //    assetTexture = AssetPreview.GetMiniThumbnail(obj);

            //if (assetTexture)
            //{
            //    AddDivider(objNode);

            //    objNode.extensionContainer.Add(new Image
            //    {
            //        image = assetTexture,
            //        scaleMode = ScaleMode.ScaleToFit,
            //        style =
            //        {
            //            paddingBottom = 4.0f,
            //            paddingTop = 4.0f,
            //            paddingLeft = 4.0f,
            //            paddingRight = 4.0f
            //        }
            //    });
            //}
            #endregion

            // Ports
            //if (!isMainNode) {
            Port realPort = objNode.InstantiatePort(Orientation.Horizontal, Direction.Input, Port.Capacity.Single, typeof(Object));
            realPort.portName = "Dependent";
            objNode.inputContainer.Add(realPort);
            //}

            if (dependencyAmount > 0)
            {
#if UNITY_2018_1
                Port port = objNode.InstantiatePort(Orientation.Horizontal, Direction.Output, typeof(Object));
#else
                Port port = objNode.InstantiatePort(Orientation.Horizontal, Direction.Output, Port.Capacity.Single, typeof(Object));
#endif
                port.portName = dependencyAmount + " Dependencies";
                objNode.outputContainer.Add(port);
                objNode.RefreshPorts();
            }

            resultNode = objNode;

            resultNode.RefreshExpandedState();
            resultNode.RefreshPorts();
            resultNode.capabilities &= ~Capabilities.Deletable;
            resultNode.capabilities |= Capabilities.Collapsible;
        }
        //Debug.Log(assetGUID);
        m_GUIDNodeLookup[assetGUID] = resultNode;
        return(resultNode);
    }
        public NoiseEditorView(NoiseSettings _noiseUpdateTarget_ = null, NoiseSettings _sourceAsset_ = null)
        {
            // create temp noisesettings asset and the IMGUI view for this window
            m_noiseUpdateTarget = _noiseUpdateTarget_ == null?ScriptableObject.CreateInstance <NoiseSettings>() : _noiseUpdateTarget_;

            m_serializedNoiseProfile = new SerializedObject(m_noiseUpdateTarget);
            m_noiseGUI = new NoiseSettingsGUI();
            m_noiseGUI.Init(m_noiseUpdateTarget);

            m_noiseSourceAsset = _sourceAsset_;

            var stylesheet = EditorGUIUtility.isProSkin ?
                             AssetDatabase.LoadAssetAtPath <StyleSheet>("Packages/com.unity.terrain-tools/Editor/TerrainTools/NoiseLib/Styles/Noise_Dark.uss") :
                             AssetDatabase.LoadAssetAtPath <StyleSheet>("Packages/com.unity.terrain-tools/Editor/TerrainTools/NoiseLib/Styles/Noise_Light.uss");

            var settingsScrollView = new ScrollView()
            {
                name = Styles.settingsScrollViewName
            };

            ///////////////////////////////////////////////////////////////////////////////
            // settings buttons
            ///////////////////////////////////////////////////////////////////////////////

            var noiseGUIContainer = new IMGUIContainer()
            {
                name = Styles.noiseGUIContainerName
            };

            noiseGUIContainer.onGUIHandler = () =>
            {
                EditorGUI.BeginChangeCheck();
                {
                    m_noiseGUI.OnGUI(NoiseSettingsGUIFlags.All & (~NoiseSettingsGUIFlags.Preview));
                }
                bool changed = EditorGUI.EndChangeCheck();

                if (changed)
                {
                    INTERNAL_OnSettingsChanged();
                }
            };
            settingsScrollView.Add(noiseGUIContainer);

            ///////////////////////////////////////////////////////////////////////////////
            // settings buttons
            ///////////////////////////////////////////////////////////////////////////////

            filePanelContainer = new VisualElement()
            {
                name  = Styles.saveButtonsContainer,
                style =
                {
                    flexDirection = FlexDirection.Row
                }
            };
            filePanelContainer.AddToClassList(Styles.filePanelContainer);

            saveAsButton = new Button(SaveAsCallback)
            {
                name    = Styles.saveAsButtonName,
                text    = "Save As",
                tooltip = Styles.saveasTooltip
            };
            saveAsButton.AddToClassList(Styles.filePanelButton);

            revertButton = new Button(ResetRevertCallback)
            {
                name    = Styles.resetButtonName,
                text    = "Reset",
                tooltip = Styles.resetTooltip
            };
            revertButton.AddToClassList(Styles.filePanelButton);

            applyButton = new Button(() => { Undo.RecordObject(m_noiseSourceAsset, "NoiseWindow - Apply Settings"); m_noiseSourceAsset.CopySerialized(m_noiseUpdateTarget); })
            {
                name    = Styles.applyButtonName,
                text    = "Apply",
                tooltip = Styles.applyTooltip
            };
            applyButton.AddToClassList(Styles.filePanelButton);
            applyButton.AddToClassList(Styles.filePanelButton);

            ///////////////////////////////////////////////////////////////////////////////
            // noise settings object field
            ///////////////////////////////////////////////////////////////////////////////

            var objectFieldContainer = new VisualElement()
            {
                name = Styles.objectFieldContainer
            };

            objectFieldContainer.AddToClassList(Styles.objectFieldContainer);

            objectField = new ObjectField()
            {
                name = Styles.noiseAssetFieldName,
                allowSceneObjects = false,
                objectType        = typeof(NoiseSettings),
                label             = Styles.noiseAssetFieldLabel,
                tooltip           = Styles.noiseAssetFieldTooltip //,
                                                                  // viewDataKey = Styles.noiseAssetFieldName
            };
            objectField.AddToClassList(Styles.noiseAssetFieldName);
            objectField.RegisterCallback <ChangeEvent <UnityEngine.Object> >(OnSourceProfileChanged);

            objectFieldContainer.Add(objectField);

            ///////////////////////////////////////////////////////////////////////////////
            // export settings
            ///////////////////////////////////////////////////////////////////////////////

            var flexArea = new VisualElement()
            {
                name = Styles.flexArea
            };

            flexArea.AddToClassList(Styles.flexArea);

            var exportContainer = new VisualElement()
            {
                name = Styles.exportContainer
            };

            exportContainer.AddToClassList(Styles.exportContainer);

            var exportHeader = new Foldout()
            {
                name        = Styles.exportHeader,
                text        = "Export Noise to Texture",
                tooltip     = Styles.exportTooltip,
                viewDataKey = Styles.exportHeader
            };

            exportHeader.RegisterCallback <ChangeEvent <bool> >(
                (evt) =>
            {
                if (evt.newValue)
                {
                    m_exportContainer.Add(m_exportSettings);
                    m_exportContainer.Add(m_exportButton);
                }
                else
                {
                    m_exportContainer.Remove(m_exportSettings);
                    m_exportContainer.Remove(m_exportButton);
                }
            }
                );
            exportHeader.AddToClassList(Styles.foldoutContainer);

            var exportSettings = CreateExportSettingsView();

            var exportButton = new Button(
                () =>
            {
                if (m_exportType.value == ExportTextureType.Texture2D)
                {
                    Export2D();
                }
                else if (m_exportType.value == ExportTextureType.Texture3D)
                {
                    Export3D();
                }
            }
                )
            {
                name = Styles.exportButton,
                text = "Export"
            };

            exportButton.AddToClassList(Styles.exportButton);

            m_exportButton = exportButton;
            exportContainer.Add(exportHeader);
            // exportContainer.Add( exportSettings );
            // exportContainer.Add( exportButton );

            m_exportContainer  = exportContainer;
            exportHeader.value = false;

            // container for the settings panel
            var settingsContainer = new VisualElement()
            {
                name = Styles.settingsContainerName
            };

            settingsContainer.AddToClassList(Styles.settingsContainerName);
            settingsContainer.Add(objectFieldContainer);
            settingsContainer.Add(filePanelContainer);
            settingsContainer.Add(settingsScrollView);
            settingsContainer.Add(flexArea); // add this so the export stuff stays at the bottom of the settings container
            settingsContainer.Add(exportContainer);
            settingsContainer.Bind(m_serializedNoiseProfile);

            ///////////////////////////////////////////////////////////////////////////////
            // settings buttons
            ///////////////////////////////////////////////////////////////////////////////

            var previewContainer = new VisualElement()
            {
                name = Styles.noisePreviewContainerName
            };

            previewContainer.AddToClassList(Styles.noisePreviewContainerName);

            var previewLabel = new Label()
            {
                name    = Styles.noisePreviewLabelName,
                text    = Styles.previewLabel,
                tooltip = Styles.previewLabelTooltip
            };

            previewLabel.AddToClassList(Styles.noisePreviewLabelName);
            previewContainer.Add(previewLabel);

            m_noiseFieldView = new NoiseFieldView(m_serializedNoiseProfile)
            {
                name = Styles.noisePreviewTextureName
            };
            m_noiseFieldView.onGUIHandler += () =>
            {
                INTERNAL_OnSettingsChanged();
            };
            m_noiseFieldView.AddToClassList(Styles.noisePreviewTextureName);
            previewContainer.Add(m_noiseFieldView);

            ///////////////////////////////////////////////////////////////////////////////
            // wrap it all up
            ///////////////////////////////////////////////////////////////////////////////

            styleSheets.Add(stylesheet);
            AddToClassList(Styles.noiseWindowName);
            Add(settingsContainer);
            Add(previewContainer);

            this.Bind(m_serializedNoiseProfile);

            m_settingsContainer = settingsContainer;

            INTERNAL_OnSourceProfileChanged(_sourceAsset_);

            this.viewDataKey = Styles.noiseWindowName;
        }
        public CollabHistoryItem(RevisionData data)
        {
            m_RevisionId  = data.id;
            m_TimeStamp   = data.timeStamp;
            name          = "HistoryItem";
            m_ActionsTray = new VisualElement {
                name = "HistoryItemActionsTray"
            };
            m_ProgressSpinner = new HistoryProgressSpinner();
            m_Details         = new VisualElement {
                name = "HistoryDetail"
            };
            var author = new Label(data.authorName)
            {
                name = "Author"
            };

            m_TimeAgo         = new Label(TimeAgo.GetString(m_TimeStamp));
            m_FullDescription = data.comment;
            var shouldTruncate = ShouldTruncateDescription(m_FullDescription);

            if (shouldTruncate)
            {
                m_Description = new Label(GetTruncatedDescription(m_FullDescription));
            }
            else
            {
                m_Description = new Label(m_FullDescription);
            }
            m_Description.name = "RevisionDescription";
            var dropdown = new CollabHistoryDropDown(data.changes, data.changesTotal, data.changesTruncated, data.id);

            if (data.current)
            {
                m_Button = new Button(Restore)
                {
                    name = "ActionButton", text = "Restore"
                };
            }
            else if (data.obtained)
            {
                m_Button = new Button(GoBackTo)
                {
                    name = "ActionButton", text = "Go back to..."
                };
            }
            else
            {
                m_Button = new Button(UpdateTo)
                {
                    name = "ActionButton", text = "Update"
                };
            }
            m_Button.SetEnabled(data.enabled);
            m_ProgressSpinner.ProgressEnabled = data.inProgress;

            m_ActionsTray.Add(m_ProgressSpinner);
            m_ActionsTray.Add(m_Button);

            m_Details.Add(author);
            m_Details.Add(m_TimeAgo);
            m_Details.Add(m_Description);

            if (shouldTruncate)
            {
                m_ExpandCollapseButton = new Button(ToggleDescription)
                {
                    name = "ToggleDescription", text = "Show More"
                };
                m_Details.Add(m_ExpandCollapseButton);
            }

            if (data.buildState != BuildState.None)
            {
                BuildStatusButton buildButton;
                if (data.buildState == BuildState.Configure)
                {
                    buildButton = new BuildStatusButton(ShowServicePage);
                }
                else
                {
                    buildButton = new BuildStatusButton(ShowBuildForCommit, data.buildState, data.buildFailures);
                }

                m_Details.Add(buildButton);
            }

            m_Details.Add(m_ActionsTray);
            m_Details.Add(dropdown);

            Add(m_Details);

            this.schedule.Execute(UpdateTimeAgo).Every(1000 * 20);
        }
Example #10
0
        void SyncAnchors(ReadOnlyCollection <VFXDataAnchorController> ports, VisualElement container)
        {
            var existingAnchors = container.Children().Cast <VFXDataAnchor>().ToDictionary(t => t.controller, t => t);


            Profiler.BeginSample("VFXNodeUI.SyncAnchors Delete");
            var deletedControllers = existingAnchors.Keys.Except(ports).ToArray();

            foreach (var deletedController in deletedControllers)
            {
                //Explicitely remove edges before removing anchor.
                GetFirstAncestorOfType <VFXView>().RemoveAnchorEdges(existingAnchors[deletedController]);
                container.Remove(existingAnchors[deletedController]);
                existingAnchors.Remove(deletedController);
            }
            Profiler.EndSample();

            Profiler.BeginSample("VFXNodeUI.SyncAnchors New");
            var order = ports.Select((t, i) => new KeyValuePair <VFXDataAnchorController, int>(t, i)).ToDictionary(t => t.Key, t => t.Value);

            var newAnchors = ports.Except(existingAnchors.Keys).ToArray();


            VFXDataAnchor firstAnchor = null;

            foreach (var newController in newAnchors)
            {
                Profiler.BeginSample("VFXNodeUI.InstantiateDataAnchor");
                var newElement = InstantiateDataAnchor(newController, this);
                Profiler.EndSample();

                (newElement as VFXDataAnchor).controller = newController;

                container.Add(newElement);
                existingAnchors[newController] = newElement;
                if (firstAnchor == null)
                {
                    firstAnchor = newElement as VFXDataAnchor;
                }
            }

            if (firstAnchor != null)
            {
                firstAnchor.AddToClassList("first");
            }
            Profiler.EndSample();

            Profiler.BeginSample("VFXNodeUI.SyncAnchors Reorder");
            //Reorder anchors.
            if (ports.Count > 0)
            {
                var correctOrder = new VFXDataAnchor[ports.Count];
                foreach (var kv in existingAnchors)
                {
                    correctOrder[order[kv.Key]] = kv.Value;
                }

                correctOrder[0].SendToBack();
                correctOrder[0].AddToClassList("first");
                for (int i = 1; i < correctOrder.Length; ++i)
                {
                    if (container.ElementAt(i) != correctOrder[i])
                    {
                        correctOrder[i].PlaceInFront(correctOrder[i - 1]);
                    }
                    correctOrder[i].RemoveFromClassList("first");
                }
            }
            Profiler.EndSample();
        }
        public override VisualElement CreateInspectorGUI()
        {
            var root = Root = new VisualElement();

            root.AddToClassList("scene-template-asset-inspector");
            root.AddToClassList(Styles.unityThemeVariables);
            root.AddToClassList(Styles.sceneTemplateThemeVariables);
            root.AddStyleSheetPath(Styles.k_CommonStyleSheetPath);
            root.AddStyleSheetPath(Styles.variableStyleSheet);
            root.style.flexDirection = FlexDirection.Column;

            var detailElement = new VisualElement();

            // Template scene
            var templateSceneProperty = serializedObject.FindProperty(SceneTemplateUtils.TemplateScenePropertyName);
            var templatePropertyField = new PropertyField(templateSceneProperty, L10n.Tr("Template Scene"));

            templatePropertyField.tooltip = L10n.Tr("Scene to instantiate.");
            templatePropertyField.RegisterCallback <ChangeEvent <Object> >(e =>
            {
                RebuildDependencies(root);
                TriggerSceneTemplateModified();
            });
            detailElement.Add(templatePropertyField);

            // Scene title
            var templateTitleProperty = serializedObject.FindProperty(SceneTemplateUtils.TemplateTitlePropertyName);
            var titlePropertyField    = new PropertyField(templateTitleProperty, L10n.Tr("Title"));

            titlePropertyField.tooltip = L10n.Tr("Scene template display name. Shown in New Scene Dialog.");
            titlePropertyField.RegisterCallback <ChangeEvent <string> >(e => TriggerSceneTemplateModified());
            titlePropertyField.RegisterCallback <SerializedPropertyBindEvent>(e =>
            {
                EditorApplication.delayCall += () =>
                {
                    if (!titlePropertyField.Children().Any())
                    {
                        return;
                    }
                    if (titlePropertyField.Children().First() is TextField titlePropertyFieldTextField)
                    {
                        titlePropertyFieldTextField.maxLength = 1024;
                        m_TitleTextFieldReady = true;
                    }
                };
            });
            detailElement.Add(titlePropertyField);

            // Scene description
            var templateDescriptionProperty = serializedObject.FindProperty(SceneTemplateUtils.TemplateDescriptionPropertyName);
            var description = new PropertyField(templateDescriptionProperty, L10n.Tr("Description"));

            description.tooltip = L10n.Tr("Scene template description. Shown in New Scene Dialog.");
            description.RegisterCallback <ChangeEvent <string> >(e => TriggerSceneTemplateModified());
            description.RegisterCallback <SerializedPropertyBindEvent>(e =>
            {
                EditorApplication.delayCall += () =>
                {
                    if (!description.Children().Any())
                    {
                        return;
                    }
                    var descriptionTextField = description.Children().First() as TextField;
                    if (descriptionTextField != null)
                    {
                        descriptionTextField.AddToClassList(Styles.classWrappingText);
                        descriptionTextField.multiline = true;
                        descriptionTextField.maxLength = 1024;
                        m_DescriptionTextFieldReady    = true;
                    }
                };
            });
            detailElement.Add(description);

            var templateAddToDefaultsProperty = serializedObject.FindProperty(SceneTemplateUtils.TemplateAddToDefaultsPropertyName);
            var defaultTemplateField          = new VisualElement();

            defaultTemplateField.style.flexDirection = FlexDirection.Row;
            var addToDefaultsPropertyField = new PropertyField(templateAddToDefaultsProperty, " ");

            addToDefaultsPropertyField.RegisterCallback <ChangeEvent <bool> >(e => TriggerSceneTemplateModified());
            addToDefaultsPropertyField.style.flexShrink = 0;
            defaultTemplateField.Add(addToDefaultsPropertyField);
            var label = new Label(L10n.Tr("Pin in New Scene Dialog"));

            label.tooltip = L10n.Tr("Pin in New Scene Dialog. Ensuring this template is shown before unpinned template in the list.");
            label.style.unityTextAlign = TextAnchor.MiddleLeft;
            label.style.overflow       = Overflow.Hidden;
            label.style.textOverflow   = TextOverflow.Ellipsis;
            label.style.flexShrink     = 1;
            defaultTemplateField.Add(label);
            detailElement.Add(defaultTemplateField);
            root.Add(CreateFoldoutInspector(detailElement, L10n.Tr("Details"), "SceneTemplateInspectorDetailsFoldout"));

            // Template thumbnail
            var templateThumbnailProperty      = serializedObject.FindProperty(SceneTemplateUtils.TemplateThumbnailPropertyName);
            var templateThumbnailBadgeProperty = serializedObject.FindProperty(SceneTemplateUtils.TemplateThumbnailBadgePropertyName);
            var thumbnailField = MakeThumbnailField(templateThumbnailProperty, templateThumbnailBadgeProperty);

            root.Add(CreateFoldoutInspector(thumbnailField, L10n.Tr("Thumbnail"), "SceneTemplateInspectorThumbnailFoldout"));

            // SceneTemplatePipeline
            var sceneTemplatePipeline = new VisualElement();
            var pipelineProperty      = serializedObject.FindProperty(SceneTemplateUtils.TemplatePipelineName);
            var pipelineField         = new PropertyField(pipelineProperty, L10n.Tr("Scene Template Pipeline"));

            pipelineField.tooltip = k_SceneTemplateInfo;
            pipelineField.RegisterCallback <ChangeEvent <Object> >(e =>
            {
                if (e.newValue != null && !SceneTemplateAsset.IsValidPipeline(e.newValue as MonoScript))
                {
                    Debug.LogWarning(k_SceneTemplateInfo);
                    pipelineProperty.objectReferenceValue = null;
                    serializedObject.ApplyModifiedProperties();
                }
            });
            sceneTemplatePipeline.Add(pipelineField);
            var buttonRow            = CreateEmptyLabelRow(L10n.Tr("Scene Template Pipeline"), Styles.classUnityPropertyFieldLabel); // Use a hidden label instead of an empty element for proper alignment
            var createPipelineButton = new Button(OnCreateSceneTemplatePipeline)
            {
                text = k_CreatePipelineButtonLabel, tooltip = k_CreatePipelineTooltip
            };

            createPipelineButton.AddToClassList(Styles.classUnityBaseFieldInput);
            buttonRow.Add(createPipelineButton);
            sceneTemplatePipeline.Add(buttonRow);
            root.Add(CreateFoldoutInspectorWithHelp(sceneTemplatePipeline, L10n.Tr("Scene Template Pipeline"), "SceneTemplatePipelineFoldout", k_PipelineHelpUrl));

            // Dependencies
            root.Add(CreateFoldoutInspector(BuildDependencyRows(), L10n.Tr("Dependencies"), "SceneTemplateDependenciesFoldout"));
            return(root);
        }
        private VisualElement MakeThumbnailField(SerializedProperty thumbnailProperty, SerializedProperty thumbnailBadgeProperty)
        {
            var propertyElement           = new VisualElement();
            var thumbnailBadgeObjectField = new PropertyField(thumbnailBadgeProperty, L10n.Tr("Badge"));

            thumbnailBadgeObjectField.tooltip = L10n.Tr("Scene template badge. Shown in New Scene Dialog.");
            propertyElement.Add(thumbnailBadgeObjectField);

            thumbnailBadgeObjectField.RegisterCallback <ChangeEvent <Object> >(e =>
            {
                TriggerSceneTemplateModified();
            });

            var thumbnailObjectField = new PropertyField(thumbnailProperty, L10n.Tr("Preview"));

            thumbnailObjectField.tooltip = L10n.Tr("Scene template thumbnail. Shown in New Scene Dialog.");
            propertyElement.Add(thumbnailObjectField);

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

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

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

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

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

            snapshotHeaderLabel.tooltip = L10n.Tr("Generate a Scene template thumbnail from a snapshot in Scene or Game view.");
            snapshotHeaderLabel.AddToClassList(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 = L10n.Tr("Game View"), OnSnapshotAction = (info, callback) => TakeSnapshotFromGameView(callback)
            });
            var snapshotTargetPopup = new PopupField <SnapshotTargetInfo>(L10n.Tr("View"), cameraNames, Camera.allCameras.Length == 0 ? 1 : 0);

            snapshotTargetPopup.tooltip = L10n.Tr("View or Camera to use as the source of the snapshot.");
            snapshotTargetPopup.formatListItemCallback      = info => info.Name;
            snapshotTargetPopup.formatSelectedValueCallback = info => info.Name;
            snapshotTargetPopup.name = k_SnapshotTargetPopupName;
            propertyElement.Add(snapshotTargetPopup);

            var snapshotSecondRowElement = CreateEmptyLabelRow();

            propertyElement.Add(snapshotSecondRowElement);
            var snapshotButton = new Button(() =>
            {
                var targetInfo = snapshotTargetPopup.value;
                if (targetInfo.OnSnapshotAction == null)
                {
                    return;
                }

                targetInfo.OnSnapshotAction(targetInfo, null);
            });

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

            return(propertyElement);
        }
Example #13
0
        VisualElement GeneratedMatchingSelectors()
        {
            m_MatchingSelectors.GetElementMatchers();
            if (m_MatchingSelectors.matchedRulesExtractor.selectedElementRules == null ||
                m_MatchingSelectors.matchedRulesExtractor.selectedElementRules.Count <= 0)
            {
                return(null);
            }

            var container = new VisualElement();

            int ruleIndex = 0;

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

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

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

                for (int j = 0; j < props.Length; j++)
                {
                    string s = "";
                    for (int k = 0; k < props[j].values.Length; k++)
                    {
                        if (k > 0)
                        {
                            s += " ";
                        }

                        var str = rule.matchRecord.sheet.ReadAsString(props[j].values[k]);
                        s += str;
                    }

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

            return(container);
        }
Example #14
0
        public ComponentRow(ComponentQueryDeclarationModel componentQueryDeclarationModel,
                            ComponentDefinition component,
                            Stencil stencil,
                            Store store,
                            ExpandedContainer parentElement,
                            Action <EventBase> onDeleteComponent,
                            EventCallback <ChangeEvent <bool> > onUsageChanged)
            : base(string.Empty, componentQueryDeclarationModel, store, parentElement, null, null)
        {
            Component = component;
            m_Stencil = stencil;

            ClearClassList();
            AddToClassList("componentRow");

            var fieldViewContainerTooltip = new StringBuilder();
            var fields   = Component.TypeHandle.Resolve(stencil).GetFields();
            int nbFields = fields.Length;

            if (nbFields > 0)
            {
                int i = 0;
                foreach (var field in fields)
                {
                    var fieldView = new VisualElement {
                        name = "fieldView"
                    };
                    var fieldName     = field.Name + ": ";
                    var fieldTypeName = field.FieldType.Name;
                    fieldView.Add(new Label(fieldName));
                    fieldView.Add(new Label(fieldTypeName));
                    fieldViewContainerTooltip.Append(fieldName + fieldTypeName);
                    i++;
                    if (i < nbFields)
                    {
                        fieldViewContainerTooltip.Append('\n');
                    }
                    ExpandedContainer.Add(fieldView);
                }
            }
            else
            {
                ExpandedButton.style.display = DisplayStyle.None;
            }

            var deleteComponentButton = new Button {
                name = "deleteComponentIcon"
            };

            deleteComponentButton.clickable.clickedWithEventInfo += onDeleteComponent;
            ExpandableRowTitleContainer.Insert(0, deleteComponentButton);

            var componentContainer = new VisualElement {
                name = "rowFieldContainer"
            };

            string componentNamespace = component.TypeHandle.GetMetadata(stencil).Namespace;
            string componentName      = component.TypeHandle.ToTypeSyntax(stencil).ToString().Replace(componentNamespace + ".", "");

            userData = $"{GraphElementModel}/{componentName}";

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

            var componentPill = new ComponentPill(component, componentName, fieldViewContainerTooltip.ToString());

            rowPillContainer.Add(componentPill);

            componentContainer.Add(rowPillContainer);

            var usageField = new Toggle("Subtract")
            {
                value = component.Subtract
            };

            usageField.AddToClassList("usage");
            usageField.RegisterValueChangedCallback(onUsageChanged);
            componentContainer.Add(usageField);

            ExpandableRowTitleContainer.Add(componentContainer);

            capabilities |= Capabilities.Selectable | Capabilities.Deletable;

            var expandedRowName = $"{ComponentQueriesRow.BlackboardEcsProviderTypeName}/{typeof(ComponentsSubSection).Name}/{componentQueryDeclarationModel}/{componentName}";

            if (store.GetState().EditorDataModel.ShouldExpandBlackboardRowUponCreation(expandedRowName))
            {
                Expanded = true;
            }

            OnExpanded = e => Store.GetState().EditorDataModel?.ExpandBlackboardRowsUponCreation(new[] { expandedRowName }, e);

            this.AddManipulator(new ContextualMenuManipulator(OnContextualMenuEvent));
        }
        public void Initialize(AbstractMaterialNode inNode, PreviewManager previewManager, IEdgeConnectorListener connectorListener)
        {
            AddStyleSheetPath("Styles/MaterialNodeView");
            AddToClassList("MaterialNode");

            if (inNode == null)
            {
                return;
            }

            var contents = this.Q("contents");

            m_ConnectorListener = connectorListener;
            node           = inNode;
            persistenceKey = node.guid.ToString();
            UpdateTitle();

            // Add controls container
            var controlsContainer = new VisualElement {
                name = "controls"
            };

            {
                m_ControlsDivider = new VisualElement {
                    name = "divider"
                };
                m_ControlsDivider.AddToClassList("horizontal");
                controlsContainer.Add(m_ControlsDivider);
                m_ControlItems = new VisualElement {
                    name = "items"
                };
                controlsContainer.Add(m_ControlItems);

                // Instantiate control views from node
                foreach (var propertyInfo in node.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
                {
                    foreach (IControlAttribute attribute in propertyInfo.GetCustomAttributes(typeof(IControlAttribute), false))
                    {
                        m_ControlItems.Add(attribute.InstantiateControl(node, propertyInfo));
                    }
                }
            }
            if (m_ControlItems.childCount > 0)
            {
                contents.Add(controlsContainer);
            }

            if (node.hasPreview)
            {
                // Add actual preview which floats on top of the node
                m_PreviewContainer = new VisualElement
                {
                    name            = "previewContainer",
                    clippingOptions = ClippingOptions.ClipAndCacheContents,
                    pickingMode     = PickingMode.Ignore
                };
                m_PreviewImage = new Image
                {
                    name        = "preview",
                    pickingMode = PickingMode.Ignore,
                    image       = Texture2D.whiteTexture,
                };
                {
                    // Add preview collapse button on top of preview
                    var collapsePreviewButton = new VisualElement {
                        name = "collapse"
                    };
                    collapsePreviewButton.Add(new VisualElement {
                        name = "icon"
                    });
                    collapsePreviewButton.AddManipulator(new Clickable(() =>
                    {
                        node.owner.owner.RegisterCompleteObjectUndo("Collapse Preview");
                        UpdatePreviewExpandedState(false);
                    }));
                    m_PreviewImage.Add(collapsePreviewButton);
                }
                m_PreviewContainer.Add(m_PreviewImage);

                // Hook up preview image to preview manager
                m_PreviewRenderData = previewManager.GetPreview(inNode);
                m_PreviewRenderData.onPreviewChanged += UpdatePreviewTexture;
                UpdatePreviewTexture();

                // Add fake preview which pads out the node to provide space for the floating preview
                m_PreviewFiller = new VisualElement {
                    name = "previewFiller"
                };
                m_PreviewFiller.AddToClassList("expanded");
                {
                    var previewDivider = new VisualElement {
                        name = "divider"
                    };
                    previewDivider.AddToClassList("horizontal");
                    m_PreviewFiller.Add(previewDivider);

                    var expandPreviewButton = new VisualElement {
                        name = "expand"
                    };
                    expandPreviewButton.Add(new VisualElement {
                        name = "icon"
                    });
                    expandPreviewButton.AddManipulator(new Clickable(() =>
                    {
                        node.owner.owner.RegisterCompleteObjectUndo("Expand Preview");
                        UpdatePreviewExpandedState(true);
                    }));
                    m_PreviewFiller.Add(expandPreviewButton);
                }
                contents.Add(m_PreviewFiller);

                UpdatePreviewExpandedState(node.previewExpanded);
            }

            // Add port input container, which acts as a pixel cache for all port inputs
            m_PortInputContainer = new VisualElement
            {
                name            = "portInputContainer",
                clippingOptions = ClippingOptions.ClipAndCacheContents,
                pickingMode     = PickingMode.Ignore
            };
            Add(m_PortInputContainer);

            AddSlots(node.GetSlots <MaterialSlot>());
            UpdatePortInputs();
            base.expanded = node.drawState.expanded;
            RefreshExpandedState(); //This should not be needed. GraphView needs to improve the extension api here
            UpdatePortInputVisibilities();

            SetPosition(new Rect(node.drawState.position.x, node.drawState.position.y, 0, 0));

            if (node is SubGraphNode)
            {
                RegisterCallback <MouseDownEvent>(OnSubGraphDoubleClick);
            }

            var masterNode = node as IMasterNode;

            if (masterNode != null)
            {
                if (!masterNode.IsPipelineCompatible(RenderPipelineManager.currentPipeline))
                {
                    IconBadge wrongPipeline = IconBadge.CreateError("The current render pipeline is not compatible with this node preview.");
                    Add(wrongPipeline);
                    VisualElement title = this.Q("title");
                    wrongPipeline.AttachTo(title, SpriteAlignment.LeftCenter);
                }
            }

            m_PortInputContainer.SendToBack();

            // Remove this after updated to the correct API call has landed in trunk. ------------
            VisualElement m_TitleContainer;
            VisualElement m_ButtonContainer;

            m_TitleContainer = this.Q("title");
            // -----------------------------------------------------------------------------------

            var settings = node as IHasSettings;

            if (settings != null)
            {
                m_NodeSettingsView         = new NodeSettingsView();
                m_NodeSettingsView.visible = false;

                Add(m_NodeSettingsView);

                m_SettingsButton = new VisualElement {
                    name = "settings-button"
                };
                m_SettingsButton.Add(new VisualElement {
                    name = "icon"
                });

                m_Settings = settings.CreateSettingsElement();

                m_SettingsButton.AddManipulator(new Clickable(() =>
                {
                    UpdateSettingsExpandedState();
                }));

                // Remove this after updated to the correct API call has landed in trunk. ------------
                m_ButtonContainer = new VisualElement {
                    name = "button-container"
                };
                m_ButtonContainer.style.flexDirection = StyleValue <FlexDirection> .Create(FlexDirection.Row);

                m_ButtonContainer.Add(m_SettingsButton);
                m_ButtonContainer.Add(m_CollapseButton);
                m_TitleContainer.Add(m_ButtonContainer);
                // -----------------------------------------------------------------------------------
                //titleButtonContainer.Add(m_SettingsButton);
                //titleButtonContainer.Add(m_CollapseButton);

                RegisterCallback <GeometryChangedEvent>(OnGeometryChanged);
            }
        }
Example #16
0
        private void RenderRecordings()
        {
            if (!recordingPaths.Any())
            {
                recordingPaths = GetAllRecordingAssetPaths();
            }

            recordingContainer = new VisualElement();
            for (int i = 0; i < recordingPaths.Count; i++)
            {
                string recordingFilePath = recordingPaths[i];
                string filename          = recordingFilePath.Substring($"{AutomatedQARuntimeSettings.RecordingFolderNameWithAssetPath}".Length + 1);

                if (!string.IsNullOrEmpty(searchFilterText))
                {
                    if (!filename.Contains(searchFilterText))
                    {
                        continue;
                    }
                }

                VisualElement row = new VisualElement();
                if (renameFile == recordingFilePath)
                {
                    RecordingRenameView(recordingFilePath);
                }
                else
                {
                    VisualElement recordingRow = new VisualElement();
                    recordingRow.AddToClassList("item-row");
                    if (i % 2 == 0)
                    {
                        recordingRow.AddToClassList("even");
                    }
                    if (firstRecordingListedIsBrandNew)
                    {
                        firstRecordingListedIsBrandNew = false;
                        recordingRow.AddToClassList("item-row-new");
                    }

                    Button playButton = new Button()
                    {
                        text = "▸"
                    };
                    playButton.clickable.clicked += () => {
                        if (!RecordingInputModule.isWorkInProgress)
                        {
                            renderStopButton = true;
                            PlayRecording(recordingFilePath);
                            SetUpView();
                            WaitForModuleToBeReady();
                        }
                    };
                    playButton.tooltip = "Play recording";
                    playButton.AddToClassList("small-button");
                    playButton.AddToClassList("play-button");
                    recordingRow.Add(playButton);

                    Button renameButton = new Button()
                    {
                        text = "✎"
                    };
                    renameButton.clickable.clicked += () => {
                        renameFile = recordingFilePath;
                        SetUpView();
                    };
                    renameButton.tooltip = "Rename recording file";
                    renameButton.AddToClassList("small-button");
                    renameButton.AddToClassList("rename-button");
                    recordingRow.Add(renameButton);

                    Button findButton = new Button()
                    {
                        text = "↯"
                    };
                    findButton.clickable.clicked += () => {
                        Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(recordingFilePath);
                    };
                    findButton.tooltip = "Find/Highlight recording file in project window.";
                    findButton.AddToClassList("small-button");
                    findButton.AddToClassList("find-button");
                    recordingRow.Add(findButton);

                    Label label = new Label();
                    label.AddToClassList("recording-label");
                    label.text = filename;
                    recordingRow.Add(label);

                    recordingContainer.Add(recordingRow);
                }
            }
            root.Add(recordingContainer);
        }
Example #17
0
        void RenderElements()
        {
            VisualElement buttonsRow = new VisualElement()
            {
                style =
                {
                    flexDirection = FlexDirection.Row,
                    flexShrink    =                0f,
                    alignContent  = Align.Center
                }
            };

            buttonsRow.AddToClassList("buttons-row");

            if (!renderStopButton && !RecordingInputModule.isWorkInProgress)
            {
                Button saveButton = new Button()
                {
                    text = "Record", style = { flexGrow = 1, height = 30 }
                };
                saveButton.clickable.clicked += () => { StartRecording(); };
                saveButton.AddToClassList("button");
                buttonsRow.Add(saveButton);

                Button crawlButton = new Button()
                {
                    text = "Crawl", style = { flexGrow = 1, height = 30 }
                };
                crawlButton.clickable.clicked += () => { StartCrawl(); };
                crawlButton.AddToClassList("button");
                buttonsRow.Add(crawlButton);
            }
            else
            {
                stateLabel      = new Label();
                stateLabel.text = "●";
                stateLabel.AddToClassList("state-label");
                stateLabel.AddToClassList("red");
                buttonsRow.Add(stateLabel);
                Button stopButton = new Button()
                {
                    text = "Stop", style = { flexGrow = 1, height = 30 }
                };
                stopButton.clickable.clicked += () => { StopRecording(); };
                stopButton.AddToClassList("button");
                buttonsRow.Add(stopButton);
            }

            if (ReportingManager.DoesReportExist(ReportingManager.ReportType.Html))
            {
                Button reportButton = new Button()
                {
                    text = "☰ Show Report", style = { flexGrow = 1, height = 30 }
                };
                reportButton.clickable.clicked += () => { ShowHtmlReport(); };
                reportButton.AddToClassList("button");
                buttonsRow.Add(reportButton);
            }

            root.Add(buttonsRow);

            Label label = new Label();

            label.text = "- Recording asset path -";
            label.AddToClassList("center");
            root.Add(label);

            Label val = new Label()
            {
                style =
                {
                    marginBottom = 10
                }
            };

            val.text = AutomatedQARuntimeSettings.RecordingFolderNameWithAssetPath;
            val.AddToClassList("center");
            root.Add(val);

            VisualElement refreshRow = new VisualElement()
            {
                style =
                {
                    flexDirection = FlexDirection.Row,
                    flexShrink    =                0f,
                    alignContent  = Align.Center
                }
            };

            Label filterLabel = new Label();

            filterLabel.text = "Filter: ";
            filterLabel.AddToClassList("filter-label");
            refreshRow.Add(filterLabel);

            searchFilterText = string.Empty;
            TextField newName = new TextField();

            newName.AddToClassList("filter-field");
            newName.RegisterValueChangedCallback(x =>
            {
                searchFilterText = x.newValue;
                root.Remove(recordingContainer);
                RenderRecordings();
            });
            refreshRow.Add(newName);

            Button refreshListButton = new Button()
            {
                text = "↻", tooltip = "Refresh recordings list"
            };

            refreshListButton.clickable.clicked += () =>
            {
                newName.value  = string.Empty;
                recordingPaths = GetAllRecordingAssetPaths();
                recordingPaths.Sort();
                SetUpView();
            };
            refreshListButton.AddToClassList("refresh-button");
            refreshRow.Add(refreshListButton);
            root.Add(refreshRow);
        }
        VisualElement GetSettings(GraphData graphData, Action onChange)
        {
            var element = new VisualElement()
            {
                name = "graphSettings"
            };

            if (graphData.isSubGraph)
            {
                return(element);
            }

            void RegisterActionToUndo(string actionName)
            {
                graphData.owner.RegisterCompleteObjectUndo(actionName);
            }

            // Add Label
            var targetSettingsLabel = new Label("Target Settings");

            targetSettingsLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
            element.Add(new PropertyRow(targetSettingsLabel));

            var targetNameList = graphData.validTargets.Select(x => x.displayName);

            element.Add(new PropertyRow(new Label("Targets")), (row) =>
            {
                row.Add(new IMGUIContainer(() => {
                    EditorGUI.BeginChangeCheck();
                    var activeTargetBitmask = EditorGUILayout.MaskField(graphData.activeTargetBitmask, targetNameList.ToArray(), GUILayout.Width(100f));
                    if (EditorGUI.EndChangeCheck())
                    {
                        RegisterActionToUndo("Change active Targets");
                        graphData.activeTargetBitmask = activeTargetBitmask;
                        graphData.UpdateActiveTargets();
                        m_postChangeTargetSettingsCallback();
                    }
                }));
            });


            // Initialize from the active targets whenever user changes them
            // Is there a way to retain order even with that?
            if (userOrderedTargetNameList.Count != graphData.activeTargets.Count())
            {
                var activeTargetNames = graphData.activeTargets.Select(x => x.displayName);
                userOrderedTargetNameList = activeTargetNames.ToList();
            }

            var reorderableTextListView = new ReorderableListView <string>(userOrderedTargetNameList);

            reorderableTextListView.OnListReorderedCallback += list =>
            {
                userOrderedTargetNameList = (List <string>)list;
                onChange();
            };
            element.Add(reorderableTextListView);

            // Iterate active TargetImplementations
            foreach (var targetName in reorderableTextListView.TextList)
            {
                // Ensure enabled state is being tracked and get value
                bool foldoutActive = true;
                if (!m_TargetFoldouts.TryGetValue(targetName, out foldoutActive))
                {
                    m_TargetFoldouts.Add(targetName, foldoutActive);
                }

                // Create foldout
                var foldout = new Foldout()
                {
                    text = targetName, value = foldoutActive, name = "foldout"
                };
                element.Add(foldout);
                foldout.AddToClassList("MainFoldout");
                foldout.RegisterValueChangedCallback(evt =>
                {
                    // Update foldout value and rebuild
                    m_TargetFoldouts[targetName] = evt.newValue;
                    foldout.value = evt.newValue;
                    onChange();
                });

                if (foldout.value)
                {
                    var target = graphData.validTargets.Find(x => x.displayName == targetName);
                    // Get settings for Target
                    var context = new TargetPropertyGUIContext();
                    target.GetPropertiesGUI(ref context, onChange, RegisterActionToUndo);
                    element.Add(context);
                }
            }

            return(element);
        }
        private VisualElement CreateExportSettingsView()
        {
            var settingsContainer = new VisualElement()
            {
                name = Styles.exportSettings
            };

            settingsContainer.AddToClassList(Styles.exportSettings);

            var exportTypes = new List <ExportTextureType>()
            {
                ExportTextureType.Texture2D,
                ExportTextureType.Texture3D
            };

            var exportType = new PopupField <ExportTextureType>(exportTypes, exportTypes[0])
            {
                name  = Styles.exportType,
                label = "Texture Type"
            };

            exportType.RegisterCallback <ChangeEvent <ExportTextureType> >(
                (evt) =>
            {
                if (evt.newValue == ExportTextureType.Texture2D)
                {
                    m_exportSettings.Remove(m_exportDims3D);
                    m_exportSettings.Insert(1, m_exportDims2D);
                }
                else if (evt.newValue == ExportTextureType.Texture3D)
                {
                    m_exportSettings.Remove(m_exportDims2D);
                    m_exportSettings.Insert(1, m_exportDims3D);
                }
            }
                );

            var dimensionsField2D = new Vector2IntField()
            {
                name  = Styles.exportDims2D,
                label = "Dimensions",
                value = new Vector2Int(512, 512)
            };
            var dimensionsField3D = new Vector3IntField()
            {
                name  = Styles.exportDims3D,
                label = "Dimensions",
                value = new Vector3Int(64, 64, 64)
            };

            var m_listOfFormats = new List <GraphicsFormat>()
            {
                // GraphicsFormat.R8_UNorm,
                // GraphicsFormat.R8_SNorm,
                GraphicsFormat.R16_UNorm,
                // GraphicsFormat.R16_SNorm,
                GraphicsFormat.R16_SFloat,
                // GraphicsFormat.R32_SFloat,
            };

            var exportFormat = new PopupField <GraphicsFormat>(m_listOfFormats, GraphicsFormat.R16_UNorm)
            {
                name  = Styles.exportFormat,
                label = "Texture Format"
            };

            settingsContainer.Add(exportType);
            settingsContainer.Add(dimensionsField2D);
            settingsContainer.Add(exportFormat);

            m_exportSettings = settingsContainer;
            m_exportType     = exportType;
            m_exportDims2D   = dimensionsField2D;
            m_exportDims3D   = dimensionsField3D;
            m_exportFormat   = exportFormat;

            exportType.value = ExportTextureType.Texture2D;

            return(settingsContainer);
        }
Example #20
0
        private void InitializeButtons()
        {
            m_DisableIfCompiling = new ButtonDisableCondition(() => m_Application.isCompiling,
                                                              L10n.Tr("You need to wait until the compilation is finished to perform this action."));
            m_DisableIfInstallOrUninstallInProgress = new ButtonDisableCondition(() => m_PackageDatabase.isInstallOrUninstallInProgress,
                                                                                 L10n.Tr("You need to wait until other install or uninstall operations are finished to perform this action."));
            m_DisableIfNoNetwork = new ButtonDisableCondition(() => !m_Application.isInternetReachable,
                                                              L10n.Tr("You need to restore your network connection to perform this action."));

            m_UnlockButton           = new PackageUnlockButton(m_PageManager);
            m_UnlockButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_UnlockButton.element);

            m_AddButton = new PackageAddButton(m_Application, m_PackageDatabase);
            m_AddButton.SetGlobalDisableConditions(m_DisableIfInstallOrUninstallInProgress, m_DisableIfCompiling);
            m_AddButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_AddButton.element);

            m_UpdateButton = new PackageUpdateButton(m_Application, m_PackageDatabase, m_PageManager);
            m_UpdateButton.SetGlobalDisableConditions(m_DisableIfInstallOrUninstallInProgress, m_DisableIfCompiling);
            m_UpdateButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_UpdateButton.element);

            m_GitUpdateButton = new PackageGitUpdateButton(m_PackageDatabase);
            m_GitUpdateButton.SetGlobalDisableConditions(m_DisableIfInstallOrUninstallInProgress, m_DisableIfCompiling);
            m_GitUpdateButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_GitUpdateButton.element);

            m_RemoveButton = new PackageRemoveButton(m_Application, m_PackageManagerPrefs, m_PackageDatabase, m_PageManager);
            m_RemoveButton.SetGlobalDisableConditions(m_DisableIfInstallOrUninstallInProgress, m_DisableIfCompiling);
            m_RemoveButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_RemoveButton.element);

            m_RemoveCustomButton = new PackageRemoveCustomButton(m_Application, m_PackageDatabase, m_PageManager);
            m_RemoveCustomButton.SetGlobalDisableConditions(m_DisableIfInstallOrUninstallInProgress, m_DisableIfCompiling);
            m_RemoveCustomButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_RemoveCustomButton.element);

            m_ResetButton = new PackageResetButton(m_Application, m_PackageDatabase, m_PageManager);
            m_ResetButton.SetGlobalDisableConditions(m_DisableIfInstallOrUninstallInProgress, m_DisableIfCompiling);
            m_ResetButton.onAction += RefreshBuiltInButtons;
            m_ResetButton.element.SetIcon("customizedIcon");
            m_BuiltInActions.Add(m_ResetButton.element);

            m_ImportButton = new PackageImportButton(m_AssetStoreDownloadManager, m_PackageDatabase);
            m_ImportButton.SetGlobalDisableConditions(m_DisableIfCompiling);
            m_ImportButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_ImportButton.element);

            m_RedownloadButton = new PackageRedownloadButton(m_AssetStoreDownloadManager, m_AssetStoreCache, m_PackageDatabase);
            m_RedownloadButton.SetGlobalDisableConditions(m_DisableIfCompiling);
            m_RedownloadButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_RedownloadButton.element);

            m_DownloadButton = new PackageDownloadButton(m_AssetStoreDownloadManager, m_AssetStoreCache, m_PackageDatabase);
            m_DownloadButton.SetGlobalDisableConditions(m_DisableIfNoNetwork, m_DisableIfCompiling);
            m_DownloadButton.onAction += Refresh;
            m_BuiltInActions.Add(m_DownloadButton.element);

            m_DownloadUpdateButton = new PackageDownloadUpdateButton(m_AssetStoreDownloadManager, m_AssetStoreCache, m_PackageDatabase);
            m_DownloadUpdateButton.SetGlobalDisableConditions(m_DisableIfNoNetwork, m_DisableIfCompiling);
            m_DownloadUpdateButton.onAction += Refresh;
            m_BuiltInActions.Add(m_DownloadUpdateButton.element);

            m_DowngradeButton = new PackageDowngradeButton(m_AssetStoreDownloadManager, m_AssetStoreCache, m_PackageDatabase);
            m_DowngradeButton.SetGlobalDisableConditions(m_DisableIfNoNetwork, m_DisableIfCompiling);
            m_DowngradeButton.onAction += Refresh;
            m_BuiltInActions.Add(m_DowngradeButton.element);

            m_SignInButton = new PackageSignInButton(m_UnityConnectProxy);
            m_SignInButton.SetGlobalDisableConditions(m_DisableIfNoNetwork);
            m_SignInButton.onAction += RefreshBuiltInButtons;
            m_BuiltInActions.Add(m_SignInButton.element);

            // Since pause, resume, cancel buttons are only used to control the download progress, we want to put them in the progress container instead
            m_CancelButton = new PackageCancelDownloadButton(m_AssetStoreDownloadManager, m_PackageDatabase);
            m_CancelButton.SetGlobalDisableConditions(m_DisableIfCompiling);
            m_CancelButton.onAction += Refresh;
            m_ProgressContainer.Add(m_CancelButton.element);

            m_PauseButton = new PackagePauseDownloadButton(m_AssetStoreDownloadManager, m_PackageDatabase);
            m_PauseButton.SetGlobalDisableConditions(m_DisableIfCompiling);
            m_PauseButton.onAction += RefreshProgressControlButtons;
            m_ProgressContainer.Add(m_PauseButton.element);

            m_ResumeButton = new PackageResumeDownloadButton(m_AssetStoreDownloadManager, m_PackageDatabase);
            m_ResumeButton.SetGlobalDisableConditions(m_DisableIfNoNetwork, m_DisableIfCompiling);
            m_ResumeButton.onAction += RefreshProgressControlButtons;
            m_ProgressContainer.Add(m_ResumeButton.element);
        }
Example #21
0
    public void OnEnable()
    {
        m_GraphView = new AssetGraphView {
            name = "Asset Dependency Graph",
        };

        #region Toolbar
        var toolbar = new VisualElement {
            style =
            {
                flexDirection   = FlexDirection.Row,
                flexGrow        =                 0,
                backgroundColor = new Color(0.25f, 0.25f, 0.25f, 0.75f)
            }
        };

        var options = new VisualElement {
            style = { alignContent = Align.Center }
        };

        toolbar.Add(options);
        toolbar.Add(new Button(ExploreAsset)
        {
            text = "Explore Asset",
        });
        toolbar.Add(new Button(ClearGraph)
        {
            text = "Clear"
        });
        toolbar.Add(new Button(ResetAllGroups)
        {
            text = "Reset"
        });

        codeToggle       = new Toggle();
        codeToggle.text  = "Hide Scripts";
        codeToggle.value = true;
        codeToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(codeToggle);

        MaterialToggle       = new Toggle();
        MaterialToggle.text  = "Hide Materials";
        MaterialToggle.value = false;
        MaterialToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(MaterialToggle);

        textureToggle       = new Toggle();
        textureToggle.text  = "Hide Textures";
        textureToggle.value = true;
        textureToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(textureToggle);

        shaderToggle       = new Toggle();
        shaderToggle.text  = "Hide Shaders";
        shaderToggle.value = true;
        shaderToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(shaderToggle);

        audioClipToggle       = new Toggle();
        audioClipToggle.text  = "Hide Audioclips";
        audioClipToggle.value = false;
        audioClipToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(audioClipToggle);

        animationClipToggle       = new Toggle();
        animationClipToggle.text  = "Hide Animationclips";
        animationClipToggle.value = false;
        animationClipToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(animationClipToggle);

        CustomToggle       = new Toggle();
        CustomToggle.text  = "Hide Custom";
        CustomToggle.value = true;
        CustomToggle.RegisterValueChangedCallback(x => {
            FilterAssetGroups();
        });
        toolbar.Add(CustomToggle);

        var ts = new ToolbarSearchField();
        ts.RegisterValueChangedCallback(x => {
            if (string.IsNullOrEmpty(x.newValue))
            {
                m_GraphView.FrameAll();
                return;
            }

            m_GraphView.ClearSelection();
            // m_GraphView.graphElements.ForEach(y => { // BROKEN, Case 1268337
            m_GraphView.graphElements.ToList().ForEach(y => {
                if (y is Node node && y.title.IndexOf(x.newValue, System.StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    m_GraphView.AddToSelection(node);
                }
            });

            m_GraphView.FrameSelection();
        });
        toolbar.Add(ts);

        AlignmentToggle       = new Toggle();
        AlignmentToggle.text  = "Horizontal Layout";
        AlignmentToggle.value = false;
        AlignmentToggle.RegisterValueChangedCallback(x => {
            ResetAllGroups();
        });
        toolbar.Add(AlignmentToggle);
        #endregion

#if !UNITY_2019_1_OR_NEWER
        rootVisualElement = this.GetRootVisualContainer();
#endif
        rootVisualElement.Add(toolbar);
        rootVisualElement.Add(m_GraphView);
        m_GraphView.StretchToParentSize();
        toolbar.BringToFront();
    }
        public void Initialize(AbstractMaterialNode inNode, PreviewManager previewManager, IEdgeConnectorListener connectorListener)
        {
            AddStyleSheetPath("Styles/MaterialNodeView");
            AddToClassList("MaterialNode");

            if (inNode == null)
            {
                return;
            }

            var contents = this.Q("contents");

            m_ConnectorListener = connectorListener;
            node           = inNode;
            persistenceKey = node.guid.ToString();
            UpdateTitle();

            // Add controls container
            var controlsContainer = new VisualElement {
                name = "controls"
            };

            {
                m_ControlsDivider = new VisualElement {
                    name = "divider"
                };
                m_ControlsDivider.AddToClassList("horizontal");
                controlsContainer.Add(m_ControlsDivider);
                m_ControlItems = new VisualElement {
                    name = "items"
                };
                controlsContainer.Add(m_ControlItems);

                // Instantiate control views from node
                foreach (var propertyInfo in node.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
                {
                    foreach (IControlAttribute attribute in propertyInfo.GetCustomAttributes(typeof(IControlAttribute), false))
                    {
                        m_ControlItems.Add(attribute.InstantiateControl(node, propertyInfo));
                    }
                }
            }
            if (m_ControlItems.childCount > 0)
            {
                contents.Add(controlsContainer);
            }

            if (node.hasPreview)
            {
                // Add actual preview which floats on top of the node
                m_PreviewContainer = new VisualElement
                {
                    name            = "previewContainer",
                    clippingOptions = ClippingOptions.ClipAndCacheContents,
                    pickingMode     = PickingMode.Ignore
                };
                m_PreviewImage = new Image
                {
                    name        = "preview",
                    pickingMode = PickingMode.Ignore,
                    image       = Texture2D.whiteTexture,
                };
                {
                    // Add preview collapse button on top of preview
                    var collapsePreviewButton = new VisualElement {
                        name = "collapse"
                    };
                    collapsePreviewButton.Add(new VisualElement {
                        name = "icon"
                    });
                    collapsePreviewButton.AddManipulator(new Clickable(() =>
                    {
                        node.owner.owner.RegisterCompleteObjectUndo("Collapse Preview");
                        UpdatePreviewExpandedState(false);
                    }));
                    m_PreviewImage.Add(collapsePreviewButton);
                }
                m_PreviewContainer.Add(m_PreviewImage);

                // Hook up preview image to preview manager
                m_PreviewRenderData = previewManager.GetPreview(inNode);
                m_PreviewRenderData.onPreviewChanged += UpdatePreviewTexture;
                UpdatePreviewTexture();

                // Add fake preview which pads out the node to provide space for the floating preview
                m_PreviewFiller = new VisualElement {
                    name = "previewFiller"
                };
                m_PreviewFiller.AddToClassList("expanded");
                {
                    var previewDivider = new VisualElement {
                        name = "divider"
                    };
                    previewDivider.AddToClassList("horizontal");
                    m_PreviewFiller.Add(previewDivider);

                    var expandPreviewButton = new VisualElement {
                        name = "expand"
                    };
                    expandPreviewButton.Add(new VisualElement {
                        name = "icon"
                    });
                    expandPreviewButton.AddManipulator(new Clickable(() =>
                    {
                        node.owner.owner.RegisterCompleteObjectUndo("Expand Preview");
                        UpdatePreviewExpandedState(true);
                    }));
                    m_PreviewFiller.Add(expandPreviewButton);
                }
                contents.Add(m_PreviewFiller);

                UpdatePreviewExpandedState(node.previewExpanded);
            }

            // Add port input container, which acts as a pixel cache for all port inputs
            m_PortInputContainer = new VisualElement
            {
                name            = "portInputContainer",
                clippingOptions = ClippingOptions.ClipAndCacheContents,
                pickingMode     = PickingMode.Ignore
            };
            Add(m_PortInputContainer);

            AddSlots(node.GetSlots <MaterialSlot>());
            UpdatePortInputs();
            base.expanded = node.drawState.expanded;
            RefreshExpandedState(); //This should not be needed. GraphView needs to improve the extension api here
            UpdatePortInputVisibilities();

            SetPosition(new Rect(node.drawState.position.x, node.drawState.position.y, 0, 0));

            /*if (node is PreviewNode)
             * {
             *  var resizeHandle = new Label { name = "resize", text = "" };
             *  resizeHandle.AddManipulator(new Draggable(OnResize));
             *  Add(resizeHandle);
             *  UpdateSize();
             * }*/

            m_PortInputContainer.SendToBack();
            if (node.hasPreview)
            {
                m_PreviewFiller.BringToFront();
            }
        }
Example #23
0
        public LogicGraphEditorView(LogicGraphEditorWindow editorWindow, LogicGraphEditorObject logicGraphEditorObject)
        {
            Debug.Log(logicGraphEditorObject.GetInstanceID());
            _editorWindow           = editorWindow;
            _logicGraphEditorObject = logicGraphEditorObject;
            _logicGraphEditorObject.Deserialized += LogicGraphEditorDataOnDeserialized;

            this.LoadAndAddStyleSheet("Styles/LogicGraphEditorView");

            var toolbar = new IMGUIContainer(() =>
            {
                GUILayout.BeginHorizontal(EditorStyles.toolbar);
                if (GUILayout.Button("Save Asset", EditorStyles.toolbarButton))
                {
                    saveRequested?.Invoke();
                }

                GUILayout.Space(6);
                if (GUILayout.Button("Show In Project", EditorStyles.toolbarButton))
                {
                    showInProjectRequested?.Invoke();
                }

                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            });

            Add(toolbar);

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

            {
                _graphView = new LogicGraphView(_logicGraphEditorObject)
                {
                    name = "GraphView",
//                    persistenceKey = "LogicGraphView",
                };

                _graphView.SetupZoom(0.05f, ContentZoomer.DefaultMaxScale);
                _graphView.AddManipulator(new ContentDragger());
                _graphView.AddManipulator(new SelectionDragger());
                _graphView.AddManipulator(new RectangleSelector());
                _graphView.AddManipulator(new ClickSelector());
                _graphView.RegisterCallback <KeyDownEvent>(KeyDown);
                content.Add(_graphView);

                _graphView.graphViewChanged = GraphViewChanged;
            }

            _searchWindowProvider = ScriptableObject.CreateInstance <SearchWindowProvider>();
            _searchWindowProvider.Initialize(editorWindow, this, _graphView);

            _edgeConnectorListener = new EdgeConnectorListener(this, _searchWindowProvider);

            _graphView.nodeCreationRequest = (c) =>
            {
                _searchWindowProvider.ConnectedLogicPort = null;
                SearchWindow.Open(new SearchWindowContext(c.screenMousePosition), _searchWindowProvider);
            };

            LoadElements();

            Add(content);
        }
Example #24
0
        public GraphEditorView(EditorWindow editorWindow, GraphData graph, MessageManager messageManager)
        {
            m_Graph          = graph;
            m_MessageManager = messageManager;
            styleSheets.Add(Resources.Load <StyleSheet>("Styles/GraphEditorView"));
            previewManager = new PreviewManager(graph, messageManager);

            string serializedToggle = EditorUserSettings.GetConfigValue(k_ToggleSettings);

            if (!string.IsNullOrEmpty(serializedToggle))
            {
                m_ToggleSettings = JsonUtility.FromJson <ToggleSettings>(serializedToggle);
            }

            string serializedWindowLayout = EditorUserSettings.GetConfigValue(k_FloatingWindowsLayoutKey);

            if (!string.IsNullOrEmpty(serializedWindowLayout))
            {
                m_FloatingWindowsLayout = JsonUtility.FromJson <FloatingWindowsLayout>(serializedWindowLayout);
            }
            else
            {
                m_FloatingWindowsLayout = new FloatingWindowsLayout
                {
                    blackboardLayout =
                    {
                        dockingTop       = true,
                        dockingLeft      = true,
                        verticalOffset   =              16,
                        horizontalOffset =              16,
                        size             = new Vector2(200, 400)
                    }
                };
            }

            if (m_FloatingWindowsLayout.masterPreviewSize.x > 0f && m_FloatingWindowsLayout.masterPreviewSize.y > 0f)
            {
                previewManager.ResizeMasterPreview(m_FloatingWindowsLayout.masterPreviewSize);
            }

            previewManager.RenderPreviews();
            var toolbar = new IMGUIContainer(() =>
            {
                GUILayout.BeginHorizontal(EditorStyles.toolbar);
                if (GUILayout.Button("Save Asset", EditorStyles.toolbarButton))
                {
                    if (saveRequested != null)
                    {
                        saveRequested();
                    }
                }
                GUILayout.Space(6);
                if (GUILayout.Button("Show In Project", EditorStyles.toolbarButton))
                {
                    if (showInProjectRequested != null)
                    {
                        showInProjectRequested();
                    }
                }

                GUILayout.FlexibleSpace();

                EditorGUI.BeginChangeCheck();
                m_ToggleSettings.isBlackboardVisible = GUILayout.Toggle(m_ToggleSettings.isBlackboardVisible, "Blackboard", EditorStyles.toolbarButton);

                GUILayout.Space(6);

                m_ToggleSettings.isPreviewVisible = GUILayout.Toggle(m_ToggleSettings.isPreviewVisible, "Main Preview", EditorStyles.toolbarButton);
                if (EditorGUI.EndChangeCheck())
                {
                    m_MasterPreviewView.visible             = m_ToggleSettings.isPreviewVisible;
                    m_BlackboardProvider.blackboard.visible = m_ToggleSettings.isBlackboardVisible;
                    string serializedToggleables            = JsonUtility.ToJson(m_ToggleSettings);
                    EditorUserSettings.SetConfigValue(k_ToggleSettings, serializedToggleables);
                }
                GUILayout.EndHorizontal();
            });

            Add(toolbar);

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

            {
                m_GraphView = new MaterialGraphView(graph)
                {
                    name = "GraphView", viewDataKey = "MaterialGraphView"
                };
                m_GraphView.SetupZoom(0.05f, ContentZoomer.DefaultMaxScale);
                m_GraphView.AddManipulator(new ContentDragger());
                m_GraphView.AddManipulator(new SelectionDragger());
                m_GraphView.AddManipulator(new RectangleSelector());
                m_GraphView.AddManipulator(new ClickSelector());
                m_GraphView.RegisterCallback <KeyDownEvent>(OnSpaceDown);
                m_GraphView.groupTitleChanged        = OnGroupTitleChanged;
                m_GraphView.elementsAddedToGroup     = OnElementsAddedToGroup;
                m_GraphView.elementsRemovedFromGroup = OnElementsRemovedFromGroup;
                content.Add(m_GraphView);

                m_BlackboardProvider = new BlackboardProvider(graph);
                m_GraphView.Add(m_BlackboardProvider.blackboard);

                // Initialize toggle settings if it doesnt exist.
                if (m_ToggleSettings == null)
                {
                    m_ToggleSettings = new ToggleSettings();
                }
                m_BlackboardProvider.blackboard.visible = m_ToggleSettings.isBlackboardVisible;

                m_MasterPreviewView = new MasterPreviewView(previewManager, graph)
                {
                    name = "masterPreview"
                };

                WindowDraggable masterPreviewViewDraggable = new WindowDraggable(null, this);
                m_MasterPreviewView.AddManipulator(masterPreviewViewDraggable);
                m_GraphView.Add(m_MasterPreviewView);

                //m_BlackboardProvider.onDragFinished += UpdateSerializedWindowLayout;
                //m_BlackboardProvider.onResizeFinished += UpdateSerializedWindowLayout;
                masterPreviewViewDraggable.OnDragFinished += UpdateSerializedWindowLayout;
                m_MasterPreviewView.previewResizeBorderFrame.OnResizeFinished += UpdateSerializedWindowLayout;
                m_MasterPreviewView.visible = m_ToggleSettings.isPreviewVisible;

                m_GraphView.graphViewChanged = GraphViewChanged;

                RegisterCallback <GeometryChangedEvent>(ApplySerializewindowLayouts);
            }

            m_SearchWindowProvider = ScriptableObject.CreateInstance <SearchWindowProvider>();
            m_SearchWindowProvider.Initialize(editorWindow, m_Graph, m_GraphView);
            m_GraphView.nodeCreationRequest = (c) =>
            {
                m_SearchWindowProvider.connectedPort = null;
                SearchWindow.Open(new SearchWindowContext(c.screenMousePosition), m_SearchWindowProvider);
            };

            m_EdgeConnectorListener = new EdgeConnectorListener(m_Graph, m_SearchWindowProvider);

            foreach (var graphGroup in graph.groups)
            {
                AddGroup(graphGroup);
            }

            foreach (var node in graph.GetNodes <AbstractMaterialNode>())
            {
                AddNode(node);
            }

            foreach (var edge in graph.edges)
            {
                AddEdge(edge);
            }

            Add(content);
        }
Example #25
0
        public override void OnActivate(string searchContext, VisualElement root)
        {
            var padRect = new VisualElement();
            int padding = 10;

            padRect.style.paddingBottom = padding;
            padRect.style.paddingLeft   = padding;
            padRect.style.paddingRight  = padding;
            padRect.style.paddingTop    = padding - 5;
            root.Add(padRect);

            var title = new Label("Notch Solution");

            title.style.fontSize = 15;
            title.style.unityFontStyleAndWeight = FontStyle.Bold;
            padRect.Add(title);

            var repo = new Label("https://github.com/5argon/NotchSolution");

            repo.style.paddingBottom           = 15;
            repo.style.unityFontStyleAndWeight = FontStyle.Bold;
            repo.RegisterCallback((MouseDownEvent ev) =>
            {
                System.Diagnostics.Process.Start("https://github.com/5argon/NotchSolution");
            });
            padRect.Add(repo);

            var colorField = new ColorField("Prefab mode overlay color");

            colorField.value = NotchSolutionUtility.PrefabModeOverlayColor;
            colorField.RegisterValueChangedCallback(ev =>
            {
                NotchSolutionUtility.PrefabModeOverlayColor = ev.newValue;
                NotchSimulator.UpdateAllMockups();
                NotchSimulator.UpdateSimulatorTargets();
            });
            padRect.Add(colorField);

            string shortcutString = ShortcutManager.instance.GetShortcutBinding(NotchSolutionShortcuts.switchNarrowestWidestShortcut).ToString();
            string text           = $"This feature allows you to press {shortcutString} to quick switch between 2 aspect ratio choices. Commonly I would often switch between the longest phone like LG G7 and widest device like an iPad as I design. The index is counted from the top choice where 0 equals Free Aspect.";

            var box     = new Box();
            var helpBox = new Label(text);

            helpBox.style.whiteSpace = WhiteSpace.Normal;
            box.style.paddingTop     = 5;
            box.style.paddingLeft    = 5;
            box.style.paddingRight   = 5;
            box.style.paddingBottom  = 2;
            box.style.marginTop      = 10;
            box.style.marginBottom   = 10;
            box.Add(helpBox);
            padRect.Add(box);

            //TODO : Reflect to `GameViewSizes.instance` and request all sizes to draw a nicer drop down menu instead of index number.

            var narrowest = new IntegerField("Narrowest aspect index");

            narrowest.value = NotchSolutionUtility.NarrowestAspectIndex;
            narrowest.RegisterValueChangedCallback(ev =>
            {
                narrowest.value = Mathf.Max(0, ev.newValue); //go to -1 and the game view crashes..
                NotchSolutionUtility.NarrowestAspectIndex = ev.newValue;
                NotchSimulator.UpdateAllMockups();
                NotchSimulator.UpdateSimulatorTargets();
            });
            padRect.Add(narrowest);

            var widest = new IntegerField("Widest aspect index");

            widest.value = NotchSolutionUtility.WidestAspectIndex;
            widest.RegisterValueChangedCallback(ev =>
            {
                widest.value = Mathf.Max(0, ev.newValue);
                NotchSolutionUtility.WidestAspectIndex = ev.newValue;
                NotchSimulator.UpdateAllMockups();
                NotchSimulator.UpdateSimulatorTargets();
            });
            padRect.Add(widest);
        }
Example #26
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);
            }
        private VisualElement CreateInboundRtpView(string id)
        {
            var root      = new VisualElement();
            var container = new VisualElement();

            root.Add(container);

            var inboundGraph = new InboundRTPStreamGraphView();

            m_parent.OnStats += (peer, report) =>
            {
                if (peer != m_peerConnection)
                {
                    return;
                }

                container.Clear();
                if (!report.TryGetValue(id, out var stats) ||
                    !(stats is RTCInboundRTPStreamStats inboundStats))
                {
                    container.Add(new Label($"no stats report about {RTCStatsType.InboundRtp}"));
                    return;
                }

                container.Add(new Label($"{nameof(inboundStats.Id)}: {inboundStats.Id}"));
                container.Add(new Label($"{nameof(inboundStats.Timestamp)}: {inboundStats.Timestamp}"));
                container.Add(new Label($"{nameof(inboundStats.ssrc)}: {inboundStats.ssrc}"));
                container.Add(new Label($"{nameof(inboundStats.estimatedPlayoutTimestamp)}: {inboundStats.estimatedPlayoutTimestamp}"));
                container.Add(new Label($"{nameof(inboundStats.isRemote)}: {inboundStats.isRemote}"));
                container.Add(new Label($"{nameof(inboundStats.mediaType)}: {inboundStats.mediaType}"));
                container.Add(new Label($"{nameof(inboundStats.kind)}: {inboundStats.kind}"));
                container.Add(new Label($"{nameof(inboundStats.trackId)}: {inboundStats.trackId}"));
                container.Add(new Label($"{nameof(inboundStats.transportId)}: {inboundStats.transportId}"));
                container.Add(new Label($"{nameof(inboundStats.codecId)}: {inboundStats.codecId}"));
                container.Add(new Label($"{nameof(inboundStats.firCount)}: {inboundStats.firCount}"));
                container.Add(new Label($"{nameof(inboundStats.pliCount)}: {inboundStats.pliCount}"));
                container.Add(new Label($"{nameof(inboundStats.nackCount)}: {inboundStats.nackCount}"));
                container.Add(new Label($"{nameof(inboundStats.sliCount)}: {inboundStats.sliCount}"));
                container.Add(new Label($"{nameof(inboundStats.qpSum)}: {inboundStats.qpSum}"));
                container.Add(new Label($"{nameof(inboundStats.packetsReceived)}: {inboundStats.packetsReceived}"));
                container.Add(new Label($"{nameof(inboundStats.bytesReceived)}: {inboundStats.bytesReceived}"));
                container.Add(
                    new Label($"{nameof(inboundStats.headerBytesReceived)}: {inboundStats.headerBytesReceived}"));
                container.Add(new Label($"{nameof(inboundStats.packetsLost)}: {inboundStats.packetsLost}"));
                container.Add(new Label(
                                  $"{nameof(inboundStats.lastPacketReceivedTimestamp)}: {inboundStats.lastPacketReceivedTimestamp}"));
                container.Add(new Label($"{nameof(inboundStats.jitter)}: {inboundStats.jitter}"));
                container.Add(new Label($"{nameof(inboundStats.roundTripTime)}: {inboundStats.roundTripTime}"));
                container.Add(new Label($"{nameof(inboundStats.packetsDiscarded)}: {inboundStats.packetsDiscarded}"));
                container.Add(new Label($"{nameof(inboundStats.packetsRepaired)}: {inboundStats.packetsRepaired}"));
                container.Add(new Label($"{nameof(inboundStats.burstPacketsLost)}: {inboundStats.burstPacketsLost}"));
                container.Add(
                    new Label($"{nameof(inboundStats.burstPacketsDiscarded)}: {inboundStats.burstPacketsDiscarded}"));
                container.Add(new Label($"{nameof(inboundStats.burstLossCount)}: {inboundStats.burstLossCount}"));
                container.Add(new Label($"{nameof(inboundStats.burstDiscardCount)}: {inboundStats.burstDiscardCount}"));
                container.Add(new Label($"{nameof(inboundStats.burstLossRate)}: {inboundStats.burstLossRate}"));
                container.Add(new Label($"{nameof(inboundStats.burstDiscardRate)}: {inboundStats.burstDiscardRate}"));
                container.Add(new Label($"{nameof(inboundStats.gapLossRate)}: {inboundStats.gapLossRate}"));
                container.Add(new Label($"{nameof(inboundStats.gapDiscardRate)}: {inboundStats.gapDiscardRate}"));
                container.Add(new Label($"{nameof(inboundStats.framesDecoded)}: {inboundStats.framesDecoded}"));
                container.Add(new Label($"{nameof(inboundStats.keyFramesDecoded)}: {inboundStats.keyFramesDecoded}"));
                container.Add(new Label($"{nameof(inboundStats.totalDecodeTime)}: {inboundStats.totalDecodeTime}"));
                container.Add(new Label($"{nameof(inboundStats.contentType)}: {inboundStats.contentType}"));
                container.Add(
                    new Label($"{nameof(inboundStats.decoderImplementation)}: {inboundStats.decoderImplementation}"));

                inboundGraph.AddInput(inboundStats);
            };

            root.Add(inboundGraph.Create());

            return(root);
        }
Example #28
0
        public BoxModelView()
        {
            AddToClassList("box-model-view");
            visible = false;

            m_OverlayPainter = new HighlightOverlayPainter();

            m_Container = new VisualElement();
            m_Container.AddToClassList("box-model-view-container");

            m_Layer1 = new VisualElement()
            {
                name = "BoxModelViewLayer1"
            };
            m_Layer2 = new VisualElement()
            {
                name = "BoxModelViewLayer2"
            };
            m_Layer2.style.position = Position.Absolute;
            m_Layer2.pickingMode    = PickingMode.Ignore;
            m_Layer2.StretchToParentSize();

            m_TopTextFieldMarginContainer.pickingMode = PickingMode.Ignore;
            m_TopTextFieldMarginContainer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_BottomTextFieldMarginContainer.pickingMode = PickingMode.Ignore;
            m_BottomTextFieldMarginContainer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_TopTextFieldBorderContainer.pickingMode = PickingMode.Ignore;
            m_TopTextFieldBorderContainer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_BottomTextFieldBorderContainer.pickingMode = PickingMode.Ignore;
            m_BottomTextFieldBorderContainer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_TopTextFieldPaddingContainer.pickingMode = PickingMode.Ignore;
            m_TopTextFieldPaddingContainer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_BottomTextFieldPaddingContainer.pickingMode = PickingMode.Ignore;
            m_BottomTextFieldPaddingContainer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_ContentSpacer.pickingMode = PickingMode.Ignore;
            m_ContentSpacer.AddToClassList("box-model-textfield-top-bottom-spacer");

            m_Layer2.Add(m_TopTextFieldMarginContainer);
            m_Layer2.Add(m_TopTextFieldBorderContainer);
            m_Layer2.Add(m_TopTextFieldPaddingContainer);
            m_Layer2.Add(m_ContentSpacer);
            m_Layer2.Add(m_BottomTextFieldPaddingContainer);
            m_Layer2.Add(m_BottomTextFieldBorderContainer);
            m_Layer2.Add(m_BottomTextFieldMarginContainer);

            m_ContentBox = new ContentBox();
            m_ContentBox.AddToClassList("box-model");
            m_ContentBox.AddToClassList("box-model-container-content");
            m_ContentBox.RegisterCallback <MouseOverEvent, BoxType>(OnMouseOver, BoxType.Content);

            m_PaddingBox = new BoxModelElement(BoxType.Padding, m_ContentBox,
                                               m_TopTextFieldPaddingContainer, m_BottomTextFieldPaddingContainer);
            m_PaddingBox.AddToClassList("box-model");
            m_PaddingBox.AddToClassList("box-model-container-padding");
            m_PaddingBox.RegisterCallback <MouseOverEvent, BoxType>(OnMouseOver, BoxType.Padding);

            m_BorderBox = new BoxModelElement(BoxType.Border, m_PaddingBox,
                                              m_TopTextFieldBorderContainer, m_BottomTextFieldBorderContainer);
            m_BorderBox.AddToClassList("box-model");
            m_BorderBox.AddToClassList("box-model-container-border");
            m_BorderBox.RegisterCallback <MouseOverEvent, BoxType>(OnMouseOver, BoxType.Border);

            m_MarginBox = new BoxModelElement(BoxType.Margin, m_BorderBox,
                                              m_TopTextFieldMarginContainer, m_BottomTextFieldMarginContainer);
            m_MarginBox.AddToClassList("box-model");
            m_MarginBox.AddToClassList("box-model-container-margin");
            m_MarginBox.RegisterCallback <MouseOverEvent, BoxType>(OnMouseOver, BoxType.Margin);

            m_Layer1.Add(m_MarginBox);

            m_Container.Add(m_Layer1);
            m_Container.Add(m_Layer2);

            var spacerLeft = new VisualElement()
            {
                style = { flexGrow = 1 }
            };
            var spacerRight = new VisualElement()
            {
                style = { flexGrow = 1 }
            };

            Add(spacerLeft);
            Add(m_Container);
            Add(spacerRight);

            RegisterCallback <MouseOutEvent>(OnMouseOut);
        }
        private VisualElement CreateOutboundRtpView(string id)
        {
            var root      = new VisualElement();
            var container = new VisualElement();

            root.Add(container);

            var outboundGraph = new OutboundRTPStreamGraphView();

            m_parent.OnStats += (peer, report) =>
            {
                if (peer != m_peerConnection)
                {
                    return;
                }

                container.Clear();
                if (!report.TryGetValue(id, out var stats) ||
                    !(stats is RTCOutboundRTPStreamStats outboundStats))
                {
                    container.Add(new Label($"no stats report about {RTCStatsType.OutboundRtp}"));
                    return;
                }

                container.Add(new Label($"{nameof(outboundStats.Id)}: {outboundStats.Id}"));
                container.Add(new Label($"{nameof(outboundStats.Timestamp)}: {outboundStats.Timestamp}"));
                container.Add(new Label($"{nameof(outboundStats.ssrc)}: {outboundStats.ssrc}"));
                container.Add(new Label($"{nameof(outboundStats.estimatedPlayoutTimestamp)}: {outboundStats.estimatedPlayoutTimestamp}"));
                container.Add(new Label($"{nameof(outboundStats.isRemote)}: {outboundStats.isRemote}"));
                container.Add(new Label($"{nameof(outboundStats.mediaType)}: {outboundStats.mediaType}"));
                container.Add(new Label($"{nameof(outboundStats.kind)}: {outboundStats.kind}"));
                container.Add(new Label($"{nameof(outboundStats.trackId)}: {outboundStats.trackId}"));
                container.Add(new Label($"{nameof(outboundStats.transportId)}: {outboundStats.transportId}"));
                container.Add(new Label($"{nameof(outboundStats.codecId)}: {outboundStats.codecId}"));
                container.Add(new Label($"{nameof(outboundStats.firCount)}: {outboundStats.firCount}"));
                container.Add(new Label($"{nameof(outboundStats.pliCount)}: {outboundStats.pliCount}"));
                container.Add(new Label($"{nameof(outboundStats.nackCount)}: {outboundStats.nackCount}"));
                container.Add(new Label($"{nameof(outboundStats.sliCount)}: {outboundStats.sliCount}"));
                container.Add(new Label($"{nameof(outboundStats.qpSum)}: {outboundStats.qpSum}"));
                container.Add(new Label($"{nameof(outboundStats.mediaSourceId)}: {outboundStats.mediaSourceId}"));
                container.Add(new Label($"{nameof(outboundStats.packetsSent)}: {outboundStats.packetsSent}"));
                container.Add(new Label(
                                  $"{nameof(outboundStats.retransmittedPacketsSent)}: {outboundStats.retransmittedPacketsSent}"));
                container.Add(new Label($"{nameof(outboundStats.bytesSent)}: {outboundStats.bytesSent}"));
                container.Add(new Label($"{nameof(outboundStats.headerBytesSent)}: {outboundStats.headerBytesSent}"));
                container.Add(new Label(
                                  $"{nameof(outboundStats.retransmittedBytesSent)}: {outboundStats.retransmittedBytesSent}"));
                container.Add(new Label($"{nameof(outboundStats.targetBitrate)}: {outboundStats.targetBitrate}"));
                container.Add(new Label($"{nameof(outboundStats.framesEncoded)}: {outboundStats.framesEncoded}"));
                container.Add(new Label($"{nameof(outboundStats.keyFramesEncoded)}: {outboundStats.keyFramesEncoded}"));
                container.Add(new Label($"{nameof(outboundStats.totalEncodeTime)}: {outboundStats.totalEncodeTime}"));
                container.Add(new Label(
                                  $"{nameof(outboundStats.totalEncodedBytesTarget)}: {outboundStats.totalEncodedBytesTarget}"));
                container.Add(
                    new Label($"{nameof(outboundStats.totalPacketSendDelay)}: {outboundStats.totalPacketSendDelay}"));
                container.Add(new Label(
                                  $"{nameof(outboundStats.qualityLimitationReason)}: {outboundStats.qualityLimitationReason}"));
                container.Add(new Label(
                                  $"{nameof(outboundStats.qualityLimitationResolutionChanges)}: {outboundStats.qualityLimitationResolutionChanges}"));
                container.Add(new Label($"{nameof(outboundStats.contentType)}: {outboundStats.contentType}"));
                container.Add(new Label(
                                  $"{nameof(outboundStats.encoderImplementation)}: {outboundStats.encoderImplementation}"));

                outboundGraph.AddInput(outboundStats);
            };

            root.Add(outboundGraph.Create());

            return(root);
        }
Example #30
0
        void InitializeCoppaManager(VisualElement rootVisualElement)
        {
            rootVisualElement.AddStyleSheetPath(k_CoppaCommonStyleSheetPath);
            rootVisualElement.AddStyleSheetPath(EditorGUIUtility.isProSkin ? k_CoppaDarkStyleSheetPath : k_CoppaLightStyleSheetPath);
            var coppaTemplate = EditorGUIUtility.Load(k_CoppaTemplatePath) as VisualTreeAsset;

            rootVisualElement.Add(coppaTemplate.CloneTree().contentContainer);
            m_CoppaContainer = rootVisualElement.Q(coppaContainerName);
            var persistContainer = m_CoppaContainer.Q(k_PersistContainerName);
            var coppaField       = BuildPopupField(m_CoppaContainer, k_CoppaFieldName);

            //Setup dashboard link
            var learnMoreClickable = new Clickable(() =>
            {
                Application.OpenURL(k_CoppaLearnMoreUrl);
            });

            m_CoppaContainer.Q(k_CoppaLearnLinkBtnName).AddManipulator(learnMoreClickable);

            var originalCoppaValue = UnityConnect.instance.GetProjectInfo().COPPA;
            var coppaChoicesList   = new List <String>()
            {
                L10n.Tr(k_No), L10n.Tr(k_Yes)
            };

            if (originalCoppaValue == COPPACompliance.COPPAUndefined)
            {
                coppaChoicesList.Insert(0, L10n.Tr(k_Undefined));
            }
            coppaField.choices = coppaChoicesList;
            SetCoppaFieldValue(originalCoppaValue, coppaField);

            persistContainer.Q <Button>(k_SaveBtnName).clicked += () =>
            {
                try
                {
                    ServicesConfiguration.instance.RequestCurrentProjectCoppaApiUrl(projectCoppaApiUrl =>
                    {
                        var payload            = $"{{\"coppa\":\"{GetCompliancyJsonValueFromFieldValue(coppaField)}\"}}";
                        var uploadHandler      = new UploadHandlerRaw(Encoding.UTF8.GetBytes(payload));
                        var currentSaveRequest = new UnityWebRequest(projectCoppaApiUrl, UnityWebRequest.kHttpVerbPUT)
                        {
                            uploadHandler = uploadHandler
                        };
                        currentSaveRequest.suppressErrorsToConsole = true;
                        currentSaveRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}");
                        currentSaveRequest.SetRequestHeader("Content-Type", "application/json;charset=UTF-8");
                        var operation = currentSaveRequest.SendWebRequest();
                        SetEnabledCoppaControls(coppaContainer, false);
                        operation.completed += asyncOperation =>
                        {
                            try
                            {
                                if (currentSaveRequest.responseCode == k_HttpStatusNoContent)
                                {
                                    try
                                    {
                                        var newCompliancyValue = GetCompliancyForFieldValue(coppaField);
                                        if (!UnityConnect.instance.SetCOPPACompliance(newCompliancyValue))
                                        {
                                            EditorAnalytics.SendCoppaComplianceEvent(new CoppaState()
                                            {
                                                isCompliant = newCompliancyValue == COPPACompliance.COPPACompliant
                                            });

                                            SetCoppaFieldValue(originalCoppaValue, coppaField);
                                            SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                            exceptionCallback?.Invoke(originalCoppaValue, new CoppaComplianceEditorConfigurationException(k_CoppaComplianceEditorConfigurationExceptionMessage));
                                        }
                                        else
                                        {
                                            originalCoppaValue = newCompliancyValue;
                                            SetCoppaFieldValue(originalCoppaValue, coppaField);
                                            SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                            NotificationManager.instance.Publish(Notification.Topic.CoppaCompliance, Notification.Severity.Info,
                                                                                 L10n.Tr(CoppaComplianceChangedMessage));
                                            saveButtonCallback?.Invoke(originalCoppaValue);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        SetCoppaFieldValue(originalCoppaValue, coppaField);
                                        SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                        exceptionCallback?.Invoke(originalCoppaValue, new CoppaComplianceEditorConfigurationException(k_CoppaComplianceEditorConfigurationExceptionMessage, ex));
                                    }
                                    finally
                                    {
                                        currentSaveRequest.Dispose();
                                        currentSaveRequest = null;
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        SetCoppaFieldValue(originalCoppaValue, coppaField);
                                        SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                                        exceptionCallback?.Invoke(originalCoppaValue, new CoppaComplianceWebConfigurationException(L10n.Tr(k_CoppaUnexpectedSaveRequestBehaviorMessage))
                                        {
                                            error           = currentSaveRequest.error,
                                            method          = currentSaveRequest.method,
                                            timeout         = currentSaveRequest.timeout,
                                            url             = currentSaveRequest.url,
                                            responseHeaders = currentSaveRequest.GetResponseHeaders(),
                                            responseCode    = currentSaveRequest.responseCode,
                                            isHttpError     = (currentSaveRequest.result == UnityWebRequest.Result.ProtocolError),
                                            isNetworkError  = (currentSaveRequest.result == UnityWebRequest.Result.ConnectionError),
                                        });
                                    }
                                    finally
                                    {
                                        currentSaveRequest.Dispose();
                                        currentSaveRequest = null;
                                    }
                                }
                            }
                            finally
                            {
                                SetEnabledCoppaControls(coppaContainer, true);
                            }
                        };
                    });
                }
                catch (Exception ex)
                {
                    SetCoppaFieldValue(originalCoppaValue, coppaField);
                    SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                    exceptionCallback?.Invoke(originalCoppaValue, ex);
                }
            };

            persistContainer.Q <Button>(k_CancelBtnName).clicked += () =>
            {
                SetCoppaFieldValue(originalCoppaValue, coppaField);
                SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
                cancelButtonCallback?.Invoke(originalCoppaValue);
            };

            persistContainer.style.display = DisplayStyle.None;
            coppaField.RegisterValueChangedCallback(evt =>
            {
                SetPersistContainerVisibility(originalCoppaValue, persistContainer, coppaField);
            });
        }