diff --git a/Assets/QuickSheet/Editor/BaseMachine.cs b/Assets/QuickSheet/Editor/BaseMachine.cs index 8f2c1d3..41b8506 100644 --- a/Assets/QuickSheet/Editor/BaseMachine.cs +++ b/Assets/QuickSheet/Editor/BaseMachine.cs @@ -6,10 +6,11 @@ /// /////////////////////////////////////////////////////////////////////////////// using UnityEngine; +using UnityEditor; using System.Collections; using System.Collections.Generic; -namespace UnityEditor +namespace UnityQuicksheet { [System.Serializable] public class HeaderColumn diff --git a/Assets/QuickSheet/Editor/BaseMachineEditor.cs b/Assets/QuickSheet/Editor/BaseMachineEditor.cs index d3212fc..b79dd09 100644 --- a/Assets/QuickSheet/Editor/BaseMachineEditor.cs +++ b/Assets/QuickSheet/Editor/BaseMachineEditor.cs @@ -11,302 +11,304 @@ using System.Collections.Generic; using System.IO; - -/// -/// -/// -[CustomEditor(typeof(BaseMachine))] -public class BaseMachineEditor : Editor +namespace UnityQuicksheet { - protected BaseMachine machine; - - protected readonly string NoTemplateString = "No Template File Found"; - - protected virtual void Import(bool reimport = false) - { - Debug.LogWarning("!!! It should be implemented in the derived class !!!"); - } - /// - /// Generate script files with the given templates. - /// Total four files are generated, two for runtime and others for editor. + /// /// - protected virtual ScriptPrescription Generate(BaseMachine m) + [CustomEditor(typeof(BaseMachine))] + public class BaseMachineEditor : Editor { - if (m == null) - return null; + protected BaseMachine machine; - ScriptPrescription sp = new ScriptPrescription(); + protected readonly string NoTemplateString = "No Template File Found"; - if (m.onlyCreateDataClass) + protected virtual void Import(bool reimport = false) { - CreateDataClassScript(m, sp); + Debug.LogWarning("!!! It should be implemented in the derived class !!!"); } - else + + /// + /// Generate script files with the given templates. + /// Total four files are generated, two for runtime and others for editor. + /// + protected virtual ScriptPrescription Generate(BaseMachine m) { - CreateScriptableObjectClassScript(m, sp); - CreateScriptableObjectEditorClassScript(m, sp); - CreateDataClassScript(m, sp); - CreateAssetCreationScript(m, sp); - } + if (m == null) + return null; - AssetDatabase.Refresh(); + ScriptPrescription sp = new ScriptPrescription(); - return sp; - } + if (m.onlyCreateDataClass) + { + CreateDataClassScript(m, sp); + } + else + { + CreateScriptableObjectClassScript(m, sp); + CreateScriptableObjectEditorClassScript(m, sp); + CreateDataClassScript(m, sp); + CreateAssetCreationScript(m, sp); + } - /// - /// Create a ScriptableObject class and write it down on the specified folder. - /// - protected void CreateScriptableObjectClassScript(BaseMachine machine, ScriptPrescription sp) - { - sp.className = machine.WorkSheetName; - sp.dataClassName = machine.WorkSheetName + "Data"; - sp.template = GetTemplate("ScriptableObjectClass"); - - // check the directory path exists - string fullPath = TargetPathForClassScript(machine.WorkSheetName); - string folderPath = Path.GetDirectoryName(fullPath); - if (!Directory.Exists(folderPath)) - { - EditorUtility.DisplayDialog( - "Warning", - "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.", - "OK" - ); - return; - } + AssetDatabase.Refresh(); - StreamWriter writer = null; - try - { - // write a script to the given folder. - writer = new StreamWriter(fullPath); - writer.Write(new NewScriptGenerator(sp).ToString()); - } - catch (System.Exception e) - { - Debug.LogError(e); + return sp; } - finally + + /// + /// Create a ScriptableObject class and write it down on the specified folder. + /// + protected void CreateScriptableObjectClassScript(BaseMachine machine, ScriptPrescription sp) { - if (writer != null) + sp.className = machine.WorkSheetName; + sp.dataClassName = machine.WorkSheetName + "Data"; + sp.template = GetTemplate("ScriptableObjectClass"); + + // check the directory path exists + string fullPath = TargetPathForClassScript(machine.WorkSheetName); + string folderPath = Path.GetDirectoryName(fullPath); + if (!Directory.Exists(folderPath)) { - writer.Close(); - writer.Dispose(); + EditorUtility.DisplayDialog( + "Warning", + "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.", + "OK" + ); + return; + } + + StreamWriter writer = null; + try + { + // write a script to the given folder. + writer = new StreamWriter(fullPath); + writer.Write(new NewScriptGenerator(sp).ToString()); + } + catch (System.Exception e) + { + Debug.LogError(e); + } + finally + { + if (writer != null) + { + writer.Close(); + writer.Dispose(); + } } } - } - /// - /// Create a ScriptableObject editor class and write it down on the specified folder. - /// - protected void CreateScriptableObjectEditorClassScript(BaseMachine machine, ScriptPrescription sp) - { - sp.className = machine.WorkSheetName + "Editor"; - sp.worksheetClassName = machine.WorkSheetName; - sp.dataClassName = machine.WorkSheetName + "Data"; - sp.template = GetTemplate("ScriptableObjectEditorClass"); - - // check the directory path exists - string fullPath = TargetPathForEditorScript(machine.WorkSheetName); - string folderPath = Path.GetDirectoryName(fullPath); - if (!Directory.Exists(folderPath)) + /// + /// Create a ScriptableObject editor class and write it down on the specified folder. + /// + protected void CreateScriptableObjectEditorClassScript(BaseMachine machine, ScriptPrescription sp) { - EditorUtility.DisplayDialog( - "Warning", - "The folder for editor script files does not exist. Check the path " + folderPath + " exists.", - "OK" - ); - return; + sp.className = machine.WorkSheetName + "Editor"; + sp.worksheetClassName = machine.WorkSheetName; + sp.dataClassName = machine.WorkSheetName + "Data"; + sp.template = GetTemplate("ScriptableObjectEditorClass"); + + // check the directory path exists + string fullPath = TargetPathForEditorScript(machine.WorkSheetName); + string folderPath = Path.GetDirectoryName(fullPath); + if (!Directory.Exists(folderPath)) + { + EditorUtility.DisplayDialog( + "Warning", + "The folder for editor script files does not exist. Check the path " + folderPath + " exists.", + "OK" + ); + return; + } + + StreamWriter writer = null; + try + { + // write a script to the given folder. + writer = new StreamWriter(fullPath); + writer.Write(new NewScriptGenerator(sp).ToString()); + } + catch (System.Exception e) + { + Debug.LogError(e); + } + finally + { + if (writer != null) + { + writer.Close(); + writer.Dispose(); + } + } } - StreamWriter writer = null; - try + /// + /// Create a data class which describes the spreadsheet and write it down on the specified folder. + /// + protected void CreateDataClassScript(BaseMachine machine, ScriptPrescription sp) { + // check the directory path exists + string fullPath = TargetPathForData(machine.WorkSheetName); + string folderPath = Path.GetDirectoryName(fullPath); + if (!Directory.Exists(folderPath)) + { + EditorUtility.DisplayDialog( + "Warning", + "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.", + "OK" + ); + return; + } + + List fieldList = new List(); + + //FIXME: replace ValueType to CellType and support Enum type. + foreach (HeaderColumn header in machine.HeaderColumnList) + { + MemberFieldData member = new MemberFieldData(); + member.Name = header.name; + member.type = header.type; + member.IsArrayType = header.isArray; + + fieldList.Add(member); + } + + sp.className = machine.WorkSheetName + "Data"; + sp.template = GetTemplate("DataClass"); + + sp.memberFields = fieldList.ToArray(); + // write a script to the given folder. - writer = new StreamWriter(fullPath); - writer.Write(new NewScriptGenerator(sp).ToString()); - } - catch (System.Exception e) - { - Debug.LogError(e); - } - finally - { - if (writer != null) + using (var writer = new StreamWriter(fullPath)) { + writer.Write(new NewScriptGenerator(sp).ToString()); writer.Close(); - writer.Dispose(); } } - } - /// - /// Create a data class which describes the spreadsheet and write it down on the specified folder. - /// - protected void CreateDataClassScript(BaseMachine machine, ScriptPrescription sp) - { - // check the directory path exists - string fullPath = TargetPathForData(machine.WorkSheetName); - string folderPath = Path.GetDirectoryName(fullPath); - if (!Directory.Exists(folderPath)) + protected virtual void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) { - EditorUtility.DisplayDialog( - "Warning", - "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.", - "OK" - ); - return; + Debug.LogWarning("!!! It should be implemented in the derived class !!!"); } - List fieldList = new List(); - - //FIXME: replace ValueType to CellType and support Enum type. - foreach (HeaderColumn header in machine.HeaderColumnList) + /// + /// e.g. "Assets/Script/Data/Runtime/Item.cs" + /// + protected string TargetPathForClassScript(string worksheetName) { - MemberFieldData member = new MemberFieldData(); - member.Name = header.name; - member.type = header.type; - member.IsArrayType = header.isArray; - - fieldList.Add(member); + return Path.Combine("Assets/" + machine.RuntimeClassPath, worksheetName + "." + "cs"); } - sp.className = machine.WorkSheetName + "Data"; - sp.template = GetTemplate("DataClass"); - - sp.memberFields = fieldList.ToArray(); - - // write a script to the given folder. - using (var writer = new StreamWriter(fullPath)) + /// + /// e.g. "Assets/Script/Data/Editor/ItemEditor.cs" + /// + protected string TargetPathForEditorScript(string worksheetName) { - writer.Write(new NewScriptGenerator(sp).ToString()); - writer.Close(); + return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "Editor" + "." + "cs"); } - } - - protected virtual void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) - { - Debug.LogWarning("!!! It should be implemented in the derived class !!!"); - } - - /// - /// e.g. "Assets/Script/Data/Runtime/Item.cs" - /// - protected string TargetPathForClassScript(string worksheetName) - { - return Path.Combine("Assets/" + machine.RuntimeClassPath, worksheetName + "." + "cs"); - } - - /// - /// e.g. "Assets/Script/Data/Editor/ItemEditor.cs" - /// - protected string TargetPathForEditorScript(string worksheetName) - { - return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "Editor" + "." + "cs"); - } - - /// - /// data class script file has 'WorkSheetNameData' for its filename. - /// e.g. "Assets/Script/Data/Runtime/ItemData.cs" - /// - protected string TargetPathForData(string worksheetName) - { - return Path.Combine("Assets/" + machine.RuntimeClassPath, worksheetName + "Data" + "." + "cs"); - } - - /// - /// e.g. "Assets/Script/Data/Editor/ItemAssetCreator.cs" - /// - protected string TargetPathForAssetFileCreateFunc(string worksheetName) - { - return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "AssetCreator" + "." + "cs"); - } - /// - /// AssetPostprocessor class should be under "Editor" folder. - /// - protected string TargetPathForAssetPostProcessorFile(string worksheetName) - { - return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "AssetPostProcessor" + "." + "cs"); - } + /// + /// data class script file has 'WorkSheetNameData' for its filename. + /// e.g. "Assets/Script/Data/Runtime/ItemData.cs" + /// + protected string TargetPathForData(string worksheetName) + { + return Path.Combine("Assets/" + machine.RuntimeClassPath, worksheetName + "Data" + "." + "cs"); + } - /// - /// Retrieves all ascii text in the given template file. - /// - protected string GetTemplate(string nameWithoutExtension) - { - string path = Path.Combine(GetAbsoluteCustomTemplatePath(), nameWithoutExtension + ".txt"); - if (File.Exists(path)) - return File.ReadAllText(path); + /// + /// e.g. "Assets/Script/Data/Editor/ItemAssetCreator.cs" + /// + protected string TargetPathForAssetFileCreateFunc(string worksheetName) + { + return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "AssetCreator" + "." + "cs"); + } - path = Path.Combine(GetAbsoluteBuiltinTemplatePath(), nameWithoutExtension + ".txt"); - if (File.Exists(path)) - return File.ReadAllText(path); + /// + /// AssetPostprocessor class should be under "Editor" folder. + /// + protected string TargetPathForAssetPostProcessorFile(string worksheetName) + { + return Path.Combine("Assets/" + machine.EditorClassPath, worksheetName + "AssetPostProcessor" + "." + "cs"); + } - return NoTemplateString; - } + /// + /// Retrieves all ascii text in the given template file. + /// + protected string GetTemplate(string nameWithoutExtension) + { + string path = Path.Combine(GetAbsoluteCustomTemplatePath(), nameWithoutExtension + ".txt"); + if (File.Exists(path)) + return File.ReadAllText(path); - /// - /// e.g. "Assets/QuickSheet/Templates" - /// - protected string GetAbsoluteCustomTemplatePath() - { - return Path.Combine(Application.dataPath, machine.TemplatePath); - } + path = Path.Combine(GetAbsoluteBuiltinTemplatePath(), nameWithoutExtension + ".txt"); + if (File.Exists(path)) + return File.ReadAllText(path); - /// - /// e.g. "C:/Program File(x86)/Unity/Editor/Data" - /// - protected string GetAbsoluteBuiltinTemplatePath() - { - return Path.Combine(EditorApplication.applicationContentsPath, machine.TemplatePath); - } + return NoTemplateString; + } - protected void DrawHeaderSetting(BaseMachine m) - { - if (m.HasHeadColumn()) + /// + /// e.g. "Assets/QuickSheet/Templates" + /// + protected string GetAbsoluteCustomTemplatePath() { - GUIStyle headerStyle = GUIHelper.MakeHeader(); - GUILayout.Label("Type Settings:", headerStyle); - - const int MEMBER_WIDTH = 100; - GUILayout.BeginHorizontal(EditorStyles.toolbar); - GUILayout.Label("Member", GUILayout.MinWidth(MEMBER_WIDTH)); - GUILayout.FlexibleSpace(); - string[] names = { "Type", "Array" }; - int[] widths = { 55, 40 }; - for (int i=0; i + /// e.g. "C:/Program File(x86)/Unity/Editor/Data" + /// + protected string GetAbsoluteBuiltinTemplatePath() + { + return Path.Combine(EditorApplication.applicationContentsPath, machine.TemplatePath); + } - //string lastCellName = string.Empty; - foreach (HeaderColumn header in m.HeaderColumnList) + protected void DrawHeaderSetting(BaseMachine m) + { + if (m.HasHeadColumn()) { - GUILayout.BeginHorizontal(); + GUIStyle headerStyle = GUIHelper.MakeHeader(); + GUILayout.Label("Type Settings:", headerStyle); - // member field label - EditorGUILayout.LabelField(header.name, GUILayout.MinWidth(MEMBER_WIDTH)); + const int MEMBER_WIDTH = 100; + GUILayout.BeginHorizontal(EditorStyles.toolbar); + GUILayout.Label("Member", GUILayout.MinWidth(MEMBER_WIDTH)); GUILayout.FlexibleSpace(); - - // type enum popup - header.type = (CellType)EditorGUILayout.EnumPopup(header.type, GUILayout.Width(60)); - GUILayout.Space(20); - - // array toggle - header.isArray = EditorGUILayout.Toggle(header.isArray, GUILayout.Width(20)); - GUILayout.Space(10); - GUILayout.EndHorizontal(); + string[] names = { "Type", "Array" }; + int[] widths = { 55, 40 }; + for (int i = 0; i < names.Length; i++) + { + GUILayout.Label(new GUIContent(names[i]), GUILayout.Width(widths[i])); + } + GUILayout.EndHorizontal();//EditorStyles.toolbar + + //curretScroll = EditorGUILayout.BeginScrollView(curretScroll, false, false); + EditorGUILayout.BeginVertical("box"); + + //string lastCellName = string.Empty; + foreach (HeaderColumn header in m.HeaderColumnList) + { + GUILayout.BeginHorizontal(); + + // member field label + EditorGUILayout.LabelField(header.name, GUILayout.MinWidth(MEMBER_WIDTH)); + GUILayout.FlexibleSpace(); + + // type enum popup + header.type = (CellType)EditorGUILayout.EnumPopup(header.type, GUILayout.Width(60)); + GUILayout.Space(20); + + // array toggle + header.isArray = EditorGUILayout.Toggle(header.isArray, GUILayout.Width(20)); + GUILayout.Space(10); + GUILayout.EndHorizontal(); + } + + EditorGUILayout.EndVertical(); //box + //EditorGUILayout.EndScrollView(); } - - EditorGUILayout.EndVertical(); //box - //EditorGUILayout.EndScrollView(); } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/Editor/GUIHelper.cs b/Assets/QuickSheet/Editor/GUIHelper.cs index 36a9804..5611426 100644 --- a/Assets/QuickSheet/Editor/GUIHelper.cs +++ b/Assets/QuickSheet/Editor/GUIHelper.cs @@ -8,14 +8,17 @@ using UnityEngine; using UnityEditor; -public static class GUIHelper +namespace UnityQuicksheet { - public static GUIStyle MakeHeader() + public static class GUIHelper { - GUIStyle headerStyle = new GUIStyle(GUI.skin.label); - headerStyle.fontSize = 12; - headerStyle.fontStyle = FontStyle.Bold; + public static GUIStyle MakeHeader() + { + GUIStyle headerStyle = new GUIStyle(GUI.skin.label); + headerStyle.fontSize = 12; + headerStyle.fontStyle = FontStyle.Bold; - return headerStyle; + return headerStyle; + } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/Editor/NewScriptGenerator.cs b/Assets/QuickSheet/Editor/NewScriptGenerator.cs index da49985..f4dd29f 100644 --- a/Assets/QuickSheet/Editor/NewScriptGenerator.cs +++ b/Assets/QuickSheet/Editor/NewScriptGenerator.cs @@ -7,6 +7,7 @@ /////////////////////////////////////////////////////////////////////////////// using System; using UnityEngine; +using UnityEditor; using System.Linq; using System.IO; using System.Text.RegularExpressions; @@ -15,7 +16,7 @@ using Object = UnityEngine.Object; -namespace UnityEditor +namespace UnityQuicksheet { internal class NewScriptGenerator { diff --git a/Assets/QuickSheet/Editor/ScriptPrescription.cs b/Assets/QuickSheet/Editor/ScriptPrescription.cs index 070704c..045a2f5 100644 --- a/Assets/QuickSheet/Editor/ScriptPrescription.cs +++ b/Assets/QuickSheet/Editor/ScriptPrescription.cs @@ -7,13 +7,14 @@ /////////////////////////////////////////////////////////////////////////////// using System; using UnityEngine; +using UnityEditor; using System.Linq; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using Object = UnityEngine.Object; -namespace UnityEditor +namespace UnityQuicksheet { [Serializable] public class ScriptPrescription diff --git a/Assets/QuickSheet/ExcelPlugin/Editor/BaseExcelEditor.cs b/Assets/QuickSheet/ExcelPlugin/Editor/BaseExcelEditor.cs index 921b697..35ddf30 100644 --- a/Assets/QuickSheet/ExcelPlugin/Editor/BaseExcelEditor.cs +++ b/Assets/QuickSheet/ExcelPlugin/Editor/BaseExcelEditor.cs @@ -11,75 +11,78 @@ using System.Collections.Generic; using System.IO; -/// -/// Base class of the created .asset ScriptableObject class. -/// -public class BaseExcelEditor : Editor +namespace UnityQuicksheet { + /// + /// Base class of the created .asset ScriptableObject class. + /// + public class BaseExcelEditor : Editor + { - // to reflect properties on the Inspector view. - protected PropertyField[] databaseFields; - protected PropertyField[] dataFields; + // to reflect properties on the Inspector view. + protected PropertyField[] databaseFields; + protected PropertyField[] dataFields; - protected List pInfoList = new List(); + protected List pInfoList = new List(); - GUIStyle brown; - bool isInitialized = false; + GUIStyle brown; + bool isInitialized = false; - public virtual void OnEnable() - { - } - - private void InitGUISkin() - { - brown = new GUIStyle("box"); - brown.normal.background = Resources.Load("brown", typeof(Texture2D)) as Texture2D; - brown.border = new RectOffset(4, 4, 4, 4); - brown.margin = new RectOffset(3, 3, 3, 3); - brown.padding = new RectOffset(4, 4, 4, 4); - } + public virtual void OnEnable() + { + } - public override void OnInspectorGUI() - { - if (!isInitialized) + private void InitGUISkin() { - isInitialized = true; - InitGUISkin(); + brown = new GUIStyle("box"); + brown.normal.background = Resources.Load("brown", typeof(Texture2D)) as Texture2D; + brown.border = new RectOffset(4, 4, 4, 4); + brown.margin = new RectOffset(3, 3, 3, 3); + brown.padding = new RectOffset(4, 4, 4, 4); } - if (GUILayout.Button("Update")) + public override void OnInspectorGUI() { - if (!Load()) + if (!isInitialized) { - const string error1 = "\n- Check the path of the 'Sheet Name' and the file is exist at the path."; - const string error2 = "\n- Also check the excel file has the sheet which matches with 'Worksheet Name'."; - EditorUtility.DisplayDialog( - "Error", - "Failed to import and update the excel file." + error1 + error2, - "OK" - ); + isInitialized = true; + InitGUISkin(); } - } - if (target == null) - return; + if (GUILayout.Button("Update")) + { + if (!Load()) + { + const string error1 = "\n- Check the path of the 'Sheet Name' and the file is exist at the path."; + const string error2 = "\n- Also check the excel file has the sheet which matches with 'Worksheet Name'."; + EditorUtility.DisplayDialog( + "Error", + "Failed to import and update the excel file." + error1 + error2, + "OK" + ); + } + } - //this.DrawDefaultInspector(); - ExposeProperties.Expose(databaseFields); + if (target == null) + return; - foreach (PropertyField[] p in pInfoList) - { - GUILayout.BeginVertical(brown); - ExposeProperties.Expose(p); - GUILayout.EndVertical(); + //this.DrawDefaultInspector(); + ExposeProperties.Expose(databaseFields); + + foreach (PropertyField[] p in pInfoList) + { + GUILayout.BeginVertical(brown); + ExposeProperties.Expose(p); + GUILayout.EndVertical(); + } } - } - /// - /// Called when 'Update' button is pressed. It should be reimplemented in the derived class. - /// - public virtual bool Load() - { - return false; + /// + /// Called when 'Update' button is pressed. It should be reimplemented in the derived class. + /// + public virtual bool Load() + { + return false; + } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachine.cs b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachine.cs index 3e8e715..b13834d 100644 --- a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachine.cs +++ b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachine.cs @@ -6,9 +6,10 @@ /// /////////////////////////////////////////////////////////////////////////////// using UnityEngine; +using UnityEditor; using System.Collections; -namespace UnityEditor +namespace UnityQuicksheet { /// /// A class for various setting to read excel file and generated related script files. diff --git a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachineEditor.cs b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachineEditor.cs index 24fc956..18b9956 100644 --- a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachineEditor.cs +++ b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelMachineEditor.cs @@ -12,272 +12,275 @@ using System.IO; using System.Linq; -/// -/// Custom editor script class for excel file setting. -/// -[CustomEditor(typeof(ExcelMachine))] -public class ExcelMachineEditor : BaseMachineEditor +namespace UnityQuicksheet { - void OnEnable() + /// + /// Custom editor script class for excel file setting. + /// + [CustomEditor(typeof(ExcelMachine))] + public class ExcelMachineEditor : BaseMachineEditor { - machine = target as ExcelMachine; - if (machine != null) + void OnEnable() { - if (string.IsNullOrEmpty(ExcelSettings.Instance.RuntimePath) == false) - machine.RuntimeClassPath = ExcelSettings.Instance.RuntimePath; - if (string.IsNullOrEmpty(ExcelSettings.Instance.EditorPath) == false) - machine.EditorClassPath = ExcelSettings.Instance.EditorPath; + machine = target as ExcelMachine; + if (machine != null) + { + if (string.IsNullOrEmpty(ExcelSettings.Instance.RuntimePath) == false) + machine.RuntimeClassPath = ExcelSettings.Instance.RuntimePath; + if (string.IsNullOrEmpty(ExcelSettings.Instance.EditorPath) == false) + machine.EditorClassPath = ExcelSettings.Instance.EditorPath; + } } - } - public override void OnInspectorGUI() - { - ExcelMachine machine = target as ExcelMachine; + public override void OnInspectorGUI() + { + ExcelMachine machine = target as ExcelMachine; - GUIStyle headerStyle = GUIHelper.MakeHeader(); - GUILayout.Label("Excel Settings:", headerStyle); + GUIStyle headerStyle = GUIHelper.MakeHeader(); + GUILayout.Label("Excel Settings:", headerStyle); - GUILayout.BeginHorizontal(); - GUILayout.Label("File:", GUILayout.Width(50)); + GUILayout.BeginHorizontal(); + GUILayout.Label("File:", GUILayout.Width(50)); - string path = string.Empty; - if (string.IsNullOrEmpty(machine.excelFilePath)) - path = Application.dataPath; - else - path = machine.excelFilePath; + string path = string.Empty; + if (string.IsNullOrEmpty(machine.excelFilePath)) + path = Application.dataPath; + else + path = machine.excelFilePath; - machine.excelFilePath = GUILayout.TextField(path, GUILayout.Width(250)); - if (GUILayout.Button("...", GUILayout.Width(20))) - { - string folder = Path.GetDirectoryName(path); + machine.excelFilePath = GUILayout.TextField(path, GUILayout.Width(250)); + if (GUILayout.Button("...", GUILayout.Width(20))) + { + string folder = Path.GetDirectoryName(path); #if UNITY_EDITOR_WIN - path = EditorUtility.OpenFilePanel("Open Excel file", folder, "excel files;*.xls;*.xlsx"); + path = EditorUtility.OpenFilePanel("Open Excel file", folder, "excel files;*.xls;*.xlsx"); #else path = EditorUtility.OpenFilePanel("Open Excel file", folder, "xls"); #endif - if (path.Length != 0) - { - machine.SpreadSheetName = Path.GetFileName(path); - - // the path should be relative not absolute one to make it work on any platform. - int index = path.IndexOf("Assets"); - if (index >= 0) + if (path.Length != 0) { - // set relative path - machine.excelFilePath = path.Substring(index); - - // pass absolute path - machine.SheetNames = new ExcelQuery(path).GetSheetNames(); - } - else - { - EditorUtility.DisplayDialog("Error", - @"Wrong folder is selected. + machine.SpreadSheetName = Path.GetFileName(path); + + // the path should be relative not absolute one to make it work on any platform. + int index = path.IndexOf("Assets"); + if (index >= 0) + { + // set relative path + machine.excelFilePath = path.Substring(index); + + // pass absolute path + machine.SheetNames = new ExcelQuery(path).GetSheetNames(); + } + else + { + EditorUtility.DisplayDialog("Error", + @"Wrong folder is selected. Set a folder under the 'Assets' folder! \n The excel file should be anywhere under the 'Assets' folder", "OK"); - return; + return; + } } } - } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - // Failed to get sheet name so we just return not to make editor on going. - if (machine.SheetNames.Length == 0) - { - EditorGUILayout.Separator(); - EditorGUILayout.LabelField("Error: Failed to retrieve the specified excel file."); - EditorGUILayout.LabelField("If the excel file is opened, close it then reopen it again."); - return; - } + // Failed to get sheet name so we just return not to make editor on going. + if (machine.SheetNames.Length == 0) + { + EditorGUILayout.Separator(); + EditorGUILayout.LabelField("Error: Failed to retrieve the specified excel file."); + EditorGUILayout.LabelField("If the excel file is opened, close it then reopen it again."); + return; + } - machine.SpreadSheetName = EditorGUILayout.TextField("Spreadsheet File: ", machine.SpreadSheetName); + machine.SpreadSheetName = EditorGUILayout.TextField("Spreadsheet File: ", machine.SpreadSheetName); - EditorGUILayout.Space(); + EditorGUILayout.Space(); - using (new GUILayout.HorizontalScope()) - { - EditorGUILayout.LabelField("Worksheet: ", GUILayout.Width(100)); - machine.CurrentSheetIndex = EditorGUILayout.Popup(machine.CurrentSheetIndex, machine.SheetNames); - if (machine.SheetNames != null) - machine.WorkSheetName = machine.SheetNames[machine.CurrentSheetIndex]; - - if (GUILayout.Button("Refresh", GUILayout.Width(60))) + using (new GUILayout.HorizontalScope()) { - // reopen the excel file e.g) new worksheet is added so need to reopen. - machine.SheetNames = new ExcelQuery(machine.excelFilePath).GetSheetNames(); + EditorGUILayout.LabelField("Worksheet: ", GUILayout.Width(100)); + machine.CurrentSheetIndex = EditorGUILayout.Popup(machine.CurrentSheetIndex, machine.SheetNames); + if (machine.SheetNames != null) + machine.WorkSheetName = machine.SheetNames[machine.CurrentSheetIndex]; - // one of worksheet was removed, so reset the selected worksheet index - // to prevent the index out of range error. - if (machine.SheetNames.Length <= machine.CurrentSheetIndex) + if (GUILayout.Button("Refresh", GUILayout.Width(60))) { - machine.CurrentSheetIndex = 0; - - string message = "Worksheet was changed. Check the 'Worksheet' and 'Update' it again if it is necessary."; - EditorUtility.DisplayDialog("Info", message, "OK"); + // reopen the excel file e.g) new worksheet is added so need to reopen. + machine.SheetNames = new ExcelQuery(machine.excelFilePath).GetSheetNames(); + + // one of worksheet was removed, so reset the selected worksheet index + // to prevent the index out of range error. + if (machine.SheetNames.Length <= machine.CurrentSheetIndex) + { + machine.CurrentSheetIndex = 0; + + string message = "Worksheet was changed. Check the 'Worksheet' and 'Update' it again if it is necessary."; + EditorUtility.DisplayDialog("Info", message, "OK"); + } } } - } - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - GUILayout.BeginHorizontal(); + GUILayout.BeginHorizontal(); - if (machine.HasHeadColumn()) - { - if (GUILayout.Button("Update")) - Import(); - if (GUILayout.Button("Reimport")) - Import(true); - } - else - { - if (GUILayout.Button("Import")) - Import(); - } + if (machine.HasHeadColumn()) + { + if (GUILayout.Button("Update")) + Import(); + if (GUILayout.Button("Reimport")) + Import(true); + } + else + { + if (GUILayout.Button("Import")) + Import(); + } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - DrawHeaderSetting(machine); + DrawHeaderSetting(machine); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - GUILayout.Label("Path Settings:", headerStyle); + GUILayout.Label("Path Settings:", headerStyle); - machine.TemplatePath = EditorGUILayout.TextField("Template: ", machine.TemplatePath); - machine.RuntimeClassPath = EditorGUILayout.TextField("Runtime: ", machine.RuntimeClassPath); - machine.EditorClassPath = EditorGUILayout.TextField("Editor:", machine.EditorClassPath); - //machine.DataFilePath = EditorGUILayout.TextField("Data:", machine.DataFilePath); + machine.TemplatePath = EditorGUILayout.TextField("Template: ", machine.TemplatePath); + machine.RuntimeClassPath = EditorGUILayout.TextField("Runtime: ", machine.RuntimeClassPath); + machine.EditorClassPath = EditorGUILayout.TextField("Editor:", machine.EditorClassPath); + //machine.DataFilePath = EditorGUILayout.TextField("Data:", machine.DataFilePath); - machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass); + machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - if (GUILayout.Button("Generate")) - { - ScriptPrescription sp = Generate(machine); - if (sp != null) + if (GUILayout.Button("Generate")) { - Debug.Log("Successfully generated!"); + ScriptPrescription sp = Generate(machine); + if (sp != null) + { + Debug.Log("Successfully generated!"); + } + else + Debug.LogError("Failed to create a script from excel."); } - else - Debug.LogError("Failed to create a script from excel."); - } - if (GUI.changed) - { - EditorUtility.SetDirty(machine); - AssetDatabase.SaveAssets(); - AssetDatabase.Refresh(); + if (GUI.changed) + { + EditorUtility.SetDirty(machine); + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + } } - } - /// - /// Import the specified excel file and prepare to set type of each cell. - /// - protected override void Import(bool reimport = false) - { - base.Import(reimport); - - ExcelMachine machine = target as ExcelMachine; + /// + /// Import the specified excel file and prepare to set type of each cell. + /// + protected override void Import(bool reimport = false) + { + base.Import(reimport); - string path = machine.excelFilePath; - string sheet = machine.WorkSheetName; + ExcelMachine machine = target as ExcelMachine; - if (string.IsNullOrEmpty(path)) - { - EditorUtility.DisplayDialog( - "Error", - "You should specify spreadsheet file first!", - "OK" - ); - return; - } + string path = machine.excelFilePath; + string sheet = machine.WorkSheetName; - if (!File.Exists(path)) - { - EditorUtility.DisplayDialog( - "Error", - "File at " + path + " does not exist.", - "OK" - ); - return; - } + if (string.IsNullOrEmpty(path)) + { + EditorUtility.DisplayDialog( + "Error", + "You should specify spreadsheet file first!", + "OK" + ); + return; + } - var titles = new ExcelQuery(path, sheet).GetTitle(); - List titleList = titles.ToList(); + if (!File.Exists(path)) + { + EditorUtility.DisplayDialog( + "Error", + "File at " + path + " does not exist.", + "OK" + ); + return; + } - if (machine.HasHeadColumn() && reimport == false) - { - var headerDic = machine.HeaderColumnList.ToDictionary(header => header.name); + var titles = new ExcelQuery(path, sheet).GetTitle(); + List titleList = titles.ToList(); - // collect non changed header columns - var exist = from t in titleList - where headerDic.ContainsKey(t) == true - select new HeaderColumn { name = t, type = headerDic[t].type, OrderNO = headerDic[t].OrderNO }; + if (machine.HasHeadColumn() && reimport == false) + { + var headerDic = machine.HeaderColumnList.ToDictionary(header => header.name); - // collect newly added or changed header columns - var changed = from t in titleList - where headerDic.ContainsKey(t) == false - select new HeaderColumn { name = t, type = CellType.Undefined, OrderNO = titleList.IndexOf(t) }; + // collect non changed header columns + var exist = from t in titleList + where headerDic.ContainsKey(t) == true + select new HeaderColumn { name = t, type = headerDic[t].type, OrderNO = headerDic[t].OrderNO }; - // merge two - var merged = exist.Union(changed).OrderBy(x => x.OrderNO); + // collect newly added or changed header columns + var changed = from t in titleList + where headerDic.ContainsKey(t) == false + select new HeaderColumn { name = t, type = CellType.Undefined, OrderNO = titleList.IndexOf(t) }; - machine.HeaderColumnList.Clear(); - machine.HeaderColumnList = merged.ToList(); - } - else - { - machine.HeaderColumnList.Clear(); + // merge two + var merged = exist.Union(changed).OrderBy(x => x.OrderNO); - if (titles != null) - { - int i = 0; - foreach (string s in titles) - { - machine.HeaderColumnList.Add(new HeaderColumn { name = s, type = CellType.Undefined, OrderNO = i}); - i++; - } + machine.HeaderColumnList.Clear(); + machine.HeaderColumnList = merged.ToList(); } else { - Debug.LogWarning("The WorkSheet [" + sheet + "] may be empty."); + machine.HeaderColumnList.Clear(); + + if (titles != null) + { + int i = 0; + foreach (string s in titles) + { + machine.HeaderColumnList.Add(new HeaderColumn { name = s, type = CellType.Undefined, OrderNO = i }); + i++; + } + } + else + { + Debug.LogWarning("The WorkSheet [" + sheet + "] may be empty."); + } } - } - EditorUtility.SetDirty(machine); - AssetDatabase.SaveAssets(); - } + EditorUtility.SetDirty(machine); + AssetDatabase.SaveAssets(); + } - /// - /// Generate AssetPostprocessor editor script file. - /// - protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) - { - ExcelMachine machine = target as ExcelMachine; + /// + /// Generate AssetPostprocessor editor script file. + /// + protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) + { + ExcelMachine machine = target as ExcelMachine; - sp.className = machine.WorkSheetName; - sp.dataClassName = machine.WorkSheetName + "Data"; - sp.worksheetClassName = machine.WorkSheetName; + sp.className = machine.WorkSheetName; + sp.dataClassName = machine.WorkSheetName + "Data"; + sp.worksheetClassName = machine.WorkSheetName; - // where the imported excel file is. - sp.importedFilePath = machine.excelFilePath; + // where the imported excel file is. + sp.importedFilePath = machine.excelFilePath; - // path where the .asset file will be created. - string path = Path.GetDirectoryName(machine.excelFilePath); - path += "/" + machine.WorkSheetName + ".asset"; - sp.assetFilepath = path; - sp.assetPostprocessorClass = machine.WorkSheetName + "AssetPostprocessor"; - sp.template = GetTemplate("PostProcessor"); + // path where the .asset file will be created. + string path = Path.GetDirectoryName(machine.excelFilePath); + path += "/" + machine.WorkSheetName + ".asset"; + sp.assetFilepath = path; + sp.assetPostprocessorClass = machine.WorkSheetName + "AssetPostprocessor"; + sp.template = GetTemplate("PostProcessor"); - // write a script to the given folder. - using (var writer = new StreamWriter(TargetPathForAssetPostProcessorFile(machine.WorkSheetName))) - { - writer.Write(new NewScriptGenerator(sp).ToString()); - writer.Close(); + // write a script to the given folder. + using (var writer = new StreamWriter(TargetPathForAssetPostProcessorFile(machine.WorkSheetName))) + { + writer.Write(new NewScriptGenerator(sp).ToString()); + writer.Close(); + } } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelQuery.cs b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelQuery.cs index 5656981..fa95470 100644 --- a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelQuery.cs +++ b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelQuery.cs @@ -17,263 +17,266 @@ using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; -/// -/// Query each of cell data from the given excel sheet and deserialize it to the ScriptableObject's data array. -/// -public class ExcelQuery +namespace UnityQuicksheet { - private readonly IWorkbook workbook = null; - private readonly ISheet sheet = null; - private string filepath = string.Empty; - /// - /// Constructor. + /// Query each of cell data from the given excel sheet and deserialize it to the ScriptableObject's data array. /// - public ExcelQuery(string path, string sheetName = "") + public class ExcelQuery { - try - { - this.filepath = path; + private readonly IWorkbook workbook = null; + private readonly ISheet sheet = null; + private string filepath = string.Empty; - using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + /// + /// Constructor. + /// + public ExcelQuery(string path, string sheetName = "") + { + try { - string extension = GetSuffix(path); + this.filepath = path; - if (extension == "xls") - workbook = new HSSFWorkbook(fileStream); - else if (extension == "xlsx") + using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { + string extension = GetSuffix(path); + + if (extension == "xls") + workbook = new HSSFWorkbook(fileStream); + else if (extension == "xlsx") + { #if UNITY_MAC throw new Exception("xlsx is not supported on OSX."); #else - workbook = new XSSFWorkbook(fileStream); + workbook = new XSSFWorkbook(fileStream); #endif - } - else - { - throw new Exception("Wrong file."); - } + } + else + { + throw new Exception("Wrong file."); + } - if (!string.IsNullOrEmpty(sheetName)) - sheet = workbook.GetSheet(sheetName); + if (!string.IsNullOrEmpty(sheetName)) + sheet = workbook.GetSheet(sheetName); + } + } + catch (Exception e) + { + Debug.LogError(e.Message); } } - catch(Exception e) - { - Debug.LogError(e.Message); - } - } - - /// - /// Determine whether the excel file is successfully read in or not. - /// - public bool IsValid() - { - if (this.workbook != null && this.sheet != null) - return true; - - return false; - } - /// - /// Retrieves file extension only from the given file path. - /// - static string GetSuffix(string path) - { - string ext = Path.GetExtension(path); - string[] arg = ext.Split(new char[] { '.' }); - return arg[1]; - } + /// + /// Determine whether the excel file is successfully read in or not. + /// + public bool IsValid() + { + if (this.workbook != null && this.sheet != null) + return true; - string GetHeaderColumnName(int cellnum) - { - ICell headerCell = sheet.GetRow(0).GetCell(cellnum); - if (headerCell != null) - return headerCell.StringCellValue; - return string.Empty; - } + return false; + } - /// - /// Deserialize all the cell of the given sheet. - /// - /// NOTE: - /// The first row of a sheet is header column which is not the actual value - /// so it skips when it deserializes. - /// - public List Deserialize(int start = 1) - { - var t = typeof(T); - PropertyInfo[] p = t.GetProperties(); + /// + /// Retrieves file extension only from the given file path. + /// + static string GetSuffix(string path) + { + string ext = Path.GetExtension(path); + string[] arg = ext.Split(new char[] { '.' }); + return arg[1]; + } - var result = new List(); + string GetHeaderColumnName(int cellnum) + { + ICell headerCell = sheet.GetRow(0).GetCell(cellnum); + if (headerCell != null) + return headerCell.StringCellValue; + return string.Empty; + } - int current = 0; - foreach(IRow row in sheet) + /// + /// Deserialize all the cell of the given sheet. + /// + /// NOTE: + /// The first row of a sheet is header column which is not the actual value + /// so it skips when it deserializes. + /// + public List Deserialize(int start = 1) { - if (current < start) - { - current++; // skip header column. - continue; - } + var t = typeof(T); + PropertyInfo[] p = t.GetProperties(); + + var result = new List(); - var item = (T)Activator.CreateInstance(t); - for(var i=0; i tokenizedValues = new List(); - foreach (string s in parser) - tokenizedValues.Add(s); - - // convert string to corresponded type of the array element. - object[] convertedValues = null; - if (property.PropertyType.GetElementType() == typeof(string)) - convertedValues = tokenizedValues.ToArray(); - else - convertedValues = tokenizedValues.ToArray().Select(s => Convert.ChangeType(s, property.PropertyType.GetElementType())).ToArray(); - - // set converted string value to the array. - Array array = (Array)property.GetValue(item, null); - if (array != null) + var value = ConvertFrom(cell, property.PropertyType); + + if (property.PropertyType.IsArray) { - // initialize the array of the data class - array = Array.CreateInstance(property.PropertyType.GetElementType(), convertedValues.Length); - for (int j = 0; j < convertedValues.Length; j++) - array.SetValue(convertedValues[j], j); + // collect string values. + CsvParser parser = new CsvParser(value as string); + List tokenizedValues = new List(); + foreach (string s in parser) + tokenizedValues.Add(s); + + // convert string to corresponded type of the array element. + object[] convertedValues = null; + if (property.PropertyType.GetElementType() == typeof(string)) + convertedValues = tokenizedValues.ToArray(); + else + convertedValues = tokenizedValues.ToArray().Select(s => Convert.ChangeType(s, property.PropertyType.GetElementType())).ToArray(); - // should do deep copy - property.SetValue(item, array, null); + // set converted string value to the array. + Array array = (Array)property.GetValue(item, null); + if (array != null) + { + // initialize the array of the data class + array = Array.CreateInstance(property.PropertyType.GetElementType(), convertedValues.Length); + for (int j = 0; j < convertedValues.Length; j++) + array.SetValue(convertedValues[j], j); + + // should do deep copy + property.SetValue(item, array, null); + } } - } - else - property.SetValue(item, value, null); + else + property.SetValue(item, value, null); - //Debug.Log("cell value: " + value.ToString()); - } - catch(Exception e) - { - string pos = string.Format("Row[{0}], Cell[{1}]", (current + 1).ToString(), GetHeaderColumnName(i)); - Debug.LogError(string.Format("Excel File {0} Deserialize Exception: {1} at {2}", this.filepath, e.Message, pos)); + //Debug.Log("cell value: " + value.ToString()); + } + catch (Exception e) + { + string pos = string.Format("Row[{0}], Cell[{1}]", (current + 1).ToString(), GetHeaderColumnName(i)); + Debug.LogError(string.Format("Excel File {0} Deserialize Exception: {1} at {2}", this.filepath, e.Message, pos)); + } } } - } - result.Add(item); + result.Add(item); - current++; - } + current++; + } - return result; - } + return result; + } - /// - /// Retrieves all sheet names. - /// - public string[] GetSheetNames() - { - List sheetList = new List(); - if (this.workbook != null) + /// + /// Retrieves all sheet names. + /// + public string[] GetSheetNames() { - int numSheets = this.workbook.NumberOfSheets; - for (int i=0; i sheetList = new List(); + if (this.workbook != null) { - sheetList.Add(this.workbook.GetSheetName(i)); + int numSheets = this.workbook.NumberOfSheets; + for (int i = 0; i < numSheets; i++) + { + sheetList.Add(this.workbook.GetSheetName(i)); + } } - } - else - Debug.LogError("Workbook is null. Did you forget to import excel file first?"); - - return (sheetList.Count > 0) ? sheetList.ToArray() : null; - } + else + Debug.LogError("Workbook is null. Did you forget to import excel file first?"); - /// - /// Retrieves all first columns(aka. header) which are needed to determine type of each cell. - /// - public string[] GetTitle(int start = 0) - { - List result = new List(); + return (sheetList.Count > 0) ? sheetList.ToArray() : null; + } - IRow title = sheet.GetRow(start); - if (title != null) + /// + /// Retrieves all first columns(aka. header) which are needed to determine type of each cell. + /// + public string[] GetTitle(int start = 0) { - for (int i = 0; i < title.LastCellNum; i++) - result.Add(title.GetCell(i).StringCellValue); + List result = new List(); - return result.ToArray(); - } + IRow title = sheet.GetRow(start); + if (title != null) + { + for (int i = 0; i < title.LastCellNum; i++) + result.Add(title.GetCell(i).StringCellValue); - return null; - } + return result.ToArray(); + } - /// - /// Convert type of cell value to its predefined type in the sheet's ScriptMachine setting file. - /// - protected object ConvertFrom(ICell cell, Type t) - { - object value = null; + return null; + } - if (t == typeof(float) || t == typeof(double) || t == typeof(int) || t == typeof(long)) + /// + /// Convert type of cell value to its predefined type in the sheet's ScriptMachine setting file. + /// + protected object ConvertFrom(ICell cell, Type t) { - if (cell.CellType == CellType.Numeric) - value = cell.NumericCellValue; - else if (cell.CellType == CellType.String) + object value = null; + + if (t == typeof(float) || t == typeof(double) || t == typeof(int) || t == typeof(long)) { - //Get correct numeric value even the cell is string type but defined with a numeric type in a data class. - if (t == typeof(float)) - value = Convert.ToSingle(cell.StringCellValue); - if (t == typeof(double)) - value = Convert.ToDouble(cell.StringCellValue); - if (t == typeof(int)) - value = Convert.ToInt32(cell.StringCellValue); - if (t == typeof(long)) - value = Convert.ToInt64(cell.StringCellValue); + if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric) + value = cell.NumericCellValue; + else if (cell.CellType == NPOI.SS.UserModel.CellType.String) + { + //Get correct numeric value even the cell is string type but defined with a numeric type in a data class. + if (t == typeof(float)) + value = Convert.ToSingle(cell.StringCellValue); + if (t == typeof(double)) + value = Convert.ToDouble(cell.StringCellValue); + if (t == typeof(int)) + value = Convert.ToInt32(cell.StringCellValue); + if (t == typeof(long)) + value = Convert.ToInt64(cell.StringCellValue); + } } - } - else if (t == typeof(string) || t.IsArray) - { - // HACK: handles the case that a cell contains numeric value - // but a member field in a data class is defined as string type. - if (cell.CellType == CellType.Numeric) - value = cell.NumericCellValue; - else - value = cell.StringCellValue; - } - else if (t == typeof(bool)) - value = cell.BooleanCellValue; + else if (t == typeof(string) || t.IsArray) + { + // HACK: handles the case that a cell contains numeric value + // but a member field in a data class is defined as string type. + if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric) + value = cell.NumericCellValue; + else + value = cell.StringCellValue; + } + else if (t == typeof(bool)) + value = cell.BooleanCellValue; - if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) - { - var nc = new NullableConverter(t); - return nc.ConvertFrom(value); - } + if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) + { + var nc = new NullableConverter(t); + return nc.ConvertFrom(value); + } - if (t.IsEnum) - { - // for enum type, first get value by string then convert it to enum. - value = cell.StringCellValue; - return Enum.Parse(t, value.ToString(), true); - } - else if (t.IsArray) - { - // for array type, return comma separated string - // then parse and covert its corresponding type. - return value as string; - } - else - { - // for all other types, convert its corresponding type. - return Convert.ChangeType(value, t); + if (t.IsEnum) + { + // for enum type, first get value by string then convert it to enum. + value = cell.StringCellValue; + return Enum.Parse(t, value.ToString(), true); + } + else if (t.IsArray) + { + // for array type, return comma separated string + // then parse and covert its corresponding type. + return value as string; + } + else + { + // for all other types, convert its corresponding type. + return Convert.ChangeType(value, t); + } } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettings.cs b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettings.cs index dc598d1..919bc6d 100644 --- a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettings.cs +++ b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettings.cs @@ -10,153 +10,155 @@ using System.Collections; using System.IO; -/// -/// A class to manage excel setting. -/// -public class ExcelSettings : ScriptableObject +namespace UnityQuicksheet { - public string AssetPath = "Assets/QuickSheet/ExcelPlugin/Editor/"; - - [SerializeField] - public static string AssetFileName = "ExcelSettings.asset"; - /// - /// A property which specifies or retrieves generated runtime class path. + /// A class to manage excel setting. /// - public string RuntimePath + public class ExcelSettings : ScriptableObject { - get { return runTimePath; } - set + public string AssetPath = "Assets/QuickSheet/ExcelPlugin/Editor/"; + + [SerializeField] + public static string AssetFileName = "ExcelSettings.asset"; + + /// + /// A property which specifies or retrieves generated runtime class path. + /// + public string RuntimePath { - if (runTimePath != value) - runTimePath = value; + get { return runTimePath; } + set + { + if (runTimePath != value) + runTimePath = value; + } } - } - [SerializeField] - private string runTimePath = string.Empty; + [SerializeField] + private string runTimePath = string.Empty; - /// - /// A property which specifies or retrieves generated editor class path. - /// - public string EditorPath - { - get { return editorPath; } - set + /// + /// A property which specifies or retrieves generated editor class path. + /// + public string EditorPath { - if (editorPath != value) - editorPath = value; + get { return editorPath; } + set + { + if (editorPath != value) + editorPath = value; + } } - } - [SerializeField] - private string editorPath = string.Empty; + [SerializeField] + private string editorPath = string.Empty; - /// - /// A singleton instance. - /// - private static ExcelSettings s_Instance; + /// + /// A singleton instance. + /// + private static ExcelSettings s_Instance; - /// - /// Create new account setting asset file if there is already one then select it. - /// - [MenuItem("Assets/Create/QuickSheet/Setting/Excel Setting")] - public static void CreateExcelSetting() - { - ExcelSettings.Create(); - } + /// + /// Create new account setting asset file if there is already one then select it. + /// + [MenuItem("Assets/Create/QuickSheet/Setting/Excel Setting")] + public static void CreateExcelSetting() + { + ExcelSettings.Create(); + } - /// - /// Select currently exist account setting asset file. - /// - [MenuItem("Edit/Project Settings/QuickSheet/Select Excel Setting")] - public static void Edit() - { - Selection.activeObject = Instance; - if (Selection.activeObject == null) + /// + /// Select currently exist account setting asset file. + /// + [MenuItem("Edit/Project Settings/QuickSheet/Select Excel Setting")] + public static void Edit() { - Debug.LogError("No ExcelSetting.asset file is found. Create setting file first. See the menu at 'Assets/Create/QuickSheet/Setting/Excel Setting'."); + Selection.activeObject = Instance; + if (Selection.activeObject == null) + { + Debug.LogError("No ExcelSetting.asset file is found. Create setting file first. See the menu at 'Assets/Create/QuickSheet/Setting/Excel Setting'."); + } } - } - /// - /// - /// - void OnEnable() - { - } - - /// - /// Checks ExcelSetting.asset file exist at the specified path(AssetPath+AssetFileName). - /// - public bool CheckPath() - { - string file = AssetDatabase.GetAssetPath(Selection.activeObject); - string assetFile = AssetPath + ExcelSettings.AssetFileName; + /// + /// + /// + void OnEnable() + { + } - return (file == assetFile) ? true : false; - } + /// + /// Checks ExcelSetting.asset file exist at the specified path(AssetPath+AssetFileName). + /// + public bool CheckPath() + { + string file = AssetDatabase.GetAssetPath(Selection.activeObject); + string assetFile = AssetPath + ExcelSettings.AssetFileName; - /// - /// A property for singleton. - /// - public static ExcelSettings Instance - { - get + return (file == assetFile) ? true : false; + } + + /// + /// A property for singleton. + /// + public static ExcelSettings Instance { - if (s_Instance == null) + get { - // A tricky way to assess non-static member in the static method. - ExcelSettings temp = new ExcelSettings(); - string path = temp.AssetPath + ExcelSettings.AssetFileName; - - s_Instance = AssetDatabase.LoadAssetAtPath (path, typeof (ExcelSettings)) as ExcelSettings; if (s_Instance == null) { - Debug.LogWarning("No exel setting file is at " + path + " You need to create a new one or modify its path."); + // A tricky way to assess non-static member in the static method. + ExcelSettings temp = new ExcelSettings(); + string path = temp.AssetPath + ExcelSettings.AssetFileName; + + s_Instance = AssetDatabase.LoadAssetAtPath(path, typeof(ExcelSettings)) as ExcelSettings; + if (s_Instance == null) + { + Debug.LogWarning("No exel setting file is at " + path + " You need to create a new one or modify its path."); + } } + return s_Instance; } - return s_Instance; + } - } - - /// - /// Create account setting asset file if it does not exist. - /// - public static ExcelSettings Create() - { - string filePath = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); - s_Instance = (ExcelSettings)AssetDatabase.LoadAssetAtPath(filePath, typeof(ExcelSettings)); - - if (s_Instance == null) + /// + /// Create account setting asset file if it does not exist. + /// + public static ExcelSettings Create() { - s_Instance = CreateInstance (); + string filePath = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); + s_Instance = (ExcelSettings)AssetDatabase.LoadAssetAtPath(filePath, typeof(ExcelSettings)); - string path = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); - AssetDatabase.CreateAsset(s_Instance, path); + if (s_Instance == null) + { + s_Instance = CreateInstance(); - s_Instance.AssetPath = Path.GetDirectoryName(path); - s_Instance.AssetPath += "/"; + string path = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); + AssetDatabase.CreateAsset(s_Instance, path); - // saves file path of the created asset. - EditorUtility.SetDirty(s_Instance); - AssetDatabase.SaveAssets(); + s_Instance.AssetPath = Path.GetDirectoryName(path); + s_Instance.AssetPath += "/"; - EditorUtility.DisplayDialog ( - "Validate Settings", - "Default excel settings file has been created for accessing excel spreadsheet. Set valid runtime editor paths before proceeding.", - "OK" - ); - } - else - { - Debug.LogWarning("Already exist at " + filePath); - } + // saves file path of the created asset. + EditorUtility.SetDirty(s_Instance); + AssetDatabase.SaveAssets(); - Selection.activeObject = s_Instance; - - return s_Instance; + EditorUtility.DisplayDialog( + "Validate Settings", + "Default excel settings file has been created for accessing excel spreadsheet. Set valid runtime editor paths before proceeding.", + "OK" + ); + } + else + { + Debug.LogWarning("Already exist at " + filePath); + } + + Selection.activeObject = s_Instance; + + return s_Instance; + } } } - diff --git a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettingsEditor.cs b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettingsEditor.cs index 80c1953..a317868 100644 --- a/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettingsEditor.cs +++ b/Assets/QuickSheet/ExcelPlugin/Editor/ExcelSettingsEditor.cs @@ -9,67 +9,70 @@ using UnityEditor; using System.Collections; -/// -/// Editor script class for ExcelSettings scriptable object to hide password of google account. -/// -[CustomEditor(typeof(ExcelSettings))] -public class ExcelSettingsEditor : Editor +namespace UnityQuicksheet { - ExcelSettings setting; - - public void OnEnable() + /// + /// Editor script class for ExcelSettings scriptable object to hide password of google account. + /// + [CustomEditor(typeof(ExcelSettings))] + public class ExcelSettingsEditor : Editor { - setting = target as ExcelSettings; - } - - public override void OnInspectorGUI() - { - GUI.changed = false; - GUIStyle headerStyle = GUIHelper.MakeHeader(); - GUILayout.Label("Excel Settings", headerStyle); - - EditorGUILayout.Separator(); + ExcelSettings setting; - // paths for runtime and editor folder which will contain generated script files. - GUILayout.BeginHorizontal(); - GUILayout.Label("Setting FilePath: ", GUILayout.Width(110)); - setting.AssetPath = GUILayout.TextField(setting.AssetPath, 120); - GUILayout.EndHorizontal(); + public void OnEnable() + { + setting = target as ExcelSettings; + } - GUILayout.BeginHorizontal(); - GUILayout.Label("Setting FileName: ", GUILayout.Width(110)); - ExcelSettings.AssetFileName = GUILayout.TextField(ExcelSettings.AssetFileName, 120); - GUILayout.EndHorizontal(); + public override void OnInspectorGUI() + { + GUI.changed = false; + GUIStyle headerStyle = GUIHelper.MakeHeader(); + GUILayout.Label("Excel Settings", headerStyle); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - if (setting.CheckPath()) - { + // paths for runtime and editor folder which will contain generated script files. GUILayout.BeginHorizontal(); - GUILayout.Label("Runtime Path: ", GUILayout.Width(100)); - setting.RuntimePath = GUILayout.TextField(setting.RuntimePath); + GUILayout.Label("Setting FilePath: ", GUILayout.Width(110)); + setting.AssetPath = GUILayout.TextField(setting.AssetPath, 120); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); - GUILayout.Label("Editor Path: ", GUILayout.Width(100)); - setting.EditorPath = GUILayout.TextField(setting.EditorPath); + GUILayout.Label("Setting FileName: ", GUILayout.Width(110)); + ExcelSettings.AssetFileName = GUILayout.TextField(ExcelSettings.AssetFileName, 120); GUILayout.EndHorizontal(); - } - else - { - GUILayout.BeginHorizontal(); - GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); - GUILayout.BeginVertical(); - GUILayout.Label("", GUILayout.Height(12)); - GUILayout.Label("Correct the path of the ExcelSetting.asset file.", GUILayout.Height(20)); - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - } - if (GUI.changed) - { - EditorUtility.SetDirty(setting); - AssetDatabase.SaveAssets(); + EditorGUILayout.Separator(); + + if (setting.CheckPath()) + { + GUILayout.BeginHorizontal(); + GUILayout.Label("Runtime Path: ", GUILayout.Width(100)); + setting.RuntimePath = GUILayout.TextField(setting.RuntimePath); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + GUILayout.Label("Editor Path: ", GUILayout.Width(100)); + setting.EditorPath = GUILayout.TextField(setting.EditorPath); + GUILayout.EndHorizontal(); + } + else + { + GUILayout.BeginHorizontal(); + GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); + GUILayout.BeginVertical(); + GUILayout.Label("", GUILayout.Height(12)); + GUILayout.Label("Correct the path of the ExcelSetting.asset file.", GUILayout.Height(20)); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } + + if (GUI.changed) + { + EditorUtility.SetDirty(setting); + AssetDatabase.SaveAssets(); + } } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/ExcelPlugin/Templates/AssetFileClass.txt b/Assets/QuickSheet/ExcelPlugin/Templates/AssetFileClass.txt index 564dd2b..e3f521d 100644 --- a/Assets/QuickSheet/ExcelPlugin/Templates/AssetFileClass.txt +++ b/Assets/QuickSheet/ExcelPlugin/Templates/AssetFileClass.txt @@ -1,6 +1,7 @@ using UnityEngine; using UnityEditor; using System.IO; +using UnityQuicksheet; /// /// !!! Machine generated code !!! diff --git a/Assets/QuickSheet/ExcelPlugin/Templates/DataClass.txt b/Assets/QuickSheet/ExcelPlugin/Templates/DataClass.txt index fc37ec2..1b6a14f 100644 --- a/Assets/QuickSheet/ExcelPlugin/Templates/DataClass.txt +++ b/Assets/QuickSheet/ExcelPlugin/Templates/DataClass.txt @@ -1,5 +1,6 @@ using UnityEngine; using System.Collections; +using UnityQuicksheet; /// /// !!! Machine generated code !!! diff --git a/Assets/QuickSheet/ExcelPlugin/Templates/PostProcessor.txt b/Assets/QuickSheet/ExcelPlugin/Templates/PostProcessor.txt index a978a66..753038c 100644 --- a/Assets/QuickSheet/ExcelPlugin/Templates/PostProcessor.txt +++ b/Assets/QuickSheet/ExcelPlugin/Templates/PostProcessor.txt @@ -2,6 +2,7 @@ using UnityEditor; using System.Collections; using System.IO; +using UnityQuicksheet; /// /// !!! Machine generated code !!! diff --git a/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectClass.txt b/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectClass.txt index 8c7e9c7..7d1df07 100644 --- a/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectClass.txt +++ b/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectClass.txt @@ -2,6 +2,7 @@ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; +using UnityQuicksheet; /// /// !!! Machine generated code !!! diff --git a/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectEditorClass.txt b/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectEditorClass.txt index fb779f7..2b20cfe 100644 --- a/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectEditorClass.txt +++ b/Assets/QuickSheet/ExcelPlugin/Templates/ScriptableObjectEditorClass.txt @@ -4,6 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; +using UnityQuicksheet; /// /// !!! Machine generated code !!! diff --git a/Assets/QuickSheet/GDataPlugin/Editor/BaseGoogleEditor.cs b/Assets/QuickSheet/GDataPlugin/Editor/BaseGoogleEditor.cs index f7454f5..6966d78 100644 --- a/Assets/QuickSheet/GDataPlugin/Editor/BaseGoogleEditor.cs +++ b/Assets/QuickSheet/GDataPlugin/Editor/BaseGoogleEditor.cs @@ -23,145 +23,148 @@ using Google.GData.Client; using Google.GData.Spreadsheets; -/// -/// A BaseEditor class. -/// -public class BaseGoogleEditor : Editor -{ - // property draw - protected PropertyField[] databaseFields; - protected PropertyField[] dataFields; - - protected List pInfoList = new List(); - - GUIStyle brown; - bool isInitialized = false; - +namespace UnityQuicksheet +{ /// - /// Actively ignore security concerns to resolve TlsException error. + /// A BaseEditor class. /// - /// See: http://www.mono-project.com/UsingTrustedRootsRespectfully - /// - public static bool Validator (object sender, X509Certificate certificate, X509Chain chain, - SslPolicyErrors sslPolicyErrors) - { - return true; - } - - public virtual void OnEnable() + public class BaseGoogleEditor : Editor { - // resolves TlsException error - ServicePointManager.ServerCertificateValidationCallback = Validator; + // property draw + protected PropertyField[] databaseFields; + protected PropertyField[] dataFields; + + protected List pInfoList = new List(); + + GUIStyle brown; + bool isInitialized = false; + + /// + /// Actively ignore security concerns to resolve TlsException error. + /// + /// See: http://www.mono-project.com/UsingTrustedRootsRespectfully + /// + public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + return true; + } - GoogleDataSettings settings = GoogleDataSettings.Instance; - if (settings != null) + public virtual void OnEnable() { - if (string.IsNullOrEmpty(settings.OAuth2Data.client_id) || - string.IsNullOrEmpty(settings.OAuth2Data.client_secret)) - Debug.LogWarning("Client_ID and Client_Sceret is empty. Reload .json file."); + // resolves TlsException error + ServicePointManager.ServerCertificateValidationCallback = Validator; + + GoogleDataSettings settings = GoogleDataSettings.Instance; + if (settings != null) + { + if (string.IsNullOrEmpty(settings.OAuth2Data.client_id) || + string.IsNullOrEmpty(settings.OAuth2Data.client_secret)) + Debug.LogWarning("Client_ID and Client_Sceret is empty. Reload .json file."); - if (string.IsNullOrEmpty(settings._AccessCode)) - Debug.LogWarning("AccessCode is empty. Redo authenticate again."); + if (string.IsNullOrEmpty(settings._AccessCode)) + Debug.LogWarning("AccessCode is empty. Redo authenticate again."); + } + else + { + Debug.LogError("Failed to get google data settings. See the google data setting if it has correct path."); + return; + } } - else + + private void InitGUISkin() { - Debug.LogError("Failed to get google data settings. See the google data setting if it has correct path."); - return; + brown = new GUIStyle("box"); + brown.normal.background = Resources.Load("brown", typeof(Texture2D)) as Texture2D; + brown.border = new RectOffset(4, 4, 4, 4); + brown.margin = new RectOffset(3, 3, 3, 3); + brown.padding = new RectOffset(4, 4, 4, 4); } - } - private void InitGUISkin() - { - brown = new GUIStyle("box"); - brown.normal.background = Resources.Load("brown", typeof(Texture2D)) as Texture2D; - brown.border = new RectOffset(4, 4, 4, 4); - brown.margin = new RectOffset(3, 3, 3, 3); - brown.padding = new RectOffset(4, 4, 4, 4); - } + public override void OnInspectorGUI() + { + if (target == null) + return; - public override void OnInspectorGUI() - { - if (target == null) - return; + if (!isInitialized) + { + isInitialized = true; + InitGUISkin(); + } - if (!isInitialized) - { - isInitialized = true; - InitGUISkin(); + if (GUILayout.Button("Download")) + { + if (!Load()) + Debug.LogError("Failed to Load data from Google."); + } + + EditorGUILayout.Separator(); + + //this.DrawDefaultInspector(); + ExposeProperties.Expose(databaseFields); + + foreach (PropertyField[] p in pInfoList) + { + GUILayout.BeginVertical(brown); + ExposeProperties.Expose(p); + GUILayout.EndVertical(); + } } - if (GUILayout.Button("Download")) + /// + /// Should be reimplemented in derived class. + /// + public virtual bool Load() { - if (!Load()) - Debug.LogError("Failed to Load data from Google."); + return true; } - EditorGUILayout.Separator(); - - //this.DrawDefaultInspector(); - ExposeProperties.Expose(databaseFields); - - foreach(PropertyField[] p in pInfoList) + protected List SetArrayValue(string from) { - GUILayout.BeginVertical(brown); - ExposeProperties.Expose( p ); - GUILayout.EndVertical(); - } - } - - /// - /// Should be reimplemented in derived class. - /// - public virtual bool Load() - { - return true; - } - - protected List SetArrayValue(string from) - { - List tmp = new List(); + List tmp = new List(); - CsvParser parser = new CsvParser(from); + CsvParser parser = new CsvParser(from); - foreach(string s in parser) - { - Debug.Log("parsed value: " + s); - tmp.Add(int.Parse(s)); - } + foreach (string s in parser) + { + Debug.Log("parsed value: " + s); + tmp.Add(int.Parse(s)); + } - return tmp; - } + return tmp; + } - /* - static string[] SplitCamelCase(string stringToSplit) - { - if (!string.IsNullOrEmpty(stringToSplit)) + /* + static string[] SplitCamelCase(string stringToSplit) { - List words = new List(); + if (!string.IsNullOrEmpty(stringToSplit)) + { + List words = new List(); - string temp = string.Empty; + string temp = string.Empty; - foreach (char ch in stringToSplit) - { - if (ch >= 'a' && ch <= 'z') - temp = temp + ch; - else + foreach (char ch in stringToSplit) { - words.Add(temp); - temp = string.Empty + ch; + if (ch >= 'a' && ch <= 'z') + temp = temp + ch; + else + { + words.Add(temp); + temp = string.Empty + ch; + } } + words.Add(temp); + return words.ToArray(); } - words.Add(temp); - return words.ToArray(); + else + return null; + } + */ + + public static string SplitCamelCase(string inputCamelCaseString) + { + string sTemp = Regex.Replace(inputCamelCaseString, "([A-Z][a-z])", " $1", RegexOptions.Compiled).Trim(); + return Regex.Replace(sTemp, "([A-Z][A-Z])", " $1", RegexOptions.Compiled).Trim(); } - else - return null; } - */ - - public static string SplitCamelCase(string inputCamelCaseString) - { - string sTemp = Regex.Replace(inputCamelCaseString, "([A-Z][a-z])", " $1", RegexOptions.Compiled).Trim(); - return Regex.Replace(sTemp, "([A-Z][A-Z])", " $1", RegexOptions.Compiled).Trim(); - } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/GDataDBRequestFactory.cs b/Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/GDataDBRequestFactory.cs index 5669ce2..fb41022 100644 --- a/Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/GDataDBRequestFactory.cs +++ b/Assets/QuickSheet/GDataPlugin/Editor/GDataDB/GDataDB/Impl/GDataDBRequestFactory.cs @@ -14,6 +14,7 @@ using Google.GData.Spreadsheets; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using UnityQuicksheet; namespace GDataDB.Impl { diff --git a/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.asset b/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.asset index c80a1d6..00b83b1 100644 Binary files a/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.asset and b/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.asset differ diff --git a/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.cs b/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.cs index b17b3e4..75f01df 100644 --- a/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.cs +++ b/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettings.cs @@ -11,188 +11,191 @@ using System.IO; using System.Collections.Generic; -/// -/// A class to manage google account setting. -/// -public class GoogleDataSettings : ScriptableObject +namespace UnityQuicksheet { - public string AssetPath = "Assets/QuickSheet/GDataPlugin/Editor/"; + /// + /// A class to manage google account setting. + /// + public class GoogleDataSettings : ScriptableObject + { + public string AssetPath = "Assets/QuickSheet/GDataPlugin/Editor/"; - [SerializeField] - public static string AssetFileName = "GoogleDataSettings.asset"; + [SerializeField] + public static string AssetFileName = "GoogleDataSettings.asset"; - public string JsonFilePath - { - get { return jsonFilePath; } - set + public string JsonFilePath { - if (string.IsNullOrEmpty(value) == false) - jsonFilePath = value; + get { return jsonFilePath; } + set + { + if (string.IsNullOrEmpty(value) == false) + jsonFilePath = value; + } } - } - private string jsonFilePath = string.Empty; + private string jsonFilePath = string.Empty; - /// - /// A property which specifies or retrieves generated runtime class path. - /// - public string RuntimePath - { - get { return runTimePath; } - set + /// + /// A property which specifies or retrieves generated runtime class path. + /// + public string RuntimePath { - if (runTimePath != value) - runTimePath = value; + get { return runTimePath; } + set + { + if (runTimePath != value) + runTimePath = value; + } } - } - [SerializeField] - private string runTimePath = string.Empty; + [SerializeField] + private string runTimePath = string.Empty; - /// - /// A property which specifies or retrieves generated editor class path. - /// - public string EditorPath - { - get { return editorPath; } - set + /// + /// A property which specifies or retrieves generated editor class path. + /// + public string EditorPath { - if (editorPath != value) - editorPath = value; + get { return editorPath; } + set + { + if (editorPath != value) + editorPath = value; + } } - } - - [SerializeField] - private string editorPath = string.Empty; - [System.Serializable] - public struct OAuth2JsonData - { - public string client_id; - public string auth_uri; - public string token_uri; - public string auth_provider_x509_cert_url; - public string client_secret; - public List redirect_uris; - }; - - public OAuth2JsonData OAuth2Data; - - // enter Access Code after getting it from auth url - [SerializeField] - public string _AccessCode = "Paste AcecessCode here!"; - - // enter Auth 2.0 Refresh Token and AccessToken after succesfully authorizing with Access Code - [SerializeField] - public string _RefreshToken = ""; - [SerializeField] - public string _AccessToken = ""; + [SerializeField] + private string editorPath = string.Empty; - /// - /// A singleton instance. - /// - private static GoogleDataSettings s_Instance; + [System.Serializable] + public struct OAuth2JsonData + { + public string client_id; + public string auth_uri; + public string token_uri; + public string auth_provider_x509_cert_url; + public string client_secret; + public List redirect_uris; + }; + + public OAuth2JsonData OAuth2Data; + + // enter Access Code after getting it from auth url + [SerializeField] + public string _AccessCode = "Paste AcecessCode here!"; + + // enter Auth 2.0 Refresh Token and AccessToken after succesfully authorizing with Access Code + [SerializeField] + public string _RefreshToken = ""; + [SerializeField] + public string _AccessToken = ""; + + /// + /// A singleton instance. + /// + private static GoogleDataSettings s_Instance; + + /// + /// Create new account setting asset file if there is already one then select it. + /// + [MenuItem("Assets/Create/QuickSheet/Setting/GoogleData Setting")] + public static void CreateGoogleDataSetting() + { + GoogleDataSettings.Create(); + } - /// - /// Create new account setting asset file if there is already one then select it. - /// - [MenuItem("Assets/Create/QuickSheet/Setting/GoogleData Setting")] - public static void CreateGoogleDataSetting() - { - GoogleDataSettings.Create(); - } + /// + /// Select currently exist account setting asset file. + /// + [MenuItem("Edit/Project Settings/QuickSheet/Select Google Data Setting")] + public static void Edit() + { + Selection.activeObject = Instance; + if (Selection.activeObject == null) + { + Debug.LogError("No GoogleDataSettings.asset file is found. Create setting file first."); + } + } - /// - /// Select currently exist account setting asset file. - /// - [MenuItem("Edit/Project Settings/QuickSheet/Select Google Data Setting")] - public static void Edit() - { - Selection.activeObject = Instance; - if (Selection.activeObject == null) + /// + /// + /// + void OnEnable() { - Debug.LogError("No GoogleDataSettings.asset file is found. Create setting file first."); + //if (OAuth2Data.client_id == null) + // OAuth2Data = new OAuth2JsonData(); } - } - /// - /// - /// - void OnEnable() - { - //if (OAuth2Data.client_id == null) - // OAuth2Data = new OAuth2JsonData(); - } - - /// - /// Checks GoogleDataSetting.asset file exist at the specified path(AssetPath+AssetFileName). - /// - public bool CheckPath() - { - string file = AssetDatabase.GetAssetPath(Selection.activeObject); - string assetFile = AssetPath + GoogleDataSettings.AssetFileName; + /// + /// Checks GoogleDataSetting.asset file exist at the specified path(AssetPath+AssetFileName). + /// + public bool CheckPath() + { + string file = AssetDatabase.GetAssetPath(Selection.activeObject); + string assetFile = AssetPath + GoogleDataSettings.AssetFileName; - return (file == assetFile) ? true : false; - } + return (file == assetFile) ? true : false; + } - /// - /// A property for singleton. - /// - public static GoogleDataSettings Instance - { - get + /// + /// A property for singleton. + /// + public static GoogleDataSettings Instance { - if (s_Instance == null) + get { - // A tricky way to assess non-static member in the static method. - GoogleDataSettings temp = new GoogleDataSettings(); - string path = temp.AssetPath + GoogleDataSettings.AssetFileName; - - s_Instance = (GoogleDataSettings)AssetDatabase.LoadAssetAtPath (path, typeof (GoogleDataSettings)); if (s_Instance == null) { - Debug.LogWarning("No account setting file is at " + path + " You need to create a new one or modify its path."); + // A tricky way to assess non-static member in the static method. + GoogleDataSettings temp = new GoogleDataSettings(); + string path = temp.AssetPath + GoogleDataSettings.AssetFileName; + + s_Instance = (GoogleDataSettings)AssetDatabase.LoadAssetAtPath(path, typeof(GoogleDataSettings)); + if (s_Instance == null) + { + Debug.LogWarning("No account setting file is at " + path + " You need to create a new one or modify its path."); + } } + return s_Instance; } - return s_Instance; + } - } - - /// - /// Create account setting asset file if it does not exist. - /// - public static GoogleDataSettings Create() - { - string filePath = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); - s_Instance = (GoogleDataSettings)AssetDatabase.LoadAssetAtPath(filePath, typeof(GoogleDataSettings)); - - if (s_Instance == null) + /// + /// Create account setting asset file if it does not exist. + /// + public static GoogleDataSettings Create() { - s_Instance = CreateInstance (); + string filePath = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); + s_Instance = (GoogleDataSettings)AssetDatabase.LoadAssetAtPath(filePath, typeof(GoogleDataSettings)); - string path = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); - AssetDatabase.CreateAsset(s_Instance, path); + if (s_Instance == null) + { + s_Instance = CreateInstance(); - s_Instance.AssetPath = Path.GetDirectoryName(path); - s_Instance.AssetPath += "/"; + string path = CustomAssetUtility.GetUniqueAssetPathNameOrFallback(AssetFileName); + AssetDatabase.CreateAsset(s_Instance, path); - // saves file path of the created asset. - EditorUtility.SetDirty(s_Instance); - AssetDatabase.SaveAssets(); + s_Instance.AssetPath = Path.GetDirectoryName(path); + s_Instance.AssetPath += "/"; - EditorUtility.DisplayDialog ( - "Validate Settings", - "Default google data settings file has been created for accessing Google project page. You should validate these before proceeding.", - "OK" - ); - } - else - { - Debug.LogWarning("Already exist at " + filePath); - } + // saves file path of the created asset. + EditorUtility.SetDirty(s_Instance); + AssetDatabase.SaveAssets(); + + EditorUtility.DisplayDialog( + "Validate Settings", + "Default google data settings file has been created for accessing Google project page. You should validate these before proceeding.", + "OK" + ); + } + else + { + Debug.LogWarning("Already exist at " + filePath); + } + + Selection.activeObject = s_Instance; - Selection.activeObject = s_Instance; - - return s_Instance; + return s_Instance; + } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettingsEditor.cs b/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettingsEditor.cs index d30bacd..b7bd696 100644 --- a/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettingsEditor.cs +++ b/Assets/QuickSheet/GDataPlugin/Editor/GoogleDataSettingsEditor.cs @@ -18,158 +18,161 @@ using System.Net.Security; using System.Security.Cryptography.X509Certificates; -public class UnsafeSecurityPolicy +namespace UnityQuicksheet { - public static bool Validator( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) + public class UnsafeSecurityPolicy { - Debug.Log("Validation successful!"); - return true; - } + public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) + { + Debug.Log("Validation successful!"); + return true; + } - public static void Instate() - { - ServicePointManager.ServerCertificateValidationCallback = Validator; + public static void Instate() + { + ServicePointManager.ServerCertificateValidationCallback = Validator; + } } -} - -/// -/// Editor script class for GoogleDataSettings scriptable object to hide password of google account. -/// -[CustomEditor(typeof(GoogleDataSettings))] -public class GoogleDataSettingsEditor : Editor -{ - GoogleDataSettings setting; - public void OnEnable() + /// + /// Editor script class for GoogleDataSettings scriptable object to hide password of google account. + /// + [CustomEditor(typeof(GoogleDataSettings))] + public class GoogleDataSettingsEditor : Editor { - setting = target as GoogleDataSettings; + GoogleDataSettings setting; - UnsafeSecurityPolicy.Instate(); - } + public void OnEnable() + { + setting = target as GoogleDataSettings; - public override void OnInspectorGUI() - { - GUI.changed = false; + UnsafeSecurityPolicy.Instate(); + } + + public override void OnInspectorGUI() + { + GUI.changed = false; - GUIStyle headerStyle = GUIHelper.MakeHeader(); - GUILayout.Label("GoogleSpreadsheet Settings", headerStyle); + GUIStyle headerStyle = GUIHelper.MakeHeader(); + GUILayout.Label("GoogleSpreadsheet Settings", headerStyle); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - // path and asset file name which contains a google account and password. - GUILayout.BeginHorizontal(); - GUILayout.Label("Setting FilePath: ", GUILayout.Width(110)); - setting.AssetPath = GUILayout.TextField(setting.AssetPath, 120); - GUILayout.EndHorizontal(); + // path and asset file name which contains a google account and password. + GUILayout.BeginHorizontal(); + GUILayout.Label("Setting FilePath: ", GUILayout.Width(110)); + setting.AssetPath = GUILayout.TextField(setting.AssetPath, 120); + GUILayout.EndHorizontal(); - GUILayout.BeginHorizontal(); - GUILayout.Label("Setting FileName: ", GUILayout.Width(110)); - GoogleDataSettings.AssetFileName = GUILayout.TextField(GoogleDataSettings.AssetFileName, 120); - GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + GUILayout.Label("Setting FileName: ", GUILayout.Width(110)); + GoogleDataSettings.AssetFileName = GUILayout.TextField(GoogleDataSettings.AssetFileName, 120); + GUILayout.EndHorizontal(); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - if (setting.CheckPath()) - { - const int LabelWidth = 90; + if (setting.CheckPath()) + { + const int LabelWidth = 90; - GUILayout.BeginHorizontal(); // Begin json file setting - GUILayout.Label("JSON File:", GUILayout.Width(LabelWidth)); + GUILayout.BeginHorizontal(); // Begin json file setting + GUILayout.Label("JSON File:", GUILayout.Width(LabelWidth)); - string path = ""; - if (string.IsNullOrEmpty(setting.JsonFilePath)) - path = Application.dataPath; - else - path = setting.JsonFilePath; + string path = ""; + if (string.IsNullOrEmpty(setting.JsonFilePath)) + path = Application.dataPath; + else + path = setting.JsonFilePath; - setting.JsonFilePath = GUILayout.TextField(path, GUILayout.Width(250)); - if (GUILayout.Button("...", GUILayout.Width(20))) - { - string folder = Path.GetDirectoryName(path); - path = EditorUtility.OpenFilePanel("Open JSON file", folder, "json"); - if (path.Length != 0) + setting.JsonFilePath = GUILayout.TextField(path, GUILayout.Width(250)); + if (GUILayout.Button("...", GUILayout.Width(20))) { - StringBuilder builder = new StringBuilder(); - using (StreamReader sr = new StreamReader(path)) + string folder = Path.GetDirectoryName(path); + path = EditorUtility.OpenFilePanel("Open JSON file", folder, "json"); + if (path.Length != 0) { - string s = ""; - while (s != null) + StringBuilder builder = new StringBuilder(); + using (StreamReader sr = new StreamReader(path)) { - s = sr.ReadLine(); - builder.Append(s); + string s = ""; + while (s != null) + { + s = sr.ReadLine(); + builder.Append(s); + } } - } - string jsonData = builder.ToString(); + string jsonData = builder.ToString(); - var oauthData = JObject.Parse(jsonData).SelectToken("installed").ToString(); - GoogleDataSettings.Instance.OAuth2Data = JsonConvert.DeserializeObject(oauthData); + var oauthData = JObject.Parse(jsonData).SelectToken("installed").ToString(); + GoogleDataSettings.Instance.OAuth2Data = JsonConvert.DeserializeObject(oauthData); - setting.JsonFilePath = path; + setting.JsonFilePath = path; - // force to save the setting. - EditorUtility.SetDirty(setting); - AssetDatabase.SaveAssets(); + // force to save the setting. + EditorUtility.SetDirty(setting); + AssetDatabase.SaveAssets(); + } } - } - GUILayout.EndHorizontal(); // End json file setting. + GUILayout.EndHorizontal(); // End json file setting. - if (setting.OAuth2Data.client_id == null) - setting.OAuth2Data.client_id = string.Empty; - if (setting.OAuth2Data.client_secret == null) - setting.OAuth2Data.client_secret = string.Empty; + if (setting.OAuth2Data.client_id == null) + setting.OAuth2Data.client_id = string.Empty; + if (setting.OAuth2Data.client_secret == null) + setting.OAuth2Data.client_secret = string.Empty; - // client_id for OAuth2 - GUILayout.BeginHorizontal(); - GUILayout.Label("Client ID: ", GUILayout.Width(LabelWidth)); - setting.OAuth2Data.client_id = GUILayout.TextField(setting.OAuth2Data.client_id); - GUILayout.EndHorizontal(); + // client_id for OAuth2 + GUILayout.BeginHorizontal(); + GUILayout.Label("Client ID: ", GUILayout.Width(LabelWidth)); + setting.OAuth2Data.client_id = GUILayout.TextField(setting.OAuth2Data.client_id); + GUILayout.EndHorizontal(); - // client_secret for OAuth2 - GUILayout.BeginHorizontal(); - GUILayout.Label("Client Secret: ", GUILayout.Width(LabelWidth)); - setting.OAuth2Data.client_secret = GUILayout.TextField(setting.OAuth2Data.client_secret); - GUILayout.EndHorizontal(); + // client_secret for OAuth2 + GUILayout.BeginHorizontal(); + GUILayout.Label("Client Secret: ", GUILayout.Width(LabelWidth)); + setting.OAuth2Data.client_secret = GUILayout.TextField(setting.OAuth2Data.client_secret); + GUILayout.EndHorizontal(); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); + + if (GUILayout.Button("Start Authenticate")) + { + GDataDB.Impl.GDataDBRequestFactory.InitAuthenticate(); + } - if (GUILayout.Button("Start Authenticate")) + GoogleDataSettings.Instance._AccessCode = EditorGUILayout.TextField("AccessCode", GoogleDataSettings.Instance._AccessCode); + if (GUILayout.Button("Finish Authenticate")) + { + GDataDB.Impl.GDataDBRequestFactory.FinishAuthenticate(); + } + EditorGUILayout.Separator(); + + GUILayout.BeginHorizontal(); + GUILayout.Label("Runtime Path: ", GUILayout.Width(LabelWidth)); + setting.RuntimePath = GUILayout.TextField(setting.RuntimePath); + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + GUILayout.Label("Editor Path: ", GUILayout.Width(LabelWidth)); + setting.EditorPath = GUILayout.TextField(setting.EditorPath); + GUILayout.EndHorizontal(); + } + else { - GDataDB.Impl.GDataDBRequestFactory.InitAuthenticate(); + GUILayout.BeginHorizontal(); + GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); + GUILayout.BeginVertical(); + GUILayout.Label("", GUILayout.Height(12)); + GUILayout.Label("Correct the path of the GoogleDataSetting.asset file.", GUILayout.Height(20)); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); } - GoogleDataSettings.Instance._AccessCode = EditorGUILayout.TextField("AccessCode", GoogleDataSettings.Instance._AccessCode); - if (GUILayout.Button("Finish Authenticate")) + if (GUI.changed) { - GDataDB.Impl.GDataDBRequestFactory.FinishAuthenticate(); + EditorUtility.SetDirty(setting); + AssetDatabase.SaveAssets(); } - EditorGUILayout.Separator(); - - GUILayout.BeginHorizontal(); - GUILayout.Label("Runtime Path: ", GUILayout.Width(LabelWidth)); - setting.RuntimePath = GUILayout.TextField(setting.RuntimePath); - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - GUILayout.Label("Editor Path: ", GUILayout.Width(LabelWidth)); - setting.EditorPath = GUILayout.TextField(setting.EditorPath); - GUILayout.EndHorizontal(); - } - else - { - GUILayout.BeginHorizontal(); - GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); - GUILayout.BeginVertical(); - GUILayout.Label("", GUILayout.Height(12)); - GUILayout.Label("Correct the path of the GoogleDataSetting.asset file.", GUILayout.Height(20)); - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - } - - if (GUI.changed) - { - EditorUtility.SetDirty(setting); - AssetDatabase.SaveAssets(); } } -} +} \ No newline at end of file diff --git a/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachine.cs b/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachine.cs index d85052b..5ad07c7 100644 --- a/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachine.cs +++ b/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachine.cs @@ -11,7 +11,7 @@ using System.Collections.Generic; using System.IO; -namespace UnityEditor +namespace UnityQuicksheet { /// /// A class for various setting to import google spreadsheet data and generated related script files. diff --git a/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachineEditor.cs b/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachineEditor.cs index 631762c..24db909 100644 --- a/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachineEditor.cs +++ b/Assets/QuickSheet/GDataPlugin/Editor/GoogleMachineEditor.cs @@ -25,258 +25,262 @@ using Google.GData.Client; using Google.GData.Spreadsheets; -/// -/// An editor script class of GoogleMachine class. -/// -[CustomEditor(typeof(GoogleMachine))] -public class GoogleMachineEditor : BaseMachineEditor +namespace UnityQuicksheet { - PropertyField[] databaseFields; - - // to resolve TlsException error - public static bool Validator (object sender, X509Certificate certificate, - X509Chain chain, SslPolicyErrors sslPolicyErrors) + /// + /// An editor script class of GoogleMachine class. + /// + [CustomEditor(typeof(GoogleMachine))] + public class GoogleMachineEditor : BaseMachineEditor { - return true; - } + PropertyField[] databaseFields; - void OnEnable() - { // to resolve TlsException error - ServicePointManager.ServerCertificateValidationCallback = Validator; + public static bool Validator(object sender, X509Certificate certificate, + X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + return true; + } - machine = target as GoogleMachine; - if (machine != null) + void OnEnable() { - machine.ReInitialize(); + // to resolve TlsException error + ServicePointManager.ServerCertificateValidationCallback = Validator; + + machine = target as GoogleMachine; + if (machine != null) + { + machine.ReInitialize(); - databaseFields = ExposeProperties.GetProperties(machine); + databaseFields = ExposeProperties.GetProperties(machine); - if (string.IsNullOrEmpty(GoogleDataSettings.Instance.RuntimePath) == false) - machine.RuntimeClassPath = GoogleDataSettings.Instance.RuntimePath; - if (string.IsNullOrEmpty(GoogleDataSettings.Instance.EditorPath) == false) - machine.EditorClassPath = GoogleDataSettings.Instance.EditorPath; + if (string.IsNullOrEmpty(GoogleDataSettings.Instance.RuntimePath) == false) + machine.RuntimeClassPath = GoogleDataSettings.Instance.RuntimePath; + if (string.IsNullOrEmpty(GoogleDataSettings.Instance.EditorPath) == false) + machine.EditorClassPath = GoogleDataSettings.Instance.EditorPath; + } } - } - //private Vector2 curretScroll = Vector2.zero; + //private Vector2 curretScroll = Vector2.zero; - /// - /// Draw custom UI. - /// - public override void OnInspectorGUI() - { - if (GoogleDataSettings.Instance == null) + /// + /// Draw custom UI. + /// + public override void OnInspectorGUI() { - GUILayout.BeginHorizontal(); - GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); - GUILayout.BeginVertical(); - GUILayout.Label("", GUILayout.Height(12)); - GUILayout.Label("Check the GoogleDataSetting.asset file exists or its path is correct.", GUILayout.Height(20)); - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - } + if (GoogleDataSettings.Instance == null) + { + GUILayout.BeginHorizontal(); + GUILayout.Toggle(true, "", "CN EntryError", GUILayout.Width(20)); + GUILayout.BeginVertical(); + GUILayout.Label("", GUILayout.Height(12)); + GUILayout.Label("Check the GoogleDataSetting.asset file exists or its path is correct.", GUILayout.Height(20)); + GUILayout.EndVertical(); + GUILayout.EndHorizontal(); + } - //Rect rc; - GUIStyle headerStyle = null; + //Rect rc; + GUIStyle headerStyle = null; - headerStyle = GUIHelper.MakeHeader(); + headerStyle = GUIHelper.MakeHeader(); - GUILayout.Label("GoogleDrive Settings:", headerStyle); - //rc = GUILayoutUtility.GetLastRect(); - //GUI.skin.box.Draw(rc, GUIContent.none, 0); + GUILayout.Label("GoogleDrive Settings:", headerStyle); + //rc = GUILayoutUtility.GetLastRect(); + //GUI.skin.box.Draw(rc, GUIContent.none, 0); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - GUILayout.Label("Script Path Settings:", headerStyle); - //rc = GUILayoutUtility.GetLastRect(); - //GUI.skin.box.Draw(new Rect(rc.left, rc.top + rc.height, rc.width, 1f), GUIContent.none, 0); + GUILayout.Label("Script Path Settings:", headerStyle); + //rc = GUILayoutUtility.GetLastRect(); + //GUI.skin.box.Draw(new Rect(rc.left, rc.top + rc.height, rc.width, 1f), GUIContent.none, 0); - ExposeProperties.Expose(databaseFields); - EditorGUILayout.Separator (); + ExposeProperties.Expose(databaseFields); + EditorGUILayout.Separator(); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - GUILayout.BeginHorizontal(); + GUILayout.BeginHorizontal(); - if (machine.HasHeadColumn()) - { - if (GUILayout.Button("Update")) - Import(); + if (machine.HasHeadColumn()) + { + if (GUILayout.Button("Update")) + Import(); - if (GUILayout.Button("Reimport")) - Import(true); - } - else - { - if (GUILayout.Button("Import")) - Import(); - } + if (GUILayout.Button("Reimport")) + Import(true); + } + else + { + if (GUILayout.Button("Import")) + Import(); + } - GUILayout.EndHorizontal(); + GUILayout.EndHorizontal(); - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - DrawHeaderSetting(machine); + DrawHeaderSetting(machine); - // force save changed type. - if (GUI.changed) - { - EditorUtility.SetDirty(GoogleDataSettings.Instance); - EditorUtility.SetDirty(machine); - AssetDatabase.SaveAssets(); - } + // force save changed type. + if (GUI.changed) + { + EditorUtility.SetDirty(GoogleDataSettings.Instance); + EditorUtility.SetDirty(machine); + AssetDatabase.SaveAssets(); + } - EditorGUILayout.Separator(); + EditorGUILayout.Separator(); - machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass); + machine.onlyCreateDataClass = EditorGUILayout.Toggle("Only DataClass", machine.onlyCreateDataClass); - EditorGUILayout.Separator (); + EditorGUILayout.Separator(); - if (GUILayout.Button("Generate")) - { - if (Generate(this.machine) == null) - Debug.LogError("Failed to create a script from Google."); + if (GUILayout.Button("Generate")) + { + if (Generate(this.machine) == null) + Debug.LogError("Failed to create a script from Google."); + } } - } - - /// - /// A delegate called on each of a cell query. - /// - delegate void OnEachCell(CellEntry cell); - - /// - /// Connect to google-spreadsheet with the specified account and password - /// then query cells and call the given callback. - /// - private void DoCellQuery(OnEachCell onCell) - { - // first we need to connect to the google-spreadsheet to get all the first row of the cells - // which are used for the properties of data class. - var client = new DatabaseClient("", ""); - if (string.IsNullOrEmpty(machine.SpreadSheetName)) - return; - if (string.IsNullOrEmpty(machine.WorkSheetName)) - return; + /// + /// A delegate called on each of a cell query. + /// + delegate void OnEachCell(CellEntry cell); - var db = client.GetDatabase(machine.SpreadSheetName); - if (db == null) + /// + /// Connect to google-spreadsheet with the specified account and password + /// then query cells and call the given callback. + /// + private void DoCellQuery(OnEachCell onCell) { - string message = string.Format(@"The given spreadsheet '{0}' or worksheet '{1}' does not exist. Note that the name is case sensitive.", - machine.SpreadSheetName, machine.WorkSheetName); - EditorUtility.DisplayDialog("Error", message, "OK"); - return; - } + // first we need to connect to the google-spreadsheet to get all the first row of the cells + // which are used for the properties of data class. + var client = new DatabaseClient("", ""); - // retrieves all cells - var worksheet = ((Database)db).GetWorksheetEntry(machine.WorkSheetName); + if (string.IsNullOrEmpty(machine.SpreadSheetName)) + return; + if (string.IsNullOrEmpty(machine.WorkSheetName)) + return; - // Fetch the cell feed of the worksheet. - CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink); - var cellFeed = client.SpreadsheetService.Query(cellQuery); + var db = client.GetDatabase(machine.SpreadSheetName); + if (db == null) + { + string message = string.Format(@"The given spreadsheet '{0}' or worksheet '{1}' does not exist. Note that the name is case sensitive.", + machine.SpreadSheetName, machine.WorkSheetName); + EditorUtility.DisplayDialog("Error", message, "OK"); + return; + } - // Iterate through each cell, printing its value. - foreach (CellEntry cell in cellFeed.Entries) - { - if (onCell != null) - onCell(cell); - } - } + // retrieves all cells + var worksheet = ((Database)db).GetWorksheetEntry(machine.WorkSheetName); - /// - /// Connect to the google spreadsheet and retrieves its header columns. - /// - protected override void Import(bool reimport = false) - { - base.Import(reimport); + // Fetch the cell feed of the worksheet. + CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink); + var cellFeed = client.SpreadsheetService.Query(cellQuery); - Regex re = new Regex(@"\d+"); + // Iterate through each cell, printing its value. + foreach (CellEntry cell in cellFeed.Entries) + { + if (onCell != null) + onCell(cell); + } + } - Dictionary headerDic = null; - if (reimport) - machine.HeaderColumnList.Clear(); - else - headerDic = machine.HeaderColumnList.ToDictionary(k => k.name); + /// + /// Connect to the google spreadsheet and retrieves its header columns. + /// + protected override void Import(bool reimport = false) + { + base.Import(reimport); - DoCellQuery( (cell)=>{ + Regex re = new Regex(@"\d+"); - // get numerical value from a cell's address in A1 notation - // only retrieves first column of the worksheet - // which is used for member fields of the created data class. - Match m = re.Match(cell.Title.Text); - if (int.Parse(m.Value) > 1) - return; + Dictionary headerDic = null; + if (reimport) + machine.HeaderColumnList.Clear(); + else + headerDic = machine.HeaderColumnList.ToDictionary(k => k.name); - if (machine.HasHeadColumn() && reimport == false) + DoCellQuery((cell) => { - if (headerDic != null && headerDic.ContainsKey(cell.Value)) - machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = headerDic[cell.Value].type }); + + // get numerical value from a cell's address in A1 notation + // only retrieves first column of the worksheet + // which is used for member fields of the created data class. + Match m = re.Match(cell.Title.Text); + if (int.Parse(m.Value) > 1) + return; + + if (machine.HasHeadColumn() && reimport == false) + { + if (headerDic != null && headerDic.ContainsKey(cell.Value)) + machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = headerDic[cell.Value].type }); + else + machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = CellType.Undefined }); + } else + { machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = CellType.Undefined }); - } - else - { - machine.HeaderColumnList.Add(new HeaderColumn { name = cell.Value, type = CellType.Undefined }); - } - }); + } + }); - EditorUtility.SetDirty(machine); - AssetDatabase.SaveAssets(); - } + EditorUtility.SetDirty(machine); + AssetDatabase.SaveAssets(); + } - /// - /// Translate type of the member fields directly from google spreadsheet's header column. - /// NOTE: This needs header column to be formatted with colon. e.g. "Name : string" - /// - [System.Obsolete("Use CreateDataClassScript instead of CreateDataClassScriptFromSpreadSheet.")] - private void CreateDataClassScriptFromSpreadSheet(ScriptPrescription sp) - { - List fieldList = new List(); - - Regex re = new Regex(@"\d+"); - DoCellQuery((cell) => { - // get numerical value from a cell's address in A1 notation - // only retrieves first column of the worksheet - // which is used for member fields of the created data class. - Match m = re.Match(cell.Title.Text); - if (int.Parse(m.Value) > 1) - return; + /// + /// Translate type of the member fields directly from google spreadsheet's header column. + /// NOTE: This needs header column to be formatted with colon. e.g. "Name : string" + /// + [System.Obsolete("Use CreateDataClassScript instead of CreateDataClassScriptFromSpreadSheet.")] + private void CreateDataClassScriptFromSpreadSheet(ScriptPrescription sp) + { + List fieldList = new List(); - // add cell's displayed value to the list. - fieldList.Add(new MemberFieldData(cell.Value.Replace(" ", ""))); - }); + Regex re = new Regex(@"\d+"); + DoCellQuery((cell) => + { + // get numerical value from a cell's address in A1 notation + // only retrieves first column of the worksheet + // which is used for member fields of the created data class. + Match m = re.Match(cell.Title.Text); + if (int.Parse(m.Value) > 1) + return; - sp.className = machine.WorkSheetName + "Data"; - sp.template = GetTemplate("DataClass"); + // add cell's displayed value to the list. + fieldList.Add(new MemberFieldData(cell.Value.Replace(" ", ""))); + }); - sp.memberFields = fieldList.ToArray(); + sp.className = machine.WorkSheetName + "Data"; + sp.template = GetTemplate("DataClass"); - // write a script to the given folder. - using (var writer = new StreamWriter(TargetPathForData(machine.WorkSheetName))) - { - writer.Write(new NewScriptGenerator(sp).ToString()); - writer.Close(); - } - } + sp.memberFields = fieldList.ToArray(); - /// - /// Create utility class which has menu item function to create an asset file. - /// - protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) - { - sp.className = machine.WorkSheetName; - sp.worksheetClassName = machine.WorkSheetName; - sp.assetFileCreateFuncName = "Create" + machine.WorkSheetName + "AssetFile"; - sp.template = GetTemplate("AssetFileClass"); + // write a script to the given folder. + using (var writer = new StreamWriter(TargetPathForData(machine.WorkSheetName))) + { + writer.Write(new NewScriptGenerator(sp).ToString()); + writer.Close(); + } + } - // write a script to the given folder. - using (var writer = new StreamWriter(TargetPathForAssetFileCreateFunc(machine.WorkSheetName))) + /// + /// Create utility class which has menu item function to create an asset file. + /// + protected override void CreateAssetCreationScript(BaseMachine m, ScriptPrescription sp) { - writer.Write(new NewScriptGenerator(sp).ToString()); - writer.Close(); - } - } + sp.className = machine.WorkSheetName; + sp.worksheetClassName = machine.WorkSheetName; + sp.assetFileCreateFuncName = "Create" + machine.WorkSheetName + "AssetFile"; + sp.template = GetTemplate("AssetFileClass"); -} + // write a script to the given folder. + using (var writer = new StreamWriter(TargetPathForAssetFileCreateFunc(machine.WorkSheetName))) + { + writer.Write(new NewScriptGenerator(sp).ToString()); + writer.Close(); + } + } + } +} \ No newline at end of file