Skip to content

Commit

Permalink
- Fixed bug in group creation logic that could lead to properties bei…
Browse files Browse the repository at this point in the history
…ng part of groups because their names were similar

- Fixed error when using undo after a node was deleted
- Removed old keydown recognition system
- fixed a visibility related null ref in GraphModelEditor
- removed faulty isExpanded property from foldouts (they are just claused on default now)
- fixed HasSelectedEdges check that worked with the wrong field
- fixed long foldout label that prevented node dragging
  • Loading branch information
Doppelkeks committed Mar 10, 2023
1 parent ee69b15 commit c5db61c
Show file tree
Hide file tree
Showing 13 changed files with 134 additions and 25 deletions.
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.1.8] - 2023-03-09
### Fixed
- Fixed settings file not serializing correctly.

## [0.1.9] - 2023-03-09
### Added
- Added workaround for bugged KeyDownEvent by implementing global key events
### Fixed
- Fixed bug in group creation logic that could lead to properties being part of groups because their names were similar
- Fixed error when using undo after a node was deleted
- Removed old keydown recognition system
- fixed a visibility related null ref in GraphModelEditor
- removed faulty isExpanded property from foldouts (they are just claused on default now)
- fixed HasSelectedEdges check that worked with the wrong field
- fixed long foldout label that prevented node dragging
41 changes: 41 additions & 0 deletions Editor/Helpers/GlobalKeyHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using UnityEditor;
using UnityEngine;

/// <summary>
/// Thanks to https://forum.unity.com/threads/4-6-editorapplication-modifierkeyschanged-how-to-find-out-which-key-was-pressed.357367/#post-2705846
/// </summary>
public static class GlobalKeyEventHandler {
public static event Action<Event> OnKeyEvent;
public static bool RegistrationSucceeded = false;

static GlobalKeyEventHandler() {
RegistrationSucceeded = false;
string msg = "";
try {
System.Reflection.FieldInfo info = typeof(EditorApplication).GetField("globalEventHandler", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
if (info != null) {
EditorApplication.CallbackFunction value = (EditorApplication.CallbackFunction)info.GetValue(null);

value -= onKeyPressed;
value += onKeyPressed;

info.SetValue(null, value);

RegistrationSucceeded = true;
} else {
msg = "globalEventHandler not found";
}
} catch (Exception e) {
msg = e.Message;
} finally {
if (!RegistrationSucceeded) {
Debug.LogWarning("GlobalKeyEventHandler: error while registering for globalEventHandler: " + msg);
}
}
}

private static void onKeyPressed() {
OnKeyEvent?.Invoke(Event.current);
}
}
11 changes: 11 additions & 0 deletions Editor/Helpers/GlobalKeyHandler.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions Editor/Serialization/PropertyBag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,12 +267,16 @@ private int RetrieveCurrentAttributes() {
private void FindGroupAndAdd(ref string relativePath, GraphPropertyInfo propertyInfo) {
GroupInfo groupPropertyBelongsTo = null;
if (groupInfoLookup.Count > 0) {
string[] levels = relativePath.Split('.');

// loop backwards to find the most inner group first!
for (int i = groupInfoLookup.Count - 1; i >= 0; i--) {
GroupInfo groupInfo = groupInfoLookup[i];
if (relativePath.Contains(groupInfo.relativePropertyPath)) {
groupPropertyBelongsTo = groupInfo;
break;
if (groupInfo.levels.Length < levels.Length) {
if(levels[levels.Length-2] == groupInfo.levels[groupInfo.levels.Length - 1]) {
groupPropertyBelongsTo = groupInfo;
break;
}
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions Editor/Serialization/PropertyInfo/GroupInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ namespace NewGraph {
public class GroupInfo : GraphPropertyInfo {
public string groupName;
public List<PropertyInfo> graphProperties = new List<PropertyInfo>();
public string[] levels = new string[] {};

public GroupInfo(string groupName, string relativePropertyPath, GraphDisplayAttribute graphDisplayAttribute) : base(relativePropertyPath, graphDisplayAttribute) {
this.groupName = groupName;
this.levels = relativePropertyPath.Split('.');
}

}
Expand Down
1 change: 1 addition & 0 deletions Editor/Views/Elements/EditableLabelElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ private void OnKeyDown(KeyDownEvent evt) {
// enter/escape = exit edit mode
if (isInitialized && isInEditMode && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.Escape)) {
EnableInput(false);
evt.StopImmediatePropagation();
}
}

Expand Down
8 changes: 7 additions & 1 deletion Editor/Views/GraphModelEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,15 @@ private VisualElement MakeItem() {
}

private void BindItem(VisualElement itemRow, int i) {
serializedObject.Update();
SerializedProperty prop = listProperty.GetArrayElementAtIndex(i);
Label label = itemRow[0] as Label;
label.text = $"Element {i+1}: {prop.FindPropertyRelative(NodeModel.nameIdentifier).stringValue}";
if (prop != null) {
SerializedProperty propRelative = prop.FindPropertyRelative(NodeModel.nameIdentifier);
if (propRelative != null) {
label.text = $"Element {i + 1}: {propRelative.stringValue}";
}
}
}

private void OpenGraphClicked() {
Expand Down
21 changes: 16 additions & 5 deletions Editor/Views/GraphView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,8 @@ public class GraphView : GraphViewBase.GraphView {
public MouseDown OnMouseDown { get; set; }

public GraphView(VisualElement parent, VisualElement root, Action<Actions, object> OnAction) {
// this fixes a bug where keyevents are not fired sometimes
// with this we are attaching a keyevent listener to the up most root object of the window.
root.RegisterCallback<KeyDownEvent>(base.ExecuteDefaultAction);
GraphWindow.OnGlobalKeyDown -= OnKeyDown;
GraphWindow.OnGlobalKeyDown += OnKeyDown;
root.RegisterCallback<MouseDownEvent>((evt) => { OnMouseDown(evt); });

graphViewRoot = parent.Q<VisualElement>(nameof(graphViewRoot));
Expand All @@ -28,6 +27,10 @@ public GraphView(VisualElement parent, VisualElement root, Action<Actions, objec
this.OnAction = OnAction;
}

private void OnKeyDown(Event evt) {
ExecuteShortcutHandler(evt.keyCode, evt.modifiers);
}

public Vector2 LocalToViewTransformPosition(Vector2 localMousePosition) {
return new Vector2((localMousePosition.x - ContentContainer.transform.position.x) / ContentContainer.transform.scale.x, (localMousePosition.y - ContentContainer.transform.position.y) / ContentContainer.transform.scale.y);
}
Expand All @@ -40,6 +43,14 @@ public Vector2 GetCurrentMouseViewPosition() {
return LocalToViewTransformPosition(this.WorldToLocal(mousePosition));
}

/// <summary>
/// Empty override to prevent defualt logic due to keydown event bugs.
/// </summary>
/// <param name="baseEvent"></param>
protected override void ExecuteDefaultAction(EventBase baseEvent) {
//base.ExecuteDefaultAction(baseEvent);
}

public void SetSelected(GraphElement graphElement, bool selected = true, bool clear = true) {
if (clear) {
ClearSelection();
Expand All @@ -65,7 +76,6 @@ public void ClearView() {
}



public BaseNode GetFirstSelectedNode() {
return ContentContainer.NodesSelected.First();
}
Expand All @@ -84,7 +94,8 @@ public int GetSelectedEdgesCount() {
}

public bool HasSelectedEdges() {
return ContentContainer.NodesSelected.Count() > 0 ? true : false;

return ContentContainer.EdgesSelected.Count() > 0 ? true : false;
}

public void ForEachPortDo(Action<BasePort> callback) {
Expand Down
21 changes: 19 additions & 2 deletions Editor/Views/GraphWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@
using static NewGraph.GraphSettingsSingleton;

namespace NewGraph {
/// <summary>
/// The actual editor window for our graph.
/// Contains a key down workaround to prevent an issue where key down events are passing through elements instead of bein received.
/// https://forum.unity.com/threads/capturing-keydownevents-in-editorwindow-and-focus.762155/
/// </summary>
public class GraphWindow : EditorWindow {

private GraphController graphController;
private PlayModeStateChange lastState;
private static GraphWindow window;

public static event System.Action<Event> OnGlobalKeyDown;

[MenuItem(GraphSettings.menuItemBase+nameof(GraphWindow))]
public static void Initialize() {
window = GetWindow<GraphWindow>(nameof(GraphWindow));
Expand All @@ -20,6 +27,14 @@ public static void Initialize() {
private void OnEnable() {
EditorApplication.playModeStateChanged -= LogPlayModeState;
EditorApplication.playModeStateChanged += LogPlayModeState;
GlobalKeyEventHandler.OnKeyEvent -= HandleGlobalKeyPressEvents;
GlobalKeyEventHandler.OnKeyEvent += HandleGlobalKeyPressEvents;
}

private void HandleGlobalKeyPressEvents(Event evt) {
if (evt.isKey && mouseOverWindow == this && hasFocus) {
OnGlobalKeyDown?.Invoke(evt);
}
}

public void LogPlayModeState(PlayModeStateChange state) {
Expand All @@ -35,6 +50,8 @@ private void OnGUI() {

private void OnDisable() {
graphController?.Disable();
GlobalKeyEventHandler.OnKeyEvent -= HandleGlobalKeyPressEvents;
EditorApplication.playModeStateChanged -= LogPlayModeState;
}

public static Vector2 screenPosition {
Expand All @@ -43,7 +60,7 @@ public static Vector2 screenPosition {
Initialize();
}
return window.position.position;
}
}
}

public static void Redraw() {
Expand Down Expand Up @@ -72,7 +89,7 @@ private void CreateGUI() {
if (lastLoadedGraph != null) {
graphController.OpenGraphExternal(lastLoadedGraph);
}
}

}
}
}
19 changes: 8 additions & 11 deletions Editor/Views/NodeView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,18 @@ void AddAtIndex(int index, bool empty) {
if (!empty) {
SerializedProperty prop = property.Copy();
Foldout newGroup = new Foldout();
newGroup.pickingMode = PickingMode.Ignore;
newGroup.AddToClassList(nameof(GroupInfo));
newGroup.text = groupInfo.groupName;
newGroup.name = groupInfo.relativePropertyPath;
newGroup.value = false /*prop.isExpanded*/;
/*
newGroup.RegisterValueChangedCallback((evt) => {
prop.isExpanded = evt.newValue;
prop.serializedObject.ApplyModifiedProperties();
});
newGroup.bindingPath = prop.propertyPath;
*/
newGroup.name = "unity-foldout-" + prop.propertyPath;
newGroups[index] = newGroup;
} else {
Expand Down Expand Up @@ -213,10 +221,6 @@ private void CreateLabelUI(SerializedProperty property) {

private void BindUI(SerializedObject serializedObject) {
this.Bind(serializedObject);
/*
if (inspectorContent != null) {
inspectorContent.Bind(serializedObject);
}*/
}


Expand All @@ -232,13 +236,6 @@ private PropertyField CreatePropertyField(SerializedProperty property) {
bindingPath = property.propertyPath,
};

/*
if (property.propertyType != SerializedPropertyType.ManagedReference) {
Debug.Log($" {property.name} {property.propertyPath} {property.propertyType} {property.depth}");
} else {
Debug.Log($" {property.name} {property.propertyPath} {property.propertyType} {property.managedReferenceId} {property.managedReferenceFullTypename}");
}*/

return propertyField;
}

Expand Down
4 changes: 4 additions & 0 deletions Editor/Views/USS/NewGraph.uss
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,17 @@ GridBackground.grid-background {
}

.GroupInfo {
margin-top: 3px;
padding-right: 3px;
background-color: rgba(25, 25, 25, 0.2);
border-radius: 3px;
border-width: 1px 1px 1px 1px;
border-color: rgba(0, 0, 0, 0.3);
}

Foldout.GroupInfo Toggle{
max-width:50px;
}
.unity-base-field__label {
min-width: 80px;
}
Expand Down
7 changes: 5 additions & 2 deletions Models/GraphModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,11 @@ public void RemoveNode(NodeModel node) {
}

public void RemoveNodes(List<NodeModel> nodesToRemove) {
foreach (NodeModel node in nodesToRemove) {
RemoveNode(node);
if (nodesToRemove.Count > 0) {
Undo.RecordObject(this, "Remove Nodes");
foreach (NodeModel node in nodesToRemove) {
RemoveNode(node);
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "com.gentlymad.newgraph",
"version": "0.1.8",
"version": "0.1.9",
"displayName": "NewGraph",
"description": "Our general node graph solution. This is build upon the idea to visualize complex data structures as graph networks without having to modify already established data classes, except adding [Node], [Port] and [SerializeReference] attributes to call classes that should show in the Graph View.",
"unity": "2022.2",
Expand Down

0 comments on commit c5db61c

Please sign in to comment.