예제 #1
0
	void Selector(SerializedProperty property) {
		SpineSlot attrib = (SpineSlot)attribute;
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
		if (data == null)
			return;

		GenericMenu menu = new GenericMenu();

		menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		for (int i = 0; i < data.Slots.Count; i++) {
			string name = data.Slots.Items[i].Name;
			if (name.StartsWith(attrib.startsWith)) {
				if (attrib.containsBoundingBoxes) {

					int slotIndex = i;

					List<Attachment> attachments = new List<Attachment>();
					foreach (var skin in data.Skins) {
						skin.FindAttachmentsForSlot(slotIndex, attachments);
					}

					bool hasBoundingBox = false;
					foreach (var attachment in attachments) {
						if (attachment is BoundingBoxAttachment) {
							menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
							hasBoundingBox = true;
							break;
						}
					}

					if (!hasBoundingBox)
						menu.AddDisabledItem(new GUIContent(name));
					

				} else {
					menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
				}
				
			}
				
		}

		menu.ShowAsContext();
	}
    protected override void showBodyContextMenu(Event evt)
    {
        MultiCurveTrack itemTrack = TargetTrack.Behaviour as MultiCurveTrack;
        if (itemTrack == null) return;

        Behaviour b = DirectorCopyPaste.Peek();

        PasteContext pasteContext = new PasteContext(evt.mousePosition, itemTrack);
        GenericMenu createMenu = new GenericMenu();
        if (b != null && DirectorHelper.IsTrackItemValidForTrack(b, itemTrack))
        {
            createMenu.AddItem(new GUIContent("Paste"), false, pasteItem, pasteContext);
        }
        else
        {
            createMenu.AddDisabledItem(new GUIContent("Paste"));
        }
        createMenu.ShowAsContext();
    }
예제 #3
0
        public virtual void ShowContextMenu()
        {
            var block     = target as Block;
            var flowchart = (Flowchart)block.GetFlowchart();

            if (flowchart == null)
            {
                return;
            }

            bool showCut    = false;
            bool showCopy   = false;
            bool showDelete = false;
            bool showPaste  = false;
            bool showPlay   = false;

            if (flowchart.SelectedCommands.Count > 0)
            {
                showCut    = true;
                showCopy   = true;
                showDelete = true;
                if (flowchart.SelectedCommands.Count == 1 && Application.isPlaying)
                {
                    showPlay = true;
                }
            }



            CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance();

            if (commandCopyBuffer.HasCommands())
            {
                showPaste = true;
            }

            GenericMenu commandMenu = new GenericMenu();

            if (showCut)
            {
                commandMenu.AddItem(new GUIContent("Cut"), false, Cut);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Cut"));
            }

            if (showCopy)
            {
                commandMenu.AddItem(new GUIContent("Copy"), false, Copy);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Copy"));
            }

            if (showPaste)
            {
                commandMenu.AddItem(new GUIContent("Paste"), false, Paste);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Paste"));
            }

            if (showDelete)
            {
                commandMenu.AddItem(new GUIContent("Delete"), false, Delete);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Delete"));
            }

            if (showPlay)
            {
                commandMenu.AddItem(new GUIContent("Play from selected"), false, PlayCommand);
                commandMenu.AddItem(new GUIContent("Stop all and play"), false, StopAllPlayCommand);
            }

            commandMenu.AddSeparator("");

            commandMenu.AddItem(new GUIContent("Select All"), false, SelectAll);
            commandMenu.AddItem(new GUIContent("Select None"), false, SelectNone);

            commandMenu.ShowAsContext();
        }
예제 #4
0
	void Selector(SerializedProperty property) {
		SpineBone attrib = (SpineBone)attribute;
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
		if (data == null)
			return;

		GenericMenu menu = new GenericMenu();

		menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		for (int i = 0; i < data.Bones.Count; i++) {
			string name = data.Bones.Items[i].Name;
			if (name.StartsWith(attrib.startsWith))
				menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
		}

		menu.ShowAsContext();
	}
예제 #5
0
        private void DoPopupMenu(EditorWindow console)
        {
            var listView    = consoleListViewField.GetValue(console);
            int listViewRow = listView != null ? (int)listViewStateRowField.GetValue(listView) : -1;

            if (listViewRow < 0)
            {
                return;
            }

            string text = (string)consoleActiveTextField.GetValue(console);

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

            GenericMenu codeViewPopupMenu = new GenericMenu();

            string[] lines = text.Split('\n');
            foreach (string line in lines)
            {
                int atAssetsIndex = line.IndexOf("(at Assets/");
                if (atAssetsIndex < 0)
                {
                    continue;
                }

                int functionNameEnd = line.IndexOf('(');
                if (functionNameEnd < 0)
                {
                    continue;
                }
                string functionName = line.Substring(0, functionNameEnd).TrimEnd(' ');

                int lineIndex = line.LastIndexOf(':');
                if (lineIndex <= atAssetsIndex)
                {
                    continue;
                }
                int atLine = 0;
                for (int i = lineIndex + 1; i < line.Length; ++i)
                {
                    char c = line[i];
                    if (c < '0' || c > '9')
                    {
                        break;
                    }
                    atLine = atLine * 10 + (c - '0');
                }

                atAssetsIndex += "(at ".Length;
                string assetPath  = line.Substring(atAssetsIndex, lineIndex - atAssetsIndex);
                string scriptName = assetPath.Substring(assetPath.LastIndexOf('/') + 1);

                string guid = AssetDatabase.AssetPathToGUID(assetPath);
                if (!string.IsNullOrEmpty(guid))
                {
                    codeViewPopupMenu.AddItem(
                        new GUIContent(scriptName + " - " + functionName.Replace(':', '.') + ", line " + atLine),
                        false,
                        () => {
                        bool openInSI = (openLogEntriesInSi2 || SISettings.handleOpenAssets) && !SISettings.dontOpenAssets;
                        if (EditorGUI.actionKey)
                        {
                            openInSI = !openInSI;
                        }
                        if (openInSI)
                        {
                            FGCodeWindow.addRecentLocationForNextAsset = true;
                            FGCodeWindow.OpenAssetInTab(guid, atLine);
                        }
                        else
                        {
                            FGCodeWindow.openInExternalIDE = true;
                            AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath(assetPath), atLine);
                        }
                    });
                }
            }

            if (codeViewPopupMenu.GetItemCount() > 0)
            {
                codeViewPopupMenu.AddSeparator(string.Empty);
                if (SISettings.handleOpenAssets || SISettings.dontOpenAssets)
                {
                    codeViewPopupMenu.AddDisabledItem(
                        new GUIContent("Open Call-Stack Entries in Script Inspector")
                        );
                }
                else
                {
                    codeViewPopupMenu.AddItem(
                        new GUIContent("Open Call-Stack Entries in Script Inspector"),
                        openLogEntriesInSi2,
                        () => { openLogEntriesInSi2 = !openLogEntriesInSi2; }
                        );
                }

                GUIUtility.hotControl = 0;
                codeViewPopupMenu.ShowAsContext();
                GUIUtility.ExitGUI();
            }
        }
    private void HandleAnchorContext(int controlID, JointHelpers.AnchorBias bias, AnchoredJoint2D joint,
        Joint2DSettingsBase joint2DSettings, Vector2 anchorPosition,
        Rigidbody2D connectedBody)
    {
        EditorHelpers.ContextClick(controlID, () => {
            var menu = new GenericMenu();
            menu.AddDisabledItem(new GUIContent(joint.GetType()
                                                     .Name));
            menu.AddSeparator("");
            if (WantsLocking()) {
                menu.AddItem(new GUIContent("Lock Anchors", GetAnchorLockTooltip()),
                    joint2DSettings.lockAnchors, () => {
                        EditorHelpers.RecordUndo(
                            joint2DSettings.lockAnchors ? "Unlock Anchors" : "Lock Anchors", joint2DSettings,
                            joint);
                        if (!joint2DSettings.lockAnchors) {
                            ReAlignAnchors(joint, bias);
                        }
                        joint2DSettings.lockAnchors = !joint2DSettings.lockAnchors;
                        EditorUtility.SetDirty(joint2DSettings);
                        EditorUtility.SetDirty(joint);
                    });
            }
            {
                var otherBias = JointHelpers.GetOppositeBias(bias);
                var otherPosition = JointHelpers.GetAnchorPosition(joint, otherBias);
                if (Vector2.Distance(otherPosition, anchorPosition) <= AnchorEpsilon) {
                    menu.AddDisabledItem(new GUIContent("Bring other anchor here"));
                } else {
                    menu.AddItem(new GUIContent("Bring other anchor here"), false, () => {
                        EditorHelpers.RecordUndo("Move Joint Anchor", joint);
                        JointHelpers.SetWorldAnchorPosition(joint, anchorPosition, otherBias);
                        EditorUtility.SetDirty(joint);
                    });
                }
            }

            menu.AddItem(new GUIContent("Enable Collision",
                "Should rigid bodies connected with this joint collide?"), joint.enableCollision,
                () => {
                    EditorHelpers.RecordUndo("Move Joint Anchor", joint);
                    joint.enableCollision = !joint.enableCollision;
                    EditorUtility.SetDirty(joint);
                });

            menu.AddSeparator("");

            var itemCount = menu.GetItemCount();

            ExtraMenuItems(menu, joint);

            if (itemCount != menu.GetItemCount()) {
                menu.AddSeparator("");
            }

            if (connectedBody) {
                var connectedBodyName = connectedBody.name;
                var selectConnectedBodyContent = new GUIContent(string.Format("Select '{0}'", connectedBodyName));
                if (isCreatedByTarget) {
                    menu.AddDisabledItem(selectConnectedBodyContent);
                } else {
                    menu.AddItem(selectConnectedBodyContent, false,
                        () => { Selection.activeGameObject = connectedBody.gameObject; });
                }
                menu.AddItem(new GUIContent(string.Format("Move ownership to '{0}'", connectedBodyName)), false, () => {
                    var connectedObject = connectedBody.gameObject;

                    var cloneJoint =
                        Undo.AddComponent(connectedObject, joint.GetType()) as AnchoredJoint2D;
                    if (!cloneJoint) {
                        return;
                    }
                    EditorUtility.CopySerialized(joint, cloneJoint);
                    cloneJoint.connectedBody = joint.GetComponent<Rigidbody2D>();

                    JointHelpers.SetWorldAnchorPosition(cloneJoint,
                        JointHelpers.GetAnchorPosition(joint, JointHelpers.AnchorBias.Main),
                        JointHelpers.AnchorBias.Connected);
                    JointHelpers.SetWorldAnchorPosition(cloneJoint,
                        JointHelpers.GetAnchorPosition(joint, JointHelpers.AnchorBias.Connected),
                        JointHelpers.AnchorBias.Main);

                    var jointSettings = SettingsHelper.GetOrCreate(joint);
                    var cloneSettings =
                        Undo.AddComponent(connectedObject, jointSettings.GetType()) as Joint2DSettingsBase;

                    if (cloneSettings == null) {
                        return;
                    }
                    cloneSettings.hideFlags = HideFlags.HideInInspector;

                    EditorUtility.CopySerialized(jointSettings, cloneSettings);
                    cloneSettings.Setup(cloneJoint);

                    cloneSettings.SetOffset(JointHelpers.AnchorBias.Main,
                        jointSettings.GetOffset(JointHelpers.AnchorBias.Connected));
                    cloneSettings.SetOffset(JointHelpers.AnchorBias.Connected,
                        jointSettings.GetOffset(JointHelpers.AnchorBias.Main));

                    if (!Selection.Contains(connectedObject)) {
                        var selectedObjects = new List<Object>(Selection.objects) {connectedObject};

                        if (selectedObjects.Contains(joint.gameObject)) {
                            selectedObjects.Remove(joint.gameObject);
                        }

                        Selection.objects = selectedObjects.ToArray();
                    }

                    Undo.DestroyObjectImmediate(joint);

                    OwnershipMoved(cloneJoint);
                });
                menu.AddItem(new GUIContent("Disconnect from '" + connectedBodyName + "'"), false, () => {
                    var worldConnectedPosition = JointHelpers.GetConnectedAnchorPosition(joint);

                    using (new Modification("Disconnect from connected body", joint)) {
                        joint.connectedBody = null;
                        JointHelpers.SetWorldConnectedAnchorPosition(joint, worldConnectedPosition);
                    }
                });
            } else {
                menu.AddDisabledItem(new GUIContent("Select connected body"));
                menu.AddDisabledItem(new GUIContent("Move ownership to connected body"));
                menu.AddDisabledItem(new GUIContent("Disconnect from connected body"));
            }

            menu.AddItem(new GUIContent("Delete " + joint.GetType()
                                                         .Name), false,
                () => Undo.DestroyObjectImmediate(joint));
            menu.ShowAsContext();
        });
    }
예제 #7
0
 internal static void Show(string folder, string currentSubFolder, Rect activatorRect, ProjectBrowser caller)
 {
     m_Caller = caller;
     string[] subFolders = AssetDatabase.GetSubFolders(folder);
     GenericMenu menu = new GenericMenu();
     if (subFolders.Length >= 0)
     {
         currentSubFolder = Path.GetFileName(currentSubFolder);
         foreach (string str in subFolders)
         {
             string fileName = Path.GetFileName(str);
             menu.AddItem(new GUIContent(fileName), fileName == currentSubFolder, new GenericMenu.MenuFunction(new ProjectBrowser.BreadCrumbListMenu(str).SelectSubFolder));
             menu.ShowAsContext();
         }
     }
     else
     {
         menu.AddDisabledItem(new GUIContent("No sub folders..."));
     }
     menu.DropDown(activatorRect);
 }
예제 #8
0
        public static void TagsMaskField(GUIContent changeLabel, GUIContent setLabel, ref Pathfinding.TagMask value)
        {
            GUILayout.BeginHorizontal();

            //Debug.Log (value.ToString ());
            EditorGUIUtility.LookLikeControls();
            EditorGUILayout.PrefixLabel(changeLabel, EditorStyles.layerMaskField);
            //GUILayout.FlexibleSpace ();
            //Rect r = GUILayoutUtility.GetLastRect ();

            string text = "";

            if (value.tagsChange == 0)
            {
                text = "Nothing";
            }
            else if (value.tagsChange == ~0)
            {
                text = "Everything";
            }
            else
            {
                text = System.Convert.ToString(value.tagsChange, 2);
            }

            if (GUILayout.Button(text, EditorStyles.layerMaskField, GUILayout.ExpandWidth(true)))
            {
                //Debug.Log ("pre");
                GenericMenu menu = new GenericMenu();

                menu.AddItem(new GUIContent("Everything"), value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask(~0, value.tagsSet));
                menu.AddItem(new GUIContent("Nothing"), value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask(0, value.tagsSet));

                for (int i = 0; i < 32; i++)
                {
                    bool on = (value.tagsChange >> i & 0x1) != 0;
                    Pathfinding.TagMask result = new Pathfinding.TagMask(on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1 << i, value.tagsSet);
                    menu.AddItem(new GUIContent("" + i), on, value.SetValues, result);
                    //value.SetValues (result);
                }

                menu.ShowAsContext();

                Event.current.Use();
                //Debug.Log ("Post");
            }

        #if UNITY_LE_4_3
            EditorGUIUtility.LookLikeInspector();
        #endif
            GUILayout.EndHorizontal();



            GUILayout.BeginHorizontal();

            //Debug.Log (value.ToString ());
            EditorGUIUtility.LookLikeControls();
            EditorGUILayout.PrefixLabel(setLabel, EditorStyles.layerMaskField);
            //GUILayout.FlexibleSpace ();
            //r = GUILayoutUtility.GetLastRect ();

            text = "";
            if (value.tagsSet == 0)
            {
                text = "Nothing";
            }
            else if (value.tagsSet == ~0)
            {
                text = "Everything";
            }
            else
            {
                text = System.Convert.ToString(value.tagsSet, 2);
            }

            if (GUILayout.Button(text, EditorStyles.layerMaskField, GUILayout.ExpandWidth(true)))
            {
                //Debug.Log ("pre");
                GenericMenu menu = new GenericMenu();

                if (value.tagsChange != 0)
                {
                    menu.AddItem(new GUIContent("Everything"), value.tagsSet == ~0, value.SetValues, new Pathfinding.TagMask(value.tagsChange, ~0));
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Everything"));
                }

                menu.AddItem(new GUIContent("Nothing"), value.tagsSet == 0, value.SetValues, new Pathfinding.TagMask(value.tagsChange, 0));

                for (int i = 0; i < 32; i++)
                {
                    bool enabled = (value.tagsChange >> i & 0x1) != 0;
                    bool on      = (value.tagsSet >> i & 0x1) != 0;

                    Pathfinding.TagMask result = new Pathfinding.TagMask(value.tagsChange, on ? value.tagsSet & ~(1 << i) : value.tagsSet | 1 << i);

                    if (enabled)
                    {
                        menu.AddItem(new GUIContent("" + i), on, value.SetValues, result);
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent("" + i));
                    }

                    //value.SetValues (result);
                }

                menu.ShowAsContext();

                Event.current.Use();
                //Debug.Log ("Post");
            }

        #if UNITY_LE_4_3
            EditorGUIUtility.LookLikeInspector();
        #endif
            GUILayout.EndHorizontal();


            //return value;
        }
예제 #9
0
    void buildAddTrackMenu_Drag()
    {
        bool hasTransform = true;
        bool hasAnimation = true;
        bool hasAudioSource = true;
        bool hasCamera = true;

        foreach(GameObject g in objects_window) {
            // break loop when all variables are false
            if(!hasTransform && !hasAnimation && !hasAudioSource && !hasCamera) break;

            if(hasTransform && !g.GetComponent(typeof(Transform))) {
                hasTransform = false;
            }
            if(hasAnimation && !g.GetComponent(typeof(Animation))) {
                hasAnimation = false;
            }
            if(hasAudioSource && !g.GetComponent(typeof(AudioSource))) {
                hasAudioSource = false;
            }
            if(hasCamera && !g.GetComponent(typeof(Camera))) {
                hasCamera = false;
            }
        }
        // add track menu
        menu_drag = new GenericMenu();

        // Translation
        if(hasTransform) { menu_drag.AddItem(new GUIContent("Translation"), false, addTrackFromMenu, (int)Track.Translation); }
        else { menu_drag.AddDisabledItem(new GUIContent("Translation")); }
        // Rotation
        if(hasTransform) { menu_drag.AddItem(new GUIContent("Rotation"), false, addTrackFromMenu, (int)Track.Rotation); }
        else { menu_drag.AddDisabledItem(new GUIContent("Rotation")); }
        // Orientation
        if(hasTransform) menu_drag.AddItem(new GUIContent("Orientation"), false, addTrackFromMenu, (int)Track.Orientation);
        else menu_drag.AddDisabledItem(new GUIContent("Orientation"));
        // Animation
        if(hasAnimation) menu_drag.AddItem(new GUIContent("Animation"), false, addTrackFromMenu, (int)Track.Animation);
        else menu_drag.AddDisabledItem(new GUIContent("Animation"));
        // Audio
        if(hasAudioSource) menu_drag.AddItem(new GUIContent("Audio"), false, addTrackFromMenu, (int)Track.Audio);
        else menu_drag.AddDisabledItem(new GUIContent("Audio"));
        // Property
        menu_drag.AddItem(new GUIContent("Property"), false, addTrackFromMenu, (int)Track.Property);
        // Event
        menu_drag.AddItem(new GUIContent("Event"), false, addTrackFromMenu, (int)Track.Event);
        // GO Active
        menu_drag.AddItem(new GUIContent("GO Active"), false, addTrackFromMenu, (int)Track.GOSetActive);

        if(oData.quickAdd_Combos.Count > 0) {
            // multiple tracks
            menu_drag.AddSeparator("");
            foreach(List<int> combo in oData.quickAdd_Combos) {
                string combo_name = "";
                for(int i = 0; i < combo.Count; i++) {
                    //combo_name += Enum.GetName(typeof(Track),combo[i])+" ";
                    combo_name += TrackNames[combo[i]] + " ";
                    if(i < combo.Count - 1) combo_name += "+ ";
                }
                if(canQuickAddCombo(combo, hasTransform, hasAnimation, hasAudioSource, hasCamera)) menu_drag.AddItem(new GUIContent(combo_name), false, addTrackFromMenu, 100 + oData.quickAdd_Combos.IndexOf(combo));
                else menu_drag.AddDisabledItem(new GUIContent(combo_name));
            }
        }
    }
        void DrawBackgroundTexture(Rect rect, int pass)
        {
            if (s_MaterialGrid == null)
            {
                s_MaterialGrid = new Material(Shader.Find("Hidden/PostProcessing/Editor/CurveGrid"))
                {
                    hideFlags = HideFlags.HideAndDontSave
                }
            }
            ;

            float scale = EditorGUIUtility.pixelsPerPoint;

        #if UNITY_2018_1_OR_NEWER
            const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.sRGB;
        #else
            const RenderTextureReadWrite kReadWrite = RenderTextureReadWrite.Linear;
        #endif

            var oldRt = RenderTexture.active;
            var rt    = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, kReadWrite);
            s_MaterialGrid.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
            s_MaterialGrid.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);

            Graphics.Blit(null, rt, s_MaterialGrid, pass);
            RenderTexture.active = oldRt;

            GUI.DrawTexture(rect, rt);
            RenderTexture.ReleaseTemporary(rt);
        }

        int DoCurveSelectionPopup(int id, bool hdr)
        {
            GUILayout.Label(s_Curves[id], EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));

            var lastRect = GUILayoutUtility.GetLastRect();
            var e        = Event.current;

            if (e.type == EventType.MouseDown && e.button == 0 && lastRect.Contains(e.mousePosition))
            {
                var menu = new GenericMenu();

                for (int i = 0; i < s_Curves.Length; i++)
                {
                    if (i == 4)
                    {
                        menu.AddSeparator("");
                    }

                    if (hdr && i < 4)
                    {
                        menu.AddDisabledItem(s_Curves[i]);
                    }
                    else
                    {
                        int current = i; // Capture local for closure
                        menu.AddItem(s_Curves[i], current == id, () => GlobalSettings.currentCurve = current);
                    }
                }

                menu.DropDown(new Rect(lastRect.xMin, lastRect.yMax, 1f, 1f));
            }

            return(id);
        }
    }
예제 #11
0
        public static void AddToMenu(GenericMenu menu, WindowState state)
        {
            var tracks = SelectionManager.SelectedTracks().ToArray();

            if (tracks.Length == 0)
            {
                return;
            }

            actions.ForEach(action =>
            {
                var subMenuPath  = string.Empty;
                var categoryAttr = GetCategoryAttribute(action);

                if (categoryAttr != null)
                {
                    subMenuPath = categoryAttr.Category;
                    if (!subMenuPath.EndsWith("/"))
                    {
                        subMenuPath += "/";
                    }
                }

                string displayName   = action.GetDisplayName(state, tracks);
                string menuItemName  = subMenuPath + displayName;
                var separator        = GetSeparator(action);
                var canBeAddedToMenu = !TypeUtility.IsHiddenInMenu(action.GetType());

                if (canBeAddedToMenu)
                {
                    Vector2?currentMousePosition = null;
                    if (Event.current != null)
                    {
                        currentMousePosition = Event.current.mousePosition;
                    }

                    action.mousePosition = currentMousePosition;
                    var displayState     = action.GetDisplayState(state, tracks);
                    if (displayState == MenuActionDisplayState.Visible && !IsActionActiveInMode(action, TimelineWindow.instance.currentMode.mode))
                    {
                        displayState = MenuActionDisplayState.Disabled;
                    }
                    action.mousePosition = null;

                    if (displayState == MenuActionDisplayState.Visible)
                    {
                        menu.AddItem(new GUIContent(menuItemName), action.IsChecked(state, tracks), f =>
                        {
                            action.Execute(state, tracks);
                        }, action);
                    }

                    if (displayState == MenuActionDisplayState.Disabled)
                    {
                        menu.AddDisabledItem(new GUIContent(menuItemName), action.IsChecked(state, tracks));
                    }

                    if (displayState != MenuActionDisplayState.Hidden && separator != null && separator.after)
                    {
                        menu.AddSeparator(subMenuPath);
                    }
                }
            });
        }
	void DrawTimelinePanel() {
		
		if (!enableTempPreview)
			playbackTime = eventInspector.GetPlaybackTime();
		
		
		GUILayout.BeginVertical(); {
			
			GUILayout.Space(10);
		
			GUILayout.BeginHorizontal(); {
				
				GUILayout.Space(20);
				
				playbackTime = Timeline(playbackTime);
				
				GUILayout.Space(10);
				
			}
			GUILayout.EndHorizontal();
			
			GUILayout.FlexibleSpace();
			
			GUILayout.BeginHorizontal(); {
				
                if (GUILayout.Button("Tools")) {
					GenericMenu menu = new GenericMenu();
					
					GenericMenu.MenuFunction2 callback = delegate(object obj) {
						int id = (int)obj;
						
						switch(id)
						{
							case 1:
							{
								stateClipboard = eventInspector.GetEvents(targetController, selectedLayer, targetState.GetFullPathHash(targetStateMachine));
								break;
							}
								
							case 2:
							{
								eventInspector.InsertEventsCopy(targetController, selectedLayer, targetState.GetFullPathHash(targetStateMachine), stateClipboard);
								break;
							}
								
							case 3:
							{
								controllerClipboard = eventInspector.GetEvents(targetController);
								break;
							}
							
							case 4:
							{
								eventInspector.InsertControllerEventsCopy(targetController, controllerClipboard);
								break;
							}
						}
					};
					
					if (targetState == null)
						menu.AddDisabledItem(new GUIContent("Copy All Events From Selected State"));
					else
						menu.AddItem(new GUIContent("Copy All Events From Selected State"), false, callback, 1);
					
					if (targetState == null || stateClipboard == null || stateClipboard.Length == 0)
						menu.AddDisabledItem(new GUIContent("Paste All Events To Selected State"));
					else
						menu.AddItem(new GUIContent("Paste All Events To Selected State"), false, callback, 2);
					
					if (targetController == null)
						menu.AddDisabledItem(new GUIContent("Copy All Events From Selected Controller"));
					else
						menu.AddItem(new GUIContent("Copy All Events From Selected Controller"), false, callback, 3);
					
					if (targetController == null || controllerClipboard == null || controllerClipboard.Count == 0)
						menu.AddDisabledItem(new GUIContent("Paste All Events To Selected Controller"));
					else
						menu.AddItem(new GUIContent("Paste All Events To Selected Controller"), false, callback, 4);
					
					
					
					menu.ShowAsContext();
				}
				
				GUILayout.FlexibleSpace();
				
				if (GUILayout.Button("Add", GUILayout.Width(80))) {
					MecanimEvent newEvent = new MecanimEvent();
					newEvent.normalizedTime = playbackTime;
					newEvent.functionName = "MessageName";
					newEvent.paramType = MecanimEventParamTypes.None;
					
					displayEvents.Add(newEvent);
					SortEvents();
					
					SetActiveEvent(newEvent);
					
					MecanimEventEditorPopup.Show(this, newEvent, GetConditionParameters());
				}
				
				if (GUILayout.Button("Del", GUILayout.Width(80))) {
					DelEvent(targetEvent);
				}
				
				EditorGUI.BeginDisabledGroup(targetEvent == null);
				
				if (GUILayout.Button("Copy", GUILayout.Width(80))) {
					clipboard = new MecanimEvent(targetEvent);
				}
				
				EditorGUI.EndDisabledGroup();
				
				EditorGUI.BeginDisabledGroup(clipboard == null);
				
				if (GUILayout.Button("Paste", GUILayout.Width(80))) {
					MecanimEvent newEvent = new MecanimEvent(clipboard);
					displayEvents.Add(newEvent);
					SortEvents();
					
					SetActiveEvent(newEvent);
				}
				
				EditorGUI.EndDisabledGroup();
				
				EditorGUI.BeginDisabledGroup(targetEvent == null);
				
				if (GUILayout.Button("Edit", GUILayout.Width(80))) {
					MecanimEventEditorPopup.Show(this, targetEvent, GetConditionParameters());
				}
				
				EditorGUI.EndDisabledGroup();
				
				if (GUILayout.Button("Save", GUILayout.Width(80))) {
					eventInspector.SaveData();
				}
				
				if (GUILayout.Button("Close", GUILayout.Width(80))) {
					Close();
				}
				
			}
			GUILayout.EndHorizontal();
		
		}
		GUILayout.EndVertical();
		
		if (enableTempPreview) {
			eventInspector.SetPlaybackTime(tempPreviewPlaybackTime);
			eventInspector.StopPlaying();
		}
		else {
			eventInspector.SetPlaybackTime(playbackTime);
		}
		
		SaveState();
	}
예제 #13
0
	void DrawMenu() {
		//if (GUILayout.Button("Create...", EditorStyles.toolbarButton))
		Color OldColor = GUI.backgroundColor;
		GUI.backgroundColor = new Color(1,1,1,1);
		GUILayout.BeginHorizontal(GUI.skin.GetStyle("Toolbar"));
		if (GUILayout.Button("File", GUI.skin.GetStyle("ToolbarDropDown")))
		{
			GenericMenu toolsMenu = new GenericMenu();

			//if (Selection.activeGameObject != null)
			//toolsMenu.AddItem(new GUIContent("New/Simple"), false, NewSimple);
			toolsMenu.AddItem(new GUIContent("New"), false, NewAdvanced);
			toolsMenu.AddItem(new GUIContent("Open"), false, Load);
			toolsMenu.AddSeparator("");
			if (CurrentFilePath!="")
			toolsMenu.AddItem(new GUIContent("Save"), false, Save);
			else
			toolsMenu.AddDisabledItem(new GUIContent("Save"));
			toolsMenu.AddItem(new GUIContent("Save as..."), false, SaveAs);

			toolsMenu.AddSeparator("");
			toolsMenu.AddItem(new GUIContent("Help"), false, OpenHelp);
			toolsMenu.AddSeparator("");
			//List<string> lst = new List<string>();
			/*lst.AddRange(GlobalSettings.RecentFiles);
			string[] lstArray = lst.Distinct().ToArray();
			for(int i=0;i<(lstArray.Length);i+=1)
			{
				toolsMenu.AddItem(new GUIContent("Open Recent/"+Path.GetFileName(lstArray[i])), false, Nothing,i);
			}*/
			//else
			//toolsMenu.AddDisabledItem(new GUIContent("Optimize Selected"));

			//toolsMenu.AddSeparator("");

			//toolsMenu.AddItem(new GUIContent("Help..."), false, Nothing);

			// Offset menu from right of editor window
			toolsMenu.DropDown(new Rect(5, 0, 0, 16));
			EditorGUIUtility.ExitGUI();
		}
		if (GUILayout.Button("View", GUI.skin.GetStyle("ToolbarDropDown")))
		{
			GenericMenu toolsMenu = new GenericMenu();

			//if (Selection.activeGameObject != null)
			//toolsMenu.AddItem(new GUIContent("New/Simple"), false, NewSimple);
			toolsMenu.AddItem(new GUIContent("Layer Names"), ViewLayerNames, SetViewLayerNames);
			toolsMenu.AddItem(new GUIContent("Flat Look"), Flatter, SetFlatter);
			toolsMenu.AddItem(new GUIContent("Blend Layer Icons"), BlendLayers, SetBlendLayers);
			toolsMenu.DropDown(new Rect(41, 0, 0, 16));
			EditorGUIUtility.ExitGUI();
		}
		if (GUILayout.Button("Previews",GUI.skin.GetStyle("ToolbarDropDown")))
		{
			GenericMenu toolsMenu = new GenericMenu();

			//if (Selection.activeGameObject != null)
			toolsMenu.AddItem(new GUIContent("Open Preview Window"), false, OpenPreview);
			toolsMenu.AddItem(new GUIContent("Realtime Preview Updates"), RealtimePreviewUpdates, SetRealtimePreviewUpdates);
			toolsMenu.AddItem(new GUIContent("Animate Layer Previews"), AnimateInputs, SetAnimateInputs);

			toolsMenu.DropDown(new Rect(83, 0, 0, 16));
			EditorGUIUtility.ExitGUI();
		}
		if (GUILayout.Button("Help",GUI.skin.GetStyle("ToolbarDropDown")))
		{
			GenericMenu toolsMenu = new GenericMenu();
			toolsMenu.AddItem(new GUIContent("Open Online Documentation"), false, OpenHelp);
			toolsMenu.AddItem(new GUIContent("Report Bug or Suggest Feature!"), false, SendFeedback);
			toolsMenu.AddItem(new GUIContent("See Bug and Feature Reports"), false, OpenFeedback);

			toolsMenu.DropDown(new Rect(146, 0, 0, 17));
			EditorGUIUtility.ExitGUI();
		}
//		Debug.Log("DrawMenu:"+Status);
		GUILayout.Button("Status: "+Status,GUI.skin.GetStyle("ToolbarButton"));
		//GUILayout.Label(Path.GetFileName(AssetDatabase.GetAssetPath(OpenShader)));
		GUILayout.FlexibleSpace();
		GUILayout.EndHorizontal();
		GUI.backgroundColor = OldColor;
	}	
예제 #14
0
    private void OnGUI_LinesTab()
    {
        if (settings.querier == null)
        {
            EditorGUILayout.HelpBox("EasyVoice could not automatically select a valid text-to-speech platform/option for the current platform.", MessageType.Warning);
        }

        EditorGUILayout.Separator();

        int outputCount = 0;
        int outputOkayCount = 0;
        int outputIssueCount = 0;
        int outputProblemCount = 0;

        bool createNewLine = false; // this gets trigerred by something in the middle of line drawing (we can't just create mid-list iteration), then creates a new line at the end

        // Cache current event stuff
        Event currentEvent = Event.current;
        EventType currentEventType = currentEvent.type;

        if (settings.data.LineCount() > 0)
        {
            // == HEADERS == //

            GUI.BeginGroup(spacingInfo.GetHeaderRect(), EditorStyles.toolbar);

            //GUI.Label("Dr", GUILayout.Width(SpacingInfo.dragWidth));
            if (GUI.Button(spacingInfo.GetFlagControlRect(), "O", GUI.skin.label))
            {
                GenericMenu outputMenu = new GenericMenu();
                outputMenu.AddItem(new GUIContent("Enable all"), false, Enable);
                outputMenu.AddItem(new GUIContent("Disable all"), false, Disable);
                outputMenu.ShowAsContext();
            }
            if (GUI.Button(spacingInfo.GetSpeakerNamePopupRect(), "Voice", GUI.skin.label))
            {
                GenericMenu outputMenu = new GenericMenu();
                outputMenu.AddItem(new GUIContent("Sort ascending"), false, SortSpeakerAscending);
                outputMenu.AddItem(new GUIContent("Sort descending"), false, SortSpeakerDescending);
                outputMenu.ShowAsContext();
            }
            GUI.Label(spacingInfo.GetSpeechTextRect(), "Text to say");
            if (GUI.Button(spacingInfo.GetFileNameTextRect(), "File/asset name", GUI.skin.label))
            {
                GenericMenu outputMenu = new GenericMenu();
                outputMenu.AddItem(new GUIContent("Sort ascending"), false, SortFileNameAscending);
                outputMenu.AddItem(new GUIContent("Sort descending"), false, SortFileNameDescending);
                outputMenu.ShowAsContext();
            }
            GUI.Label(spacingInfo.GetControlsRect(), "Action");
        
            GUI.EndGroup();

            // If we are in delete mode, then any de-focus
            if (deleteConfirmActive)
            {
                string focusedControl = GUI.GetNameOfFocusedControl();
                if (focusedControl != "LinesToggle" && focusedControl != "DeleteConfirmButton" && focusedControl != "DeleteCancelButton")
                    deleteConfirmActive = false;
            }

            // == LINES == //

            int issueStringHeight;
            string issueString = GetLineIssuesString(out issueStringHeight);
            if (deleteConfirmActive)
                issueStringHeight = 0; // we won't be printing issue list if delete confirm is active

            // Scroll view

            Rect scrollBoxLayoutRect = spacingInfo.GetScrollBoxLayoutRect(issueStringHeight);
            Rect scrollBoxContentRect = spacingInfo.GetScrollBoxContentRect(settings.data.LineCount(), scrollBoxLayoutRect);
            linesScrollPosition = GUI.BeginScrollView(scrollBoxLayoutRect, linesScrollPosition, scrollBoxContentRect);

            //GUI.Label(scrollBoxContentRect, logoTexture);
            //GUI.DrawTexture(scrollBoxContentRect, logoTexture);

            // Speaker names

            string[] speakerNames = settings.GetSpeakerNamesForEditor(true, false); // cache for performance

            // Drag

            // If we are dragging, decide whereabouts our new position is
            int dragInsertIndex = settings.data.LineCount(); // none by default
            if (LineDragInfo.dragging && LineDragInfo.lastLineY > -100000)
            {
                dragInsertIndex = (int)((LineDragInfo.lastLineY + SpacingInfo.lineHeight / 2) / (SpacingInfo.lineHeight + SpacingInfo.lineSpacing));
                dragInsertIndex = Mathf.Min(Mathf.Max(dragInsertIndex, 0), settings.data.LineCount());
                //Debug.Log("Drag drop index = " + dragInsertIndex);
            }

            // Drag & dropped objects

            AudioClip linkedClip = null;
            foreach (Object obj in DragAndDrop.objectReferences)
            {
                if (obj is AudioClip)
                {
                    linkedClip = (AudioClip)obj;
                    break;
                }
            }

            // Events

            // Check the mouse events related to dragging
            if (currentEventType == EventType.MouseUp)
            {
                if (LineDragInfo.dragging)
                {
                    LineDragInfo.dragging = false;
                    //Debug.Log("Done dragging line #" + LineDragInfo.draggedLineIndex + " -> " + dragInsertIndex);
                    if (LineDragInfo.draggedLineIndex != dragInsertIndex)
                        settings.data.MoveLine(LineDragInfo.draggedLineIndex, dragInsertIndex < LineDragInfo.draggedLineIndex ? dragInsertIndex : dragInsertIndex + 1); // it will do sanity checks within
                    currentEvent.Use();
                }
            }
            else if (currentEventType == EventType.MouseDrag)
            {
                if (LineDragInfo.dragging)
                {
                    currentEvent.Use(); // otherwise, UI won't update next frame
                    LineDragInfo.lastTrueMousePosition = currentEvent.mousePosition;
                    //Debug.Log("Dragging line #" + LineDragInfo.draggedLineIndex + ", line at " + LineDragInfo.lastLineY);
                }
            }

            if (currentEventType == EventType.dragUpdated)
            {
                DragAndDropInfo.lastTrueMousePosition = currentEvent.mousePosition;
            }

            // Now, go through all the data lines (we run 1 extra line for when we draw the dragged line above others)
            for (int lineIterator = 0; lineIterator <= settings.data.LineCount(); lineIterator++)
            {
                int lineIndex = 0;
                bool currentLineDragged = false;

                // When we are dragging, we always draw the dragged line last so that it is on top, so we wait for max lineIterator
                if (lineIterator == settings.data.LineCount())
                {
                    if (!LineDragInfo.dragging)
                        break;

                    currentLineDragged = true;
                    lineIndex = LineDragInfo.draggedLineIndex;
                }
                else
                {
                    lineIndex = lineIterator;
                }

                float currentLineY = SpacingInfo.GetLineY(lineIndex);

                // If we are dragging, adjust the line spacing
                if (LineDragInfo.dragging)
                {
                    if (lineIterator < settings.data.LineCount()) // for non-dragged lines
                    {
                        if (lineIndex >= dragInsertIndex && lineIndex < LineDragInfo.draggedLineIndex) // lines before move down, when we try to insert above them
                            currentLineY += SpacingInfo.lineHeight + SpacingInfo.lineSpacing;
                        if (lineIndex <= dragInsertIndex && lineIndex > LineDragInfo.draggedLineIndex) // lines after move up, wehn we try to insert below them
                            currentLineY -= SpacingInfo.lineHeight + SpacingInfo.lineSpacing;
                    }
                }

                if (LineDragInfo.dragging && LineDragInfo.draggedLineIndex == lineIterator) // not lineIndex
                {
                    //currentLineY = (SpacingInfo.lineHeight + SpacingInfo.lineSpacing) * lineIndex;
                    //GUI.backgroundColor = Color.black;
                    //GUILayout.BeginArea(spacingInfo.GetLineRect(currentLineY), "", GUI.skin.box);
                    //GUI.backgroundColor = Color.white;
                    //GUILayout.EndArea();
                    continue;
                }

                if (currentLineDragged)
                {
                    Rect lineRect = spacingInfo.GetLineRect(currentLineY);
                    lineRect.y += LineDragInfo.lastTrueMousePosition.y - LineDragInfo.dragStartMousePositionY;
                    lineRect.y = Mathf.Max(Mathf.Min(lineRect.y, (settings.data.LineCount() - 1) * (SpacingInfo.lineHeight + SpacingInfo.lineSpacing)), 0);
                    LineDragInfo.lastLineY = lineRect.y;
                    //GUI.backgroundColor = new Color(1,1,1,.5f); -- doesn't get any lighter, only tinted
                    GUILayout.BeginArea(lineRect, "", OurStyles.DraggedLine);
                    //GUI.backgroundColor = Color.white;
                }
                else
                {
                    GUILayout.BeginArea(spacingInfo.GetLineRect(currentLineY), "", OurStyles.Line);
                }
                //GUILayout.BeginHorizontal(GUI.skin.box);

                // == DRAG == //

                Rect dragControlRect = spacingInfo.GetDragControlRect();
                GUI.Label(dragControlRect, SafeTextureContent(dragLineTextureDark, dragLineTextureLight, "=", LineDragInfo.dragging ? null : "Drag to re-order line"));

                if (currentEventType == EventType.MouseDown)
                {
                    if (!LineDragInfo.dragging)
                    {
                        if (dragControlRect.Contains(currentEvent.mousePosition))
                        {
                            deleteConfirmActive = false; // Make sure delete confirm is disabled (no focus trigger here otherwise)
                            if (currentEvent.button == 0) // left
                            {
                                LineDragInfo.draggedLineIndex = lineIndex;
                                LineDragInfo.dragging = true;
                                LineDragInfo.lastTrueMousePosition = new Vector2(currentEvent.mousePosition.x, currentEvent.mousePosition.y + currentLineY);
                                LineDragInfo.dragStartMousePositionY = LineDragInfo.lastTrueMousePosition.y;
                                LineDragInfo.lastLineY = -100001;
                                //Debug.Log("Starting to drag line #" + LineDragInfo.draggedLineIndex + " at mouse " + LineDragInfo.dragStartMousePositionY);
                                GUI.FocusControl("LinesToggle"); // cancel any non-drag control focus
                                currentEvent.Use();
                            }
                            else
                            {
                                GenericMenu outputMenu = new GenericMenu();
                                if (lineIndex == 0)
                                    outputMenu.AddDisabledItem(new GUIContent("Move up"));
                                else
                                    outputMenu.AddItem(new GUIContent("Move up"), false, DragHandleContextMoveUp, lineIndex);
                                if (lineIndex == settings.data.LineCount() - 1)
                                    outputMenu.AddDisabledItem(new GUIContent("Move down"));
                                else
                                    outputMenu.AddItem(new GUIContent("Move down"), false, DragHandleContextMoveDown, lineIndex);
                                outputMenu.AddSeparator("");
                                if (lineIndex == 0)
                                    outputMenu.AddDisabledItem(new GUIContent("Move to top"));
                                else
                                    outputMenu.AddItem(new GUIContent("Move to top"), false, DragHandleContextMoveTop, lineIndex);
                                if (lineIndex == settings.data.LineCount() - 1)
                                    outputMenu.AddDisabledItem(new GUIContent("Move to bottom"));
                                else
                                    outputMenu.AddItem(new GUIContent("Move to bottom"), false, DragHandleContextMoveBottom, lineIndex);
                                outputMenu.AddSeparator("");
                                outputMenu.AddItem(new GUIContent("Duplicate line"), false, DragHandleContextDuplicate, lineIndex);
                                outputMenu.ShowAsContext();
                            }
                        }
                    }
                }

                // == FLAG == //

                bool currentOutputStatus = settings.data.GetOutputStatus(lineIndex);

                Rect outputFlagRect = spacingInfo.GetFlagControlRect();
                if (currentOutputStatus)
                {
                    LineIssue issues = settings.data.GetIssues(lineIndex);
                    if (EasyVoiceClipCreator.IssuePreventsFileMaking(issues))
                        GUI.color = EditorGUIUtility.isProSkin ? new Color(1f, 0.6f, 0.6f) : new Color(1f, 0.5f, 0.5f); // red
                    else
                        GUI.color = EditorGUIUtility.isProSkin ? new Color(0.6f, 1f, 0.6f) : new Color(0.5f, 1f, 0.5f); // green
                }
                bool newOutputStatus = EditorGUI.Toggle(outputFlagRect, currentOutputStatus);
                if (newOutputStatus != currentOutputStatus)
                {
                    settings.data.SetOutputStatus(lineIndex, newOutputStatus);
                    EasyVoiceIssueChecker.CheckLineIssues(lineIndex); // recheck it when toggling, while we are at it, no other way to manually recheck
                }
                GUI.color = Color.white;
                GUI.Label(outputFlagRect, new GUIContent("", "Toggle output of this line")); // Checbox doesn't show tooltips when mouseover check area

                //EditorGUILayout.Popup(settings.GetSourceIndex(settings.data.GetSpeakerSource(i)), speakerSources, GUILayout.Width(speakerSourceWidth));

                // == SPEAKER NAME == //

                string currentSpeakerName = settings.data.GetSpeakerName(lineIndex);
                if (settings.ValidVoiceName(currentSpeakerName, true))
                {
                    Rect speakerPopupRect = spacingInfo.GetSpeakerNamePopupRect();
                    settings.data.SetSpeakerName(lineIndex, settings.GetSpeakerName(
                        EditorGUI.Popup(speakerPopupRect, settings.GetSpeakerIndex(currentSpeakerName, true), speakerNames),
                        true));
                    GUI.Label(speakerPopupRect, new GUIContent("", "Choose a voice for this line")); // Popup needs content for each field for tooltips
                }
                else
                {
                    if (currentOutputStatus && settings.data.HasIssue(lineIndex, LineIssue.invalidSpeaker)) GUI.backgroundColor = Color.red;
                    Rect speakerTextRect = spacingInfo.GetSpeakerNameTextRect();
                    settings.data.SetSpeakerName(lineIndex, EditorGUI.TextField(speakerTextRect, settings.data.GetSpeakerName(lineIndex)));
                    GUI.backgroundColor = Color.white;
                    GUI.Label(speakerTextRect, new GUIContent("", "Enter a custom speaker name for this line")); // Text field doesn't show tooltips when mouseover edit area
                    if (GUI.Button(spacingInfo.GetSpeakerNameButtonRect(), new GUIContent("X", "Reset to default speaker name")))
                    {
                        settings.data.SetSpeakerName(lineIndex, EasyVoiceSettings.defaultSpeakerNameString);
                        GUI.FocusControl("LinesToggle"); // make sure we are not focused on a wrong control (probably speech edit box)
                    }
                }
                
                // == SPEECH TEXT == //

                string currentSpeechText = settings.data.GetSpeechText(lineIndex);

                bool needToFocusSpeechTextField = justCreatedLine && justCreatedLineIndex == lineIndex; // focus if this line was just created
                bool speechTextFieldFocused =
                    needToFocusSpeechTextField || // basically, we will focus it, so treat it as focused (and don't redraw again thus losing focus)
                    GUI.GetNameOfFocusedControl() == "SpeechTextField" + lineIndex;

                Rect speechTextRect = spacingInfo.GetSpeechTextRect();

                if (currentSpeechText == "" && !speechTextFieldFocused && (!forceNoPlaceholderFocus || forceNoPlaceholderFocusIndex != lineIndex))
                {
                    //GUI.contentColor = EditorGUIUtility.isProSkin ? Color.black : Color.gray; // Can't get free to work like this, pro works fine
                    GUI.SetNextControlName("SpeechTextField" + lineIndex);

                    if (currentOutputStatus) GUI.backgroundColor = Color.red;
                    EditorGUI.TextArea(speechTextRect, "<Enter text here>", OurStyles.EmptyTextFieldStyle);
                    if (currentOutputStatus) GUI.backgroundColor = Color.white;

                    //GUI.contentColor = Color.white;

                    if (lastFocusedControl != "SpeechTextField" + lineIndex && GUI.GetNameOfFocusedControl() == "SpeechTextField" + lineIndex)
                    {
                        GUI.FocusControl("LinesToggle");
                        forceNoPlaceholderFocus = true;
                        forceNoPlaceholderFocusIndex = lineIndex;
                    }
                }
                else
                {
                    bool pressedEnter = currentEventType == EventType.KeyUp && currentEvent.keyCode == KeyCode.Return; // must be before control consumes it
                    if (pressedEnter)
                    {
                        if (speechTextFieldFocused && settings.data.GetSpeechText(lineIndex) != "" && lineIndex == settings.data.LineCount() - 1)
                        {
                            //Debug.Log("Enter pressed on focused");
                            GUI.FocusControl("LinesToggle"); // unfocus edit field
                            createNewLine = true; // tell it to create a new line at the end
                            currentEvent.Use(); // don't process Enter again (it will trigger on the new line)
                        }
                        else if (lineIndex == settings.data.LineCount() - 1)
                        {
                            //Debug.Log("Enter pressed on unfocused");
                        }
                    }

                    GUI.SetNextControlName("SpeechTextField" + lineIndex);
                    settings.data.SetSpeechText(lineIndex, EditorGUI.TextArea(speechTextRect, currentSpeechText));

                    //if (lastFocusedControl != "SpeechTextField" + i && GUI.GetNameOfFocusedControl() == "SpeechTextField" + i)
                    //{
                    //    Debug.Log("Just got regular focused!");
                    //}
                }
                GUI.Label(speechTextRect, new GUIContent("", "Enter text to be spoken")); // Text field doesn't show tooltips when mouseover edit area

                if (currentEventType == EventType.Layout && (needToFocusSpeechTextField || (forceNoPlaceholderFocus && forceNoPlaceholderFocusIndex == lineIndex)))
                {
                    //GUI.FocusControl("SpeechTextField" + justCreatedLineIndex); //-- use below one for text fields
                    EditorGUI.FocusTextInControl("SpeechTextField" + lineIndex); // text fields also need to go into their editing state
                    if (GUI.GetNameOfFocusedControl() == "SpeechTextField" + lineIndex)
                    {
                        justCreatedLine = false;
                        forceNoPlaceholderFocus = false;
                    }
                }

                // == FILE NAME OR CLIP REFERENCE == //

                AudioClip ourClip = settings.data.GetClip(lineIndex);
                if (ourClip != null)
                {
                    // -- CLIP REFERENCE -- //
                    bool playingOurClip = playingPreviewClip && clipPlayer != null && ourClip == clipPlayer.clip;
                    if (GUI.Button(spacingInfo.GetFileNameClipPlayRect(), new GUIContent(SafeTextureContent(playingOurClip ? stopTextureDark : playTextureDark, playingOurClip ? stopTextureLight : playTextureLight, ">", "Play the clip")), OurStyles.SortButtonStyle))
                    {
                        PlayClip(ourClip);
                    }
                    if (settings.data.HasIssue(lineIndex, LineIssue.duplicateAssetFileName)) GUI.backgroundColor = Color.red; //new Color(1.0f, 0, 0.5f);
                    else if (settings.data.HasIssue(lineIndex, LineIssue.duplicateClipReference)) GUI.backgroundColor = Color.red; //new Color(1.0f, 0.4f, 0);
                    Rect fileClipRect = spacingInfo.GetFileNameClipFieldRect();
                    settings.data.SetClip(lineIndex, (AudioClip)EditorGUI.ObjectField(fileClipRect, ourClip, typeof(AudioClip), false));
                    GUI.backgroundColor = Color.white;
                    GUI.Label(fileClipRect, new GUIContent("", "Drop another AudioClip to replace currently linked file")); // Text field doesn't show tooltips when mouseover edit area
                    if (GUI.Button(spacingInfo.GetFileNameClipButtonRect(), new GUIContent(SafeTextureContent(unlinkTextureDark, unlinkTextureLight, "X", "Unlink from the asset and keep file name only")), OurStyles.SortButtonStyle))
                    {
                        settings.data.ClearClip(lineIndex);
                        GUI.FocusControl("LinesToggle"); // because the mouse can be in the text field next to it (showing old value)
                    }
                }
                else
                {
                    // -- FILE NAME -- //

                    if (settings.data.HasIssue(lineIndex, LineIssue.duplicateAssetFileName)) GUI.backgroundColor = Color.red; //new Color(1.0f, 0, 0.5f);
                    else if (settings.data.HasIssue(lineIndex, LineIssue.duplicateBaseFileName)) GUI.backgroundColor = Color.red; //new Color(1, 0, 0);
                    else if (settings.data.HasIssue(lineIndex, LineIssue.clashingExistingAsset) && settings.linkClips) GUI.backgroundColor = Color.red; //new Color(1.0f, 0, 1.0f);
                    else if (settings.data.HasIssue(lineIndex, LineIssue.badFileName)) GUI.backgroundColor = Color.red; //new Color(1, 0, 0);

                    Rect fileNameRect = spacingInfo.GetFileNameTextRect();

                    string currentFileName = settings.data.GetFileName(lineIndex);
                    if (currentFileName == EasyVoiceSettings.defaultFileNameString)
                    {
                        string currentFullFileName = settings.data.GetFileNameOrDefault(lineIndex);
                        string newValue = EditorGUI.TextField(fileNameRect, currentFullFileName, OurStyles.EmptyTextFieldStyle);
                        if (newValue != currentFullFileName) // only update if user manually changed something, otherwise it will write in the auto-generated value
                            settings.data.SetFileName(lineIndex, newValue, false);
                    }
                    else
                    {
                        settings.data.SetFileName(lineIndex, EditorGUI.TextField(fileNameRect, settings.data.GetFileName(lineIndex)), false);
                    }

                    if (currentEventType == EventType.DragUpdated || currentEventType == EventType.DragPerform)
                    {
                        if (DragAndDropInfo.lastTrueMousePosition != null)
                        {
                            Rect dropRect = new Rect(fileNameRect.x, fileNameRect.y + currentLineY, fileNameRect.width, fileNameRect.height);
                            if (dropRect.Contains((Vector2)DragAndDropInfo.lastTrueMousePosition)) // need to use last seen real mouse position
                            {
                                if (linkedClip != null)
                                {
                                    DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                                    //Debug.Log("Dropped for " + lineIndex + ", rect = " + dropRect + ", mouse = " + DragAndDropInfo.lastTrueMousePosition);
                                    if (currentEventType == EventType.DragPerform)
                                    {
                                        currentEvent.Use();
                                        settings.data.SetClip(lineIndex, linkedClip);
                                    }
                                }
                            }
                        }
                    }
                    GUI.backgroundColor = Color.white;

                    GUI.Label(fileNameRect, new GUIContent("", "Enter output file name here or drop an existing AudioClip")); // Text field doesn't show tooltips when mouseover edit area
                }


                // == CONTROLS == //

                if (deleteConfirmActive && lineIndex == deleteConfirmIndex)
                {
                    // -- DELETE PROMPT CONTOLS -- //

                    //GUILayout.Label("Rly?", GUILayout.Width(delConfirmLabelWidth));
                    GUIStyle smallTextButtonStyle = new GUIStyle(GUI.skin.button);
                    smallTextButtonStyle.fontSize = 9;
                    GUIStyle redButtonStyle = new GUIStyle(smallTextButtonStyle);
                    GUI.backgroundColor = Color.red;
                    GUI.SetNextControlName("DeleteConfirmButton");
                    if (GUI.Button(spacingInfo.GetDeleteConfirmButtonRect(), "Delete", redButtonStyle))
                    {
                        settings.data.DeleteLine(lineIndex); // deleteConfirmIndex == i
                        deleteConfirmActive = false;
                    }
                    GUI.SetNextControlName("DeleteCancelButton");
                    GUI.backgroundColor = Color.white;
                    if (GUI.Button(spacingInfo.GetDeleteCancelButtonRect(), "Cancel", smallTextButtonStyle))
                    {
                        deleteConfirmActive = false;
                    }

                    //GUILayout.EndArea();
                    //currentLineY = (SpacingInfo.lineHeight + SpacingInfo.lineSpacing) * lineIndex;
                    //GUILayout.BeginArea(spacingInfo.GetLineRect(currentLineY));
                    //TextAnchor current = GUI.skin.label.alignment;
                    //GUI.skin.label.alignment = TextAnchor.MiddleRight;
                    //GUILayout.Label("Are you sure you want to delete the above line?");
                    //GUI.skin.label.alignment = current;
                }
                else
                {
                    // -- REGULAR CONTROLS -- //

                    if (GUI.Button(spacingInfo.GetDeleteButtonRect(), new GUIContent("Delete", "Delete this line (this won't delete the created file if any)")))
                    {
                        deleteConfirmActive = true;
                        deleteConfirmIndex = lineIndex;
                        GUI.FocusControl("LinesToggle");
                    }
                    //else if (GUI.Button(spacingInfo.GetMoveDownButtonRect(), SafeTextureContent(arrowUpTexture, "U", "Move this line up"), sortButtonStyle))
                    //{
                    //    deleteConfirmActive = false; // since buttons don't grab focus
                    //    settings.data.MoveLineUp(lineIndex);
                    //    GUI.FocusControl("LinesToggle");
                    //}
                    //else if (GUI.Button(spacingInfo.GetMoveUpButtonRect(), SafeTextureContent(arrowDownTexture, "U", "Move this line down"), sortButtonStyle))
                    //{
                    //    deleteConfirmActive = false; // since buttons don't grab focus
                    //    settings.data.MoveLineDown(lineIndex);
                    //    GUI.FocusControl("LinesToggle");
                    //}
                }
                //GUILayout.EndHorizontal();

                //if (currentLineDragged)
                    GUILayout.EndArea();

                // Update out output okay/issue/error counters for summary
                if (settings.data.GetOutputStatus(lineIndex))
                {
                    if (settings.data.GetIssues(lineIndex) == 0)
                    {
                        outputCount++;
                        outputOkayCount++;
                    }
                    else
                    {
                        if (EasyVoiceClipCreator.IssuePreventsFileMaking(settings.data.GetIssues(lineIndex)))
                        {
                            outputProblemCount++;
                        }
                        else
                        {
                            outputCount++;
                            outputIssueCount++;
                        }
                    }
                }
            }

            GUI.EndScrollView();

            if (!deleteConfirmActive && issueString != "")
                EditorGUI.HelpBox(spacingInfo.GetIssueBoxRect(issueStringHeight), issueString, MessageType.Warning);
        }
        else
        {
            linesScrollPosition = EditorGUILayout.BeginScrollView(linesScrollPosition); // to match normal layout, with button at bottom

            EditorGUI.HelpBox(spacingInfo.GetNoLinesMessageRect(), "No lines have been added yet, click \"New line\" to add your first line.", MessageType.Info);

            GUI.EndScrollView();
        }

        if (currentEventType == EventType.DragExited || currentEventType == EventType.DragPerform)
        {
            DragAndDropInfo.lastTrueMousePosition = null;
        }

        GUI.BeginGroup(spacingInfo.GetFooterRect(), "", OurStyles.SettingsBox);

        if (deleteConfirmActive)
        {
            if (warningIconTexture != null) GUI.Label(new Rect(6, 6, 22, 22), new GUIContent(warningIconTexture));
            GUI.Label(new Rect(32, 7, 500, 20), "You have selected a line for deletion, click delete again to delete it or cancel.");
        }
        else
        {
            // We keep track of the label offset, then we measure the text we want to print and adjust this offset for further labels
            float labelOffset = 4;

            //// BETA VERSION TIMER
            //
            //GUI.Label(new Rect(labelOffset, 7, 210, 20), "RC (r143) DO NOT DISTRIBUTE");
            //
            //labelOffset += 200;
            //
            //if (DateTime.Now > new DateTime(2014, 10, 25))
            //{
            //    GUI.color = Color.red;
            //    GUI.Label(new Rect(labelOffset, 7, 200, 20), "      This version is expired!");
            //    GUI.color = Color.white;
            //}
            //else
            {
                if (createNewLine)
                {
                    // We need to create a new line, but this has to happen at the very end, i.e. here, so we just do that here
                    GUI.FocusControl("");
                    justCreatedLineIndex = settings.data.AddNewLine();
                    justCreatedLine = true;
                }
                else
                {
                    if (settings.data.LineCount() == 0) GUI.backgroundColor = Color.green;
                    if (GUI.Button(new Rect(labelOffset, 4, 100, 20), "New line"))
                    {
                        justCreatedLineIndex = settings.data.AddNewLine();
                        justCreatedLine = true;
                    }
                    if (settings.data.LineCount() == 0) GUI.backgroundColor = Color.white;
                }

                labelOffset += 104;

                if (settings.data.LineCount() > 0)
                {
                    if (outputCount == 0) GUI.enabled = false;
                    else GUI.backgroundColor = Color.green;
                    //if (GUI.Button(new Rect(108, 4, 100, 20), new GUIContent(outputCount > 0 ? "Create " + outputCount + " clips" : "Create clips", outputCount > 0 ? outputProblemCount > 0 ? "Create voice files for all error-free lines" : "Create voice files for all lines" : outputProblemCount > 0 ? "No error-free lines are selected for output, fix errors or select other lines" : "No lines are are selected for output, create more or select some lines first")))
                    if (GUI.Button(new Rect(labelOffset, 4, 100, 20), new GUIContent("Create voice", outputCount > 0 ? outputProblemCount > 0 ? "Create voice files for all error-free lines" : "Create voice files for all lines" : outputProblemCount > 0 ? "No error-free lines are selected for output, fix errors or select other lines" : "No lines are selected for output, create more or select some lines first")))
                    {
                        GUI.backgroundColor = Color.white;
                        switch (EasyVoiceClipCreator.CreateFilesPreCheck(settings))
                        {
                            case EasyVoiceClipCreator.CreateFilesCheckResult.ok:
                                CreateFiles();
                                break;

                            case EasyVoiceClipCreator.CreateFilesCheckResult.badDefaultFolder:
                                EditorUtility.DisplayDialog("Invalid directory", "The default directory you selected in the settings does not appear to be a valid sub-path of your Assets folder; please check your EasyVoice settings.", "Ok");
                                break;

                            case EasyVoiceClipCreator.CreateFilesCheckResult.missingDefaultFolder:
                                //if (EditorUtility.DisplayDialogComplex("Missing directory", "The default directory you selected in the settings does not exist.\r\nWould you like to attempt and create it first?", "Yes", "No", "Cancel") == 0)
                            {
                                string fullPath = settings.GetFullClipDefaultPath();
                                try
                                {
                                    Directory.CreateDirectory(fullPath);
                                    AssetDatabase.Refresh(); // immediate folder refresh, although below will do it too
                                    CreateFiles();
                                }
                                catch (Exception e)
                                {
                                    Debug.LogError("EasyVoice failed to create the missing folder \"" + fullPath + "\" with error: " + e);
                                }
                            }
                                break;

                            case EasyVoiceClipCreator.CreateFilesCheckResult.querierFailedToVerifyApp:
                                Debug.LogError("EasyVoice could not locate its application at \"" + EasyVoiceQuerierWinOS.FileName() + "\"");
                                break;
                        }
                    }
                    GUI.backgroundColor = Color.white;
                    if (outputCount == 0) GUI.enabled = true;
                }
                else
                {
                    GUI.enabled = false;
                    GUI.Button(new Rect(labelOffset, 4, 100, 20), new GUIContent("Create voice", "No lines have been created yet, create some lines first"));
                    GUI.enabled = true;
                }

                labelOffset += 112;

                if (outputOkayCount > 0)
                {
                    if (okayIconTexture != null) GUI.Label(new Rect(labelOffset, 6, 22, 22), new GUIContent(okayIconTexture));
                    //if (outputIssueCount > 0 || outputProblemCount > 0)
                    //{
                    string text = outputOkayCount + " line" + (outputOkayCount == 1 ? "" : "s") + " ready for output";
                    float textWidth = GUI.skin.label.CalcSize(new GUIContent(text)).x;
                    GUI.Label(new Rect(labelOffset + 24, 7, textWidth, 20), text);
                    labelOffset += textWidth + 40;
                    //}
                    //else
                    //{
                    //    string text = "All lines ready for output";
                    //    float textWidth = GUI.skin.label.CalcSize(new GUIContent(text)).x;
                    //    GUI.Label(new Rect(labelOffset + 24, 7, textWidth, 20), text); // redundant number
                    //    labelOffset += textWidth + 40;
                    //}

                }

                if (outputIssueCount > 0)
                {
                    if (warningIconTexture != null) GUI.Label(new Rect(labelOffset, 6, 22, 22), new GUIContent(warningIconTexture));
                    string text = outputIssueCount + " line" + (outputIssueCount == 1 ? " has" : "s have") + " minor issues";
                    float textWidth = GUI.skin.label.CalcSize(new GUIContent(text)).x;
                    GUI.Label(new Rect(labelOffset + 24, 7, textWidth, 20), text);
                    labelOffset += textWidth + 40;
                }

                if (outputProblemCount > 0)
                {
                    if (errorIconTexture != null) GUI.Label(new Rect(labelOffset, 6, 22, 22), new GUIContent(errorIconTexture));
                    string text = outputProblemCount + " line" + (outputProblemCount == 1 ? " has" : "s have") + " errors preventing output";
                    float textWidth = GUI.skin.label.CalcSize(new GUIContent(text)).x;
                    GUI.Label(new Rect(labelOffset + 24, 7, textWidth, 20), text);
                    labelOffset += textWidth + 40;
                }

                if (outputCount == 0 && outputIssueCount == 0 && outputProblemCount == 0)
                {
                    string text = "No lines selected for output";
                    float textWidth = GUI.skin.label.CalcSize(new GUIContent(text)).x;
                    GUI.Label(new Rect(labelOffset, 7, textWidth, 20), text);
                    labelOffset += textWidth + 40;
                }

            }
        }

        GUI.EndGroup();

        lastFocusedControl = GUI.GetNameOfFocusedControl();

        //Debug.Log("Verifications = " + EasyVoiceIssueChecker.verifyCount);
    }
예제 #15
0
	private void HandleNodeEvents (State node)
	{
		Event ev = Event.current;
		switch (ev.type) {
		case EventType.mouseDown:
			if (node.position.Contains (ev.mousePosition) && Event.current.button == 0) {
				isDraggingState = true;
			}

			if (node.position.Contains (ev.mousePosition) && Event.current.button == 1) {
				GenericMenu genericMenu = new GenericMenu ();
				genericMenu.AddItem (new GUIContent ("Make Transition"), false, new GenericMenu.MenuFunction2 (this.MakeTransitionCallback), node);
				if (!((State)node).isDefaultState && node.GetType() != typeof(AnyState) && !(node is BaseTrigger)) {
					genericMenu.AddItem (new GUIContent ("Set As Default"), false, new GenericMenu.MenuFunction2 (this.SetDefaultCallback), node);
				} else {
					genericMenu.AddDisabledItem (new GUIContent ("Set As Default"));
				}
				
				if(node.GetType() == typeof(AnyState)){
					genericMenu.AddDisabledItem (new GUIContent ("Delete"));
				}else{
					genericMenu.AddItem (new GUIContent ("Delete"), false, new GenericMenu.MenuFunction2 (this.DeleteStateCallback), node);
				}

				if(node.GetType() == typeof(AnyState)){
					genericMenu.AddDisabledItem (new GUIContent ("Copy"));
				}else{
					genericMenu.AddItem (new GUIContent ("Copy"), false, new GenericMenu.MenuFunction2 (this.CopyState), node);
				}
				if(copyOfState!= null && node.GetType() != typeof(AnyState) && copyOfState.id != node.id){
					genericMenu.AddItem (new GUIContent ("Paste"), false, new GenericMenu.MenuFunction2 (this.PasteState), node);
				}else{
					genericMenu.AddDisabledItem (new GUIContent ("Paste"));
				}
				genericMenu.ShowAsContext ();
				ev.Use ();
			}
			break;
		case EventType.mouseUp:
			isDraggingState = false;
			Selection.activeObject=node;
			break;
		case EventType.mouseDrag:
			if (isDraggingState) {
				selectedState.position.x += Event.current.delta.x;
				selectedState.position.y += Event.current.delta.y;
				
				if (selectedState.position.y < 10) {
					selectedState.position.y = 10;
				}
				if (selectedState.position.x <  10) {
					selectedState.position.x = 10;
				}
				ev.Use ();
			}
			break;
		}
		
		if (node.position.Contains (ev.mousePosition) && (ev.type != EventType.MouseDown || ev.button != 0 ? false : ev.clickCount == 1)) {
			if (selectedState != node) {
				OnStateSelectionChanged (node);
			}
		}
	}
예제 #16
0
 private void ShowContextMenu(ANode node)
 {
     if (_tree == null || !_tree.Nodes.Contains(node)) {
         return;
     }
     GenericMenu menu = new GenericMenu();
     if(node is AFlowNode) {
         if(node != _tree.Root) {
             menu.AddItem(new GUIContent("Make Root"), false, RootCallback, node);
         } else {
             menu.AddDisabledItem(new GUIContent("Make Root"));
         }
         menu.AddItem(new GUIContent("Connect"), false, ConnectCallback, node);
     } else {
         menu.AddDisabledItem(new GUIContent("Make Root"));
         menu.AddDisabledItem(new GUIContent("Connect"));
     }
     menu.AddSeparator("");
     menu.AddItem(new GUIContent("Delete"), false, DeleteCallback, node);
     menu.ShowAsContext();
 }
예제 #17
0
        /*public override string OnCompilerTransitionGeneration(FD.FlowWindow window) {
         *
         *      return Tpl.GenerateTransitionMethods(window);
         *
         * }
         *
         * public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {
         *
         *      if (windowTo.IsFunction() == true &&
         *          windowTo.IsSmall() == true &&
         *          windowTo.IsContainer() == false &&
         *          windowTo.GetFunctionId() > 0) {
         *
         *              return FlowFunctionsTemplateGenerator.GenerateTransitionMethod(this.flowEditor, windowFrom, windowTo);
         *
         *      }
         *
         *      return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);
         *
         * }*/

        /*public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {
         *
         *      if (windowTo.IsLinker() == true &&
         *              windowTo.GetLinkerId() > 0) {
         *
         *              var result = string.Empty;
         *
         *              var linkerWindow = FlowSystem.GetWindow(windowTo.GetLinkerId());
         *
         *              var className = linkerWindow.directory;
         *              var classNameWithNamespace = Tpl.GetNamespace(linkerWindow) + "." + Tpl.GetDerivedClassName(linkerWindow);
         *
         *              result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(windowFrom, linkerWindow, className, classNameWithNamespace);
         *
         *              WindowSystem.CollectCallVariations(linkerWindow.GetScreen(), (listTypes, listNames) => {
         *
         *                      result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(windowFrom, linkerWindow, className, classNameWithNamespace, listTypes, listNames);
         *
         *              });
         *
         *              return result;
         *
         *      }
         *
         *      return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);
         *
         * }*/

        /*public override string OnCompilerTransitionTypedAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName, System.Type[] types, string[] names) {
         *
         *      if (windowTo.IsLinker() == true &&
         *              windowTo.GetLinkerId() > 0) {
         *
         *              var result = string.Empty;
         *
         *              var window = FlowSystem.GetWindow(windowTo.GetLinkerId());
         *
         *              var className = window.directory;
         *              var classNameWithNamespace = Tpl.GetNamespace(window) + "." + Tpl.GetDerivedClassName(window);
         *
         *              result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(windowFrom, window, className, classNameWithNamespace);
         *
         *              WindowSystem.CollectCallVariations(windowTo.GetScreen(), (listTypes, listNames) => {
         *
         *                      result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(windowFrom, window, className, classNameWithNamespace, listTypes, listNames);
         *
         *              });
         *
         *              Debug.Log(className + " :: " + classNameWithNamespace + " == " + result);
         *
         *              return result;
         *
         *      }
         *
         *      return base.OnCompilerTransitionTypedAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName, types, names);
         *
         * }*/

        public override void OnFlowWindowGUI(FD.FlowWindow window)
        {
            var data = FlowSystem.GetData();

            if (data == null)
            {
                return;
            }

            var flag =
                (window.IsLinker() == true &&
                 window.IsSmall() == true &&
                 window.IsContainer() == false);

            if (flag == true)
            {
                var alreadyConnectedFunctionIds = new List <int>();

                // Find caller window
                var windowFrom = data.windowAssets.FirstOrDefault((item) => item.HasAttach(window.id));
                if (windowFrom != null)
                {
                    var attaches = windowFrom.GetAttachedWindows();
                    foreach (var attachWindow in attaches)
                    {
                        if (attachWindow.IsLinker() == true)
                        {
                            alreadyConnectedFunctionIds.Add(attachWindow.GetLinkerId());
                        }
                    }
                }

                foreach (var win in data.windowAssets)
                {
                    if (win.CanDirectCall() == true)
                    {
                        var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
                        if ((window.GetLinkerId() == win.id && count == 1) || count == 0)
                        {
                        }
                        else
                        {
                            if (win.id == window.GetLinkerId())
                            {
                                window.linkerId = 0;
                            }
                            alreadyConnectedFunctionIds.Remove(win.id);
                        }
                    }
                }

                var linkerId         = window.GetLinkerId();
                var linker           = linkerId == 0 ? null : data.GetWindow(linkerId);
                var isActiveSelected = true;

                var oldColor = GUI.color;
                GUI.color = isActiveSelected ? Color.white : Color.grey;
                var result = GUILayout.Button(linker != null ? string.Format("{0} ({1})", linker.title, linker.directory) : "None", FlowSystemEditorWindow.defaultSkin.button, GUILayout.ExpandHeight(true));
                GUI.color = oldColor;
                var rect = GUILayoutUtility.GetLastRect();
                rect.y += rect.height;

                if (result == true)
                {
                    System.Action <int> onApply = (int id) => {
                        var linkerSources = new List <FD.FlowWindow>();
                        foreach (var w in data.windowAssets)
                        {
                            if (w.AlreadyAttached(window.id) == true)
                            {
                                linkerSources.Add(w);
                            }
                        }

                        if (window.linkerId != 0)
                        {
                            foreach (var w in linkerSources)
                            {
                                data.Detach(w.id, window.linkerId, oneWay: true);
                            }
                        }

                        window.linkerId = id;

                        if (window.linkerId != 0)
                        {
                            foreach (var w in linkerSources)
                            {
                                data.Attach(w.id, window.linkerId, oneWay: true);
                            }
                        }
                    };

                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("None"), window.linkerId == 0, () => {
                        onApply(0);
                    });

                    if (windowFrom != null)
                    {
                        alreadyConnectedFunctionIds.Clear();
                        var attaches = windowFrom.GetAttachedWindows();
                        foreach (var attachWindow in attaches)
                        {
                            if (attachWindow.IsLinker() == true)
                            {
                                alreadyConnectedFunctionIds.Add(attachWindow.GetLinkerId());
                            }
                        }
                    }
                    foreach (var win in data.windowAssets)
                    {
                        if (win.CanDirectCall() == true)
                        {
                            var caption = new GUIContent(string.Format("{0} ({1})", win.title, win.directory));

                            var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
                            if ((window.GetLinkerId() == win.id && count == 1) || count == 0)
                            {
                                var id = win.id;
                                menu.AddItem(caption, win.id == window.GetLinkerId(), () => {
                                    onApply(id);
                                });
                            }
                            else
                            {
                                if (win.id == window.GetLinkerId())
                                {
                                    window.linkerId = 0;
                                }

                                alreadyConnectedFunctionIds.Remove(win.id);
                                menu.AddDisabledItem(caption);
                            }
                        }
                    }

                    menu.DropDown(rect);
                }
            }
        }
예제 #18
0
        private static void DoPrefabTypeGUI()
        {
            if (SkillEditor.SelectedFsmGameObject == null || SkillEditor.SelectedTemplate != null)
            {
                return;
            }
            bool   isModifiedPrefabInstance = SkillEditor.SelectedFsm.get_IsModifiedPrefabInstance();
            string text = "";

            if (isModifiedPrefabInstance)
            {
                text = Strings.get_Label_Modified_postfix();
            }
            switch (SkillEditor.Selection.ActiveFsmPrefabType)
            {
            case 0:
                if (GUILayout.Button(SkillEditorContent.MainToolbarPrefabTypeNone, EditorStyles.get_toolbarButton(), new GUILayoutOption[0]))
                {
                    SkillEditor.SelectFsmGameObject();
                    return;
                }
                break;

            case 1:
                if (GUILayout.Button(Strings.get_Label_Prefab(), EditorStyles.get_toolbarDropDown(), new GUILayoutOption[0]))
                {
                    GenericMenu genericMenu = new GenericMenu();
                    genericMenu.AddItem(new GUIContent(Strings.get_Menu_Select_Prefab()), false, new GenericMenu.MenuFunction(SkillEditor.SelectFsmGameObject));
                    genericMenu.AddItem(new GUIContent(Strings.get_Menu_Make_Instance()), false, new GenericMenu.MenuFunction(SkillEditor.InstantiatePrefab));
                    genericMenu.ShowAsContext();
                    return;
                }
                break;

            case 2:
                if (GUILayout.Button(Strings.get_Label_Model_Prefab(), EditorStyles.get_toolbarDropDown(), new GUILayoutOption[0]))
                {
                    GenericMenu genericMenu2 = new GenericMenu();
                    genericMenu2.AddItem(new GUIContent(Strings.get_Menu_Select_GameObject()), false, new GenericMenu.MenuFunction(SkillEditor.SelectFsmGameObject));
                    genericMenu2.AddItem(new GUIContent(Strings.get_Menu_Make_Instance()), false, new GenericMenu.MenuFunction(SkillEditor.InstantiatePrefab));
                    genericMenu2.ShowAsContext();
                    return;
                }
                break;

            case 3:
                if (GUILayout.Button(Strings.get_Label_Prefab_Instance() + text, EditorStyles.get_toolbarDropDown(), new GUILayoutOption[0]))
                {
                    GenericMenu genericMenu3 = new GenericMenu();
                    genericMenu3.AddItem(new GUIContent(Strings.get_Menu_Select_GameObject()), false, new GenericMenu.MenuFunction(SkillEditor.SelectFsmGameObject));
                    if (isModifiedPrefabInstance)
                    {
                        genericMenu3.AddItem(new GUIContent(Strings.get_Menu_Revert_To_Prefab()), false, new GenericMenu.MenuFunction(SkillEditor.ResetToPrefabState));
                    }
                    else
                    {
                        genericMenu3.AddDisabledItem(new GUIContent(Strings.get_Menu_Revert_To_Prefab()));
                    }
                    genericMenu3.AddItem(new GUIContent(Strings.get_Menu_Select_Prefab()), false, new GenericMenu.MenuFunction(SkillEditor.SelectPrefabParent));
                    genericMenu3.ShowAsContext();
                    return;
                }
                break;

            case 4:
                if (GUILayout.Button(Strings.get_Label_Model_Prefab_Instance(), EditorStyles.get_toolbarDropDown(), new GUILayoutOption[0]))
                {
                    GenericMenu genericMenu4 = new GenericMenu();
                    genericMenu4.AddItem(new GUIContent(Strings.get_Menu_Select_GameObject()), false, new GenericMenu.MenuFunction(SkillEditor.SelectFsmGameObject));
                    if (isModifiedPrefabInstance)
                    {
                        genericMenu4.AddItem(new GUIContent(Strings.get_Menu_Revert_To_Prefab()), false, new GenericMenu.MenuFunction(SkillEditor.ResetToPrefabState));
                    }
                    else
                    {
                        genericMenu4.AddDisabledItem(new GUIContent(Strings.get_Menu_Revert_To_Prefab()));
                    }
                    genericMenu4.AddItem(new GUIContent(Strings.get_Menu_Select_Prefab_Parent()), false, new GenericMenu.MenuFunction(SkillEditor.SelectPrefabParent));
                    genericMenu4.ShowAsContext();
                    return;
                }
                break;

            case 5:
                break;

            case 6:
                if (GUILayout.Button(Strings.get_Label_Prefab_Instance_disconnected(), EditorStyles.get_toolbarDropDown(), new GUILayoutOption[0]))
                {
                    GenericMenu genericMenu5 = new GenericMenu();
                    genericMenu5.AddItem(new GUIContent(Strings.get_Menu_Select_GameObject()), false, new GenericMenu.MenuFunction(SkillEditor.SelectFsmGameObject));
                    genericMenu5.AddItem(new GUIContent(Strings.get_Menu_Reconnect_to_Prefab()), false, new GenericMenu.MenuFunction(SkillEditor.ReconnectToLastPrefab));
                    genericMenu5.ShowAsContext();
                    return;
                }
                break;

            case 7:
                if (GUILayout.Button(Strings.get_Label_Model_Prefab_Instance_disconnected(), EditorStyles.get_toolbarDropDown(), new GUILayoutOption[0]))
                {
                    GenericMenu genericMenu6 = new GenericMenu();
                    genericMenu6.AddItem(new GUIContent(Strings.get_Menu_Select_GameObject()), false, new GenericMenu.MenuFunction(SkillEditor.SelectFsmGameObject));
                    genericMenu6.AddItem(new GUIContent(Strings.get_Menu_Reconnect_to_Prefab()), false, new GenericMenu.MenuFunction(SkillEditor.ReconnectToLastPrefab));
                    genericMenu6.ShowAsContext();
                }
                break;

            default:
                return;
            }
        }
예제 #19
0
        protected override void PopulateMenu(GenericMenu menu, SerializedProperty property, SpineAttachment targetAttribute, SkeletonData data)
        {
            ISkeletonComponent skeletonComponent = GetTargetSkeletonComponent(property);
            var validSkins = new List <Skin>();

            if (skeletonComponent != null && targetAttribute.currentSkinOnly)
            {
                var currentSkin = skeletonComponent.Skeleton.Skin;
                if (currentSkin != null)
                {
                    validSkins.Add(currentSkin);
                }
                else
                {
                    validSkins.Add(data.Skins.Items[0]);
                }
            }
            else
            {
                foreach (Skin skin in data.Skins)
                {
                    if (skin != null)
                    {
                        validSkins.Add(skin);
                    }
                }
            }

            var    attachmentNames  = new List <string>();
            var    placeholderNames = new List <string>();
            string prefix           = "";

            if (skeletonComponent != null && targetAttribute.currentSkinOnly)
            {
                menu.AddDisabledItem(new GUIContent((skeletonComponent as Component).gameObject.name + " (Skeleton)"));
            }
            else
            {
                menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
            }

            menu.AddSeparator("");
            menu.AddItem(new GUIContent("Null"), property.stringValue == "", HandleSelect, new SpineDrawerValuePair("", property));
            menu.AddSeparator("");

            Skin defaultSkin = data.Skins.Items[0];

            SerializedProperty slotProperty = property.serializedObject.FindProperty(targetAttribute.slotField);
            string             slotMatch    = "";

            if (slotProperty != null)
            {
                if (slotProperty.propertyType == SerializedPropertyType.String)
                {
                    slotMatch = slotProperty.stringValue.ToLower();
                }
            }

            foreach (Skin skin in validSkins)
            {
                string skinPrefix = skin.Name + "/";

                if (validSkins.Count > 1)
                {
                    prefix = skinPrefix;
                }

                for (int i = 0; i < data.Slots.Count; i++)
                {
                    if (slotMatch.Length > 0 && !(data.Slots.Items[i].Name.ToLower().Contains(slotMatch)))
                    {
                        continue;
                    }

                    attachmentNames.Clear();
                    placeholderNames.Clear();

                    skin.FindNamesForSlot(i, attachmentNames);
                    if (skin != defaultSkin)
                    {
                        defaultSkin.FindNamesForSlot(i, attachmentNames);
                        skin.FindNamesForSlot(i, placeholderNames);
                    }

                    for (int a = 0; a < attachmentNames.Count; a++)
                    {
                        string attachmentPath = attachmentNames[a];
                        string menuPath       = prefix + data.Slots.Items[i].Name + "/" + attachmentPath;
                        string name           = attachmentNames[a];

                        if (targetAttribute.returnAttachmentPath)
                        {
                            name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath;
                        }

                        if (targetAttribute.placeholdersOnly && !placeholderNames.Contains(attachmentPath))
                        {
                            menu.AddDisabledItem(new GUIContent(menuPath));
                        }
                        else
                        {
                            menu.AddItem(new GUIContent(menuPath), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
                        }
                    }
                }
            }
        }
예제 #20
0
        ///Get a menu for variable
        GenericMenu GetVariableMenu(Variable data, int index)
        {
            var menu = new GenericMenu();

            if (data.varType == typeof(VariableSeperator))
            {
                menu.AddItem(new GUIContent("Rename"), false, () => { (data.value as VariableSeperator).isEditingName = true; });
                menu.AddItem(new GUIContent("Remove"), false, () =>
                {
                    UndoUtility.RecordObject(contextObject, "Remove Variable");
                    bb.RemoveVariable(data.name);
                    UndoUtility.SetDirty(contextObject);
                });
                return(menu);
            }

            System.Action <PropertyInfo> BindProp = (p) =>
            {
                UndoUtility.RecordObject(contextObject, "Bind Variable");
                data.BindProperty(p);
                UndoUtility.SetDirty(contextObject);
            };
            System.Action <FieldInfo> BindField = (f) =>
            {
                UndoUtility.RecordObject(contextObject, "Bind Variable");
                data.BindProperty(f);
                UndoUtility.SetDirty(contextObject);
            };

            menu.AddDisabledItem(new GUIContent(string.Format("Type: {0}", data.varType.FriendlyName())));

            if (bb.propertiesBindTarget != null)
            {
                foreach (var comp in bb.propertiesBindTarget.GetComponents(typeof(Component)).Where(c => c != null))
                {
                    menu = EditorUtils.GetInstanceFieldSelectionMenu(comp.GetType(), data.varType, BindField, menu, "Bind (Self)");
                    menu = EditorUtils.GetInstancePropertySelectionMenu(comp.GetType(), data.varType, BindProp, false, false, menu, "Bind (Self)");
                }
                menu.AddSeparator("Bind (Self)/");
            }
            foreach (var type in TypePrefs.GetPreferedTypesList())
            {
                if (bb.propertiesBindTarget != null && typeof(UnityEngine.Component).RTIsAssignableFrom(type))
                {
                    menu = EditorUtils.GetInstanceFieldSelectionMenu(type, typeof(object), BindField, menu, "Bind (Self)");
                    menu = EditorUtils.GetInstancePropertySelectionMenu(type, typeof(object), BindProp, false, false, menu, "Bind (Self)");
                }
                menu = EditorUtils.GetStaticFieldSelectionMenu(type, data.varType, BindField, menu, "Bind (Static)");
                menu = EditorUtils.GetStaticPropertySelectionMenu(type, data.varType, BindProp, false, false, menu, "Bind (Static)");
            }

            menu.AddItem(new GUIContent("Duplicate"), false, () =>
            {
                UndoUtility.RecordObject(contextObject, "Duplicate Variable");
                data.Duplicate(bb);
                UndoUtility.SetDirty(contextObject);
            });

            if (bb is BlackboardSource)     //TODO: avoid this check (but Im too tired now)
            {
                if (!data.isPropertyBound)
                {
                    menu.AddItem(new GUIContent("Exposed Public"), data.isExposedPublic, () =>
                    {
                        UndoUtility.RecordObject(contextObject, "Modify Variable");
                        data.isExposedPublic = !data.isExposedPublic;
                        UndoUtility.SetDirty(contextObject);
                    });
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Bound Variables Can't Be Exposed"));
                }
            }

            menu.AddSeparator("/");
            if (data.isPropertyBound)
            {
                menu.AddItem(new GUIContent("UnBind"), false, () =>
                {
                    UndoUtility.RecordObject(contextObject, "UnBind Variable");
                    data.UnBind();
                    UndoUtility.SetDirty(contextObject);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("UnBind"));
            }


            var serProp = variablesProperty?.GetArrayElementAtIndex(index);

            if (serProp != null && serProp.prefabOverride)
            {
                var prefabAssetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(contextObject);
                var asset           = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(prefabAssetPath);
                menu.AddItem(new GUIContent("Apply Prefab Modification To '" + asset.name + "'"), false, () =>
                {
                    UndoUtility.RecordObject(asset, "Apply Variable To Prefab");
                    UndoUtility.RecordObject(contextObject, "Apply Variable To Prefab");
                    PrefabUtility.ApplyPropertyOverride(serProp, prefabAssetPath, InteractionMode.UserAction);
                    UndoUtility.SetDirty(contextObject);
                    UndoUtility.SetDirty(asset);
                });

                menu.AddItem(new GUIContent("Revert Prefab Modification"), false, () =>
                {
                    UndoUtility.RecordObject(contextObject, "Revert Variable From Prefab");
                    PrefabUtility.RevertPropertyOverride(serProp, InteractionMode.UserAction);
                    UndoUtility.SetDirty(contextObject);
                });
            }

            menu.AddItem(new GUIContent("Delete Variable"), false, () =>
            {
                if (EditorUtility.DisplayDialog("Delete Variable '" + data.name + "'", "Are you sure?", "Yes", "No"))
                {
                    UndoUtility.RecordObject(contextObject, "Delete Variable");
                    bb.RemoveVariable(data.name);
                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;
                    UndoUtility.SetDirty(contextObject);
                }
            });

            return(menu);
        }
예제 #21
0
		/*public override string OnCompilerTransitionGeneration(FD.FlowWindow window) {
			
			return Tpl.GenerateTransitionMethods(window);

		}
		
		public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {
			
			if (windowTo.IsFunction() == true && 
			    windowTo.IsSmall() == true &&
			    windowTo.IsContainer() == false &&
			    windowTo.GetFunctionId() > 0) {
				
				return FlowFunctionsTemplateGenerator.GenerateTransitionMethod(this.flowEditor, windowFrom, windowTo);

			}
			
			return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);
			
		}*/

		/*public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {
			
			if (windowTo.IsLinker() == true &&
				windowTo.GetLinkerId() > 0) {

				var result = string.Empty;

				var linkerWindow = FlowSystem.GetWindow(windowTo.GetLinkerId());

				var className = linkerWindow.directory;
				var classNameWithNamespace = Tpl.GetNamespace(linkerWindow) + "." + Tpl.GetDerivedClassName(linkerWindow);

				result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(windowFrom, linkerWindow, className, classNameWithNamespace);

				WindowSystem.CollectCallVariations(linkerWindow.GetScreen(), (listTypes, listNames) => {

					result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(windowFrom, linkerWindow, className, classNameWithNamespace, listTypes, listNames);

				});

				return result;

			}

			return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);

		}*/

		/*public override string OnCompilerTransitionTypedAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName, System.Type[] types, string[] names) {
			
			if (windowTo.IsLinker() == true &&
				windowTo.GetLinkerId() > 0) {

				var result = string.Empty;

				var window = FlowSystem.GetWindow(windowTo.GetLinkerId());

				var className = window.directory;
				var classNameWithNamespace = Tpl.GetNamespace(window) + "." + Tpl.GetDerivedClassName(window);

				result += TemplateGenerator.GenerateWindowLayoutTransitionMethod(windowFrom, window, className, classNameWithNamespace);

				WindowSystem.CollectCallVariations(windowTo.GetScreen(), (listTypes, listNames) => {

					result += TemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(windowFrom, window, className, classNameWithNamespace, listTypes, listNames);

				});

				Debug.Log(className + " :: " + classNameWithNamespace + " == " + result);

				return result;

			}
			
			return base.OnCompilerTransitionTypedAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName, types, names);
			
		}*/

		public override void OnFlowWindowGUI(FD.FlowWindow window) {

			var data = FlowSystem.GetData();
			if (data == null) return;

			var flag =
				(window.IsLinker() == true && 
				 window.IsSmall() == true &&
				 window.IsContainer() == false);

			if (flag == true) {
				
				var alreadyConnectedFunctionIds = new List<int>();

				// Find caller window
				var windowFrom = data.windowAssets.FirstOrDefault((item) => item.HasAttach(window.id));
				if (windowFrom != null) {
					
					var attaches = windowFrom.GetAttachedWindows();
					foreach (var attachWindow in attaches) {
						
						if (attachWindow.IsLinker() == true) {
							
							alreadyConnectedFunctionIds.Add(attachWindow.GetLinkerId());
							
						}
						
					}
					
				}
				
				foreach (var win in data.windowAssets) {

					if (win.CanDirectCall() == true) {

						var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
						if ((window.GetLinkerId() == win.id && count == 1) || count == 0) {
							
						} else {
							
							if (win.id == window.GetLinkerId()) window.linkerId = 0;
							alreadyConnectedFunctionIds.Remove(win.id);
							
						}

					}

				}

				var linkerId = window.GetLinkerId();
				var linker = linkerId == 0 ? null : data.GetWindow(linkerId);
				var isActiveSelected = true;

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayout.Button(linker != null ? string.Format("{0} ({1})", linker.title, linker.directory) : "None", FlowSystemEditorWindow.defaultSkin.button, GUILayout.ExpandHeight(true));
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					System.Action<int> onApply = (int id) => {

						var linkerSources = new List<FD.FlowWindow>();
						foreach (var w in data.windowAssets) {

							if (w.AlreadyAttached(window.id) == true) {

								linkerSources.Add(w);

							}

						}

						if (window.linkerId != 0) {

							foreach (var w in linkerSources) {

								data.Detach(w.id, window.linkerId, oneWay: true);

							}

						}

						window.linkerId = id;

						if (window.linkerId != 0) {

							foreach (var w in linkerSources) {

								data.Attach(w.id, window.linkerId, oneWay: true);

							}

						}

					};

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), window.linkerId == 0, () => {

						onApply(0);

					});

					if (windowFrom != null) {

						alreadyConnectedFunctionIds.Clear();
						var attaches = windowFrom.GetAttachedWindows();
						foreach (var attachWindow in attaches) {
							
							if (attachWindow.IsLinker() == true) {
								
								alreadyConnectedFunctionIds.Add(attachWindow.GetLinkerId());
								
							}
							
						}
						
					}
					foreach (var win in data.windowAssets) {
						
						if (win.CanDirectCall() == true) {

							var caption = new GUIContent(string.Format("{0} ({1})", win.title, win.directory));

							var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
							if ((window.GetLinkerId() == win.id && count == 1) || count == 0) {

								var id = win.id;
								menu.AddItem(caption, win.id == window.GetLinkerId(), () => {

									onApply(id);

								});

							} else {

								if (win.id == window.GetLinkerId()) window.linkerId = 0;

								alreadyConnectedFunctionIds.Remove(win.id);
								menu.AddDisabledItem(caption);

							}

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
예제 #22
0
            protected override void AddColumnHeaderContextMenuItems(GenericMenu menu)
            {
                var isFullMenuOverride = m_TableView.AddColumnHeaderContextMenuItems(menu);

                if (isFullMenuOverride)
                {
                    return;
                }

                var mousePosition       = Event.current.mousePosition;
                var windowMousePosition = Utils.Unclip(new Rect(mousePosition, Vector2.zero)).position;

                var activeColumn = currentColumnIndex;

                if (state.columns.Length > 1)
                {
                    for (int i = 0; i < state.columns.Length; ++i)
                    {
                        var column      = state.columns[i];
                        var menuContent = new GUIContent("Show Columns/" + GetDisplayLabel(column.headerContent));
                        if (state.visibleColumns.Length == 1 && state.visibleColumns.Contains(i))
                        {
                            menu.AddDisabledItem(menuContent, state.visibleColumns.Contains(i));
                        }
                        else
                        {
                            menu.AddItem(menuContent, state.visibleColumns.Contains(i), index => ToggleColumnVisibility((int)index), i);
                        }
                    }
                }


                if (activeColumn != -1)
                {
                    if (state.columns[activeColumn] is PropertyColumn pc && pc.userDataObj is SearchColumn sourceColumn)
                    {
                        m_TableView.AddColumnHeaderContextMenuItems(menu, sourceColumn);
                    }
                }

                // If the table view is readonly, we can't change the columns
                if (m_TableView.readOnly)
                {
                    return;
                }

                menu.AddSeparator("");
                menu.AddItem(EditorGUIUtility.TrTextContent("Add Column..."), false, () => m_TableView.AddColumn(windowMousePosition, activeColumn));

                if (activeColumn != -1)
                {
                    var colName = state.columns[activeColumn].headerContent.text;
                    menu.AddItem(EditorGUIUtility.TrTextContent($"Edit {colName}..."), false, EditColumn, activeColumn);
                    menu.AddItem(EditorGUIUtility.TrTextContent($"Remove {colName}"), false, () =>
                    {
                        if (state.columns.Length == 1)
                        {
                            ResetColumnLayout();
                        }
                        else
                        {
                            m_TableView.RemoveColumn(activeColumn);
                        }
                    });
                }

                menu.AddSeparator("");
                menu.AddItem(EditorGUIUtility.TrTextContent("Reset Columns"), false, ResetColumnLayout);
            }
예제 #23
0
    void BuildFileMenu()
    {
        _fileMenu = new GenericMenu();
        _fileMenu.AddItem(new GUIContent("New psai Soundtrack"), false, FileMenuCallback, "new");
        _fileMenu.AddItem(new GUIContent("Open psai Soundtrack"), false, FileMenuCallback, "open");
        if (EditorModel.Instance.ProjectDataChangedSinceLastSave)
        {
            _fileMenu.AddItem(new GUIContent("Save"), false, FileMenuCallback, "save");
        }
        else
        {
            _fileMenu.AddDisabledItem(new GUIContent("Save"));
        }

        if (EditorModel.Instance.Project != null)
        {
            _fileMenu.AddItem(new GUIContent("Save As"), false, FileMenuCallback, "saveas");
        }
        else
        {
            _fileMenu.AddDisabledItem(new GUIContent("Save As"));
        }

        _fileMenu.AddSeparator("");

        if (EditorModel.Instance.Project != null)
        {
            _fileMenu.AddItem(new GUIContent("Import Theme(s) from other psai Soundtrack"), false, FileMenuCallback, "import");
        }
        else
        {
            _fileMenu.AddDisabledItem(new GUIContent("Import Theme(s) from other psai Soundtrack"));
        }

        /*
        _fileMenu.AddSeparator("");
        if (EditorModel.Instance.Project != null && EditorModel.Instance.Project.Themes.Count > 0)
        {
            _fileMenu.AddItem(new GUIContent("Build Soundtrack"), false, FileMenuCallback, "export");
        }
        else
        {
            _fileMenu.AddDisabledItem(new GUIContent("Build Soundtrack"));
        }
         */
    }
예제 #24
0
        public static void DisplayDropdownMenu(Rect position, IList <MenuOption> options)
        {
            if (Mode == DisplayMode.Playback)
            {
                if (prepickedSelections.Count == 0)
                {
                    return;
                }

                int index;
                if (int.TryParse(prepickedSelections.Dequeue(), out index) == false)
                {
                    return;
                }

                if (index == -1)
                {
                    return;
                }

                MenuItem item = options[index] as MenuItem;
                if (item == null)
                {
                    return;
                }

                if (item.Func != null)
                {
                    item.Func();
                }
                else if (item.Func2 != null)
                {
                    item.Func2(item.UserData);
                }

                return;
            }

            GenericMenu menu = new GenericMenu();

            if (Mode == DisplayMode.Recording)
            {
                // DisplayDropdownMenu gets called several times according to the graphic elements
                // resulting in multiples enqueues for the same action. That is why is necessary to limit enqueues
                // to only 1 per selected DropDownItem.
                string value = "-1";
                if (recordedSelections.Contains(value) == false)
                {
                    recordedSelections.Enqueue("-1");
                }
            }

            for (int i = 0; i < options.Count; i++)
            {
                MenuOption closuredOption = options[i];

                if (closuredOption is MenuSeparator)
                {
                    menu.AddSeparator(closuredOption.Label.text);
                }
                else if (closuredOption is DisabledMenuItem)
                {
                    menu.AddDisabledItem(closuredOption.Label);
                }
                else
                {
                    MenuItem item = closuredOption as MenuItem;

                    Action itemCallback;

                    if (item.Func2 != null)
                    {
                        itemCallback = () => item.Func2(item.UserData);
                    }
                    else
                    {
                        itemCallback = () => item.Func();
                    }

                    GenericMenu.MenuFunction finalCallback = new GenericMenu.MenuFunction(itemCallback);

                    if (Mode == DisplayMode.Recording)
                    {
                        int closuredIndex = i;
                        finalCallback = () =>
                        {
                            recordedSelections.Enqueue(closuredIndex.ToString());
                            itemCallback();
                        };
                    }

                    menu.AddItem(closuredOption.Label, item.On, finalCallback);
                }
            }

            menu.DropDown(position);
        }
예제 #25
0
	private void ShowAddEventmenu(){
		GenericMenu genericMenu = new GenericMenu();
		for (int i = 0; i < (int)this.eventCallbackTypes.Length; i++)
		{
			bool flag = true;
			for (int j = 0; j < this.delegatesProperty.arraySize; j++)
			{
				if (this.delegatesProperty.GetArrayElementAtIndex(j).FindPropertyRelative("eventID").stringValue == eventCallbackTypes[i].text)
				{
					flag = false;
				}
			}
			if (!flag)
			{
				genericMenu.AddDisabledItem(this.eventCallbackTypes[i]);
			}
			else
			{
				genericMenu.AddItem(this.eventCallbackTypes[i], false, new GenericMenu.MenuFunction2(this.OnAddNewSelected), eventCallbackTypes[i].text);
			}
		}
		genericMenu.ShowAsContext();
		Event.current.Use();
	}
        void DrawSchemas(List <AddressableAssetGroupSchema> schemas)
        {
            GUILayout.Space(6);

            EditorGUILayout.BeginHorizontal();
            var activeProfileName = m_GroupTarget.Settings.profileSettings.GetProfileName(m_GroupTarget.Settings.activeProfileId);

            if (string.IsNullOrEmpty(activeProfileName))
            {
                m_GroupTarget.Settings.activeProfileId = null; //this will reset it to default.
                activeProfileName = m_GroupTarget.Settings.profileSettings.GetProfileName(m_GroupTarget.Settings.activeProfileId);
            }
            EditorGUILayout.PrefixLabel("Active Profile: " + activeProfileName);
            if (GUILayout.Button("Inspect Top Level Settings"))
            {
                EditorGUIUtility.PingObject(AddressableAssetSettingsDefaultObject.Settings);
                Selection.activeObject = AddressableAssetSettingsDefaultObject.Settings;
            }

            EditorGUILayout.EndHorizontal();
            GUILayout.Space(6);


            if (m_FoldoutState == null || m_FoldoutState.Length != schemas.Count)
            {
                m_FoldoutState = new bool[schemas.Count];
            }

            EditorGUILayout.BeginVertical();
            for (int i = 0; i < schemas.Count; i++)
            {
                var schema       = schemas[i];
                int currentIndex = i;

                DrawDivider();
                EditorGUILayout.BeginHorizontal();
                m_FoldoutState[i] = EditorGUILayout.Foldout(m_FoldoutState[i], AddressableAssetUtility.GetCachedTypeDisplayName(schema.GetType()));
                if (!m_GroupTarget.ReadOnly)
                {
                    GUILayout.FlexibleSpace();
                    GUIStyle gearIconStyle = UnityEngine.GUI.skin.FindStyle("IconButton") ?? EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector).FindStyle("IconButton");

                    if (EditorGUILayout.DropdownButton(EditorGUIUtility.IconContent("_Popup"), FocusType.Keyboard, gearIconStyle))
                    {
                        var menu = new GenericMenu();
                        menu.AddItem(AddressableAssetGroup.RemoveSchemaContent, false, () =>
                        {
                            if (EditorUtility.DisplayDialog("Remove selected schema?", "Are you sure you want to remove " + AddressableAssetUtility.GetCachedTypeDisplayName(schema.GetType()) + " schema?\n\nYou cannot undo this action.", "Yes", "No"))
                            {
                                m_GroupTarget.RemoveSchema(schema.GetType());
                                var newFoldoutstate = new bool[schemas.Count];
                                for (int j = 0; j < newFoldoutstate.Length; j++)
                                {
                                    if (j < i)
                                    {
                                        newFoldoutstate[j] = m_FoldoutState[j];
                                    }
                                    else
                                    {
                                        newFoldoutstate[j] = m_FoldoutState[i + 1];
                                    }
                                }

                                m_FoldoutState = newFoldoutstate;
                            }
                        });
                        menu.AddItem(AddressableAssetGroup.MoveSchemaUpContent, false, () =>
                        {
                            if (currentIndex > 0)
                            {
                                m_GroupTarget.Schemas[currentIndex]     = m_GroupTarget.Schemas[currentIndex - 1];
                                m_GroupTarget.Schemas[currentIndex - 1] = schema;
                                return;
                            }
                        });
                        menu.AddItem(AddressableAssetGroup.MoveSchemaDownContent, false, () =>
                        {
                            if (currentIndex < m_GroupTarget.Schemas.Count - 1)
                            {
                                m_GroupTarget.Schemas[currentIndex]     = m_GroupTarget.Schemas[currentIndex + 1];
                                m_GroupTarget.Schemas[currentIndex + 1] = schema;
                                return;
                            }
                        });
                        menu.AddSeparator("");
                        menu.AddItem(AddressableAssetGroup.ExpandSchemaContent, false, () =>
                        {
                            m_FoldoutState[currentIndex] = true;
                            foreach (var targetSchema in m_GroupTarget.Schemas)
                            {
                                targetSchema.ShowAllProperties();
                            }
                        });
                        menu.ShowAsContext();
                    }
                }

                EditorGUILayout.EndHorizontal();
                if (m_FoldoutState[i])
                {
                    try
                    {
                        EditorGUI.indentLevel++;
                        if (m_GroupTargets.Length == 1)
                        {
                            schema.OnGUI();
                        }
                        else
                        {
                            schema.OnGUIMultiple(GetSchemasForOtherTargets(schema));
                        }
                        EditorGUI.indentLevel--;
                    }
                    catch (Exception se)
                    {
                        Debug.LogException(se);
                    }
                }
            }

            if (schemas.Count > 0)
            {
                DrawDivider();
            }
            GUILayout.Space(4);
            EditorGUILayout.BeginHorizontal();

            GUILayout.FlexibleSpace();
            GUIStyle addSchemaButton = new GUIStyle(UnityEngine.GUI.skin.button);

            addSchemaButton.fontSize    = 12;
            addSchemaButton.fixedWidth  = 225;
            addSchemaButton.fixedHeight = 22;

            if (!m_GroupTarget.ReadOnly)
            {
                if (EditorGUILayout.DropdownButton(new GUIContent("Add Schema", "Add new schema to this group."), FocusType.Keyboard, addSchemaButton))
                {
                    var menu = new GenericMenu();
                    for (int i = 0; i < m_SchemaTypes.Count; i++)
                    {
                        var type = m_SchemaTypes[i];

                        if (m_GroupTarget.GetSchema(type) == null)
                        {
                            menu.AddItem(new GUIContent(AddressableAssetUtility.GetCachedTypeDisplayName(type), ""), false, () => OnAddSchema(type));
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent(AddressableAssetUtility.GetCachedTypeDisplayName(type), ""), true);
                        }
                    }

                    menu.ShowAsContext();
                }
            }

            GUILayout.FlexibleSpace();

            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }
	public static void TagsMaskField (GUIContent changeLabel, GUIContent setLabel,ref Pathfinding.TagMask value) {
		
		GUILayout.BeginHorizontal ();
		
		//Debug.Log (value.ToString ());
		EditorGUIUtility.LookLikeControls();
		EditorGUILayout.PrefixLabel (changeLabel,EditorStyles.layerMaskField);
		//GUILayout.FlexibleSpace ();
		//Rect r = GUILayoutUtility.GetLastRect ();
		
		string text = "";
		if (value.tagsChange == 0) text = "Nothing";
		else if (value.tagsChange == ~0) text = "Everything";
		else {
			text = System.Convert.ToString (value.tagsChange,2);
		}
		
		if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) {
			
			
			//Debug.Log ("pre");
			GenericMenu menu = new GenericMenu ();
			
			menu.AddItem (new GUIContent ("Everything"),value.tagsChange == ~0, value.SetValues, new Pathfinding.TagMask (~0,value.tagsSet));
			menu.AddItem (new GUIContent ("Nothing"),value.tagsChange == 0, value.SetValues, new Pathfinding.TagMask (0,value.tagsSet));
			
			for (int i=0;i<32;i++) {
				bool on = (value.tagsChange >> i & 0x1) != 0;
				Pathfinding.TagMask result = new Pathfinding.TagMask (on ? value.tagsChange & ~(1 << i) : value.tagsChange | 1<<i,value.tagsSet);
				menu.AddItem (new GUIContent (""+i),on,value.SetValues, result);
				//value.SetValues (result);
			}
			
			menu.ShowAsContext ();
			
			Event.current.Use ();
			//Debug.Log ("Post");
		}
		
		EditorGUIUtility.LookLikeInspector();
		GUILayout.EndHorizontal ();
		
		
		
		GUILayout.BeginHorizontal ();
		
		//Debug.Log (value.ToString ());
		EditorGUIUtility.LookLikeControls();
		EditorGUILayout.PrefixLabel (setLabel,EditorStyles.layerMaskField);
		//GUILayout.FlexibleSpace ();
		//r = GUILayoutUtility.GetLastRect ();
		
		text = "";
		if (value.tagsSet == 0) text = "Nothing";
		else if (value.tagsSet == ~0) text = "Everything";
		else {
			text = System.Convert.ToString (value.tagsSet,2);
		}
		
		if (GUILayout.Button (text,EditorStyles.layerMaskField,GUILayout.ExpandWidth (true))) {
			
			
			//Debug.Log ("pre");
			GenericMenu menu = new GenericMenu ();
			
			if (value.tagsChange != 0)	menu.AddItem (new GUIContent ("Everything"),value.tagsSet == ~0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,~0));
			else				menu.AddDisabledItem (new GUIContent ("Everything"));
			
			menu.AddItem (new GUIContent ("Nothing"),value.tagsSet == 0, value.SetValues, new Pathfinding.TagMask (value.tagsChange,0));
			
			for (int i=0;i<32;i++) {
				bool enabled = (value.tagsChange >> i & 0x1) != 0;
				bool on = (value.tagsSet >> i & 0x1) != 0;
				
				Pathfinding.TagMask result = new Pathfinding.TagMask (value.tagsChange, on ? value.tagsSet & ~(1 << i) : value.tagsSet | 1<<i);
				
				if (enabled)	menu.AddItem (new GUIContent (""+i),on,value.SetValues, result);
				else	menu.AddDisabledItem (new GUIContent (""+i));
				
				//value.SetValues (result);
			}
			
			menu.ShowAsContext ();
			
			Event.current.Use ();
			//Debug.Log ("Post");
		}
		
		EditorGUIUtility.LookLikeInspector();
		GUILayout.EndHorizontal ();
		
		
		//return value;
	}
        private void SinglePassStereoGUI(BuildTargetGroup targetGroup, SerializedProperty stereoRenderingPath)
        {
            if (!PlayerSettings.virtualRealitySupported)
            {
                return;
            }

            bool supportsMultiPass           = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.MultiPass);
            bool supportsSinglePass          = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.SinglePass);
            bool supportsSinglePassInstanced = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.Instancing);

            // populate the dropdown with the valid options based on target platform.
            int multiPassAndSinglePass           = 2;
            int validStereoRenderingOptionsCount = multiPassAndSinglePass + (supportsSinglePassInstanced ? 1 : 0);
            var validStereoRenderingPaths        = new GUIContent[validStereoRenderingOptionsCount];
            var validStereoRenderingValues       = new int[validStereoRenderingOptionsCount];

            GUIContent[] stereoRenderingPaths = GetStereoRenderingPaths(targetGroup);

            int addedStereoRenderingOptionsCount = 0;

            validStereoRenderingPaths[addedStereoRenderingOptionsCount]    = stereoRenderingPaths[(int)StereoRenderingPath.MultiPass];
            validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.MultiPass;

            validStereoRenderingPaths[addedStereoRenderingOptionsCount]    = stereoRenderingPaths[(int)StereoRenderingPath.SinglePass];
            validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.SinglePass;

            if (supportsSinglePassInstanced)
            {
                validStereoRenderingPaths[addedStereoRenderingOptionsCount]    = stereoRenderingPaths[(int)StereoRenderingPath.Instancing];
                validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.Instancing;
            }

            // setup fallbacks
            if (!supportsMultiPass && (stereoRenderingPath.intValue == (int)StereoRenderingPath.MultiPass))
            {
                stereoRenderingPath.intValue = (int)StereoRenderingPath.SinglePass;
                m_ShowMultiPassSRPInfoBox    = true;
            }

            if (!supportsSinglePassInstanced && (stereoRenderingPath.intValue == (int)StereoRenderingPath.Instancing))
            {
                stereoRenderingPath.intValue = (int)StereoRenderingPath.SinglePass;
            }

            if (!supportsSinglePass && (stereoRenderingPath.intValue == (int)StereoRenderingPath.SinglePass))
            {
                stereoRenderingPath.intValue = (int)StereoRenderingPath.MultiPass;
            }

            if (m_ShowMultiPassSRPInfoBox)
            {
                EditorGUILayout.HelpBox(Styles.multiPassNotSupportedWithSRP.text, MessageType.Info);
            }

            var rect = EditorGUILayout.GetControlRect();

            EditorGUI.BeginProperty(rect, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*"), stereoRenderingPath);
            rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*"));

            int index = Math.Max(0, Array.IndexOf(validStereoRenderingValues, stereoRenderingPath.intValue));

            if (EditorGUI.DropdownButton(rect, validStereoRenderingPaths[index], FocusType.Passive))
            {
                var menu = new GenericMenu();
                for (int i = 0; i < validStereoRenderingValues.Length; i++)
                {
                    int  value    = validStereoRenderingValues[i];
                    bool selected = (value == stereoRenderingPath.intValue);

                    if (!IsStereoRenderingModeSupported(targetGroup, (StereoRenderingPath)value))
                    {
                        menu.AddDisabledItem(validStereoRenderingPaths[i], selected);
                    }
                    else
                    {
                        menu.AddItem(validStereoRenderingPaths[i], selected, (object userData) => { OnStereoModeSelected(stereoRenderingPath, userData); }, value);
                    }
                }
                menu.DropDown(rect);
            }
            EditorGUI.EndProperty();

            if ((stereoRenderingPath.intValue == (int)StereoRenderingPath.SinglePass) && (targetGroup == BuildTargetGroup.Android))
            {
                var apisAndroid = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android);
                if ((apisAndroid.Length > 0) && (apisAndroid[0] == GraphicsDeviceType.OpenGLES3))
                {
                    if (supportsMultiPass)
                    {
                        EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning2.text, MessageType.Info);
                    }
                    else
                    {
                        EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning3.text, MessageType.Info);
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning.text, MessageType.Warning);
                }
            }
            else if ((stereoRenderingPath.intValue == (int)StereoRenderingPath.Instancing) && (targetGroup == BuildTargetGroup.Standalone))
            {
                EditorGUILayout.HelpBox(Styles.singlePassInstancedWarning.text, MessageType.Warning);
            }

            m_Settings.serializedObject.ApplyModifiedProperties();
        }
예제 #29
0
    void ShowAddTriggermenu()
    {
        // Now create the menu, add items and show it
        GenericMenu menu = new GenericMenu();
        for (int i = 0; i < m_EventTypes.Length; ++i){
            bool active = true;

            // Check if we already have a Entry for the current eventType, if so, disable it
            for (int p = 0; p < m_DelegatesProperty.arraySize; ++p){
                SerializedProperty delegateEntry = m_DelegatesProperty.GetArrayElementAtIndex(p);
                SerializedProperty eventProperty = delegateEntry.FindPropertyRelative("eventID");
                if (eventProperty.enumValueIndex == i){
                    active = false;
                }
            }

            if (active)
                menu.AddItem(m_EventTypes[i], false, OnAddNewSelected, i);
            else
                menu.AddDisabledItem(m_EventTypes[i]);
        }
        menu.ShowAsContext();
        Event.current.Use();
    }
예제 #30
0
        /// <summary>
        /// 绘制子项
        /// </summary>
        /// <param name="dialogue"></param>
        /// <param name="index"></param>
        private void DrawDialogueItem(ScenarioDialogue dialogue, int index)
        {
            bool foldOut = GetItemFoldOut(m_dialogueItemFoldOuts, index);

            if (foldOut)
            {
                GUILayout.Space(10);
            }
            GUILayout.Space(5);
            Rect rect = EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true));

            rect.width  += 12;
            rect.height += 10;
            rect.x      -= 9;
            rect.y      -= 4;
            GUI.Box(rect, "");
            //是否展开
            SetItemFoldOut(m_dialogueItemFoldOuts, index, EditorGUILayout.Foldout(GetItemFoldOut(m_dialogueItemFoldOuts, index), "", true, EditorStyles.label));

            Rect dialogueDisplayRect = new Rect(rect);

            dialogueDisplayRect.x     += 20;
            dialogueDisplayRect.width -= 30;
            dialogueDisplayRect.height = 18;
            dialogueDisplayRect.y     += 5;
            GUI.Label(dialogueDisplayRect, new GUIContent(m_target.GetLocalText(dialogue.text), m_target.GetLocalText(dialogue.text)));

            Rect menuRect = new Rect(rect);

            menuRect.height = 25;
            PBEditorUtils.ShowContextMenu(menuRect, () =>
            {
                GenericMenu menu = new GenericMenu();
                menu.AddDisabledItem(new GUIContent("Dialogue"));
                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Add"), false, OnMenuAddDialogueItem, index + 1);
                menu.AddItem(new GUIContent("Insert"), false, OnMenuAddDialogueItem, index);
                menu.AddItem(new GUIContent("Duplicate"), false, OnMenuInsertDialogueItem, index);
                menu.AddItem(new GUIContent("Delete"), false, OnMenuDeleteDialogueItem, dialogue);
                menu.ShowAsContext();
            });

            if (foldOut)
            {
                //绘制内部内容
                Rect subRect = new Rect(rect);
                subRect.width -= 3;
                //subRect.height += 10;
                subRect.x      += 3;
                subRect.y      += 32;
                subRect.height -= 50;
                GUI.Box(subRect, "");
                GUILayout.Space(15);

                PBEditorUtils.DrawCustomText(ref dialogue.key, "Key", customLabelWith, m_target);

                Rect lineRect = new Rect(subRect);
                lineRect.height = 2;
                lineRect.y     += 24;
                GUI.Box(lineRect, "");

                DrawCharacterGroup(dialogue, index);
                DrawDialogueText(dialogue, index);
                DrawSelectionGroup(dialogue, index);
                DrawCommandGroup(dialogue, index);

                OnDialogueItemGUI(dialogue, index);
                GUILayout.Space(3);
            }
            EditorGUILayout.EndVertical();
            GUILayout.Space(5);
            if (foldOut)
            {
                GUILayout.Space(10);
            }
        }
    void DrawTimelinePanel()
    {
        if (!enableTempPreview)
        {
            playbackTime = eventInspector.GetPlaybackTime();
        }


        GUILayout.BeginVertical();
        {
            GUILayout.Space(10);

            GUILayout.BeginHorizontal();
            {
                GUILayout.Space(20);

                playbackTime = Timeline(playbackTime);

                GUILayout.Space(10);
            }
            GUILayout.EndHorizontal();

            GUILayout.FlexibleSpace();

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button("Tools"))
                {
                    GenericMenu menu = new GenericMenu();

                    GenericMenu.MenuFunction2 callback = delegate(object obj) {
                        int id = (int)obj;

                        switch (id)
                        {
                        case 1:
                        {
                            stateClipboard = eventInspector.GetEvents(targetController, selectedLayer, targetState.GetFullPathHash(targetStateMachine));
                            break;
                        }

                        case 2:
                        {
                            eventInspector.InsertEventsCopy(targetController, selectedLayer, targetState.GetFullPathHash(targetStateMachine), stateClipboard);
                            break;
                        }

                        case 3:
                        {
                            controllerClipboard = eventInspector.GetEvents(targetController);
                            break;
                        }

                        case 4:
                        {
                            eventInspector.InsertControllerEventsCopy(targetController, controllerClipboard);
                            break;
                        }
                        }
                    };

                    if (targetState == null)
                    {
                        menu.AddDisabledItem(new GUIContent("Copy All Events From Selected State"));
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Copy All Events From Selected State"), false, callback, 1);
                    }

                    if (targetState == null || stateClipboard == null || stateClipboard.Length == 0)
                    {
                        menu.AddDisabledItem(new GUIContent("Paste All Events To Selected State"));
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Paste All Events To Selected State"), false, callback, 2);
                    }

                    if (targetController == null)
                    {
                        menu.AddDisabledItem(new GUIContent("Copy All Events From Selected Controller"));
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Copy All Events From Selected Controller"), false, callback, 3);
                    }

                    if (targetController == null || controllerClipboard == null || controllerClipboard.Count == 0)
                    {
                        menu.AddDisabledItem(new GUIContent("Paste All Events To Selected Controller"));
                    }
                    else
                    {
                        menu.AddItem(new GUIContent("Paste All Events To Selected Controller"), false, callback, 4);
                    }



                    menu.ShowAsContext();
                }

                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Add", GUILayout.Width(80)))
                {
                    MecanimEvent newEvent = new MecanimEvent();
                    newEvent.normalizedTime = playbackTime;
                    newEvent.functionName   = "MessageName";
                    newEvent.paramType      = MecanimEventParamTypes.None;

                    displayEvents.Add(newEvent);
                    SortEvents();

                    SetActiveEvent(newEvent);

                    MecanimEventEditorPopup.Show(this, newEvent, GetConditionParameters());
                }

                if (GUILayout.Button("Del", GUILayout.Width(80)))
                {
                    DelEvent(targetEvent);
                }

                EditorGUI.BeginDisabledGroup(targetEvent == null);

                if (GUILayout.Button("Copy", GUILayout.Width(80)))
                {
                    clipboard = new MecanimEvent(targetEvent);
                }

                EditorGUI.EndDisabledGroup();

                EditorGUI.BeginDisabledGroup(clipboard == null);

                if (GUILayout.Button("Paste", GUILayout.Width(80)))
                {
                    MecanimEvent newEvent = new MecanimEvent(clipboard);
                    displayEvents.Add(newEvent);
                    SortEvents();

                    SetActiveEvent(newEvent);
                }

                EditorGUI.EndDisabledGroup();

                EditorGUI.BeginDisabledGroup(targetEvent == null);

                if (GUILayout.Button("Edit", GUILayout.Width(80)))
                {
                    MecanimEventEditorPopup.Show(this, targetEvent, GetConditionParameters());
                }

                EditorGUI.EndDisabledGroup();

                if (GUILayout.Button("Save", GUILayout.Width(80)))
                {
                    eventInspector.SaveData();
                }

                if (GUILayout.Button("Close", GUILayout.Width(80)))
                {
                    Close();
                }
            }
            GUILayout.EndHorizontal();
        }
        GUILayout.EndVertical();

        if (enableTempPreview)
        {
            eventInspector.SetPlaybackTime(tempPreviewPlaybackTime);
            eventInspector.StopPlaying();
        }
        else
        {
            eventInspector.SetPlaybackTime(playbackTime);
        }

        SaveState();
    }
예제 #32
0
        protected override void OnInspectorDefaultGUI()
        {
            base.OnInspectorDefaultGUI();

            GUILayout.BeginHorizontal();
            EditorGUILayout.HelpBox("Finite state machine!", MessageType.Info);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            Toggle(Target.IsAutoRegister, out Target.IsAutoRegister, "Auto Register");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            TextField(Target.Name, out Target.Name, "Name");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            TextField(Target.Group, out Target.Group, "Group");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUI.color = Target.Data == "<None>" ? Color.gray : Color.white;
            GUILayout.Label("Data", GUILayout.Width(60));
            if (GUILayout.Button(Target.Data, EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm = new GenericMenu();
                gm.AddItem(new GUIContent("<None>"), Target.Data == "<None>", () =>
                {
                    Undo.RecordObject(target, "Set FSM Data Class");
                    Target.Data = "<None>";
                    HasChanged();
                });
                List <Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type =>
                {
                    return(type.IsSubclassOf(typeof(FSMDataBase)));
                });
                for (int i = 0; i < types.Count; i++)
                {
                    int j = i;
                    gm.AddItem(new GUIContent(types[j].FullName), Target.Data == types[j].FullName, () =>
                    {
                        Undo.RecordObject(target, "Set FSM Data Class");
                        Target.Data = types[j].FullName;
                        HasChanged();
                    });
                }
                gm.ShowAsContext();
            }
            GUI.color = Color.white;
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUI.enabled = Target.DefaultStateName != "";
            GUILayout.Label("Default: " + Target.DefaultStateName);
            GUI.enabled = true;
            GUILayout.FlexibleSpace();
            GUI.enabled = Target.StateNames.Count > 0;
            if (GUILayout.Button("Set Default", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm = new GenericMenu();
                for (int i = 0; i < Target.StateNames.Count; i++)
                {
                    int j = i;
                    gm.AddItem(new GUIContent(Target.StateNames[j]), Target.DefaultStateName == Target.StateNames[j], () =>
                    {
                        Undo.RecordObject(target, "Set FSM Default State");
                        Target.DefaultState     = Target.States[j];
                        Target.DefaultStateName = Target.StateNames[j];
                        HasChanged();
                    });
                }
                gm.ShowAsContext();
            }
            GUI.enabled = true;
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUI.enabled = Target.FinalStateName != "";
            GUILayout.Label("Final: " + Target.FinalStateName);
            GUI.enabled = true;
            GUILayout.FlexibleSpace();
            GUI.enabled = Target.StateNames.Count > 0;
            if (GUILayout.Button("Set Final", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm = new GenericMenu();
                for (int i = 0; i < Target.StateNames.Count; i++)
                {
                    int j = i;
                    gm.AddItem(new GUIContent(Target.StateNames[j]), Target.FinalStateName == Target.StateNames[j], () =>
                    {
                        Undo.RecordObject(target, "Set FSM Final State");
                        Target.FinalState     = Target.States[j];
                        Target.FinalStateName = Target.StateNames[j];
                        HasChanged();
                    });
                }
                gm.ShowAsContext();
            }
            GUI.enabled = true;
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical(EditorGlobalTools.Styles.Box);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Enabled State:");
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            for (int i = 0; i < Target.StateNames.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label(string.Format("{0}.{1}", i + 1, Target.StateNames[i]));
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Edit", EditorStyles.miniButtonLeft))
                {
                    MonoScriptToolkit.OpenMonoScript(Target.States[i]);
                }
                if (GUILayout.Button("Delete", EditorStyles.miniButtonRight))
                {
                    Undo.RecordObject(target, "Delete FSM State");

                    if (Target.DefaultStateName == Target.StateNames[i])
                    {
                        Target.DefaultState     = "";
                        Target.DefaultStateName = "";
                    }
                    if (Target.FinalStateName == Target.StateNames[i])
                    {
                        Target.FinalState     = "";
                        Target.FinalStateName = "";
                    }

                    Target.States.RemoveAt(i);
                    Target.StateNames.RemoveAt(i);

                    if (Target.DefaultStateName == "" && Target.StateNames.Count > 0)
                    {
                        Target.DefaultState     = Target.States[0];
                        Target.DefaultStateName = Target.StateNames[0];
                    }
                    if (Target.FinalStateName == "" && Target.StateNames.Count > 0)
                    {
                        Target.FinalState     = Target.States[0];
                        Target.FinalStateName = Target.StateNames[0];
                    }

                    HasChanged();
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add State", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm    = new GenericMenu();
                List <Type> types = ReflectionToolkit.GetTypesInRunTimeAssemblies(type =>
                {
                    return(type.IsSubclassOf(typeof(FiniteStateBase)));
                });
                for (int i = 0; i < types.Count; i++)
                {
                    int    j         = i;
                    string stateName = types[j].FullName;
                    FiniteStateNameAttribute fsmAtt = types[j].GetCustomAttribute <FiniteStateNameAttribute>();
                    if (fsmAtt != null)
                    {
                        stateName = fsmAtt.Name;
                    }

                    if (Target.States.Contains(types[j].FullName))
                    {
                        gm.AddDisabledItem(new GUIContent(stateName));
                    }
                    else
                    {
                        gm.AddItem(new GUIContent(stateName), false, () =>
                        {
                            Undo.RecordObject(target, "Add FSM State");
                            Target.States.Add(types[j].FullName);
                            Target.StateNames.Add(stateName);

                            if (Target.DefaultStateName == "")
                            {
                                Target.DefaultState     = Target.States[0];
                                Target.DefaultStateName = Target.StateNames[0];
                            }
                            if (Target.FinalStateName == "")
                            {
                                Target.FinalState     = Target.States[0];
                                Target.FinalStateName = Target.StateNames[0];
                            }
                            HasChanged();
                        });
                    }
                }
                gm.ShowAsContext();
            }
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
        }
예제 #33
0
 public void AddDisabledItem(GUIContent content)
 {
     _innerMenu.AddDisabledItem(content);
 }
예제 #34
0
파일: GitGUI.cs 프로젝트: Amitkapadi/UniGit
        public static void SecurePasswordField(Rect rect, GUIContent content, SecureString value)
        {
            int controlId = GUIUtility.GetControlID(_secureTextFieldHash, FocusType.Keyboard, rect);

            rect = EditorGUI.PrefixLabel(rect, content);
            EditorGUIUtility.AddCursorRect(rect, MouseCursor.Text);
            GUIStyle fieldStyle = EditorStyles.textField;
            Event    current    = Event.current;

            switch (current.GetTypeForControl(controlId))
            {
            case EventType.MouseDown:
                if (rect.Contains(current.mousePosition))
                {
                    GUIUtility.keyboardControl = controlId;
                    current.Use();
                }
                break;

            case EventType.KeyDown:
                if (GUIUtility.keyboardControl == controlId)
                {
                    if (!char.IsWhiteSpace(current.character) && current.character != '\0')
                    {
                        value.AppendChar(current.character);
                        GUI.changed = true;
                    }
                    else if (current.keyCode == KeyCode.Backspace)
                    {
                        if (value.Length > 0)
                        {
                            value.RemoveAt(value.Length - 1);
                            GUI.changed = true;
                        }
                    }
                    else if (current.character == '\n' || current.keyCode == KeyCode.Escape)
                    {
                        GUIUtility.keyboardControl = 0;
                    }
                    current.Use();
                }
                break;

            case EventType.ValidateCommand:
                Debug.Log(current.commandName);
                break;

            case EventType.KeyUp:
                if (GUIUtility.keyboardControl == controlId)
                {
                    current.Use();
                }
                break;

            case EventType.Repaint:
                fieldStyle.Draw(rect, GetTempContent("".PadRight(value != null ? value.Length : 0, '*')), controlId);
                break;

            case EventType.ContextClick:
                if (rect.Contains(current.mousePosition))
                {
                    GenericMenu menu = new GenericMenu();
                    if (value != null && value.Length > 0)
                    {
                        menu.AddItem(new GUIContent("Clear"), false, () =>
                        {
                            value.Clear();
                            GUI.changed = true;
                        });
                    }
                    else
                    {
                        menu.AddDisabledItem(new GUIContent("Clear"));
                    }
                    menu.ShowAsContext();
                }

                break;
            }
        }
예제 #35
0
            void InitializeCustomPostProcessesLists()
            {
                var hdrpAsset = HDRenderPipeline.defaultAsset;

                if (hdrpAsset == null)
                {
                    return;
                }

                var ppVolumeTypes = TypeCache.GetTypesDerivedFrom <CustomPostProcessVolumeComponent>();
                var ppVolumeTypeInjectionPoints = new Dictionary <Type, CustomPostProcessInjectionPoint>();

                foreach (var ppVolumeType in ppVolumeTypes)
                {
                    if (ppVolumeType.IsAbstract)
                    {
                        continue;
                    }

                    var comp = ScriptableObject.CreateInstance(ppVolumeType) as CustomPostProcessVolumeComponent;
                    ppVolumeTypeInjectionPoints[ppVolumeType] = comp.injectionPoint;
                    CoreUtils.Destroy(comp);
                }

                InitList(ref m_BeforeTransparentCustomPostProcesses, hdrpAsset.beforeTransparentCustomPostProcesses, "Before Transparent", CustomPostProcessInjectionPoint.BeforeTransparent);
                InitList(ref m_BeforePostProcessCustomPostProcesses, hdrpAsset.beforePostProcessCustomPostProcesses, "Before Post Process", CustomPostProcessInjectionPoint.BeforePostProcess);
                InitList(ref m_AfterPostProcessCustomPostProcesses, hdrpAsset.afterPostProcessCustomPostProcesses, "After Post Process", CustomPostProcessInjectionPoint.AfterPostProcess);

                void InitList(ref ReorderableList reorderableList, List <string> customPostProcessTypes, string headerName, CustomPostProcessInjectionPoint injectionPoint)
                {
                    // Sanitize the list:
                    customPostProcessTypes.RemoveAll(s => Type.GetType(s) == null);

                    reorderableList = new ReorderableList(customPostProcessTypes, typeof(string));
                    reorderableList.drawHeaderCallback = (rect) =>
                                                         EditorGUI.LabelField(rect, headerName, EditorStyles.boldLabel);
                    reorderableList.drawElementCallback = (rect, index, isActive, isFocused) =>
                    {
                        rect.height = EditorGUIUtility.singleLineHeight;
                        var elemType = Type.GetType(customPostProcessTypes[index]);
                        EditorGUI.LabelField(rect, elemType.ToString(), EditorStyles.boldLabel);
                    };
                    reorderableList.onAddCallback = (list) =>
                    {
                        var menu = new GenericMenu();

                        foreach (var kp in ppVolumeTypeInjectionPoints)
                        {
                            if (kp.Value == injectionPoint && !customPostProcessTypes.Contains(kp.Key.AssemblyQualifiedName))
                            {
                                menu.AddItem(new GUIContent(kp.Key.ToString()), false, () => customPostProcessTypes.Add(kp.Key.AssemblyQualifiedName));
                            }
                        }

                        if (menu.GetItemCount() == 0)
                        {
                            menu.AddDisabledItem(new GUIContent("No Custom Post Process Availble"));
                        }

                        menu.ShowAsContext();
                        EditorUtility.SetDirty(hdrpAsset);
                    };
                    reorderableList.onRemoveCallback = (list) =>
                    {
                        customPostProcessTypes.RemoveAt(list.index);
                        EditorUtility.SetDirty(hdrpAsset);
                    };
                    reorderableList.elementHeightCallback = _ => EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
                }
            }
예제 #36
0
        void CreateFileMenu(Rect position)
        {
            GenericMenu fileMenu = new GenericMenu();

            fileMenu.AddItem(new GUIContent("Overwrite Project Settings"), false, HandleFileMenuOption, 0);

            fileMenu.AddSeparator("");
            fileMenu.AddItem(new GUIContent("Save Project Inputs"), false, HandleFileMenuOption, 1);

            fileMenu.AddSeparator("");

            fileMenu.AddItem(new GUIContent("New Control Scheme"), false, HandleFileMenuOption, 2);
            if (IsControlSchemeSelected)
            {
                fileMenu.AddItem(new GUIContent("New Action"), false, HandleFileMenuOption, 3);
            }
            else
            {
                fileMenu.AddDisabledItem(new GUIContent("New Action"));
            }

            fileMenu.AddSeparator("");

            if (!selectionEmpty)
            {
                fileMenu.AddItem(new GUIContent("Duplicate"), false, HandleFileMenuOption, 4);
            }
            else
            {
                fileMenu.AddDisabledItem(new GUIContent("Duplicate"));
            }

            if (!selectionEmpty)
            {
                fileMenu.AddItem(new GUIContent("Delete"), false, HandleFileMenuOption, 5);
            }
            else
            {
                fileMenu.AddDisabledItem(new GUIContent("Delete"));
            }

            if (IsActionSelected)
            {
                fileMenu.AddItem(new GUIContent("Copy"), false, HandleFileMenuOption, 6);
            }
            else
            {
                fileMenu.AddDisabledItem(new GUIContent("Copy"));
            }

            if (m_copySource != null && IsActionSelected)
            {
                fileMenu.AddItem(new GUIContent("Paste"), false, HandleFileMenuOption, 7);
            }
            else
            {
                fileMenu.AddDisabledItem(new GUIContent("Paste"));
            }

            fileMenu.DropDown(position);
        }
예제 #37
0
        void UpdateMenuItems(GenericMenu menu)
        {
            SelectedDiffsGroupInfo groupInfo =
                mOperations.GetSelectedDiffsGroupInfo();

            DiffTreeViewMenuOperations operations =
                DiffTreeViewMenuUpdater.GetAvailableMenuOperations(groupInfo);

            if (operations == DiffTreeViewMenuOperations.None)
            {
                menu.AddDisabledItem(GetNoActionMenuItemContent());
                return;
            }

            bool isMultipleSelection = groupInfo.SelectedItemsCount > 1;
            bool selectionHasMeta    = mMetaMenuOperations.SelectionHasMeta();

            if (operations.HasFlag(DiffTreeViewMenuOperations.Diff))
            {
                menu.AddItem(mDiffMenuItemContent, false, DiffMenuItem_Click);
            }
            else
            {
                menu.AddDisabledItem(mDiffMenuItemContent, false);
            }

            if (mMetaMenuOperations.SelectionHasMeta())
            {
                if (operations.HasFlag(DiffTreeViewMenuOperations.Diff))
                {
                    menu.AddItem(mDiffMetaMenuItemContent, false, DiffMetaMenuItem_Click);
                }
                else
                {
                    menu.AddDisabledItem(mDiffMetaMenuItemContent);
                }
            }

            menu.AddSeparator(string.Empty);

            if (operations.HasFlag(DiffTreeViewMenuOperations.History))
            {
                menu.AddItem(mViewHistoryMenuItemContent, false, HistoryMenuItem_Click);
            }
            else
            {
                menu.AddDisabledItem(mViewHistoryMenuItemContent, false);
            }

            if (mMetaMenuOperations.SelectionHasMeta())
            {
                if (operations.HasFlag(DiffTreeViewMenuOperations.History))
                {
                    menu.AddItem(mViewHistoryMetaMenuItemContent, false, HistoryMetaMenuItem_Click);
                }
                else
                {
                    menu.AddDisabledItem(mViewHistoryMetaMenuItemContent, false);
                }
            }

            if (operations.HasFlag(DiffTreeViewMenuOperations.RevertChanges))
            {
                menu.AddSeparator(string.Empty);

                mRevertMenuItemContent.text = GetRevertMenuItemText(
                    isMultipleSelection,
                    selectionHasMeta);

                menu.AddItem(mRevertMenuItemContent, false, RevertMenuItem_Click);
            }

            if (operations.HasFlag(DiffTreeViewMenuOperations.Undelete) ||
                operations.HasFlag(DiffTreeViewMenuOperations.UndeleteToSpecifiedPaths))
            {
                menu.AddSeparator(string.Empty);
            }

            if (operations.HasFlag(DiffTreeViewMenuOperations.Undelete))
            {
                mUndeleteMenuItemContent.text = GetUndeleteMenuItemText(
                    isMultipleSelection,
                    selectionHasMeta);

                menu.AddItem(mUndeleteMenuItemContent, false, UndeleteMenuItem_Click);
            }

            if (operations.HasFlag(DiffTreeViewMenuOperations.UndeleteToSpecifiedPaths))
            {
                mUndeleteToSpecifiedPathMenuItemContent.text = GetUndeleteToSpecifiedPathMenuItemText(
                    isMultipleSelection,
                    selectionHasMeta);

                menu.AddItem(mUndeleteToSpecifiedPathMenuItemContent, false, UndeleteToSpecifiedPathMenuItem_Click);
            }
        }
        //-----------------------------------------------------------------------------------
        void DrawToolStrip()
        {
            GUILayout.BeginHorizontal(EditorStyles.toolbar);

            #region FX GameObject
            Rect fxButtonRect = GUILayoutUtility.GetRect(new GUIContent("FX GameObject"), EditorStyles.toolbarDropDown);
            if (GUI.Button(fxButtonRect, "FX GameObject", EditorStyles.toolbarDropDown))
            {
                GenericMenu fxMenu = new GenericMenu();
                if (Controller.BlockEdition)
                {
                    fxMenu.AddDisabledItem(new GUIContent("New FX"));
                    fxMenu.AddSeparator("");
                    fxMenu.AddDisabledItem(new GUIContent("Select FX in Hierarchy"));
                }
                else
                {
                    fxMenu.AddItem(new GUIContent("New FX"), false, Controller.CreateNewFx);
                    fxMenu.AddSeparator("");
                    fxMenu.AddItem(new GUIContent("Select FX in Hierarchy"), false, () =>
                    {
                        EditorGUIUtility.PingObject(FxData.gameObject);
                        Selection.activeGameObject = FxData.gameObject;
                    });
                    fxMenu.AddSeparator("");
                    fxMenu.AddItem(new GUIContent("Quit Edition"), false, () =>
                    {
                        Controller.Deinit();
                        Controller.FxData = null;
                        Close();
                    });
                }
                fxMenu.DropDown(new Rect(fxButtonRect.xMin, 0, 16, 16));
            }
            #endregion

            #region Scene FXs
            Event     evCurrent     = Event.current;
            EventType evCurrentType = evCurrent.type;

            string   longestName;
            string[] effectNames = Controller.GetFxNames(out longestName);

            GUIStyle fxRectStyle = EditorStyles.toolbarPopup;
            fxRectStyle.fontStyle = FontStyle.Bold;

            Rect effectRect = GUILayoutUtility.GetRect(new GUIContent(longestName), fxRectStyle);
            if ((evCurrentType == EventType.MouseDown && effectRect.Contains(evCurrent.mousePosition)) ||
                (Controller.CurrentFxIdx > (effectNames.Length - 1)))
            {
                Controller.RefreshEffectsArray();
                effectNames = Controller.GetFxNames(out longestName);
                Repaint();
            }

            EditorGUI.BeginDisabledGroup(Controller.BlockEdition);
            int fxIdx = EditorGUI.Popup(effectRect, Controller.CurrentFxIdx, effectNames, fxRectStyle);
            EditorGUI.EndDisabledGroup();
            if (fxIdx != Controller.CurrentFxIdx)
            {
                Controller.ChangeToFx(fxIdx);
            }
            #endregion

            #region SceneGUIOverlay
            Rect overlayRect = GUILayoutUtility.GetRect(new GUIContent("SceneGUI overlay"), EditorStyles.toolbarButton);
            EditorGUI.BeginChangeCheck();
            FxData.ShowOverlay = GUI.Toggle(overlayRect, FxData.ShowOverlay, new GUIContent("SceneGUI overlay"), EditorStyles.toolbarButton);
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(FxData);
            }
            #endregion

            GUILayout.FlexibleSpace();

            #region Help Menu
            Rect helpButtonRect = GUILayoutUtility.GetRect(new GUIContent("Help"), EditorStyles.toolbarDropDown);
            if (GUI.Button(helpButtonRect, "Help", EditorStyles.toolbarDropDown))
            {
                GenericMenu helpMenu = new GenericMenu();

                helpMenu.AddItem(new GUIContent("About CaronteFX..."), false, ShowAboutCaronteFXWindow);
                helpMenu.AddSeparator("");
                helpMenu.AddItem(new GUIContent("Reset CaronteFX"), false, Controller.ResetSimulation);
                helpMenu.DropDown(new Rect(helpButtonRect.x, 0, 16, 16));
            }
            #endregion

            GUILayout.EndHorizontal();
        }
예제 #39
0
파일: ReactEditor.cs 프로젝트: s76/testAI
    void OnGUIHasBeenDrawn()
    {
        if (BaseNode.hotNode == null)
            return;
        if (BaseNode.hotNode.activateContext) {
            // Now create the menu, add items and show it
            var menu = new GenericMenu ();
            var isParent = BaseNode.hotNode.IsParent ();
            var sequenceTypes = (from i in nodeTypes orderby i.Name where i.BaseType == typeof(React.BranchNode) select i).ToArray ();
            foreach (var t in sequenceTypes) {
                if (isParent)
                    menu.AddItem (new GUIContent ("Add/Branch/" + t.Name), false, AddToHotNode, t);
                menu.AddItem (new GUIContent ("Convert/Branch/" + t.Name), false, ConvertHotNode, t);
            }

            var leafTypes = (from i in nodeTypes orderby i.Name where i.BaseType == typeof(React.LeafNode) select i).ToArray ();
            foreach (var t in leafTypes) {
                if (isParent)
                    menu.AddItem (new GUIContent ("Add/Leaf/" + t.Name), false, AddToHotNode, t);
                menu.AddItem (new GUIContent ("Convert/Leaf/" + t.Name), false, ConvertHotNode, t);
            }

            var decoratorTypes = (from i in nodeTypes orderby i.Name where i.BaseType == typeof(React.DecoratorNode) select i).ToArray ();
            foreach (var t in decoratorTypes) {
                if (isParent)
                    menu.AddItem (new GUIContent ("Add/Decorator/" + t.Name), false, AddToHotNode, t);
                menu.AddItem (new GUIContent ("Convert/Decorator/" + t.Name), false, ConvertHotNode, t);
                menu.AddItem (new GUIContent ("Decorate/" + t.Name), false, DecorateHotNode, t);
            }

            menu.AddSeparator ("");
            Action hotNodeAction = BaseNode.hotNode as Action;
            if (hotNodeAction != null)
            {
                Dictionary< string, List< string > > actionsMap = BaseNode.editorReactable.CollectActionsMap();

                foreach (KeyValuePair<string, List<string> > kvp in actionsMap)
                {
                    foreach (string method in kvp.Value )
                    {
                        menu.AddItem(new GUIContent("Set Action/" + kvp.Key + "/" + method), false, SetActionMethod, new KeyValuePair<string, string>( kvp.Key, method ) );
                    }
                }
            }

            Condition hotNodeCondition = BaseNode.hotNode as Condition;
            If hotNodeIf = BaseNode.hotNode as If;
            if (hotNodeCondition != null || hotNodeIf != null )
            {
                Dictionary< string, List< string > > actionsMap = BaseNode.editorReactable.CollectConditionsMap();

                foreach (KeyValuePair<string, List<string> > kvp in actionsMap)
                {
                    foreach (string method in kvp.Value )
                    {
                        menu.AddItem(new GUIContent("Set Condition/" + kvp.Key + "/" + method), false, SetConditionMethod, new KeyValuePair<string, string>(kvp.Key, method));
                    }
                }
            }

            menu.AddSeparator("");

            menu.AddItem (new GUIContent ("Cut"), false, OnCut);
            menu.AddItem (new GUIContent ("Copy"), false, OnCopy);
            if (isParent)
                menu.AddItem (new GUIContent ("Paste"), false, OnPaste);
            else
                menu.AddDisabledItem (new GUIContent ("Paste"));
            menu.AddItem (new GUIContent ("Duplicate"), false, OnDuplicate);
            menu.AddItem (new GUIContent ("Delete"), false, OnDelete);

            if (BaseNode.hotNode.HasAnyChildren())
            {
                if (BaseNode.hotNode.hideChildren)
                {
                    menu.AddItem(new GUIContent("Show"), false, OnShowChildren );
                }
                else
                {
                    menu.AddItem(new GUIContent("Hide"), false, OnHideChildren );
                }
            }

            menu.ShowAsContext ();
        }
    }
예제 #40
0
        public static ReorderableList CreateTileViewReorderableList(Tileset tileset)
        {
            ReorderableList tileViewRList = new ReorderableList(tileset.TileViews, typeof(TileView), true, true, true, true);

            tileViewRList.onAddDropdownCallback = (Rect buttonRect, ReorderableList l) => {
                GenericMenu menu = new GenericMenu();
                GenericMenu.MenuFunction addTileSelectionFunc = () => {
                    TileSelection tileSelection = tileset.TileSelection.Clone();
                    tileSelection.FlipVertical(); // flip vertical to fit the tileset coordinate system ( from top to bottom )
                    tileset.AddTileView("new TileView", tileSelection);
                    EditorUtility.SetDirty(tileset);
                };
                GenericMenu.MenuFunction addBrushSelectionFunc = () => {
                    TileSelection tileSelection = BrushBehaviour.CreateTileSelection();
                    tileset.AddTileView("new TileView", tileSelection);
                    EditorUtility.SetDirty(tileset);
                };
                GenericMenu.MenuFunction removeAllTileViewsFunc = () => {
                    if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete all the TileViews?", "Yes", "No"))
                    {
                        tileset.RemoveAllTileViews();
                        EditorUtility.SetDirty(tileset);
                    }
                };
                if (tileset.TileSelection != null)
                {
                    menu.AddItem(new GUIContent("Add Tile Selection"), false, addTileSelectionFunc);
                }
                else
                {
                    menu.AddDisabledItem(new GUIContent("Add Tile Selection to TileView"));
                }

                if (BrushBehaviour.GetBrushTileset() == tileset && BrushBehaviour.CreateTileSelection() != null)
                {
                    menu.AddItem(new GUIContent("Add Brush Selection"), false, addBrushSelectionFunc);
                }

                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Remove All TileViews"), false, removeAllTileViewsFunc);
                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Sort By Name"), false, tileset.SortTileViewsByName);
                menu.ShowAsContext();
            };
            tileViewRList.onRemoveCallback = (ReorderableList list) => {
                if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete the TileView?", "Yes", "No"))
                {
                    ReorderableList.defaultBehaviours.DoRemoveButton(list);
                    EditorUtility.SetDirty(tileset);
                }
            };
            tileViewRList.drawHeaderCallback = (Rect rect) => {
                EditorGUI.LabelField(rect, "TileViews", EditorStyles.boldLabel);
                Texture2D btnTexture = tileViewRList.elementHeight == 0f ? EditorGUIUtility.FindTexture("winbtn_win_max_h") : EditorGUIUtility.FindTexture("winbtn_win_min_h");
                if (GUI.Button(new Rect(rect.width - rect.height, rect.y, rect.height, rect.height), btnTexture, EditorStyles.label))
                {
                    tileViewRList.elementHeight = tileViewRList.elementHeight == 0f ? EditorGUIUtility.singleLineHeight : 0f;
                    tileViewRList.draggable     = tileViewRList.elementHeight > 0f;
                }
            };
            tileViewRList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => {
                if (tileViewRList.elementHeight == 0f)
                {
                    return;
                }
                Rect     rLabel   = new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight);
                TileView tileView = tileViewRList.list[index] as TileView;
                if (index == tileViewRList.index)
                {
                    string newName = EditorGUI.TextField(rLabel, tileView.name);
                    if (newName != tileView.name)
                    {
                        tileset.RenameTileView(tileView.name, newName);
                    }
                }
                else
                {
                    EditorGUI.LabelField(rLabel, tileView.name);
                }
            };

            return(tileViewRList);
        }
    private static void ShowPopup(Event evt, UTNodeEditorModel model)
    {
        var menu = new GenericMenu ();
        if (!model.HasPlan) {
            menu.AddDisabledItem (new GUIContent ("Please select an automation plan."));
            menu.ShowAsContext ();
            return;
        }

        var hotNode = GetNodeUnderMouse (model, evt.mousePosition);
        var hotConnector = GetConnectorUnderMouse (model, evt.mousePosition);
        var data = new NodeEventData (evt, model, hotConnector);
        if (hotNode == null && hotConnector == null) {
        #if UTOMATE_DEMO
            if (!model.CanAddEntriesToPlan) {
                menu.AddDisabledItem (new GUIContent ("You cannot add any more entries in the demo version."));
            }
            else {
        #endif
            menu.AddItem (new GUIContent ("Add Action Entry"), false, AddActionNode, data);
            menu.AddItem (new GUIContent ("Add Decision Entry"), false, AddDecisionNode, data);
            menu.AddItem (new GUIContent ("Add For-Each Entry"), false, AddForEachNode, data);
            menu.AddItem (new GUIContent ("Add For-Each File Entry"), false, AddForEachFileNode, data);
            menu.AddItem (new GUIContent ("Add Sub-Plan Entry"), false, AddPlanNode, data);
            menu.AddItem (new GUIContent ("Add Note"), false, AddNote, data);

        #if UTOMATE_DEMO
            }
        #endif
        }

        if (hotNode != null) {
            if (!model.SelectedNodes.Contains (hotNode)) {
                model.SelectNode (hotNode, UTNodeEditorModel.SelectionMode.Replace);
            }

            if (menu.GetItemCount () > 0) {
                menu.AddSeparator ("");
            }

            var isMultiSelection = model.SelectedNodes.Count > 1;

            if (!model.IsFirstNode (hotNode) && !isMultiSelection) {
                menu.AddItem (new GUIContent ("Set As First Entry"), false, SetAsFirstNode, data);
            }
            menu.AddItem (new GUIContent (isMultiSelection ? "Delete Entries" : "Delete Entry"), false, DeleteNode, data);
        }

        if (hotConnector != null && hotConnector.isConnected) {
            if (menu.GetItemCount () > 0) {
                menu.AddSeparator ("");
            }
            menu.AddItem (new GUIContent ("Delete Connection"), false, DeleteConnection, data);
        }
        menu.ShowAsContext ();
    }
예제 #42
0
        public static bool Header(string title, SerializedProperty group, SerializedProperty enabledField, System.Action resetAction)
        {
            var          field  = ReflectionUtils.GetFieldInfoFromPath(enabledField.serializedObject.targetObject, enabledField.propertyPath);
            object       parent = null;
            PropertyInfo prop   = null;

            if (field != null && field.IsDefined(typeof(GetSetAttribute), false))
            {
                var attr = (GetSetAttribute)field.GetCustomAttributes(typeof(GetSetAttribute), false)[0];
                parent = ReflectionUtils.GetParentObject(enabledField.propertyPath, enabledField.serializedObject.targetObject);
                prop   = parent.GetType().GetProperty(attr.name);
            }

            var display = group == null || group.isExpanded;
            var enabled = enabledField.boolValue;

            var rect = GUILayoutUtility.GetRect(16f, 22f, FxStyles.header);

            GUI.Box(rect, title, FxStyles.header);

            var toggleRect = new Rect(rect.x + 4f, rect.y + 4f, 13f, 13f);
            var e          = Event.current;

            var popupRect = new Rect(rect.x + rect.width - FxStyles.paneOptionsIcon.width - 5f, rect.y + FxStyles.paneOptionsIcon.height / 2f + 1f, FxStyles.paneOptionsIcon.width, FxStyles.paneOptionsIcon.height);

            GUI.DrawTexture(popupRect, FxStyles.paneOptionsIcon);

            if (e.type == EventType.Repaint)
            {
                FxStyles.headerCheckbox.Draw(toggleRect, false, false, enabled, false);
            }

            if (e.type == EventType.MouseDown)
            {
                const float kOffset = 2f;
                toggleRect.x      -= kOffset;
                toggleRect.y      -= kOffset;
                toggleRect.width  += kOffset * 2f;
                toggleRect.height += kOffset * 2f;

                if (toggleRect.Contains(e.mousePosition))
                {
                    enabledField.boolValue = !enabledField.boolValue;

                    if (prop != null)
                    {
                        prop.SetValue(parent, enabledField.boolValue, null);
                    }

                    e.Use();
                }
                else if (popupRect.Contains(e.mousePosition))
                {
                    var popup = new GenericMenu();
                    popup.AddItem(GetContent("Reset"), false, () => resetAction());
                    popup.AddSeparator(string.Empty);
                    popup.AddItem(GetContent("Copy Settings"), false, () => CopySettings(group));

                    if (CanPaste(group))
                    {
                        popup.AddItem(GetContent("Paste Settings"), false, () => PasteSettings(group));
                    }
                    else
                    {
                        popup.AddDisabledItem(GetContent("Paste Settings"));
                    }

                    popup.ShowAsContext();
                }
                else if (rect.Contains(e.mousePosition) && group != null)
                {
                    display          = !display;
                    group.isExpanded = !group.isExpanded;
                    e.Use();
                }
            }

            return(display);
        }
예제 #43
0
 void buildContextMenu(int frame)
 {
     contextMenuFrame = frame;
     contextMenu = new GenericMenu();
     bool selectionHasKeys = aData.getCurrentTake().contextSelectionTracks.Count > 1 || aData.getCurrentTake().contextSelectionHasKeys();
     bool copyBufferNotEmpty = (contextSelectionKeysBuffer.Count > 0);
     bool canPaste = false;
     bool singleTrack = contextSelectionKeysBuffer.Count == 1;
     AMTrack selectedTrack = aData.getCurrentTake().getSelectedTrack();
     if(copyBufferNotEmpty) {
         if(singleTrack) {
             // if origin is property track
             if(selectedTrack is AMPropertyTrack) {
                 // if pasting into property track
                 if(contextSelectionTracksBuffer[0] is AMPropertyTrack) {
                     // if property tracks have the same property
                     if((selectedTrack as AMPropertyTrack).hasSamePropertyAs((contextSelectionTracksBuffer[0] as AMPropertyTrack))) {
                         canPaste = true;
                     }
                 }
                 // if origin is event track
             }
             else if(selectedTrack is AMEventTrack) {
                 // if pasting into event track
                 if(contextSelectionTracksBuffer[0] is AMEventTrack) {
                     // if event tracks are compaitable
                     if((selectedTrack as AMEventTrack).hasSameEventsAs((contextSelectionTracksBuffer[0] as AMEventTrack))) {
                         canPaste = true;
                     }
                 }
             }
             else {
                 if(selectedTrack.getTrackType() == contextSelectionTracksBuffer[0].getTrackType()) {
                     canPaste = true;
                 }
             }
         }
         else {
             // to do
             if(contextSelectionTracksBuffer.Contains(selectedTrack)) canPaste = true;
         }
     }
     contextMenu.AddItem(new GUIContent("Insert Keyframe"), false, invokeContextMenuItem, 0);
     contextMenu.AddSeparator("");
     if(selectionHasKeys) {
         contextMenu.AddItem(new GUIContent("Cut Frames"), false, invokeContextMenuItem, 1);
         contextMenu.AddItem(new GUIContent("Copy Frames"), false, invokeContextMenuItem, 2);
         if(canPaste) contextMenu.AddItem(new GUIContent("Paste Frames"), false, invokeContextMenuItem, 3);
         else contextMenu.AddDisabledItem(new GUIContent("Paste Frames"));
         contextMenu.AddItem(new GUIContent("Clear Frames"), false, invokeContextMenuItem, 4);
     }
     else {
         contextMenu.AddDisabledItem(new GUIContent("Cut Frames"));
         contextMenu.AddDisabledItem(new GUIContent("Copy Frames"));
         if(canPaste) contextMenu.AddItem(new GUIContent("Paste Frames"), false, invokeContextMenuItem, 3);
         else contextMenu.AddDisabledItem(new GUIContent("Paste Frames"));
         contextMenu.AddDisabledItem(new GUIContent("Clear Frames"));
     }
     contextMenu.AddItem(new GUIContent("Select All Frames"), false, invokeContextMenuItem, 5);
 }
예제 #44
0
        public override void Execute(Rect editorRect, Rect precentageRect, Event e, EngineGraph currentGraph)
        {
            _textStyle = new GUIStyle(GUI.skin.label)
            {
                fontSize  = 12,
                alignment = TextAnchor.UpperCenter,
                onNormal  = new GUIStyleState()
                {
                    textColor = Color.white
                }
            };

            base.Execute(editorRect, precentageRect, e, currentGraph);
            _style = new GUIStyle(GUI.skin.box);

            ShowCreatePanelGUI();
            GUILayout.BeginHorizontal(_toolbar);

            if (GUILayout.Button("File", _dropdown, GUILayout.Width(50)))
            {
                GenericMenu menu = new GenericMenu();

                menu.AddItem(new GUIContent("Create Graph"), false, () => showDialogue = true);
                menu.AddItem(new GUIContent("Load Graph"), false, EngineGraphEditorUtilities.LoadGraph);

                menu.AddSeparator("");

                if (currentGraph == null)
                {
                    menu.AddDisabledItem(new GUIContent("Unload Graph"));
                    menu.AddDisabledItem(new GUIContent("Delete Graph"));
                }

                else
                {
                    currentGraph.selectedNode = null;

                    menu.AddItem(new GUIContent("Delete Graph/Confirm"), false, EngineGraphEditorUtilities.DeleteGraph);
                    menu.AddItem(new GUIContent("Unload Graph"), false, EngineGraphEditorUtilities.UnloadGraph);
                }

                menu.Show(new Vector2(5, 17));
            }

            GUILayout.Space(10);

            if (GUILayout.Button("Insert", _dropdown, GUILayout.Width(100)))
            {
                GenericMenu menu = new GenericMenu();

                if (currentGraph != null)
                {
                    currentGraph.selectedNode = null;

                    menu.AddItem(new GUIContent("Story State/Add Text State", "Write dialogues and narrative text in the text container."), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Text, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Story State/Add Clear Text State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Clear, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Story State/Add Change Flow Chart State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Change_Flow_Chart, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Character State/Add Show Character State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Show_Character, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Character State/Add Hide Character State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Hide_Character, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Character State/Add Change Character Sprite State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Change_Character_Sprite, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Character State/Add Character Move State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Move_Character, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Image State/Add Change Background State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Change_Background, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Effect State/Add Delay State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Delay, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Effect State/Add Show Text Container"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Show_Text_Container, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Effect State/Add Hide Text Container"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Hide_Text_Container, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Sound State/Music/Add Play Music State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Play_Music, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Sound State/Music/Add Stop Music State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Stop_Music, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Sound State/Sound FX/Add Play Sound State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Play_Sound, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Sound State/Sound FX/Add Stop SouSoundnd State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Stop_Sound, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Sound State/Voice/Add Play Voice State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Play_Voice, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Sound State/Voice/Add Stop Voice State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Stop_Voice, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Branch State/Add Question Branch State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Branch_Question, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Branch State/Add Conditional Branch State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Branch_Condition, new Vector2(50, 50)));
                    menu.AddSeparator("Branch State/");
                    menu.AddItem(new GUIContent("Branch State/Add Answer State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Answer, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("Branch State/Add Condition State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Condition, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("System State/Add Set Parameter State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Set_Param, new Vector2(50, 50)));
                    menu.AddItem(new GUIContent("System State/Add Trigger Event State"), false, () => EngineGraphEditorUtilities.CreateNode(currentGraph, EnumNodeType.Set_Param, new Vector2(50, 50)));
                }

                else
                {
                    menu.AddDisabledItem(new GUIContent("Story State/Add Text State"));
                    menu.AddDisabledItem(new GUIContent("Story State/Add Clear Text State"));
                    menu.AddDisabledItem(new GUIContent("Story State/Add Change Flow Chart State"));
                    menu.AddDisabledItem(new GUIContent("Character State/Add Show Character State"));
                    menu.AddDisabledItem(new GUIContent("Character State/Add Hide Character State"));
                    menu.AddDisabledItem(new GUIContent("Character State/Add Change Character Sprite State"));
                    menu.AddDisabledItem(new GUIContent("Character State/Add Character Move State"));
                    menu.AddDisabledItem(new GUIContent("Image State/Add Change Background State"));
                    menu.AddDisabledItem(new GUIContent("Effect State/Add Delay State"));
                    menu.AddDisabledItem(new GUIContent("Effect State/Add Show Text Container"));
                    menu.AddDisabledItem(new GUIContent("Effect State/Add Hide Text Container"));
                    menu.AddDisabledItem(new GUIContent("Sound State/Music/Add Play Music State"));
                    menu.AddDisabledItem(new GUIContent("Sound State/Music/Add Stop Music State"));
                    menu.AddDisabledItem(new GUIContent("Sound State/Sound FX/Add Play Sound State"));
                    menu.AddDisabledItem(new GUIContent("Sound State/Sound FX/Add Stop Sound State"));
                    menu.AddDisabledItem(new GUIContent("Sound State/Voice/Add Play Voice State"));
                    menu.AddDisabledItem(new GUIContent("Sound State/Voice/Add Stop Voice State"));
                    menu.AddDisabledItem(new GUIContent("Branch State/Add Question Branch State"));
                    menu.AddDisabledItem(new GUIContent("Branch State/Add Conditional Brach State"));
                    menu.AddSeparator("Branch State/");
                    menu.AddDisabledItem(new GUIContent("Branch State/Add Answer State"));
                    menu.AddDisabledItem(new GUIContent("Branch State/Add Condition State"));
                    menu.AddDisabledItem(new GUIContent("System State/Add Set Parameter State"));
                    menu.AddDisabledItem(new GUIContent("System State/Add Trigger Event State"));
                }

                menu.Show(new Vector2(65, 17));
            }

            if (GUILayout.Button("Tools", _dropdown, GUILayout.Width(80)))
            {
                GenericMenu menu = new GenericMenu();

                //menu.AddDisabledItem(new GUIContent("Import/XML"));
                //menu.AddDisabledItem(new GUIContent("Import/TXT"));
                //menu.AddDisabledItem(new GUIContent("Export/XML"));
                //menu.AddDisabledItem(new GUIContent("Export/TXT"));
                menu.AddItem(new GUIContent("Clear cache", "Clear the cache information of the last session."), false, EngineGraphCacheUtilities.ClearSessionCache);

                menu.Show(new Vector2(135, 17));
            }

            GUILayout.FlexibleSpace();

            GUILayout.EndHorizontal();

            if (showDialogue)
            {
                CreateGraphDialogueGUI();
            }
        }
 private void OnConditionHeaderClick()
 {
     GenericMenu genericMenu = new GenericMenu ();
     if(state.transitions[transitionIndex].conditions.Count == 0){
         genericMenu.AddDisabledItem (new GUIContent ("Copy"));
     }else{
         genericMenu.AddItem (new GUIContent ("Copy"), false, new GenericMenu.MenuFunction (this.CopyConditions));
     }
     if(copiedConditions != null && copiedConditions.Count>0 && conditionCopiedState != null && conditionCopiedState.id != state.id){
         genericMenu.AddItem (new GUIContent ("Paste"), false, new GenericMenu.MenuFunction (this.PasteConditions));
     }else{
         genericMenu.AddDisabledItem (new GUIContent ("Paste"));
     }
     genericMenu.ShowAsContext ();
     Event.current.Use ();
 }
예제 #46
0
        private GenericMenu ElementContextMenu(IList list, int index)
        {
            GenericMenu menu = new GenericMenu();

            if (list[index] == null)
            {
                return(menu);
            }
            Type elementType = list[index].GetType();

            menu.AddItem(new GUIContent("Reset"), false, delegate {
                object value = System.Activator.CreateInstance(list[index].GetType());
                list[index]  = value;
                EditorUtility.SetDirty(target);
            });
            menu.AddSeparator(string.Empty);
            menu.AddItem(new GUIContent("Remove"), false, delegate {
                list.RemoveAt(index);
                EditorUtility.SetDirty(target);
            });

            if (index > 0)
            {
                menu.AddItem(new GUIContent("Move Up"), false, delegate {
                    object value = list[index];
                    list.RemoveAt(index);
                    list.Insert(index - 1, value);
                    EditorUtility.SetDirty(target);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Move Up"));
            }

            if (index < list.Count - 1)
            {
                menu.AddItem(new GUIContent("Move Down"), false, delegate
                {
                    object value = list[index];
                    list.RemoveAt(index);
                    list.Insert(index + 1, value);
                    EditorUtility.SetDirty(target);
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Move Down"));
            }

            if (list[index] != null)
            {
                MonoScript script = EditorTools.FindMonoScript(list[index].GetType());
                if (script != null)
                {
                    menu.AddSeparator(string.Empty);
                    menu.AddItem(new GUIContent("Edit Script"), false, delegate { AssetDatabase.OpenAsset(script); });
                }
            }
            return(menu);
        }
예제 #47
0
		public override void OnFlowWindowGUI(FlowWindow window) {

			var data = FlowSystem.GetData();
			if (data == null) return;

			var flag = (window.IsFunction() == true && 
					window.IsSmall() == true &&
					window.IsContainer() == false);

			if (flag == true) {
				
				var alreadyConnectedFunctionIds = new List<int>();

				// Find caller window
				var windowFrom = data.windows.FirstOrDefault((item) => item.HasAttach(window.id));
				if (windowFrom != null) {
					
					var attaches = windowFrom.GetAttachedWindows();
					foreach (var attachWindow in attaches) {
						
						if (attachWindow.IsFunction() == true) {
							
							alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());
							
						}
						
					}
					
				}
				
				foreach (var win in data.windows) {
					
					if (win.IsFunction() == true &&
					    win.IsContainer() == true) {
						
						var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
						if ((window.GetFunctionId() == win.id && count == 1) || count == 0) {
							
						} else {
							
							if (win.id == window.functionId) window.functionId = 0;
							alreadyConnectedFunctionIds.Remove(win.id);
							
						}
						
					}
					
				}

				var functionId = window.GetFunctionId();
				var functionContainer = functionId == 0 ? null : data.GetWindow(functionId);
				var isActiveSelected = true;

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(functionContainer != null ? functionContainer.title : "None", GUILayout.MaxHeight(60f), GUILayout.MaxWidth(150f));
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), window.functionId == 0, () => {

						window.functionId = 0;

					});

					if (windowFrom != null) {

						alreadyConnectedFunctionIds.Clear();
						var attaches = windowFrom.GetAttachedWindows();
						foreach (var attachWindow in attaches) {
							
							if (attachWindow.IsFunction() == true) {
								
								alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());
								
							}
							
						}
						
					}
					foreach (var win in data.windows) {
						
						if (win.IsFunction() == true &&
						    win.IsContainer() == true) {

							var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
							if ((window.GetFunctionId() == win.id && count == 1) || count == 0) {

								var id = win.id;
								menu.AddItem(new GUIContent(win.title), win.id == window.functionId, () => {

									window.functionId = id;

								});

							} else {

								if (win.id == window.functionId) window.functionId = 0;

								alreadyConnectedFunctionIds.Remove(win.id);
								menu.AddDisabledItem(new GUIContent(win.title));

							}

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
예제 #48
0
        protected virtual GenericMenu GetContextMenu(UnityEngine.Object target)
        {
            GenericMenu menu  = new GenericMenu();
            int         index = Array.IndexOf(this.m_Targets, target);

            menu.AddItem(new GUIContent("Reset"), false, delegate {
                Type type = target.GetType();
                DestroyImmediate(target);
                this.m_Targets[index] = (this.m_Target as Component).gameObject.AddComponent(type);
                DestroyImmediate(this.m_Editors[index]);
                this.m_Editors[index]             = Editor.CreateEditor(this.m_Targets[index]);
                SerializedObject serializedObject = new SerializedObject(this.m_Target);
                SerializedProperty elements       = serializedObject.FindProperty(this.m_ElementPropertyPath);
                serializedObject.Update();
                elements.GetArrayElementAtIndex(index).objectReferenceValue = this.m_Targets[index];
                serializedObject.ApplyModifiedProperties();
                if (this.m_HasPrefab && typeof(Component).IsAssignableFrom(this.m_Target.GetType()) && this.m_ApplyToPrefab)
                {
                    PrefabUtility.ApplyPrefabInstance((this.m_Target as Component).gameObject, InteractionMode.AutomatedAction);
                }
            });
            menu.AddSeparator(string.Empty);
            menu.AddItem(new GUIContent("Remove"), false, delegate {
                DestroyImmediate(this.m_Editors[index]);
                this.m_Editors.RemoveAt(index);
                DestroyImmediate(target);
                ArrayUtility.RemoveAt(ref this.m_Targets, index);

                SerializedObject serializedObject = new SerializedObject(this.m_Target);
                SerializedProperty elements       = serializedObject.FindProperty(this.m_ElementPropertyPath);
                serializedObject.Update();
                elements.GetArrayElementAtIndex(index).objectReferenceValue = null;
                elements.DeleteArrayElementAtIndex(index);
                serializedObject.ApplyModifiedProperties();
                if (this.m_HasPrefab && typeof(Component).IsAssignableFrom(this.m_Target.GetType()) && this.m_ApplyToPrefab)
                {
                    PrefabUtility.ApplyPrefabInstance((this.m_Target as Component).gameObject, InteractionMode.AutomatedAction);
                }
            });

            menu.AddItem(new GUIContent("Copy"), false, delegate {
                m_CopyComponent = target as Component;
            });

            if (m_CopyComponent != null && m_CopyComponent.GetType() == target.GetType())
            {
                menu.AddItem(new GUIContent("Paste"), false, delegate {
                    UnityEditorInternal.ComponentUtility.CopyComponent(m_CopyComponent);
                    UnityEditorInternal.ComponentUtility.PasteComponentValues((Component)target);
                    if (this.m_HasPrefab && typeof(Component).IsAssignableFrom(this.m_Target.GetType()) && this.m_ApplyToPrefab)
                    {
                        PrefabUtility.ApplyPrefabInstance((this.m_Target as Component).gameObject, InteractionMode.AutomatedAction);
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Paste"));
            }

            if (index > 0)
            {
                menu.AddItem(new GUIContent("Move Up"), false, delegate
                {
                    ArrayUtility.RemoveAt(ref this.m_Targets, index);
                    ArrayUtility.Insert(ref this.m_Targets, index - 1, target);
                    Editor editor = this.m_Editors[index];
                    this.m_Editors.RemoveAt(index);
                    this.m_Editors.Insert(index - 1, editor);

                    SerializedObject serializedObject = new SerializedObject(this.m_Target);
                    SerializedProperty elements       = serializedObject.FindProperty(this.m_ElementPropertyPath);
                    serializedObject.Update();
                    elements.MoveArrayElement(index, index - 1);
                    serializedObject.ApplyModifiedProperties();
                    if (this.m_HasPrefab && typeof(Component).IsAssignableFrom(this.m_Target.GetType()) && this.m_ApplyToPrefab)
                    {
                        PrefabUtility.ApplyPrefabInstance((this.m_Target as Component).gameObject, InteractionMode.AutomatedAction);
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Move Up"));
            }
            if (index < this.m_Targets.Length - 1)
            {
                menu.AddItem(new GUIContent("Move Down"), false, delegate
                {
                    ArrayUtility.RemoveAt(ref this.m_Targets, index);
                    ArrayUtility.Insert(ref this.m_Targets, index + 1, target);
                    Editor editor = this.m_Editors[index];
                    this.m_Editors.RemoveAt(index);
                    this.m_Editors.Insert(index + 1, editor);

                    SerializedObject serializedObject = new SerializedObject(this.m_Target);
                    SerializedProperty elements       = serializedObject.FindProperty(this.m_ElementPropertyPath);
                    serializedObject.Update();
                    elements.MoveArrayElement(index, index + 1);
                    serializedObject.ApplyModifiedProperties();
                    if (this.m_HasPrefab && typeof(Component).IsAssignableFrom(this.m_Target.GetType()) && this.m_ApplyToPrefab)
                    {
                        PrefabUtility.ApplyPrefabInstance((this.m_Target as Component).gameObject, InteractionMode.AutomatedAction);
                    }
                });
            }
            else
            {
                menu.AddDisabledItem(new GUIContent("Move Down"));
            }
            return(menu);
        }
예제 #49
0
 internal static void Show()
 {
     GenericMenu menu = new GenericMenu();
     GUIContent content = new GUIContent("Show in Asset Store window");
     AssetStoreAsset firstAsset = AssetStoreAssetSelection.GetFirstAsset();
     if ((firstAsset != null) && (firstAsset.id != 0))
     {
         menu.AddItem(content, false, new GenericMenu.MenuFunction(new ProjectBrowser.AssetStoreItemContextMenu().OpenAssetStoreWindow));
     }
     else
     {
         menu.AddDisabledItem(content);
     }
     menu.ShowAsContext();
 }
예제 #50
0
        public virtual void ShowContextMenu()
        {
            Block     block     = target as Block;
            Flowchart flowchart = block.GetFlowchart();

            if (flowchart == null)
            {
                return;
            }

            bool showCut    = false;
            bool showCopy   = false;
            bool showDelete = false;
            bool showPaste  = false;

            if (flowchart.selectedCommands.Count > 0)
            {
                showCut    = true;
                showCopy   = true;
                showDelete = true;
            }

            CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance();

            if (commandCopyBuffer.HasCommands())
            {
                showPaste = true;
            }

            GenericMenu commandMenu = new GenericMenu();

            if (showCut)
            {
                commandMenu.AddItem(new GUIContent("Cut"), false, Cut);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Cut"));
            }

            if (showCopy)
            {
                commandMenu.AddItem(new GUIContent("Copy"), false, Copy);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Copy"));
            }

            if (showPaste)
            {
                commandMenu.AddItem(new GUIContent("Paste"), false, Paste);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Paste"));
            }

            if (showDelete)
            {
                commandMenu.AddItem(new GUIContent("Delete"), false, Delete);
            }
            else
            {
                commandMenu.AddDisabledItem(new GUIContent("Delete"));
            }

            commandMenu.AddSeparator("");

            commandMenu.AddItem(new GUIContent("Select All"), false, SelectAll);
            commandMenu.AddItem(new GUIContent("Select None"), false, SelectNone);

            commandMenu.ShowAsContext();
        }
    private void displayContextMenu()
    {
        var menu = new GenericMenu();

        var items = new List<ContextMenuItem>();
        FillContextMenu( items );

        var actionFunc = new System.Action<int>( ( command ) =>
        {
            var handler = items[ command ].Handler;
            handler();
        } );

        menu.AddDisabledItem( new GUIContent( string.Format( "{0} (GUI Manager)", target.name ) ) );
        menu.AddSeparator( "" );

        var options = items.Select( i => i.MenuText ).ToList();
        for( int i = 0; i < options.Count; i++ )
        {
            var index = i;
            if( options[ i ] == "-" )
                menu.AddSeparator( "" );
            else
                menu.AddItem( new GUIContent( options[ i ] ), false, () => { actionFunc( index ); } );
        }

        menu.ShowAsContext();
    }
예제 #52
0
		public override void OnFlowWindowGUI(FD.FlowWindow window) {

			if (Social.settings == null) return;

			var socialFlag = (window.flags & Social.settings.uniqueTag) == Social.settings.uniqueTag;
			if (socialFlag == true) {

				var settings = Social.settings;
				if (settings == null) return;
				
				var data = settings.data.Get(window);
				var isActiveSelected = settings.IsPlatformActive(data.settings);

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(data.settings ? data.settings.GetPlatformName() : "None", 60f, 150f);
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), data.settings == null, () => {

						data.settings = null;

					});

					foreach (var platform in settings.activePlatforms) {

						if (platform.active == true) {

							var item = platform.settings;
							menu.AddItem(new GUIContent(platform.GetPlatformName()), data.settings == platform.settings, () => {

								data.settings = item;

							});
							
						} else {

							menu.AddDisabledItem(new GUIContent(platform.GetPlatformName()));

						}
						
					}

					menu.DropDown(rect);

				}

			}

		}
예제 #53
0
	void Selector(SerializedProperty property) {
		SkeletonData data = skeletonDataAsset.GetSkeletonData(true);

		if (data == null)
			return;

		SpineAttachment attrib = (SpineAttachment)attribute;

		List<Skin> validSkins = new List<Skin>();

		if (skeletonRenderer != null && attrib.currentSkinOnly) {
			if (skeletonRenderer.skeleton.Skin != null) {
				validSkins.Add(skeletonRenderer.skeleton.Skin);
			} else {
				validSkins.Add(data.Skins.Items[0]);
			}
		} else {
			foreach (Skin skin in data.Skins) {
				if (skin != null)
					validSkins.Add(skin);
			}
		}

		GenericMenu menu = new GenericMenu();
		List<string> attachmentNames = new List<string>();
		List<string> placeholderNames = new List<string>();

		string prefix = "";

		if (skeletonRenderer != null && attrib.currentSkinOnly)
			menu.AddDisabledItem(new GUIContent(skeletonRenderer.gameObject.name + " (SkeletonRenderer)"));
		else
			menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
		menu.AddSeparator("");

		menu.AddItem(new GUIContent("Null"), property.stringValue == "", HandleSelect, new SpineDrawerValuePair("", property));
		menu.AddSeparator("");

		Skin defaultSkin = data.Skins.Items[0];

		SerializedProperty slotProperty = property.serializedObject.FindProperty(attrib.slotField);
		string slotMatch = "";
		if (slotProperty != null) {
			if (slotProperty.propertyType == SerializedPropertyType.String) {
				slotMatch = slotProperty.stringValue.ToLower();
			}
		}

		foreach (Skin skin in validSkins) {
			string skinPrefix = skin.Name + "/";

			if (validSkins.Count > 1)
				prefix = skinPrefix;

			for (int i = 0; i < data.Slots.Count; i++) {
				if (slotMatch.Length > 0 && data.Slots.Items[i].Name.ToLower().Contains(slotMatch) == false)
					continue;

				attachmentNames.Clear();
				placeholderNames.Clear();

				skin.FindNamesForSlot(i, attachmentNames);
				if (skin != defaultSkin) {
					defaultSkin.FindNamesForSlot(i, attachmentNames);
					skin.FindNamesForSlot(i, placeholderNames);
				}
					

				for (int a = 0; a < attachmentNames.Count; a++) {
					
					string attachmentPath = attachmentNames[a];
					string menuPath = prefix + data.Slots.Items[i].Name + "/" + attachmentPath;
					string name = attachmentNames[a];

					if (attrib.returnAttachmentPath)
						name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath;

					if (attrib.placeholdersOnly && placeholderNames.Contains(attachmentPath) == false) {
						menu.AddDisabledItem(new GUIContent(menuPath));
					} else {
						menu.AddItem(new GUIContent(menuPath), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
					}
					
					
				}
			}
		}


		menu.ShowAsContext();
	}
예제 #54
0
        public static bool Header(string title, SerializedProperty group, SerializedProperty enabledField, Action resetAction)
        {
            var field = ReflectionUtils.GetFieldInfoFromPath(enabledField.serializedObject.targetObject, enabledField.propertyPath);
            object parent = null;
            PropertyInfo prop = null;

            if (field != null && field.IsDefined(typeof(GetSetAttribute), false))
            {
                var attr = (GetSetAttribute)field.GetCustomAttributes(typeof(GetSetAttribute), false)[0];
                parent = ReflectionUtils.GetParentObject(enabledField.propertyPath, enabledField.serializedObject.targetObject);
                prop = parent.GetType().GetProperty(attr.name);
            }

            var display = group == null || group.isExpanded;
            var enabled = enabledField.boolValue;

            var rect = GUILayoutUtility.GetRect(16f, 22f, FxStyles.header);
            GUI.Box(rect, title, FxStyles.header);

            var toggleRect = new Rect(rect.x + 4f, rect.y + 4f, 13f, 13f);
            var e = Event.current;

            var popupRect = new Rect(rect.x + rect.width - FxStyles.paneOptionsIcon.width - 5f, rect.y + FxStyles.paneOptionsIcon.height / 2f + 1f, FxStyles.paneOptionsIcon.width, FxStyles.paneOptionsIcon.height);
            GUI.DrawTexture(popupRect, FxStyles.paneOptionsIcon);

            if (e.type == EventType.Repaint)
                FxStyles.headerCheckbox.Draw(toggleRect, false, false, enabled, false);

            if (e.type == EventType.MouseDown)
            {
                const float kOffset = 2f;
                toggleRect.x -= kOffset;
                toggleRect.y -= kOffset;
                toggleRect.width += kOffset * 2f;
                toggleRect.height += kOffset * 2f;

                if (toggleRect.Contains(e.mousePosition))
                {
                    enabledField.boolValue = !enabledField.boolValue;

                    if (prop != null)
                        prop.SetValue(parent, enabledField.boolValue, null);

                    e.Use();
                }
                else if (popupRect.Contains(e.mousePosition))
                {
                    var popup = new GenericMenu();
                    popup.AddItem(GetContent("Reset"), false, () => resetAction());
                    popup.AddSeparator(string.Empty);
                    popup.AddItem(GetContent("Copy Settings"), false, () => CopySettings(group));

                    if (CanPaste(group))
                        popup.AddItem(GetContent("Paste Settings"), false, () => PasteSettings(group));
                    else
                        popup.AddDisabledItem(GetContent("Paste Settings"));

                    popup.ShowAsContext();
                }
                else if (rect.Contains(e.mousePosition) && group != null)
                {
                    display = !display;
                    group.isExpanded = !group.isExpanded;
                    e.Use();
                }
            }

            return display;
        }
예제 #55
0
        //Handles events, Mouse downs, ups etc.
        void HandleEvents(Event e)
        {
            //delete shortcut
            if (isSelected && e.keyCode == KeyCode.Delete && e.type == EventType.KeyUp && GUIUtility.keyboardControl == 0)
            {
                Graph.PostGUI += delegate { graph.RemoveNode(this); };
                e.Use();
            }

            //Duplicate shortcut
            if (isSelected && e.keyCode == KeyCode.D && e.isKey && e.control)
            {
                Graph.PostGUI += delegate { Graph.currentSelection = Duplicate(graph); };
                e.Use();
            }

            //Node click
            if (Graph.allowClick && e.button != 2 && e.type == EventType.MouseDown)
            {
                if (!e.control)
                {
                    Graph.currentSelection = this;
                }

                nodeIsPressed = true;

                //Double click
                if (e.button == 0 && e.clickCount == 2)
                {
                    if (this is IGraphAssignable && (this as IGraphAssignable).nestedGraph != null)
                    {
                        graph.currentChildGraph = (this as IGraphAssignable).nestedGraph;
                        nodeIsPressed           = false;
                    }
                    else if (this is ITaskAssignable && (this as ITaskAssignable).task != null)
                    {
                        EditorUtils.OpenScriptOfType((this as ITaskAssignable).task.GetType());
                    }
                    else
                    {
                        EditorUtils.OpenScriptOfType(this.GetType());
                    }
                    e.Use();
                }


                if (e.control)
                {
                    if (isSelected)
                    {
                        Graph.multiSelection.Remove(this);
                    }
                    else
                    {
                        Graph.multiSelection.Add(this);
                    }
                }

                OnNodePicked();
            }

            //Mouse up
            if (e.type == EventType.MouseUp)
            {
                nodeIsPressed = false;
                if (graph.autoSort)
                {
                    Graph.PostGUI += delegate { SortConnectionsByPositionX(); }
                }
                ;
                OnNodeReleased();
            }
        }

        //Shows the icons relative to the current node status
        void ShowStatusIcons()
        {
            if (Application.isPlaying && status != Status.Resting)
            {
                var markRect = new Rect(5, 5, 15, 15);
                if (status == Status.Success)
                {
                    GUI.color = successColor;
                    GUI.Box(markRect, "", new GUIStyle("checkMark"));
                }
                else if (status == Status.Running)
                {
                    GUI.Box(markRect, "", new GUIStyle("clockMark"));
                }
                else if (status == Status.Failure)
                {
                    GUI.color = failureColor;
                    GUI.Box(markRect, "", new GUIStyle("xMark"));
                }
            }
        }

        //Shows the breakpoint mark icon if node is set as a breakpoint
        void ShowBreakpointMark()
        {
            if (!isBreakpoint)
            {
                return;
            }
            var rect = new Rect(nodeRect.width - 15, 5, 12, 12);

            GUI.DrawTexture(rect, EditorUtils.redCircle);
        }

        //Shows the actual node contents GUI
        void ShowNodeContents()
        {
            GUI.color = Color.white;
            GUI.skin  = null;
            GUI.skin.label.richText  = true;
            GUI.skin.label.alignment = TextAnchor.MiddleCenter;
            GUILayout.BeginVertical();

            OnNodeGUI();

            if (this is ITaskAssignable)
            {
                var task = (this as ITaskAssignable).task;
                if (task == null)
                {
                    GUILayout.Label("No Task");
                }
                else
                {
                    GUILayout.Label(NCPrefs.showTaskSummary? task.summaryInfo : string.Format("<b>{0}</b>", task.name));
                }
            }

            GUILayout.EndVertical();
            GUI.skin.label.alignment = TextAnchor.UpperLeft;
        }

        //Handles and shows the right click mouse button for the node context menu
        void HandleContextMenu(Event e)
        {
            if (Graph.allowClick && e.button == 1 && e.type == EventType.MouseUp)
            {
                //Multiselection menu
                if (Graph.multiSelection.Count > 0)
                {
                    var menu = new GenericMenu();
                    menu.AddItem(new GUIContent("Duplicate Selected Nodes"), false, () => { Graph.CopyNodesToGraph(Graph.multiSelection.OfType <Node>().ToList(), graph); });
                    menu.AddItem(new GUIContent("Copy Selected Nodes"), false, () => { copiedNodes = Graph.multiSelection.OfType <Node>().ToArray(); });
                    menu.AddSeparator("/");
                    menu.AddItem(new GUIContent("Delete Selected Nodes"), false, () => { foreach (Node node in Graph.multiSelection.ToArray())
                                                                                         {
                                                                                             graph.RemoveNode(node);
                                                                                         }
                                 });
                    Graph.PostGUI += () => { menu.ShowAsContext(); };            //Post GUI cause of zoom
                    e.Use();
                    return;

                    //Single node menu
                }
                else
                {
                    var menu = new GenericMenu();

                    if (graph.primeNode != this && allowAsPrime)
                    {
                        menu.AddItem(new GUIContent("Set Start"), false, () => { graph.primeNode = this; });
                    }

                    if (this is IGraphAssignable)
                    {
                        menu.AddItem(new GUIContent("Edit Nested (Double Click)"), false, () => { graph.currentChildGraph = (this as IGraphAssignable).nestedGraph; });
                    }


                    menu.AddItem(new GUIContent("Duplicate (CTRL+D)"), false, () => { Duplicate(graph); });
                    menu.AddItem(new GUIContent("Copy Node"), false, () => { copiedNodes = new Node[] { this }; });

                    if (inConnections.Count > 0)
                    {
                        menu.AddItem(new GUIContent(isActive? "Disable" : "Enable"), false, () => { SetActive(!isActive); });
                    }

                    if (graph.autoSort && outConnections.Count > 0)
                    {
                        menu.AddItem(new GUIContent(collapsed? "Expand Children" : "Collapse Children"), false, () => { collapsed = !collapsed; });
                    }

                    if (this is ITaskAssignable)
                    {
                        var assignable = this as ITaskAssignable;
                        if (assignable.task != null)
                        {
                            menu.AddItem(new GUIContent("Copy Assigned Task"), false, () => { Task.copiedTask = assignable.task; });
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent("Copy Assigned Task"));
                        }

                        if (Task.copiedTask != null)
                        {
                            menu.AddItem(new GUIContent("Paste Assigned Task"), false, () =>
                            {
                                if (assignable.task == Task.copiedTask)
                                {
                                    return;
                                }

                                if (assignable.task != null)
                                {
                                    if (!EditorUtility.DisplayDialog("Paste Task", string.Format("Node already has a Task assigned '{0}'. Replace assigned task with pasted task '{1}'?", assignable.task.name, Task.copiedTask.name), "YES", "NO"))
                                    {
                                        return;
                                    }
                                }

                                try { assignable.task = Task.copiedTask.Duplicate(graph); }
                                catch { Debug.LogWarning("Can't paste Task here. Incombatible Types"); }
                            });
                        }
                        else
                        {
                            menu.AddDisabledItem(new GUIContent("Paste Assigned Task"));
                        }
                    }

                    OnContextMenu(menu);

                    menu.AddSeparator("/");
                    menu.AddItem(new GUIContent("Delete (DEL)"), false, () => { graph.RemoveNode(this); });
                    Graph.PostGUI += () => { menu.ShowAsContext(); };
                    e.Use();
                }
            }
        }

        //basicaly handles the node position and draging etc
        void HandleNodePosition(Event e)
        {
            if (Graph.allowClick && e.button != 2)
            {
                //drag all selected nodes
                if (e.type == EventType.MouseDrag && Graph.multiSelection.Count > 1)
                {
                    for (var i = 0; i < Graph.multiSelection.Count; i++)
                    {
                        ((Node)Graph.multiSelection[i]).nodePosition += e.delta;
                    }
                    return;
                }

                if (nodeIsPressed)
                {
                    Undo.RecordObject(graph, "Move Move");

                    var hierarchicalMove = NCPrefs.hierarchicalMove != e.shift;

                    //snap to grid
                    if (!hierarchicalMove && NCPrefs.doSnap && Graph.multiSelection.Count == 0)
                    {
                        nodePosition = new Vector2(Mathf.Round(nodePosition.x / 15) * 15, Mathf.Round(nodePosition.y / 15) * 15);
                    }

                    //recursive drag
                    if (graph.autoSort && e.type == EventType.MouseDrag)
                    {
                        if (hierarchicalMove || collapsed)
                        {
                            RecursivePanNode(e.delta);
                        }
                    }
                }

                //this drag
                GUI.DragWindow();
            }
        }

        //The comments of the node sitting next or bottom of it
        void DrawNodeComments()
        {
            if (NCPrefs.showComments && !string.IsNullOrEmpty(nodeComment))
            {
                var commentsRect = new Rect();
                var size         = new GUIStyle("textArea").CalcSize(new GUIContent(nodeComment));

                if (showCommentsBottom)
                {
                    size.y       = new GUIStyle("textArea").CalcHeight(new GUIContent(nodeComment), nodeRect.width);
                    commentsRect = new Rect(nodeRect.x, nodeRect.yMax + 5, nodeRect.width, size.y);
                }
                else
                {
                    commentsRect = new Rect(nodeRect.xMax + 5, nodeRect.yMin, Mathf.Min(size.x, nodeRect.width * 2), nodeRect.height);
                }

                GUI.color           = new Color(1, 1, 1, 0.6f);
                GUI.backgroundColor = new Color(1f, 1f, 1f, 0.2f);
                GUI.Box(commentsRect, nodeComment, "textArea");
                GUI.backgroundColor = Color.white;
                GUI.color           = Color.white;
            }
        }

        //Shows the tag label on the left of the node if it is tagged
        void DrawNodeTag()
        {
            if (!string.IsNullOrEmpty(tag))
            {
                var size    = new GUIStyle("label").CalcSize(new GUIContent(tag));
                var tagRect = new Rect(nodeRect.x - size.x - 10, nodeRect.y, size.x, size.y);
                GUI.Label(tagRect, tag);
                tagRect.width  = 12;
                tagRect.height = 12;
                tagRect.y     += tagRect.height + 5;
                tagRect.x      = nodeRect.x - 22;
                GUI.DrawTexture(tagRect, EditorUtils.tagIcon);
            }
        }

        //Function to pan the node with children recursively
        void RecursivePanNode(Vector2 delta)
        {
            nodePosition += delta;

            for (var i = 0; i < outConnections.Count; i++)
            {
                var node = outConnections[i].targetNode;
                if (node.ID > this.ID)
                {
                    node.RecursivePanNode(delta);
                }
            }
        }
 private void ShowAddTriggermenu()
 {
   GenericMenu genericMenu = new GenericMenu();
   for (int index1 = 0; index1 < this.m_EventTypes.Length; ++index1)
   {
     bool flag = true;
     for (int index2 = 0; index2 < this.m_DelegatesProperty.arraySize; ++index2)
     {
       if (this.m_DelegatesProperty.GetArrayElementAtIndex(index2).FindPropertyRelative("eventID").enumValueIndex == index1)
         flag = false;
     }
     if (flag)
       genericMenu.AddItem(this.m_EventTypes[index1], false, new GenericMenu.MenuFunction2(this.OnAddNewSelected), (object) index1);
     else
       genericMenu.AddDisabledItem(this.m_EventTypes[index1]);
   }
   genericMenu.ShowAsContext();
   Event.current.Use();
 }
예제 #57
0
        private void CreateEditMenu(Rect position)
        {
            GenericMenu editMenu = new GenericMenu();

            editMenu.AddItem(new GUIContent("New Configuration"), false, HandleEditMenuOption, EditMenuOptions.NewInputConfiguration);
            if (_selectionPath.Count >= 1)
            {
                editMenu.AddItem(new GUIContent("New Axis"), false, HandleEditMenuOption, EditMenuOptions.NewAxisConfiguration);
            }
            else
            {
                editMenu.AddDisabledItem(new GUIContent("New Axis"));
            }
            editMenu.AddSeparator("");

            if (_selectionPath.Count > 0)
            {
                editMenu.AddItem(new GUIContent("Duplicate          Shift+D"), false, HandleEditMenuOption, EditMenuOptions.Duplicate);
            }
            else
            {
                editMenu.AddDisabledItem(new GUIContent("Duplicate          Shift+D"));
            }

            if (_selectionPath.Count > 0)
            {
                editMenu.AddItem(new GUIContent("Delete                Del"), false, HandleEditMenuOption, EditMenuOptions.Delete);
            }
            else
            {
                editMenu.AddDisabledItem(new GUIContent("Delete                Del"));
            }

            if (_inputManager.inputConfigurations.Count > 0)
            {
                editMenu.AddItem(new GUIContent("Delete All"), false, HandleEditMenuOption, EditMenuOptions.DeleteAll);
            }
            else
            {
                editMenu.AddDisabledItem(new GUIContent("Delete All"));
            }

            if (_selectionPath.Count >= 2)
            {
                editMenu.AddItem(new GUIContent("Copy"), false, HandleEditMenuOption, EditMenuOptions.Copy);
            }
            else
            {
                editMenu.AddDisabledItem(new GUIContent("Copy"));
            }

            if (_copySource != null && _selectionPath.Count >= 2)
            {
                editMenu.AddItem(new GUIContent("Paste"), false, HandleEditMenuOption, EditMenuOptions.Paste);
            }
            else
            {
                editMenu.AddDisabledItem(new GUIContent("Paste"));
            }

            editMenu.AddSeparator("");

            editMenu.AddItem(new GUIContent("Select Target"), false, HandleEditMenuOption, EditMenuOptions.SelectTarget);
            editMenu.AddItem(new GUIContent("Ignore Timescale"), _inputManager.ignoreTimescale, HandleEditMenuOption, EditMenuOptions.IgnoreTimescale);
            editMenu.AddItem(new GUIContent("Dont Destroy On Load"), _inputManager.dontDestroyOnLoad, HandleEditMenuOption, EditMenuOptions.DontDestroyOnLoad);
            editMenu.DropDown(position);
        }
    // Show the available mono behaviour method list menu.
    protected void ShowMethodEventMenu(SerializedProperty cMethodList)
    {
        // Now create the menu, add items and show it.
        GenericMenu cMenu = new GenericMenu();
        Array aMethodEnum = Enum.GetValues(typeof(YwLuaMonoBehaviourParams.EMonoMethod));
        for (int i = 0; i < aMethodEnum.Length; i++)
        {
            bool bActive = true;
            int nEventIndex = (int)aMethodEnum.GetValue(i);

            // Check if we already have a Entry for the current eventType, if so, disable it.
            for (int j = 0; j < cMethodList.arraySize; j++)
            {
                SerializedProperty cEvent = cMethodList.GetArrayElementAtIndex(j);
                if (cEvent.enumValueIndex == nEventIndex)
                {
                    bActive = false;
                    break;
                }
            }

            if (bActive)
            {
                cMenu.AddItem(new GUIContent(aMethodEnum.GetValue(i).ToString()), false, MethodEventMenuCallback, new MethodMenuEventParam(cMethodList, nEventIndex));
            }
            else
            {
                cMenu.AddDisabledItem(new GUIContent(aMethodEnum.GetValue(i).ToString()));
            }
        }

        cMenu.ShowAsContext();
        Event.current.Use();
    }