using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace XNodeEditor.Internal {
/// Handles caching of custom editor classes and their target types. Accessible with GetEditor(Type type)
/// Editor Type. Should be the type of the deriving script itself (eg. NodeEditor)
/// Attribute Type. The attribute used to connect with the runtime type (eg. CustomNodeEditorAttribute)
/// Runtime Type. The Object this can be an editor for (eg. Node)
public abstract class NodeEditorBase : Editor where A : Attribute, INodeEditorAttrib where T : NodeEditorBase where K : UnityEngine.Object {
/// Custom editors defined with [CustomNodeEditor]
private static Dictionary editorTypes;
private static Dictionary editors = new Dictionary();
public NodeEditorWindow window;
public new K target { get { return _target == base.target ? _target : _target = (K) base.target; } set { base.target = value; } }
private K _target;
public static T GetEditor(Q target, NodeEditorWindow window) where Q : class {
if ((target as UnityEngine.Object) == null) return default(T);
T editor;
if (!editors.TryGetValue(target as K, out editor)) {
Type type = target.GetType();
Type editorType = GetEditorType(type);
editor = (T) Editor.CreateEditor(target as UnityEngine.Object, editorType);
editor.window = window;
editors.Add(target as K, editor);
}
if (editor.target == null) editor.Initialize(new UnityEngine.Object[] { target as UnityEngine.Object });
if (editor.window != window) editor.window = window;
return editor;
}
private static Type GetEditorType(Type type) {
if (type == null) return null;
if (editorTypes == null) CacheCustomEditors();
Type result;
if (editorTypes.TryGetValue(type, out result)) return result;
//If type isn't found, try base type
return GetEditorType(type.BaseType);
}
private static void CacheCustomEditors() {
editorTypes = new Dictionary();
//Get all classes deriving from NodeEditor via reflection
Type[] nodeEditors = XNodeEditor.NodeEditorWindow.GetDerivedTypes(typeof(T));
for (int i = 0; i < nodeEditors.Length; i++) {
if (nodeEditors[i].IsAbstract) continue;
var attribs = nodeEditors[i].GetCustomAttributes(typeof(A), false);
if (attribs == null || attribs.Length == 0) continue;
A attrib = attribs[0] as A;
editorTypes.Add(attrib.GetInspectedType(), nodeEditors[i]);
}
}
}
public interface INodeEditorAttrib {
Type GetInspectedType();
}
}