Exemple #1
0
        void OnDragPerform(DragPerformEvent e)
        {
            var stencil          = Store.GetState().CurrentGraphModel.Stencil;
            var dragNDropHandler = stencil.DragNDropHandler;

            dragNDropHandler?.HandleDragPerform(e, Store, DragNDropContext.Blackboard, this);
            e.StopPropagation();
        }
Exemple #2
0
        void OnDragUpdated(DragUpdatedEvent e)
        {
            var stencil          = Store.GetState().CurrentGraphModel.Stencil;
            var dragNDropHandler = stencil.DragNDropHandler;

            dragNDropHandler?.HandleDragUpdated(e, DragNDropContext.Blackboard);
            e.StopPropagation();
        }
Exemple #3
0
 void RebuildSections()
 {
     if (Sections != null)
     {
         var currentGraphModel  = Store.GetState().CurrentGraphModel;
         var blackboardProvider = currentGraphModel.Stencil.GetBlackboardProvider();
         blackboardProvider.RebuildSections(this);
     }
 }
        public Blackboard(Store store, VseGraphView graphView, bool windowed)
        {
            Store = store;

            styleSheets.Add(AssetDatabase.LoadAssetAtPath <StyleSheet>(UICreationHelper.templatePath + "Blackboard.uss"));

            AddToClassList("blackboard");

            scrollable = true;
            base.title = k_ClassLibraryTitle;
            subTitle   = "";

            viewDataKey = string.Empty;

            addItemRequested  = OnAddItemRequested;
            moveItemRequested = OnMoveItemRequested;

            // TODO 0.5: hack - we have two conflicting renaming systems
            // the blackboard one seems to win
            // for 0.4, just rewire it to dispatch the same action as ours
            editTextRequested = OnEditTextRequested;

            RegisterCallback <AttachToPanelEvent>(OnAttachToPanel);
            RegisterCallback <DetachFromPanelEvent>(OnDetachFromPanel);

            this.AddManipulator(new ContextualMenuManipulator(OnContextualMenuEvent));

            graphView.OnSelectionChangedCallback += s =>
            {
                IGraphModel currentGraphModel = Store.GetState().CurrentGraphModel;
                if (!(currentGraphModel as Object))
                {
                    return;
                }

                if (currentGraphModel == GraphView.UIController.LastGraphModel &&
                    (GraphView.selection.LastOrDefault() is BlackboardField ||
                     GraphView.selection.LastOrDefault() is IVisualScriptingField))
                {
                    ((VSGraphModel)currentGraphModel).LastChanges.RequiresRebuild = true;
                    return;
                }

                RebuildSections();
            };

            var header = this.Query("header").First();

            m_AddButton = header?.Query <Button>("addButton").First();
            if (m_AddButton != null)
            {
                m_AddButton.style.visibility = Visibility.Hidden;
            }

            this.windowed  = windowed;
            this.graphView = graphView;
        }
Exemple #5
0
        public TokenDeclaration(Store store, IVariableDeclarationModel model, GraphView graphView)
        {
            m_Pill = new Pill();
            Add(m_Pill);

            if (model is IObjectReference modelReference)
            {
                if (modelReference is IExposeTitleProperty titleProperty)
                {
#if UNITY_2019_3_OR_NEWER
                    m_TitleLabel = m_Pill.Q <Label>("title-label");
#else
                    m_TitleLabel = m_Pill.Q <Label>("title-label").ReplaceWithBoundLabel();
#endif
                    m_TitleLabel.bindingPath = titleProperty.TitlePropertyName;
                }
            }

            styleSheets.Add(AssetDatabase.LoadAssetAtPath <StyleSheet>(UICreationHelper.templatePath + "Token.uss"));

            Declaration = model;
            m_Store     = store;
            m_GraphView = graphView;

            m_Pill.icon = Declaration.IsExposed
                ? VisualScriptingIconUtility.LoadIconRequired("GraphView/Nodes/BlackboardFieldExposed.png")
                : null;

            m_Pill.text = Declaration.Title;

            if (model != null)
            {
                capabilities = VseUtility.ConvertCapabilities(model);
            }

            var     variableModel = model as VariableDeclarationModel;
            Stencil stencil       = store.GetState().CurrentGraphModel?.Stencil;
            if (variableModel != null && stencil != null && variableModel.DataType.IsValid)
            {
                string friendlyTypeName = variableModel.DataType.GetMetadata(stencil).FriendlyName;
                Assert.IsTrue(!string.IsNullOrEmpty(friendlyTypeName));
                tooltip = $"{variableModel.VariableString} declaration of type {friendlyTypeName}";
                if (!string.IsNullOrEmpty(variableModel.Tooltip))
                {
                    tooltip += "\n" + variableModel.Tooltip;
                }
            }

            SetClasses();

            this.EnableRename();

            if (model != null)
            {
                viewDataKey = model.GetId();
            }
        }
        public VseUIController(VseGraphView graphView, Store store)
        {
            m_GraphView   = graphView;
            m_Store       = store;
            m_IconsParent = new VisualElement {
                name = "iconsParent"
            };
            m_IconsParent.style.overflow = Overflow.Visible;
            Blackboard = new Blackboard(m_Store, m_GraphView);
            var blackboardPosition = m_Store.GetState().EditorDataModel.BlackboardPosition;

            if (Math.Abs(blackboardPosition.size.x) > float.Epsilon && Math.Abs(blackboardPosition.size.y) > float.Epsilon)
            {
                Blackboard.SetPosition(m_Store.GetState().EditorDataModel.BlackboardPosition);
            }
            else
            {
                ResetBlackboard();
            }
            m_LastGraphModel = null;
        }
        public void OnAddedToGraphView()
        {
            this.Query <GraphElement>().ForEach(childGraphElement =>
            {
                switch (childGraphElement)
                {
                case TokenDeclaration tokenDeclaration:
                    ((VseGraphView)m_GraphView).RestoreSelectionForElement(tokenDeclaration);
                    break;

                case IHasGraphElementModel hasGraphElementChildModel when m_Store.GetState().EditorDataModel
                    .ShouldSelectElementUponCreation(hasGraphElementChildModel):
                    childGraphElement.Select(m_GraphView, true);
                    break;

                case IVisualScriptingField visualScriptingField when m_Store.GetState().EditorDataModel
                    .ShouldExpandElementUponCreation(visualScriptingField):
                    visualScriptingField.Expand();
                    break;
                }
            });
        }
Exemple #8
0
        static void OnDropOutsideCallback(Store store, Vector2 pos, Edge edge)
        {
            VseGraphView graphView = edge.GetFirstAncestorOfType <VseGraphView>();
            Vector2      worldPos  = pos;

            pos = graphView.contentViewContainer.WorldToLocal(pos);

            List <IEdgeModel> edgesToDelete = GetDropEdgeModelsToDelete(edge);

            // when grabbing an existing edge's end, the edgeModel should be deleted
            if ((edge).GraphElementModel != null)
            {
                edgesToDelete.Add((IEdgeModel)edge.GraphElementModel);
            }

            IStackModel targetStackModel = null;
            int         targetIndex      = -1;
            StackNode   stackNode        = graphView.lastHoveredVisualElement as StackNode ??
                                           graphView.lastHoveredVisualElement.GetFirstOfType <StackNode>();

            if (stackNode != null)
            {
                targetStackModel = stackNode.stackModel;
                targetIndex      = stackNode.GetInsertionIndex(worldPos);
            }

            IPortModel existingPortModel;

            // warning: when dragging the end of an existing edge, both ports are non null.
            if (edge.input != null && edge.output != null)
            {
                float distanceToOutput = Vector2.Distance(edge.edgeControl.from, pos);
                float distanceToInput  = Vector2.Distance(edge.edgeControl.to, pos);
                // note: if the user was able to stack perfectly both ports, we'd be in trouble
                if (distanceToOutput < distanceToInput)
                {
                    existingPortModel = (IPortModel)edge.input.userData;
                }
                else
                {
                    existingPortModel = (IPortModel)edge.output.userData;
                }
            }
            else
            {
                Port existingPort = (Port)(edge.input ?? edge.output);
                existingPortModel = existingPort.userData as IPortModel;
            }

            store.GetState().CurrentGraphModel?.Stencil.CreateNodesFromPort(store, existingPortModel, pos, edgesToDelete, targetStackModel, targetIndex);
        }
Exemple #9
0
        void OnMoveItemRequested(Experimental.GraphView.Blackboard blackboard, int index, VisualElement field)
        {
            // TODO: Workaround to prevent moving item above a BlackboardThisField, as all check code is executed
            // within UnityEditor.Experimental.GraphView.BlackboardSection in private or internal functions
            bool hasBlackboardThisField = (blackboard as Blackboard)?.Sections?[0]?.Children()
                                          ?.Any(x => x is BlackboardThisField) ?? false;

            if (index == 0 && hasBlackboardThisField)
            {
                return;
            }

            var currentGraphModel = Store.GetState().CurrentGraphModel;

            currentGraphModel.Stencil.GetBlackboardProvider().MoveItemRequested(Store, index, field);
        }
Exemple #10
0
        void OnSelectionChange()
        {
            IGraphModel currentGraphModel = Store.GetState().CurrentGraphModel;

            if (!(currentGraphModel as Object))
            {
                return;
            }

            if (currentGraphModel == GraphView.UIController.LastGraphModel &&
                (GraphView.selection.LastOrDefault() is BlackboardField ||
                 GraphView.selection.LastOrDefault() is IVisualScriptingField))
            {
                ((VSGraphModel)currentGraphModel).LastChanges.RequiresRebuild = true;
                return;
            }

            RebuildBlackboard();
        }
        public virtual void OnCompilationRequest(RequestCompilationOptions options)
        {
            CompilationOptions compilationOptions = EditorApplication.isPlaying
                ? CompilationOptions.LiveEditing
                : CompilationOptions.Default;

            if (TracingEnabled)
            {
                compilationOptions |= CompilationOptions.Tracing;
            }

            // Register
            m_PluginRepository.RegisterPlugins(compilationOptions);

            VSGraphModel vsGraphModel = Store.GetState().CurrentGraphModel as VSGraphModel;

            if (vsGraphModel == null || vsGraphModel.Stencil == null)
            {
                return;
            }

            ITranslator translator = vsGraphModel.Stencil.CreateTranslator();

            if (!translator.SupportsCompilation())
            {
                return;
            }

            if (options == RequestCompilationOptions.SaveGraph)
            {
                AssetDatabase.SaveAssets();
            }

            CompilationResult r = vsGraphModel.Compile(AssemblyType.None, translator, compilationOptions, m_PluginRepository.GetPluginHandlers());

            if (Store?.GetState()?.CompilationResultModel is CompilationResultModel compilationResultModel) // TODO: could have disappeared during the await
            {
                compilationResultModel.lastResult = r;
                OnCompilationDone(vsGraphModel, compilationOptions, r);
            }
        }
        void RebuildBlackboard()
        {
            var currentGraphModel = Store.GetState().CurrentGraphModel;

            title = currentGraphModel.FriendlyScriptName;

            subTitle = currentGraphModel.Stencil.GetBlackboardProvider().GetSubTitle();

            var blackboardProvider = currentGraphModel.Stencil.GetBlackboardProvider();

            if (m_AddButton != null)
            {
                if (!blackboardProvider.CanAddItems)
                {
                    m_AddButton.style.visibility = Visibility.Hidden;
                }
                else
                {
                    m_AddButton.style.visibility = StyleKeyword.Null;
                }
            }

            RebuildSections();

            var editorDataModel = Store.GetState().EditorDataModel;
            IGraphElementModel elementModelToRename = editorDataModel?.ElementModelToRename;

            if (elementModelToRename != null)
            {
                IRenamable elementToRename = GraphVariables.OfType <IRenamable>()
                                             .FirstOrDefault(x => ReferenceEquals(x.GraphElementModel, elementModelToRename));
                if (elementToRename != null)
                {
                    GraphView.UIController.ElementToRename = elementToRename;
                }
            }

            GraphView.HighlightGraphElements();
        }
Exemple #13
0
        public void Rebuild(RebuildMode rebuildMode)
        {
            IBlackboardProvider blackboardProvider =
                ((VSGraphModel)Store.GetState().CurrentGraphModel).Stencil.GetBlackboardProvider();

            if (Sections == null || m_LastProvider != blackboardProvider)
            {
                m_LastProvider = blackboardProvider;
                ClearContents();
                Clear();
                Sections = blackboardProvider?.CreateSections().ToList();
                Sections?.ForEach(Add);
            }

            if (rebuildMode == RebuildMode.BlackboardAndGraphView)
            {
                Store.Dispatch(new RefreshUIAction(UpdateFlags.GraphTopology));
            }
            else
            {
                RebuildBlackboard();
            }
        }
        public void ClearContents()
        {
            if (Sections != null)
            {
                foreach (var section in Sections)
                {
                    section.Clear();
                }
            }

            GraphVariables.Clear();

            IGraphModel currentGraphModel = null;

            if (!(Store.GetState().AssetModel as ScriptableObject))
            {
                title    = k_ClassLibraryTitle;
                subTitle = "";
            }
            else
            {
                currentGraphModel = Store.GetState().CurrentGraphModel;
                title             = currentGraphModel.FriendlyScriptName;
                subTitle          = currentGraphModel.Stencil.GetBlackboardProvider().GetSubTitle();
            }

            var blackboardProvider = currentGraphModel?.Stencil.GetBlackboardProvider();

            if (m_AddButton != null)
            {
                if (blackboardProvider == null || blackboardProvider.CanAddItems == false)
                {
                    m_AddButton.style.visibility = Visibility.Hidden;
                }
            }
        }
        public virtual void AddItemsToMenu(GenericMenu menu)
        {
            var disabled = m_Store?.GetState().CurrentGraphModel == null;

            m_LockTracker.AddItemsToMenu(menu, disabled);
        }
        protected virtual void OnEnable()
        {
            if (m_PreviousGraphModels == null)
            {
                m_PreviousGraphModels = new List <GraphModel>();
            }

            if (m_BlackboardExpandedRowStates == null)
            {
                m_BlackboardExpandedRowStates = new List <string>();
            }

            if (m_ElementModelsToSelectUponCreation == null)
            {
                m_ElementModelsToSelectUponCreation = new List <string>();
            }

            if (m_ElementModelsToExpandUponCreation == null)
            {
                m_ElementModelsToExpandUponCreation = new List <string>();
            }

            rootVisualElement.RegisterCallback <ValidateCommandEvent>(OnValidateCommand);
            rootVisualElement.RegisterCallback <ExecuteCommandEvent>(OnExecuteCommand);
            rootVisualElement.RegisterCallback <MouseMoveEvent>(_ => m_IdleTimer?.Restart());

            rootVisualElement.styleSheets.Add(AssetDatabase.LoadAssetAtPath <StyleSheet>(k_StyleSheetPath + "VSEditor.uss"));

            rootVisualElement.Clear();
            rootVisualElement.style.overflow      = Overflow.Hidden;
            rootVisualElement.pickingMode         = PickingMode.Ignore;
            rootVisualElement.style.flexDirection = FlexDirection.Column;
            rootVisualElement.name = "vseRoot";

            // Create the store.
            DataModel = CreateDataModel();
            State initialState = CreateInitialState();

            m_Store = new Store(initialState, Store.Options.TrackUndoRedo);

            VseUtility.SetupLogStickyCallback();

            m_GraphContainer = new VisualElement {
                name = "graphContainer"
            };
            m_GraphView = CreateGraphView();
            m_Menu      = CreateMenu();
            m_BlankPage = CreateBlankPage();


            IMGUIContainer imguiContainer = null;

            imguiContainer = new IMGUIContainer(() =>
            {
                var timeRect = new Rect(0, 0, rootVisualElement.layout.width, imguiContainer.layout.height);
                m_TracingTimeline.OnGUI(timeRect);
            });
            m_TracingTimeline = new TracingTimeline(m_Store.GetState(), imguiContainer);
            m_TracingTimeline.SyncVisible();

            rootVisualElement.Add(m_Menu);
            rootVisualElement.Add(imguiContainer);
            rootVisualElement.Add(m_GraphContainer);

            m_CompilationPendingLabel = new Label("Compilation Pending")
            {
                name = "compilationPendingLabel"
            };

            m_GraphContainer.Add(m_GraphView);

            m_ShortcutHandler = new ShortcutHandler(
                new Dictionary <Event, ShortcutDelegate>
            {
                { Event.KeyboardEvent("F2"), () => Application.platform != RuntimePlatform.OSXEditor ? RenameElement() : EventPropagation.Continue },
                { Event.KeyboardEvent("F5"), () =>
                  {
                      RefreshUI(UpdateFlags.All);
                      return(EventPropagation.Continue);
                  } },
                { Event.KeyboardEvent("return"), () => Application.platform == RuntimePlatform.OSXEditor ? RenameElement() : EventPropagation.Continue },
                { Event.KeyboardEvent("[enter]"), () => Application.platform == RuntimePlatform.OSXEditor ? RenameElement() : EventPropagation.Continue },
                { Event.KeyboardEvent("backspace"), OnBackspaceKeyDown },
                { Event.KeyboardEvent("space"), OnSpaceKeyDown },
                { Event.KeyboardEvent("C"), () =>
                  {
                      IGraphElementModel[] selectedModels = m_GraphView.selection
                                                            .OfType <IHasGraphElementModel>()
                                                            .Select(x => x.GraphElementModel)
                                                            .ToArray();

                      // Convert variable -> constant if selection contains at least one item that satisfies conditions
                      IVariableModel[] variableModels = selectedModels.OfType <VariableNodeModel>().Cast <IVariableModel>().ToArray();
                      if (variableModels.Any())
                      {
                          m_Store.Dispatch(new ConvertVariableNodesToConstantNodesAction(variableModels));
                          return(EventPropagation.Stop);
                      }

                      IConstantNodeModel[] constantModels = selectedModels.OfType <IConstantNodeModel>().ToArray();
                      if (constantModels.Any())
                      {
                          m_Store.Dispatch(new ConvertConstantNodesToVariableNodesAction(constantModels));
                      }
                      return(EventPropagation.Stop);
                  } },
                { Event.KeyboardEvent("Q"), () => m_GraphView.AlignSelection(false) },
                { Event.KeyboardEvent("#Q"), () => m_GraphView.AlignSelection(true) },
                // DEBUG
                { Event.KeyboardEvent("1"), () => OnCreateLogNode(LogNodeModel.LogTypes.Message) },
                { Event.KeyboardEvent("2"), () => OnCreateLogNode(LogNodeModel.LogTypes.Warning) },
                { Event.KeyboardEvent("3"), () => OnCreateLogNode(LogNodeModel.LogTypes.Error) },
                { Event.KeyboardEvent("`"), () => OnCreateStickyNote(new Rect(m_GraphView.ChangeCoordinatesTo(m_GraphView.contentViewContainer, m_GraphView.WorldToLocal(Event.current.mousePosition)), StickyNote.defaultSize)) },
            });

            rootVisualElement.parent.AddManipulator(m_ShortcutHandler);
            Selection.selectionChanged += OnGlobalSelectionChange;

            m_Store.StateChanged   += StoreOnStateChanged;
            Undo.undoRedoPerformed += UndoRedoPerformed;

            rootVisualElement.RegisterCallback <AttachToPanelEvent>(OnEnterPanel);
            rootVisualElement.RegisterCallback <DetachFromPanelEvent>(OnLeavePanel);

            titleContent = new GUIContent("Visual Script");

            // After a domain reload, all loaded objects will get reloaded and their OnEnable() called again
            // It looks like all loaded objects are put in a deserialization/OnEnable() queue
            // the previous graph's nodes/edges/... might be queued AFTER this window's OnEnable
            // so relying on objects to be loaded/initialized is not safe
            // hence, we need to defer the loading action
            rootVisualElement.schedule.Execute(() =>
            {
                if (!String.IsNullOrEmpty(LastGraphFilePath))
                {
                    try
                    {
                        m_Store.Dispatch(new LoadGraphAssetAction(LastGraphFilePath, loadType: LoadGraphAssetAction.Type.KeepHistory));
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e);
                    }
                }
                else             // will display the blank page. not needed otherwise as the LoadGraphAsset reducer will refresh
                {
                    m_Store.Dispatch(new RefreshUIAction(UpdateFlags.All));
                }
            }).ExecuteLater(0);


            m_LockTracker.lockStateChanged.AddListener(OnLockStateChanged);

            m_PluginRepository = new PluginRepository(m_Store, m_GraphView);

            EditorApplication.playModeStateChanged += OnEditorPlayModeStateChanged;
            EditorApplication.pauseStateChanged    += OnEditorPauseStateChanged;

            if (DataModel is VSEditorDataModel vsDataModel)
            {
                vsDataModel.PluginRepository     = m_PluginRepository;
                vsDataModel.OnCompilationRequest = OnCompilationRequest;
            }
        }
        public void UnloadGraphIfDeleted()
        {
            var iGraphModel = m_Store.GetState().CurrentGraphModel as ScriptableObject;

            if (!iGraphModel)
            {
                m_GraphView.UIController.Clear();
                m_Store.GetState().UnloadCurrentGraphAsset();
                m_LastGraphFilePath = null;
                Menu.UpdateUI();
                UpdateGraphContainer();
            }
        }
Exemple #18
0
        public void UnloadGraphIfDeleted()
        {
            var iGraphModel = m_Store.GetState().CurrentGraphModel as ScriptableObject;

            if (!iGraphModel)
            {
                UnloadGraph();
            }
        }
Exemple #19
0
        public void BuildContextualMenu()
        {
            var selectedModelsDictionary = m_Selection
                                           .OfType <IHasGraphElementModel>()
                                           .Where(x => !(x is BlackboardThisField)) // this blackboard field
                                           .Distinct(s_HasGraphElementModelComparer)
                                           .ToDictionary(x => x.GraphElementModel);

            IReadOnlyCollection <IGraphElementModel> selectedModelsKeys = selectedModelsDictionary.Keys.ToList();

            BuildBlackboardContextualMenu();

            var originatesFromBlackboard = (m_Evt.target as VisualElement)?.GetFirstOfType <Blackboard>() != null;

            if (!originatesFromBlackboard || m_Evt.target is IHasGraphElementModel)
            {
                BuildGraphViewContextualMenu();
                if (!originatesFromBlackboard)
                {
                    BuildNodeContextualMenu(selectedModelsDictionary);
                    BuildStackContextualMenu(selectedModelsKeys);
                    BuildEdgeContextualMenu(selectedModelsKeys);
                }

                BuildVariableNodeContextualMenu(selectedModelsKeys);
                if (!originatesFromBlackboard)
                {
                    BuildConstantNodeContextualMenu(selectedModelsKeys);
                    BuildStaticConstantNodeContextualMenu(selectedModelsKeys);
                    BuildPropertyNodeContextualMenu(selectedModelsKeys);
                    BuildSpecialContextualMenu(selectedModelsKeys);
                    BuildStickyNoteContextualMenu();
                    BuildRefactorContextualMenu(selectedModelsKeys);
                }

                if (selectedModelsDictionary.Any())
                {
                    m_Evt.menu.AppendAction("Delete", menuAction =>
                    {
                        m_Store.Dispatch(new DeleteElementsAction(selectedModelsKeys.ToArray()));
                    }, eventBase => DropdownMenuAction.Status.Normal);
                }
            }

            if (originatesFromBlackboard && !(m_Evt.target is IHasGraphElementModel))
            {
                var currentGraphModel = m_Store.GetState().CurrentGraphModel;
                currentGraphModel?.Stencil.GetBlackboardProvider()
                .BuildContextualMenu(m_Evt.menu,
                                     (VisualElement)m_Evt.target,
                                     m_Store,
                                     m_Evt.mousePosition);
            }

            var renamable = originatesFromBlackboard && m_Evt.target is IRenamable ? m_Evt.target as IRenamable :
                            (!originatesFromBlackboard && selectedModelsDictionary.Count == 1) ? selectedModelsDictionary.Single().Value as IRenamable : null;

            if (renamable != null)
            {
                m_Evt.menu.AppendAction("Rename", menuAction =>
                {
                    renamable.Rename(true);
                    m_Evt.PreventDefault();
                    m_Evt.StopImmediatePropagation();
                }, eventBase => DropdownMenuAction.Status.Normal);
            }

            if (m_Evt.target is IContextualMenuBuilder contextualMenuBuilder)
            {
                contextualMenuBuilder.BuildContextualMenu(m_Evt);
            }
        }
Exemple #20
0
// TODO: Enable when GraphView supports it
//        void UpdateProperties(PersistedProperties properties)
//        {
//            var newPosition = properties.position;
//            var newSize = properties.size;
//            var newAutoDimOpacityEnabled = properties.isAutoDimOpacityEnabled;
//
//            float validateFloat = newPosition.x + newPosition.y + newPosition.z + newSize.x + newSize.y;
//            if (float.IsInfinity(validateFloat) || float.IsNaN(validateFloat) || newSize.x < float.Epsilon || newSize.y < float.Epsilon)
//                return;
//
//            SetPosition(new Rect(newPosition, newSize));
//
//            if ((this.IsAutoDimOpacityEnabled() && !newAutoDimOpacityEnabled) ||
//                (!this.IsAutoDimOpacityEnabled() && newAutoDimOpacityEnabled))
//                this.ToggleAutoDimOpacity(VisualElementExtensions.StartingOpacity.Min);
//
//            UpdatePersistedProperties(newPosition, newSize, newAutoDimOpacityEnabled);
//        }

        void OnAddItemRequested(Experimental.GraphView.Blackboard blackboard)
        {
            var currentGraphModel = Store.GetState().CurrentGraphModel;

            currentGraphModel.Stencil.GetBlackboardProvider().AddItemRequested(Store, (IAction)null);
        }
Exemple #21
0
 public void UpdateTooltip(IPortModel portModel)
 {
     tooltip = m_Store.GetState().CurrentGraphModel?.Stencil.GetTooltipForPortModel(portModel);
 }
        internal void UpdateTopology()
        {
            Profiler.BeginSample("UpdateTopology");
            Stopwatch topologyStopwatch = new Stopwatch();

            topologyStopwatch.Start();

            State       state             = m_Store.GetState();
            IGraphModel currentGraphModel = state.CurrentGraphModel;

            if (currentGraphModel == null)
            {
                return;
            }

            IGraphChangeList graphChangeList      = currentGraphModel.LastChanges;
            string           dispatchedActionName = state.LastDispatchedActionName; // save this now, because some actions trigger a UIRefresh, hiding the original action (TODO)

            m_GraphView.DisablePersistedSelectionRestore();

            bool fullUIRebuildOnChange = state.Preferences.GetBool(VSPreferences.BoolPref.FullUIRebuildOnChange);
            bool forceRebuildUI        = fullUIRebuildOnChange || currentGraphModel != m_LastGraphModel || graphChangeList == null || !graphChangeList.HasAnyTopologyChange() || ModelsToNodeMapping == null;

            if (forceRebuildUI) // no specific graph changes passed, assume rebuild everything
            {
                RebuildAll(state);
            }
            else
            {
                PartialRebuild(state);
            }

            state.EditorDataModel.ClearElementsToSelectUponCreation();

            MapModelsToNodes();

            if (state.Preferences.GetBool(VSPreferences.BoolPref.ShowUnusedNodes))
            {
                m_GraphView.PositionDependenciesManagers.UpdateNodeState(ModelsToNodeMapping);
            }

            m_GraphView.HighlightGraphElements();

            m_LastGraphModel = currentGraphModel;

            m_GraphView.EnablePersistedSelectionRestore();

            if (ElementToRename != null)
            {
                m_GraphView.ClearSelection();
                m_GraphView.AddToSelection((GraphElement)ElementToRename);
                ElementToRename.Rename(forceRename: true);
                ElementToRename = null;
                state.EditorDataModel.ElementModelToRename = null;
            }

            m_GraphView.MarkDirtyRepaint();

            topologyStopwatch.Stop();
            Profiler.EndSample();

            if (state.Preferences.GetBool(VSPreferences.BoolPref.WarnOnUIFullRebuild) && state.lastActionUIRebuildType == State.UIRebuildType.Full)
            {
                Debug.LogWarning($"Rebuilding the whole UI ({dispatchedActionName})");
            }
            if (state.Preferences.GetBool(VSPreferences.BoolPref.LogUIBuildTime))
            {
                Debug.Log($"UI Update ({dispatchedActionName}) took {topologyStopwatch.ElapsedMilliseconds} ms");
            }
        }
// TODO: Enable when GraphView supports it
//        void UpdateProperties(PersistedProperties properties)
//        {
//            var newPosition = properties.position;
//            var newSize = properties.size;
//            var newAutoDimOpacityEnabled = properties.isAutoDimOpacityEnabled;
//
//            float validateFloat = newPosition.x + newPosition.y + newPosition.z + newSize.x + newSize.y;
//            if (float.IsInfinity(validateFloat) || float.IsNaN(validateFloat) || newSize.x < float.Epsilon || newSize.y < float.Epsilon)
//                return;
//
//            SetPosition(new Rect(newPosition, newSize));
//
//            if ((this.IsAutoDimOpacityEnabled() && !newAutoDimOpacityEnabled) ||
//                (!this.IsAutoDimOpacityEnabled() && newAutoDimOpacityEnabled))
//                this.ToggleAutoDimOpacity(VisualElementExtensions.StartingOpacity.Min);
//
//            UpdatePersistedProperties(newPosition, newSize, newAutoDimOpacityEnabled);
//        }

        void OnAddItemRequested(Unity.GraphElements.Blackboard blackboard)
        {
            var currentGraphModel = Store.GetState().CurrentGraphModel;

            currentGraphModel.Stencil.GetBlackboardProvider().AddItemRequested(Store, (IAction)null);
        }